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_press(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 accesskit::TreeUpdate;
51use freya_clipboard::{
52    copypasta::{
53        ClipboardContext,
54        ClipboardProvider,
55    },
56    prelude::Clipboard,
57};
58use freya_components::{
59    cache::AssetCacher,
60    integration::integration,
61};
62use freya_core::{
63    integration::*,
64    prelude::*,
65};
66use freya_engine::prelude::{
67    EncodedImageFormat,
68    FontCollection,
69    FontMgr,
70    SkData,
71    SkSurface,
72    TypefaceFontProvider,
73    raster_n32_premul,
74    register_font_typeface,
75};
76use ragnarok::{
77    CursorPoint,
78    EventsExecutorRunner,
79    EventsMeasurerRunner,
80    NodesState,
81};
82use torin::prelude::{
83    LayoutNode,
84    Size2D,
85};
86
87pub mod prelude {
88    pub use freya_core::{
89        events::platform::*,
90        prelude::*,
91    };
92
93    pub use crate::{
94        TestingRunner,
95        launch_test,
96    };
97}
98
99type PendingFonts = Rc<RefCell<Vec<(Cow<'static, str>, Bytes)>>>;
100
101pub fn launch_test(app: impl Into<AppComponent>) -> TestingRunner {
102    TestingRunner::new(app, Size2D::new(500., 500.), |_| {}, 1.0).0
103}
104
105pub struct TestingRunner {
106    nodes_state: NodesState<NodeId>,
107    runner: Runner,
108    tree: Rc<RefCell<Tree>>,
109    size: Size2D,
110    surface: Option<SkSurface>,
111
112    accessibility: AccessibilityTree,
113
114    events_receiver: futures_channel::mpsc::UnboundedReceiver<EventsChunk>,
115    events_sender: futures_channel::mpsc::UnboundedSender<EventsChunk>,
116
117    requested_focus_strategy: Rc<RefCell<Option<AccessibilityFocusStrategy>>>,
118    pending_fonts: PendingFonts,
119
120    font_provider: TypefaceFontProvider,
121    font_manager: FontMgr,
122    font_collection: FontCollection,
123
124    platform: PlatformWindow,
125
126    animation_clock: AnimationClock,
127    ticker_sender: RenderingTickerSender,
128
129    default_fonts: Vec<Cow<'static, str>>,
130    scale_factor: f64,
131}
132
133impl Drop for TestingRunner {
134    fn drop(&mut self) {
135        if let Some(contexts) = GlobalContexts::try_get()
136            && let Some(platform) = contexts.try_get_context::<Platform>()
137        {
138            platform.unregister_window(self.platform.id);
139        }
140    }
141}
142
143impl TestingRunner {
144    /// Creates a runner with a physical viewport size and rendering scale factor.
145    pub fn new<T>(
146        app: impl Into<AppComponent>,
147        size: Size2D,
148        hook: impl FnOnce(&mut Runner) -> T,
149        scale_factor: f64,
150    ) -> (Self, T) {
151        GlobalContexts::register();
152
153        let (events_sender, events_receiver) = futures_channel::mpsc::unbounded();
154        let app = app.into();
155        let mut runner = Runner::new(move || integration(app.clone()).into_element());
156
157        GlobalContexts::get().insert_context(Clipboard::create(
158            ClipboardContext::new()
159                .ok()
160                .map(|clipboard| Box::new(clipboard) as Box<dyn ClipboardProvider>),
161        ));
162
163        runner.provide_root_context(ScreenReader::new);
164
165        let (ticker_sender, ticker) = RenderingTicker::new();
166        runner.provide_root_context(|| ticker);
167
168        let animation_clock = runner.provide_root_context(AnimationClock::new);
169
170        runner.provide_root_context(AssetCacher::create);
171
172        let tree = Tree::default();
173        let tree = Rc::new(RefCell::new(tree));
174
175        let requested_focus_strategy: Rc<RefCell<Option<AccessibilityFocusStrategy>>> =
176            Rc::new(RefCell::new(None));
177
178        let mut font_collection = FontCollection::new();
179        let def_mgr = FontMgr::default();
180        let provider = TypefaceFontProvider::new();
181        let font_manager: FontMgr = provider.clone().into();
182        font_collection.set_default_font_manager(def_mgr, None);
183        font_collection.set_dynamic_font_manager(font_manager.clone());
184        font_collection.paragraph_cache_mut().turn_on(false);
185
186        let pending_fonts = Rc::new(RefCell::new(Vec::new()));
187        GlobalContexts::get().insert_context(Platform::new({
188            let pending_fonts = pending_fonts.clone();
189            move |event| {
190                if let GlobalUserEvent::LoadFont {
191                    font_name,
192                    font_data,
193                } = event
194                {
195                    pending_fonts.borrow_mut().push((font_name, font_data));
196                }
197            }
198        }));
199
200        runner.provide_root_context(TargetPlatform::detect);
201        let platform = runner.run_in({
202            let requested_focus_strategy = requested_focus_strategy.clone();
203            || PlatformWindow {
204                id: 0,
205                focused_accessibility_id: State::create(ACCESSIBILITY_ROOT_ID),
206                focused_accessibility_node: State::create(accesskit::Node::new(
207                    accesskit::Role::Window,
208                )),
209                root_size: State::create(size / scale_factor as f32),
210                scale_factor: State::create(scale_factor),
211                custom_scale_factor: State::create(1.0),
212                navigation_mode: State::create(NavigationMode::NotKeyboard),
213                preferred_theme: State::create(PreferredTheme::Light),
214                is_app_focused: State::create(true),
215                accent_color: State::create(AccentColor::default()),
216                sender: Rc::new(move |user_event| {
217                    match user_event {
218                        UserEvent::FocusAccessibilityNode(strategy) => {
219                            requested_focus_strategy.borrow_mut().replace(strategy);
220                        }
221                        UserEvent::RequestRedraw | UserEvent::SetCustomScaleFactor(_) => {
222                            // Nothing
223                        }
224                    }
225                }),
226            }
227        });
228
229        Platform::get().register_window(platform.clone());
230        runner.provide_root_context(|| CurrentWindowId(platform.id));
231        runner.provide_root_context(|| tree.borrow().accessibility_generator.clone());
232
233        let hook_result = hook(&mut runner);
234
235        runner.provide_root_context(|| font_collection.clone());
236
237        let nodes_state = NodesState::default();
238        let accessibility = AccessibilityTree::default();
239
240        let mut runner = Self {
241            runner,
242            tree,
243            size,
244            surface: None,
245
246            accessibility,
247            platform,
248
249            nodes_state,
250            events_receiver,
251            events_sender,
252
253            requested_focus_strategy,
254            pending_fonts,
255
256            font_provider: provider,
257            font_manager,
258            font_collection,
259
260            animation_clock,
261            ticker_sender,
262
263            default_fonts: default_fonts(),
264            scale_factor,
265        };
266
267        runner.sync_and_update();
268
269        (runner, hook_result)
270    }
271
272    pub fn set_fonts(&mut self, fonts: HashMap<&str, &[u8]>) {
273        for (font_name, font_data) in fonts {
274            self.register_font(font_name, font_data);
275        }
276        self.invalidate_text_layout();
277    }
278
279    fn register_font(&mut self, font_name: &str, font_data: &[u8]) {
280        let typeface = self
281            .font_collection
282            .fallback_manager()
283            .unwrap()
284            .new_from_data(SkData::new_copy(font_data), None)
285            .unwrap_or_else(|| panic!("Failed to load font {font_name}."));
286        register_font_typeface(&mut self.font_provider, font_name, typeface);
287    }
288
289    fn invalidate_text_layout(&mut self) {
290        self.font_collection.clear_caches();
291        let mut tree = self.tree.borrow_mut();
292        tree.layout.reset();
293        tree.text_cache.reset();
294    }
295
296    pub fn set_default_fonts(&mut self, fonts: &[Cow<'static, str>]) {
297        self.default_fonts.clear();
298        self.default_fonts.extend_from_slice(fonts);
299        self.invalidate_text_layout();
300        self.tree.borrow_mut().measure_layout(
301            self.size,
302            &mut self.font_collection,
303            &self.font_manager,
304            &self.events_sender,
305            &mut self.nodes_state,
306            self.scale_factor,
307            &self.default_fonts,
308        );
309        self.tree.borrow_mut().accessibility_diff.clear();
310        self.accessibility.focused_id = ACCESSIBILITY_ROOT_ID;
311        self.accessibility.init(&mut self.tree.borrow_mut(), "");
312        self.sync_and_update();
313    }
314
315    /// Run a closure inside the app runtime.
316    pub fn run_in<T>(&self, run: impl FnOnce() -> T) -> T {
317        self.runner.run_in(run)
318    }
319
320    pub async fn handle_events(&mut self) {
321        self.runner.handle_events().await
322    }
323
324    pub fn handle_events_immediately(&mut self) {
325        self.runner.handle_events_immediately()
326    }
327
328    pub fn process_focus_strategy(&mut self) {
329        if let Some(strategy) = self.requested_focus_strategy.borrow_mut().take() {
330            self.tree
331                .borrow_mut()
332                .accessibility_diff
333                .request_focus(strategy);
334        }
335    }
336
337    pub fn process_events_and_layout(&mut self) {
338        while let Ok(events_chunk) = self.events_receiver.try_recv() {
339            match events_chunk {
340                EventsChunk::Processed(processed_events) => {
341                    let events_executor_adapter = EventsExecutorAdapter {
342                        runner: &mut self.runner,
343                    };
344                    events_executor_adapter.run(&mut self.nodes_state, processed_events);
345                }
346                EventsChunk::Batch(events) => {
347                    for event in events {
348                        self.runner.handle_event(
349                            event.node_id,
350                            event.name,
351                            event.data,
352                            event.bubbles,
353                        );
354                    }
355                }
356            }
357        }
358
359        let mutations = self.runner.sync_and_update();
360        let result = self.runner.run_in(|| {
361            self.tree
362                .borrow_mut()
363                .apply_mutations(mutations, self.scale_factor as f32)
364        });
365        if let Some(strategy) = result.auto_focus {
366            self.requested_focus_strategy.borrow_mut().replace(strategy);
367        }
368        let pending_fonts = self.pending_fonts.take();
369        if !pending_fonts.is_empty() {
370            for (font_name, font_data) in pending_fonts {
371                self.register_font(&font_name, &font_data);
372            }
373            self.invalidate_text_layout();
374        }
375        self.tree.borrow_mut().measure_layout(
376            self.size,
377            &mut self.font_collection,
378            &self.font_manager,
379            &self.events_sender,
380            &mut self.nodes_state,
381            self.scale_factor,
382            &self.default_fonts,
383        );
384    }
385
386    pub fn commit_accessibility(&mut self) -> TreeUpdate {
387        let accessibility_update = self.accessibility.process_updates(
388            &mut self.tree.borrow_mut(),
389            &self.events_sender,
390            "",
391        );
392
393        self.platform
394            .focused_accessibility_id
395            .set_if_modified(accessibility_update.focus);
396        let node_id = self.accessibility.focused_node_id().unwrap();
397        let tree = self.tree.borrow();
398        let layout_node = tree.layout.get(&node_id).unwrap();
399        self.platform
400            .focused_accessibility_node
401            .set_if_modified(AccessibilityTree::create_node(
402                node_id,
403                layout_node,
404                &tree,
405                "",
406            ));
407
408        accessibility_update
409    }
410
411    pub fn sync_and_update(&mut self) -> TreeUpdate {
412        self.process_focus_strategy();
413        self.process_events_and_layout();
414        self.commit_accessibility()
415    }
416
417    /// Poll async tasks and events every `step` time for a total time of `duration`.
418    /// This is useful for animations for instance.
419    pub fn poll(&mut self, step: Duration, duration: Duration) {
420        let started = Instant::now();
421        while started.elapsed() < duration {
422            self.handle_events_immediately();
423            self.sync_and_update();
424            std::thread::sleep(step);
425            self.ticker_sender.notify();
426        }
427    }
428
429    /// Poll async tasks and events every `step`, N times.
430    /// This is useful for animations for instance.
431    pub fn poll_n(&mut self, step: Duration, times: u32) {
432        for _ in 0..times {
433            self.handle_events_immediately();
434            self.sync_and_update();
435            std::thread::sleep(step);
436            self.ticker_sender.notify();
437        }
438    }
439
440    /// Resolve the [CursorIcon] for the currently hovered nodes.
441    pub fn cursor_icon(&self) -> CursorIcon {
442        self.tree.borrow().cursor_icon(&self.nodes_state)
443    }
444
445    /// Queue an action requested by assistive technology for a supported target.
446    pub fn send_accessibility_action(&mut self, request: AccessibilityActionEventData) -> bool {
447        self.accessibility
448            .handle_action(request, &mut self.tree.borrow_mut(), &self.events_sender)
449    }
450
451    /// Resolve cursor visibility for the currently hovered nodes.
452    pub fn cursor_visible(&self) -> bool {
453        self.tree.borrow().cursor_visible(&self.nodes_state)
454    }
455
456    pub fn send_event(&mut self, platform_event: PlatformEvent) {
457        let mut events_measurer_adapter = EventsMeasurerAdapter {
458            tree: &mut self.tree.borrow_mut(),
459            scale_factor: self.scale_factor,
460        };
461        let processed_events = events_measurer_adapter.run(
462            &mut vec![platform_event],
463            &mut self.nodes_state,
464            self.accessibility.focused_node_id(),
465        );
466        self.events_sender
467            .unbounded_send(EventsChunk::Processed(processed_events))
468            .unwrap();
469    }
470
471    pub fn move_cursor(&mut self, cursor: impl Into<CursorPoint>) {
472        self.send_event(PlatformEvent::Mouse {
473            name: MouseEventName::MouseMove,
474            cursor: cursor.into(),
475            button: Some(MouseButton::Left),
476        });
477        self.sync_and_update();
478    }
479
480    pub fn write_text(&mut self, text: impl ToString) {
481        let text = text.to_string();
482        self.send_event(PlatformEvent::Keyboard {
483            name: KeyboardEventName::KeyDown,
484            key: Key::Character(text),
485            code: Code::Unidentified,
486            modifiers: Modifiers::default(),
487        });
488        self.sync_and_update();
489    }
490
491    pub fn press_key(&mut self, key: Key) {
492        self.send_event(PlatformEvent::Keyboard {
493            name: KeyboardEventName::KeyDown,
494            key,
495            code: Code::Unidentified,
496            modifiers: Modifiers::default(),
497        });
498        self.sync_and_update();
499    }
500
501    pub fn press_cursor(&mut self, cursor: impl Into<CursorPoint>) {
502        let cursor = cursor.into();
503        self.send_event(PlatformEvent::Mouse {
504            name: MouseEventName::MouseDown,
505            cursor,
506            button: Some(MouseButton::Left),
507        });
508        self.sync_and_update();
509    }
510
511    pub fn release_cursor(&mut self, cursor: impl Into<CursorPoint>) {
512        let cursor = cursor.into();
513        self.send_event(PlatformEvent::Mouse {
514            name: MouseEventName::MouseUp,
515            cursor,
516            button: Some(MouseButton::Left),
517        });
518        self.sync_and_update();
519    }
520
521    pub fn click_cursor(&mut self, cursor: impl Into<CursorPoint>) {
522        let cursor = cursor.into();
523        self.send_event(PlatformEvent::Mouse {
524            name: MouseEventName::MouseDown,
525            cursor,
526            button: Some(MouseButton::Left),
527        });
528        self.sync_and_update();
529        self.send_event(PlatformEvent::Mouse {
530            name: MouseEventName::MouseUp,
531            cursor,
532            button: Some(MouseButton::Left),
533        });
534        self.sync_and_update();
535    }
536
537    pub fn press_touch(&mut self, location: impl Into<CursorPoint>) {
538        self.send_event(PlatformEvent::Touch {
539            name: TouchEventName::TouchStart,
540            location: location.into(),
541            finger_id: 0,
542            phase: TouchPhase::Started,
543            force: None,
544        });
545        self.sync_and_update();
546    }
547
548    pub fn move_touch(&mut self, location: impl Into<CursorPoint>) {
549        self.send_event(PlatformEvent::Touch {
550            name: TouchEventName::TouchMove,
551            location: location.into(),
552            finger_id: 0,
553            phase: TouchPhase::Moved,
554            force: None,
555        });
556        self.sync_and_update();
557    }
558
559    pub fn release_touch(&mut self, location: impl Into<CursorPoint>) {
560        self.send_event(PlatformEvent::Touch {
561            name: TouchEventName::TouchEnd,
562            location: location.into(),
563            finger_id: 0,
564            phase: TouchPhase::Ended,
565            force: None,
566        });
567        self.sync_and_update();
568    }
569
570    pub fn scroll(&mut self, cursor: impl Into<CursorPoint>, scroll: impl Into<CursorPoint>) {
571        let cursor = cursor.into();
572        let scroll = scroll.into();
573        self.send_event(PlatformEvent::Wheel {
574            name: WheelEventName::Wheel,
575            scroll,
576            cursor,
577            source: WheelSource::Custom,
578            phase: TouchPhase::Moved,
579        });
580        self.sync_and_update();
581        // Refresh hover states after the scroll
582        self.send_event(PlatformEvent::Mouse {
583            name: MouseEventName::MouseMove,
584            cursor,
585            button: None,
586        });
587        self.sync_and_update();
588    }
589
590    pub fn animation_clock(&mut self) -> &mut AnimationClock {
591        &mut self.animation_clock
592    }
593
594    /// Render into a persistent surface without encoding an image.
595    pub fn render_to_surface(&mut self) {
596        let surface = self.surface.get_or_insert_with(|| {
597            raster_n32_premul((self.size.width as i32, self.size.height as i32))
598                .expect("Failed to create the surface.")
599        });
600
601        let render_pipeline = RenderPipeline {
602            font_collection: &mut self.font_collection,
603            font_manager: &self.font_manager,
604            tree: &self.tree.borrow(),
605            canvas: surface.canvas(),
606            scale_factor: self.scale_factor,
607            background: Color::WHITE,
608        };
609        render_pipeline.render();
610    }
611
612    pub fn render(&mut self) -> SkData {
613        self.render_to_surface();
614        let surface = self.surface.as_mut().expect("Surface was initialized.");
615        let image = surface.image_snapshot();
616        let mut context = surface.direct_context();
617        image
618            .encode(context.as_mut(), EncodedImageFormat::PNG, None)
619            .expect("Failed to encode the snapshot.")
620    }
621
622    pub fn render_to_file(&mut self, path: impl Into<PathBuf>) {
623        let path = path.into();
624
625        let image = self.render();
626
627        let mut snapshot_file = File::create(path).expect("Failed to create the snapshot file.");
628
629        snapshot_file
630            .write_all(&image)
631            .expect("Failed to save the snapshot file.");
632    }
633
634    pub fn find<T>(
635        &self,
636        matcher: impl Fn(TestingNode, &dyn ElementExt) -> Option<T>,
637    ) -> Option<T> {
638        let mut matched = None;
639        {
640            let tree = self.tree.borrow();
641            tree.traverse_depth(|id| {
642                if matched.is_some() {
643                    return;
644                }
645                let element = tree.elements.get(&id).unwrap();
646                let node = TestingNode {
647                    tree: self.tree.clone(),
648                    id,
649                };
650                matched = matcher(node, element.as_ref());
651            });
652        }
653
654        matched
655    }
656
657    pub fn find_many<T>(
658        &self,
659        matcher: impl Fn(TestingNode, &dyn ElementExt) -> Option<T>,
660    ) -> Vec<T> {
661        let mut matched = Vec::new();
662        {
663            let tree = self.tree.borrow();
664            tree.traverse_depth(|id| {
665                let element = tree.elements.get(&id).unwrap();
666                let node = TestingNode {
667                    tree: self.tree.clone(),
668                    id,
669                };
670                if let Some(result) = matcher(node, element.as_ref()) {
671                    matched.push(result);
672                }
673            });
674        }
675
676        matched
677    }
678}
679
680pub struct TestingNode {
681    tree: Rc<RefCell<Tree>>,
682    id: NodeId,
683}
684
685impl TestingNode {
686    pub fn layout(&self) -> LayoutNode {
687        self.tree.borrow().layout.get(&self.id).cloned().unwrap()
688    }
689
690    pub fn children(&self) -> Vec<Self> {
691        let children = self
692            .tree
693            .borrow()
694            .children
695            .get(&self.id)
696            .cloned()
697            .unwrap_or_default();
698
699        children
700            .into_iter()
701            .map(|child_id| Self {
702                id: child_id,
703                tree: self.tree.clone(),
704            })
705            .collect()
706    }
707
708    pub fn is_visible(&self) -> bool {
709        let layout = self.layout();
710        let effect_state = self
711            .tree
712            .borrow()
713            .effect_state
714            .get(&self.id)
715            .cloned()
716            .unwrap();
717
718        effect_state.is_visible(&self.tree.borrow().layout, &layout.area)
719    }
720
721    pub fn element(&self) -> Rc<dyn ElementExt> {
722        self.tree
723            .borrow()
724            .elements
725            .get(&self.id)
726            .cloned()
727            .expect("Element does not exist.")
728    }
729}