Skip to main content

waft_test/
view.rs

1//! A view that draws nowhere, whose metrics a test sets.
2
3use std::cell::{Cell, RefCell};
4use std::rc::{Rc, Weak};
5use std::sync::Arc;
6
7use waft_embedder::{
8    GestureSettings, RequestId, Scene, ScreenId, Size, TitleBarArea, View, ViewConstraints,
9    ViewHost, ViewId, ViewMetrics, ViewPadding, WindowRef,
10};
11
12use crate::TestWindow;
13use crate::view_host::TestViewHost;
14
15/// The id of a [`TestView`] given none: the view of a test with one, as the engine numbers
16/// Flutter's implicit view.
17pub const IMPLICIT_VIEW_ID: ViewId = ViewId(0);
18
19/// What hears that a [`TestView`]'s metrics changed: the host's client, which
20/// `EmbedderClient::view_metrics_changed` reaches in an app a host runs.
21pub type MetricsListener = Rc<dyn Fn(ViewId)>;
22
23/// A view that counts the scenes presented to it, keeps the last and the size it came at, shows
24/// none, and records what it asks of the system in its host: `flutter_test`'s `TestFlutterView`.
25/// A frame of a size other than the view had is heard by its host
26/// ([`ViewHost::view_size_changed`]), as a host that shows views sized to their content tells it.
27///
28/// Its metrics are what it was made with until a test sets one; each setter, and each `reset_*`
29/// that puts a metric back to what the view was made with, tells the [`MetricsListener`], as
30/// `TestFlutterView`'s setters call `onMetricsChanged`.
31pub struct TestView {
32    id: ViewId,
33    /// What the view was made with, which the `reset_*` methods return to.
34    initial_metrics: ViewMetrics,
35    metrics: Cell<ViewMetrics>,
36    gesture_settings: Cell<GestureSettings>,
37    metrics_listener: RefCell<Option<MetricsListener>>,
38    presented: Cell<u32>,
39    last_scene: RefCell<Option<Arc<Scene>>>,
40    /// The size of the frame presented last, in physical pixels.
41    last_frame_size: Cell<Option<Size>>,
42    /// The view's size in physical pixels: what its metrics last gave it, or the size of a frame
43    /// presented since.
44    size: Cell<Size>,
45    request_id: Option<RequestId>,
46    initial_data: Option<String>,
47    /// The window the view is in, until it closes; held weakly, since the window holds the view.
48    window: RefCell<Option<Weak<TestWindow>>>,
49    /// What the view asks of the system, recorded.
50    host: TestViewHost,
51    /// The host the app gave a view it added, which takes what the view asks of the system in
52    /// place of `host`.
53    app_host: Option<Rc<dyn ViewHost>>,
54}
55
56impl TestView {
57    /// View [`IMPLICIT_VIEW_ID`] at pixel ratio 1, `width` by `height` physical pixels.
58    pub fn new(width: f64, height: f64) -> TestView {
59        TestView::with_pixel_ratio(width, height, 1.0)
60    }
61
62    /// View [`IMPLICIT_VIEW_ID`] at `device_pixel_ratio`, `width` by `height` physical pixels.
63    pub fn with_pixel_ratio(width: f64, height: f64, device_pixel_ratio: f64) -> TestView {
64        TestView::with_metrics(ViewMetrics {
65            physical_size: [width, height],
66            physical_constraints: ViewConstraints::tight(width, height),
67            device_pixel_ratio,
68            ..ViewMetrics::default()
69        })
70    }
71
72    /// View [`IMPLICIT_VIEW_ID`] at `metrics`, as a host gives a view the metrics it was asked
73    /// for.
74    pub fn with_metrics(metrics: ViewMetrics) -> TestView {
75        let [width, height] = metrics.physical_size;
76        TestView {
77            id: IMPLICIT_VIEW_ID,
78            initial_metrics: metrics,
79            metrics: Cell::new(metrics),
80            gesture_settings: Cell::new(GestureSettings::default()),
81            metrics_listener: RefCell::new(None),
82            presented: Cell::new(0),
83            last_scene: RefCell::new(None),
84            last_frame_size: Cell::new(None),
85            size: Cell::new(Size::new(width, height)),
86            request_id: None,
87            initial_data: None,
88            window: RefCell::new(None),
89            host: TestViewHost::default(),
90            app_host: None,
91        }
92    }
93
94    /// The same view under another id, for a platform with several.
95    pub fn with_id(mut self, id: ViewId) -> TestView {
96        self.id = id;
97        self
98    }
99
100    /// The same view as one that arrived for request `id`, carrying `initial_data`.
101    pub fn with_request(mut self, id: RequestId, initial_data: Option<String>) -> TestView {
102        self.request_id = Some(id);
103        self.initial_data = initial_data;
104        self
105    }
106
107    /// The same view asking what it asks of the system of `host`, as a view the app adds on a
108    /// layer does; its own [`test_host`](Self::test_host) hears nothing then.
109    pub fn with_host(mut self, host: Rc<dyn ViewHost>) -> TestView {
110        self.app_host = Some(host);
111        self
112    }
113
114    /// The same view on `screen`, as its metrics say.
115    pub fn on_screen(mut self, screen: ScreenId) -> TestView {
116        self.initial_metrics.screen = Some(screen);
117        self.metrics.set(self.initial_metrics);
118        self
119    }
120
121    /// The same view as one an embedder gave with `initial_data`.
122    pub fn with_initial_data(mut self, initial_data: impl Into<String>) -> TestView {
123        self.initial_data = Some(initial_data.into());
124        self
125    }
126
127    /// Makes `listener` the one that hears of each change to the view's metrics, in place of the
128    /// one before: what runs the app installs it, as a host hands a view's changes to its client.
129    pub fn set_metrics_listener(&self, listener: MetricsListener) {
130        *self.metrics_listener.borrow_mut() = Some(listener);
131    }
132
133    /// Dart's `tester.view.physicalSize = size`, which also makes the physical constraints tight
134    /// to it.
135    pub fn set_physical_size(&self, size: Size) {
136        self.change_metrics(|metrics| {
137            metrics.physical_size = [size.width(), size.height()];
138            metrics.physical_constraints = ViewConstraints::tight(size.width(), size.height());
139        });
140    }
141
142    /// Dart's `tester.view.resetPhysicalSize()`, which resets the physical constraints too.
143    pub fn reset_physical_size(&self) {
144        let initial = self.initial_metrics;
145        self.change_metrics(|metrics| {
146            metrics.physical_size = initial.physical_size;
147            metrics.physical_constraints = initial.physical_constraints;
148        });
149    }
150
151    /// Dart's `tester.view.physicalConstraints = constraints`.
152    pub fn set_physical_constraints(&self, constraints: ViewConstraints) {
153        self.change_metrics(|metrics| metrics.physical_constraints = constraints);
154    }
155
156    /// Dart's `tester.view.resetPhysicalConstraints()`.
157    pub fn reset_physical_constraints(&self) {
158        let initial = self.initial_metrics.physical_constraints;
159        self.change_metrics(|metrics| metrics.physical_constraints = initial);
160    }
161
162    /// Dart's `tester.view.devicePixelRatio = ratio`.
163    pub fn set_device_pixel_ratio(&self, ratio: f64) {
164        self.change_metrics(|metrics| metrics.device_pixel_ratio = ratio);
165    }
166
167    /// Dart's `tester.view.resetDevicePixelRatio()`.
168    pub fn reset_device_pixel_ratio(&self) {
169        let initial = self.initial_metrics.device_pixel_ratio;
170        self.change_metrics(|metrics| metrics.device_pixel_ratio = initial);
171    }
172
173    /// Dart's `tester.view.padding = padding`, in physical pixels.
174    pub fn set_padding(&self, padding: ViewPadding) {
175        self.change_metrics(|metrics| metrics.padding = padding);
176    }
177
178    /// Dart's `tester.view.resetPadding()`.
179    pub fn reset_padding(&self) {
180        let initial = self.initial_metrics.padding;
181        self.change_metrics(|metrics| metrics.padding = initial);
182    }
183
184    /// Dart's `tester.view.viewPadding = padding`, in physical pixels.
185    pub fn set_view_padding(&self, padding: ViewPadding) {
186        self.change_metrics(|metrics| metrics.view_padding = padding);
187    }
188
189    /// Dart's `tester.view.resetViewPadding()`.
190    pub fn reset_view_padding(&self) {
191        let initial = self.initial_metrics.view_padding;
192        self.change_metrics(|metrics| metrics.view_padding = initial);
193    }
194
195    /// Dart's `tester.view.viewInsets = insets`, in physical pixels.
196    pub fn set_view_insets(&self, insets: ViewPadding) {
197        self.change_metrics(|metrics| metrics.view_insets = insets);
198    }
199
200    /// Dart's `tester.view.resetViewInsets()`.
201    pub fn reset_view_insets(&self) {
202        let initial = self.initial_metrics.view_insets;
203        self.change_metrics(|metrics| metrics.view_insets = initial);
204    }
205
206    /// Dart's `tester.view.systemGestureInsets = insets`, in physical pixels.
207    pub fn set_system_gesture_insets(&self, insets: ViewPadding) {
208        self.change_metrics(|metrics| metrics.system_gesture_insets = insets);
209    }
210
211    /// Dart's `tester.view.resetSystemGestureInsets()`.
212    pub fn reset_system_gesture_insets(&self) {
213        let initial = self.initial_metrics.system_gesture_insets;
214        self.change_metrics(|metrics| metrics.system_gesture_insets = initial);
215    }
216
217    /// The strip the window buttons sit in, in physical pixels, as a windowed iPad reports it;
218    /// Dart's `TestFlutterView` has no counterpart.
219    pub fn set_title_bar_area(&self, area: Option<TitleBarArea>) {
220        self.change_metrics(|metrics| metrics.title_bar_area = area);
221    }
222
223    /// Dart's `tester.view.gestureSettings = settings`.
224    pub fn set_gesture_settings(&self, settings: GestureSettings) {
225        self.gesture_settings.set(settings);
226        self.notify_metrics_changed();
227    }
228
229    /// Dart's `tester.view.resetGestureSettings()`.
230    pub fn reset_gesture_settings(&self) {
231        self.set_gesture_settings(GestureSettings::default());
232    }
233
234    /// Dart's `tester.view.reset()`: every metric back to what the view was made with, told as
235    /// one change.
236    pub fn reset(&self) {
237        self.gesture_settings.set(GestureSettings::default());
238        let initial = self.initial_metrics;
239        self.change_metrics(|metrics| *metrics = initial);
240    }
241
242    /// How many pictures have been presented.
243    pub fn presented(&self) -> u32 {
244        self.presented.get()
245    }
246
247    /// The scene presented last, the frame's layer tree, which `waft_embedder::slices` turns
248    /// into what it draws and the composition layers it places.
249    pub fn last_scene(&self) -> Option<Arc<Scene>> {
250        self.last_scene.borrow().clone()
251    }
252
253    /// The size the frame presented last came at, in physical pixels: the size the view laid
254    /// itself out at within its physical constraints.
255    pub fn last_frame_size(&self) -> Option<Size> {
256        self.last_frame_size.get()
257    }
258
259    /// The view's host, which records the cursors shown over the view, the focus requested for it,
260    /// what its text input was asked, what the framework said of handling Back in it and the bars'
261    /// styles set over it.
262    pub fn test_host(&self) -> &TestViewHost {
263        &self.host
264    }
265
266    /// The window the view is in, until it closes, with what it records: what `View::window`
267    /// answers, as the test's own window.
268    pub fn test_window(&self) -> Option<Rc<TestWindow>> {
269        self.window.borrow().as_ref()?.upgrade()
270    }
271
272    /// The view is in `window` from now on, or in none.
273    pub(crate) fn set_window(&self, window: Option<Weak<TestWindow>>) {
274        *self.window.borrow_mut() = window;
275    }
276
277    /// Applies `change` to the metrics, then tells the listener. A new physical size is the
278    /// view's size from now on.
279    fn change_metrics(&self, change: impl FnOnce(&mut ViewMetrics)) {
280        let previous = self.metrics.get();
281        let mut metrics = previous;
282        change(&mut metrics);
283        self.metrics.set(metrics);
284        if metrics.physical_size != previous.physical_size {
285            let [width, height] = metrics.physical_size;
286            self.size.set(Size::new(width, height));
287        }
288        self.notify_metrics_changed();
289    }
290
291    /// Tells the listener, if one is installed, that the metrics changed; outside its borrow, so
292    /// the listener may install another.
293    fn notify_metrics_changed(&self) {
294        let listener = self.metrics_listener.borrow().clone();
295        if let Some(listener) = listener {
296            listener(self.id);
297        }
298    }
299}
300
301impl View for TestView {
302    fn id(&self) -> ViewId {
303        self.id
304    }
305
306    fn metrics(&self) -> ViewMetrics {
307        self.metrics.get()
308    }
309
310    fn gesture_settings(&self) -> GestureSettings {
311        self.gesture_settings.get()
312    }
313
314    fn present(&self, scene: Arc<Scene>, size: Size) {
315        self.presented.set(self.presented.get() + 1);
316        *self.last_scene.borrow_mut() = Some(scene);
317        self.last_frame_size.set(Some(size));
318        if self.size.replace(size) != size {
319            self.host().view_size_changed(size);
320        }
321    }
322
323    fn host(&self) -> &dyn ViewHost {
324        self.app_host.as_deref().unwrap_or(&self.host)
325    }
326
327    fn initial_data(&self) -> Option<String> {
328        self.initial_data.clone()
329    }
330
331    fn request_id(&self) -> Option<RequestId> {
332        self.request_id
333    }
334
335    fn window(&self) -> Option<WindowRef> {
336        Some(self.test_window()? as WindowRef)
337    }
338}