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    font_manager: FontMgr,
161    font_collection: FontCollection,
162
163    platform: Platform,
164
165    animation_clock: AnimationClock,
166    ticker_sender: RenderingTickerSender,
167
168    default_fonts: Vec<Cow<'static, str>>,
169    scale_factor: f64,
170}
171
172impl TestingRunner {
173    pub fn new<T>(
174        app: impl Into<AppComponent>,
175        size: Size2D,
176        hook: impl FnOnce(&mut Runner) -> T,
177        scale_factor: f64,
178    ) -> (Self, T) {
179        let (events_sender, events_receiver) = futures_channel::mpsc::unbounded();
180        let app = app.into();
181        let mut runner = Runner::new(move || integration(app.clone()).into_element());
182
183        runner.provide_root_context(ScreenReader::new);
184
185        let (mut ticker_sender, ticker) = RenderingTicker::new();
186        ticker_sender.set_overflow(true);
187        runner.provide_root_context(|| ticker);
188
189        let animation_clock = runner.provide_root_context(AnimationClock::new);
190
191        runner.provide_root_context(AssetCacher::create);
192
193        let tree = Tree::default();
194        let tree = Rc::new(RefCell::new(tree));
195
196        let platform = runner.provide_root_context({
197            let tree = tree.clone();
198            || Platform {
199                focused_accessibility_id: State::create(ACCESSIBILITY_ROOT_ID),
200                focused_accessibility_node: State::create(accesskit::Node::new(
201                    accesskit::Role::Window,
202                )),
203                root_size: State::create(size),
204                navigation_mode: State::create(NavigationMode::NotKeyboard),
205                preferred_theme: State::create(PreferredTheme::Light),
206                sender: Rc::new(move |user_event| {
207                    match user_event {
208                        UserEvent::RequestRedraw => {
209                            // Nothing
210                        }
211                        UserEvent::FocusAccessibilityNode(strategy) => {
212                            tree.borrow_mut().accessibility_diff.request_focus(strategy);
213                        }
214                        UserEvent::SetCursorIcon(_) => {
215                            // Nothing
216                        }
217                        UserEvent::Erased(_) => {
218                            // Nothing
219                        }
220                    }
221                }),
222            }
223        });
224
225        runner.provide_root_context(|| {
226            let clipboard: Option<Box<dyn ClipboardProvider>> = ClipboardContext::new()
227                .ok()
228                .map(|c| Box::new(c) as Box<dyn ClipboardProvider>);
229
230            State::create(clipboard)
231        });
232
233        runner.provide_root_context(|| tree.borrow().accessibility_generator.clone());
234
235        let hook_result = hook(&mut runner);
236
237        let mut font_collection = FontCollection::new();
238        let def_mgr = FontMgr::default();
239        let provider = TypefaceFontProvider::new();
240        let font_manager: FontMgr = provider.into();
241        font_collection.set_default_font_manager(def_mgr, None);
242        font_collection.set_dynamic_font_manager(font_manager.clone());
243        font_collection.paragraph_cache_mut().turn_on(false);
244
245        runner.provide_root_context(|| font_collection.clone());
246
247        let nodes_state = NodesState::default();
248        let accessibility = AccessibilityTree::default();
249
250        let mut runner = Self {
251            runner,
252            tree,
253            size,
254
255            accessibility,
256            platform,
257
258            nodes_state,
259            events_receiver,
260            events_sender,
261
262            font_manager,
263            font_collection,
264
265            animation_clock,
266            ticker_sender,
267
268            default_fonts: default_fonts(),
269            scale_factor,
270        };
271
272        runner.sync_and_update();
273
274        (runner, hook_result)
275    }
276
277    pub fn set_fonts(&mut self, fonts: HashMap<&str, &[u8]>) {
278        let mut provider = TypefaceFontProvider::new();
279        for (font_name, font_data) in fonts {
280            let ft_type = self
281                .font_collection
282                .fallback_manager()
283                .unwrap()
284                .new_from_data(font_data, None)
285                .unwrap_or_else(|| panic!("Failed to load font {font_name}."));
286            provider.register_typeface(ft_type, Some(font_name));
287        }
288        let font_manager: FontMgr = provider.into();
289        self.font_manager = font_manager.clone();
290        self.font_collection.set_dynamic_font_manager(font_manager);
291    }
292
293    pub fn set_default_fonts(&mut self, fonts: &[Cow<'static, str>]) {
294        self.default_fonts.clear();
295        self.default_fonts.extend_from_slice(fonts);
296        self.tree.borrow_mut().layout.reset();
297        self.tree.borrow_mut().text_cache.reset();
298        self.tree.borrow_mut().measure_layout(
299            self.size,
300            &self.font_collection,
301            &self.font_manager,
302            &self.events_sender,
303            self.scale_factor,
304            &self.default_fonts,
305        );
306        self.tree.borrow_mut().accessibility_diff.clear();
307        self.accessibility.focused_id = ACCESSIBILITY_ROOT_ID;
308        self.accessibility.init(&mut self.tree.borrow_mut());
309        self.sync_and_update();
310    }
311
312    pub async fn handle_events(&mut self) {
313        self.runner.handle_events().await
314    }
315
316    pub fn handle_events_immediately(&mut self) {
317        self.runner.handle_events_immediately()
318    }
319
320    pub fn sync_and_update(&mut self) {
321        while let Ok(events_chunk) = self.events_receiver.try_recv() {
322            match events_chunk {
323                EventsChunk::Processed(processed_events) => {
324                    let events_executor_adapter = EventsExecutorAdapter {
325                        runner: &mut self.runner,
326                    };
327                    events_executor_adapter.run(&mut self.nodes_state, processed_events);
328                }
329                EventsChunk::Batch(events) => {
330                    for event in events {
331                        self.runner.handle_event(
332                            event.node_id,
333                            event.name,
334                            event.data,
335                            event.bubbles,
336                        );
337                    }
338                }
339            }
340        }
341
342        let mutations = self.runner.sync_and_update();
343        self.runner.run_in(|| {
344            self.tree.borrow_mut().apply_mutations(mutations);
345        });
346        self.tree.borrow_mut().measure_layout(
347            self.size,
348            &self.font_collection,
349            &self.font_manager,
350            &self.events_sender,
351            self.scale_factor,
352            &self.default_fonts,
353        );
354
355        let accessibility_update = self
356            .accessibility
357            .process_updates(&mut self.tree.borrow_mut(), &self.events_sender);
358
359        self.platform
360            .focused_accessibility_id
361            .set_if_modified(accessibility_update.focus);
362        let node_id = self.accessibility.focused_node_id().unwrap();
363        let tree = self.tree.borrow();
364        let layout_node = tree.layout.get(&node_id).unwrap();
365        self.platform
366            .focused_accessibility_node
367            .set_if_modified(AccessibilityTree::create_node(node_id, layout_node, &tree));
368    }
369
370    /// Poll async tasks and events every `step` time for a total time of `duration`.
371    /// This is useful for animations for instance.
372    pub fn poll(&mut self, step: Duration, duration: Duration) {
373        let started = Instant::now();
374        while started.elapsed() < duration {
375            self.handle_events_immediately();
376            self.sync_and_update();
377            std::thread::sleep(step);
378            self.ticker_sender.broadcast_blocking(()).unwrap();
379        }
380    }
381
382    /// Poll async tasks and events every `step`, N times.
383    /// This is useful for animations for instance.
384    pub fn poll_n(&mut self, step: Duration, times: u32) {
385        for _ in 0..times {
386            self.handle_events_immediately();
387            self.sync_and_update();
388            std::thread::sleep(step);
389            self.ticker_sender.broadcast_blocking(()).unwrap();
390        }
391    }
392
393    pub fn send_event(&mut self, platform_event: PlatformEvent) {
394        let mut events_measurer_adapter = EventsMeasurerAdapter {
395            tree: &mut self.tree.borrow_mut(),
396            scale_factor: self.scale_factor,
397        };
398        let processed_events = events_measurer_adapter.run(
399            &mut vec![platform_event],
400            &mut self.nodes_state,
401            self.accessibility.focused_node_id(),
402        );
403        self.events_sender
404            .unbounded_send(EventsChunk::Processed(processed_events))
405            .unwrap();
406    }
407
408    pub fn move_cursor(&mut self, cursor: impl Into<CursorPoint>) {
409        self.send_event(PlatformEvent::Mouse {
410            name: MouseEventName::MouseMove,
411            cursor: cursor.into(),
412            button: Some(MouseButton::Left),
413        })
414    }
415
416    pub fn write_text(&mut self, text: impl ToString) {
417        let text = text.to_string();
418        self.send_event(PlatformEvent::Keyboard {
419            name: KeyboardEventName::KeyDown,
420            key: Key::Character(text),
421            code: Code::Unidentified,
422            modifiers: Modifiers::default(),
423        });
424        self.sync_and_update();
425    }
426
427    pub fn press_key(&mut self, key: Key) {
428        self.send_event(PlatformEvent::Keyboard {
429            name: KeyboardEventName::KeyDown,
430            key,
431            code: Code::Unidentified,
432            modifiers: Modifiers::default(),
433        });
434        self.sync_and_update();
435    }
436
437    pub fn press_cursor(&mut self, cursor: impl Into<CursorPoint>) {
438        let cursor = cursor.into();
439        self.send_event(PlatformEvent::Mouse {
440            name: MouseEventName::MouseDown,
441            cursor,
442            button: Some(MouseButton::Left),
443        });
444        self.sync_and_update();
445    }
446
447    pub fn release_cursor(&mut self, cursor: impl Into<CursorPoint>) {
448        let cursor = cursor.into();
449        self.send_event(PlatformEvent::Mouse {
450            name: MouseEventName::MouseUp,
451            cursor,
452            button: Some(MouseButton::Left),
453        });
454        self.sync_and_update();
455    }
456
457    pub fn click_cursor(&mut self, cursor: impl Into<CursorPoint>) {
458        let cursor = cursor.into();
459        self.send_event(PlatformEvent::Mouse {
460            name: MouseEventName::MouseDown,
461            cursor,
462            button: Some(MouseButton::Left),
463        });
464        self.sync_and_update();
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 scroll(&mut self, cursor: impl Into<CursorPoint>, scroll: impl Into<CursorPoint>) {
474        let cursor = cursor.into();
475        let scroll = scroll.into();
476        self.send_event(PlatformEvent::Wheel {
477            name: WheelEventName::Wheel,
478            scroll,
479            cursor,
480            source: WheelSource::Device,
481        });
482        self.sync_and_update();
483    }
484
485    pub fn animation_clock(&mut self) -> &mut AnimationClock {
486        &mut self.animation_clock
487    }
488
489    pub fn render(&mut self) -> SkData {
490        let mut surface = raster_n32_premul((self.size.width as i32, self.size.height as i32))
491            .expect("Failed to create the surface.");
492
493        let render_pipeline = RenderPipeline {
494            font_collection: &mut self.font_collection,
495            font_manager: &self.font_manager,
496            tree: &self.tree.borrow(),
497            canvas: surface.canvas(),
498            scale_factor: self.scale_factor,
499            background: Color::WHITE,
500        };
501        render_pipeline.render();
502
503        let image = surface.image_snapshot();
504        let mut context = surface.direct_context();
505        image
506            .encode(context.as_mut(), EncodedImageFormat::PNG, None)
507            .expect("Failed to encode the snapshot.")
508    }
509
510    pub fn render_to_file(&mut self, path: impl Into<PathBuf>) {
511        let path = path.into();
512
513        let image = self.render();
514
515        let mut snapshot_file = File::create(path).expect("Failed to create the snapshot file.");
516
517        snapshot_file
518            .write_all(&image)
519            .expect("Failed to save the snapshot file.");
520    }
521
522    pub fn find<T>(
523        &self,
524        matcher: impl Fn(TestingNode, &dyn ElementExt) -> Option<T>,
525    ) -> Option<T> {
526        let mut matched = None;
527        {
528            let tree = self.tree.borrow();
529            tree.traverse_depth(|id| {
530                if matched.is_some() {
531                    return;
532                }
533                let element = tree.elements.get(&id).unwrap();
534                let node = TestingNode {
535                    tree: self.tree.clone(),
536                    id,
537                };
538                matched = matcher(node, element.as_ref());
539            });
540        }
541
542        matched
543    }
544
545    pub fn find_many<T>(
546        &self,
547        matcher: impl Fn(TestingNode, &dyn ElementExt) -> Option<T>,
548    ) -> Vec<T> {
549        let mut matched = Vec::new();
550        {
551            let tree = self.tree.borrow();
552            tree.traverse_depth(|id| {
553                let element = tree.elements.get(&id).unwrap();
554                let node = TestingNode {
555                    tree: self.tree.clone(),
556                    id,
557                };
558                if let Some(result) = matcher(node, element.as_ref()) {
559                    matched.push(result);
560                }
561            });
562        }
563
564        matched
565    }
566}
567
568pub struct TestingNode {
569    tree: Rc<RefCell<Tree>>,
570    id: NodeId,
571}
572
573impl TestingNode {
574    pub fn layout(&self) -> LayoutNode {
575        self.tree.borrow().layout.get(&self.id).cloned().unwrap()
576    }
577
578    pub fn children(&self) -> Vec<Self> {
579        let children = self
580            .tree
581            .borrow()
582            .children
583            .get(&self.id)
584            .cloned()
585            .unwrap_or_default();
586
587        children
588            .into_iter()
589            .map(|child_id| Self {
590                id: child_id,
591                tree: self.tree.clone(),
592            })
593            .collect()
594    }
595
596    pub fn is_visible(&self) -> bool {
597        let layout = self.layout();
598        let effect_state = self
599            .tree
600            .borrow()
601            .effect_state
602            .get(&self.id)
603            .cloned()
604            .unwrap();
605
606        effect_state.is_visible(&self.tree.borrow().layout, &layout.area)
607    }
608
609    pub fn element(&self) -> Rc<dyn ElementExt> {
610        self.tree
611            .borrow()
612            .elements
613            .get(&self.id)
614            .cloned()
615            .expect("Element does not exist.")
616    }
617}