Skip to main content

waft_widgets/
window.rs

1//! Flutter counterpart: `WindowScope` from `widgets/_window.dart` (experimental), which there hands
2//! a subtree its window's controller; here it hands the window itself.
3//!
4//! A [`View`](crate::View) in a window, one the app asked for or one the system made or restored,
5//! provides a [`WindowScope`] to its content: the window the host keeps around the view
6//! (`View::window`), its frame, its title, minimizing, its size limits and its closing. Widgets
7//! that read it rebuild when the host reports the window changed, minimized or restored, occluded
8//! or shown, maximized or full screen or back from either, or moved, as widgets reading
9//! `MediaQuery` rebuild when the view's metrics change.
10//!
11//! The invariant a later editor will break: a window's change reaches the scope through the
12//! binding's crate-private window listeners, never through a public observer method; the scope
13//! notifies its dependents at each one.
14
15use std::fmt;
16use std::rc::Rc;
17
18use waft_embedder::{ViewRef, WindowRef};
19use waft_foundation::{App, Handle, Listener};
20
21use crate::binding::WidgetsBinding;
22use crate::framework::{
23    BuildContext, InheritedWidget, IntoWidget, State, StateData, StatefulWidget, WidgetRef,
24};
25
26/// Provides the window a view is in to the widgets below it.
27pub struct WindowScope {
28    window: WindowRef,
29    /// How many changes of the window the host has reported, which tells the scope's dependents
30    /// to read it again.
31    changes: u64,
32    child: WidgetRef,
33}
34
35impl WindowScope {
36    /// The window the `context` is drawn in, or `None` for a view in no window, as an iPhone's
37    /// screen or a web page's element is. The widget of `context` rebuilds when the window
38    /// changes.
39    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<WindowRef> {
40        context
41            .depend_on_inherited_widget_of_exact_type::<WindowScope>(app)
42            .map(|scope| Rc::clone(&scope.window))
43    }
44
45    /// The window the `context` is drawn in.
46    ///
47    /// # Panics
48    ///
49    /// Outside a view in a window.
50    pub fn of(app: &mut App, context: BuildContext) -> WindowRef {
51        WindowScope::maybe_of(app, context)
52            .expect("WindowScope::of() was called with a context that is not inside a window")
53    }
54}
55
56impl fmt::Debug for WindowScope {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.debug_struct("WindowScope")
59            .field("changes", &self.changes)
60            .finish_non_exhaustive()
61    }
62}
63
64impl InheritedWidget for WindowScope {
65    fn child(&self) -> &WidgetRef {
66        &self.child
67    }
68
69    fn update_should_notify(&self, old_widget: &WindowScope) -> bool {
70        self.changes != old_widget.changes || !Rc::ptr_eq(&self.window, &old_widget.window)
71    }
72}
73
74/// The [`WindowScope`] of `view`'s window, which `View` builds for a view in a window, rebuilt at
75/// each change of the window the host reports.
76pub(crate) struct WindowScopeOfView {
77    pub(crate) view: ViewRef,
78    pub(crate) window: WindowRef,
79    pub(crate) child: WidgetRef,
80}
81
82impl fmt::Debug for WindowScopeOfView {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.debug_struct("WindowScopeOfView")
85            .field("view", &self.view.id())
86            .finish_non_exhaustive()
87    }
88}
89
90impl StatefulWidget for WindowScopeOfView {
91    type State = WindowScopeOfViewState;
92
93    fn create_state(&self) -> WindowScopeOfViewState {
94        WindowScopeOfViewState {
95            state: StateData::new(),
96            changes: 0,
97            listener: None,
98        }
99    }
100}
101
102pub(crate) struct WindowScopeOfViewState {
103    state: StateData<WindowScopeOfView>,
104    changes: u64,
105    /// Retains the listener's identity for removal on disposal.
106    listener: Option<Listener>,
107}
108
109impl WindowScopeOfViewState {
110    fn window_changed(self: Handle<Self>, app: &mut App) {
111        self.set_state(app, |state| state.changes += 1);
112    }
113}
114
115impl State for WindowScopeOfViewState {
116    type Widget = WindowScopeOfView;
117    crate::state_accessors!();
118
119    fn init_state(self: Handle<Self>, app: &mut App) {
120        let view = self.widget(app).view.id();
121        let listener = Listener::handle_method(self, WindowScopeOfViewState::window_changed);
122        WidgetsBinding::instance(app).add_window_listener(app, view, listener.clone());
123        app.get_mut(self).listener = Some(listener);
124    }
125
126    fn dispose(self: Handle<Self>, app: &mut App) {
127        if let Some(listener) = app.get_mut(self).listener.take() {
128            let view = self.widget(app).view.id();
129            WidgetsBinding::instance(app).remove_window_listener(app, view, &listener);
130        }
131    }
132
133    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
134        let widget = self.widget(app);
135        WindowScope {
136            window: Rc::clone(&widget.window),
137            changes: app.get(self).changes,
138            child: widget.child.clone(),
139        }
140        .into_widget()
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use std::cell::RefCell;
147    use std::time::Duration;
148
149    use waft_embedder::{EmbedderClient, HostWindow, ViewId, WindowConfig};
150    use waft_test::{TestPlatform, TestView, TestWindow};
151
152    use super::*;
153    use crate::testing::WidgetTester;
154    use crate::widgets::basic::Builder;
155    use crate::{MultiViewApp, SizedBox};
156
157    /// What the content of each view read of its window, each time it built.
158    type Read = Rc<RefCell<Vec<Option<bool>>>>;
159
160    /// An app showing, in each of `views`, content that reads whether its window is minimized.
161    fn reading(views: &[Rc<TestView>]) -> (WidgetTester, Read) {
162        let mut platform = TestPlatform::new();
163        for view in views {
164            platform = platform.with_view(Rc::clone(view) as ViewRef);
165        }
166        let mut tester = WidgetTester::for_app(platform);
167        let read: Read = Rc::default();
168        let kept = Rc::clone(&read);
169        let content = Builder::new(move |app, context| {
170            let window = WindowScope::maybe_of(app, context);
171            kept.borrow_mut()
172                .push(window.map(|window| window.is_minimized()));
173            SizedBox::new().into_widget()
174        })
175        .into_widget();
176        tester.update(|app| {
177            crate::binding::run_widget(
178                app,
179                MultiViewApp::new(move |_app, _view| Some(content.clone())).into_widget(),
180            );
181        });
182        tester.pump_by(Duration::ZERO);
183        (tester, read)
184    }
185
186    #[test]
187    fn a_view_in_a_window_hands_its_content_the_window_and_its_changes() {
188        let window = TestWindow::around(
189            TestView::new(300.0, 200.0).with_id(ViewId(1)),
190            WindowConfig::default(),
191        );
192        let (mut tester, read) = reading(&[Rc::clone(window.test_view())]);
193        assert_eq!(*read.borrow(), [Some(false)]);
194
195        window.set_minimized(true);
196        tester.shell().window_changed(ViewId(1));
197        tester.pump_by(Duration::from_millis(16));
198        assert_eq!(
199            *read.borrow(),
200            [Some(false), Some(true)],
201            "rebuilt at the change"
202        );
203    }
204
205    #[test]
206    fn content_activates_the_window_it_is_in() {
207        let window = TestWindow::around(
208            TestView::new(300.0, 200.0).with_id(ViewId(1)),
209            WindowConfig::default(),
210        );
211        window.set_minimized(true);
212        let platform = TestPlatform::new().with_view(Rc::clone(window.test_view()) as ViewRef);
213        let mut tester = WidgetTester::for_app(platform);
214        let content = Builder::new(|app, context| {
215            WindowScope::of(app, context).activate();
216            SizedBox::new().into_widget()
217        })
218        .into_widget();
219        tester.update(|app| {
220            crate::binding::run_widget(
221                app,
222                MultiViewApp::new(move |_app, _view| Some(content.clone())).into_widget(),
223            );
224        });
225        tester.pump_by(Duration::ZERO);
226
227        assert_eq!(window.activations(), 1);
228        assert!(!window.is_minimized(), "a minimized window returns");
229    }
230
231    #[test]
232    fn a_view_in_no_window_has_none() {
233        let (_tester, read) = reading(&[Rc::new(TestView::new(300.0, 200.0).with_id(ViewId(1)))]);
234        assert_eq!(*read.borrow(), [None]);
235    }
236}