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(Some(events_chunk)) = self.events_receiver.try_next() {
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.tree.borrow_mut().apply_mutations(mutations);
342        self.tree.borrow_mut().measure_layout(
343            self.size,
344            &self.font_collection,
345            &self.font_manager,
346            &self.events_sender,
347            self.scale_factor,
348            &self.default_fonts,
349        );
350
351        let accessibility_update = self
352            .accessibility
353            .process_updates(&mut self.tree.borrow_mut(), &self.events_sender);
354
355        self.platform
356            .focused_accessibility_id
357            .set_if_modified(accessibility_update.focus);
358        let node_id = self.accessibility.focused_node_id().unwrap();
359        let tree = self.tree.borrow();
360        let layout_node = tree.layout.get(&node_id).unwrap();
361        self.platform
362            .focused_accessibility_node
363            .set_if_modified(AccessibilityTree::create_node(node_id, layout_node, &tree));
364    }
365
366    /// Poll async tasks and events every `step` time for a total time of `duration`.
367    /// This is useful for animations for instance.
368    pub fn poll(&mut self, step: Duration, duration: Duration) {
369        let started = Instant::now();
370        while started.elapsed() < duration {
371            self.handle_events_immediately();
372            self.sync_and_update();
373            std::thread::sleep(step);
374            self.ticker_sender.broadcast_blocking(()).unwrap();
375        }
376    }
377
378    /// Poll async tasks and events every `step`, N times.
379    /// This is useful for animations for instance.
380    pub fn poll_n(&mut self, step: Duration, times: u32) {
381        for _ in 0..times {
382            self.handle_events_immediately();
383            self.sync_and_update();
384            std::thread::sleep(step);
385            self.ticker_sender.broadcast_blocking(()).unwrap();
386        }
387    }
388
389    pub fn send_event(&mut self, platform_event: PlatformEvent) {
390        let mut events_measurer_adapter = EventsMeasurerAdapter {
391            tree: &mut self.tree.borrow_mut(),
392            scale_factor: self.scale_factor,
393        };
394        let processed_events = events_measurer_adapter.run(
395            &mut vec![platform_event],
396            &mut self.nodes_state,
397            self.accessibility.focused_node_id(),
398        );
399        self.events_sender
400            .unbounded_send(EventsChunk::Processed(processed_events))
401            .unwrap();
402    }
403
404    pub fn move_cursor(&mut self, cursor: impl Into<CursorPoint>) {
405        self.send_event(PlatformEvent::Mouse {
406            name: MouseEventName::MouseMove,
407            cursor: cursor.into(),
408            button: Some(MouseButton::Left),
409        })
410    }
411
412    pub fn write_text(&mut self, text: impl ToString) {
413        let text = text.to_string();
414        self.send_event(PlatformEvent::Keyboard {
415            name: KeyboardEventName::KeyDown,
416            key: Key::Character(text),
417            code: Code::Unidentified,
418            modifiers: Modifiers::default(),
419        });
420        self.sync_and_update();
421    }
422
423    pub fn press_key(&mut self, key: Key) {
424        self.send_event(PlatformEvent::Keyboard {
425            name: KeyboardEventName::KeyDown,
426            key,
427            code: Code::Unidentified,
428            modifiers: Modifiers::default(),
429        });
430        self.sync_and_update();
431    }
432
433    pub fn press_cursor(&mut self, cursor: impl Into<CursorPoint>) {
434        let cursor = cursor.into();
435        self.send_event(PlatformEvent::Mouse {
436            name: MouseEventName::MouseDown,
437            cursor,
438            button: Some(MouseButton::Left),
439        });
440        self.sync_and_update();
441    }
442
443    pub fn release_cursor(&mut self, cursor: impl Into<CursorPoint>) {
444        let cursor = cursor.into();
445        self.send_event(PlatformEvent::Mouse {
446            name: MouseEventName::MouseUp,
447            cursor,
448            button: Some(MouseButton::Left),
449        });
450        self.sync_and_update();
451    }
452
453    pub fn click_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        self.send_event(PlatformEvent::Mouse {
462            name: MouseEventName::MouseUp,
463            cursor,
464            button: Some(MouseButton::Left),
465        });
466        self.sync_and_update();
467    }
468
469    pub fn scroll(&mut self, cursor: impl Into<CursorPoint>, scroll: impl Into<CursorPoint>) {
470        let cursor = cursor.into();
471        let scroll = scroll.into();
472        self.send_event(PlatformEvent::Wheel {
473            name: WheelEventName::Wheel,
474            scroll,
475            cursor,
476            source: WheelSource::Device,
477        });
478        self.sync_and_update();
479    }
480
481    pub fn animation_clock(&mut self) -> &mut AnimationClock {
482        &mut self.animation_clock
483    }
484
485    pub fn render(&mut self) -> SkData {
486        let mut surface = raster_n32_premul((self.size.width as i32, self.size.height as i32))
487            .expect("Failed to create the surface.");
488
489        let render_pipeline = RenderPipeline {
490            font_collection: &mut self.font_collection,
491            font_manager: &self.font_manager,
492            tree: &self.tree.borrow(),
493            canvas: surface.canvas(),
494            scale_factor: self.scale_factor,
495            background: Color::WHITE,
496        };
497        render_pipeline.render();
498
499        let image = surface.image_snapshot();
500        let mut context = surface.direct_context();
501        image
502            .encode(context.as_mut(), EncodedImageFormat::PNG, None)
503            .expect("Failed to encode the snapshot.")
504    }
505
506    pub fn render_to_file(&mut self, path: impl Into<PathBuf>) {
507        let path = path.into();
508
509        let image = self.render();
510
511        let mut snapshot_file = File::create(path).expect("Failed to create the snapshot file.");
512
513        snapshot_file
514            .write_all(&image)
515            .expect("Failed to save the snapshot file.");
516    }
517
518    pub fn find<T>(
519        &self,
520        matcher: impl Fn(TestingNode, &dyn ElementExt) -> Option<T>,
521    ) -> Option<T> {
522        let mut matched = None;
523        {
524            let tree = self.tree.borrow();
525            tree.traverse_depth(|id| {
526                if matched.is_some() {
527                    return;
528                }
529                let element = tree.elements.get(&id).unwrap();
530                let node = TestingNode {
531                    tree: self.tree.clone(),
532                    id,
533                };
534                matched = matcher(node, element.as_ref());
535            });
536        }
537
538        matched
539    }
540
541    pub fn find_many<T>(
542        &self,
543        matcher: impl Fn(TestingNode, &dyn ElementExt) -> Option<T>,
544    ) -> Vec<T> {
545        let mut matched = Vec::new();
546        {
547            let tree = self.tree.borrow();
548            tree.traverse_depth(|id| {
549                let element = tree.elements.get(&id).unwrap();
550                let node = TestingNode {
551                    tree: self.tree.clone(),
552                    id,
553                };
554                if let Some(result) = matcher(node, element.as_ref()) {
555                    matched.push(result);
556                }
557            });
558        }
559
560        matched
561    }
562}
563
564pub struct TestingNode {
565    tree: Rc<RefCell<Tree>>,
566    id: NodeId,
567}
568
569impl TestingNode {
570    pub fn layout(&self) -> LayoutNode {
571        self.tree.borrow().layout.get(&self.id).cloned().unwrap()
572    }
573
574    pub fn children(&self) -> Vec<Self> {
575        let children = self
576            .tree
577            .borrow()
578            .children
579            .get(&self.id)
580            .cloned()
581            .unwrap_or_default();
582
583        children
584            .into_iter()
585            .map(|child_id| Self {
586                id: child_id,
587                tree: self.tree.clone(),
588            })
589            .collect()
590    }
591
592    pub fn is_visible(&self) -> bool {
593        let layout = self.layout();
594        let effect_state = self
595            .tree
596            .borrow()
597            .effect_state
598            .get(&self.id)
599            .cloned()
600            .unwrap();
601
602        effect_state.is_visible(&self.tree.borrow().layout, &layout.area)
603    }
604
605    pub fn element(&self) -> Rc<dyn ElementExt> {
606        self.tree
607            .borrow()
608            .elements
609            .get(&self.id)
610            .cloned()
611            .expect("Element does not exist.")
612    }
613}