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