Skip to main content

sui_testing/
lib.rs

1#![forbid(unsafe_code)]
2
3mod app;
4mod diagnostics;
5mod expect;
6mod harness;
7mod locator;
8mod screenshot;
9mod selector;
10mod snapshot;
11mod window;
12
13pub use app::{IntoTestRuntime, TestApp, TestAppBuilder};
14pub use expect::Expectation;
15pub use locator::Locator;
16pub use screenshot::{
17    ArtifactBundle, Screenshot, hdr_clip_mask, hdr_headroom_heatmap, hdr_luminance_heatmap,
18    write_hdr_avif, write_hdr_exr,
19};
20pub use selector::Selector;
21pub use snapshot::{SceneSummary, WindowSnapshot};
22pub use window::TestWindow;
23
24pub mod prelude {
25    pub use crate::{
26        ArtifactBundle, Expectation, IntoTestRuntime, Locator, SceneSummary, Screenshot, Selector,
27        TestApp, TestAppBuilder, TestWindow, hdr_clip_mask, hdr_headroom_heatmap,
28        hdr_luminance_heatmap, write_hdr_avif, write_hdr_exr,
29    };
30}
31
32#[cfg(test)]
33mod tests {
34    use std::{
35        cell::RefCell,
36        fs,
37        path::PathBuf,
38        rc::Rc,
39        sync::{
40            Arc,
41            atomic::{AtomicBool, AtomicUsize, Ordering},
42        },
43        time::{Duration, SystemTime, UNIX_EPOCH},
44    };
45
46    use crate::TestApp;
47    use sui_core::{
48        Color, Event, ImeEvent, KeyState, PointerEventKind, Result, SemanticsAction, SemanticsNode,
49        SemanticsRole, SemanticsValue, Size, TimerToken, Vector, WakeEvent, WindowEvent,
50    };
51    use sui_layout::Constraints;
52    use sui_runtime::{
53        Application, ArrangeCtx, EventCtx, MeasureCtx, PaintCtx, SemanticsCtx, SingleChild, Widget,
54        WidgetChildren, WidgetPodVisitor, WindowBuilder,
55    };
56    use sui_scene::StrokeStyle;
57
58    #[derive(Debug, Default)]
59    struct AppState {
60        button_hovered: bool,
61        button_clicks: usize,
62        save_timer: Option<TimerToken>,
63        status: String,
64        input_value: String,
65    }
66
67    struct HarnessRoot {
68        children: WidgetChildren,
69    }
70
71    impl HarnessRoot {
72        fn new(state: Rc<RefCell<AppState>>) -> Self {
73            let mut children = WidgetChildren::new();
74            children.push(StatusButton::new(Rc::clone(&state)));
75            children.push(TestInput::new(state));
76            Self { children }
77        }
78    }
79
80    impl Widget for HarnessRoot {
81        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
82            let viewport = constraints.clamp(Size::new(480.0, 240.0));
83            let child_constraints = Constraints::tight(Size::new(180.0, 44.0));
84            self.children.measure_child(0, ctx, child_constraints);
85            self.children.measure_child(1, ctx, child_constraints);
86            viewport
87        }
88
89        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: sui_core::Rect) {
90            self.children.arrange_child(
91                0,
92                ctx,
93                sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 24.0, 180.0, 44.0),
94            );
95            self.children.arrange_child(
96                1,
97                ctx,
98                sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 92.0, 180.0, 44.0),
99            );
100        }
101
102        fn paint(&self, ctx: &mut PaintCtx) {
103            ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
104            self.children.paint(ctx);
105        }
106
107        fn semantics(&self, ctx: &mut SemanticsCtx) {
108            let mut root = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Window, ctx.bounds());
109            root.name = Some("Harness Window".to_string());
110            ctx.push(root);
111            self.children.semantics(ctx);
112        }
113
114        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
115            self.children.visit_children(visitor);
116        }
117
118        fn visit_children_mut(&mut self, visitor: &mut dyn sui_runtime::WidgetPodMutVisitor) {
119            self.children.visit_children_mut(visitor);
120        }
121    }
122
123    struct StatusButton {
124        state: Rc<RefCell<AppState>>,
125    }
126
127    impl StatusButton {
128        fn new(state: Rc<RefCell<AppState>>) -> Self {
129            Self { state }
130        }
131    }
132
133    impl Widget for StatusButton {
134        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
135            match event {
136                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
137                    let hovered = ctx.bounds().contains(pointer.position);
138                    let mut state = self.state.borrow_mut();
139                    if state.button_hovered != hovered {
140                        state.button_hovered = hovered;
141                        ctx.request_paint();
142                        ctx.request_semantics();
143                    }
144                }
145                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
146                    let mut state = self.state.borrow_mut();
147                    state.button_clicks += 1;
148                    state.status = "Saving".to_string();
149                    state.save_timer = Some(ctx.schedule_timer_after(2.0));
150                    ctx.request_focus();
151                    ctx.request_paint();
152                    ctx.request_semantics();
153                    ctx.set_handled();
154                }
155                Event::Keyboard(key)
156                    if key.state == KeyState::Pressed
157                        && ctx.is_focused()
158                        && matches!(key.key.as_str(), "Enter" | " ") =>
159                {
160                    let mut state = self.state.borrow_mut();
161                    state.status = "Activated".to_string();
162                    state.save_timer = None;
163                    ctx.request_paint();
164                    ctx.request_semantics();
165                    ctx.set_handled();
166                }
167                Event::Wake(WakeEvent::Timer { token, .. }) => {
168                    let mut state = self.state.borrow_mut();
169                    if state.save_timer == Some(*token) {
170                        state.status = "Saved".to_string();
171                        state.save_timer = None;
172                        ctx.request_paint();
173                        ctx.request_semantics();
174                        ctx.set_handled();
175                    }
176                }
177                _ => {}
178            }
179        }
180
181        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
182            constraints.clamp(Size::new(180.0, 44.0))
183        }
184
185        fn paint(&self, ctx: &mut PaintCtx) {
186            let state = self.state.borrow();
187            let color = if ctx.is_focused() {
188                Color::rgba(0.25, 0.52, 0.88, 1.0)
189            } else if state.button_hovered {
190                Color::rgba(0.21, 0.38, 0.66, 1.0)
191            } else {
192                Color::rgba(0.17, 0.24, 0.37, 1.0)
193            };
194            ctx.fill_bounds(color);
195            ctx.label(
196                ctx.bounds(),
197                format!("Save ({})", state.button_clicks),
198                Color::rgba(0.95, 0.96, 0.98, 1.0),
199            );
200        }
201
202        fn semantics(&self, ctx: &mut SemanticsCtx) {
203            let state = self.state.borrow();
204            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
205            node.name = Some("Save".to_string());
206            node.description = Some(state.status.clone());
207            node.state.hovered = state.button_hovered;
208            node.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
209            ctx.push(node);
210
211            let mut status = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
212            status.parent = Some(ctx.root_widget_id());
213            status.name = Some(state.status.clone());
214            ctx.push(status);
215        }
216
217        fn accepts_focus(&self) -> bool {
218            true
219        }
220
221        fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
222            ctx.request_paint();
223            ctx.request_semantics();
224        }
225    }
226
227    struct TestInput {
228        state: Rc<RefCell<AppState>>,
229    }
230
231    impl TestInput {
232        fn new(state: Rc<RefCell<AppState>>) -> Self {
233            Self { state }
234        }
235    }
236
237    impl Widget for TestInput {
238        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
239            match event {
240                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
241                    ctx.request_focus();
242                    ctx.request_paint();
243                    ctx.request_semantics();
244                    ctx.set_handled();
245                }
246                Event::Ime(ImeEvent::CompositionCommit { text }) if ctx.is_focused() => {
247                    self.state.borrow_mut().input_value = text.clone();
248                    ctx.request_paint();
249                    ctx.request_semantics();
250                    ctx.set_handled();
251                }
252                _ => {}
253            }
254        }
255
256        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
257            constraints.clamp(Size::new(180.0, 44.0))
258        }
259
260        fn paint(&self, ctx: &mut PaintCtx) {
261            let border = if ctx.is_focused() {
262                Color::rgba(0.66, 0.74, 0.93, 1.0)
263            } else {
264                Color::rgba(0.38, 0.43, 0.52, 1.0)
265            };
266            ctx.fill_bounds(Color::rgba(0.13, 0.15, 0.20, 1.0));
267            ctx.stroke_rect(ctx.bounds(), border, StrokeStyle::new(1.0));
268            ctx.label(
269                ctx.bounds(),
270                self.state.borrow().input_value.clone(),
271                Color::rgba(0.95, 0.96, 0.98, 1.0),
272            );
273        }
274
275        fn semantics(&self, ctx: &mut SemanticsCtx) {
276            let mut node =
277                SemanticsNode::new(ctx.widget_id(), SemanticsRole::TextInput, ctx.bounds());
278            node.name = Some("Name".to_string());
279            node.value = Some(SemanticsValue::Text(
280                self.state.borrow().input_value.clone(),
281            ));
282            node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
283            ctx.push(node);
284        }
285
286        fn accepts_focus(&self) -> bool {
287            true
288        }
289
290        fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
291            ctx.request_paint();
292            ctx.request_semantics();
293        }
294    }
295
296    fn build_app() -> Result<TestApp> {
297        TestApp::new(|| {
298            let state = Rc::new(RefCell::new(AppState::default()));
299            Application::new().window(
300                WindowBuilder::new()
301                    .title("Harness")
302                    .root(HarnessRoot::new(state)),
303            )
304        })
305    }
306
307    #[derive(Debug, Default)]
308    struct ListState {
309        selected: String,
310    }
311
312    struct ListRoot {
313        state: Rc<RefCell<ListState>>,
314        children: WidgetChildren,
315    }
316
317    impl ListRoot {
318        fn new(state: Rc<RefCell<ListState>>) -> Self {
319            let mut children = WidgetChildren::new();
320            children.push(StatusLabel::new(Rc::clone(&state)));
321            children.push(ContactRow::new(
322                "Ada",
323                sui_core::Point::new(320.0, 6.0),
324                Rc::clone(&state),
325            ));
326            children.push(ContactRow::new(
327                "Grace",
328                sui_core::Point::new(320.0, 6.0),
329                Rc::clone(&state),
330            ));
331            Self { state, children }
332        }
333    }
334
335    impl Widget for ListRoot {
336        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
337            let viewport = constraints.clamp(Size::new(480.0, 260.0));
338            let width = viewport.width - 48.0;
339
340            self.children
341                .measure_child(0, ctx, Constraints::tight(Size::new(width, 32.0)));
342            self.children
343                .measure_child(1, ctx, Constraints::tight(Size::new(width, 44.0)));
344            self.children
345                .measure_child(2, ctx, Constraints::tight(Size::new(width, 44.0)));
346
347            viewport
348        }
349
350        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: sui_core::Rect) {
351            let width = bounds.width() - 48.0;
352            self.children.arrange_child(
353                0,
354                ctx,
355                sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 20.0, width, 32.0),
356            );
357            self.children.arrange_child(
358                1,
359                ctx,
360                sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 72.0, width, 44.0),
361            );
362            self.children.arrange_child(
363                2,
364                ctx,
365                sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 128.0, width, 44.0),
366            );
367        }
368
369        fn paint(&self, ctx: &mut PaintCtx) {
370            let _ = &self.state;
371            ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
372            self.children.paint(ctx);
373        }
374
375        fn semantics(&self, ctx: &mut SemanticsCtx) {
376            let mut root = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Window, ctx.bounds());
377            root.name = Some("List Harness Window".to_string());
378            ctx.push(root);
379            self.children.semantics(ctx);
380        }
381
382        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
383            self.children.visit_children(visitor);
384        }
385
386        fn visit_children_mut(&mut self, visitor: &mut dyn sui_runtime::WidgetPodMutVisitor) {
387            self.children.visit_children_mut(visitor);
388        }
389    }
390
391    struct StatusLabel {
392        state: Rc<RefCell<ListState>>,
393    }
394
395    impl StatusLabel {
396        fn new(state: Rc<RefCell<ListState>>) -> Self {
397            Self { state }
398        }
399    }
400
401    impl Widget for StatusLabel {
402        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
403            constraints.clamp(Size::new(320.0, 32.0))
404        }
405
406        fn paint(&self, ctx: &mut PaintCtx) {
407            ctx.label(
408                ctx.bounds(),
409                format!("Selected: {}", self.state.borrow().selected),
410                Color::rgba(0.95, 0.96, 0.98, 1.0),
411            );
412        }
413
414        fn semantics(&self, ctx: &mut SemanticsCtx) {
415            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
416            node.name = Some(format!("Selected: {}", self.state.borrow().selected));
417            ctx.push(node);
418        }
419    }
420
421    struct ContactRow {
422        name: String,
423        button_origin: sui_core::Point,
424        children: WidgetChildren,
425    }
426
427    impl ContactRow {
428        fn new(name: &str, button_origin: sui_core::Point, state: Rc<RefCell<ListState>>) -> Self {
429            let mut children = WidgetChildren::new();
430            children.push(RowButton::new(name.to_string(), state));
431            Self {
432                name: name.to_string(),
433                button_origin,
434                children,
435            }
436        }
437    }
438
439    impl Widget for ContactRow {
440        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
441            let size = constraints.clamp(Size::new(360.0, 44.0));
442            self.children
443                .measure_child(0, ctx, Constraints::tight(Size::new(120.0, 32.0)));
444            size
445        }
446
447        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: sui_core::Rect) {
448            self.children.arrange_child(
449                0,
450                ctx,
451                sui_core::Rect::new(
452                    bounds.x() + self.button_origin.x,
453                    bounds.y() + self.button_origin.y,
454                    120.0,
455                    32.0,
456                ),
457            );
458        }
459
460        fn paint(&self, ctx: &mut PaintCtx) {
461            ctx.fill_bounds(Color::rgba(0.13, 0.15, 0.20, 1.0));
462            ctx.label(
463                sui_core::Rect::new(ctx.bounds().x() + 12.0, ctx.bounds().y() + 8.0, 140.0, 24.0),
464                &self.name,
465                Color::rgba(0.95, 0.96, 0.98, 1.0),
466            );
467            self.children.paint(ctx);
468        }
469
470        fn semantics(&self, ctx: &mut SemanticsCtx) {
471            let mut node = SemanticsNode::new(
472                ctx.widget_id(),
473                SemanticsRole::GenericContainer,
474                ctx.bounds(),
475            );
476            node.description = Some(self.name.clone());
477            ctx.push(node);
478            self.children.semantics(ctx);
479        }
480
481        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
482            self.children.visit_children(visitor);
483        }
484
485        fn visit_children_mut(&mut self, visitor: &mut dyn sui_runtime::WidgetPodMutVisitor) {
486            self.children.visit_children_mut(visitor);
487        }
488    }
489
490    struct RowButton {
491        label: String,
492        state: Rc<RefCell<ListState>>,
493    }
494
495    impl RowButton {
496        fn new(label: String, state: Rc<RefCell<ListState>>) -> Self {
497            Self { label, state }
498        }
499    }
500
501    impl Widget for RowButton {
502        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
503            match event {
504                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
505                    self.state.borrow_mut().selected = self.label.clone();
506                    ctx.request_focus();
507                    ctx.request_paint();
508                    ctx.request_semantics();
509                    ctx.set_handled();
510                }
511                _ => {}
512            }
513        }
514
515        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
516            constraints.clamp(Size::new(120.0, 32.0))
517        }
518
519        fn paint(&self, ctx: &mut PaintCtx) {
520            let color = if ctx.is_focused() {
521                Color::rgba(0.25, 0.52, 0.88, 1.0)
522            } else {
523                Color::rgba(0.17, 0.24, 0.37, 1.0)
524            };
525            ctx.fill_bounds(color);
526            ctx.label(ctx.bounds(), "Select", Color::rgba(0.95, 0.96, 0.98, 1.0));
527        }
528
529        fn semantics(&self, ctx: &mut SemanticsCtx) {
530            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
531            node.name = Some("Select".to_string());
532            node.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
533            ctx.push(node);
534        }
535
536        fn accepts_focus(&self) -> bool {
537            true
538        }
539
540        fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
541            ctx.request_paint();
542            ctx.request_semantics();
543        }
544    }
545
546    fn build_list_app() -> Result<TestApp> {
547        TestApp::new(|| {
548            let state = Rc::new(RefCell::new(ListState::default()));
549            Application::new().window(
550                WindowBuilder::new()
551                    .title("List Harness")
552                    .root(ListRoot::new(state)),
553            )
554        })
555    }
556
557    struct ScrollHarness {
558        offset_y: f32,
559        child: SingleChild,
560    }
561
562    impl ScrollHarness {
563        fn new() -> Self {
564            Self {
565                offset_y: 0.0,
566                child: SingleChild::new(ScrollContent),
567            }
568        }
569    }
570
571    impl Widget for ScrollHarness {
572        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
573            match event {
574                Event::Pointer(pointer)
575                    if pointer.kind == PointerEventKind::Scroll
576                        && ctx.bounds().contains(pointer.position) =>
577                {
578                    let delta = pointer
579                        .scroll_delta
580                        .map(|delta| match delta {
581                            sui_core::ScrollDelta::Lines(delta) => {
582                                Vector::new(delta.x * 40.0, delta.y * 40.0)
583                            }
584                            sui_core::ScrollDelta::Pixels(delta) => delta,
585                        })
586                        .unwrap_or(pointer.delta);
587                    let next = (self.offset_y - delta.y).clamp(0.0, 120.0);
588                    if (next - self.offset_y).abs() > f32::EPSILON {
589                        self.offset_y = next;
590                        ctx.request_arrange();
591                        ctx.request_paint();
592                        ctx.request_semantics();
593                        ctx.set_handled();
594                    }
595                }
596                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
597                    ctx.request_focus();
598                    ctx.request_semantics();
599                }
600                _ => {}
601            }
602        }
603
604        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
605            let viewport = constraints.clamp(Size::new(160.0, 80.0));
606            self.child
607                .measure(ctx, Constraints::tight(Size::new(160.0, 200.0)));
608            viewport
609        }
610
611        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: sui_core::Rect) {
612            self.child.arrange(
613                ctx,
614                sui_core::Rect::new(bounds.x(), bounds.y() - self.offset_y, 160.0, 200.0),
615            );
616        }
617
618        fn paint(&self, ctx: &mut PaintCtx) {
619            ctx.clear(Color::rgba(0.05, 0.06, 0.08, 1.0));
620            ctx.push_clip_rect(ctx.bounds());
621            self.child.paint(ctx);
622            ctx.pop_clip();
623        }
624
625        fn semantics(&self, ctx: &mut SemanticsCtx) {
626            let mut node =
627                SemanticsNode::new(ctx.widget_id(), SemanticsRole::ScrollView, ctx.bounds());
628            node.name = Some("Scroll Harness".to_string());
629            node.actions = vec![SemanticsAction::Focus];
630            node.state.focused = ctx.is_focused();
631            ctx.push(node);
632            self.child.semantics(ctx);
633        }
634
635        fn accepts_focus(&self) -> bool {
636            true
637        }
638
639        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
640            self.child.visit_children(visitor);
641        }
642
643        fn visit_children_mut(&mut self, visitor: &mut dyn sui_runtime::WidgetPodMutVisitor) {
644            self.child.visit_children_mut(visitor);
645        }
646    }
647
648    struct ScrollContent;
649
650    impl Widget for ScrollContent {
651        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
652            constraints.clamp(Size::new(160.0, 200.0))
653        }
654
655        fn paint(&self, ctx: &mut PaintCtx) {
656            ctx.fill_rect(
657                sui_core::Rect::new(ctx.bounds().x(), ctx.bounds().y(), 160.0, 100.0),
658                Color::rgba(0.18, 0.32, 0.68, 1.0),
659            );
660            ctx.fill_rect(
661                sui_core::Rect::new(ctx.bounds().x(), ctx.bounds().y() + 100.0, 160.0, 100.0),
662                Color::rgba(0.78, 0.32, 0.18, 1.0),
663            );
664        }
665
666        fn semantics(&self, ctx: &mut SemanticsCtx) {
667            let mut node = SemanticsNode::new(
668                ctx.widget_id(),
669                SemanticsRole::GenericContainer,
670                ctx.bounds(),
671            );
672            node.name = Some("Scroll Content".to_string());
673            ctx.push(node);
674        }
675    }
676
677    #[derive(Default)]
678    struct NonIdleWidget {
679        timer: Option<TimerToken>,
680    }
681
682    impl Widget for NonIdleWidget {
683        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
684            match event {
685                Event::Window(WindowEvent::RedrawRequested) if self.timer.is_none() => {
686                    self.timer = Some(ctx.schedule_timer_after(0.0));
687                }
688                Event::Wake(WakeEvent::Timer { token, .. }) if self.timer == Some(*token) => {
689                    self.timer = Some(ctx.schedule_timer_after(0.0));
690                    ctx.request_paint();
691                    ctx.set_handled();
692                }
693                _ => {}
694            }
695        }
696
697        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
698            constraints.clamp(Size::new(48.0, 48.0))
699        }
700
701        fn paint(&self, ctx: &mut PaintCtx) {
702            ctx.fill_rect(ctx.bounds(), Color::rgba(0.8, 0.2, 0.2, 1.0));
703        }
704
705        fn semantics(&self, ctx: &mut SemanticsCtx) {
706            let mut node = SemanticsNode::new(
707                ctx.widget_id(),
708                SemanticsRole::GenericContainer,
709                ctx.bounds(),
710            );
711            node.name = Some("Non-idle".to_string());
712            ctx.push(node);
713        }
714    }
715
716    #[derive(Default)]
717    struct SlowAnimationState {
718        active: AtomicBool,
719        frames: AtomicUsize,
720    }
721
722    struct SlowAnimatingButton {
723        state: Arc<SlowAnimationState>,
724    }
725
726    impl Widget for SlowAnimatingButton {
727        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
728            match event {
729                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
730                    let active = !self.state.active.load(Ordering::Acquire);
731                    self.state.active.store(active, Ordering::Release);
732                    ctx.request_paint();
733                    if active {
734                        ctx.request_animation_frame();
735                    }
736                    ctx.set_handled();
737                }
738                Event::Wake(WakeEvent::AnimationFrame { .. })
739                    if self.state.active.load(Ordering::Acquire) =>
740                {
741                    self.state.frames.fetch_add(1, Ordering::AcqRel);
742                    ctx.request_paint();
743                    ctx.request_animation_frame();
744                    ctx.set_handled();
745                }
746                _ => {}
747            }
748        }
749
750        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
751            constraints.clamp(Size::new(240.0, 120.0))
752        }
753
754        fn paint(&self, ctx: &mut PaintCtx) {
755            if self.state.active.load(Ordering::Acquire) {
756                // Deliberately cross the runtime's animation-frame interval.
757                // A synchronous live flush must not treat render wall time as
758                // permission to advance another logical animation frame.
759                std::thread::sleep(Duration::from_millis(20));
760            }
761            ctx.fill_rect(ctx.bounds(), Color::rgba(0.18, 0.32, 0.68, 1.0));
762        }
763
764        fn semantics(&self, ctx: &mut SemanticsCtx) {
765            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
766            node.name = Some("Toggle slow animation".to_string());
767            node.actions = vec![SemanticsAction::Activate];
768            ctx.push(node);
769        }
770    }
771
772    fn build_scroll_app() -> Result<TestApp> {
773        TestApp::new(|| {
774            Application::new().window(
775                WindowBuilder::new()
776                    .title("Scroll Harness")
777                    .root(ScrollHarness::new()),
778            )
779        })
780    }
781
782    fn build_non_idle_app() -> Result<TestApp> {
783        let runtime = Application::new()
784            .window(
785                WindowBuilder::new()
786                    .title("Non-idle Harness")
787                    .root(NonIdleWidget::default()),
788            )
789            .build()?;
790        TestApp::from_runtime_with_frame_budget(runtime, 2)
791    }
792
793    #[test]
794    fn unbounded_timeouts_wait_and_bad_ones_are_refused() -> Result<()> {
795        let app = build_switch_app()?;
796        let window = app.main_window()?;
797
798        // An infinite timeout means no deadline, rather than a panic.
799        app.set_default_timeout(f64::INFINITY)?;
800        window.run_until_idle()?;
801        window
802            .get_by_role(SemanticsRole::Switch)
803            .with_name("Wi-Fi")
804            .expect()
805            .with_timeout(f64::INFINITY)
806            .to_be_visible()?;
807        app.set_default_timeout(5.0)?;
808
809        // Values that mean nothing are errors, not panics or endless loops.
810        assert!(app.set_default_timeout(f64::NAN).is_err());
811        assert!(app.advance_time(f64::NAN).is_err());
812        assert!(app.advance_time(f64::INFINITY).is_err());
813        assert!(app.record_motion(f64::INFINITY, 0.1, || Ok(())).is_err());
814        Ok(())
815    }
816
817    fn build_switch_app() -> Result<TestApp> {
818        TestApp::new(|| {
819            sui::Application::new().window(sui::WindowBuilder::new().title("Motion").root(
820                sui::containers::Padding::all(24.0, sui::Switch::new("Wi-Fi")),
821            ))
822        })
823    }
824
825    #[test]
826    fn settle_animations_runs_slowed_transitions_to_completion() -> Result<()> {
827        let app = build_switch_app()?;
828        app.set_motion_time_scale(0.1)?;
829        let window = app.main_window()?;
830
831        window
832            .get_by_role(SemanticsRole::Switch)
833            .with_name("Wi-Fi")
834            .click()?;
835        assert!(app.has_running_animations()?);
836        let elapsed = app.settle_animations()?;
837
838        // The 140 ms toggle token runs ten times slower.
839        assert!(elapsed > 0.5, "settled after {elapsed} s");
840        assert!(!app.has_running_animations()?);
841        Ok(())
842    }
843
844    #[test]
845    fn motion_off_finishes_transitions_immediately() -> Result<()> {
846        let app = build_switch_app()?;
847        app.set_motion_preference(Some(sui_core::MotionPreference::Off))?;
848        let window = app.main_window()?;
849
850        window
851            .get_by_role(SemanticsRole::Switch)
852            .with_name("Wi-Fi")
853            .click()?;
854
855        assert!(!app.has_running_animations()?);
856        assert_eq!(app.settle_animations()?, 0.0);
857        Ok(())
858    }
859
860    #[test]
861    fn record_motion_samples_at_each_step() -> Result<()> {
862        let app = build_switch_app()?;
863        let mut calls = 0;
864
865        let samples = app.record_motion(0.1, 0.025, || {
866            calls += 1;
867            Ok(calls)
868        })?;
869
870        let times: Vec<f64> = samples.iter().map(|(time, _)| *time).collect();
871        assert_eq!(times.len(), 5);
872        assert!((times[4] - 0.1).abs() < 1e-9);
873        assert_eq!(samples[4].1, 5);
874        assert!(app.record_motion(0.1, 0.0, || Ok(())).is_err());
875        Ok(())
876    }
877
878    #[test]
879    fn locators_actions_and_focus_work_end_to_end() -> Result<()> {
880        let app = build_app()?;
881        let window = app.main_window()?;
882        let save = window.get_by_role(SemanticsRole::Button).with_name("Save");
883
884        save.expect().to_be_visible()?;
885        save.hover()?;
886        save.click()?;
887        save.expect().to_be_focused()?;
888        save.press("Enter")?;
889
890        let focused = window.focused().with_name("Save");
891        focused.expect().to_have_count(1)?;
892        window.get_by_text("Activated").expect().to_be_visible()?;
893
894        Ok(())
895    }
896
897    #[test]
898    fn fill_and_virtual_time_waiting_work() -> Result<()> {
899        let app = build_app()?;
900        let window = app.main_window()?;
901
902        window
903            .get_by_role(SemanticsRole::TextInput)
904            .with_name("Name")
905            .fill("Ada")?;
906        window
907            .get_by_role(SemanticsRole::TextInput)
908            .with_name("Name")
909            .expect()
910            .to_have_value("Ada")?;
911
912        window
913            .get_by_role(SemanticsRole::Button)
914            .with_name("Save")
915            .click()?;
916        window.get_by_text("Saved").expect().to_be_visible()?;
917
918        Ok(())
919    }
920
921    #[test]
922    fn locator_scroll_updates_child_layout_and_screenshot() -> Result<()> {
923        let app = build_scroll_app()?;
924        let window = app.main_window()?;
925        let scroll = window
926            .get_by_role(SemanticsRole::ScrollView)
927            .with_name("Scroll Harness");
928
929        let before = scroll.capture_screenshot()?;
930        let before_snapshot = window.snapshot()?;
931        let before_child = before_snapshot
932            .widget_graph
933            .nodes
934            .iter()
935            .find(|node| node.bounds.width() == 160.0 && node.bounds.height() == 200.0)
936            .expect("scroll content node present");
937
938        scroll.scroll_pixels(Vector::new(0.0, -80.0))?;
939
940        let after = scroll.capture_screenshot()?;
941        let after_snapshot = window.snapshot()?;
942        let after_child = after_snapshot
943            .widget_graph
944            .nodes
945            .iter()
946            .find(|node| node.bounds.width() == 160.0 && node.bounds.height() == 200.0)
947            .expect("scroll content node present after scroll");
948
949        assert_ne!(before, after);
950        assert!(after_child.bounds.y() < before_child.bounds.y());
951
952        Ok(())
953    }
954
955    #[test]
956    fn failures_include_semantics_and_graph_diagnostics() {
957        let app = build_app().unwrap();
958        let window = app.main_window().unwrap();
959        let error = window
960            .get_by_text("missing")
961            .expect()
962            .with_timeout(0.0)
963            .to_be_visible()
964            .unwrap_err();
965
966        assert!(error.message().contains("selector: text=\"missing\""));
967        assert!(error.message().contains("Semantics snapshot:"));
968        assert!(error.message().contains("Widget graph:"));
969    }
970
971    #[test]
972    fn run_until_idle_times_out_when_headless_work_never_settles() -> Result<()> {
973        let app = build_non_idle_app()?;
974        app.set_default_timeout(0.01)?;
975        let window = app.main_window()?;
976
977        let error = window.run_until_idle().unwrap_err();
978        assert!(
979            error
980                .message()
981                .contains("headless harness idle did not complete within"),
982            "{error}"
983        );
984
985        Ok(())
986    }
987
988    #[test]
989    fn synchronous_live_dispatch_does_not_chase_slow_perpetual_animation() -> Result<()> {
990        let state = Arc::new(SlowAnimationState::default());
991        let widget_state = Arc::clone(&state);
992        let app = TestApp::new(move || {
993            Application::new().window(WindowBuilder::new().title("Slow Animation Harness").root(
994                SlowAnimatingButton {
995                    state: widget_state,
996                },
997            ))
998        })?;
999        let window = app.main_window()?;
1000        let toggle = window
1001            .get_by_role(SemanticsRole::Button)
1002            .with_name("Toggle slow animation");
1003
1004        toggle.click()?;
1005        assert!(state.frames.load(Ordering::Acquire) > 0);
1006
1007        // Stop the repeating animation before releasing the shared live
1008        // harness service to another test.
1009        toggle.click()?;
1010        Ok(())
1011    }
1012
1013    #[test]
1014    fn scoped_descendant_locators_target_repeated_widgets() -> Result<()> {
1015        let app = build_list_app()?;
1016        let window = app.main_window()?;
1017
1018        window
1019            .get_by_role(SemanticsRole::Button)
1020            .with_name("Select")
1021            .expect()
1022            .to_have_count(2)?;
1023
1024        let grace_row = window
1025            .get_by_role(SemanticsRole::GenericContainer)
1026            .with_description("Grace");
1027
1028        grace_row
1029            .get_by_role(SemanticsRole::Button)
1030            .with_name("Select")
1031            .click()?;
1032
1033        window
1034            .get_by_text("Selected: Grace")
1035            .expect()
1036            .to_be_visible()?;
1037
1038        Ok(())
1039    }
1040
1041    #[test]
1042    fn screenshot_capture_and_artifact_bundles_work() -> Result<()> {
1043        let app = build_app()?;
1044        let window = app.main_window()?;
1045
1046        let screenshot = window.capture_screenshot()?;
1047        assert!(screenshot.width() > 0);
1048        assert!(screenshot.height() > 0);
1049
1050        let artifacts = window.capture_artifacts()?;
1051        assert!(artifacts.screenshot.is_some());
1052        assert!(artifacts.semantics_overlay.is_some());
1053        assert!(artifacts.widget_overlay.is_some());
1054        assert!(artifacts.snapshot.scene_summary.is_some());
1055
1056        let dir = unique_temp_path("artifacts");
1057        artifacts.write_to_dir(&dir)?;
1058
1059        assert!(dir.join("summary.txt").exists());
1060        assert!(dir.join("semantics.txt").exists());
1061        assert!(dir.join("widget-graph.txt").exists());
1062        assert!(dir.join("scene.txt").exists());
1063        assert!(dir.join("screenshot.png").exists());
1064        assert!(dir.join("semantics-overlay.png").exists());
1065        assert!(dir.join("widget-overlay.png").exists());
1066
1067        Ok(())
1068    }
1069
1070    #[test]
1071    fn screenshot_expectations_compare_against_png_baselines() -> Result<()> {
1072        let app = build_app()?;
1073        let window = app.main_window()?;
1074        let save = window.get_by_role(SemanticsRole::Button).with_name("Save");
1075        let baseline = unique_temp_path("save-button.png");
1076
1077        save.capture_screenshot()?.write_png(&baseline)?;
1078        save.expect().to_match_screenshot(&baseline)?;
1079
1080        save.click()?;
1081
1082        let error = save
1083            .expect()
1084            .with_timeout(0.0)
1085            .to_match_screenshot(&baseline)
1086            .unwrap_err();
1087        let actual = baseline.with_file_name("save-button.actual.png");
1088        let diff = baseline.with_file_name("save-button.diff.png");
1089
1090        assert!(actual.exists());
1091        assert!(diff.exists());
1092        assert!(error.message().contains("screenshot assertion failed"));
1093
1094        Ok(())
1095    }
1096
1097    fn unique_temp_path(name: &str) -> PathBuf {
1098        let nonce = SystemTime::now()
1099            .duration_since(UNIX_EPOCH)
1100            .expect("system time is after unix epoch")
1101            .as_nanos();
1102        let dir =
1103            std::env::temp_dir().join(format!("sui-testing-{}-{}", std::process::id(), nonce));
1104        fs::create_dir_all(&dir).expect("temporary screenshot directory created");
1105        dir.join(name)
1106    }
1107}