Skip to main content

freya_testing/
lib.rs

1//! Testing utilities for Freya applications.
2//!
3//! Simulate your app execution in a headless environment.
4//!
5//! Use [launch_test] or [TestingRunner] to instantiate a headless testing runner.
6//!
7//! # Examples
8//!
9//! Basic usage:
10//!
11//! ```rust,no_run
12//! use freya::prelude::*;
13//! use freya_testing::TestingRunner;
14//!
15//! fn app() -> impl IntoElement {
16//!     let mut state = use_consume::<State<i32>>();
17//!     rect().on_mouse_up(move |_| *state.write() += 1)
18//! }
19//!
20//! fn main() {
21//!     let (mut test, state) = TestingRunner::new(
22//!         app,
23//!         (300., 300.).into(),
24//!         |runner| runner.provide_root_context(|| State::create(0)),
25//!         1.,
26//!     );
27//!     test.sync_and_update();
28//!     // Simulate a mouse click
29//!     test.click_cursor((15., 15.));
30//!     assert_eq!(*state.peek(), 1);
31//! }
32//! ```
33//!
34//! For a runnable example see `examples/testing_events.rs` in the repository.
35
36use std::{
37    borrow::Cow,
38    cell::RefCell,
39    collections::HashMap,
40    fs::File,
41    io::Write,
42    path::PathBuf,
43    rc::Rc,
44    time::{
45        Duration,
46        Instant,
47    },
48};
49
50use freya_clipboard::copypasta::{
51    ClipboardContext,
52    ClipboardProvider,
53};
54use freya_components::{
55    cache::AssetCacher,
56    integration::integration,
57};
58use freya_core::{
59    integration::*,
60    prelude::*,
61};
62use freya_engine::prelude::{
63    EncodedImageFormat,
64    FontCollection,
65    FontMgr,
66    SkData,
67    TypefaceFontProvider,
68    raster_n32_premul,
69};
70use ragnarok::{
71    CursorPoint,
72    EventsExecutorRunner,
73    EventsMeasurerRunner,
74    NodesState,
75};
76use torin::prelude::{
77    LayoutNode,
78    Size2D,
79};
80
81pub mod prelude {
82    pub use freya_core::{
83        events::platform::*,
84        prelude::*,
85    };
86
87    pub use crate::{
88        DocRunner,
89        TestingRunner,
90        launch_doc,
91        launch_test,
92    };
93}
94
95type DocRunnerHook = Box<dyn FnOnce(&mut TestingRunner)>;
96
97pub struct DocRunner {
98    app: AppComponent,
99    size: Size2D,
100    scale_factor: f64,
101    hook: Option<DocRunnerHook>,
102    image_path: PathBuf,
103}
104
105impl DocRunner {
106    pub fn render(self) {
107        let (mut test, _) = TestingRunner::new(self.app, self.size, |_| {}, self.scale_factor);
108        if let Some(hook) = self.hook {
109            (hook)(&mut test);
110        }
111        test.render_to_file(self.image_path);
112    }
113
114    pub fn with_hook(mut self, hook: impl FnOnce(&mut TestingRunner) + 'static) -> Self {
115        self.hook = Some(Box::new(hook));
116        self
117    }
118
119    pub fn with_image_path(mut self, image_path: PathBuf) -> Self {
120        self.image_path = image_path;
121        self
122    }
123
124    pub fn with_scale_factor(mut self, scale_factor: f64) -> Self {
125        self.scale_factor = scale_factor;
126        self
127    }
128
129    pub fn with_size(mut self, size: Size2D) -> Self {
130        self.size = size;
131        self
132    }
133}
134
135pub fn launch_doc(app: impl Into<AppComponent>, path: impl Into<PathBuf>) -> DocRunner {
136    DocRunner {
137        app: app.into(),
138        size: Size2D::new(250., 250.),
139        scale_factor: 1.0,
140        hook: None,
141        image_path: path.into(),
142    }
143}
144
145pub fn launch_test(app: impl Into<AppComponent>) -> TestingRunner {
146    TestingRunner::new(app, Size2D::new(500., 500.), |_| {}, 1.0).0
147}
148
149pub struct TestingRunner {
150    nodes_state: NodesState<NodeId>,
151    runner: Runner,
152    tree: Rc<RefCell<Tree>>,
153    size: Size2D,
154
155    accessibility: AccessibilityTree,
156
157    events_receiver: futures_channel::mpsc::UnboundedReceiver<EventsChunk>,
158    events_sender: futures_channel::mpsc::UnboundedSender<EventsChunk>,
159
160    requested_focus_strategy: Rc<RefCell<Option<AccessibilityFocusStrategy>>>,
161
162    font_manager: FontMgr,
163    font_collection: FontCollection,
164
165    platform: Platform,
166
167    animation_clock: AnimationClock,
168    ticker_sender: RenderingTickerSender,
169
170    default_fonts: Vec<Cow<'static, str>>,
171    scale_factor: f64,
172}
173
174impl TestingRunner {
175    pub fn new<T>(
176        app: impl Into<AppComponent>,
177        size: Size2D,
178        hook: impl FnOnce(&mut Runner) -> T,
179        scale_factor: f64,
180    ) -> (Self, T) {
181        let (events_sender, events_receiver) = futures_channel::mpsc::unbounded();
182        let app = app.into();
183        let mut runner = Runner::new(move || integration(app.clone()).into_element());
184
185        runner.provide_root_context(ScreenReader::new);
186
187        let (ticker_sender, ticker) = RenderingTicker::new();
188        runner.provide_root_context(|| ticker);
189
190        let animation_clock = runner.provide_root_context(AnimationClock::new);
191
192        runner.provide_root_context(AssetCacher::create);
193
194        let tree = Tree::default();
195        let tree = Rc::new(RefCell::new(tree));
196
197        let requested_focus_strategy: Rc<RefCell<Option<AccessibilityFocusStrategy>>> =
198            Rc::new(RefCell::new(None));
199
200        let platform = runner.provide_root_context({
201            let requested_focus_strategy = requested_focus_strategy.clone();
202            || Platform {
203                focused_accessibility_id: State::create(ACCESSIBILITY_ROOT_ID),
204                focused_accessibility_node: State::create(accesskit::Node::new(
205                    accesskit::Role::Window,
206                )),
207                root_size: State::create(size),
208                scale_factor: State::create(scale_factor),
209                navigation_mode: State::create(NavigationMode::NotKeyboard),
210                preferred_theme: State::create(PreferredTheme::Light),
211                is_app_focused: State::create(true),
212                accent_color: State::create(AccentColor::default()),
213                sender: Rc::new(move |user_event| {
214                    match user_event {
215                        UserEvent::RequestRedraw => {
216                            // Nothing
217                        }
218                        UserEvent::FocusAccessibilityNode(strategy) => {
219                            requested_focus_strategy.borrow_mut().replace(strategy);
220                        }
221                        UserEvent::SetCursorIcon(_) => {
222                            // Nothing
223                        }
224                        UserEvent::Erased(_) => {
225                            // Nothing
226                        }
227                    }
228                }),
229            }
230        });
231
232        runner.provide_root_context(|| {
233            let clipboard: Option<Box<dyn ClipboardProvider>> = ClipboardContext::new()
234                .ok()
235                .map(|c| Box::new(c) as Box<dyn ClipboardProvider>);
236
237            State::create(clipboard)
238        });
239
240        runner.provide_root_context(|| tree.borrow().accessibility_generator.clone());
241
242        let hook_result = hook(&mut runner);
243
244        let mut font_collection = FontCollection::new();
245        let def_mgr = FontMgr::default();
246        let provider = TypefaceFontProvider::new();
247        let font_manager: FontMgr = provider.into();
248        font_collection.set_default_font_manager(def_mgr, None);
249        font_collection.set_dynamic_font_manager(font_manager.clone());
250        font_collection.paragraph_cache_mut().turn_on(false);
251
252        runner.provide_root_context(|| font_collection.clone());
253
254        let nodes_state = NodesState::default();
255        let accessibility = AccessibilityTree::default();
256
257        let mut runner = Self {
258            runner,
259            tree,
260            size,
261
262            accessibility,
263            platform,
264
265            nodes_state,
266            events_receiver,
267            events_sender,
268
269            requested_focus_strategy,
270
271            font_manager,
272            font_collection,
273
274            animation_clock,
275            ticker_sender,
276
277            default_fonts: default_fonts(),
278            scale_factor,
279        };
280
281        runner.sync_and_update();
282
283        (runner, hook_result)
284    }
285
286    pub fn set_fonts(&mut self, fonts: HashMap<&str, &[u8]>) {
287        let mut provider = TypefaceFontProvider::new();
288        for (font_name, font_data) in fonts {
289            let ft_type = self
290                .font_collection
291                .fallback_manager()
292                .unwrap()
293                .new_from_data(font_data, None)
294                .unwrap_or_else(|| panic!("Failed to load font {font_name}."));
295            provider.register_typeface(ft_type, Some(font_name));
296        }
297        let font_manager: FontMgr = provider.into();
298        self.font_manager = font_manager.clone();
299        self.font_collection.set_dynamic_font_manager(font_manager);
300    }
301
302    pub fn set_default_fonts(&mut self, fonts: &[Cow<'static, str>]) {
303        self.default_fonts.clear();
304        self.default_fonts.extend_from_slice(fonts);
305        self.tree.borrow_mut().layout.reset();
306        self.tree.borrow_mut().text_cache.reset();
307        self.tree.borrow_mut().measure_layout(
308            self.size,
309            &mut self.font_collection,
310            &self.font_manager,
311            &self.events_sender,
312            self.scale_factor,
313            &self.default_fonts,
314        );
315        self.tree.borrow_mut().accessibility_diff.clear();
316        self.accessibility.focused_id = ACCESSIBILITY_ROOT_ID;
317        self.accessibility.init(&mut self.tree.borrow_mut());
318        self.sync_and_update();
319    }
320
321    pub async fn handle_events(&mut self) {
322        self.runner.handle_events().await
323    }
324
325    pub fn handle_events_immediately(&mut self) {
326        self.runner.handle_events_immediately()
327    }
328
329    pub fn sync_and_update(&mut self) {
330        if let Some(strategy) = self.requested_focus_strategy.borrow_mut().take() {
331            self.tree
332                .borrow_mut()
333                .accessibility_diff
334                .request_focus(strategy);
335        }
336
337        while let Ok(events_chunk) = self.events_receiver.try_recv() {
338            match events_chunk {
339                EventsChunk::Processed(processed_events) => {
340                    let events_executor_adapter = EventsExecutorAdapter {
341                        runner: &mut self.runner,
342                    };
343                    events_executor_adapter.run(&mut self.nodes_state, processed_events);
344                }
345                EventsChunk::Batch(events) => {
346                    for event in events {
347                        self.runner.handle_event(
348                            event.node_id,
349                            event.name,
350                            event.data,
351                            event.bubbles,
352                        );
353                    }
354                }
355            }
356        }
357
358        let mutations = self.runner.sync_and_update();
359        self.runner.run_in(|| {
360            self.tree.borrow_mut().apply_mutations(mutations);
361        });
362        self.tree.borrow_mut().measure_layout(
363            self.size,
364            &mut self.font_collection,
365            &self.font_manager,
366            &self.events_sender,
367            self.scale_factor,
368            &self.default_fonts,
369        );
370
371        let accessibility_update = self
372            .accessibility
373            .process_updates(&mut self.tree.borrow_mut(), &self.events_sender);
374
375        self.platform
376            .focused_accessibility_id
377            .set_if_modified(accessibility_update.focus);
378        let node_id = self.accessibility.focused_node_id().unwrap();
379        let tree = self.tree.borrow();
380        let layout_node = tree.layout.get(&node_id).unwrap();
381        self.platform
382            .focused_accessibility_node
383            .set_if_modified(AccessibilityTree::create_node(node_id, layout_node, &tree));
384    }
385
386    /// Poll async tasks and events every `step` time for a total time of `duration`.
387    /// This is useful for animations for instance.
388    pub fn poll(&mut self, step: Duration, duration: Duration) {
389        let started = Instant::now();
390        while started.elapsed() < duration {
391            self.handle_events_immediately();
392            self.sync_and_update();
393            std::thread::sleep(step);
394            self.ticker_sender.send(()).ok();
395        }
396    }
397
398    /// Poll async tasks and events every `step`, N times.
399    /// This is useful for animations for instance.
400    pub fn poll_n(&mut self, step: Duration, times: u32) {
401        for _ in 0..times {
402            self.handle_events_immediately();
403            self.sync_and_update();
404            std::thread::sleep(step);
405            self.ticker_sender.send(()).ok();
406        }
407    }
408
409    pub fn send_event(&mut self, platform_event: PlatformEvent) {
410        let mut events_measurer_adapter = EventsMeasurerAdapter {
411            tree: &mut self.tree.borrow_mut(),
412            scale_factor: self.scale_factor,
413        };
414        let processed_events = events_measurer_adapter.run(
415            &mut vec![platform_event],
416            &mut self.nodes_state,
417            self.accessibility.focused_node_id(),
418        );
419        self.events_sender
420            .unbounded_send(EventsChunk::Processed(processed_events))
421            .unwrap();
422    }
423
424    pub fn move_cursor(&mut self, cursor: impl Into<CursorPoint>) {
425        self.send_event(PlatformEvent::Mouse {
426            name: MouseEventName::MouseMove,
427            cursor: cursor.into(),
428            button: Some(MouseButton::Left),
429        })
430    }
431
432    pub fn write_text(&mut self, text: impl ToString) {
433        let text = text.to_string();
434        self.send_event(PlatformEvent::Keyboard {
435            name: KeyboardEventName::KeyDown,
436            key: Key::Character(text),
437            code: Code::Unidentified,
438            modifiers: Modifiers::default(),
439        });
440        self.sync_and_update();
441    }
442
443    pub fn press_key(&mut self, key: Key) {
444        self.send_event(PlatformEvent::Keyboard {
445            name: KeyboardEventName::KeyDown,
446            key,
447            code: Code::Unidentified,
448            modifiers: Modifiers::default(),
449        });
450        self.sync_and_update();
451    }
452
453    pub fn press_cursor(&mut self, cursor: impl Into<CursorPoint>) {
454        let cursor = cursor.into();
455        self.send_event(PlatformEvent::Mouse {
456            name: MouseEventName::MouseDown,
457            cursor,
458            button: Some(MouseButton::Left),
459        });
460        self.sync_and_update();
461    }
462
463    pub fn release_cursor(&mut self, cursor: impl Into<CursorPoint>) {
464        let cursor = cursor.into();
465        self.send_event(PlatformEvent::Mouse {
466            name: MouseEventName::MouseUp,
467            cursor,
468            button: Some(MouseButton::Left),
469        });
470        self.sync_and_update();
471    }
472
473    pub fn click_cursor(&mut self, cursor: impl Into<CursorPoint>) {
474        let cursor = cursor.into();
475        self.send_event(PlatformEvent::Mouse {
476            name: MouseEventName::MouseDown,
477            cursor,
478            button: Some(MouseButton::Left),
479        });
480        self.sync_and_update();
481        self.send_event(PlatformEvent::Mouse {
482            name: MouseEventName::MouseUp,
483            cursor,
484            button: Some(MouseButton::Left),
485        });
486        self.sync_and_update();
487    }
488
489    pub fn press_touch(&mut self, location: impl Into<CursorPoint>) {
490        self.send_event(PlatformEvent::Touch {
491            name: TouchEventName::TouchStart,
492            location: location.into(),
493            finger_id: 0,
494            phase: TouchPhase::Started,
495            force: None,
496        });
497        self.sync_and_update();
498    }
499
500    pub fn move_touch(&mut self, location: impl Into<CursorPoint>) {
501        self.send_event(PlatformEvent::Touch {
502            name: TouchEventName::TouchMove,
503            location: location.into(),
504            finger_id: 0,
505            phase: TouchPhase::Moved,
506            force: None,
507        });
508        self.sync_and_update();
509    }
510
511    pub fn release_touch(&mut self, location: impl Into<CursorPoint>) {
512        self.send_event(PlatformEvent::Touch {
513            name: TouchEventName::TouchEnd,
514            location: location.into(),
515            finger_id: 0,
516            phase: TouchPhase::Ended,
517            force: None,
518        });
519        self.sync_and_update();
520    }
521
522    pub fn scroll(&mut self, cursor: impl Into<CursorPoint>, scroll: impl Into<CursorPoint>) {
523        let cursor = cursor.into();
524        let scroll = scroll.into();
525        self.send_event(PlatformEvent::Wheel {
526            name: WheelEventName::Wheel,
527            scroll,
528            cursor,
529            source: WheelSource::Device,
530        });
531        self.sync_and_update();
532    }
533
534    pub fn animation_clock(&mut self) -> &mut AnimationClock {
535        &mut self.animation_clock
536    }
537
538    pub fn render(&mut self) -> SkData {
539        let mut surface = raster_n32_premul((self.size.width as i32, self.size.height as i32))
540            .expect("Failed to create the surface.");
541
542        let render_pipeline = RenderPipeline {
543            font_collection: &mut self.font_collection,
544            font_manager: &self.font_manager,
545            tree: &self.tree.borrow(),
546            canvas: surface.canvas(),
547            scale_factor: self.scale_factor,
548            background: Color::WHITE,
549        };
550        render_pipeline.render();
551
552        let image = surface.image_snapshot();
553        let mut context = surface.direct_context();
554        image
555            .encode(context.as_mut(), EncodedImageFormat::PNG, None)
556            .expect("Failed to encode the snapshot.")
557    }
558
559    pub fn render_to_file(&mut self, path: impl Into<PathBuf>) {
560        let path = path.into();
561
562        let image = self.render();
563
564        let mut snapshot_file = File::create(path).expect("Failed to create the snapshot file.");
565
566        snapshot_file
567            .write_all(&image)
568            .expect("Failed to save the snapshot file.");
569    }
570
571    pub fn find<T>(
572        &self,
573        matcher: impl Fn(TestingNode, &dyn ElementExt) -> Option<T>,
574    ) -> Option<T> {
575        let mut matched = None;
576        {
577            let tree = self.tree.borrow();
578            tree.traverse_depth(|id| {
579                if matched.is_some() {
580                    return;
581                }
582                let element = tree.elements.get(&id).unwrap();
583                let node = TestingNode {
584                    tree: self.tree.clone(),
585                    id,
586                };
587                matched = matcher(node, element.as_ref());
588            });
589        }
590
591        matched
592    }
593
594    pub fn find_many<T>(
595        &self,
596        matcher: impl Fn(TestingNode, &dyn ElementExt) -> Option<T>,
597    ) -> Vec<T> {
598        let mut matched = Vec::new();
599        {
600            let tree = self.tree.borrow();
601            tree.traverse_depth(|id| {
602                let element = tree.elements.get(&id).unwrap();
603                let node = TestingNode {
604                    tree: self.tree.clone(),
605                    id,
606                };
607                if let Some(result) = matcher(node, element.as_ref()) {
608                    matched.push(result);
609                }
610            });
611        }
612
613        matched
614    }
615}
616
617pub struct TestingNode {
618    tree: Rc<RefCell<Tree>>,
619    id: NodeId,
620}
621
622impl TestingNode {
623    pub fn layout(&self) -> LayoutNode {
624        self.tree.borrow().layout.get(&self.id).cloned().unwrap()
625    }
626
627    pub fn children(&self) -> Vec<Self> {
628        let children = self
629            .tree
630            .borrow()
631            .children
632            .get(&self.id)
633            .cloned()
634            .unwrap_or_default();
635
636        children
637            .into_iter()
638            .map(|child_id| Self {
639                id: child_id,
640                tree: self.tree.clone(),
641            })
642            .collect()
643    }
644
645    pub fn is_visible(&self) -> bool {
646        let layout = self.layout();
647        let effect_state = self
648            .tree
649            .borrow()
650            .effect_state
651            .get(&self.id)
652            .cloned()
653            .unwrap();
654
655        effect_state.is_visible(&self.tree.borrow().layout, &layout.area)
656    }
657
658    pub fn element(&self) -> Rc<dyn ElementExt> {
659        self.tree
660            .borrow()
661            .elements
662            .get(&self.id)
663            .cloned()
664            .expect("Element does not exist.")
665    }
666}