waft-widgets 0.13.0

Widget framework and widgets for Waft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! [`WidgetTester`]: the app a case runs through [`waft_shell::Shell`], its views, and the
//! frames and time it pumps.

use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;

use waft_embedder::{
    EmbedderClient, Frame, Platform, RestorationMap, RestorationUpdate, Size, TargetPlatform,
    View as EmbedderView, ViewId, ViewRef,
};
use waft_foundation::{App, AppCell};
use waft_rendering::RendererBinding;
use waft_scheduler::{FrameTarget, SchedulerBinding};
use waft_shell::Shell;
use waft_test::{IMPLICIT_VIEW_ID, TestPlatform, TestView};

use crate::{Center, Container, IntoWidget, RootWidget, Text, View, WidgetsBinding};

/// The real-time deadline for [`WidgetTester::pump_until`].
const PUMP_UNTIL_DEADLINE: Duration = Duration::from_secs(60);

/// Dart's `WidgetTester`: an app driven through [`Shell`] over a [`TestPlatform`], with one
/// implicit view by default or none ([`for_app`](Self::for_app)), and the frames,
/// windows, time and input a case gives it.
///
/// Dropped after a case that did not panic, it disposes whatever root the app attached across
/// every view and checks that no timer is still pending, as flutter_test does after each test. A
/// case that caught a panic out of a pump skips both: the frame unwound and left the tree half
/// built (`PORTING.md`).
pub struct WidgetTester {
    /// The app under test, which the case borrows to read and change the tree.
    pub cell: Rc<AppCell>,
    shell: Shell,
    platform: Rc<TestPlatform>,
    view: Option<Rc<TestView>>,
    /// The views the framework has been told about (launch views plus reported `view_added` minus
    /// reported `view_removed`), so each pump reports newly created or closed views once.
    known_views: Vec<ViewId>,
    restoration: Option<Rc<TestRestoration>>,
    /// Whether a pump is running, or began and unwound: a pump that panicked never clears it.
    in_pump: bool,
    /// Dart's `_nextPointer`: the pointer the next finder-taking gesture uses.
    next_pointer: std::cell::Cell<i64>,
}

/// The host side of flutter_test's `TestRestorationManager`: it answers `Restoration::get` with
/// the data it was handed and keeps every `Restoration::put`.
struct TestRestoration {
    stored: Option<RestorationUpdate>,
    puts: RefCell<Vec<RestorationMap>>,
}

impl waft_embedder::Restoration for TestRestoration {
    fn get(&self) -> Option<RestorationUpdate> {
        self.stored.clone()
    }

    fn put(&self, data: RestorationMap) {
        self.puts.borrow_mut().push(data);
    }
}

impl WidgetTester {
    /// The logical size of flutter_test's view.
    pub const SIZE: Size = Size::new(800.0, 600.0);

    /// flutter_test's device pixel ratio.
    pub const DEVICE_PIXEL_RATIO: f64 = 3.0;

    /// A tester on Android, the platform flutter_test runs on.
    pub fn new() -> WidgetTester {
        WidgetTester::on(TargetPlatform::Android)
    }

    /// A tester on `platform`: Dart's `debugDefaultTargetPlatformOverride`.
    pub fn on(platform: TargetPlatform) -> WidgetTester {
        WidgetTester::with_platform(TestPlatform::new().on(platform))
    }

    /// A tester on `platform`, which this gives flutter_test's view; `platform` names the target
    /// (Android unless it says otherwise) and whatever the case's host reports.
    pub fn with_platform(platform: TestPlatform) -> WidgetTester {
        WidgetTester::with_view(platform, Self::default_view())
    }

    /// A tester on `platform` with `view` as its one view, for a case whose view is not
    /// flutter_test's: one with a host of the case's own. A case that only sets the view's
    /// metrics sets them on [`view`](Self::view), as Dart's does.
    pub fn with_view(platform: TestPlatform, view: TestView) -> WidgetTester {
        let view = Rc::new(view);
        let platform = platform.with_view(Rc::clone(&view) as ViewRef);
        let mut tester = Self::build(platform, Some(view));
        tester.pump_pre_test_tree();
        tester
    }

    /// A tester of an app that sets itself up, as Flutter's integration tests run `app.main()`:
    /// on `platform` with only the windows the platform has, or makes as the app asks for them
    /// ([`TestPlatform::with_windows`]), and no view or pre-test tree of the tester's own. The
    /// app's setup runs through [`update`](Self::update), calling `run_app` or `run_widget`; a
    /// window the platform gives later ([`TestPlatform::give_view`]) reaches it at the next
    /// [`pump`](Self::pump).
    pub fn for_app(platform: TestPlatform) -> WidgetTester {
        Self::build(platform, None)
    }

    fn build(platform: TestPlatform, view: Option<Rc<TestView>>) -> WidgetTester {
        let platform = Rc::new(platform);
        let known_views: Vec<ViewId> = platform.views().into_iter().map(|view| view.id()).collect();
        let shell = Shell::new(Rc::clone(&platform) as waft_embedder::PlatformRef, |app| {
            WidgetsBinding::instance(app);
        });
        let cell = Rc::clone(shell.cell());
        let tester = WidgetTester {
            cell,
            shell,
            platform,
            view,
            known_views,
            restoration: None,
            in_pump: false,
            next_pointer: std::cell::Cell::new(1),
        };
        tester.listen_to_metrics_of(&tester.known_views);
        tester
    }

    /// Makes the metrics changes of each of the platform's [`TestView`]s numbered among `ids`
    /// reach the framework, as a host hands its views' changes to its client.
    fn listen_to_metrics_of(&self, ids: &[ViewId]) {
        for view in self.platform.views() {
            if ids.contains(&view.id())
                && let Ok(view) = (view as Rc<dyn std::any::Any>).downcast::<TestView>()
            {
                self.listen_to_view_metrics(&view);
            }
        }
    }

    /// Makes `view`'s metrics changes reach the framework as a host's do: dart:ui's
    /// `onMetricsChanged`, which the framework sets to `RendererBinding.handleMetricsChanged`,
    /// as one platform event, the checkpoint after it.
    fn listen_to_view_metrics(&self, view: &TestView) {
        let cell = Rc::downgrade(&self.cell);
        view.set_metrics_listener(Rc::new(move |_view| {
            let Some(cell) = cell.upgrade() else {
                return;
            };
            {
                let mut app = cell.borrow_mut();
                RendererBinding::instance(&mut app).handle_metrics_changed(&mut app);
            }
            cell.checkpoint();
        }));
    }

    /// flutter_test's `_runTestBody` before the case: `runApp(Container(key: UniqueKey(), child:
    /// _preTestMessage))` and a pump, which resets the tree to a known state. The case's first
    /// [`pump_widget`](Self::pump_widget) then replaces a tree, building it within its frame, as
    /// Dart's does.
    fn pump_pre_test_tree(&mut self) {
        self.pump_widget(
            Container::new()
                .key(waft_foundation::UniqueKey::new().into())
                .child(
                    Center::new().child(
                        Text::new("Test starting...")
                            .style(
                                waft_painting::TextStyle::new()
                                    .color(waft_embedder::Color::new(0xFF917FFF))
                                    .font_size(40.0),
                            )
                            .text_direction(waft_embedder::TextDirection::Ltr),
                    ),
                ),
        );
    }

    /// A tester on Android whose host restores `data`: the app that Dart's
    /// `tester.restartAndRestore()` and `tester.restoreFrom(data)` start again, which the case
    /// pumps its widget into once more.
    pub fn restoring(data: Option<RestorationMap>) -> WidgetTester {
        let restoration = Rc::new(TestRestoration {
            stored: Some(RestorationUpdate {
                enabled: true,
                data,
            }),
            puts: RefCell::new(Vec::new()),
        });
        let platform = TestPlatform::new()
            .on(TargetPlatform::Android)
            .with_restoration(Rc::clone(&restoration) as Rc<dyn waft_embedder::Restoration>);
        let mut tester = WidgetTester::with_platform(platform);
        tester.restoration = Some(restoration);
        tester
    }

    /// flutter_test's view: 2400x1800 physical pixels at 3.0, which is 800x600 logical.
    fn default_view() -> TestView {
        TestView::with_pixel_ratio(
            WidgetTester::SIZE.width() * WidgetTester::DEVICE_PIXEL_RATIO,
            WidgetTester::SIZE.height() * WidgetTester::DEVICE_PIXEL_RATIO,
            WidgetTester::DEVICE_PIXEL_RATIO,
        )
    }

    /// The platform the app runs on, for a case that changes what the host reports while it
    /// runs: Dart's `tester.platformDispatcher.*TestValue`.
    pub fn platform(&self) -> &Rc<TestPlatform> {
        &self.platform
    }

    /// The shell driving the app, for sending platform events directly: Back (`pop_route`),
    /// close requests, focus, lifecycle, edit commands and the rest.
    pub fn shell(&mut self) -> &mut Shell {
        &mut self.shell
    }

    /// The ids of the views the platform has now, in order.
    fn view_ids(&self) -> Vec<ViewId> {
        self.platform
            .views()
            .into_iter()
            .map(|view| view.id())
            .collect()
    }

    /// The view the tree is in, whose host records what the framework asks of it and whose
    /// metrics a case sets: Dart's `tester.view`. A metric set reaches the framework at once, so
    /// a case sets it while it does not hold the app.
    ///
    /// # Panics
    ///
    /// If the tester was made [`for_app`](Self::for_app).
    pub fn view(&self) -> &Rc<TestView> {
        self.view
            .as_ref()
            .expect("a tester made for_app has no view of its own")
    }

    /// The default view's id, or [`IMPLICIT_VIEW_ID`] when constructed without one.
    pub(super) fn default_view_id(&self) -> ViewId {
        self.view
            .as_ref()
            .map_or(IMPLICIT_VIEW_ID, |view| view.id())
    }

    /// Dart's `tester.binding.setSurfaceSize(size)`: the view's render view is laid out at `size`
    /// logical pixels, or at the view's own size again for `None`, while the view's metrics, and
    /// so the `MediaQuery`, stay as they are.
    pub fn set_surface_size(&self, size: Option<Size>) {
        let view = self.view().id();
        {
            let mut app = self.cell.borrow_mut();
            RendererBinding::instance(&mut app).set_surface_size(&mut app, view, size);
        }
        self.cell.checkpoint();
    }

    /// The target platform the case runs on: Dart's `defaultTargetPlatform`, which a
    /// [`TargetPlatformVariant`](super::TargetPlatformVariant) sets.
    pub fn target_platform(&self) -> TargetPlatform {
        self.platform.target_platform()
    }

    /// The view's device pixel ratio, which turns a case's logical positions into the physical
    /// ones the host reports.
    pub fn device_pixel_ratio(&self) -> f64 {
        self.view
            .as_ref()
            .map_or(1.0, |view| view.metrics().device_pixel_ratio)
    }

    /// Dart's `tester.hasRunningAnimations`: whether any transient callback is scheduled, which
    /// a running [`Ticker`](waft_scheduler::Ticker) registers one per frame.
    pub fn has_running_animations(&self) -> bool {
        SchedulerBinding::transient_callback_count(&mut self.cell.borrow_mut()) > 0
    }

    /// Dart's `tester.getRestorationData()`: what the host holds, which is what the app last
    /// handed it, or else what it restored the app from.
    pub fn restoration_data(&self) -> Option<RestorationMap> {
        let restoration = self
            .restoration
            .as_ref()
            .expect("a tester made by WidgetTester::restoring");
        let last_put = restoration.puts.borrow().last().cloned();
        last_put.or_else(|| {
            restoration
                .stored
                .as_ref()
                .and_then(|stored| stored.data.clone())
        })
    }

    /// Dart's `tester.pumpWidget(widget)`: makes `widget` the view's child, schedules a frame
    /// and pumps once.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn pump_widget<K>(&mut self, widget: impl IntoWidget<K>) {
        self.attach_and_schedule(widget);
        self.pump();
    }

    /// Dart's `binding.attachRootWidget(binding.wrapWithDefaultView(widget))` and
    /// `binding.scheduleFrame()`.
    #[cfg_attr(debug_assertions, track_caller)]
    fn attach_and_schedule<K>(&mut self, widget: impl IntoWidget<K>) {
        self.in_pump = true;
        let view = Rc::clone(self.view()) as ViewRef;
        let view_id = view.id();
        let mut app = self.cell.borrow_mut();
        let root = View::new(view, widget.into_widget()).into_widget();
        WidgetsBinding::instance(&mut app).attach_root_widget(&mut app, root);
        SchedulerBinding::schedule_frame(&mut app, FrameTarget::View(view_id));
    }

    /// Dart's `tester.pumpFrames(target, maxDuration)`: makes `widget` the view's child,
    /// schedules a frame, and pumps frames 16.683ms apart until `max_duration` has passed.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn pump_frames<K>(&mut self, widget: impl IntoWidget<K>, max_duration: Duration) {
        self.pump_frames_every(widget, max_duration, Duration::from_micros(16_683));
    }

    /// Dart's `tester.pumpFrames(target, maxDuration, interval)`.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn pump_frames_every<K>(
        &mut self,
        widget: impl IntoWidget<K>,
        max_duration: Duration,
        interval: Duration,
    ) {
        self.attach_and_schedule(widget);
        let mut elapsed = Duration::ZERO;
        while elapsed < max_duration {
            self.pump_by(interval);
            elapsed += interval;
        }
    }

    /// Dart's `tester.nextPointer`: the pointer a finder-taking gesture uses, numbered from 1.
    pub fn next_pointer(&self) -> i64 {
        let pointer = self.next_pointer.get();
        self.next_pointer.set(pointer + 1);
        pointer
    }

    /// Dart's `tester.pump()`: flushes queued tasks, reports any windows added or closed since the
    /// last pump, and runs a frame of every view that asked for one, with no time passing and so
    /// no timer firing.
    pub fn pump(&mut self) {
        self.in_pump = true;
        let elapsed = self.platform.elapsed();
        self.shell.wake(elapsed);
        let removed_any = self.sync_views();
        self.frame_if_asked(removed_any);
        self.in_pump = false;
    }

    /// Dart's `tester.pump(duration)`: `duration` passes on the platform's and app's clock, firing
    /// the timers due by then, reports any windows added or closed, and then runs a frame of every
    /// view that asked for one.
    pub fn pump_by(&mut self, duration: Duration) {
        self.in_pump = true;
        self.platform.advance_clock(duration);
        self.cell.elapse(duration);
        let elapsed = self.platform.elapsed();
        self.shell.wake(elapsed);
        let removed_any = self.sync_views();
        self.frame_if_asked(removed_any);
        self.in_pump = false;
    }

    /// Dart's `tester.pumpAndSettle()`: 100ms frames until none is scheduled; answers how many
    /// it ran.
    pub fn pump_and_settle(&mut self) -> u32 {
        self.pump_and_settle_by(Duration::from_millis(100))
    }

    /// Dart's `tester.pumpAndSettle(duration)`: frames `duration` apart, at least one, until
    /// none is scheduled and no view changes remain, failing once its default 10 minutes of test
    /// time have passed; answers how many frames it ran.
    pub fn pump_and_settle_by(&mut self, duration: Duration) -> u32 {
        let end_time = self.cell.borrow().clock() + Duration::from_secs(10 * 60);
        let mut count = 0;
        loop {
            assert!(
                self.cell.borrow().clock() <= end_time,
                "pumpAndSettle timed out"
            );
            self.pump_by(duration);
            count += 1;
            if !SchedulerBinding::has_scheduled_frame(&mut self.cell.borrow_mut())
                && !self.has_pending_view_changes()
            {
                return count;
            }
        }
    }

    /// Pumps (dispatched work, windows and frames) until `done` answers `true`, sleeping between
    /// pumps until work on another thread wakes the app, as the host's event loop does, and
    /// failing after 60 real seconds naming `what`: for work finishing on other threads, where
    /// Flutter's tests use `runAsync`. The app's clock does not move meanwhile, as `runAsync`'s
    /// does not: what waits on a timer needs [`pump_by`](Self::pump_by).
    pub fn pump_until(&mut self, what: &str, mut done: impl FnMut(&mut App) -> bool) {
        let deadline = std::time::Instant::now() + PUMP_UNTIL_DEADLINE;
        loop {
            let wake_count = self.platform.wake_now_requests();
            self.pump();
            if self.update(&mut done) {
                return;
            }
            let now = std::time::Instant::now();
            assert!(
                now < deadline,
                "timed out waiting for {what} after {}s",
                PUMP_UNTIL_DEADLINE.as_secs()
            );
            // The event loop sleeps until work on another thread wakes the app.
            self.platform
                .wait_for_wake(wake_count, deadline.saturating_duration_since(now));
        }
    }

    fn has_pending_view_changes(&self) -> bool {
        let current = self.view_ids();
        self.known_views.iter().any(|id| !current.contains(id))
            || current.iter().any(|id| !self.known_views.contains(id))
    }

    /// Reports every view added to or removed from the platform since the last sync through the
    /// shell's `view_added` and `view_removed`, installing metrics listeners on new test views.
    /// Returns whether any view was removed.
    fn sync_views(&mut self) -> bool {
        let mut removed_any = false;
        let mut rounds = 0usize;
        loop {
            let current = self.view_ids();
            let removed: Vec<ViewId> = self
                .known_views
                .iter()
                .copied()
                .filter(|id| !current.contains(id))
                .collect();
            let added: Vec<ViewId> = current
                .iter()
                .copied()
                .filter(|id| !self.known_views.contains(id))
                .collect();
            if removed.is_empty() && added.is_empty() {
                return removed_any;
            }
            rounds += 1;
            assert!(
                rounds <= 1024,
                "view additions and removals did not settle after 1024 rounds"
            );
            self.known_views = current;
            for id in removed {
                removed_any = true;
                self.shell.view_removed(id);
            }
            self.listen_to_metrics_of(&added);
            for id in added {
                self.shell.view_added(id);
            }
        }
    }

    /// A frame at the platform's clock of every view that asked for one since the last, driven
    /// through [`Shell::frame`]. When a view was removed and none remains to ask for a frame, an
    /// empty-view frame still runs the build and tree finalization that unmounts it.
    fn frame_if_asked(&mut self, flush_removed_views: bool) {
        let views = self.platform.take_frame_requests();
        let elapsed = self.platform.elapsed();
        if !views.is_empty() || flush_removed_views {
            self.shell.frame(
                &views,
                Frame {
                    elapsed,
                    vsync: None,
                },
            );
        }
    }

    /// What Flutter's leak tracking checks: `cycle` (say, opening and closing a route) leaves no
    /// object behind in the arena. The first run warms up what is made once and kept, such as a
    /// singleton or a theme's cached value; the second is checked with
    /// [`waft_test::assert_no_new_objects`], which names each object left behind with its type
    /// and creation site.
    #[cfg(debug_assertions)]
    pub fn assert_leaves_nothing_behind(&mut self, mut cycle: impl FnMut(&mut WidgetTester)) {
        cycle(self);
        self.cell.checkpoint();
        let snapshot = waft_test::object_snapshot(&self.cell.borrow());
        cycle(self);
        self.cell.checkpoint();
        waft_test::assert_no_new_objects(&self.cell.borrow(), &snapshot);
    }

    /// Runs `body` with the app borrowed: a case's reads and changes that are not a pump.
    pub fn update<R>(&self, body: impl FnOnce(&mut App) -> R) -> R {
        body(&mut self.cell.borrow_mut())
    }
}

impl Default for WidgetTester {
    fn default() -> WidgetTester {
        WidgetTester::new()
    }
}

/// flutter_test's checks after a test: whatever root was attached across every view is disposed,
/// and then no timer may be pending.
impl Drop for WidgetTester {
    fn drop(&mut self) {
        if std::thread::panicking() || self.in_pump {
            return;
        }
        let has_root = {
            let mut app = self.cell.borrow_mut();
            let binding = WidgetsBinding::instance(&mut app);
            if binding.is_root_widget_attached(&app) {
                binding.attach_to_build_owner(&mut app, RootWidget::new());
                true
            } else {
                false
            }
        };
        if has_root {
            let views = self.view_ids();
            let elapsed = self.platform.elapsed();
            self.shell.frame(
                &views,
                Frame {
                    elapsed,
                    vsync: None,
                },
            );
        }
        assert!(
            !self.cell.borrow().has_pending_timers(),
            "A Timer is still pending even after the widget tree was disposed."
        );
    }
}

/// flutter_test's `TestVSync`: vends ordinary tickers, in no view.
pub struct TestVSync;

impl waft_scheduler::TickerProvider for TestVSync {
    fn create_ticker(
        &self,
        app: &mut App,
        on_tick: waft_scheduler::TickerCallback,
    ) -> waft_foundation::Ref<waft_scheduler::Ticker> {
        waft_scheduler::Ticker::new(app, on_tick, None)
    }
}