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