Skip to main content

waft_test/
platform.rs

1//! A platform a test configures and reads back.
2
3use std::cell::{Cell, RefCell};
4use std::rc::{Rc, Weak};
5use std::sync::{Arc, Condvar, Mutex};
6use std::time::Duration;
7
8use waft_embedder::{
9    AppExit, AppLifecycleState, Brightness, Cameras, CaptionSettings, Clipboard, CompositionLayer,
10    Compositor, Dispatcher, DockMenu, EmbeddedView, FileDialogs, Files, FontSource, GpuId, Haptics,
11    HardwareBuffer, HardwareBufferAllocator, HostEmbeddedView, HostGpu, HttpClient, Image,
12    ImageCodecFuture, ImageDecodeError, Instant, MediaAssets, MenuBar, Notifications, Offset,
13    Opener, Picture, Platform, Players, PointerReport, PopupMenus, RequestId, Restoration, Screen,
14    Screens, SignedDuration, SystemChrome, SystemContextMenu, SystemGpu, TargetPlatform,
15    TextServices, TrayIcons, VideoFrame, VideoFrameReaders, View, ViewEmbedder, ViewError,
16    ViewFocusEvent, ViewHost, ViewId, ViewMetrics, ViewRef, WindowConfig,
17};
18
19use waft_embedder::image_codecs::{ImageCodecs, ImageError, ImageErrorKind, ImageFuture};
20use waft_embedder::video_decoders::VideoDecoders;
21use waft_embedder::{SystemFontSource, test_support, valo};
22
23use crate::windows::view_of_request;
24use crate::{TestFontSource, TestTimeZone, TestView, TestWindows};
25
26type FontSourceMaker = Rc<dyn Fn() -> Box<dyn FontSource>>;
27type ImageCodecOpener = Rc<dyn Fn(Arc<[u8]>) -> ImageCodecFuture>;
28type PixelImporter = Rc<dyn Fn(valo::PixelBuffer) -> Option<Image>>;
29type PictureRasterizer = Rc<dyn Fn(&Picture, u32, u32) -> Option<Image>>;
30type ImageReader = Rc<dyn Fn(&Image) -> ImageFuture<valo::PixelBuffer>>;
31type FrameImporter = Rc<dyn Fn(&dyn VideoFrame) -> Option<Image>>;
32type BufferImporter = Rc<dyn Fn(&dyn HardwareBuffer) -> Option<Image>>;
33
34/// A platform a test builds: which host it claims to be, the views it offers, and each
35/// capability as the test's own implementation or absent. It keeps the frames the framework asks
36/// for, what it says of whether it handles back, and the deadlines it asks to be woken at, so a
37/// test can assert on them; the test itself
38/// pumps the app, since there is no loop to run it.
39///
40/// With a compositor it has a view embedder, which adds a view on any layer the app asks it to
41/// (`ViewEmbedder::add_view`), at once: a [`TestView`] at the request's metrics, carrying its id
42/// and asking what it asks of the system of the app's host, listed among the views until the app
43/// removes it. The test tells the framework of each view's coming and going itself, as a host
44/// would through `EmbedderClient::view_added` and `view_removed`.
45pub struct TestPlatform {
46    target: Cell<TargetPlatform>,
47    briefly_show_password: Cell<bool>,
48    brightness: Cell<Brightness>,
49    time_zone: RefCell<TestTimeZone>,
50    default_route: String,
51    /// The real instant the platform's clock starts from; [`now`](Platform::now) moves only when
52    /// [`advance_clock`](Self::advance_clock) advances [`elapsed`](Self::elapsed).
53    clock_origin: Instant,
54    /// How far the test has moved the platform's clock since `clock_origin`.
55    elapsed: Cell<Duration>,
56    /// The screens the platform reports and where the pointer is on them; `None` in both means
57    /// [`Platform::screens`] answers `None`.
58    screens: TestScreens,
59    /// The views the platform gave the app, as a phone gives its screen.
60    views: RefCell<Vec<ViewRef>>,
61    /// The number the next request for a view takes, a window's or one on a layer.
62    next_request: Cell<u64>,
63    /// The views the app added on layers and has not removed, in the order it added them, which
64    /// each view's handle removes its view from as it is dropped.
65    added_views: Rc<RefCell<Vec<Rc<TestView>>>>,
66    /// The view of each frame asked for since the test last took them, in the order asked.
67    frame_requests: RefCell<Vec<ViewId>>,
68    dispatcher: Arc<TestDispatcher>,
69    /// Makes the source the platform's fonts come from: flutter_test's unless the test gives
70    /// one.
71    font_source: FontSourceMaker,
72    image_codec: Option<ImageCodecOpener>,
73    pixel_import: Option<PixelImporter>,
74    picture_to_image: Option<PictureRasterizer>,
75    image_read_back: Option<ImageReader>,
76    frame_import: Option<FrameImporter>,
77    buffer_import: Option<BufferImporter>,
78    windows: Option<Rc<TestWindows>>,
79    clipboard: Option<Rc<dyn Clipboard>>,
80    system_chrome: Option<Rc<dyn SystemChrome>>,
81    haptics: Option<Rc<dyn Haptics>>,
82    system_context_menu: Option<Rc<dyn SystemContextMenu>>,
83    menu_bar: Option<Rc<dyn MenuBar>>,
84    popup_menus: Option<Rc<dyn PopupMenus>>,
85    tray_icons: Option<Rc<dyn TrayIcons>>,
86    file_dialogs: Option<Rc<dyn FileDialogs>>,
87    http: Option<Rc<dyn HttpClient>>,
88    files: Option<Rc<dyn Files>>,
89    opener: Option<Rc<dyn Opener>>,
90    notifications: Option<Rc<dyn Notifications>>,
91    compositor: Option<Arc<dyn Compositor>>,
92    /// The name of the platform's one GPU, which every device runs on.
93    gpu_id: Option<GpuId>,
94    hardware_buffer_allocator: Option<Arc<dyn HardwareBufferAllocator>>,
95    players: Option<Rc<dyn Players>>,
96    media_assets: Option<Rc<dyn MediaAssets>>,
97    image_codecs: Option<Rc<dyn ImageCodecs>>,
98    video_decoders: Option<Rc<dyn VideoDecoders>>,
99    cameras: Option<Rc<dyn Cameras>>,
100    video_frame_readers: Option<Rc<dyn VideoFrameReaders>>,
101    caption_settings: Option<Rc<dyn CaptionSettings>>,
102    dock_menu: Option<Rc<dyn DockMenu>>,
103    text_services: Option<Rc<dyn TextServices>>,
104    restoration: Option<Rc<dyn Restoration>>,
105    app_exit: Option<Rc<dyn AppExit>>,
106    initial_lifecycle_state: Option<AppLifecycleState>,
107}
108
109impl TestPlatform {
110    /// A platform claiming to be Android, as Flutter's test binding does, in light mode, with
111    /// flutter_test's fonts, no view and no capability.
112    pub fn new() -> TestPlatform {
113        TestPlatform {
114            target: Cell::new(TargetPlatform::Android),
115            briefly_show_password: Cell::new(true),
116            brightness: Cell::new(Brightness::Light),
117            time_zone: RefCell::default(),
118            default_route: "/".into(),
119            clock_origin: Instant::now(),
120            elapsed: Cell::new(Duration::ZERO),
121            screens: TestScreens::default(),
122            views: RefCell::default(),
123            next_request: Cell::new(1),
124            added_views: Rc::default(),
125            frame_requests: RefCell::default(),
126            dispatcher: Arc::new(TestDispatcher::default()),
127            font_source: Rc::new(|| Box::new(TestFontSource::new())),
128            image_codec: None,
129            pixel_import: None,
130            picture_to_image: None,
131            image_read_back: None,
132            frame_import: None,
133            buffer_import: None,
134            windows: None,
135            clipboard: None,
136            system_chrome: None,
137            haptics: None,
138            system_context_menu: None,
139            menu_bar: None,
140            popup_menus: None,
141            tray_icons: None,
142            file_dialogs: None,
143            http: None,
144            files: None,
145            opener: None,
146            notifications: None,
147            compositor: None,
148            gpu_id: None,
149            hardware_buffer_allocator: None,
150            players: None,
151            media_assets: None,
152            image_codecs: None,
153            video_decoders: None,
154            cameras: None,
155            video_frame_readers: None,
156            caption_settings: None,
157            dock_menu: None,
158            text_services: None,
159            restoration: None,
160            app_exit: None,
161            initial_lifecycle_state: None,
162        }
163    }
164
165    /// The same platform claiming to be `target`.
166    pub fn on(self, target: TargetPlatform) -> TestPlatform {
167        self.target.set(target);
168        self
169    }
170
171    /// The same platform giving the app `view`, as a phone gives its screen.
172    pub fn with_view(self, view: ViewRef) -> TestPlatform {
173        self.views.borrow_mut().push(view);
174        self
175    }
176
177    /// The same platform giving the app an 800 x 600 [`TestView`] numbered by each of `ids`, in
178    /// that order, as a desktop gives one window to each.
179    pub fn with_views(self, ids: &[ViewId]) -> TestPlatform {
180        for &id in ids {
181            let view = Rc::new(TestView::new(800.0, 600.0).with_id(id));
182            self.views.borrow_mut().push(view as ViewRef);
183        }
184        self
185    }
186
187    /// The [`TestView`] numbered `id` among the platform's views, however it came: given,
188    /// made for a window the app asked for, or added on a layer.
189    ///
190    /// # Panics
191    ///
192    /// If none of the platform's views numbered `id` is a [`TestView`].
193    pub fn test_view(&self, id: ViewId) -> Rc<TestView> {
194        self.views()
195            .into_iter()
196            .find(|view| view.id() == id)
197            .and_then(|view| (view as Rc<dyn std::any::Any>).downcast::<TestView>().ok())
198            .unwrap_or_else(|| panic!("no TestView numbered {id:?} among the platform's views"))
199    }
200
201    /// How far the test has moved the platform's clock since it was made.
202    pub fn elapsed(&self) -> Duration {
203        self.elapsed.get()
204    }
205
206    /// Advances the platform's clock by `duration`, so [`Platform::now`] moves only when the test
207    /// says so.
208    pub fn advance_clock(&self, duration: Duration) {
209        self.elapsed.set(self.elapsed.get() + duration);
210    }
211
212    /// The same platform reporting `screens` from [`Platform::screens`].
213    pub fn with_screens(self, screens: Vec<Screen>) -> TestPlatform {
214        self.set_screens(screens);
215        self
216    }
217
218    /// Changes the screens [`Platform::screens`] reports; the client hears of it through
219    /// `EmbedderClient::screens_changed`.
220    pub fn set_screens(&self, screens: Vec<Screen>) {
221        *self.screens.screens.borrow_mut() = Some(screens);
222    }
223
224    /// The same platform reporting the pointer at `location` from
225    /// [`Screens::pointer_location`].
226    pub fn with_pointer_location(self, location: Offset) -> TestPlatform {
227        self.set_pointer_location(Some(location));
228        self
229    }
230
231    /// Changes where [`Screens::pointer_location`] reports the pointer.
232    pub fn set_pointer_location(&self, location: Option<Offset>) {
233        self.screens.pointer_location.set(location);
234    }
235
236    /// The views the app added on layers and has not removed, in the order it added them.
237    pub fn added_views(&self) -> Vec<Rc<TestView>> {
238        self.added_views.borrow().clone()
239    }
240
241    /// Gives the app `view` while it runs, as an embedder adds one; the test tells the
242    /// framework of it itself, as a host would through `EmbedderClient::view_added`.
243    pub fn give_view(&self, view: ViewRef) {
244        self.views.borrow_mut().push(view);
245    }
246
247    /// Takes the view numbered `id` back while the app runs.
248    pub fn take_view(&self, id: ViewId) {
249        self.views.borrow_mut().retain(|view| view.id() != id);
250    }
251
252    /// The same platform answering `shown` for the system's setting of whether an obscured field
253    /// briefly shows the character just typed; on unless set, as dart:ui's default is.
254    pub fn with_briefly_show_password(self, shown: bool) -> TestPlatform {
255        self.briefly_show_password.set(shown);
256        self
257    }
258
259    pub fn with_brightness(self, brightness: Brightness) -> TestPlatform {
260        self.brightness.set(brightness);
261        self
262    }
263
264    /// The route the host would open the app at; `/` unless set.
265    pub fn with_default_route(mut self, route: impl Into<String>) -> TestPlatform {
266        self.default_route = route.into();
267        self
268    }
269
270    /// The lifecycle state the host would start the app in; none unless set.
271    pub fn with_initial_lifecycle_state(mut self, state: AppLifecycleState) -> TestPlatform {
272        self.initial_lifecycle_state = Some(state);
273        self
274    }
275
276    /// Fonts for text to shape against, in place of flutter_test's, where every family is
277    /// FlutterTest ([`TestFontSource`]).
278    pub fn with_font_source(
279        mut self,
280        make: impl Fn() -> Box<dyn FontSource> + 'static,
281    ) -> TestPlatform {
282        self.font_source = Rc::new(make);
283        self
284    }
285
286    /// The system's fonts in place of flutter_test's, as a host shapes text against, for a test
287    /// that looks at what its text draws as.
288    pub fn with_system_fonts(self) -> TestPlatform {
289        self.with_font_source(|| {
290            Box::new(SystemFontSource::new(valo_system_fonts::fontmgr::platform()))
291        })
292    }
293
294    /// One GPU with no window, as a host has its renderer's: encoded pictures, such as a PNG's
295    /// bytes, are opened on it, images made from pixels and pictures, and images read back. What
296    /// a test that looks at what the app paints gives its platform. Encoded pictures are decoded
297    /// by valo's software decoders, the same on every machine.
298    pub fn with_gpu(self) -> TestPlatform {
299        self.with_image_codec(test_support::open_image_codec)
300            .with_pixel_import(test_support::imported_pixels)
301            .with_picture_to_image(|picture, width, height| {
302                Some(test_support::picture_to_image(picture, [width, height]))
303            })
304            .with_read_image_pixels(test_support::read_image_pixels)
305    }
306
307    /// The decoder behind `open_image_codec`; none unless set, so every image fails to open.
308    pub fn with_image_codec(
309        mut self,
310        open: impl Fn(Arc<[u8]>) -> ImageCodecFuture + 'static,
311    ) -> TestPlatform {
312        self.image_codec = Some(Rc::new(open));
313        self
314    }
315
316    /// The renderer behind `import_pixels`; none unless set, so no image is made from pixels.
317    pub fn with_pixel_import(
318        mut self,
319        import: impl Fn(valo::PixelBuffer) -> Option<Image> + 'static,
320    ) -> TestPlatform {
321        self.pixel_import = Some(Rc::new(import));
322        self
323    }
324
325    /// The renderer behind `picture_to_image_sync`; none unless set, so no picture is drawn
326    /// into an image.
327    pub fn with_picture_to_image(
328        mut self,
329        draw: impl Fn(&Picture, u32, u32) -> Option<Image> + 'static,
330    ) -> TestPlatform {
331        self.picture_to_image = Some(Rc::new(draw));
332        self
333    }
334
335    /// The renderer behind `read_image_pixels`; none unless set, so no image is read back.
336    pub fn with_read_image_pixels(
337        mut self,
338        read: impl Fn(&Image) -> ImageFuture<valo::PixelBuffer> + 'static,
339    ) -> TestPlatform {
340        self.image_read_back = Some(Rc::new(read));
341        self
342    }
343
344    /// The renderer behind `import_video_frame`; none unless set, so no image is made of a frame.
345    pub fn with_frame_import(
346        mut self,
347        import: impl Fn(&dyn VideoFrame) -> Option<Image> + 'static,
348    ) -> TestPlatform {
349        self.frame_import = Some(Rc::new(import));
350        self
351    }
352
353    /// The renderer behind `import_hardware_buffer`; none unless set, so no image is made of a
354    /// buffer.
355    pub fn with_buffer_import(
356        mut self,
357        import: impl Fn(&dyn HardwareBuffer) -> Option<Image> + 'static,
358    ) -> TestPlatform {
359        self.buffer_import = Some(Rc::new(import));
360        self
361    }
362
363    /// The same platform answering requests for views with `windows`, as a desktop makes a
364    /// window for each.
365    pub fn with_windows(mut self, windows: Rc<TestWindows>) -> TestPlatform {
366        self.windows = Some(windows);
367        self
368    }
369
370    pub fn with_clipboard(mut self, clipboard: Rc<dyn Clipboard>) -> TestPlatform {
371        self.clipboard = Some(clipboard);
372        self
373    }
374
375    pub fn with_system_chrome(mut self, system_chrome: Rc<dyn SystemChrome>) -> TestPlatform {
376        self.system_chrome = Some(system_chrome);
377        self
378    }
379
380    pub fn with_haptics(mut self, haptics: Rc<dyn Haptics>) -> TestPlatform {
381        self.haptics = Some(haptics);
382        self
383    }
384
385    pub fn with_system_context_menu(mut self, menu: Rc<dyn SystemContextMenu>) -> TestPlatform {
386        self.system_context_menu = Some(menu);
387        self
388    }
389
390    pub fn with_menu_bar(mut self, menu_bar: Rc<dyn MenuBar>) -> TestPlatform {
391        self.menu_bar = Some(menu_bar);
392        self
393    }
394
395    pub fn with_popup_menus(mut self, menus: Rc<dyn PopupMenus>) -> TestPlatform {
396        self.popup_menus = Some(menus);
397        self
398    }
399
400    pub fn with_tray_icons(mut self, tray_icons: Rc<dyn TrayIcons>) -> TestPlatform {
401        self.tray_icons = Some(tray_icons);
402        self
403    }
404
405    pub fn with_file_dialogs(mut self, file_dialogs: Rc<dyn FileDialogs>) -> TestPlatform {
406        self.file_dialogs = Some(file_dialogs);
407        self
408    }
409
410    /// The HTTP client behind `http`; none unless set, so every request fails at once.
411    pub fn with_http(mut self, http: Rc<dyn HttpClient>) -> TestPlatform {
412        self.http = Some(http);
413        self
414    }
415
416    /// The file system behind `files`; none unless set, so every path fails at once.
417    pub fn with_files(mut self, files: Rc<dyn Files>) -> TestPlatform {
418        self.files = Some(files);
419        self
420    }
421
422    pub fn with_opener(mut self, opener: Rc<dyn Opener>) -> TestPlatform {
423        self.opener = Some(opener);
424        self
425    }
426
427    pub fn with_notifications(mut self, notifications: Rc<dyn Notifications>) -> TestPlatform {
428        self.notifications = Some(notifications);
429        self
430    }
431
432    pub fn with_compositor(mut self, compositor: Arc<dyn Compositor>) -> TestPlatform {
433        self.compositor = Some(compositor);
434        self
435    }
436
437    /// The platform's one GPU named `id`, as Windows names an adapter by its LUID and Linux a GPU
438    /// by its render node: what [`gpu_id`](Platform::gpu_id) answers for every device, and its GPU
439    /// says of itself. None unless set, as on Apple's systems and Android.
440    pub fn with_gpu_id(mut self, id: GpuId) -> TestPlatform {
441        self.gpu_id = Some(id);
442        self
443    }
444
445    pub fn with_hardware_buffer_allocator(
446        mut self,
447        allocator: Arc<dyn HardwareBufferAllocator>,
448    ) -> TestPlatform {
449        self.hardware_buffer_allocator = Some(allocator);
450        self
451    }
452
453    pub fn with_players(mut self, players: Rc<dyn Players>) -> TestPlatform {
454        self.players = Some(players);
455        self
456    }
457
458    pub fn with_media_assets(mut self, media_assets: Rc<dyn MediaAssets>) -> TestPlatform {
459        self.media_assets = Some(media_assets);
460        self
461    }
462
463    pub fn with_image_codecs(mut self, image_codecs: Rc<dyn ImageCodecs>) -> TestPlatform {
464        self.image_codecs = Some(image_codecs);
465        self
466    }
467
468    /// The platform's GPU answering `video_decoders` as its video decoders: a host's own, where a
469    /// test decodes for real, as `waft-embedder-apple`'s are VideoToolbox's.
470    pub fn with_video_decoders(mut self, video_decoders: Rc<dyn VideoDecoders>) -> TestPlatform {
471        self.video_decoders = Some(video_decoders);
472        self
473    }
474
475    pub fn with_cameras(mut self, cameras: Rc<dyn Cameras>) -> TestPlatform {
476        self.cameras = Some(cameras);
477        self
478    }
479
480    pub fn with_video_frame_readers(
481        mut self,
482        video_frame_readers: Rc<dyn VideoFrameReaders>,
483    ) -> TestPlatform {
484        self.video_frame_readers = Some(video_frame_readers);
485        self
486    }
487
488    pub fn with_caption_settings(
489        mut self,
490        caption_settings: Rc<dyn CaptionSettings>,
491    ) -> TestPlatform {
492        self.caption_settings = Some(caption_settings);
493        self
494    }
495
496    pub fn with_dock_menu(mut self, dock_menu: Rc<dyn DockMenu>) -> TestPlatform {
497        self.dock_menu = Some(dock_menu);
498        self
499    }
500
501    pub fn with_text_services(mut self, services: Rc<dyn TextServices>) -> TestPlatform {
502        self.text_services = Some(services);
503        self
504    }
505
506    pub fn with_restoration(mut self, restoration: Rc<dyn Restoration>) -> TestPlatform {
507        self.restoration = Some(restoration);
508        self
509    }
510
511    pub fn with_app_exit(mut self, app_exit: Rc<dyn AppExit>) -> TestPlatform {
512        self.app_exit = Some(app_exit);
513        self
514    }
515
516    /// The platform in `zone`, which is UTC unless a test says otherwise.
517    pub fn with_time_zone(self, zone: TestTimeZone) -> TestPlatform {
518        self.set_time_zone(zone);
519        self
520    }
521
522    /// Changes which host the platform claims to be, for a test that switches mid-way.
523    pub fn set_target(&self, target: TargetPlatform) {
524        self.target.set(target);
525    }
526
527    /// Changes whether an obscured field briefly shows the character just typed, as the user
528    /// changes the system's setting; dart:ui tells no one, and the framework reads it next as
529    /// it needs it.
530    pub fn set_briefly_show_password(&self, shown: bool) {
531        self.briefly_show_password.set(shown);
532    }
533
534    /// Changes the local time zone, as the user changes the system's; a `DateTime` made after it
535    /// reads the new zone.
536    pub fn set_time_zone(&self, zone: TestTimeZone) {
537        *self.time_zone.borrow_mut() = zone;
538    }
539
540    /// Changes the brightness; the client hears of it as it would from a host.
541    pub fn set_brightness(&self, brightness: Brightness) {
542        self.brightness.set(brightness);
543    }
544
545    /// The view of each frame the framework asked for since the test last took them, in the
546    /// order asked, a view asked again included.
547    pub fn frame_requests(&self) -> Vec<ViewId> {
548        self.frame_requests.borrow().clone()
549    }
550
551    /// Whether `view` asked for a frame since the test last took the requests.
552    pub fn has_frame_request(&self, view: ViewId) -> bool {
553        self.frame_requests.borrow().contains(&view)
554    }
555
556    /// Takes the request `view` made for a frame, for the test to give it its frame; answers
557    /// whether it had made one since the last take.
558    pub fn take_frame_request(&self, view: ViewId) -> bool {
559        let mut requests = self.frame_requests.borrow_mut();
560        let asked = requests.contains(&view);
561        requests.retain(|&asking| asking != view);
562        asked
563    }
564
565    /// The views that asked for a frame since the last take, each once, in the order the platform
566    /// gained them, for the test to give them a refresh, as a host does. A request of a view the
567    /// platform does not have is dropped, as a host drops it.
568    pub fn take_frame_requests(&self) -> Vec<ViewId> {
569        let requests = std::mem::take(&mut *self.frame_requests.borrow_mut());
570        self.views()
571            .iter()
572            .map(|view| view.id())
573            .filter(|id| requests.contains(id))
574            .collect()
575    }
576
577    /// The timer wakeups the framework has set, in order. A `None` is the framework
578    /// saying no timer is waiting.
579    pub fn wakes(&self) -> Vec<Option<Instant>> {
580        self.dispatcher.timer_wakeups()
581    }
582
583    /// How often a ready task has asked the host to wake the app.
584    pub fn wake_now_requests(&self) -> usize {
585        self.dispatcher.wake_now_requests()
586    }
587
588    /// The host's event loop asleep: waits up to `timeout` until a ready task has asked to wake
589    /// the app more than `since` times ([`wake_now_requests`](Self::wake_now_requests)), as work
590    /// finishing on another thread does.
591    pub fn wait_for_wake(&self, since: usize, timeout: Duration) {
592        self.dispatcher.wait_for_wake(since, timeout);
593    }
594
595    /// The number of a new request for a view.
596    fn take_request_id(&self) -> RequestId {
597        let id = RequestId(self.next_request.get());
598        self.next_request.set(id.0 + 1);
599        id
600    }
601}
602
603impl Default for TestPlatform {
604    fn default() -> TestPlatform {
605        TestPlatform::new()
606    }
607}
608
609impl Platform for TestPlatform {
610    fn target_platform(&self) -> TargetPlatform {
611        self.target.get()
612    }
613
614    fn request_frame(&self, view: ViewId) {
615        self.frame_requests.borrow_mut().push(view);
616    }
617
618    fn now(&self) -> Instant {
619        self.clock_origin + self.elapsed.get()
620    }
621
622    fn dispatcher(&self) -> Arc<dyn Dispatcher> {
623        Arc::clone(&self.dispatcher) as Arc<dyn Dispatcher>
624    }
625
626    fn views(&self) -> Vec<ViewRef> {
627        let windows = self.windows.iter().flat_map(|windows| windows.open_views());
628        let added = self.added_views().into_iter().map(|view| view as ViewRef);
629        let given = self.views.borrow().clone();
630        given.into_iter().chain(windows).chain(added).collect()
631    }
632
633    fn view(&self, id: ViewId) -> Option<ViewRef> {
634        self.views().into_iter().find(|view| view.id() == id)
635    }
636
637    fn request_view(
638        &self,
639        config: WindowConfig,
640        initial_data: Option<String>,
641    ) -> Result<RequestId, ViewError> {
642        let windows = self.windows.as_ref().ok_or(ViewError::Unsupported)?;
643        let id = self.take_request_id();
644        windows.request(id, config, initial_data);
645        Ok(id)
646    }
647
648    fn briefly_show_password(&self) -> bool {
649        self.briefly_show_password.get()
650    }
651
652    fn time_zone_offset(&self, seconds_since_epoch: i64) -> SignedDuration {
653        self.time_zone.borrow().offset(seconds_since_epoch)
654    }
655
656    fn time_zone_name(&self, seconds_since_epoch: i64) -> String {
657        self.time_zone.borrow().name(seconds_since_epoch)
658    }
659
660    fn platform_brightness(&self) -> Brightness {
661        self.brightness.get()
662    }
663
664    fn default_route_name(&self) -> String {
665        self.default_route.clone()
666    }
667
668    fn initial_lifecycle_state(&self) -> Option<AppLifecycleState> {
669        self.initial_lifecycle_state
670    }
671
672    fn font_source(&self) -> Option<Box<dyn FontSource>> {
673        Some((self.font_source)())
674    }
675
676    fn open_image_codec(&self, bytes: Arc<[u8]>) -> ImageCodecFuture {
677        match &self.image_codec {
678            Some(open) => open(bytes),
679            None => Box::pin(std::future::ready(Err(ImageDecodeError::NoDecoder))),
680        }
681    }
682
683    fn import_pixels(&self, pixels: valo::PixelBuffer) -> Option<Image> {
684        self.pixel_import.as_ref().and_then(|import| import(pixels))
685    }
686
687    fn picture_to_image_sync(&self, picture: &Picture, width: u32, height: u32) -> Option<Image> {
688        self.picture_to_image
689            .as_ref()
690            .and_then(|draw| draw(picture, width, height))
691    }
692
693    fn read_image_pixels(&self, image: &Image) -> ImageFuture<valo::PixelBuffer> {
694        match &self.image_read_back {
695            Some(read) => read(image),
696            None => Box::pin(std::future::ready(Err(ImageError::new(
697                ImageErrorKind::Unsupported,
698                "the test platform reads no image back: give it with_gpu",
699            )))),
700        }
701    }
702
703    fn import_video_frame(&self, frame: &dyn VideoFrame) -> Option<Image> {
704        self.frame_import.as_ref().and_then(|import| import(frame))
705    }
706
707    fn import_hardware_buffer(&self, buffer: &dyn HardwareBuffer) -> Option<Image> {
708        self.buffer_import
709            .as_ref()
710            .and_then(|import| import(buffer))
711    }
712
713    /// None: this host's buffers are in memory, on no GPU, as buffers a device cannot take, which
714    /// a drawing skips.
715    fn import_texture(
716        &self,
717        _buffer: &dyn HardwareBuffer,
718        _device: &wgpu::Device,
719    ) -> Option<wgpu::Texture> {
720        None
721    }
722
723    /// None, as for `import_texture`: no device takes this host's buffers.
724    fn import_planes(
725        &self,
726        _buffer: &dyn HardwareBuffer,
727        _device: &wgpu::Device,
728    ) -> Option<Vec<wgpu::TextureView>> {
729        None
730    }
731
732    fn screens(&self) -> Option<&dyn Screens> {
733        (self.screens.screens.borrow().is_some() || self.screens.pointer_location.get().is_some())
734            .then_some(&self.screens as &dyn Screens)
735    }
736
737    fn clipboard(&self) -> Option<&dyn Clipboard> {
738        self.clipboard.as_deref()
739    }
740
741    fn system_chrome(&self) -> Option<&dyn SystemChrome> {
742        self.system_chrome.as_deref()
743    }
744
745    fn haptics(&self) -> Option<&dyn Haptics> {
746        self.haptics.as_deref()
747    }
748
749    fn system_context_menu(&self) -> Option<&dyn SystemContextMenu> {
750        self.system_context_menu.as_deref()
751    }
752
753    fn menu_bar(&self) -> Option<&dyn MenuBar> {
754        self.menu_bar.as_deref()
755    }
756
757    fn popup_menus(&self) -> Option<&dyn PopupMenus> {
758        self.popup_menus.as_deref()
759    }
760
761    fn tray_icons(&self) -> Option<&dyn TrayIcons> {
762        self.tray_icons.as_deref()
763    }
764
765    fn file_dialogs(&self) -> Option<&dyn FileDialogs> {
766        self.file_dialogs.as_deref()
767    }
768
769    fn http(&self) -> Option<&dyn HttpClient> {
770        self.http.as_deref()
771    }
772
773    fn files(&self) -> Option<&dyn Files> {
774        self.files.as_deref()
775    }
776
777    fn opener(&self) -> Option<&dyn Opener> {
778        self.opener.as_deref()
779    }
780
781    fn notifications(&self) -> Option<&dyn Notifications> {
782        self.notifications.as_deref()
783    }
784
785    fn compositor(&self) -> Option<Arc<dyn Compositor>> {
786        self.compositor.clone()
787    }
788
789    /// The GPU the test named, whatever the device.
790    fn gpu_id(&self, _device: &wgpu::Device) -> Option<GpuId> {
791        self.gpu_id
792    }
793
794    /// One GPU, whatever `id` names, under the name the test gave it, with the decoders and the
795    /// allocator the test gave it; none where it gave neither.
796    fn gpu(&self, _id: Option<GpuId>) -> Option<Rc<dyn SystemGpu>> {
797        if self.video_decoders.is_none() && self.hardware_buffer_allocator.is_none() {
798            return None;
799        }
800        Some(Rc::new(HostGpu {
801            id: self.gpu_id,
802            video_decoders: self.video_decoders.clone(),
803            hardware_buffer_allocator: self.hardware_buffer_allocator.clone(),
804        }))
805    }
806
807    fn players(&self) -> Option<&dyn Players> {
808        self.players.as_deref()
809    }
810
811    fn media_assets(&self) -> Option<&dyn MediaAssets> {
812        self.media_assets.as_deref()
813    }
814
815    fn image_codecs(&self) -> Option<&dyn ImageCodecs> {
816        self.image_codecs.as_deref()
817    }
818
819    fn cameras(&self) -> Option<&dyn Cameras> {
820        self.cameras.as_deref()
821    }
822
823    fn video_frame_readers(&self) -> Option<&dyn VideoFrameReaders> {
824        self.video_frame_readers.as_deref()
825    }
826
827    fn caption_settings(&self) -> Option<&dyn CaptionSettings> {
828        self.caption_settings.as_deref()
829    }
830
831    fn view_embedder(&self) -> Option<&dyn ViewEmbedder> {
832        self.compositor.as_ref().map(|_| self as &dyn ViewEmbedder)
833    }
834
835    fn dock_menu(&self) -> Option<&dyn DockMenu> {
836        self.dock_menu.as_deref()
837    }
838
839    fn text_services(&self) -> Option<&dyn TextServices> {
840        self.text_services.as_deref()
841    }
842
843    fn restoration(&self) -> Option<&dyn Restoration> {
844        self.restoration.as_deref()
845    }
846
847    fn app_exit(&self) -> Option<&dyn AppExit> {
848        self.app_exit.as_deref()
849    }
850}
851
852/// The views the app adds on layers, made at once at the metrics the app gives, and removed as
853/// their handles are dropped. The metrics, sight and input the app sends them later go nowhere: a
854/// test hands the framework what a host would make of them itself.
855impl ViewEmbedder for TestPlatform {
856    fn add_view(
857        &self,
858        _layer: &Arc<dyn CompositionLayer>,
859        metrics: ViewMetrics,
860        host: Rc<dyn ViewHost>,
861        initial_data: Option<String>,
862    ) -> Result<EmbeddedView, ViewError> {
863        let id = self.take_request_id();
864        let view = TestView::with_metrics(metrics)
865            .with_id(view_of_request(id))
866            .with_request(id, initial_data)
867            .with_host(host);
868        self.added_views.borrow_mut().push(Rc::new(view));
869        let added = AddedView {
870            view: view_of_request(id),
871            added_views: Rc::downgrade(&self.added_views),
872        };
873        Ok(EmbeddedView::new(id, Box::new(added)))
874    }
875
876    fn send_pointer_reports(&self, _reports: Vec<PointerReport>) {}
877
878    fn send_view_focus_event(&self, _event: ViewFocusEvent) {}
879}
880
881/// The test platform's side of a view the app added: dropping its handle removes it from the
882/// platform's views.
883struct AddedView {
884    view: ViewId,
885    added_views: Weak<RefCell<Vec<Rc<TestView>>>>,
886}
887
888impl HostEmbeddedView for AddedView {
889    fn set_metrics(&self, _metrics: ViewMetrics) {}
890
891    fn set_in_sight(&self, _in_sight: bool) {}
892
893    fn remove(&self) {
894        if let Some(added_views) = self.added_views.upgrade() {
895            added_views
896                .borrow_mut()
897                .retain(|added| added.id() != self.view);
898        }
899    }
900}
901
902#[derive(Default)]
903struct TestScreens {
904    screens: RefCell<Option<Vec<Screen>>>,
905    pointer_location: Cell<Option<Offset>>,
906}
907
908impl Screens for TestScreens {
909    fn screens(&self) -> Vec<Screen> {
910        self.screens.borrow().clone().unwrap_or_default()
911    }
912
913    fn pointer_location(&self) -> Option<Offset> {
914        self.pointer_location.get()
915    }
916}
917
918/// A host that records what it was asked for and never wakes the app. The test pumps the app
919/// instead, where a host would call `EmbedderClient::wake`, and work runs at once on the
920/// calling thread, so a test needs only a checkpoint to see its result.
921#[derive(Default)]
922pub struct TestDispatcher {
923    timer_wakeups: Mutex<Vec<Option<Instant>>>,
924    /// How often a ready task has asked the host to wake the app.
925    wakes: Mutex<usize>,
926    /// Told at each wake.
927    woken: Condvar,
928}
929
930impl TestDispatcher {
931    /// The timer wakeups set, in order. A `None` is the application saying no timer is
932    /// waiting.
933    pub fn timer_wakeups(&self) -> Vec<Option<Instant>> {
934        self.timer_wakeups
935            .lock()
936            .expect("the wakeups are never poisoned: nothing runs under their lock")
937            .clone()
938    }
939
940    /// How often a ready task has asked the host to wake the app.
941    pub fn wake_now_requests(&self) -> usize {
942        *self.wakes()
943    }
944
945    /// Waits up to `timeout` until a ready task has asked to wake the app more than `since`
946    /// times.
947    pub(crate) fn wait_for_wake(&self, since: usize, timeout: Duration) {
948        let wakes = self.wakes();
949        let _ = self
950            .woken
951            .wait_timeout_while(wakes, timeout, |wakes| *wakes <= since);
952    }
953
954    fn wakes(&self) -> std::sync::MutexGuard<'_, usize> {
955        self.wakes
956            .lock()
957            .expect("the wake counter is never poisoned: nothing runs under its lock")
958    }
959}
960
961impl Dispatcher for TestDispatcher {
962    fn wake_at(&self, timer_wakeup: Option<Instant>) {
963        self.timer_wakeups
964            .lock()
965            .expect("the wakeups are never poisoned: nothing runs under their lock")
966            .push(timer_wakeup);
967    }
968
969    fn wake_now(&self) {
970        *self.wakes() += 1;
971        self.woken.notify_all();
972    }
973
974    fn dispatch(&self, work: Box<dyn FnOnce() + Send>) {
975        work();
976    }
977}
978
979#[cfg(test)]
980mod tests {
981    use waft_embedder::Platform;
982
983    use super::TestPlatform;
984
985    #[test]
986    fn the_test_platforms_fonts_are_flutter_test() {
987        let platform = TestPlatform::new();
988        let mut source = platform.font_source().expect("the test platform has fonts");
989        assert!(source.family("Roboto")[0].matches("FlutterTest"));
990    }
991
992    #[test]
993    fn with_the_systems_fonts_a_family_is_the_systems_not_flutter_tests() {
994        let platform = TestPlatform::new().with_system_fonts();
995        let mut source = platform.font_source().expect("the test platform has fonts");
996        let face = source
997            .face_for_codepoint('a', Default::default())
998            .expect("the system has a face for 'a'");
999        assert!(!face.matches("FlutterTest"));
1000    }
1001
1002    #[test]
1003    fn with_gpu_a_png_opens_as_its_picture() {
1004        use waft_embedder::valo;
1005        let pixels = valo::PixelBuffer::new(
1006            valo::PixelLayout::packed([3, 2], valo::PixelFormat::Rgba8, valo::AlphaType::Straight),
1007            vec![255; 3 * 2 * 4],
1008        )
1009        .expect("white pixels");
1010        let png = crate::encode_png(&pixels);
1011        let platform = TestPlatform::new().with_gpu();
1012        let mut codec =
1013            pollster::block_on(platform.open_image_codec(png.into())).expect("a PNG opens");
1014        assert_eq!(codec.frame_count(), 1);
1015        let frame = pollster::block_on(codec.next_frame()).expect("its frame");
1016        assert_eq!(frame.image.size(), [3, 2]);
1017    }
1018
1019    #[test]
1020    fn a_test_platform_briefly_shows_passwords_unless_told_not_to() {
1021        assert!(TestPlatform::new().briefly_show_password());
1022        assert!(
1023            !TestPlatform::new()
1024                .with_briefly_show_password(false)
1025                .briefly_show_password()
1026        );
1027    }
1028
1029    #[test]
1030    fn a_change_of_the_setting_is_what_the_platform_answers_next() {
1031        let platform = TestPlatform::new();
1032        platform.set_briefly_show_password(false);
1033        assert!(!platform.briefly_show_password());
1034        platform.set_briefly_show_password(true);
1035        assert!(platform.briefly_show_password());
1036    }
1037
1038    #[test]
1039    fn the_clock_moves_only_when_advanced() {
1040        use std::time::Duration;
1041
1042        let platform = TestPlatform::new();
1043        let start = platform.now();
1044        std::thread::sleep(Duration::from_millis(5));
1045        assert_eq!(platform.now(), start);
1046        assert_eq!(platform.elapsed(), Duration::ZERO);
1047
1048        platform.advance_clock(Duration::from_millis(16));
1049        assert_eq!(platform.elapsed(), Duration::from_millis(16));
1050        assert_eq!(
1051            platform.now().duration_since(start),
1052            Duration::from_millis(16)
1053        );
1054
1055        platform.advance_clock(Duration::from_millis(4));
1056        assert_eq!(platform.elapsed(), Duration::from_millis(20));
1057        assert_eq!(
1058            platform.now().duration_since(start),
1059            Duration::from_millis(20)
1060        );
1061    }
1062
1063    #[test]
1064    fn screens_and_pointer_location_are_absent_until_configured() {
1065        use waft_embedder::{Offset, Rect, Screen, ScreenId};
1066
1067        let bare = TestPlatform::new();
1068        assert!(bare.screens().is_none());
1069
1070        let main = Screen {
1071            id: ScreenId(1),
1072            name: "Main".to_owned(),
1073            frame: Rect::from_ltwh(0.0, 0.0, 1440.0, 900.0),
1074            visible_frame: Rect::from_ltwh(0.0, 25.0, 1440.0, 875.0),
1075            scale: 2.0,
1076            refresh_rate: Some(60.0),
1077        };
1078        let with_screens = TestPlatform::new()
1079            .with_screens(vec![main.clone()])
1080            .with_pointer_location(Offset::new(120.0, 340.0));
1081        let screens = with_screens.screens().expect("configured screens");
1082        assert_eq!(screens.screens(), [main]);
1083        assert_eq!(screens.pointer_location(), Some(Offset::new(120.0, 340.0)));
1084
1085        with_screens.set_pointer_location(None);
1086        assert_eq!(with_screens.screens().unwrap().pointer_location(), None);
1087
1088        let pointer_only = TestPlatform::new().with_pointer_location(Offset::new(5.0, 6.0));
1089        let screens = pointer_only.screens().expect("pointer location configured");
1090        assert!(screens.screens().is_empty());
1091        assert_eq!(screens.pointer_location(), Some(Offset::new(5.0, 6.0)));
1092    }
1093}