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