Skip to main content

yog_kit/
host.rs

1//! The screen host: owns the view model, the view and the laid-out tree,
2//! runs binding updates and routes input. Used by [`crate::Screen`] (the
3//! game) and [`crate::testing::TestHost`] (tests) alike; nothing here needs
4//! a graphics context.
5
6use yog_api::ui::event::keys;
7use yog_api::ui::widget::WidgetKind;
8use yog_api::ui::{
9    Action, FlexDir, LayoutNode, Pointer, Rect, StateFlags, TextBoxEvent, UiEvent, UiRoot, Units,
10    Widget, layout, surface, widget,
11};
12
13use crate::screen::{self, Request};
14use crate::{Anchor, Cx, Parts, ScreenHandle, View, ViewEvent, ViewModel};
15
16/// Pixels per mouse-wheel notch.
17const WHEEL_STEP: f32 = 16.0;
18/// Rows PgUp/PgDn move in a list whose row height or viewport is unknown.
19const FALLBACK_PAGE: u32 = 5;
20/// [`Host::log`] entries for a close / back request.
21pub(crate) const LOG_CLOSE: &str = "close";
22const LOG_BACK: &str = "back";
23
24/// A scroller's visible window during an update.
25#[derive(Debug, Clone, Copy, Default, PartialEq)]
26pub struct Viewport {
27    /// Scroll offset (0 = top).
28    pub offset: f32,
29    /// Height of the scroller in the last layout (0 before the first).
30    pub height: f32,
31}
32
33/// What a [`View::update`] changed, plus what it can ask of the host.
34#[derive(Debug, Default)]
35pub struct Update {
36    pub(crate) relayout: bool,
37    pub(crate) repaint: bool,
38    pub(crate) viewports: Vec<Viewport>,
39    pub(crate) text_sets: Vec<(u16, String)>,
40    pub(crate) scroll_resets: Vec<u16>,
41    pub(crate) lists: Vec<(u16, u32, Option<u32>)>,
42}
43
44impl Update {
45    /// A standalone update (no scrollers) — for tests of generated views.
46    pub fn new() -> Self {
47        Self::default()
48    }
49    /// A change that may move or resize widgets.
50    pub fn relayout(&mut self) {
51        self.relayout = true;
52    }
53    /// A paint-only change.
54    pub fn repaint(&mut self) {
55        self.repaint = true;
56    }
57    pub fn needs_relayout(&self) -> bool {
58        self.relayout
59    }
60    pub fn needs_repaint(&self) -> bool {
61        self.repaint || self.relayout
62    }
63    /// The visible window of scroller `i`.
64    pub fn viewport(&self, scroller: u16) -> Viewport {
65        self.viewports
66            .get(scroller as usize)
67            .copied()
68            .unwrap_or_default()
69    }
70    /// Sets text box `slot`'s text (kept if it's already that, so the caret
71    /// doesn't jump while typing).
72    pub fn set_text_box(&mut self, slot: u16, text: &str) {
73        self.text_sets.push((slot, text.to_owned()));
74    }
75    /// Scrolls scroller `i` back to the top.
76    pub fn reset_scroll(&mut self, scroller: u16) {
77        self.scroll_resets.push(scroller);
78        self.relayout();
79    }
80    /// Records list `owner`'s item count and selected index.
81    pub fn list_info(&mut self, owner: u16, len: u32, selected: Option<u32>) {
82        self.lists.push((owner, len, selected));
83    }
84}
85
86/// Child-index path of the first widget tagged `id`.
87pub(crate) fn find_path(w: &Widget, id: &str) -> Option<Vec<u16>> {
88    if w.id.as_deref() == Some(id) {
89        return Some(Vec::new());
90    }
91    w.children.iter().enumerate().find_map(|(i, c)| {
92        find_path(c, id).map(|mut p| {
93            p.insert(0, i as u16);
94            p
95        })
96    })
97}
98
99fn with_root(path: &[u16]) -> Vec<u16> {
100    let mut p = Vec::with_capacity(path.len() + 1);
101    p.push(0);
102    p.extend_from_slice(path);
103    p
104}
105
106pub(crate) struct Host<W: View> {
107    pub(crate) vm: W::Vm,
108    view: W,
109    /// Root = a full-screen panel whose only child is the view's content.
110    pub(crate) ui: UiRoot,
111    pub(crate) parts: Parts,
112    pub(crate) size: (f32, f32),
113    pub(crate) dirty: bool,
114    /// Content-relative paths.
115    hover: Option<Vec<u16>>,
116    pressed: Option<Vec<u16>>,
117    focus: Option<Vec<u16>>,
118    /// The focus came from the keyboard (draw its outline).
119    focus_visible: bool,
120    outlined: Option<Vec<u16>>,
121    mouse: Option<(f32, f32)>,
122    /// The surface a button went down on (it gets the drags and the release).
123    captured: Option<Vec<u16>>,
124    /// The surface under the cursor (it gets `Move`s, then a `Leave`).
125    hovered_surface: Option<Vec<u16>>,
126    opened: bool,
127    reveal: Option<(u16, u32)>,
128    /// Viewports the last update saw.
129    seen_viewports: Vec<Viewport>,
130    pub(crate) handle: ScreenHandle<W::Vm>,
131    /// What the screen asked for (close, navigate, ...), for tests.
132    pub(crate) log: Vec<String>,
133    /// Calls `yog_api` for close/navigation (off in tests).
134    pub(crate) live: bool,
135}
136
137impl<W: View> Host<W> {
138    pub(crate) fn new(vm: W::Vm, handle: ScreenHandle<W::Vm>, live: bool) -> Self {
139        let (view, content, parts) = W::build();
140        let screen = widget::panel(FlexDir::Column).child(content);
141        Self {
142            vm,
143            view,
144            ui: UiRoot::new(W::META.id, screen),
145            parts,
146            size: (W::META.w, W::META.h),
147            dirty: true,
148            hover: None,
149            pressed: None,
150            focus: None,
151            focus_visible: false,
152            outlined: None,
153            mouse: None,
154            captured: None,
155            hovered_surface: None,
156            opened: false,
157            reveal: None,
158            seen_viewports: Vec::new(),
159            handle,
160            log: Vec::new(),
161            live,
162        }
163    }
164
165    pub(crate) fn content(&self) -> &Widget {
166        &self.ui.root.children[0]
167    }
168
169    fn node(&self, path: &[u16]) -> Option<&LayoutNode> {
170        layout::node_at(&self.ui.layout_root, &with_root(path))
171    }
172
173    pub(crate) fn content_node(&self, path: &[u16]) -> Option<&LayoutNode> {
174        self.node(path)
175    }
176
177    /// Content path of the clickable widget at `(x, y)`.
178    fn hit(&self, x: f32, y: f32) -> Option<Vec<u16>> {
179        let p = layout::hit_path(&self.ui.layout_root, x, y)?;
180        (p.first() == Some(&0)).then(|| p[1..].to_vec())
181    }
182
183    // ── view model calls ────────────────────────────────────────────────────
184
185    fn with_cx<R>(&mut self, f: impl FnOnce(&mut W::Vm, &mut W, &mut Cx<'_, W::Vm>) -> R) -> R {
186        let mut reqs = Vec::new();
187        let r = {
188            let mut cx = Cx::new(&mut reqs, &self.handle);
189            f(&mut self.vm, &mut self.view, &mut cx)
190        };
191        self.dirty = true;
192        for req in reqs {
193            self.request(req);
194        }
195        r
196    }
197
198    fn request(&mut self, req: Request) {
199        let id = W::META.id;
200        match req {
201            Request::Close => {
202                self.log.push(LOG_CLOSE.into());
203                if self.live {
204                    yog_api::close_ui(id);
205                }
206            }
207            Request::Navigate(to) => {
208                self.log.push(format!("navigate:{to}"));
209                if self.live {
210                    screen::navigate(id, &to);
211                }
212            }
213            Request::Back => {
214                self.log.push(LOG_BACK.into());
215                if !self.live || !screen::go_back() {
216                    self.request(Request::Close);
217                }
218            }
219            Request::Focus(wid) => {
220                if let Some(p) = find_path(self.content(), &wid) {
221                    self.set_focus(Some(p), true);
222                }
223            }
224            Request::Invalidate => self.dirty = true,
225        }
226    }
227
228    pub(crate) fn dispatch(&mut self, ev: ViewEvent) {
229        self.with_cx(|vm, view, cx| view.dispatch(vm, cx, ev));
230    }
231
232    fn open_vm(&mut self) {
233        self.opened = true;
234        self.reset_input();
235        self.with_cx(|vm, _, cx| vm.on_open(cx));
236    }
237
238    fn close_vm(&mut self) {
239        self.opened = false;
240        self.reset_input();
241        self.with_cx(|vm, _, cx| vm.on_close(cx));
242    }
243
244    fn reset_input(&mut self) {
245        self.hover = None;
246        self.pressed = None;
247        self.focus = None;
248        self.mouse = None;
249        for t in &mut self.parts.text_boxes {
250            t.state.blur();
251        }
252    }
253
254    pub(crate) fn drain_queue(&mut self) {
255        for job in self.handle.take_queue() {
256            job(&mut self.vm);
257            self.dirty = true;
258        }
259    }
260
261    // ── frame ───────────────────────────────────────────────────────────────
262
263    /// Brings the tree up to date and lays it out for a `sw` × `sh` GUI.
264    pub(crate) fn frame(&mut self, sw: f32, sh: f32) {
265        self.size = (sw, sh);
266        self.drain_queue();
267        // A keyboard reveal can scroll a virtualized list, which needs a
268        // second update for the rows that came into view.
269        for _ in 0..2 {
270            if self.dirty {
271                self.run_update();
272            }
273            self.apply_parts();
274            self.apply_states();
275            self.layout();
276            if !self.do_reveal() && !self.viewports_changed() {
277                break;
278            }
279        }
280    }
281
282    fn viewports(&self) -> Vec<Viewport> {
283        self.parts
284            .scrollers
285            .iter()
286            .map(|s| Viewport {
287                offset: s.state.offset,
288                height: self.node(&s.path).map_or(0.0, |n| n.rect.h),
289            })
290            .collect()
291    }
292
293    /// A virtualized list's scroller changed size since the last update
294    /// (e.g. the first layout) — its window must be recomputed.
295    fn viewports_changed(&mut self) -> bool {
296        let now = self.viewports();
297        let changed = self.parts.lists.iter().any(|l| {
298            let (Some(_), Some(s)) = (l.item_height, l.scroller) else {
299                return false;
300            };
301            let (a, b) = (self.seen_viewports.get(s as usize), now.get(s as usize));
302            a.map(|v| v.height) != b.map(|v| v.height)
303        });
304        if changed {
305            self.dirty = true;
306        }
307        changed
308    }
309
310    fn run_update(&mut self) {
311        let viewports = self.viewports();
312        self.seen_viewports.clone_from(&viewports);
313        let mut u = Update {
314            viewports,
315            ..Update::default()
316        };
317        let content = &mut self.ui.root.children[0];
318        self.view.update(content, &self.vm, &mut u);
319        self.vm.customize(content);
320        for (slot, text) in u.text_sets {
321            if let Some(t) = self.parts.text_boxes.get_mut(slot as usize)
322                && t.state.text() != text
323            {
324                t.state.set_text(text);
325            }
326        }
327        for s in u.scroll_resets {
328            if let Some(s) = self.parts.scrollers.get_mut(s as usize) {
329                s.state.reset();
330            }
331        }
332        for (owner, len, selected) in u.lists {
333            if let Some(l) = self.parts.lists.iter_mut().find(|l| l.owner == owner) {
334                l.len = len;
335                l.selected = selected;
336            }
337        }
338        self.dirty = false;
339    }
340
341    fn apply_parts(&mut self) {
342        let content = &mut self.ui.root.children[0];
343        for s in &self.parts.scrollers {
344            if let Some(w) = content.get_path_mut(&s.path) {
345                w.style.scroll_y = s.state.offset;
346            }
347        }
348        for t in &mut self.parts.text_boxes {
349            if let Some(w) = content.get_path_mut(&t.path) {
350                t.state.apply(w);
351            }
352        }
353    }
354
355    fn apply_states(&mut self) {
356        let content = &mut self.ui.root.children[0];
357        content.clear_state_deep(StateFlags::HOVER | StateFlags::PRESSED | StateFlags::FOCUSED);
358        if let Some(p) = self.outlined.take()
359            && let Some(w) = content.get_path_mut(&p)
360        {
361            w.focused = false;
362        }
363        for (path, flag) in [
364            (&self.hover, StateFlags::HOVER),
365            (&self.pressed, StateFlags::PRESSED),
366            (&self.focus, StateFlags::FOCUSED),
367        ] {
368            if let Some(w) = path.as_deref().and_then(|p| content.get_path_mut(p)) {
369                w.set_state_inherited(flag, true);
370            }
371        }
372        if self.focus_visible
373            && let Some(p) = &self.focus
374            && let Some(w) = content.get_path_mut(p)
375            && w.is_interactive()
376        {
377            w.focused = true;
378            self.outlined = Some(p.clone());
379        }
380    }
381
382    fn layout(&mut self) {
383        let (sw, sh) = self.size;
384        let m = W::META;
385        let root = &mut self.ui.root;
386        root.style.w = Units::Px(sw);
387        root.style.h = Units::Px(sh);
388        let c = &mut root.children[0];
389        if m.anchor == Anchor::Fill {
390            c.style.w = Units::Percent(100.0);
391            c.style.h = Units::Percent(100.0);
392            c.style.pos = Some((0.0, 0.0));
393        } else {
394            c.style.w = Units::Px(m.w);
395            c.style.h = Units::Px(m.h);
396            c.style.pos = Some(m.anchor.place(sw, sh, m.w, m.h));
397        }
398        self.ui.layout(sw, sh);
399    }
400
401    /// Scrolls a list so the item asked for is visible; `true` when the
402    /// offset changed.
403    fn do_reveal(&mut self) -> bool {
404        let Some((owner, index)) = self.reveal.take() else {
405            return false;
406        };
407        let Some(list) = self.parts.lists.iter().find(|l| l.owner == owner) else {
408            return false;
409        };
410        let Some(si) = list.scroller else {
411            return false;
412        };
413        let Some(scroller) = self.parts.scrollers.get(si as usize) else {
414            return false;
415        };
416        let (Some(view), Some(items)) = (self.node(&scroller.path), self.node(&list.path)) else {
417            return false;
418        };
419        let found = items.children.iter().find(|c| {
420            c.action
421                .is_some_and(|a| a.owner == owner && a.index == index)
422        });
423        let (top, h) = match (found, list.item_height) {
424            (Some(n), _) => (n.rect.y - view.rect.y + view.scroll_y, n.rect.h),
425            (None, Some(ih)) => {
426                let w = self.content().get_path(&list.path);
427                let (gap, pad) = w.map_or((0.0, 0.0), |w| (w.style.gap, w.style.pad[0]));
428                (pad + index as f32 * (ih + gap), ih)
429            }
430            (None, None) => return false,
431        };
432        let (view_h, max) = (view.rect.h, view.max_scroll());
433        let state = &mut self.parts.scrollers[si as usize].state;
434        let before = state.offset;
435        state.scroll_into_view(top, h, view_h);
436        state.offset = state.offset.clamp(0.0, max.max(0.0));
437        if (state.offset - before).abs() > f32::EPSILON {
438            self.dirty = true;
439            true
440        } else {
441            false
442        }
443    }
444
445    // ── input ───────────────────────────────────────────────────────────────
446
447    /// Handles one raw UI event; `true` = consumed.
448    pub(crate) fn on_event(&mut self, raw: &str) -> bool {
449        self.drain_queue();
450        let ev = UiEvent::parse(raw);
451        match ev {
452            UiEvent::Open { w, h } => {
453                self.size = (w, h);
454                if self.opened {
455                    self.close_vm();
456                }
457                self.open_vm();
458                false
459            }
460            UiEvent::Close => {
461                self.captured = None;
462                self.leave_surface();
463                if self.opened {
464                    self.close_vm();
465                }
466                if self.live {
467                    screen::screen_closed();
468                }
469                false
470            }
471            UiEvent::Move { x, y } => {
472                self.mouse = Some((x, y));
473                self.hover = self.hit(x, y);
474                let under = self.surface_at(x, y);
475                if under != self.hovered_surface {
476                    self.leave_surface();
477                    self.hovered_surface = under.clone();
478                }
479                under.is_some_and(|p| self.to_surface(&p, x, y, |x, y| Pointer::Move { x, y }))
480            }
481            UiEvent::Scroll { .. } => self.scroll(&ev),
482            UiEvent::Click { x, y } => self.click(x, y, &ev),
483            UiEvent::Drag { x, y } | UiEvent::Release { x, y } if self.captured.is_some() => {
484                let release = matches!(ev, UiEvent::Release { .. });
485                let path = if release {
486                    self.pressed = None;
487                    self.captured.take()
488                } else {
489                    self.captured.clone()
490                };
491                if let Some(path) = path {
492                    self.to_surface(&path, x, y, |x, y| {
493                        if release {
494                            Pointer::Up { x, y }
495                        } else {
496                            Pointer::Drag { x, y }
497                        }
498                    });
499                }
500                true
501            }
502            UiEvent::Drag { .. } | UiEvent::Release { .. } => {
503                if matches!(ev, UiEvent::Release { .. }) {
504                    self.pressed = None;
505                }
506                let used = self.feed_scrollers(&ev, false);
507                self.feed_text_boxes(&ev).is_some() | used
508            }
509            UiEvent::Key { key, mods } => self.key(key, mods, &ev),
510            UiEvent::Char(_) => self.text_input(&ev),
511            UiEvent::Other(_) => false,
512        }
513    }
514
515    fn scroll(&mut self, ev: &UiEvent<'_>) -> bool {
516        // A surface under the cursor gets the wheel first.
517        if let (Some((x, y)), UiEvent::Scroll { dy }) = (self.mouse, ev)
518            && let Some((s, r)) = self.surface_at(x, y).and_then(|p| self.surface_box(&p))
519            && s.scroll(*dy, (r.w, r.h))
520        {
521            return true;
522        }
523        let under = self
524            .mouse
525            .and_then(|(x, y)| layout::deepest_path(&self.ui.layout_root, x, y))
526            .filter(|p| p.first() == Some(&0))
527            .map(|p| p[1..].to_vec());
528        let target = under
529            .and_then(|p| {
530                self.parts
531                    .scrollers
532                    .iter()
533                    .enumerate()
534                    .filter(|(_, s)| p.starts_with(&s.path))
535                    .max_by_key(|(_, s)| s.path.len())
536                    .map(|(i, _)| i)
537            })
538            .or_else(|| {
539                self.focused_list()
540                    .and_then(|l| l.scroller.map(usize::from))
541            })
542            .or_else(|| (!self.parts.scrollers.is_empty()).then_some(0));
543        let Some(i) = target else {
544            return false;
545        };
546        let s = &mut self.parts.scrollers[i];
547        let Some(node) = layout::node_at(&self.ui.layout_root, &with_root(&s.path)) else {
548            return false;
549        };
550        s.state.handle_event(ev, node, WHEEL_STEP);
551        self.dirty = true;
552        true
553    }
554
555    fn click(&mut self, x: f32, y: f32, ev: &UiEvent<'_>) -> bool {
556        self.mouse = Some((x, y));
557        self.hover = self.hit(x, y);
558        if self.feed_scrollers(ev, true) {
559            return true;
560        }
561        if let Some(i) = self.feed_text_boxes(ev) {
562            self.focus = Some(self.parts.text_boxes[i].path.clone());
563            self.focus_visible = false;
564            return true;
565        }
566        if let Some(path) = self.surface_at(x, y)
567            && self.to_surface(&path, x, y, |x, y| Pointer::Down { x, y })
568        {
569            self.captured = Some(path);
570            self.focus = None;
571            return true;
572        }
573        let Some(path) = self.hit(x, y) else {
574            self.focus = None;
575            return false;
576        };
577        self.pressed = Some(path.clone());
578        self.focus = self
579            .parts
580            .lists
581            .iter()
582            .filter(|l| l.scroller.is_some() && path.starts_with(&l.path))
583            .max_by_key(|l| l.path.len())
584            .map(|l| l.path.clone());
585        self.focus_visible = false;
586        self.activate(&path);
587        true
588    }
589
590    /// Feeds a pointer event to the scrollers (stopping at the first taker
591    /// when `first`); true if any used it.
592    fn feed_scrollers(&mut self, ev: &UiEvent<'_>, first: bool) -> bool {
593        let root = &self.ui.layout_root;
594        let mut used = false;
595        for s in &mut self.parts.scrollers {
596            let Some(node) = layout::node_at(root, &with_root(&s.path)) else {
597                continue;
598            };
599            if s.state.handle_event(ev, node, WHEEL_STEP) {
600                used = true;
601                if first {
602                    break;
603                }
604            }
605        }
606        self.dirty |= used;
607        used
608    }
609
610    /// Feeds a pointer event to every text box; the last one that took it.
611    fn feed_text_boxes(&mut self, ev: &UiEvent<'_>) -> Option<usize> {
612        let root = &self.ui.layout_root;
613        let mut taker = None;
614        for (i, b) in self.parts.text_boxes.iter_mut().enumerate() {
615            let Some(node) = layout::node_at(root, &with_root(&b.path)) else {
616                continue;
617            };
618            if b.state.handle_event(ev, node).consumed() {
619                taker = Some(i);
620            }
621        }
622        taker
623    }
624
625    // ── surfaces ────────────────────────────────────────────────────────────
626
627    /// Content path of the enabled surface under `(x, y)`: the deepest node
628    /// there or its nearest surface ancestor.
629    fn surface_at(&self, x: f32, y: f32) -> Option<Vec<u16>> {
630        let p = layout::deepest_path(&self.ui.layout_root, x, y)?;
631        if p.first() != Some(&0) {
632            return None;
633        }
634        let mut p = p[1..].to_vec();
635        loop {
636            if let Some(w) = self.content().get_path(&p)
637                && matches!(w.kind, WidgetKind::Surface(_))
638                && w.enabled
639                && w.visible
640            {
641                return Some(p);
642            }
643            p.pop()?;
644        }
645    }
646
647    /// The surface at `path` and its content box (rect less padding).
648    fn surface_box(
649        &self,
650        path: &[u16],
651    ) -> Option<(std::sync::Arc<dyn yog_api::ui::Surface>, Rect)> {
652        let w = self.content().get_path(path)?;
653        let WidgetKind::Surface(id) = &w.kind else {
654            return None;
655        };
656        let rect = self.node(path)?.rect.inset(w.effective_style().pad);
657        Some((surface::get(id)?, rect))
658    }
659
660    /// Hands the surface at `path` a pointer event at screen `(x, y)`.
661    fn to_surface(
662        &self,
663        path: &[u16],
664        x: f32,
665        y: f32,
666        ev: impl FnOnce(f32, f32) -> Pointer,
667    ) -> bool {
668        match self.surface_box(path) {
669            Some((s, r)) => s.pointer(ev(x - r.x, y - r.y), (r.w, r.h)),
670            None => false,
671        }
672    }
673
674    /// Tells the hovered surface the cursor left it.
675    fn leave_surface(&mut self) {
676        if let Some(path) = self.hovered_surface.take()
677            && let Some((s, r)) = self.surface_box(&path)
678        {
679            s.pointer(Pointer::Leave, (r.w, r.h));
680        }
681    }
682
683    /// Runs the action of the widget at `path`.
684    fn activate(&mut self, path: &[u16]) {
685        let Some(w) = self.content().get_path(path) else {
686            return;
687        };
688        if !w.enabled || !w.visible {
689            return;
690        }
691        if let Some(a) = w.action {
692            if a.slot == Action::SELECT {
693                self.reveal = Some((a.owner, a.index));
694            }
695            self.dispatch(ViewEvent::Action(a));
696        }
697    }
698
699    fn focused_box(&self) -> Option<usize> {
700        self.parts
701            .text_boxes
702            .iter()
703            .position(|t| t.state.is_focused())
704    }
705
706    fn focused_list(&self) -> Option<&crate::ListPart> {
707        let f = self.focus.as_ref()?;
708        self.parts.lists.iter().find(|l| &l.path == f)
709    }
710
711    /// Feeds a key/char event to the focused text box.
712    fn text_input(&mut self, ev: &UiEvent<'_>) -> bool {
713        let Some(i) = self.focused_box() else {
714            return false;
715        };
716        let b = &mut self.parts.text_boxes[i];
717        let Some(node) = layout::node_at(&self.ui.layout_root, &with_root(&b.path)) else {
718            return false;
719        };
720        let r = b.state.handle_event(ev, node);
721        let text = || self.parts.text_boxes[i].state.text().to_owned();
722        match r {
723            TextBoxEvent::Changed => {
724                let text = text();
725                self.dispatch(ViewEvent::TextChanged {
726                    slot: i as u16,
727                    text,
728                });
729            }
730            TextBoxEvent::Submitted => {
731                let text = text();
732                self.dispatch(ViewEvent::TextSubmitted {
733                    slot: i as u16,
734                    text,
735                });
736            }
737            _ => {}
738        }
739        if !self.parts.text_boxes[i].state.is_focused() {
740            self.focus = None;
741        }
742        r.consumed()
743    }
744
745    fn key(&mut self, key: i32, mods: i32, ev: &UiEvent<'_>) -> bool {
746        if key == keys::TAB {
747            self.cycle_focus(mods & keys::MOD_SHIFT != 0);
748            return true;
749        }
750        if self.focused_box().is_some() {
751            return self.text_input(ev);
752        }
753        match key {
754            keys::ESCAPE => {
755                if self.with_cx(|vm, _, cx| vm.on_back(cx)) {
756                    return true;
757                }
758                if self.live && screen::go_back() {
759                    self.log.push(LOG_BACK.into());
760                    return true;
761                }
762                false
763            }
764            keys::ENTER | keys::KP_ENTER | keys::SPACE => {
765                let Some(p) = self.focus.clone() else {
766                    return false;
767                };
768                if self
769                    .content()
770                    .get_path(&p)
771                    .is_some_and(|w| w.is_interactive())
772                {
773                    self.activate(&p);
774                    return true;
775                }
776                false
777            }
778            keys::UP | keys::DOWN | keys::PAGE_UP | keys::PAGE_DOWN | keys::HOME | keys::END => {
779                self.list_key(key)
780            }
781            _ => false,
782        }
783    }
784
785    /// Up/Down/PgUp/PgDn/Home/End in the focused list (else the first).
786    fn list_key(&mut self, key: i32) -> bool {
787        let list = self
788            .focused_list()
789            .or_else(|| self.parts.lists.iter().find(|l| l.scroller.is_some()));
790        let Some(list) = list.cloned() else {
791            return false;
792        };
793        if list.len == 0 {
794            return true;
795        }
796        let last = list.len - 1;
797        let page = match (list.item_height, list.scroller) {
798            (Some(ih), Some(s)) => {
799                let view_h = self
800                    .parts
801                    .scrollers
802                    .get(s as usize)
803                    .and_then(|s| self.node(&s.path))
804                    .map_or(0.0, |n| n.rect.h);
805                ((view_h / ih.max(1.0)) as u32).max(1)
806            }
807            _ => FALLBACK_PAGE,
808        };
809        let new = match (key, list.selected) {
810            (keys::HOME, _) => 0,
811            (keys::END, _) => last,
812            (_, None) => 0,
813            (keys::UP, Some(i)) => i.saturating_sub(1),
814            (keys::DOWN, Some(i)) => (i + 1).min(last),
815            (keys::PAGE_UP, Some(i)) => i.saturating_sub(page),
816            (_, Some(i)) => (i + page).min(last),
817        };
818        if list.selected != Some(new) {
819            self.dispatch(ViewEvent::Select {
820                list: list.owner,
821                index: new,
822            });
823        }
824        self.reveal = Some((list.owner, new));
825        if self.focus.is_none() {
826            self.focus = Some(list.path.clone());
827        }
828        true
829    }
830
831    fn set_focus(&mut self, path: Option<Vec<u16>>, visible: bool) {
832        for t in &mut self.parts.text_boxes {
833            t.state.blur();
834        }
835        if let Some(p) = &path
836            && let Some(t) = self.parts.text_boxes.iter_mut().find(|t| &t.path == p)
837        {
838            t.state.focus();
839        }
840        self.focus = path;
841        self.focus_visible = visible;
842    }
843
844    /// Tab / Shift+Tab through the visible, enabled focusables.
845    fn cycle_focus(&mut self, back: bool) {
846        let n = self.parts.focusables.len();
847        if n == 0 {
848            return;
849        }
850        let cur = self
851            .focus
852            .as_ref()
853            .and_then(|f| self.parts.focusables.iter().position(|p| p == f));
854        for step in 1..=n {
855            let i = match (cur, back) {
856                (None, false) => step - 1,
857                (None, true) => n - step,
858                (Some(c), false) => (c + step) % n,
859                (Some(c), true) => (c + n - step % n) % n,
860            };
861            let p = &self.parts.focusables[i];
862            if self
863                .node(p)
864                .is_some_and(|n| n.visible && n.enabled && n.rect.w > 0.0)
865            {
866                let p = p.clone();
867                self.set_focus(Some(p), true);
868                return;
869            }
870        }
871    }
872}