Skip to main content

xrack_testing/
lib.rs

1//! Test XRack components without opening a window.
2//!
3//! `UiDriver` routes input through XRack's layout and interaction state machine.
4//! Both generated Rust components and interpreter instances implement `Component`.
5use std::{
6    rc::Rc,
7    time::{Duration, Instant},
8};
9pub use xrack_layout::{ActivationKey, EditAction, Point, Size, TableEditCommit, TextMeasurer};
10use xrack_layout::{
11    ChoiceKey, EditSource, Interaction, LayoutNode, MenuKey, MenuPanel, MenuShortcut,
12    NavigationKey, ScrollBarUpdate, ViewportObservers, WindowEffects, prepare_scene_with_input,
13};
14pub use xrack_runtime::RowKey;
15use xrack_runtime::{
16    Component, ControlAction, Node, RowSelection, ScrollRequests, TextCommand, TimerQueue,
17};
18
19/// Approximate text metrics independent of installed fonts.
20#[derive(Debug, Clone, Copy, Default)]
21pub struct FixedText;
22
23impl TextMeasurer for FixedText {
24    fn measure(&mut self, text: &str, font_size: f32, max_width: f32) -> Size {
25        let width = text.chars().count() as f32 * font_size * 0.55;
26        Size::new(width.min(max_width), font_size)
27    }
28}
29
30#[derive(Debug, PartialEq, Eq, thiserror::Error)]
31pub enum TargetError {
32    #[error("no materialized UI target matches {0}")]
33    Missing(String),
34    #[error("multiple UI targets match {0}; scope the query to a view and row")]
35    Ambiguous(String),
36}
37
38/// Drives a component on the test thread with an explicit clock for DSL timers.
39pub struct UiDriver<C, T = FixedText> {
40    component: C,
41    text: T,
42    input: Interaction,
43    scene: Rc<Node>,
44    layout: LayoutNode,
45    viewport: Size,
46    scroll_requests: ScrollRequests,
47    viewport_observers: ViewportObservers,
48    focus_requests: xrack_runtime::FocusRequests,
49    now: Instant,
50    timers: TimerQueue,
51}
52
53impl<C: Component> UiDriver<C> {
54    /// Use deterministic text metrics and a viewport in logical pixels.
55    pub fn headless(component: C, viewport: Size) -> Self {
56        Self::new(component, FixedText, viewport)
57    }
58}
59
60impl<C: Component, T: TextMeasurer> UiDriver<C, T> {
61    pub fn new(component: C, mut text: T, viewport: Size) -> Self {
62        let mut input = Interaction::default();
63        let (scene, layout) = prepare_scene_with_input(
64            &component,
65            component.render_shared(),
66            viewport,
67            &mut text,
68            &input,
69        );
70        input.reconcile(&scene, &layout);
71        let mut viewport_observers = ViewportObservers::default();
72        viewport_observers.sync(&scene, &layout);
73        let now = Instant::now();
74        viewport_observers.sync_scroll_activity(&scene, &layout, &input, now);
75        let mut driver = Self {
76            component,
77            text,
78            input,
79            scene,
80            layout,
81            viewport,
82            scroll_requests: ScrollRequests::default(),
83            viewport_observers,
84            focus_requests: xrack_runtime::FocusRequests::default(),
85            now,
86            timers: TimerQueue::default(),
87        };
88        driver.dispatch_loader_events();
89        if driver.component.scene_dirty() {
90            driver.prepare();
91        }
92        driver.sync_timers();
93        driver
94    }
95
96    fn dispatch_loader_events(&mut self) {
97        let _focus = self.focus_requests.enter();
98        xrack_runtime::dispatch_loader_events(&mut self.component, &self.scene);
99        self.input
100            .apply_focus_requests(&self.scene, &self.layout, self.focus_requests.drain());
101    }
102
103    fn prepare(&mut self) {
104        xrack_runtime::update_profile::layout(false);
105        (self.scene, self.layout) = prepare_scene_with_input(
106            &self.component,
107            self.component.render_shared(),
108            self.viewport,
109            &mut self.text,
110            &self.input,
111        );
112        self.input.reconcile(&self.scene, &self.layout);
113        self.sync_timers();
114    }
115
116    fn sync_timers(&mut self) {
117        let effects = WindowEffects::collect(&self.scene, &self.layout);
118        self.timers.sync(self.now, effects.timers);
119    }
120
121    /// Advance DSL timers and deliver due callbacks using the runtime's timer queue.
122    /// Repeating timers coalesce missed ticks, just as in a desktop window.
123    pub fn advance_time(&mut self, elapsed: Duration) {
124        self.now += elapsed;
125        for _ in 0..64 {
126            let Some(delivery) = self.timers.next_due(self.now) else {
127                return;
128            };
129            self.update(|_| {
130                delivery.fire();
131            });
132        }
133        assert!(
134            self.timers
135                .deadline()
136                .is_none_or(|deadline| deadline > self.now),
137            "DSL timer callbacks did not settle after 64 deliveries"
138        );
139    }
140
141    fn refresh(&mut self) {
142        let _focus = self.focus_requests.enter();
143        let _scroll = self.scroll_requests.enter();
144        self.prepare();
145        self.dispatch_loader_events();
146        let scrolled = self.input.take_scroll_events(&self.scene, &self.layout);
147        if self
148            .input
149            .apply_scroll_requests(&self.scene, &self.layout, self.scroll_requests.drain())
150        {
151            self.prepare();
152        }
153        self.viewport_observers.sync(&self.scene, &self.layout);
154        self.viewport_observers.sync_scroll_activity(
155            &self.scene,
156            &self.layout,
157            &self.input,
158            self.now,
159        );
160        for event in scrolled {
161            event.apply(&mut self.component, &self.scene);
162        }
163        if self.component.scene_dirty() {
164            self.prepare();
165        }
166        self.input
167            .apply_focus_requests(&self.scene, &self.layout, self.focus_requests.drain());
168    }
169
170    pub fn finish_loader_frame(&mut self) -> bool {
171        if !xrack_runtime::finish_loader_frame(&self.scene) {
172            return false;
173        }
174        self.refresh();
175        self.dispatch_loader_events();
176        true
177    }
178
179    pub fn update(&mut self, update: impl FnOnce(&mut C)) {
180        let _focus = self.focus_requests.enter();
181        let _scroll = self.scroll_requests.enter();
182        update(&mut self.component);
183        self.refresh();
184    }
185
186    pub fn scroll(&mut self, id: &str, delta: Point) -> bool {
187        let point = self.point_at(&self.path(id));
188        self.scroll_at(point, delta)
189    }
190
191    pub fn scroll_at(&mut self, point: Point, delta: Point) -> bool {
192        self.input.pointer_move(&self.scene, &self.layout, point);
193        let moved = self.input.scroll_wheel(&self.layout, delta, false);
194        if moved {
195            self.refresh();
196        }
197        moved
198    }
199
200    pub fn scroll_to_top(&mut self) -> bool {
201        let moved = self.input.scroll_to_top(&self.scene, &self.layout);
202        if moved {
203            self.refresh();
204        }
205        moved
206    }
207
208    pub fn scroll_bar(&self, id: &str) -> Option<xrack_layout::ScrollBarGeometry> {
209        let path = self.path(id);
210        self.layout
211            .at_path(&path)?
212            .scroll_control_geometry(self.scene.at_path(&path)?)
213    }
214
215    pub fn drag_scroll_bar(&mut self, id: &str, fraction: f32, touch: bool) -> bool {
216        self.drag_scroll_bar_with(id, fraction, touch, |_| true)
217    }
218
219    /// Inspect the committed move before release. Returning false cancels the capture.
220    pub fn drag_scroll_bar_with(
221        &mut self,
222        id: &str,
223        fraction: f32,
224        touch: bool,
225        finish: impl FnOnce(&mut Self) -> bool,
226    ) -> bool {
227        let Some(bar) = self.scroll_bar(id) else {
228            return false;
229        };
230        let start = Point {
231            x: bar.thumb.x + bar.thumb.width * 0.5,
232            y: bar.thumb.y + bar.thumb.height * 0.5,
233        };
234        // Drag past the end stops so rounding the grab point cannot miss an endpoint.
235        let overrun = if fraction <= 0.0 {
236            -1.0
237        } else if fraction >= 1.0 {
238            1.0
239        } else {
240            0.0
241        };
242        let mut end = start;
243        match bar.orientation {
244            xrack_runtime::Orientation::Horizontal => {
245                end.x = bar.track.x
246                    + bar.thumb.width * 0.5
247                    + (bar.track.width - bar.thumb.width) * fraction
248                    + overrun;
249            }
250            xrack_runtime::Orientation::Vertical => {
251                end.y = bar.track.y
252                    + bar.thumb.height * 0.5
253                    + (bar.track.height - bar.thumb.height) * fraction
254                    + overrun;
255            }
256        }
257        let _focus = self.focus_requests.enter();
258        let _scroll = self.scroll_requests.enter();
259        let update = if touch {
260            if self
261                .input
262                .touch_scroll_bar_press(&self.scene, &self.layout, start)
263                .is_none()
264            {
265                return false;
266            }
267            self.input
268                .touch_scroll_bar_drag(&self.scene, &self.layout, end)
269        } else {
270            self.input.pointer_move(&self.scene, &self.layout, start);
271            if self
272                .input
273                .scroll_bar_press(&self.scene, &self.layout)
274                .is_none()
275            {
276                return false;
277            }
278            self.input.pointer_move(&self.scene, &self.layout, end);
279            self.input
280                .scroll_bar_drag(&self.scene, &self.layout)
281                .unwrap_or(ScrollBarUpdate::Unchanged)
282        };
283        let moved = self.apply_scroll_bar(update);
284        if !finish(self) {
285            if touch {
286                self.input.finish_touch_scroll_bar();
287            } else {
288                self.input.finish_scroll_bar();
289            }
290            return moved;
291        }
292        let release = if touch {
293            self.input
294                .release_touch_scroll_bar(&self.scene, &self.layout, end)
295        } else {
296            self.input.release_scroll_bar(&self.scene, &self.layout)
297        };
298        moved | release.is_some_and(|update| self.apply_scroll_bar(update))
299    }
300
301    pub fn scroll_bar_key(&mut self, key: NavigationKey) -> Option<bool> {
302        let _focus = self.focus_requests.enter();
303        let _scroll = self.scroll_requests.enter();
304        let update = self.input.scroll_bar_key(&self.scene, &self.layout, key)?;
305        Some(self.apply_scroll_bar(update))
306    }
307
308    fn apply_scroll_bar(&mut self, update: ScrollBarUpdate) -> bool {
309        let moved = match update {
310            ScrollBarUpdate::Unchanged => false,
311            ScrollBarUpdate::ViewportMoved => true,
312            ScrollBarUpdate::Range(input) => {
313                self.component
314                    .adjust_range_at(&self.scene, &input.path, input.action)
315            }
316        };
317        if moved {
318            self.refresh();
319        }
320        moved
321    }
322
323    pub fn drag_viewport_from(&mut self, id: &str, delta: Point) -> bool {
324        let _focus = self.focus_requests.enter();
325        let _scroll = self.scroll_requests.enter();
326        let path = self.path(id);
327        self.move_to(&path);
328        let start = self.point_at(&path);
329        let end = Point {
330            x: start.x + delta.x,
331            y: start.y + delta.y,
332        };
333        let now = self.now;
334        self.input.pointer_press_in_scene(&self.scene, &self.layout);
335        self.input.arm_drag(&self.scene, &self.layout, start);
336        self.input
337            .arm_mouse_viewport_pan(&self.scene, &self.layout, start, now);
338        let moved = self.input.move_scroll_gesture(
339            &self.scene,
340            &self.layout,
341            end,
342            now + Duration::from_millis(20),
343        );
344        let claimed = self.input.mouse_viewport_pan_claimed();
345        if moved {
346            self.refresh();
347        }
348        if claimed {
349            self.input.end_scroll_gesture(
350                &self.scene,
351                &self.layout,
352                end,
353                now + Duration::from_millis(160),
354            );
355        } else {
356            self.input.cancel_scroll_gesture();
357            self.input.pointer_move(&self.scene, &self.layout, end);
358            if let Some(target) = self.input.pointer_release_target() {
359                self.component
360                    .dispatch_at(&self.scene, &target.path, "clicked");
361            }
362            self.refresh();
363        }
364        claimed
365    }
366
367    pub fn scene(&self) -> &Node {
368        &self.scene
369    }
370    pub fn component(&self) -> &C {
371        &self.component
372    }
373    pub fn input(&self) -> &Interaction {
374        &self.input
375    }
376
377    /// Resolve a unique ID among the materialized scene nodes.
378    pub fn find_path(&self, id: &str) -> Result<Vec<usize>, TargetError> {
379        find_path(&self.scene, Vec::new(), id.to_owned(), |node| {
380            node.element_id() == Some(id)
381        })
382    }
383
384    /// Resolve a materialized row by its stable model key within the named view.
385    /// Pass a child ID to select an element within that row.
386    pub fn find_row_path(
387        &self,
388        view: &str,
389        key: RowKey,
390        child: Option<&str>,
391    ) -> Result<Vec<usize>, TargetError> {
392        let view_path = self.find_path(view)?;
393        let view_node = self
394            .scene
395            .at_path(&view_path)
396            .ok_or_else(|| TargetError::Missing(view.into()))?;
397        let row = find_path(
398            view_node,
399            view_path,
400            format!("{view} row {key:?}"),
401            |node| node.row_key == Some(key),
402        )?;
403        match child {
404            Some(id) => {
405                let node = self
406                    .scene
407                    .at_path(&row)
408                    .ok_or_else(|| TargetError::Missing(id.into()))?;
409                find_path(
410                    node,
411                    row,
412                    format!("{view} row {key:?} child {id}"),
413                    |node| node.element_id() == Some(id),
414                )
415            }
416            None => Ok(row),
417        }
418    }
419
420    /// Resolve a materialized table cell by model row key and logical column index.
421    /// The column index is the index used by the table's selection API.
422    pub fn find_table_cell_path(
423        &self,
424        view: &str,
425        key: RowKey,
426        column: usize,
427    ) -> Result<Vec<usize>, TargetError> {
428        let mut path = self.find_row_path(view, key, None)?;
429        if self
430            .scene
431            .at_path(&path)
432            .is_some_and(|node| node.kind == "ListRow")
433        {
434            path.push(0);
435        }
436        if self
437            .scene
438            .at_path(&path)
439            .is_some_and(|node| node.kind == "TableRow" && node.child_at(column).is_some())
440        {
441            path.push(column);
442            return Ok(path);
443        }
444        Err(TargetError::Missing(format!(
445            "{view} row {key:?} column {column}"
446        )))
447    }
448
449    #[track_caller]
450    pub fn path(&self, id: &str) -> Vec<usize> {
451        self.find_path(id).unwrap_or_else(|error| panic!("{error}"))
452    }
453
454    /// Prepared layout for the current frame, usable with the native renderer.
455    pub fn layout(&self) -> &LayoutNode {
456        &self.layout
457    }
458
459    #[track_caller]
460    pub fn bounds(&self, id: &str) -> xrack_layout::Rect {
461        self.layout
462            .at_path(&self.path(id))
463            .unwrap_or_else(|| panic!("UI target {id:?} has no layout"))
464            .bounds
465    }
466
467    pub fn layout_at(&self, path: &[usize]) -> Option<&LayoutNode> {
468        self.layout.at_path(path)
469    }
470
471    #[track_caller]
472    pub fn node(&self, id: &str) -> &Node {
473        self.scene
474            .at_path(&self.path(id))
475            .unwrap_or_else(|| panic!("UI target {id:?} left the scene"))
476    }
477
478    pub fn focused(&self) -> Option<&str> {
479        self.input.focused.as_ref()?.element_id()
480    }
481
482    pub fn can_hit(&mut self, id: &str) -> bool {
483        let path = self.path(id);
484        self.move_to(&path);
485        self.input
486            .hovered
487            .as_ref()
488            .is_some_and(|target| target.path == path)
489    }
490
491    #[track_caller]
492    fn move_to(&mut self, path: &[usize]) {
493        let point = self.point_at(path);
494        self.input.pointer_move(&self.scene, &self.layout, point);
495    }
496
497    #[track_caller]
498    fn point_at(&self, path: &[usize]) -> Point {
499        let item = self
500            .layout
501            .at_path(path)
502            .unwrap_or_else(|| panic!("UI target {path:?} has no layout"));
503        let node = self
504            .scene
505            .at_path(path)
506            .unwrap_or_else(|| panic!("UI target {path:?} has no scene node"));
507        let bounds = if let Some(header) = item.tab_header {
508            header
509        } else if node.group_checkable() {
510            item.group_header(node)
511        } else {
512            item.bounds
513        };
514        let hit = item.clip.intersect(bounds);
515        assert!(
516            hit.width > 0.0 && hit.height > 0.0,
517            "target is outside the viewport"
518        );
519        Point {
520            x: hit.x + hit.width * 0.5,
521            y: hit.y + hit.height * 0.5,
522        }
523    }
524
525    #[track_caller]
526    pub fn click(&mut self, id: &str) {
527        self.click_at_path(&self.path(id));
528    }
529
530    #[track_caller]
531    pub fn click_at_path(&mut self, path: &[usize]) {
532        let _focus = self.focus_requests.enter();
533        let _scroll = self.scroll_requests.enter();
534        self.move_to(path);
535        if self.input.menu_press(&self.scene, &self.layout) {
536            self.release_menu();
537            return;
538        }
539        if let Some(close) = self.input.popup_outside_press(&self.scene, &self.layout) {
540            assert!(
541                self.component
542                    .control_at(&self.scene, &close.path, close.action)
543            );
544            self.refresh();
545            self.move_to(path);
546        }
547        if let Some(update) = self.input.scroll_bar_press(&self.scene, &self.layout) {
548            self.apply_scroll_bar(update);
549            if let Some(update) = self.input.release_scroll_bar(&self.scene, &self.layout) {
550                self.apply_scroll_bar(update);
551            }
552            return;
553        }
554        self.input.pointer_press_in_scene(&self.scene, &self.layout);
555        let target = self
556            .input
557            .pointer_release_target()
558            .unwrap_or_else(|| panic!("click did not reach {path:?}"));
559        assert_eq!(target.path, path, "click hit a different control");
560        self.activate_target(target);
561    }
562
563    fn activate_target(&mut self, mut target: xrack_layout::Target) -> bool {
564        if let Some(selection) =
565            self.input
566                .list_item_delegate_selection(&self.scene, &self.layout, &target)
567        {
568            let Some(row) = target.row_key else {
569                return false;
570            };
571            assert!(
572                self.component
573                    .control_at(&self.scene, &selection.path, selection.action)
574            );
575            self.refresh();
576            let Some(resolved) =
577                self.input
578                    .resolve_item_delegate(&self.scene, &self.layout, &selection.path, row)
579            else {
580                return false;
581            };
582            target = resolved;
583        }
584        if let Some(selection) = self.input.table_delegate_selection(
585            &self.scene,
586            &self.layout,
587            &target,
588            RowSelection::Replace,
589        ) {
590            self.component
591                .control_at(&self.scene, &selection.path, selection.action);
592            self.refresh();
593            if self.scene.row_key_at(&target.path) != target.row_key {
594                return true;
595            }
596        }
597        let action = self
598            .input
599            .dialog_button(&self.scene, &self.layout, &target)
600            .or_else(|| {
601                self.input.select_group_option_with_selection(
602                    &self.scene,
603                    &self.layout,
604                    &target,
605                    RowSelection::Replace,
606                )
607            });
608        let changed = if let Some(action) = action {
609            self.component
610                .control_at(&self.scene, &action.path, action.action)
611        } else {
612            self.input
613                .open_menu_bar(&self.scene, &self.layout, target.clone())
614                || self
615                    .input
616                    .open_choice_at_pointer(&self.scene, &self.layout, target.clone())
617                || self
618                    .component
619                    .dispatch_at(&self.scene, &target.path, "clicked")
620        };
621        self.refresh();
622        changed
623    }
624
625    /// Activate the focused control as with Enter or Space.
626    pub fn activate(&mut self, key: ActivationKey) -> bool {
627        let _focus = self.focus_requests.enter();
628        let _scroll = self.scroll_requests.enter();
629        self.input.key_press_with_scene(&self.scene, key);
630        let Some(target) = self.input.key_release_with_scene(&self.scene, key) else {
631            return false;
632        };
633        let target = self
634            .input
635            .current_item_delegate(&self.scene, &self.layout, &target)
636            .unwrap_or(target);
637        self.activate_target(target)
638    }
639
640    pub fn tab(&mut self) {
641        self.tab_with_direction(false);
642    }
643
644    pub fn begin_table_edit(&mut self) -> bool {
645        self.input.begin_table_edit(&self.scene, &self.layout)
646    }
647
648    /// Commit an active cell editor using normal validation and model writes.
649    pub fn finish_table_edit(&mut self) -> TableEditCommit {
650        let _focus = self.focus_requests.enter();
651        let _scroll = self.scroll_requests.enter();
652        let result = self
653            .input
654            .finish_table_edit(&mut self.component, &self.scene);
655        self.refresh();
656        result
657    }
658
659    pub fn tab_with_direction(&mut self, backward: bool) {
660        let _focus = self.focus_requests.enter();
661        let _scroll = self.scroll_requests.enter();
662        if let Some(origin) = self.input.tab_edit_origin(&self.scene) {
663            use xrack_layout::TableEditCommit;
664            let result = self
665                .input
666                .finish_table_edit(&mut self.component, &self.scene);
667            if result == TableEditCommit::Kept {
668                return;
669            }
670            self.refresh();
671            if matches!(
672                result,
673                TableEditCommit::Changed | TableEditCommit::Unchanged
674            ) && let Some(target) = self.input.next_table_edit_target(
675                &self.component,
676                &self.scene,
677                &self.layout,
678                &origin,
679                backward,
680            ) {
681                if self.input.apply_scroll_requests(
682                    &self.scene,
683                    &self.layout,
684                    [target.scroll_request()],
685                ) {
686                    self.prepare();
687                }
688                if self
689                    .input
690                    .begin_table_edit_target(&self.scene, &self.layout, &target)
691                {
692                    self.refresh();
693                    return;
694                }
695            }
696        }
697        if self.input.focus_next(&self.scene, &self.layout, backward) {
698            self.refresh();
699        }
700    }
701
702    pub fn group_key(&mut self, key: NavigationKey) -> bool {
703        let _focus = self.focus_requests.enter();
704        let _scroll = self.scroll_requests.enter();
705        let Some(action) = self.input.group_key(&self.scene, &self.layout, key) else {
706            return false;
707        };
708        let changed = self
709            .component
710            .control_at(&self.scene, &action.path, action.action);
711        self.refresh();
712        changed
713    }
714
715    pub fn back(&mut self) -> bool {
716        let _focus = self.focus_requests.enter();
717        let _scroll = self.scroll_requests.enter();
718        let Some(action) = self.input.stack_back(&self.scene, &self.layout) else {
719            return false;
720        };
721        let moved = self
722            .component
723            .control_at(&self.scene, &action.path, action.action);
724        self.refresh();
725        moved
726    }
727
728    pub fn menus(&self) -> Vec<MenuPanel<'_>> {
729        self.input.menu_panels(&self.scene, &self.layout)
730    }
731
732    pub fn context_menu(&mut self, id: &str) -> bool {
733        let path = self.path(id);
734        self.move_to(&path);
735        self.input
736            .open_context_menu(&self.scene, &self.layout, false)
737    }
738
739    pub fn keyboard_context_menu(&mut self) -> bool {
740        self.input
741            .open_context_menu(&self.scene, &self.layout, true)
742    }
743
744    pub fn menu_key(&mut self, key: MenuKey) {
745        let _focus = self.focus_requests.enter();
746        let _scroll = self.scroll_requests.enter();
747        if let Some(action) = self.input.menu_key(&self.scene, &self.layout, key) {
748            self.apply_menu_action(action);
749        }
750        self.refresh();
751    }
752
753    pub fn menu_shortcut(&mut self, key: MenuShortcut) -> bool {
754        let _focus = self.focus_requests.enter();
755        let _scroll = self.scroll_requests.enter();
756        let Some(action) = self.input.menu_shortcut(&self.scene, &self.layout, key) else {
757            return false;
758        };
759        self.input.close_menu(&self.scene, &self.layout);
760        self.apply_menu_action(action);
761        self.refresh();
762        true
763    }
764
765    #[track_caller]
766    pub fn click_menu_row(&mut self, label: &str) -> bool {
767        let _focus = self.focus_requests.enter();
768        let _scroll = self.scroll_requests.enter();
769        let rect = {
770            let panels = self.menus();
771            let panel = panels
772                .last()
773                .unwrap_or_else(|| panic!("menu is closed while locating {label:?}"));
774            let slot = panel
775                .rows
776                .iter()
777                .position(|row| row.label == label)
778                .unwrap_or_else(|| panic!("no visible menu row has label {label:?}"));
779            panel.row_bounds(slot)
780        };
781        self.input.pointer_move(
782            &self.scene,
783            &self.layout,
784            Point {
785                x: rect.x + rect.width * 0.5,
786                y: rect.y + rect.height * 0.5,
787            },
788        );
789        assert!(self.input.menu_press(&self.scene, &self.layout));
790        self.release_menu()
791    }
792
793    fn release_menu(&mut self) -> bool {
794        let activated = self
795            .input
796            .menu_release(&self.scene, &self.layout)
797            .is_some_and(|action| {
798                self.apply_menu_action(action);
799                true
800            });
801        self.refresh();
802        activated
803    }
804
805    fn apply_menu_action(&mut self, input: xrack_layout::ControlInput) {
806        match input.action {
807            ControlAction::TextCommand(command @ TextCommand::SelectAll) => {
808                self.input.apply_text_selection(&self.scene, command);
809            }
810            ControlAction::TextCommand(command @ (TextCommand::Undo | TextCommand::Redo)) => {
811                assert!(self.input.replay_text_edit(
812                    &mut self.component,
813                    &self.scene,
814                    command == TextCommand::Redo
815                ));
816            }
817            action => assert!(self.component.control_at(&self.scene, &input.path, action)),
818        }
819    }
820
821    pub fn choice_key(&mut self, key: ChoiceKey) {
822        let _focus = self.focus_requests.enter();
823        let _scroll = self.scroll_requests.enter();
824        assert!(self.input.choice_open(), "choice popup is closed");
825        if let Some(action) = self.input.choice_key(&self.scene, &self.layout, key) {
826            assert!(
827                self.component
828                    .control_at(&self.scene, &action.path, action.action)
829            );
830        }
831        self.refresh();
832    }
833
834    #[track_caller]
835    pub fn escape(&mut self) {
836        let _focus = self.focus_requests.enter();
837        let _scroll = self.scroll_requests.enter();
838        let action = self
839            .input
840            .dialog_escape(&self.scene, &self.layout)
841            .unwrap_or_else(|| panic!("there is no dismissible dialog"));
842        assert!(
843            self.component
844                .control_at(&self.scene, &action.path, action.action)
845        );
846        self.refresh();
847    }
848
849    /// Replace all text in the focused editor through the normal edit pipeline.
850    #[track_caller]
851    pub fn fill_focused(&mut self, text: &str) {
852        assert!(
853            self.edit_focused(EditAction::ReplaceAll(text)),
854            "focused control {:?} did not accept text input",
855            self.focused()
856        );
857    }
858
859    /// Send an edit to the focused control or active table cell editor.
860    pub fn edit_focused(&mut self, action: EditAction<'_>) -> bool {
861        let _focus = self.focus_requests.enter();
862        let _scroll = self.scroll_requests.enter();
863        let changed = self.input.edit_text(
864            &mut self.component,
865            &self.scene,
866            action,
867            EditSource::Atomic,
868            self.now,
869        );
870        self.refresh();
871        changed
872    }
873}
874
875fn find_path(
876    node: &Node,
877    mut path: Vec<usize>,
878    description: String,
879    matches: impl Fn(&Node) -> bool,
880) -> Result<Vec<usize>, TargetError> {
881    fn visit(
882        node: &Node,
883        path: &mut Vec<usize>,
884        matches: &impl Fn(&Node) -> bool,
885        found: &mut Option<Vec<usize>>,
886    ) -> bool {
887        if matches(node) && found.replace(path.clone()).is_some() {
888            return false;
889        }
890        for (index, child) in node.materialized_children() {
891            path.push(index);
892            if !visit(child, path, matches, found) {
893                return false;
894            }
895            path.pop();
896        }
897        true
898    }
899
900    let mut found = None;
901    if !visit(node, &mut path, &matches, &mut found) {
902        return Err(TargetError::Ambiguous(description));
903    }
904    found.ok_or(TargetError::Missing(description))
905}