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_bar(&self, id: &str) -> Option<xrack_layout::ScrollBarGeometry> {
201        let path = self.path(id);
202        self.layout
203            .at_path(&path)?
204            .scroll_control_geometry(self.scene.at_path(&path)?)
205    }
206
207    pub fn drag_scroll_bar(&mut self, id: &str, fraction: f32, touch: bool) -> bool {
208        self.drag_scroll_bar_with(id, fraction, touch, |_| true)
209    }
210
211    /// Inspect the committed move before release. Returning false cancels the capture.
212    pub fn drag_scroll_bar_with(
213        &mut self,
214        id: &str,
215        fraction: f32,
216        touch: bool,
217        finish: impl FnOnce(&mut Self) -> bool,
218    ) -> bool {
219        let Some(bar) = self.scroll_bar(id) else {
220            return false;
221        };
222        let start = Point {
223            x: bar.thumb.x + bar.thumb.width * 0.5,
224            y: bar.thumb.y + bar.thumb.height * 0.5,
225        };
226        // Drag past the end stops so rounding the grab point cannot miss an endpoint.
227        let overrun = if fraction <= 0.0 {
228            -1.0
229        } else if fraction >= 1.0 {
230            1.0
231        } else {
232            0.0
233        };
234        let mut end = start;
235        match bar.orientation {
236            xrack_runtime::Orientation::Horizontal => {
237                end.x = bar.track.x
238                    + bar.thumb.width * 0.5
239                    + (bar.track.width - bar.thumb.width) * fraction
240                    + overrun;
241            }
242            xrack_runtime::Orientation::Vertical => {
243                end.y = bar.track.y
244                    + bar.thumb.height * 0.5
245                    + (bar.track.height - bar.thumb.height) * fraction
246                    + overrun;
247            }
248        }
249        let _focus = self.focus_requests.enter();
250        let _scroll = self.scroll_requests.enter();
251        let update = if touch {
252            if self
253                .input
254                .touch_scroll_bar_press(&self.scene, &self.layout, start)
255                .is_none()
256            {
257                return false;
258            }
259            self.input
260                .touch_scroll_bar_drag(&self.scene, &self.layout, end)
261        } else {
262            self.input.pointer_move(&self.scene, &self.layout, start);
263            if self
264                .input
265                .scroll_bar_press(&self.scene, &self.layout)
266                .is_none()
267            {
268                return false;
269            }
270            self.input.pointer_move(&self.scene, &self.layout, end);
271            self.input
272                .scroll_bar_drag(&self.scene, &self.layout)
273                .unwrap_or(ScrollBarUpdate::Unchanged)
274        };
275        let moved = self.apply_scroll_bar(update);
276        if !finish(self) {
277            if touch {
278                self.input.finish_touch_scroll_bar();
279            } else {
280                self.input.finish_scroll_bar();
281            }
282            return moved;
283        }
284        let release = if touch {
285            self.input
286                .release_touch_scroll_bar(&self.scene, &self.layout, end)
287        } else {
288            self.input.release_scroll_bar(&self.scene, &self.layout)
289        };
290        moved | release.is_some_and(|update| self.apply_scroll_bar(update))
291    }
292
293    pub fn scroll_bar_key(&mut self, key: NavigationKey) -> Option<bool> {
294        let _focus = self.focus_requests.enter();
295        let _scroll = self.scroll_requests.enter();
296        let update = self.input.scroll_bar_key(&self.scene, &self.layout, key)?;
297        Some(self.apply_scroll_bar(update))
298    }
299
300    fn apply_scroll_bar(&mut self, update: ScrollBarUpdate) -> bool {
301        let moved = match update {
302            ScrollBarUpdate::Unchanged => false,
303            ScrollBarUpdate::ViewportMoved => true,
304            ScrollBarUpdate::Range(input) => {
305                self.component
306                    .adjust_range_at(&self.scene, &input.path, input.action)
307            }
308        };
309        if moved {
310            self.refresh();
311        }
312        moved
313    }
314
315    pub fn drag_viewport_from(&mut self, id: &str, delta: Point) -> bool {
316        let _focus = self.focus_requests.enter();
317        let _scroll = self.scroll_requests.enter();
318        let path = self.path(id);
319        self.move_to(&path);
320        let start = self.point_at(&path);
321        let end = Point {
322            x: start.x + delta.x,
323            y: start.y + delta.y,
324        };
325        let now = self.now;
326        self.input.pointer_press_in_scene(&self.scene, &self.layout);
327        self.input.arm_drag(&self.scene, &self.layout, start);
328        self.input
329            .arm_mouse_viewport_pan(&self.scene, &self.layout, start, now);
330        let moved = self.input.move_scroll_gesture(
331            &self.scene,
332            &self.layout,
333            end,
334            now + Duration::from_millis(20),
335        );
336        let claimed = self.input.mouse_viewport_pan_claimed();
337        if moved {
338            self.refresh();
339        }
340        if claimed {
341            self.input.end_scroll_gesture(
342                &self.scene,
343                &self.layout,
344                end,
345                now + Duration::from_millis(160),
346            );
347        } else {
348            self.input.cancel_scroll_gesture();
349            self.input.pointer_move(&self.scene, &self.layout, end);
350            if let Some(target) = self.input.pointer_release_target() {
351                self.component
352                    .dispatch_at(&self.scene, &target.path, "clicked");
353            }
354            self.refresh();
355        }
356        claimed
357    }
358
359    pub fn scene(&self) -> &Node {
360        &self.scene
361    }
362    pub fn component(&self) -> &C {
363        &self.component
364    }
365    pub fn input(&self) -> &Interaction {
366        &self.input
367    }
368
369    /// Resolve a unique ID among the materialized scene nodes.
370    pub fn find_path(&self, id: &str) -> Result<Vec<usize>, TargetError> {
371        find_path(&self.scene, Vec::new(), id.to_owned(), |node| {
372            node.element_id() == Some(id)
373        })
374    }
375
376    /// Resolve a materialized row by its stable model key within the named view.
377    /// Pass a child ID to select an element within that row.
378    pub fn find_row_path(
379        &self,
380        view: &str,
381        key: RowKey,
382        child: Option<&str>,
383    ) -> Result<Vec<usize>, TargetError> {
384        let view_path = self.find_path(view)?;
385        let view_node = self
386            .scene
387            .at_path(&view_path)
388            .ok_or_else(|| TargetError::Missing(view.into()))?;
389        let row = find_path(
390            view_node,
391            view_path,
392            format!("{view} row {key:?}"),
393            |node| node.row_key == Some(key),
394        )?;
395        match child {
396            Some(id) => {
397                let node = self
398                    .scene
399                    .at_path(&row)
400                    .ok_or_else(|| TargetError::Missing(id.into()))?;
401                find_path(
402                    node,
403                    row,
404                    format!("{view} row {key:?} child {id}"),
405                    |node| node.element_id() == Some(id),
406                )
407            }
408            None => Ok(row),
409        }
410    }
411
412    /// Resolve a materialized table cell by model row key and logical column index.
413    /// The column index is the index used by the table's selection API.
414    pub fn find_table_cell_path(
415        &self,
416        view: &str,
417        key: RowKey,
418        column: usize,
419    ) -> Result<Vec<usize>, TargetError> {
420        let mut path = self.find_row_path(view, key, None)?;
421        if self
422            .scene
423            .at_path(&path)
424            .is_some_and(|node| node.kind == "ListRow")
425        {
426            path.push(0);
427        }
428        if self
429            .scene
430            .at_path(&path)
431            .is_some_and(|node| node.kind == "TableRow" && node.child_at(column).is_some())
432        {
433            path.push(column);
434            return Ok(path);
435        }
436        Err(TargetError::Missing(format!(
437            "{view} row {key:?} column {column}"
438        )))
439    }
440
441    #[track_caller]
442    pub fn path(&self, id: &str) -> Vec<usize> {
443        self.find_path(id).unwrap_or_else(|error| panic!("{error}"))
444    }
445
446    /// Prepared layout for the current frame, usable with the native renderer.
447    pub fn layout(&self) -> &LayoutNode {
448        &self.layout
449    }
450
451    #[track_caller]
452    pub fn bounds(&self, id: &str) -> xrack_layout::Rect {
453        self.layout
454            .at_path(&self.path(id))
455            .unwrap_or_else(|| panic!("UI target {id:?} has no layout"))
456            .bounds
457    }
458
459    pub fn layout_at(&self, path: &[usize]) -> Option<&LayoutNode> {
460        self.layout.at_path(path)
461    }
462
463    #[track_caller]
464    pub fn node(&self, id: &str) -> &Node {
465        self.scene
466            .at_path(&self.path(id))
467            .unwrap_or_else(|| panic!("UI target {id:?} left the scene"))
468    }
469
470    pub fn focused(&self) -> Option<&str> {
471        self.input.focused.as_ref()?.element_id()
472    }
473
474    pub fn can_hit(&mut self, id: &str) -> bool {
475        let path = self.path(id);
476        self.move_to(&path);
477        self.input
478            .hovered
479            .as_ref()
480            .is_some_and(|target| target.path == path)
481    }
482
483    #[track_caller]
484    fn move_to(&mut self, path: &[usize]) {
485        let point = self.point_at(path);
486        self.input.pointer_move(&self.scene, &self.layout, point);
487    }
488
489    #[track_caller]
490    fn point_at(&self, path: &[usize]) -> Point {
491        let item = self
492            .layout
493            .at_path(path)
494            .unwrap_or_else(|| panic!("UI target {path:?} has no layout"));
495        let node = self
496            .scene
497            .at_path(path)
498            .unwrap_or_else(|| panic!("UI target {path:?} has no scene node"));
499        let bounds = if node.group_checkable() {
500            item.group_header(node)
501        } else {
502            item.bounds
503        };
504        let hit = item.clip.intersect(bounds);
505        assert!(
506            hit.width > 0.0 && hit.height > 0.0,
507            "target is outside the viewport"
508        );
509        Point {
510            x: hit.x + hit.width * 0.5,
511            y: hit.y + hit.height * 0.5,
512        }
513    }
514
515    #[track_caller]
516    pub fn click(&mut self, id: &str) {
517        self.click_at_path(&self.path(id));
518    }
519
520    #[track_caller]
521    pub fn click_at_path(&mut self, path: &[usize]) {
522        let _focus = self.focus_requests.enter();
523        let _scroll = self.scroll_requests.enter();
524        self.move_to(path);
525        if self.input.menu_press(&self.scene, &self.layout) {
526            self.release_menu();
527            return;
528        }
529        if let Some(close) = self.input.popup_outside_press(&self.scene, &self.layout) {
530            assert!(
531                self.component
532                    .control_at(&self.scene, &close.path, close.action)
533            );
534            self.refresh();
535            self.move_to(path);
536        }
537        if let Some(update) = self.input.scroll_bar_press(&self.scene, &self.layout) {
538            self.apply_scroll_bar(update);
539            if let Some(update) = self.input.release_scroll_bar(&self.scene, &self.layout) {
540                self.apply_scroll_bar(update);
541            }
542            return;
543        }
544        self.input.pointer_press_in_scene(&self.scene, &self.layout);
545        let target = self
546            .input
547            .pointer_release_target()
548            .unwrap_or_else(|| panic!("click did not reach {path:?}"));
549        assert_eq!(target.path, path, "click hit a different control");
550        self.activate_target(target);
551    }
552
553    fn activate_target(&mut self, mut target: xrack_layout::Target) -> bool {
554        if let Some(selection) =
555            self.input
556                .list_item_delegate_selection(&self.scene, &self.layout, &target)
557        {
558            let Some(row) = target.row_key else {
559                return false;
560            };
561            assert!(
562                self.component
563                    .control_at(&self.scene, &selection.path, selection.action)
564            );
565            self.refresh();
566            let Some(resolved) =
567                self.input
568                    .resolve_item_delegate(&self.scene, &self.layout, &selection.path, row)
569            else {
570                return false;
571            };
572            target = resolved;
573        }
574        if let Some(selection) = self.input.table_delegate_selection(
575            &self.scene,
576            &self.layout,
577            &target,
578            RowSelection::Replace,
579        ) {
580            self.component
581                .control_at(&self.scene, &selection.path, selection.action);
582            self.refresh();
583            if self.scene.row_key_at(&target.path) != target.row_key {
584                return true;
585            }
586        }
587        let action = self
588            .input
589            .dialog_button(&self.scene, &self.layout, &target)
590            .or_else(|| {
591                self.input.select_group_option_with_selection(
592                    &self.scene,
593                    &self.layout,
594                    &target,
595                    RowSelection::Replace,
596                )
597            });
598        let changed = if let Some(action) = action {
599            self.component
600                .control_at(&self.scene, &action.path, action.action)
601        } else {
602            self.input
603                .open_menu_bar(&self.scene, &self.layout, target.clone())
604                || self
605                    .input
606                    .open_choice_at_pointer(&self.scene, &self.layout, target.clone())
607                || self
608                    .component
609                    .dispatch_at(&self.scene, &target.path, "clicked")
610        };
611        self.refresh();
612        changed
613    }
614
615    /// Activate the focused control as with Enter or Space.
616    pub fn activate(&mut self, key: ActivationKey) -> bool {
617        let _focus = self.focus_requests.enter();
618        let _scroll = self.scroll_requests.enter();
619        self.input.key_press_with_scene(&self.scene, key);
620        let Some(target) = self.input.key_release_with_scene(&self.scene, key) else {
621            return false;
622        };
623        let target = self
624            .input
625            .current_item_delegate(&self.scene, &self.layout, &target)
626            .unwrap_or(target);
627        self.activate_target(target)
628    }
629
630    pub fn tab(&mut self) {
631        self.tab_with_direction(false);
632    }
633
634    pub fn begin_table_edit(&mut self) -> bool {
635        self.input.begin_table_edit(&self.scene, &self.layout)
636    }
637
638    /// Commit an active cell editor using normal validation and model writes.
639    pub fn finish_table_edit(&mut self) -> TableEditCommit {
640        let _focus = self.focus_requests.enter();
641        let _scroll = self.scroll_requests.enter();
642        let result = self
643            .input
644            .finish_table_edit(&mut self.component, &self.scene);
645        self.refresh();
646        result
647    }
648
649    pub fn tab_with_direction(&mut self, backward: bool) {
650        let _focus = self.focus_requests.enter();
651        let _scroll = self.scroll_requests.enter();
652        if let Some(origin) = self.input.tab_edit_origin(&self.scene) {
653            use xrack_layout::TableEditCommit;
654            let result = self
655                .input
656                .finish_table_edit(&mut self.component, &self.scene);
657            if result == TableEditCommit::Kept {
658                return;
659            }
660            self.refresh();
661            if matches!(
662                result,
663                TableEditCommit::Changed | TableEditCommit::Unchanged
664            ) && let Some(target) = self.input.next_table_edit_target(
665                &self.component,
666                &self.scene,
667                &self.layout,
668                &origin,
669                backward,
670            ) {
671                if self.input.apply_scroll_requests(
672                    &self.scene,
673                    &self.layout,
674                    [target.scroll_request()],
675                ) {
676                    self.prepare();
677                }
678                if self
679                    .input
680                    .begin_table_edit_target(&self.scene, &self.layout, &target)
681                {
682                    self.refresh();
683                    return;
684                }
685            }
686        }
687        if self.input.focus_next(&self.scene, &self.layout, backward) {
688            self.refresh();
689        }
690    }
691
692    pub fn group_key(&mut self, key: NavigationKey) -> bool {
693        let _focus = self.focus_requests.enter();
694        let _scroll = self.scroll_requests.enter();
695        let Some(action) = self.input.group_key(&self.scene, &self.layout, key) else {
696            return false;
697        };
698        let changed = self
699            .component
700            .control_at(&self.scene, &action.path, action.action);
701        self.refresh();
702        changed
703    }
704
705    pub fn back(&mut self) -> bool {
706        let _focus = self.focus_requests.enter();
707        let _scroll = self.scroll_requests.enter();
708        let Some(action) = self.input.stack_back(&self.scene, &self.layout) else {
709            return false;
710        };
711        let moved = self
712            .component
713            .control_at(&self.scene, &action.path, action.action);
714        self.refresh();
715        moved
716    }
717
718    pub fn menus(&self) -> Vec<MenuPanel<'_>> {
719        self.input.menu_panels(&self.scene, &self.layout)
720    }
721
722    pub fn context_menu(&mut self, id: &str) -> bool {
723        let path = self.path(id);
724        self.move_to(&path);
725        self.input
726            .open_context_menu(&self.scene, &self.layout, false)
727    }
728
729    pub fn keyboard_context_menu(&mut self) -> bool {
730        self.input
731            .open_context_menu(&self.scene, &self.layout, true)
732    }
733
734    pub fn menu_key(&mut self, key: MenuKey) {
735        let _focus = self.focus_requests.enter();
736        let _scroll = self.scroll_requests.enter();
737        if let Some(action) = self.input.menu_key(&self.scene, &self.layout, key) {
738            self.apply_menu_action(action);
739        }
740        self.refresh();
741    }
742
743    pub fn menu_shortcut(&mut self, key: MenuShortcut) -> bool {
744        let _focus = self.focus_requests.enter();
745        let _scroll = self.scroll_requests.enter();
746        let Some(action) = self.input.menu_shortcut(&self.scene, &self.layout, key) else {
747            return false;
748        };
749        self.input.close_menu(&self.scene, &self.layout);
750        self.apply_menu_action(action);
751        self.refresh();
752        true
753    }
754
755    #[track_caller]
756    pub fn click_menu_row(&mut self, label: &str) -> bool {
757        let _focus = self.focus_requests.enter();
758        let _scroll = self.scroll_requests.enter();
759        let rect = {
760            let panels = self.menus();
761            let panel = panels
762                .last()
763                .unwrap_or_else(|| panic!("menu is closed while locating {label:?}"));
764            let slot = panel
765                .rows
766                .iter()
767                .position(|row| row.label == label)
768                .unwrap_or_else(|| panic!("no visible menu row has label {label:?}"));
769            panel.row_bounds(slot)
770        };
771        self.input.pointer_move(
772            &self.scene,
773            &self.layout,
774            Point {
775                x: rect.x + rect.width * 0.5,
776                y: rect.y + rect.height * 0.5,
777            },
778        );
779        assert!(self.input.menu_press(&self.scene, &self.layout));
780        self.release_menu()
781    }
782
783    fn release_menu(&mut self) -> bool {
784        let activated = self
785            .input
786            .menu_release(&self.scene, &self.layout)
787            .is_some_and(|action| {
788                self.apply_menu_action(action);
789                true
790            });
791        self.refresh();
792        activated
793    }
794
795    fn apply_menu_action(&mut self, input: xrack_layout::ControlInput) {
796        match input.action {
797            ControlAction::TextCommand(command @ TextCommand::SelectAll) => {
798                self.input.apply_text_selection(&self.scene, command);
799            }
800            ControlAction::TextCommand(command @ (TextCommand::Undo | TextCommand::Redo)) => {
801                assert!(self.input.replay_text_edit(
802                    &mut self.component,
803                    &self.scene,
804                    command == TextCommand::Redo
805                ));
806            }
807            action => assert!(self.component.control_at(&self.scene, &input.path, action)),
808        }
809    }
810
811    pub fn choice_key(&mut self, key: ChoiceKey) {
812        let _focus = self.focus_requests.enter();
813        let _scroll = self.scroll_requests.enter();
814        assert!(self.input.choice_open(), "choice popup is closed");
815        if let Some(action) = self.input.choice_key(&self.scene, &self.layout, key) {
816            assert!(
817                self.component
818                    .control_at(&self.scene, &action.path, action.action)
819            );
820        }
821        self.refresh();
822    }
823
824    #[track_caller]
825    pub fn escape(&mut self) {
826        let _focus = self.focus_requests.enter();
827        let _scroll = self.scroll_requests.enter();
828        let action = self
829            .input
830            .dialog_escape(&self.scene, &self.layout)
831            .unwrap_or_else(|| panic!("there is no dismissible dialog"));
832        assert!(
833            self.component
834                .control_at(&self.scene, &action.path, action.action)
835        );
836        self.refresh();
837    }
838
839    /// Replace all text in the focused editor through the normal edit pipeline.
840    #[track_caller]
841    pub fn fill_focused(&mut self, text: &str) {
842        assert!(
843            self.edit_focused(EditAction::ReplaceAll(text)),
844            "focused control {:?} did not accept text input",
845            self.focused()
846        );
847    }
848
849    /// Send an edit to the focused control or active table cell editor.
850    pub fn edit_focused(&mut self, action: EditAction<'_>) -> bool {
851        let _focus = self.focus_requests.enter();
852        let _scroll = self.scroll_requests.enter();
853        let changed = self.input.edit_text(
854            &mut self.component,
855            &self.scene,
856            action,
857            EditSource::Atomic,
858            self.now,
859        );
860        self.refresh();
861        changed
862    }
863}
864
865fn find_path(
866    node: &Node,
867    mut path: Vec<usize>,
868    description: String,
869    matches: impl Fn(&Node) -> bool,
870) -> Result<Vec<usize>, TargetError> {
871    fn visit(
872        node: &Node,
873        path: &mut Vec<usize>,
874        matches: &impl Fn(&Node) -> bool,
875        found: &mut Option<Vec<usize>>,
876    ) -> bool {
877        if matches(node) && found.replace(path.clone()).is_some() {
878            return false;
879        }
880        for (index, child) in node.materialized_children() {
881            path.push(index);
882            if !visit(child, path, matches, found) {
883                return false;
884            }
885            path.pop();
886        }
887        true
888    }
889
890    let mut found = None;
891    if !visit(node, &mut path, &matches, &mut found) {
892        return Err(TargetError::Ambiguous(description));
893    }
894    found.ok_or(TargetError::Missing(description))
895}