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 since the last update
299    /// (e.g. the first layout) — its window must be recomputed.
300    fn viewports_changed(&mut self) -> bool {
301        let now = self.viewports();
302        let changed = self.parts.lists.iter().any(|l| {
303            let (Some(_), Some(s)) = (l.item_height, l.scroller) else {
304                return false;
305            };
306            let (a, b) = (self.seen_viewports.get(s as usize), now.get(s as usize));
307            a.map(|v| v.height) != b.map(|v| v.height)
308        });
309        if changed {
310            self.dirty = true;
311        }
312        changed
313    }
314
315    fn run_update(&mut self) {
316        let viewports = self.viewports();
317        self.seen_viewports.clone_from(&viewports);
318        let mut u = Update {
319            viewports,
320            ..Update::default()
321        };
322        let content = &mut self.ui.root.children[0];
323        self.view.update(content, &self.vm, &mut u);
324        self.vm.customize(content);
325        for (slot, text) in u.text_sets {
326            if let Some(t) = self.parts.text_boxes.get_mut(slot as usize)
327                && t.state.text() != text
328            {
329                t.state.set_text(text);
330            }
331        }
332        for s in u.scroll_resets {
333            if let Some(s) = self.parts.scrollers.get_mut(s as usize) {
334                s.state.reset();
335            }
336        }
337        for (owner, len, selected) in u.lists {
338            if let Some(l) = self.parts.lists.iter_mut().find(|l| l.owner == owner) {
339                l.len = len;
340                l.selected = selected;
341            }
342        }
343        self.dirty = false;
344    }
345
346    fn apply_parts(&mut self) {
347        let content = &mut self.ui.root.children[0];
348        for s in &self.parts.scrollers {
349            if let Some(w) = content.get_path_mut(&s.path) {
350                w.style.scroll_y = s.state.offset;
351            }
352        }
353        for t in &mut self.parts.text_boxes {
354            if let Some(w) = content.get_path_mut(&t.path) {
355                t.state.apply(w);
356            }
357        }
358    }
359
360    fn apply_states(&mut self) {
361        let content = &mut self.ui.root.children[0];
362        content.clear_state_deep(StateFlags::HOVER | StateFlags::PRESSED | StateFlags::FOCUSED);
363        if let Some(p) = self.outlined.take()
364            && let Some(w) = content.get_path_mut(&p)
365        {
366            w.focused = false;
367        }
368        for (path, flag) in [
369            (&self.hover, StateFlags::HOVER),
370            (&self.pressed, StateFlags::PRESSED),
371            (&self.focus, StateFlags::FOCUSED),
372        ] {
373            if let Some(w) = path.as_deref().and_then(|p| content.get_path_mut(p)) {
374                w.set_state_inherited(flag, true);
375            }
376        }
377        if self.focus_visible
378            && let Some(p) = &self.focus
379            && let Some(w) = content.get_path_mut(p)
380            && w.is_interactive()
381        {
382            w.focused = true;
383            self.outlined = Some(p.clone());
384        }
385    }
386
387    fn layout(&mut self) {
388        let (sw, sh) = self.size;
389        let m = W::META;
390        let root = &mut self.ui.root;
391        root.style.w = Units::Px(sw);
392        root.style.h = Units::Px(sh);
393        let c = &mut root.children[0];
394        if m.anchor == Anchor::Fill {
395            c.style.w = Units::Percent(100.0);
396            c.style.h = Units::Percent(100.0);
397            c.style.pos = Some((0.0, 0.0));
398        } else {
399            c.style.w = Units::Px(m.w);
400            c.style.h = Units::Px(m.h);
401            c.style.pos = Some(m.anchor.place(sw, sh, m.w, m.h));
402        }
403        self.ui.layout(sw, sh);
404    }
405
406    /// Scrolls a list so the item asked for is visible; `true` when the
407    /// offset changed.
408    fn do_reveal(&mut self) -> bool {
409        let Some((owner, index)) = self.reveal.take() else {
410            return false;
411        };
412        let Some(list) = self.parts.lists.iter().find(|l| l.owner == owner) else {
413            return false;
414        };
415        let Some(si) = list.scroller else {
416            return false;
417        };
418        let Some(scroller) = self.parts.scrollers.get(si as usize) else {
419            return false;
420        };
421        let (Some(view), Some(items)) = (self.node(&scroller.path), self.node(&list.path)) else {
422            return false;
423        };
424        let found = items.children.iter().find(|c| {
425            c.action
426                .is_some_and(|a| a.owner == owner && a.index == index)
427        });
428        let (top, h) = match (found, list.item_height) {
429            (Some(n), _) => (n.rect.y - view.rect.y + view.scroll_y, n.rect.h),
430            (None, Some(ih)) => {
431                let w = self.content().get_path(&list.path);
432                let (gap, pad) = w.map_or((0.0, 0.0), |w| (w.style.gap, w.style.pad[0]));
433                (pad + index as f32 * (ih + gap), ih)
434            }
435            (None, None) => return false,
436        };
437        let (view_h, max) = (view.rect.h, view.max_scroll());
438        let state = &mut self.parts.scrollers[si as usize].state;
439        let before = state.offset;
440        state.scroll_into_view(top, h, view_h);
441        state.offset = state.offset.clamp(0.0, max.max(0.0));
442        if (state.offset - before).abs() > f32::EPSILON {
443            self.dirty = true;
444            true
445        } else {
446            false
447        }
448    }
449
450    // ── input ───────────────────────────────────────────────────────────────
451
452    /// Handles one raw UI event; `true` = consumed.
453    pub(crate) fn on_event(&mut self, raw: &str) -> bool {
454        self.drain_queue();
455        let ev = UiEvent::parse(raw);
456        match ev {
457            UiEvent::Open { w, h } => {
458                self.size = (w, h);
459                if self.opened {
460                    self.close_vm();
461                }
462                self.open_vm();
463                false
464            }
465            UiEvent::Close => {
466                self.captured = None;
467                self.leave_surface();
468                if self.opened {
469                    self.close_vm();
470                }
471                if self.live {
472                    screen::screen_closed();
473                }
474                false
475            }
476            UiEvent::Move { x, y } => {
477                self.mouse = Some((x, y));
478                self.hover = self.hit(x, y);
479                let under = self.surface_at(x, y);
480                if under != self.hovered_surface {
481                    self.leave_surface();
482                    self.hovered_surface = under.clone();
483                }
484                under.is_some_and(|p| self.to_surface(&p, x, y, |x, y| Pointer::Move { x, y }))
485            }
486            UiEvent::Scroll { .. } => self.scroll(&ev),
487            UiEvent::Click { x, y } => self.click(x, y, &ev),
488            UiEvent::Drag { x, y } | UiEvent::Release { x, y } if self.captured.is_some() => {
489                let release = matches!(ev, UiEvent::Release { .. });
490                let path = if release {
491                    self.pressed = None;
492                    self.captured.take()
493                } else {
494                    self.captured.clone()
495                };
496                if let Some(path) = path {
497                    self.to_surface(&path, x, y, |x, y| {
498                        if release {
499                            Pointer::Up { x, y }
500                        } else {
501                            Pointer::Drag { x, y }
502                        }
503                    });
504                }
505                true
506            }
507            UiEvent::Drag { .. } | UiEvent::Release { .. } => {
508                if matches!(ev, UiEvent::Release { .. }) {
509                    self.pressed = None;
510                }
511                let used = self.feed_scrollers(&ev, false);
512                self.feed_text_boxes(&ev).is_some() | used
513            }
514            UiEvent::Key { key, mods } => self.key(key, mods, &ev),
515            UiEvent::Char(_) => self.text_input(&ev),
516            UiEvent::Other(_) => false,
517        }
518    }
519
520    fn scroll(&mut self, ev: &UiEvent<'_>) -> bool {
521        // A surface under the cursor gets the wheel first.
522        if let (Some((x, y)), UiEvent::Scroll { dy }) = (self.mouse, ev)
523            && let Some((s, r)) = self.surface_at(x, y).and_then(|p| self.surface_box(&p))
524            && s.scroll(*dy, (r.w, r.h))
525        {
526            return true;
527        }
528        let under = self
529            .mouse
530            .and_then(|(x, y)| layout::deepest_path(&self.ui.layout_root, x, y))
531            .filter(|p| p.first() == Some(&0))
532            .map(|p| p[1..].to_vec());
533        let target = under
534            .and_then(|p| {
535                self.parts
536                    .scrollers
537                    .iter()
538                    .enumerate()
539                    .filter(|(_, s)| p.starts_with(&s.path))
540                    .max_by_key(|(_, s)| s.path.len())
541                    .map(|(i, _)| i)
542            })
543            .or_else(|| {
544                self.focused_list()
545                    .and_then(|l| l.scroller.map(usize::from))
546            })
547            .or_else(|| (!self.parts.scrollers.is_empty()).then_some(0));
548        let Some(i) = target else {
549            return false;
550        };
551        let s = &mut self.parts.scrollers[i];
552        let Some(node) = layout::node_at(&self.ui.layout_root, &with_root(&s.path)) else {
553            return false;
554        };
555        s.state.handle_event(ev, node, WHEEL_STEP);
556        self.dirty = true;
557        true
558    }
559
560    fn click(&mut self, x: f32, y: f32, ev: &UiEvent<'_>) -> bool {
561        self.mouse = Some((x, y));
562        self.hover = self.hit(x, y);
563        if self.feed_scrollers(ev, true) {
564            return true;
565        }
566        if let Some(i) = self.feed_text_boxes(ev) {
567            self.focus = Some(self.parts.text_boxes[i].path.clone());
568            self.focus_visible = false;
569            return true;
570        }
571        if let Some(path) = self.surface_at(x, y)
572            && self.to_surface(&path, x, y, |x, y| Pointer::Down { x, y })
573        {
574            self.captured = Some(path);
575            self.focus = None;
576            return true;
577        }
578        let Some(path) = self.hit(x, y) else {
579            self.focus = None;
580            return false;
581        };
582        self.pressed = Some(path.clone());
583        self.focus = self
584            .parts
585            .lists
586            .iter()
587            .filter(|l| l.scroller.is_some() && path.starts_with(&l.path))
588            .max_by_key(|l| l.path.len())
589            .map(|l| l.path.clone());
590        self.focus_visible = false;
591        self.activate(&path);
592        true
593    }
594
595    /// Feeds a pointer event to the scrollers (stopping at the first taker
596    /// when `first`); true if any used it.
597    fn feed_scrollers(&mut self, ev: &UiEvent<'_>, first: bool) -> bool {
598        let root = &self.ui.layout_root;
599        let mut used = false;
600        for s in &mut self.parts.scrollers {
601            let Some(node) = layout::node_at(root, &with_root(&s.path)) else {
602                continue;
603            };
604            if s.state.handle_event(ev, node, WHEEL_STEP) {
605                used = true;
606                if first {
607                    break;
608                }
609            }
610        }
611        self.dirty |= used;
612        used
613    }
614
615    /// Feeds a pointer event to every text box; the last one that took it.
616    fn feed_text_boxes(&mut self, ev: &UiEvent<'_>) -> Option<usize> {
617        let root = &self.ui.layout_root;
618        let mut taker = None;
619        for (i, b) in self.parts.text_boxes.iter_mut().enumerate() {
620            let Some(node) = layout::node_at(root, &with_root(&b.path)) else {
621                continue;
622            };
623            if b.state.handle_event(ev, node).consumed() {
624                taker = Some(i);
625            }
626        }
627        taker
628    }
629
630    // ── surfaces ────────────────────────────────────────────────────────────
631
632    /// Content path of the enabled surface under `(x, y)`: the deepest node
633    /// there or its nearest surface ancestor.
634    fn surface_at(&self, x: f32, y: f32) -> Option<Vec<u16>> {
635        let p = layout::deepest_path(&self.ui.layout_root, x, y)?;
636        if p.first() != Some(&0) {
637            return None;
638        }
639        let mut p = p[1..].to_vec();
640        loop {
641            if let Some(w) = self.content().get_path(&p)
642                && matches!(w.kind, WidgetKind::Surface(_))
643                && w.enabled
644                && w.visible
645            {
646                return Some(p);
647            }
648            p.pop()?;
649        }
650    }
651
652    /// The surface at `path` and its content box (rect less padding).
653    fn surface_box(
654        &self,
655        path: &[u16],
656    ) -> Option<(std::sync::Arc<dyn yog_api::ui::Surface>, Rect)> {
657        let w = self.content().get_path(path)?;
658        let WidgetKind::Surface(id) = &w.kind else {
659            return None;
660        };
661        let rect = self.node(path)?.rect.inset(w.effective_style().pad);
662        Some((surface::get(id)?, rect))
663    }
664
665    /// Hands the surface at `path` a pointer event at screen `(x, y)`.
666    fn to_surface(
667        &self,
668        path: &[u16],
669        x: f32,
670        y: f32,
671        ev: impl FnOnce(f32, f32) -> Pointer,
672    ) -> bool {
673        match self.surface_box(path) {
674            Some((s, r)) => s.pointer(ev(x - r.x, y - r.y), (r.w, r.h)),
675            None => false,
676        }
677    }
678
679    /// Tells the hovered surface the cursor left it.
680    fn leave_surface(&mut self) {
681        if let Some(path) = self.hovered_surface.take()
682            && let Some((s, r)) = self.surface_box(&path)
683        {
684            s.pointer(Pointer::Leave, (r.w, r.h));
685        }
686    }
687
688    /// Runs the action of the widget at `path`.
689    fn activate(&mut self, path: &[u16]) {
690        let Some(w) = self.content().get_path(path) else {
691            return;
692        };
693        if !w.enabled || !w.visible {
694            return;
695        }
696        if let Some(a) = w.action {
697            if a.slot == Action::SELECT {
698                self.reveal = Some((a.owner, a.index));
699            }
700            self.dispatch(ViewEvent::Action(a));
701        }
702    }
703
704    fn focused_box(&self) -> Option<usize> {
705        self.parts
706            .text_boxes
707            .iter()
708            .position(|t| t.state.is_focused())
709    }
710
711    fn focused_list(&self) -> Option<&crate::ListPart> {
712        let f = self.focus.as_ref()?;
713        self.parts.lists.iter().find(|l| &l.path == f)
714    }
715
716    /// Feeds a key/char event to the focused text box.
717    fn text_input(&mut self, ev: &UiEvent<'_>) -> bool {
718        let Some(i) = self.focused_box() else {
719            return false;
720        };
721        let b = &mut self.parts.text_boxes[i];
722        let Some(node) = layout::node_at(&self.ui.layout_root, &with_root(&b.path)) else {
723            return false;
724        };
725        let r = b.state.handle_event(ev, node);
726        let text = || self.parts.text_boxes[i].state.text().to_owned();
727        match r {
728            TextBoxEvent::Changed => {
729                let text = text();
730                self.dispatch(ViewEvent::TextChanged {
731                    slot: i as u16,
732                    text,
733                });
734            }
735            TextBoxEvent::Submitted => {
736                let text = text();
737                self.dispatch(ViewEvent::TextSubmitted {
738                    slot: i as u16,
739                    text,
740                });
741            }
742            _ => {}
743        }
744        if !self.parts.text_boxes[i].state.is_focused() {
745            self.focus = None;
746        }
747        r.consumed()
748    }
749
750    fn key(&mut self, key: i32, mods: i32, ev: &UiEvent<'_>) -> bool {
751        if key == keys::TAB {
752            self.cycle_focus(mods & keys::MOD_SHIFT != 0);
753            return true;
754        }
755        if self.focused_box().is_some() {
756            return self.text_input(ev);
757        }
758        match key {
759            keys::ESCAPE => {
760                if self.with_cx(|vm, _, cx| vm.on_back(cx)) {
761                    return true;
762                }
763                if self.live && screen::go_back() {
764                    self.log.push(LOG_BACK.into());
765                    return true;
766                }
767                false
768            }
769            keys::ENTER | keys::KP_ENTER | keys::SPACE => {
770                let Some(p) = self.focus.clone() else {
771                    return false;
772                };
773                if self
774                    .content()
775                    .get_path(&p)
776                    .is_some_and(|w| w.is_interactive())
777                {
778                    self.activate(&p);
779                    return true;
780                }
781                false
782            }
783            keys::UP | keys::DOWN | keys::PAGE_UP | keys::PAGE_DOWN | keys::HOME | keys::END => {
784                self.list_key(key)
785            }
786            _ => false,
787        }
788    }
789
790    /// Up/Down/PgUp/PgDn/Home/End in the focused list (else the first).
791    fn list_key(&mut self, key: i32) -> bool {
792        let list = self
793            .focused_list()
794            .or_else(|| self.parts.lists.iter().find(|l| l.scroller.is_some()));
795        let Some(list) = list.cloned() else {
796            return false;
797        };
798        if list.len == 0 {
799            return true;
800        }
801        let last = list.len - 1;
802        let page = match (list.item_height, list.scroller) {
803            (Some(ih), Some(s)) => {
804                let view_h = self
805                    .parts
806                    .scrollers
807                    .get(s as usize)
808                    .and_then(|s| self.node(&s.path))
809                    .map_or(0.0, |n| n.rect.h);
810                ((view_h / ih.max(1.0)) as u32).max(1)
811            }
812            _ => FALLBACK_PAGE,
813        };
814        let new = match (key, list.selected) {
815            (keys::HOME, _) => 0,
816            (keys::END, _) => last,
817            (_, None) => 0,
818            (keys::UP, Some(i)) => i.saturating_sub(1),
819            (keys::DOWN, Some(i)) => (i + 1).min(last),
820            (keys::PAGE_UP, Some(i)) => i.saturating_sub(page),
821            (_, Some(i)) => (i + page).min(last),
822        };
823        if list.selected != Some(new) {
824            self.dispatch(ViewEvent::Select {
825                list: list.owner,
826                index: new,
827            });
828        }
829        self.reveal = Some((list.owner, new));
830        if self.focus.is_none() {
831            self.focus = Some(list.path.clone());
832        }
833        true
834    }
835
836    fn set_focus(&mut self, path: Option<Vec<u16>>, visible: bool) {
837        for t in &mut self.parts.text_boxes {
838            t.state.blur();
839        }
840        if let Some(p) = &path
841            && let Some(t) = self.parts.text_boxes.iter_mut().find(|t| &t.path == p)
842        {
843            t.state.focus();
844        }
845        self.focus = path;
846        self.focus_visible = visible;
847    }
848
849    /// Tab / Shift+Tab through the visible, enabled focusables.
850    fn cycle_focus(&mut self, back: bool) {
851        let n = self.parts.focusables.len();
852        if n == 0 {
853            return;
854        }
855        let cur = self
856            .focus
857            .as_ref()
858            .and_then(|f| self.parts.focusables.iter().position(|p| p == f));
859        for step in 1..=n {
860            let i = match (cur, back) {
861                (None, false) => step - 1,
862                (None, true) => n - step,
863                (Some(c), false) => (c + step) % n,
864                (Some(c), true) => (c + n - step % n) % n,
865            };
866            let p = &self.parts.focusables[i];
867            if self
868                .node(p)
869                .is_some_and(|n| n.visible && n.enabled && n.rect.w > 0.0)
870            {
871                let p = p.clone();
872                self.set_focus(Some(p), true);
873                return;
874            }
875        }
876    }
877}