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};
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, TestWindow, hdr_clip_mask, hdr_headroom_heatmap, hdr_luminance_heatmap,
28        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 locators_actions_and_focus_work_end_to_end() -> Result<()> {
795        let app = build_app()?;
796        let window = app.main_window()?;
797        let save = window.get_by_role(SemanticsRole::Button).with_name("Save");
798
799        save.expect().to_be_visible()?;
800        save.hover()?;
801        save.click()?;
802        save.expect().to_be_focused()?;
803        save.press("Enter")?;
804
805        let focused = window.focused().with_name("Save");
806        focused.expect().to_have_count(1)?;
807        window.get_by_text("Activated").expect().to_be_visible()?;
808
809        Ok(())
810    }
811
812    #[test]
813    fn fill_and_virtual_time_waiting_work() -> Result<()> {
814        let app = build_app()?;
815        let window = app.main_window()?;
816
817        window
818            .get_by_role(SemanticsRole::TextInput)
819            .with_name("Name")
820            .fill("Ada")?;
821        window
822            .get_by_role(SemanticsRole::TextInput)
823            .with_name("Name")
824            .expect()
825            .to_have_value("Ada")?;
826
827        window
828            .get_by_role(SemanticsRole::Button)
829            .with_name("Save")
830            .click()?;
831        window.get_by_text("Saved").expect().to_be_visible()?;
832
833        Ok(())
834    }
835
836    #[test]
837    fn locator_scroll_updates_child_layout_and_screenshot() -> Result<()> {
838        let app = build_scroll_app()?;
839        let window = app.main_window()?;
840        let scroll = window
841            .get_by_role(SemanticsRole::ScrollView)
842            .with_name("Scroll Harness");
843
844        let before = scroll.capture_screenshot()?;
845        let before_snapshot = window.snapshot()?;
846        let before_child = before_snapshot
847            .widget_graph
848            .nodes
849            .iter()
850            .find(|node| node.bounds.width() == 160.0 && node.bounds.height() == 200.0)
851            .expect("scroll content node present");
852
853        scroll.scroll_pixels(Vector::new(0.0, -80.0))?;
854
855        let after = scroll.capture_screenshot()?;
856        let after_snapshot = window.snapshot()?;
857        let after_child = after_snapshot
858            .widget_graph
859            .nodes
860            .iter()
861            .find(|node| node.bounds.width() == 160.0 && node.bounds.height() == 200.0)
862            .expect("scroll content node present after scroll");
863
864        assert_ne!(before, after);
865        assert!(after_child.bounds.y() < before_child.bounds.y());
866
867        Ok(())
868    }
869
870    #[test]
871    fn failures_include_semantics_and_graph_diagnostics() {
872        let app = build_app().unwrap();
873        let window = app.main_window().unwrap();
874        let error = window
875            .get_by_text("missing")
876            .expect()
877            .with_timeout(0.0)
878            .to_be_visible()
879            .unwrap_err();
880
881        assert!(error.message().contains("selector: text=\"missing\""));
882        assert!(error.message().contains("Semantics snapshot:"));
883        assert!(error.message().contains("Widget graph:"));
884    }
885
886    #[test]
887    fn run_until_idle_times_out_when_headless_work_never_settles() -> Result<()> {
888        let app = build_non_idle_app()?;
889        app.set_default_timeout(0.01)?;
890        let window = app.main_window()?;
891
892        let error = window.run_until_idle().unwrap_err();
893        assert!(
894            error
895                .message()
896                .contains("headless harness idle did not complete within"),
897            "{error}"
898        );
899
900        Ok(())
901    }
902
903    #[test]
904    fn synchronous_live_dispatch_does_not_chase_slow_perpetual_animation() -> Result<()> {
905        let state = Arc::new(SlowAnimationState::default());
906        let widget_state = Arc::clone(&state);
907        let app = TestApp::new(move || {
908            Application::new().window(WindowBuilder::new().title("Slow Animation Harness").root(
909                SlowAnimatingButton {
910                    state: widget_state,
911                },
912            ))
913        })?;
914        let window = app.main_window()?;
915        let toggle = window
916            .get_by_role(SemanticsRole::Button)
917            .with_name("Toggle slow animation");
918
919        toggle.click()?;
920        assert!(state.frames.load(Ordering::Acquire) > 0);
921
922        // Stop the repeating animation before releasing the shared live
923        // harness service to another test.
924        toggle.click()?;
925        Ok(())
926    }
927
928    #[test]
929    fn scoped_descendant_locators_target_repeated_widgets() -> Result<()> {
930        let app = build_list_app()?;
931        let window = app.main_window()?;
932
933        window
934            .get_by_role(SemanticsRole::Button)
935            .with_name("Select")
936            .expect()
937            .to_have_count(2)?;
938
939        let grace_row = window
940            .get_by_role(SemanticsRole::GenericContainer)
941            .with_description("Grace");
942
943        grace_row
944            .get_by_role(SemanticsRole::Button)
945            .with_name("Select")
946            .click()?;
947
948        window
949            .get_by_text("Selected: Grace")
950            .expect()
951            .to_be_visible()?;
952
953        Ok(())
954    }
955
956    #[test]
957    fn screenshot_capture_and_artifact_bundles_work() -> Result<()> {
958        let app = build_app()?;
959        let window = app.main_window()?;
960
961        let screenshot = window.capture_screenshot()?;
962        assert!(screenshot.width() > 0);
963        assert!(screenshot.height() > 0);
964
965        let artifacts = window.capture_artifacts()?;
966        assert!(artifacts.screenshot.is_some());
967        assert!(artifacts.semantics_overlay.is_some());
968        assert!(artifacts.widget_overlay.is_some());
969        assert!(artifacts.snapshot.scene_summary.is_some());
970
971        let dir = unique_temp_path("artifacts");
972        artifacts.write_to_dir(&dir)?;
973
974        assert!(dir.join("summary.txt").exists());
975        assert!(dir.join("semantics.txt").exists());
976        assert!(dir.join("widget-graph.txt").exists());
977        assert!(dir.join("scene.txt").exists());
978        assert!(dir.join("screenshot.png").exists());
979        assert!(dir.join("semantics-overlay.png").exists());
980        assert!(dir.join("widget-overlay.png").exists());
981
982        Ok(())
983    }
984
985    #[test]
986    fn screenshot_expectations_compare_against_png_baselines() -> Result<()> {
987        let app = build_app()?;
988        let window = app.main_window()?;
989        let save = window.get_by_role(SemanticsRole::Button).with_name("Save");
990        let baseline = unique_temp_path("save-button.png");
991
992        save.capture_screenshot()?.write_png(&baseline)?;
993        save.expect().to_match_screenshot(&baseline)?;
994
995        save.click()?;
996
997        let error = save
998            .expect()
999            .with_timeout(0.0)
1000            .to_match_screenshot(&baseline)
1001            .unwrap_err();
1002        let actual = baseline.with_file_name("save-button.actual.png");
1003        let diff = baseline.with_file_name("save-button.diff.png");
1004
1005        assert!(actual.exists());
1006        assert!(diff.exists());
1007        assert!(error.message().contains("screenshot assertion failed"));
1008
1009        Ok(())
1010    }
1011
1012    fn unique_temp_path(name: &str) -> PathBuf {
1013        let nonce = SystemTime::now()
1014            .duration_since(UNIX_EPOCH)
1015            .expect("system time is after unix epoch")
1016            .as_nanos();
1017        let dir =
1018            std::env::temp_dir().join(format!("sui-testing-{}-{}", std::process::id(), nonce));
1019        fs::create_dir_all(&dir).expect("temporary screenshot directory created");
1020        dir.join(name)
1021    }
1022}