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