adapter/
adapter.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5extern crate suzy;
6
7use suzy::adapter::{Adaptable, DownwardVecAdapter};
8use suzy::dims::{Rect, SimplePadding2d};
9use suzy::platform::opengl::{Text, TextAlignment, TextLayoutSettings};
10use suzy::watch::Watched;
11use suzy::widget::*;
12
13const WORDS: &str = include_str!("words.txt");
14
15struct Element {
16    value: Watched<&'static str>,
17    text: Text,
18}
19
20impl Adaptable<&'static str> for Element {
21    fn adapt(&mut self, data: &&'static str) {
22        *self.value = data;
23    }
24
25    fn from(data: &&'static str) -> Self {
26        Element {
27            value: Watched::new(data),
28            text: Text::default(),
29        }
30    }
31}
32
33impl WidgetContent for Element {
34    fn init(mut init: impl WidgetInit<Self>) {
35        init.watch(|this, rect| {
36            let text_settings = this.text.render_settings();
37            text_settings.x = rect.left();
38            text_settings.y = rect.center_y();
39        });
40        init.watch(|this, rect| {
41            let text_layout = TextLayoutSettings::default()
42                .wrap_width(rect.width())
43                .alignment(TextAlignment::Center)
44                .y_offset(-12.0);
45            this.text.set_text(&this.value, text_layout);
46        });
47    }
48
49    fn children(&mut self, _receiver: impl WidgetChildReceiver) {
50        // no children
51    }
52
53    fn graphics(&mut self, mut receiver: impl WidgetGraphicReceiver) {
54        receiver.graphic(&mut self.text);
55    }
56}
57
58#[derive(Default)]
59struct AdapterExample {
60    layout: DownwardVecAdapter<&'static str, Element>,
61}
62
63impl WidgetContent for AdapterExample {
64    fn init(mut init: impl WidgetInit<Self>) {
65        init.watch(|this, _rect| {
66            this.layout.data_mut().clear();
67            this.layout.data_mut().extend(WORDS.split_whitespace());
68        });
69        init.watch(|this, rect| {
70            this.layout.set_fill(&rect, &SimplePadding2d::zero());
71        });
72    }
73
74    fn children(&mut self, mut receiver: impl WidgetChildReceiver) {
75        receiver.child(&mut self.layout);
76    }
77
78    fn graphics(&mut self, _receiver: impl WidgetGraphicReceiver) {
79        // no graphics
80    }
81}
82
83fn main() {
84    AdapterExample::run_as_app();
85}