Skip to main content

waft_widgets/widgets/
title.rs

1//! Flutter `widgets/title.dart`.
2
3use waft_embedder::{ApplicationSwitcherDescription, Color};
4use waft_foundation::{App, DiagnosticPropertiesBuilder, Handle, StringProperty};
5use waft_painting::ColorProperty;
6use waft_services::SystemChrome;
7
8use crate::framework::{
9    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
10};
11
12/// A widget that describes this app in the operating system.
13#[derive(Debug)]
14pub struct Title {
15    key: Option<KeyRef>,
16    /// A one-line description of this app for use in the window manager.
17    /// Must not be null.
18    title: String,
19    /// A color that the window manager should use to identify this app. Must be
20    /// an opaque color (i.e. color.alpha must be 255 (0xFF)), and must not be
21    /// null.
22    color: Color,
23    /// The widget below this widget in the tree.
24    child: WidgetRef,
25}
26
27impl Title {
28    /// Creates a widget that describes this app to the Android operating system.
29    ///
30    /// `color` must be an opaque color (i.e. color.alpha must be 255 (0xFF)).
31    #[cfg_attr(debug_assertions, track_caller)]
32    pub fn new<K>(color: Color, child: impl IntoWidget<K>) -> Title {
33        debug_assert!(alpha_byte(color) == 0xFF);
34        Title {
35            key: None,
36            title: String::new(),
37            color,
38            child: child.into_widget(),
39        }
40    }
41
42    /// Dart `Title(key:)`.
43    pub fn key(mut self, key: KeyRef) -> Title {
44        self.key = Some(key);
45        self
46    }
47
48    /// Dart `Title(title:)`.
49    pub fn title(mut self, title: impl Into<String>) -> Title {
50        self.title = title.into();
51        self
52    }
53}
54
55fn alpha_byte(color: Color) -> i32 {
56    ((color.a * 255.0).round() as i32).clamp(0, 255)
57}
58
59impl StatefulWidget for Title {
60    type State = TitleState;
61
62    fn key(&self) -> Option<&KeyRef> {
63        self.key.as_ref()
64    }
65
66    fn create_state(&self) -> TitleState {
67        TitleState {
68            state: StateData::new(),
69        }
70    }
71}
72
73/// Dart's `_TitleState`.
74pub struct TitleState {
75    state: StateData<Title>,
76}
77
78impl TitleState {
79    fn update_chrome(self: Handle<Self>, app: &mut App) {
80        let widget = self.widget(app);
81        let description = ApplicationSwitcherDescription {
82            label: Some(widget.title.clone()),
83            primary_color: Some(widget.color.to_argb32()),
84        };
85        SystemChrome::set_application_switcher_description(app, &description);
86    }
87}
88
89impl State for TitleState {
90    fn debug_fill_properties(
91        self: Handle<Self>,
92        app: &App,
93        properties: &mut DiagnosticPropertiesBuilder,
94    ) {
95        let widget = self.widget(app);
96        properties.add(
97            StringProperty::new("title", Some(widget.title.clone()))
98                .default_value(Some(String::new())),
99        );
100        properties.add(ColorProperty::new("color", widget.color).default_value(None));
101    }
102
103    type Widget = Title;
104    crate::state_accessors!();
105
106    fn init_state(self: Handle<Self>, app: &mut App) {
107        self.update_chrome(app);
108    }
109
110    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Title) {
111        let widget = self.widget(app);
112        if old_widget.title != widget.title || old_widget.color != widget.color {
113            self.update_chrome(app);
114        }
115    }
116
117    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
118        self.widget(app).child.clone()
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use std::cell::RefCell;
125    use std::rc::Rc;
126    use waft_foundation::AppCell;
127
128    use waft_embedder::SystemChrome;
129    use waft_test::TestPlatform;
130
131    use super::*;
132    use crate::test_harness::Harness;
133    use crate::widgets::basic::SizedBox;
134
135    /// A host that records the descriptions the app gives of itself.
136    #[derive(Default)]
137    struct RecordingChrome {
138        descriptions: RefCell<Vec<ApplicationSwitcherDescription>>,
139    }
140
141    impl SystemChrome for RecordingChrome {
142        fn set_application_switcher_description(
143            &self,
144            description: &ApplicationSwitcherDescription,
145        ) {
146            self.descriptions.borrow_mut().push(description.clone());
147        }
148    }
149
150    #[test]
151    fn a_title_describes_the_app_to_the_platform_and_again_when_it_changes() {
152        let chrome = Rc::new(RecordingChrome::default());
153        let platform = TestPlatform::new().with_system_chrome(chrome.clone());
154        let cell = AppCell::with_platform(Rc::new(platform));
155        let mut app = cell.borrow_mut();
156        let titled = |title: &str| {
157            Title::new(Color::new(0xFF112233), SizedBox::shrink())
158                .title(title)
159                .into_widget()
160        };
161        let harness = Harness::mount(&mut app, titled("One"));
162        harness.pump(&mut app);
163        harness.set_child(&mut app, titled("One"));
164        harness.pump(&mut app);
165        harness.set_child(&mut app, titled("Two"));
166        harness.pump(&mut app);
167        let descriptions = chrome.descriptions.borrow();
168        assert_eq!(
169            descriptions.as_slice(),
170            [
171                ApplicationSwitcherDescription {
172                    label: Some(String::from("One")),
173                    primary_color: Some(0xFF112233),
174                },
175                ApplicationSwitcherDescription {
176                    label: Some(String::from("Two")),
177                    primary_color: Some(0xFF112233),
178                },
179            ],
180            "an unchanged title does not report again"
181        );
182    }
183}