Skip to main content

kui_core/runtime/
dispatch.rs

1//! Input dispatch: one event in, the UI events it resolved to out.
2//!
3//! `handle_input` routes pointer, wheel, key, text and access events
4//! against the last finished frame — its hit regions, edit buffers and
5//! focus — and stamps each result with this window. Focus motion itself
6//! lives in `focus`, the arrow-key patterns in `composites`.
7
8use super::*;
9use crate::input::Target;
10
11impl Core {
12    /// Feeds one input event; returns any UI events it resolved to,
13    /// hit-tested against the previous frame's layout.
14    pub fn handle_input(&mut self, ev: InputEvent) -> Vec<UiEvent> {
15        // The next frame's reason (backlog F111).
16        self.trace_input(&ev);
17        // What a focus move this input makes is reported as (DX18).
18        let by = match &ev {
19            InputEvent::CursorMoved(_)
20            | InputEvent::CursorLeft
21            | InputEvent::MouseDown { .. }
22            | InputEvent::MouseUp { .. }
23            | InputEvent::Scroll(_)
24            | InputEvent::ScrollGesture { .. } => "pointer",
25            InputEvent::Access(_) => "assistive",
26            InputEvent::Key(..)
27            | InputEvent::KeyDown(_)
28            | InputEvent::KeyUp(_)
29            | InputEvent::Text(_)
30            | InputEvent::Commit(_)
31            | InputEvent::Preedit(..) => "keyboard",
32            _ => "program",
33        };
34        // A move the app made since the last report — `set_focus`,
35        // `set_key_focus`, a handler's verb (ADR 0036) — with no frame
36        // finished since to report it: the program's, and before this
37        // input's own, which would otherwise carry this input's `by`
38        // (DX18, the alpha.22 regression pass).
39        let mut moved = Vec::new();
40        self.report_focus("program", &mut moved);
41        // The devtools' chords are acted on before anything is routed
42        // (ADR 0024, decision 4): the press goes no further, and what
43        // was pending still goes out.
44        let mut out = if self.devtools_intercept(&ev) {
45            std::mem::take(&mut self.pending)
46        } else {
47            self.route_input(ev)
48        };
49        if !moved.is_empty() {
50            moved.append(&mut out);
51            out = moved;
52        }
53        // Whatever the event itself made pending — the synthetic key
54        // releases a focus move forces — belongs to this batch, not to the
55        // next frame's drain.
56        out.append(&mut self.pending);
57        self.report_focus(by, &mut out);
58        // A click on a select field opens its menu and is nobody's
59        // (`widgets::select`); before the menu's own consumer, since the
60        // menu it opens is that one's from here on.
61        self.consume_select_events(&mut out);
62        // A row of the core's own context menu is not the app's click, and
63        // neither is that menu's dismissal: taken back here, acted on, and
64        // reported as one `menu` event on the node the menu was about (ADR
65        // 0017, decision 5). Here rather than inside `route_input` because
66        // several of its arms return early — the modal press among them,
67        // which is exactly the one that dismisses a menu.
68        self.consume_menu_events(&mut out);
69        // And the drawn menu bar's own nodes, on the same terms: its
70        // titles and rows post ordinary clicks, and none of them is the
71        // app's (`docs/adr/0018-a-menu-bar-the-app-declares.md`).
72        self.consume_menu_bar_events(&mut out);
73        self.outbound(&mut out);
74        out
75    }
76
77    /// The way out for every batch of events the app is about to hear,
78    /// whichever door made them — an input, or a host's own menu
79    /// answering (`activate_menu_item`), which is not an input and used
80    /// to skip this: a devtools select chosen from a native menu posted
81    /// its action to the app instead of the panel. The devtools panel's
82    /// own controls are taken back (nobody's but the core's); what is
83    /// left is translated, stamped with its window and logged on its way
84    /// out.
85    pub(crate) fn outbound(&mut self, out: &mut Vec<UiEvent>) {
86        self.devtools_consume(out);
87        self.devtools_translate(out);
88        self.stamp(out);
89        self.devtools_log(out);
90        // An event the app was handed is "the user did something": what
91        // separates a message repeated on purpose from a view announcing
92        // every frame (`announce`).
93        if !out.is_empty() {
94            self.events_answered += 1;
95        }
96    }
97
98    /// A click or drag says where it landed, in the terms of the node it
99    /// landed on — the one pass both shapes go through, run on
100    /// the `n` events at the end of `out` that `Interaction::handle` just
101    /// made from a press, and on nothing else: a click Enter, Space or a
102    /// screen reader made has no point and no count, and the cursor is
103    /// wherever the mouse happens to rest. Only a map payload can carry
104    /// the fields.
105    ///
106    /// On a `cells` grid, `cell: {row, col}` — the same arithmetic a
107    /// selection uses (`cell_row_col`), so the app never divides by a
108    /// cell size it did not choose. Inside a key sink that
109    /// draws `role="line"` rows, `line` — the ordinal among the sink's
110    /// lines, the numbering its `access` events use — `byte` — where the
111    /// point falls in that line's text, what `text_hit` would answer —
112    /// and `clicks` — the press's count, so a double click is a word
113    /// without a timer the app keeps; a point above the
114    /// first line is the first, below the last the last, and one in a
115    /// gutter is the line beside it — and `inside`, whether the point is
116    /// within that line's own box at all, so a press in the margin beside
117    /// a row is told from one on its text without the app comparing `x`
118    /// against a rect (backlog F153). The point is the event's own for a
119    /// drag and the cursor's for a click. Not opt-in, like `cell`: the
120    /// fields appear wherever the shape they describe is drawn, and a
121    /// handler that does not read them is not slower for their being
122    /// there.
123    fn attach_pointer(&mut self, out: &mut [UiEvent], n: usize) {
124        if n == 0 || self.tree.is_empty() || !(self.tree.any_text || self.tree.any_line) {
125            return;
126        }
127        let clicks = self.interaction.press_clicks();
128        let from = out.len() - n;
129        for ev in &mut out[from..] {
130            let Some(point) = self.pointer_point(ev) else {
131                continue;
132            };
133            let Some(i) = self.tree.index_of(ev.key) else {
134                continue;
135            };
136            if let Some((row, col)) = self.cell_row_col(ev.key, point)
137                && let Value::Map(entries) = &mut ev.payload
138            {
139                entries.push((
140                    "cell".to_string(),
141                    Value::map([
142                        ("row", Value::Int(row as i64)),
143                        ("col", Value::Int(col as i64)),
144                    ]),
145                ));
146            }
147            if !self.tree.any_line {
148                continue;
149            }
150            // The sink: this node, or the nearest above it.
151            let mut sink = i;
152            while self.tree.specs[sink].events().on_key.is_none() {
153                let p = self.tree.parent[sink];
154                if p == crate::tree::NIL {
155                    break;
156                }
157                sink = p as usize;
158            }
159            if self.tree.specs[sink].events().on_key.is_none() {
160                continue;
161            }
162            let lines = crate::access::lines_under(&self.tree, sink);
163            // Each line is read on its own upright layout: the point is
164            // pulled back through the turns that line is drawn under (ADR
165            // 0043) — the sink's, or a column's between it and its lines;
166            // `x` / `y` stay as drawn.
167            let at = |l: usize| self.unturned_at(l, point);
168            // Nearest vertically — inside one is a gap of zero — ties to
169            // the earlier line.
170            let gap = |l: usize| {
171                let (top, h) = (self.tree.pos[l].y, self.tree.size[l].h);
172                let y = at(l).y;
173                (top - y).max(y - (top + h)).max(0.0)
174            };
175            let Some((line, l)) = lines
176                .iter()
177                .enumerate()
178                .map(|(n, &l)| (n, l))
179                .min_by(|a, b| {
180                    gap(a.1)
181                        .partial_cmp(&gap(b.1))
182                        .unwrap_or(std::cmp::Ordering::Equal)
183                })
184            else {
185                continue;
186            };
187            let byte = self
188                .text
189                .hit_at(self.tree.keys[l], at(l), self.building)
190                .map_or(0, |h| h.byte);
191            // Within the line's box, both ways: on its band, between its
192            // left and right edges.
193            let inside = {
194                let (p, x, w) = (at(l), self.tree.pos[l].x, self.tree.size[l].w);
195                gap(l) == 0.0 && p.x >= x && p.x <= x + w
196            };
197            // A `button` event's press carries its own count and its move
198            // and release none (backlog F105): `clicks` here is the last
199            // primary press's. The core's is told by its `phase` and
200            // `button` fields, not its kind alone, which an app's click
201            // payload may spell too (backlog RG75).
202            let own_count = ev.kind() == Some("button")
203                && ev.payload.get("phase").is_some()
204                && ev.payload.get("button").is_some();
205            if let Value::Map(entries) = &mut ev.payload {
206                entries.push(("line".to_string(), Value::Int(line as i64)));
207                entries.push(("byte".to_string(), Value::Int(byte as i64)));
208                entries.push(("inside".to_string(), Value::Bool(inside)));
209                if !own_count {
210                    entries.push(("clicks".to_string(), Value::Int(clicks as i64)));
211                }
212            }
213        }
214    }
215
216    /// Where a pointer-made event happened: the `x` / `y` its payload
217    /// carries (a drag's), else the cursor (a click's), else nowhere —
218    /// and nowhere for a payload that is not a map, which can carry no
219    /// field anyway.
220    fn pointer_point(&self, ev: &UiEvent) -> Option<Vec2> {
221        let Value::Map(entries) = &ev.payload else {
222            return None;
223        };
224        let field = |name: &str| {
225            entries
226                .iter()
227                .find(|(k, _)| k == name)
228                .and_then(|(_, v)| match v {
229                    Value::Float(f) => Some(*f as f32),
230                    Value::Int(n) => Some(*n as f32),
231                    _ => None,
232                })
233        };
234        match (field("x"), field("y")) {
235            (Some(x), Some(y)) => Some(Vec2::new(x, y)),
236            _ => self.interaction.cursor(),
237        }
238    }
239
240    /// One whole key going down: both channels, in the order a window
241    /// drives them. The press reaches whatever holds key
242    /// focus, and then [`KeyPress::edit_event`] asks the core for what
243    /// that key *means* — Escape dismisses a modal, Tab walks the ring,
244    /// an arrow nudges a focused slider, a printable character reaches
245    /// the focused editor.
246    ///
247    /// This is what a driver with a real keyboard does, so it is what a
248    /// headless test should do too. [`Core::handle_input`] with a bare
249    /// `KeyDown` is still the way to drive one channel on purpose.
250    pub fn press(&mut self, key: KeyPress) -> Vec<UiEvent> {
251        // Read before the move, and before the press: the key's meaning is
252        // a property of the key, not of what the first channel did with it.
253        let edit = key.edit_event();
254        let mut out = self.handle_input(InputEvent::KeyDown(key));
255        if let Some(ev) = edit {
256            out.extend(self.handle_input(ev));
257        }
258        out
259    }
260
261    /// The same key coming up. One channel, because only one has a second
262    /// half: the editing keys act on the way down. Paired with
263    /// [`Core::press`] so a held key is a press and a release, and a sink
264    /// that asked for `key_up` hears both.
265    pub fn release(&mut self, key: KeyPress) -> Vec<UiEvent> {
266        self.handle_input(InputEvent::KeyUp(key.released()))
267    }
268
269    /// Whether this core delivered `key`'s press and has not delivered
270    /// its release — the one core a `KeyUp` for it resolves in. What a
271    /// driver with more than one core asks before routing a release: a
272    /// key pressed in a window and let go while a popup borrowed its
273    /// keyboard was released in the popup, which never saw the press, and
274    /// the owner held it until it lost focus.
275    pub fn holds_key(&self, key: &KeyPress) -> bool {
276        self.keys_held.iter().any(|h| h.same_key(key))
277    }
278
279    /// Says which window every event on its way out came from.
280    ///
281    /// Most producers cannot: hit-testing and the edit buffer are below
282    /// the level at which a window exists. A `Core` is one window, though,
283    /// and the driver already told it which one (`env.window.id`, beside
284    /// `maximized` and the rest of the window facts) — so one assignment
285    /// at each of the two exits covers every event every binding will
286    /// ever see, and a multi-window driver has only to hand each core its id.
287    ///
288    /// The one producer that does know is the audio store, whose mounts
289    /// are per window and whose `ended` / `refused` events are folded
290    /// back through whichever core the driver holds — the main one, in the
291    /// runner. An event it stamped with another window keeps that stamp; a
292    /// `MAIN` one is indistinguishable from an unstamped one and takes the
293    /// draining core's, which is right wherever the draining core is the
294    /// main window, as every driver's is.
295    pub(crate) fn stamp(&self, out: &mut [UiEvent]) {
296        let id = self.env.window.id;
297        // The slot a node was filled into, from the last frame's fill
298        // ranges (`Tree::fills`): a frame with no extension recorded none,
299        // and pays one emptiness check per batch.
300        if !self.tree.fills.is_empty() {
301            for ev in out.iter_mut() {
302                if ev.slot.is_none()
303                    && let Some(i) = self.tree.index_of(ev.key)
304                {
305                    ev.slot = self.tree.slot_of(i);
306                }
307            }
308        }
309        if id == WindowId::MAIN {
310            // What producers already wrote. Skipped rather than written so
311            // the single-window case stays free.
312            return;
313        }
314        for ev in out {
315            if ev.window == WindowId::MAIN {
316                ev.window = id;
317            }
318        }
319    }
320
321    pub(super) fn route_input(&mut self, ev: InputEvent) -> Vec<UiEvent> {
322        let mut out = std::mem::take(&mut self.pending);
323        // Chrome commands say which window they are about, and a hit
324        // region does not know: the interaction store reads it from here.
325        self.interaction.window = self.env.window.id;
326        // The press this event is the second channel of, if it is one:
327        // a `KeyDown` leaves its modifiers for the `Key` or `Text` that
328        // follows it, and anything else is not that (AR10).
329        let pressed = self.pressed_mods.take();
330        // Whether a modifier other than Shift was down on that press — the
331        // question `route_key` asked, asked again here so the two channels
332        // agree about a chord (`docs/adr/0011`, decision 3). Without a
333        // press, the editing `Mods` are what there is.
334        let chord = |mods: Option<crate::input::Mods>| match pressed {
335            Some(m) => m.ctrl || m.alt || m.super_key,
336            None => mods.is_some_and(|m| m.word || m.doc),
337        };
338        // A paste's answer is a commit with the pasteboard's markers beside
339        // it (backlog F84), and a bare commit is one whose pasteboard marked
340        // nothing — the answer an older driver sends — so the two are one
341        // arm below.
342        let (ev, marks, paste) = match ev {
343            InputEvent::Paste { text, marks } => (InputEvent::Commit(text), marks, true),
344            ev => (ev, crate::input::ClipboardMarks::default(), false),
345        };
346        match ev {
347            // Wheel up (positive y) reveals earlier content: offset
348            // decreases. An `on_scroll` node takes it instead — the whole
349            // lines it covers on a grid, the fraction carried to the next
350            // notch on the same node (ADR 0029, decision 4). A scroller
351            // takes the axes it scrolls on and passes the rest to the
352            // region under it (backlog DX13), and a gesture keeps the
353            // targets it started with (backlog F107, `mod gesture`): a
354            // bare `Scroll` is a gesture of its own.
355            InputEvent::Scroll(delta) => self.route_scroll(delta, true, &mut out),
356            InputEvent::ScrollGesture { delta, begins } => {
357                self.route_scroll(delta, begins, &mut out)
358            }
359            InputEvent::Text(s) => {
360                if let Some(key) = self.edit.focused() {
361                    if self.edit_with_fonts(|edit, fs| edit.apply_text(key, &s, fs)) {
362                        self.push_edit_event(key, "changed", &mut out);
363                    }
364                } else if let Some(i) = self.focused_control() {
365                    // Inside a composite, printable characters search the
366                    // items by name; Space extends a search already under
367                    // way rather than pressing (`docs/adr/0007`, decision
368                    // 9). Otherwise Space presses the focused control (a
369                    // sink would have taken the press as data; an editor
370                    // took the text).
371                    //
372                    // Unless the control claims neither and a sink above it
373                    // does: the raw press already bubbled there, and the
374                    // two channels have to agree about who owns the key
375                    // (`docs/adr/0011`, decision 3).
376                    let code = match s.chars().next() {
377                        Some(c) => KeyCode::Char(c),
378                        None => KeyCode::Unknown,
379                    };
380                    if !self.bubbles(i, code, chord(None))
381                        && !self.type_ahead(i, &s, &mut out)
382                        && s == " "
383                    {
384                        // The press shows the focus, as Enter's does
385                        // (`docs/adr/0002`, decision 4a).
386                        self.focus_visible = true;
387                        self.click_node(self.tree.keys[i], &mut out);
388                    }
389                }
390            }
391            InputEvent::Files(paths) => {
392                if let Some(ev) = self.file_ask.answer(&paths) {
393                    out.push(ev);
394                }
395            }
396            // Documents the OS handed the app (backlog F124): nobody's ask,
397            // so the host's, on the root, as `system` and `fonts` are.
398            InputEvent::Open(paths) => {
399                if !paths.is_empty() {
400                    out.push(UiEvent {
401                        origin: OriginId::HOST,
402                        window: WindowId::MAIN,
403                        key: Key::ROOT,
404                        payload: Value::map([
405                            ("kind", Value::str("open")),
406                            (
407                                "paths",
408                                Value::List(paths.into_iter().map(Value::Str).collect()),
409                            ),
410                        ]),
411                        slot: None,
412                    });
413                }
414            }
415            InputEvent::Commit(s) => {
416                // The paste's answer, when one was asked — a driver answers
417                // every ask, with an empty commit for an empty clipboard,
418                // which is what lets the next ask through (AR34). The same
419                // rule says whether this *is* the answer: a `Paste`, or any
420                // commit while an ask is out (backlog DX14).
421                let pasted = std::mem::replace(&mut self.awaiting_paste, false) || paste;
422                if let Some(key) = self.edit.focused() {
423                    if self.edit_with_fonts(|edit, fs| edit.apply_text(key, &s, fs)) {
424                        self.push_edit_event(key, "changed", &mut out);
425                    }
426                } else {
427                    // A custom editor: the composition's result as data,
428                    // on the sink the focused node reports to (backlog
429                    // C17). Never reaches the `Text` arm above, so a
430                    // sink hears a commit once and a keystroke once. A
431                    // marker rides along only when it is set, so a sink
432                    // that never heard of them sees the payload it always
433                    // did.
434                    let mut fields = vec![("kind", Value::str("text")), ("text", Value::Str(s))];
435                    if pasted {
436                        fields.push(("pasted", Value::Bool(true)));
437                    }
438                    if marks.concealed {
439                        fields.push(("concealed", Value::Bool(true)));
440                    }
441                    if marks.transient {
442                        fields.push(("transient", Value::Bool(true)));
443                    }
444                    self.sink_event(Value::map(fields), &mut out);
445                }
446            }
447            InputEvent::Preedit(s, cursor) => {
448                if let Some(key) = self.edit.focused() {
449                    self.edit_with_fonts(|edit, fs| edit.set_preedit(key, &s, cursor, fs));
450                } else {
451                    let cursor = match cursor {
452                        Some((a, b)) => {
453                            Value::List(vec![Value::Int(a as i64), Value::Int(b as i64)])
454                        }
455                        None => Value::Null,
456                    };
457                    self.sink_event(
458                        Value::map([
459                            ("kind", Value::str("preedit")),
460                            ("text", Value::Str(s)),
461                            ("cursor", cursor),
462                        ]),
463                        &mut out,
464                    );
465                }
466            }
467            InputEvent::Key(ek, mods) => {
468                // Inside one of the core's menus a submenu comes first: the
469                // arrows open and close one, and Escape closes the innermost
470                // before it would close the menu (backlog F128).
471                if self.submenu_key(ek) {
472                    return out;
473                }
474                // A modal owns Escape: it asks to go away, and nothing
475                // else happens (see `docs/adr/0003-modal-surfaces.md`).
476                // The core closes nothing — the app stops declaring it.
477                if ek == EditKey::Escape
478                    && let Some(key) = self.modal()
479                {
480                    self.dismiss(key, "escape", &mut out);
481                    return out;
482                }
483                // Tab walks the focus ring (Shift-Tab backwards) unless a
484                // multiline editor holds focus — there Tab stays
485                // indentation — or a key sink does: a sink is an app that
486                // owns its keyboard, Tab included (it hands focus on with
487                // `focus_next`). With nothing focused Tab enters the ring.
488                // A field declared `keep_tab` is the other exception: its
489                // Tab went to the sink above it as a press (backlog F146).
490                let sink = self.focused_sink();
491                let traverse = ek == EditKey::Tab
492                    && match self.edit.focused() {
493                        Some(k) => !self.edit.is_multiline(k) && !self.edit.keeps_tab(k),
494                        None => !sink,
495                    };
496                if traverse {
497                    self.focus_next(!mods.shift);
498                } else if let Some(key) = self.edit.focused() {
499                    let done = self.edit_with_fonts(|edit, fs| edit.apply_key(key, ek, mods, fs));
500                    self.editor_took_selection(key);
501                    if done.changed {
502                        self.push_edit_event(key, "changed", &mut out);
503                    }
504                    if done.submit {
505                        self.push_edit_event(key, "submit", &mut out);
506                    }
507                    // The key met the edge of the text and did nothing:
508                    // the app's to act on — join a block, move to the
509                    // next field (backlog F145).
510                    if let Some(edge) = done.boundary {
511                        out.push(UiEvent::on(
512                            self.edit.origin_of(key).unwrap_or(OriginId::HOST),
513                            key,
514                            Value::map([
515                                ("kind", Value::str("boundary")),
516                                ("key", Value::Str(boundary_code(ek).name())),
517                                ("edge", Value::str(edge.name())),
518                                ("word", Value::Bool(mods.word)),
519                                ("doc", Value::Bool(mods.doc)),
520                            ]),
521                        ));
522                    }
523                    if ek == EditKey::Escape {
524                        self.move_focus(None);
525                    }
526                } else if let Some(i) = self.focused_control()
527                    // A key this control does not claim has already gone to
528                    // the sink above it as a raw press, so it must not act
529                    // here as well (`docs/adr/0011`, decision 3). With no
530                    // sink above, nothing bubbled and every arm below runs
531                    // as it always did — including Escape, which is how a
532                    // control with no shortcut layer over it is let go of.
533                    && !edit_key_code(ek).is_some_and(|c| self.bubbles(i, c, chord(Some(mods))))
534                {
535                    // A control that is neither an editor nor a sink:
536                    // Enter presses it, the arrows nudge a slider (the
537                    // same events assistive technology produces), Escape
538                    // lets go.
539                    use crate::slider::SliderMove;
540                    let slider =
541                        self.tree.specs[i].access().role == Some(crate::access::Role::Slider);
542                    let changes = slider && self.tree.specs[i].events().on_change.is_some();
543                    // Each key the core acts with shows the focus first
544                    // (`docs/adr/0002`, decision 4a): pointer focus is
545                    // unshown, but the moment the keyboard uses it the
546                    // user is owed the answer to "which node did that?" —
547                    // a button pressed with Space after a click otherwise
548                    // emits its event with nothing on screen naming it.
549                    // Escape acts by letting go, and a ring around nothing
550                    // is not a ring; a key the control does not claim went
551                    // to the sink above and never arrives here at all.
552                    // Shift with a horizontal motion on a node inside a
553                    // `selectable` scope moves the scope's selection
554                    // (backlog AR28) — the keyboard's half of what a
555                    // drag does, and the one way a keyboard user selects
556                    // a label. Under a sink the press already bubbled and
557                    // never arrives here, like every other motion.
558                    let scope = self.scopes.get(i).copied().flatten();
559                    match ek {
560                        EditKey::Left | EditKey::Right | EditKey::Home | EditKey::End
561                            if mods.shift && scope.is_some() =>
562                        {
563                            self.focus_visible = true;
564                            self.keyboard_select(scope.unwrap_or(Key::ROOT), ek, mods);
565                        }
566                        EditKey::Enter => {
567                            self.focus_visible = true;
568                            self.click_node(self.tree.keys[i], &mut out);
569                        }
570                        EditKey::Escape => self.move_focus(None),
571                        EditKey::Right | EditKey::Up if slider => {
572                            self.focus_visible = true;
573                            self.nudge(i, SliderMove::Step(1), &mut out);
574                        }
575                        EditKey::Left | EditKey::Down if slider => {
576                            self.focus_visible = true;
577                            self.nudge(i, SliderMove::Step(-1), &mut out);
578                        }
579                        // A slider that asked for its changes takes the
580                        // rest of the keys a range has (ADR 0034,
581                        // decision 4); one that did not leaves them be.
582                        EditKey::PageUp | EditKey::PageDown | EditKey::Home | EditKey::End
583                            if changes =>
584                        {
585                            self.focus_visible = true;
586                            let mv = match ek {
587                                EditKey::PageUp => SliderMove::Page(1),
588                                EditKey::PageDown => SliderMove::Page(-1),
589                                EditKey::Home => SliderMove::Home,
590                                _ => SliderMove::End,
591                            };
592                            self.nudge(i, mv, &mut out);
593                        }
594                        // Inside a composite the arrows, Home and End move
595                        // focus among the items instead (see
596                        // `docs/adr/0007-composite-keyboard-patterns.md`),
597                        // showing the focus where they land; on anything
598                        // else they do nothing, as before.
599                        EditKey::Left
600                        | EditKey::Right
601                        | EditKey::Up
602                        | EditKey::Down
603                        | EditKey::Home
604                        | EditKey::End => self.composite_step(i, ek, &mut out),
605                        _ => {}
606                    }
607                }
608            }
609            InputEvent::KeyDown(kp) => {
610                self.pressed_mods = Some(kp.mods);
611                if self.route_key(&kp, KeyPhase::Down, &mut out) {
612                    // Held from here until its release, focus moving, or
613                    // the window losing the keyboard. A repeat of a key
614                    // already down is the same key, not a second one —
615                    // matched by position, since Shift moving mid-hold
616                    // changes the repeat's `code` (`KeyPress::same_key`).
617                    if !self.keys_held.iter().any(|h| h.same_key(&kp)) {
618                        self.keys_held.push(kp.released());
619                    }
620                }
621            }
622            InputEvent::KeyUp(kp) => {
623                // Only a key whose press was delivered has a release to
624                // deliver: one pressed while an editor held focus, or
625                // already let go of synthetically, resolves nothing.
626                if let Some(i) = self.keys_held.iter().position(|h| h.same_key(&kp)) {
627                    self.keys_held.remove(i);
628                    self.route_key(&kp.released(), KeyPhase::Up, &mut out);
629                }
630            }
631            InputEvent::MouseDown { button, clicks } => {
632                // Only the primary button moves anything: a secondary
633                // press asks for a context menu where it landed and leaves
634                // focus, the caret and the scrollbars exactly as they were
635                // (a right-click on a selection has to keep it). Any
636                // non-primary press an `on_button` node claims is that
637                // node's instead, and captured by it (backlog F105).
638                let primary = button == MouseButton::Primary;
639                let mut owner = None;
640                // A scrollbar wins what it was painted over — its own
641                // scroller's content, not a float over it (ADR 0023): a
642                // thumb press starts a drag, a track press jumps there
643                // first. Neither blurs the focused edit.
644                if primary
645                    && let Some(p) = self.interaction.cursor()
646                    && let Some(Target::Bar(bar)) = self.interaction.target_at(p)
647                {
648                    let (pos, thumb_start) = match bar.axis {
649                        ScrollAxis::X => (p.x, bar.thumb.x),
650                        ScrollAxis::Y => (p.y, bar.thumb.y),
651                    };
652                    let grab = if pos >= thumb_start && pos <= thumb_start + bar.bar_len {
653                        pos - thumb_start
654                    } else {
655                        let center = bar.bar_len / 2.0;
656                        let off = bar.offset_for(p, center);
657                        self.set_scroll_axis(bar.key, bar.axis, off);
658                        center
659                    };
660                    self.interaction.scrollbar_drag = Some((bar.key, bar.axis, grab));
661                    return out;
662                }
663                // Click-to-focus / caret placement / start drag-selection,
664                // against the previous frame's layout.
665                if let Some(p) = self.interaction.cursor() {
666                    let hit = self.interaction.hit_at(p).map(|h| {
667                        // A region that does something with a press
668                        // claims it: a button inside a selectable
669                        // card is a button first (ADR 0017).
670                        let claimed = h.payload.is_some()
671                            || h.drag.is_some()
672                            || h.key_sink.is_some()
673                            || h.window.is_some();
674                        let scope = h.select_scope.filter(|_| !claimed);
675                        (h.key, h.edit_origin, h.focusable, scope, h.origin)
676                    });
677                    // While a modal is up, a press outside it never
678                    // touches focus: one that finds no region asks the
679                    // modal to go away (a modal is hit-tracked, so its own
680                    // background is not "outside"), and one that finds the
681                    // only live thing out there — window chrome — is the
682                    // platform's business, not the app's.
683                    if let Some(key) = self.modal()
684                        && !hit.as_ref().is_some_and(|(k, ..)| self.within_modal(*k))
685                    {
686                        if hit.is_none() {
687                            self.dismiss(key, "outside", &mut out);
688                        }
689                        let n = self
690                            .interaction
691                            .handle(InputEvent::MouseDown { button, clicks }, &mut out);
692                        self.attach_pointer(&mut out, n);
693                        return out;
694                    }
695                    // A press moves focus (to a focusable node, or to the
696                    // key sink the press landed inside) or drops it; either
697                    // way it is pointer focus, not shown.
698                    if primary {
699                        // A press anywhere ends the last selection; the
700                        // arms below start whichever new one it begins.
701                        // One selection per window (ADR 0017) — except a
702                        // press inside the core's own context menu, which
703                        // is *about* that selection: a Copy row that
704                        // cleared what it was going to copy would be a
705                        // menu that never works.
706                        // The menu bar's Edit menu is about the selection
707                        // for the same reason, so a press in it is spared
708                        // the same way.
709                        let origin = hit.as_ref().map(|(.., o)| *o);
710                        let in_bar = origin == Some(OriginId::MENU_BAR);
711                        // A Shift-press inside the scope the selection is
712                        // in keeps its anchor and moves the live end: it
713                        // extends, so it clears nothing (ADR 0029,
714                        // decision 3). Anywhere else Shift is a press.
715                        let shift = self.interaction.modifiers().shift;
716                        let extends = shift
717                            && hit.as_ref().is_some_and(|(_, _, _, scope, _)| {
718                                scope.is_some()
719                                    && (self.selection.map(|s| s.scope) == *scope
720                                        || self.cell_selection.map(|c| c.node) == *scope)
721                            });
722                        // A press on a `keepFocus` node — a toolbar's Copy
723                        // or Bold, acting on what the sink or editor has —
724                        // is spared on the same terms as the menus (backlog
725                        // DX10): it leaves the selection, the focus and the
726                        // ring as they are. An editor inside one is its own
727                        // keyboard owner and takes its caret as ever.
728                        let keep = match hit {
729                            Some((_, Some(_), true, _, _)) | None => false,
730                            Some((key, ..)) => self.keeps_focus(key),
731                        };
732                        if origin != Some(OriginId::MENU) && !in_bar && !extends && !keep {
733                            self.clear_selection();
734                        }
735                        // And the field a menu-bar menu will be about: this
736                        // press is about to move focus onto the title, so
737                        // the answer has to be taken before it does. Only
738                        // on the way *in* — a press with a menu already
739                        // open is a row or a second title, and focus is
740                        // inside the bar by then, so asking again would
741                        // record "no field" over the real answer.
742                        if in_bar && self.menu_bar_open().is_none() {
743                            self.note_menu_bar_editor();
744                        }
745                        match hit {
746                            Some((key, Some(origin), true, _, _)) => {
747                                // A Shift-press in the focused editor
748                                // extends from its caret: cosmic-text's
749                                // `Drag` is the action that moves the
750                                // cursor and keeps (or seeds) the
751                                // selection, which is the whole gesture.
752                                let extend = shift && self.edit.focused() == Some(key);
753                                self.move_focus(Some(key));
754                                // The caret lands where the pointer is on
755                                // the editor's upright layout, through any
756                                // turn it is drawn under (ADR 0043).
757                                let q = self.unturned(key, p);
758                                let local = Vec2::new(q.x - origin.x, q.y - origin.y);
759                                self.edit_with_fonts(|edit, fs| {
760                                    edit.click(key, local, clicks, extend, fs)
761                                });
762                                self.edit.dragging = Some((key, origin));
763                                self.arm_follow(key, p);
764                            }
765                            // The press acts (its click is resolved on the
766                            // release, as any) and moves nothing: not the
767                            // focus, not the region Tab walks next — the
768                            // keyboard's ring is still the one it is in —
769                            // and no drag-select of its own.
770                            Some(_) if keep => {}
771                            // Inside a selection scope, with nothing else
772                            // claiming the press: start a drag-select.
773                            // One click places both ends together, two
774                            // take the word, three the whole run.
775                            Some((key, _, focusable, Some(scope), _)) => {
776                                let target = self.press_focus(key, focusable);
777                                self.move_focus(target);
778                                self.settle_region(Some(key));
779                                // The press arms the drag with what the
780                                // click count says it moves by: a second
781                                // click held and dragged selects word by
782                                // word, a third run by run — in bytes or,
783                                // for a grid, in cells; the arming knows.
784                                // A Shift-press keeps the anchor instead
785                                // and goes on by characters.
786                                if self.arm_select_drag(scope, p, clicks, extends) {
787                                    self.arm_follow(scope, p);
788                                }
789                            }
790                            // Everything else: a plain node, and a
791                            // disabled editor (no caret to place).
792                            Some((key, _, focusable, None, _)) => {
793                                let target = self.press_focus(key, focusable);
794                                self.move_focus(target);
795                                // Whatever the press did to focus, Tab
796                                // afterwards enters the ring under the
797                                // pointer (`docs/adr/0022`, decision 3).
798                                self.settle_region(Some(key));
799                            }
800                            None => {
801                                self.move_focus(None);
802                                self.settle_region(None);
803                            }
804                        }
805                        self.focus_visible = false;
806                    } else if let Some((key, ..)) = hit {
807                        owner = self.button_owner(key, button);
808                    }
809                }
810                let claimed_button = owner.is_some();
811                let n = match owner {
812                    Some(owner) => self
813                        .interaction
814                        .press_button(button, clicks, owner, &mut out),
815                    None => self
816                        .interaction
817                        .handle(InputEvent::MouseDown { button, clicks }, &mut out),
818                };
819                self.attach_pointer(&mut out, n);
820                // A right-click the app did not claim with `onContextMenu`
821                // or `onButton` gets the stock menu, where there is
822                // anything standard to put in one (ADR 0017, decision 5).
823                if button == MouseButton::Secondary
824                    && let Some(p) = self.interaction.cursor()
825                {
826                    let claimed =
827                        claimed_button || out.iter().any(|e| e.kind() == Some("contextmenu"));
828                    self.auto_menu(p, claimed);
829                }
830            }
831            InputEvent::CursorMoved(p) => {
832                if let Some((key, axis, grab)) = self.interaction.scrollbar_drag
833                    && let Some(bar) = self
834                        .interaction
835                        .scrollbars
836                        .iter()
837                        .rev()
838                        .find(|b| b.key == key && b.axis == axis)
839                        .copied()
840                {
841                    // Thumb drag: geometry is last frame's, which is fine —
842                    // track length only changes with the container.
843                    let off = bar.offset_for(p, grab);
844                    self.set_scroll_axis(key, axis, off);
845                }
846                self.rehit(p);
847                self.follow_point(p);
848                let n = self
849                    .interaction
850                    .handle(InputEvent::CursorMoved(p), &mut out);
851                self.attach_pointer(&mut out, n);
852            }
853            InputEvent::MouseUp { button } => {
854                if button == MouseButton::Primary {
855                    self.end_follow();
856                    self.edit.dragging = None;
857                    self.select_dragging = None;
858                    self.interaction.scrollbar_drag = None;
859                }
860                let n = self
861                    .interaction
862                    .handle(InputEvent::MouseUp { button }, &mut out);
863                self.attach_pointer(&mut out, n);
864            }
865            InputEvent::ForceClick(p) => self.force_click(p, &mut out),
866            InputEvent::Access(req) => self.handle_access(req, &mut out),
867            other => {
868                self.interaction.handle(other, &mut out);
869            }
870        }
871        self.flush_sound_requests();
872        // Input moves focus, carets and scroll offsets: an access tree
873        // derived earlier this frame no longer describes it.
874        self.access_built = 0;
875        out
876    }
877
878    /// The node a non-primary press on region `key` goes to, with the tag
879    /// its event carries: see `enclosing_button`. Read off
880    /// the tree at the press, as a force click's tag is.
881    fn button_owner(&self, key: Key, button: MouseButton) -> Option<crate::input::ButtonOwner> {
882        let i = self.tree.index_of(key)?;
883        let j = self.enclosing_button(i, button)?;
884        Some(crate::input::ButtonOwner {
885            key: self.tree.keys[j],
886            origin: self.tree.origins[j],
887            tag: self.tree.specs[j].events().on_button.clone()?,
888        })
889    }
890
891    /// A force click. Over text — an editor or a
892    /// `selectable` scope — it selects the word under it and asks the host
893    /// for its definition panel, which is what the gesture means on the
894    /// one platform that has it. Anywhere else it reaches a node
895    /// declaring `on_force_click`, and over anything else it does
896    /// nothing at all.
897    ///
898    /// It moves no focus and places no caret: it happens *during* a press
899    /// that is still running, and stealing the caret out from under a
900    /// drag would be a gesture fighting itself.
901    fn force_click(&mut self, p: Vec2, out: &mut Vec<UiEvent>) {
902        let Some(region) = self.interaction.hit_at(p) else {
903            return;
904        };
905        let (key, origin) = (region.key, region.origin);
906        // Read off the tree rather than carried on the region: a force
907        // click is one event in a session, and a tag on `HitRegion` is a
908        // clone on every region of every frame (C15's rule — a node pays
909        // for props it does not declare).
910        let tag = self
911            .tree
912            .keys
913            .iter()
914            .position(|k| *k == key)
915            .and_then(|i| self.tree.specs[i].events().on_force_click.clone());
916        let editor = region.edit_origin.map(|origin| (key, origin));
917        let scope = region.select_scope;
918        // Text first: the word under the pointer, selected, and looked up.
919        // The press that deepened into this force click is still running,
920        // and its drag would overwrite the word the moment the finger
921        // moved a pixel — which is what "the panel says one word and the
922        // highlight is one character" looks like. The gesture takes the
923        // press over: no caret drag, no selection drag.
924        self.select_dragging = None;
925        self.edit.dragging = None;
926        self.drag_follow = None;
927        if let Some((key, content_origin)) = editor {
928            let q = self.unturned(key, p);
929            let local = Vec2::new(q.x - content_origin.x, q.y - content_origin.y);
930            self.move_focus(Some(key));
931            self.edit_with_fonts(|edit, fs| edit.click(key, local, 2, false, fs));
932            self.menu_editor = Some(key);
933            if let Some(action) = self.lookup_action() {
934                self.menu_actions.push(action);
935            }
936            return;
937        }
938        if let Some(scope) = scope {
939            // A force click is a double click that also asks for a
940            // definition, so it takes the same word the second click
941            // would have.
942            if !self.select_word_under(scope, p) {
943                return;
944            }
945            // A force click between words is a force click on nothing:
946            // looking up a space would put a dictionary panel over the
947            // page for no reason, which is not what the gesture does
948            // anywhere else on the platform.
949            if self.copy_selection().is_none_or(|t| t.trim().is_empty()) {
950                self.clear_selection();
951                return;
952            }
953            if let Some(action) = self.lookup_action() {
954                self.menu_actions.push(action);
955            }
956            return;
957        }
958        // Not text: the node's own event, if it asked for one.
959        let Some(tag) = tag else { return };
960        let payload = Value::map([
961            ("kind", Value::str("forceclick")),
962            ("x", Value::Float(p.x as f64)),
963            ("y", Value::Float(p.y as f64)),
964        ]);
965        out.push(UiEvent::on(origin, key, payload).tagged(Some(&tag)));
966    }
967
968    /// Resolves a request from assistive technology against the last
969    /// frame the way the pointer or keyboard equivalent would be (see
970    /// [`crate::access::AccessAction`]).
971    fn handle_access(&mut self, req: crate::access::AccessRequest, out: &mut Vec<UiEvent>) {
972        use crate::access::AccessAction;
973        let key = req.key;
974        let idx = self.tree.index_of(key);
975        // The gates every other channel obeys (AR18): a node outside the
976        // modal is inert (ADR 0003 decision 5) and a disabled one takes no
977        // action. Only `Click` resolved against the hit list before; a
978        // reader edited, nudged and scrolled the page behind a dialog,
979        // and `Focus` on an editor there routed typing to it until the
980        // next frame's containment.
981        if let Some(i) = idx
982            && !self.interactive(i)
983        {
984            // The access tree is not pruned (ADR 0003 decision 7), so a
985            // reader can name a node behind the modal, and its click is
986            // the press outside: the modal is asked to go away, and the
987            // node hears nothing (decision 6). Dropped on the floor, a
988            // select's field clicked a second time left its own menu
989            // open where the pointer closes it (backlog RG13). Every
990            // other request behind a modal does nothing — nothing a
991            // pointer does to the page behind a dialog moves its text.
992            if req.action == AccessAction::Click
993                && let Some(modal) = self.modal()
994            {
995                self.dismiss(modal, "outside", out);
996            }
997            return;
998        }
999        // Disabled: what the access tree refuses to advertise, so a
1000        // request naming one is a reader working from a stale tree, or a
1001        // headless test.
1002        if let Some(i) = idx
1003            && self.tree.specs[i].disabled
1004        {
1005            return;
1006        }
1007        match req.action {
1008            AccessAction::Click => self.click_node(key, out),
1009            AccessAction::Focus => {
1010                // The reader's cursor lands where Tab would — on a node it
1011                // can see (decoration is not in its tree); show it.
1012                let exposed = self.access_tree().get(key).is_some();
1013                if exposed && idx.is_some_and(|i| crate::access::focusable(&self.tree, i)) {
1014                    self.move_focus(Some(key));
1015                    self.focus_visible = true;
1016                }
1017            }
1018            AccessAction::Blur => {
1019                if self.focus == Some(key) {
1020                    self.move_focus(None);
1021                }
1022            }
1023            AccessAction::SetValue => {
1024                if self.edit.contains(key) {
1025                    let value = req.value.unwrap_or_default();
1026                    if self.edit.text(key).as_deref() != Some(value.as_str()) {
1027                        self.set_edit_text(key, &value);
1028                        self.push_edit_event(key, "changed", out);
1029                    }
1030                } else if let Some(i) = idx
1031                    && crate::access::is_custom_editor(&self.tree, i)
1032                {
1033                    // The app owns the text: hand the request over as data.
1034                    let payload = Value::map([
1035                        ("kind", Value::str("access")),
1036                        ("action", Value::str(req.action.name())),
1037                        ("text", Value::str(req.value.unwrap_or_default())),
1038                    ]);
1039                    out.push(
1040                        UiEvent::on(self.tree.origins[i], key, payload)
1041                            .tagged(self.access_tag(i).as_ref()),
1042                    );
1043                } else if let Some(i) = idx {
1044                    self.set_slider(i, req.value.as_deref().unwrap_or_default(), out);
1045                }
1046            }
1047            AccessAction::Increment | AccessAction::Decrement => {
1048                let Some(i) = idx else { return };
1049                let n = if req.action == AccessAction::Increment {
1050                    1
1051                } else {
1052                    -1
1053                };
1054                self.nudge(i, crate::slider::SliderMove::Step(n), out);
1055            }
1056            AccessAction::SetTextSelection | AccessAction::ReplaceSelectedText => {
1057                let Some(i) = idx else { return };
1058                if self.edit.contains(key) {
1059                    match req.action {
1060                        AccessAction::SetTextSelection => {
1061                            let (Some(anchor), Some(focus)) = (req.anchor, req.focus) else {
1062                                return;
1063                            };
1064                            // Run positions resolve against the tree of
1065                            // the last frame, which is what the request
1066                            // was made from.
1067                            let tree = self.access_tree();
1068                            let Some(node) = tree.get(key) else { return };
1069                            let (Some(a), Some(f)) =
1070                                (node.line_offset(anchor), node.line_offset(focus))
1071                            else {
1072                                return;
1073                            };
1074                            self.edit.set_selection(key, a, f);
1075                            self.editor_took_selection(key);
1076                        }
1077                        _ => {
1078                            let text = req.value.unwrap_or_default();
1079                            if self
1080                                .edit_with_fonts(|edit, fs| edit.replace_selection(key, &text, fs))
1081                            {
1082                                self.push_edit_event(key, "changed", out);
1083                            }
1084                        }
1085                    }
1086                } else if crate::access::is_custom_editor(&self.tree, i) {
1087                    // The app owns the text: hand the request over as data.
1088                    let mut entries = vec![
1089                        ("kind".to_string(), Value::str("access")),
1090                        ("action".to_string(), Value::str(req.action.name())),
1091                    ];
1092                    if let Some(text) = req.value {
1093                        entries.push(("text".to_string(), Value::str(text)));
1094                    }
1095                    if let (Some(anchor), Some(focus)) = (req.anchor, req.focus) {
1096                        let tree = self.access_tree();
1097                        let Some(node) = tree.get(key) else { return };
1098                        let (Some(a), Some(f)) =
1099                            (node.line_offset(anchor), node.line_offset(focus))
1100                        else {
1101                            return;
1102                        };
1103                        let pos = |(line, offset): (usize, usize)| {
1104                            Value::map([
1105                                ("line", Value::Int(line as i64)),
1106                                ("offset", Value::Int(offset as i64)),
1107                            ])
1108                        };
1109                        entries.push(("anchor".to_string(), pos(a)));
1110                        entries.push(("focus".to_string(), pos(f)));
1111                    }
1112                    let ev = self.tree.specs[i].events();
1113                    let tag = ev
1114                        .on_click
1115                        .clone()
1116                        .or_else(|| ev.on_drag.clone())
1117                        .or_else(|| ev.on_key.clone());
1118                    out.push(
1119                        UiEvent::on(self.tree.origins[i], key, Value::Map(entries))
1120                            .tagged(tag.as_ref()),
1121                    );
1122                }
1123            }
1124            AccessAction::ScrollIntoView => {
1125                let Some(i) = idx else { return };
1126                let rect = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
1127                self.scroll_rect_into_view(i, rect, false);
1128            }
1129            AccessAction::ScrollUp
1130            | AccessAction::ScrollDown
1131            | AccessAction::ScrollLeft
1132            | AccessAction::ScrollRight => {
1133                let Some(i) = idx else { return };
1134                let size = self.tree.size[i];
1135                let delta = match req.action {
1136                    AccessAction::ScrollUp => Vec2::new(0.0, -size.h * 0.8),
1137                    AccessAction::ScrollDown => Vec2::new(0.0, size.h * 0.8),
1138                    AccessAction::ScrollLeft => Vec2::new(-size.w * 0.8, 0.0),
1139                    _ => Vec2::new(size.w * 0.8, 0.0),
1140                };
1141                self.scroll.scroll_by(key, delta);
1142            }
1143        }
1144    }
1145
1146    /// The `tag` an `access` event on node `i` carries: its click payload,
1147    /// else its drag or key tag; None when there is none (or it is null).
1148    pub(crate) fn access_tag(&self, i: usize) -> Option<Value> {
1149        let ev = self.tree.specs[i].events();
1150        ev.on_click
1151            .clone()
1152            .or_else(|| ev.on_drag.clone())
1153            .or_else(|| ev.on_key.clone())
1154            .filter(|t| *t != Value::Null)
1155    }
1156
1157    /// The key of the first node in tree order, in the last finished
1158    /// frame, whose accessible name is `name` — what a screen reader reads
1159    /// it as: its `label` row, else its own text, else a control's derived
1160    /// name (a button's text inside it). Not the key label `key_of` reads,
1161    /// which is the name the view opened the node under and a reader never
1162    /// hears. The window itself is not matched. More than one node with
1163    /// the name raises `ambiguous-name`; None when none has it. From
1164    /// inside a view, the tree is the last one derived ([`Self::access_tree`]).
1165    pub fn key_named(&mut self, name: &str) -> Option<Key> {
1166        use crate::access::Role;
1167        let (first, count, caption) = {
1168            let mut hits = self
1169                .access_tree()
1170                .nodes
1171                .iter()
1172                .skip(1)
1173                .filter(|n| n.name.as_deref() == Some(name));
1174            let head = hits.next()?;
1175            // A caption beside the control it repeats is text and a
1176            // control under one name (backlog F140).
1177            let (mut count, mut text, mut other) = (0, false, false);
1178            for n in std::iter::once(head).chain(hits) {
1179                count += 1;
1180                if n.role == Role::StaticText {
1181                    text = true;
1182                } else {
1183                    other = true;
1184                }
1185            }
1186            (head.key, count, text && other)
1187        };
1188        if count > 1 {
1189            self.diag.raise(if caption {
1190                crate::diag::ambiguous_caption(name, first, count)
1191            } else {
1192                crate::diag::ambiguous_name(name, first, count)
1193            });
1194        }
1195        Some(first)
1196    }
1197
1198    /// The access tree of the last finished frame (see [`crate::access`]):
1199    /// derived on the first call after a frame, then reused. A driver that
1200    /// never asks pays nothing. Asked while a frame is being built, it is
1201    /// the last tree derived, unchanged: the frame in progress is half a
1202    /// tree, and caching it would serve that half for the whole frame.
1203    pub fn access_tree(&mut self) -> &crate::access::AccessTree {
1204        if self.access_built != self.frame_no && !self.building {
1205            let src = crate::access::Sources {
1206                text: &self.text,
1207                cells: &self.cells,
1208                edit: &self.edit,
1209                scroll: &self.scroll,
1210                title: self.window_title.as_deref(),
1211                focus: self.focus,
1212                modal: self.modal(),
1213                viewport: self.viewport,
1214                scale: self.scale,
1215                clips: &self.clips,
1216            };
1217            // Deriving the tree is about 480 µs on a 10,000-node frame and
1218            // is paid on every frame a screen reader is attached; hashing
1219            // what it reads is about 105 µs, because three quarters of the
1220            // work is making the nodes rather than walking to them. So a
1221            // frame that changed nothing this tree can see — a pointer
1222            // moving across hover backgrounds, a colour transition — keeps
1223            // the one it had. See `access::inputs_hash` for the invariant
1224            // that makes it safe, and ADR 0016 decision 3 for why this is
1225            // the one thing in the frame that gets cached.
1226            let hash = crate::access::inputs_hash(&self.tree, &src);
1227            if hash.is_none() || self.access_inputs != hash {
1228                self.access = crate::access::build(&self.tree, &src);
1229                self.access_rebuilds += 1;
1230            }
1231            self.access_inputs = hash;
1232            self.access_built = self.frame_no;
1233        }
1234        &self.access
1235    }
1236
1237    /// Delivers one key event to the sink it resolves to, tagged with that
1238    /// sink's `on_key` payload; returns whether anything took it. *Which*
1239    /// sink is [`Self::key_target`]'s answer: the focused one, or — when a
1240    /// control holds focus and does not claim this key — the nearest one
1241    /// above it.
1242    ///
1243    /// A focused editor keeps every press it acts on — the editing keys,
1244    /// what it types, the clipboard chords — and a press it does not
1245    /// (⌘N, Ctrl+K, a field's Tab under `keep_tab`) goes to the nearest
1246    /// sink above it, as a chord bubbles from a control (`docs/adr/0011`,
1247    /// amended for backlog F144). A release goes where its press went:
1248    /// it only arrives here for a press a sink took.
1249    fn route_key(&mut self, kp: &KeyPress, phase: KeyPhase, out: &mut Vec<UiEvent>) -> bool {
1250        let target = match self.edit.focused() {
1251            Some(editor) => {
1252                if phase == KeyPhase::Down && self.editor_claims(editor, kp) {
1253                    return false;
1254                }
1255                let Some(j) = self
1256                    .tree
1257                    .index_of(editor)
1258                    .and_then(|i| self.enclosing_sink(i))
1259                else {
1260                    return false;
1261                };
1262                self.tree.keys[j]
1263            }
1264            None => {
1265                let Some(target) =
1266                    self.key_target(kp.code, kp.mods.ctrl || kp.mods.alt || kp.mods.super_key)
1267                else {
1268                    return false;
1269                };
1270                target
1271            }
1272        };
1273        // A sink hears releases only by asking (`key_up`): press-only is
1274        // the keymap case, and a keymap handed both halves runs every
1275        // binding twice. The key is still tracked as held either way, so
1276        // a sink that opts in mid-hold hears the release it is owed.
1277        if phase == KeyPhase::Up
1278            && !self
1279                .sink_node(target)
1280                .is_some_and(|i| self.tree.specs[i].events().key_up)
1281        {
1282            return false;
1283        }
1284        // A modifier or lock key reaches only a sink that asked for them
1285        // (`modifier_keys`, backlog F108): to any other it is held, not
1286        // pressed, and never held as a key either — so its release has
1287        // nothing to find.
1288        if kp.code.is_modifier()
1289            && !self
1290                .sink_node(target)
1291                .is_some_and(|i| self.tree.specs[i].events().modifier_keys)
1292        {
1293            return false;
1294        }
1295        self.deliver_to_sink(target, kp.to_value(phase), out)
1296    }
1297
1298    /// The node the sink `key` names, in the last frame's tree: one that
1299    /// declares `on_key`, is not disabled, and is not shut out by a
1300    /// modal.
1301    ///
1302    /// Asked of the tree and not of the hit list, because a key is not
1303    /// pointer input. The hit list is where a *point* finds a node, and
1304    /// a node outside its scroller's clip is not under any point, so it
1305    /// has no region there (`emit_node` is never reached for it) — while
1306    /// the keyboard reaches a node by having focus, which a node keeps
1307    /// wherever it is drawn. Before F79 the delivery read the hit list
1308    /// like a click, so a focused sink scrolled out of view, or drawn
1309    /// part-way to its place by `slide` or an `enter` offset, dropped
1310    /// every key typed at it until it came back.
1311    fn sink_node(&self, key: Key) -> Option<usize> {
1312        let i = (0..self.tree.len())
1313            .rev()
1314            .find(|&i| self.tree.keys[i] == key)?;
1315        let spec = &self.tree.specs[i];
1316        (spec.events().on_key.is_some() && !spec.disabled && self.interactive(i)).then_some(i)
1317    }
1318
1319    /// Hands `payload` to the sink `target` names with the sink's tag
1320    /// merged in — the one delivery both key channels end in. False when
1321    /// the last frame declared no such sink.
1322    fn deliver_to_sink(&self, target: Key, payload: Value, out: &mut Vec<UiEvent>) -> bool {
1323        let Some(i) = self.sink_node(target) else {
1324            return false;
1325        };
1326        out.push(
1327            UiEvent::on(self.tree.origins[i], self.tree.keys[i], payload)
1328                .tagged(self.tree.specs[i].events().on_key.as_ref()),
1329        );
1330        true
1331    }
1332
1333    /// Delivers `payload` to the sink the focused node reports to — the
1334    /// focused sink itself, or the nearest one above a focused control —
1335    /// with the sink's tag merged in, the way a `key` event is. A
1336    /// composition is never a control's to claim, so unlike `route_key`
1337    /// nothing is asked about the key. False with no sink to hear it.
1338    fn sink_event(&mut self, payload: Value, out: &mut Vec<UiEvent>) -> bool {
1339        let Some(i) = self.focus_index() else {
1340            // With nothing focused, the root sink that hears every
1341            // unclaimed key (`key_target`) hears this too — a paste a
1342            // shell asked for with nothing focused would otherwise
1343            // vanish (backlog C33). Not under a modal.
1344            if self.tree.is_empty() || self.modal.is_some() {
1345                return false;
1346            }
1347            let root = &self.tree.specs[0];
1348            if root.events().on_key.is_none() || root.disabled {
1349                return false;
1350            }
1351            return self.deliver_to_sink(self.tree.keys[0], payload, out);
1352        };
1353        let target = if self.tree.specs[i].events().on_key.is_some() {
1354            self.tree.keys[i]
1355        } else {
1356            match self.enclosing_sink(i) {
1357                Some(j) => self.tree.keys[j],
1358                None => return false,
1359            }
1360        };
1361        self.deliver_to_sink(target, payload, out)
1362    }
1363
1364    /// Lets go of every key the focused sink is holding, as if the user
1365    /// had released them: each becomes a `{kind="key", phase="up"}` on the
1366    /// sink that took the press. Called when focus moves — a keymap that
1367    /// armed a mode on the way down has to hear the way up, and the node
1368    /// it moved to never saw the press — and by drivers when the window
1369    /// loses the keyboard (Cmd-Tab while a key is down otherwise leaves it
1370    /// stuck down forever).
1371    pub fn release_held_keys(&mut self) {
1372        if self.keys_held.is_empty() {
1373            return;
1374        }
1375        let mut out = Vec::new();
1376        let mut held = std::mem::take(&mut self.keys_held);
1377        while !held.is_empty() {
1378            let mut kp = held.remove(0);
1379            // A modifier key's release reports the state after it, as a
1380            // real one does (ADR 0002, decision 15): its own bit off
1381            // unless its twin is still down to be let go of next. The
1382            // press stored it on (backlog RG85).
1383            let on = held.iter().any(|h| h.code == kp.code);
1384            match kp.code {
1385                KeyCode::Shift => kp.mods.shift = on,
1386                KeyCode::Ctrl => kp.mods.ctrl = on,
1387                KeyCode::Alt => kp.mods.alt = on,
1388                KeyCode::Super => kp.mods.super_key = on,
1389                _ => {}
1390            }
1391            self.route_key(&kp, KeyPhase::Up, &mut out);
1392        }
1393        // Pending rather than returned: the writers are `set_focus` and the
1394        // driver's window-focus report, neither of which is answering an
1395        // input event. `handle_input` appends it before returning, so a
1396        // click that moved focus and the release it forced arrive together.
1397        self.pending.append(&mut out);
1398    }
1399
1400    /// The driver's report that this window gained or lost the keyboard:
1401    /// `env.focused`, plus the one rule that rides on it — a window that
1402    /// lost the keyboard lets go of every key its sink was holding, since
1403    /// the OS stops delivering key events to it and the release would
1404    /// never arrive. The rule lives here rather than in each driver so a
1405    /// Node test's `setEnv({focused: false})` and a C host's `kui_env_set`
1406    /// do what the windowed runner does, instead of each remembering to.
1407    /// The synthetic `up`s are pending, like `release_held_keys`'s, and so
1408    /// are the `release`s of the buttons `onButton` nodes held.
1409    pub fn set_focused(&mut self, focused: bool) {
1410        if self.env.focused == focused {
1411            return;
1412        }
1413        self.env.focused = focused;
1414        // The app hears it as a window event rather than diffing
1415        // `env.focused` every frame (backlog DX18).
1416        let (name, id) = (self.window_name(), self.env.window.id);
1417        self.push_window_event(if focused { "focused" } else { "blurred" }, &name, id);
1418        if !focused {
1419            self.release_held_keys();
1420            // The modifiers go with the keys: a Shift released in another
1421            // window never reaches this one, and a host that does not
1422            // resend the state on the way back (winit does; a C loop may
1423            // not) would otherwise leave every later press an extending
1424            // one. The app hears it as the `modifiers` event it is.
1425            let mut out = Vec::new();
1426            self.interaction.handle(
1427                InputEvent::Modifiers(crate::input::KeyMods::default()),
1428                &mut out,
1429            );
1430            // And the buttons an `onButton` node holds captured (backlog
1431            // F105): each owner hears its release now, with the cell it
1432            // lands in, rather than every later move as a drag.
1433            let n = self.interaction.release_buttons(&mut out);
1434            self.attach_pointer(&mut out, n);
1435            // And the primary button's hold (backlog RG75): a drag or a
1436            // slide ends where the pointer was, a caret drag, a
1437            // selection drag and a scrollbar drag stop, and the press
1438            // clicks nothing — the release, like the buttons', is not
1439            // coming here, and every move after the window came back
1440            // went on dragging with no button down.
1441            self.edit.dragging = None;
1442            self.select_dragging = None;
1443            self.interaction.scrollbar_drag = None;
1444            let n = self.interaction.release_primary(&mut out);
1445            self.attach_pointer(&mut out, n);
1446            self.pending.append(&mut out);
1447            // And a held drag's follow: the release will not come here,
1448            // and a scroller stepping toward a pointer nobody holds any
1449            // more is a window asking for frames until one does.
1450            self.drag_follow = None;
1451        }
1452    }
1453
1454    /// The sink a chord pressed now would reach, if any: the focused sink,
1455    /// the nearest one above the focused control, or the root's with
1456    /// nothing focused. What a
1457    /// driver asks before greying a menu row that spells a chord — a sink
1458    /// that would hear ⌘C may do anything with it, so the row stays lit.
1459    pub fn chord_sink(&self) -> Option<Key> {
1460        if self.edit.focused().is_some() {
1461            return None;
1462        }
1463        self.key_target(KeyCode::Char('c'), true)
1464    }
1465
1466    /// Which node hears a raw press: the focused sink, the nearest sink
1467    /// above a focused control that does not claim the key, or nothing.
1468    ///
1469    /// `chord` is whether a modifier other than Shift is down. A chord is
1470    /// never a control's key — it is what a shortcut layer is made of — so
1471    /// it bubbles whatever the focused control would have done with the
1472    /// bare key.
1473    fn key_target(&self, code: KeyCode, chord: bool) -> Option<Key> {
1474        // With nothing focused there is nothing to claim, and the sink
1475        // that hears every unclaimed key in the tree — one on the root —
1476        // hears this one too (`docs/adr/0022`, decision 8). Not under a
1477        // modal, where the root is inert like everything outside it. A
1478        // shell used to take focus on the root to get this.
1479        let Some(i) = self.focus_index() else {
1480            // Tab is still the ring's: it enters, and the sink does not
1481            // hear it — a chord on it bubbles as any chord does.
1482            if self.tree.is_empty() || self.modal.is_some() || (!chord && code == KeyCode::Tab) {
1483                return None;
1484            }
1485            let root = &self.tree.specs[0];
1486            return (root.events().on_key.is_some() && !root.disabled).then_some(self.tree.keys[0]);
1487        };
1488        // A sink that holds focus keeps everything, as it always has
1489        // (`docs/adr/0002`, decision 3).
1490        if self.tree.specs[i].events().on_key.is_some() {
1491            return Some(self.tree.keys[i]);
1492        }
1493        if !chord && self.claims(i, code) {
1494            return None;
1495        }
1496        self.enclosing_sink(i).map(|j| self.tree.keys[j])
1497    }
1498
1499    /// Whether the key `code` pressed on the focused node `i` reaches a
1500    /// sink above it instead of the node itself — the question the
1501    /// `EditKey` and `Text` channels ask, so that both agree with the raw
1502    /// press channel about who owns the key. False with no sink above, so
1503    /// a key nothing claims does exactly what it did before.
1504    fn bubbles(&self, i: usize, code: KeyCode, chord: bool) -> bool {
1505        (chord || !self.claims(i, code)) && self.enclosing_sink(i).is_some()
1506    }
1507
1508    /// Whether the focused node `i` takes `code` for itself: the keys the
1509    /// core acts on *for that node*, which are exactly the keys that never
1510    /// bubble. Static — a press is resolved
1511    /// on its way down, before the channel that would act on it arrives,
1512    /// so the question has to be answerable from the node and the key
1513    /// alone rather than from what a handler did.
1514    fn claims(&self, i: usize, code: KeyCode) -> bool {
1515        use crate::access::Role;
1516        // A space bar reported as a character is still the space bar.
1517        let code = match code {
1518            KeyCode::Char(' ') => KeyCode::Space,
1519            c => c,
1520        };
1521        // Tab belongs to the ring wherever focus is: a shell sink that
1522        // heard every Tab would be this ADR's own bug in reverse.
1523        if code == KeyCode::Tab {
1524            return true;
1525        }
1526        // Only a control the core presses itself claims anything else; a
1527        // plain box someone focused by hand claims nothing.
1528        if self.focused_control() != Some(i) {
1529            return false;
1530        }
1531        let key = self.tree.keys[i];
1532        // Enter and Space activate what there is to activate: a node with
1533        // no click payload has nothing, so its Space is free to bubble.
1534        let activates = self
1535            .interaction
1536            .hits
1537            .iter()
1538            .rev()
1539            .find(|h| h.key == key)
1540            .is_some_and(|h| h.payload.is_some() || h.window.is_some());
1541        let item = crate::composite::owner(&self.tree, i, &mut Vec::new()).is_some();
1542        let slider = self.tree.specs[i].access().role == Some(Role::Slider);
1543        let changes = slider && self.tree.specs[i].events().on_change.is_some();
1544        match code {
1545            KeyCode::Enter => activates,
1546            // Inside a composite, Space either extends a type-ahead search
1547            // or presses the item (`docs/adr/0007`, decision 9).
1548            KeyCode::Space => activates || item,
1549            KeyCode::Left | KeyCode::Right | KeyCode::Up | KeyCode::Down => slider || item,
1550            KeyCode::Home | KeyCode::End => item || changes,
1551            KeyCode::PageUp | KeyCode::PageDown => changes,
1552            // Type-ahead inside a composite; nothing anywhere else.
1553            KeyCode::Char(_) => item,
1554            _ => false,
1555        }
1556    }
1557
1558    /// Whether the focused editor `key` takes the press `kp` for itself:
1559    /// every key its editing channel acts on (`KeyPress::edit_event` — the
1560    /// arrows, Home and End, the pages, Backspace, Delete, Enter, Tab,
1561    /// Escape, and whatever types), the clipboard and undo chords a driver
1562    /// performs for it (⌘C/X/V/A, ⌘Z, ⇧⌘Z, ⌘Y — the primary modifier, as
1563    /// the runner's `edit_chord` reads it), and anything pressed without
1564    /// Control or Command, which is typing: a Mac's Option composes ø,
1565    /// and a key with no text yet may be the first half of one. Static,
1566    /// like `claims`: the press is resolved before the channel that acts
1567    /// on it arrives.
1568    fn editor_claims(&self, key: Key, kp: &KeyPress) -> bool {
1569        if kp.code == KeyCode::Tab && self.edit.keeps_tab(key) {
1570            return false;
1571        }
1572        if kp.edit_event().is_some() {
1573            return true;
1574        }
1575        let clipboard = kp.mods.primary()
1576            && matches!(kp.code, KeyCode::Char(c) if "cxvazy".contains(c.to_ascii_lowercase()));
1577        clipboard || !(kp.mods.ctrl || kp.mods.super_key)
1578    }
1579
1580    /// Whether the focused node is a key sink (it owns its keys).
1581    fn focused_sink(&self) -> bool {
1582        self.focus_index()
1583            .is_some_and(|i| self.tree.specs[i].events().on_key.is_some())
1584    }
1585
1586    /// The focused node when it is a control the core presses itself:
1587    /// not an editor, not a key sink, and still focusable.
1588    fn focused_control(&self) -> Option<usize> {
1589        let i = self.focus_index()?;
1590        let spec = &self.tree.specs[i];
1591        let editor = matches!(self.tree.content[i], NodeContent::Edit(_));
1592        (!editor && spec.events().on_key.is_none() && crate::access::focusable(&self.tree, i))
1593            .then_some(i)
1594    }
1595
1596    /// Activates node `key` the way a pointer click would — against the
1597    /// last frame's hit regions, so a disabled node emits nothing — for
1598    /// Enter, Space and an assistive-technology `click`. Focus follows
1599    /// into an editor or a sink, as a click's would.
1600    pub(crate) fn click_node(&mut self, key: Key, out: &mut Vec<UiEvent>) {
1601        let Some(h) = self.interaction.hits.iter().rev().find(|h| h.key == key) else {
1602            return;
1603        };
1604        let (origin, payload, window, sound) =
1605            (h.origin, h.payload.clone(), h.window, h.click_sound);
1606        let takes_focus = h.focusable && (h.edit_origin.is_some() || h.key_sink.is_some());
1607        // Not a press: the payload gains no `cell` and no `line` /
1608        // `byte` / `clicks` from wherever the pointer rests — only what
1609        // `Interaction::handle` made from a press does (`attach_pointer`)
1610        // — and the count the last press carried describes nothing now.
1611        self.interaction.note_synthetic_click();
1612        if let Some(sound) = sound {
1613            self.interaction.sound_requests.push(sound);
1614        }
1615        match (window, payload) {
1616            (Some(crate::window::WindowRole::Button(b)), _) => self
1617                .interaction
1618                .window_commands
1619                .push(b.command(self.env.window.id)),
1620            (None, Some(payload)) => out.push(UiEvent {
1621                origin,
1622                window: WindowId::MAIN,
1623                key,
1624                payload,
1625                slot: None,
1626            }),
1627            _ => {}
1628        }
1629        if takes_focus {
1630            self.move_focus(Some(key));
1631        }
1632    }
1633
1634    /// The modal `key` was asked to go away — Escape, or a press outside
1635    /// it. Reaches the app as `{kind="dismiss", reason, tag}` on the modal
1636    /// node; what happens next is the app's, since only it can stop
1637    /// declaring the node.
1638    fn dismiss(&mut self, key: Key, reason: &str, out: &mut Vec<UiEvent>) {
1639        let Some(i) = self.tree.index_of(key) else {
1640            return;
1641        };
1642        let payload = Value::map([
1643            ("kind", Value::str("dismiss")),
1644            ("reason", Value::str(reason)),
1645        ]);
1646        out.push(
1647            UiEvent::on(self.tree.origins[i], key, payload)
1648                .tagged(self.tree.specs[i].events().modal.as_ref()),
1649        );
1650    }
1651
1652    pub(crate) fn push_edit_event(&self, key: Key, kind: &str, out: &mut Vec<UiEvent>) {
1653        out.push(UiEvent {
1654            origin: self.edit.origin_of(key).unwrap_or(OriginId::HOST),
1655            window: WindowId::MAIN,
1656            key,
1657            payload: Value::map([("kind", kind.into())]),
1658            slot: None,
1659        });
1660    }
1661
1662    /// The window's selected text, for clipboard integration: the
1663    /// selection in a `selectable` scope when there is one, else the
1664    /// focused editor's. Only one of the two exists at a time — starting
1665    /// either clears the other
1666    /// — so this asks in that order rather than merging them.
1667    pub fn copy_selection(&self) -> Option<String> {
1668        self.note_read(|| replay::Read::Opaque);
1669        if self.selection.is_some() {
1670            return self.selection_text();
1671        }
1672        if self.cell_selection.is_some() {
1673            return self.cell_selection_text();
1674        }
1675        self.edit.copy_selection(self.edit.focused()?)
1676    }
1677
1678    /// One selection per window, in the direction
1679    /// `set_selection` does not cover: an editor's selection started by
1680    /// the keyboard — Select All, Shift+arrows, a reader's
1681    /// `setTextSelection` — takes the window's one selection with it, so
1682    /// a scope's or a grid's highlight goes and Cmd-A / Cmd-C read the
1683    /// editor and not the label dragged over before Tab.
1684    fn editor_took_selection(&mut self, key: Key) {
1685        if self.edit.has_selection(key) {
1686            self.selection = None;
1687            self.cell_selection = None;
1688        }
1689    }
1690
1691    /// Cuts the focused editor's selection, returning the removed text.
1692    /// A cut is an edit like any other, so the editor's `changed` is
1693    /// pending for the caller to route — like a `resize`, since the
1694    /// caller is not answering an input event.
1695    pub fn cut_selection(&mut self) -> Option<String> {
1696        let key = self.edit.focused()?;
1697        let text = self.cut_editor(key)?;
1698        let mut out = Vec::new();
1699        self.push_edit_event(key, "changed", &mut out);
1700        self.pending.append(&mut out);
1701        Some(text)
1702    }
1703
1704    /// Deletes editor `key`'s selection, returning what was there — the
1705    /// one mutation both cuts share; the `changed` is the caller's to
1706    /// post where its batch goes.
1707    pub(crate) fn cut_editor(&mut self, key: Key) -> Option<String> {
1708        let text = self.edit.copy_selection(key)?;
1709        self.edit_with_fonts(|edit, fs| edit.delete_selection(key, fs));
1710        Some(text)
1711    }
1712
1713    /// Where editor `key`'s caret is, in logical viewport px — zero wide,
1714    /// one line tall, where the last frame drew the editor — or `None`
1715    /// for a key with no editor in that frame. With
1716    /// [`Self::edit_caret_to`] it carries a column between an editor and
1717    /// whatever the app moves the keyboard to: a block editor's ↓ from a
1718    /// title into its first line lands under the title's caret (backlog
1719    /// F154). The rect [`Self::caret_rect`] answers for a text node, for
1720    /// an editor.
1721    pub fn edit_caret_rect(&mut self, key: Key) -> Option<Rect> {
1722        self.note_read(|| replay::Read::Opaque);
1723        let origin = self.interaction.edit_origin_of(key)?;
1724        let local = self.edit_with_fonts(|edit, fs| edit.caret_local(key, fs))?;
1725        Some(self.turned_rect(
1726            key,
1727            Rect::new(origin.x + local.x, origin.y + local.y, 0.0, local.h),
1728        ))
1729    }
1730
1731    /// Puts editor `key`'s caret at the character nearest `point` (logical
1732    /// viewport px), with no selection, as a click there would — without
1733    /// the click: focus, the window's selection and the pointer are left
1734    /// alone, so an app moving the keyboard into the editor places its
1735    /// caret first and focuses it after (backlog F154). False for a key
1736    /// with no editor in the last frame.
1737    pub fn edit_caret_to(&mut self, key: Key, point: Vec2) -> bool {
1738        let Some(origin) = self.interaction.edit_origin_of(key) else {
1739            return false;
1740        };
1741        let q = self.unturned(key, point);
1742        let local = Vec2::new(q.x - origin.x, q.y - origin.y);
1743        self.edit_with_fonts(|edit, fs| edit.click(key, local, 1, false, fs));
1744        true
1745    }
1746
1747    /// Current text of an editor by key.
1748    pub fn edit_text(&self, key: Key) -> Option<String> {
1749        let t = self.edit.text(key);
1750        self.note_read(|| replay::Read::EditText(key, t.clone()));
1751        t
1752    }
1753
1754    /// Replaces an editor's text, leaving the caret at the end.
1755    ///
1756    /// The key need not have an editor behind it yet: an `update` that
1757    /// opens a rename field runs a frame ahead of the view that declares
1758    /// it, so the text is held and seeds the editor the next frame
1759    /// declares under this key, over its `initial`. Held for that one
1760    /// frame — a key nothing declares on it drops its text and raises
1761    /// [`crate::diag::EDIT_TEXT_WITHOUT_EDITOR`].
1762    ///
1763    /// Returns whether the text reached an editor now. `false` is the
1764    /// held case: nothing on screen changed, and a driver that redraws on
1765    /// it re-lowers the tree that declares no editor, which is the frame
1766    /// the hold expires on — so a binding asks for a redraw
1767    /// only on `true`.
1768    pub fn set_edit_text(&mut self, key: Key, text: &str) -> bool {
1769        let sess = &mut *self.session.state();
1770        self.edit
1771            .set_text(key, text, &mut sess.fonts, &sess.resources)
1772    }
1773
1774    /// The same call by the name the view declares — an editor's `key`
1775    /// prop / `label` — for the app that has no key to give: the hex key
1776    /// comes from an event the node fired, and an editor a rename opens
1777    /// for the first time has fired none.
1778    ///
1779    /// A label some frame declared resolves now ([`Core::key_of`]) and
1780    /// this is [`Core::set_edit_text`] on that key. One nothing has
1781    /// declared — a first open, or a second one, since an editor closed
1782    /// in between was in no recent frame — is held for the next frame
1783    /// that declares an editor under it, and seeds it there. An editor
1784    /// retained while its key was off screen takes the text over its
1785    /// draft, which is what a `set_edit_text` by key cannot say.
1786    ///
1787    /// Held for that one frame: a label nothing declares on it drops its
1788    /// text and raises [`crate::diag::EDIT_TEXT_WITHOUT_EDITOR`].
1789    ///
1790    /// Returns whether the text reached an editor now, as
1791    /// [`Core::set_edit_text`] does; a label held is `false`.
1792    pub fn set_edit_text_by_label(&mut self, label: &str, text: &str) -> bool {
1793        match self.key_of(label) {
1794            Some(key) => self.set_edit_text(key, text),
1795            None => {
1796                self.edit.hold_label(label, text);
1797                false
1798            }
1799        }
1800    }
1801
1802    /// The pointer shape for wherever the pointer is now, derived from the
1803    /// frame's hit regions (see [`crate::cursor`]). Per-frame output like
1804    /// the window commands, but a query rather than a drain: it is a state,
1805    /// not a queue, so a driver reads it after each input and each frame and
1806    /// only touches the window when the answer changes. Headless drivers
1807    /// never read it, and the core stays device-free.
1808    pub fn cursor_shape(&self) -> crate::cursor::CursorShape {
1809        self.interaction.cursor_shape()
1810    }
1811}
1812
1813/// The raw key an editing key came from, for the keys a focused control
1814/// acts on — the one place the two input channels have to name the same
1815/// press. `None` for the editing vocabulary
1816/// with no control behaviour behind it (Backspace, PageUp, Undo): those
1817/// arms do nothing on a control either way.
1818/// The key a `boundary` event names: one of the six that can meet an
1819/// edge, spelled as a key event spells it.
1820fn boundary_code(ek: EditKey) -> KeyCode {
1821    match ek {
1822        EditKey::Up => KeyCode::Up,
1823        EditKey::Down => KeyCode::Down,
1824        EditKey::Left => KeyCode::Left,
1825        EditKey::Right => KeyCode::Right,
1826        EditKey::Backspace => KeyCode::Backspace,
1827        _ => KeyCode::Delete,
1828    }
1829}
1830
1831fn edit_key_code(ek: EditKey) -> Option<KeyCode> {
1832    Some(match ek {
1833        EditKey::Enter => KeyCode::Enter,
1834        EditKey::Escape => KeyCode::Escape,
1835        EditKey::Tab => KeyCode::Tab,
1836        EditKey::Left => KeyCode::Left,
1837        EditKey::Right => KeyCode::Right,
1838        EditKey::Up => KeyCode::Up,
1839        EditKey::Down => KeyCode::Down,
1840        EditKey::Home => KeyCode::Home,
1841        EditKey::End => KeyCode::End,
1842        _ => return None,
1843    })
1844}
1845
1846/// The access tree is cached on a hash of what
1847/// derives it, so every input that hash misses is a frame that serves a
1848/// stale reading. One case per input `access::build` reads, each mutating
1849/// only that input and asserting the tree was derived again *and* came out
1850/// different; plus the case the cache exists for, where a frame changes
1851/// something the tree cannot see and keeps the one it had.
1852#[cfg(test)]
1853mod access_cache {
1854    use crate::access::{Live, Role};
1855    use crate::*;
1856
1857    /// Builds a frame from `spec` on a keyed node with a text child, reads
1858    /// the access tree, and reports (how many derivations have happened,
1859    /// the tree's own hash).
1860    fn frame(core: &mut Core, spec: NodeSpec) -> (u64, u64) {
1861        let mut ui = core.frame(Size::new(200.0, 100.0), 1.0);
1862        ui.configure_root(NodeSpec::column());
1863        ui.text_in_keyed("node", spec, "hello", TextStyle::new(12.0));
1864        ui.finish();
1865        let hash = core.access_tree().hash;
1866        (core.access_rebuilds, hash)
1867    }
1868
1869    /// The base node: a button, so it is a semantic node with a name.
1870    fn base() -> NodeSpec {
1871        NodeSpec::column()
1872            .size(40.0, 20.0)
1873            .on_click(Value::from(1.0))
1874            .label("Save")
1875    }
1876
1877    /// Draws `first`, then `second`, and says whether the second frame
1878    /// derived the tree again and whether the tree changed.
1879    fn change(first: NodeSpec, second: NodeSpec) -> (bool, bool) {
1880        let mut core = Core::new();
1881        let (b0, h0) = frame(&mut core, first.clone());
1882        let (b1, h1) = frame(&mut core, second);
1883        (b1 > b0, h1 != h0)
1884    }
1885
1886    /// The case the cache is for: a pointer moving over a hover background
1887    /// changes `style.bg` before the node is pushed, and the access tree
1888    /// cannot see a background. The tree is kept, not rebuilt.
1889    #[test]
1890    fn a_change_the_tree_cannot_see_keeps_the_tree() {
1891        let (rebuilt, moved) = change(base().bg(Color::WHITE), base().bg(Color::BLACK));
1892        assert!(!rebuilt, "a colour the access tree never reads rebuilt it");
1893        assert!(!moved, "and the tree would have been the same anyway");
1894    }
1895
1896    /// And the same frame twice: no input moved at all.
1897    #[test]
1898    fn an_identical_frame_keeps_the_tree() {
1899        assert_eq!(change(base(), base()), (false, false));
1900    }
1901
1902    macro_rules! moves_the_tree {
1903        ($($name:ident: $first:expr => $second:expr;)*) => {$(
1904            #[test]
1905            fn $name() {
1906                let (rebuilt, moved) = change($first, $second);
1907                assert!(rebuilt, "the tree was served from the cache");
1908                assert!(moved, "it was derived again but came out the same");
1909            }
1910        )*};
1911    }
1912
1913    moves_the_tree! {
1914        label:        base().label("Save") => base().label("Open");
1915        description:  base() => base().description("Writes the file");
1916        role:         base() => base().role(Role::Checkbox);
1917        clickable:    NodeSpec::column().label("x") => NodeSpec::column().label("x").on_click(Value::from(1.0));
1918        disabled:     base() => base().disabled(true);
1919        live:         base() => base().live(Live::Polite);
1920        checked:      base().role(Role::Checkbox) => base().role(Role::Checkbox).checked(true);
1921        selected:     base().role(Role::Tab) => base().role(Role::Tab).selected(true);
1922        expanded:     base() => base().expanded(true);
1923        value_now:    base().role(Role::Slider) => base().role(Role::Slider).value_now(3.0);
1924        value_min:    base().role(Role::Slider).value_now(3.0) => base().role(Role::Slider).value_now(3.0).value_min(1.0);
1925        value_text:   base().role(Role::Slider) => base().role(Role::Slider).value_text("three");
1926        focusable:    NodeSpec::column().role(Role::Group).label("g")
1927                          => NodeSpec::column().role(Role::Group).label("g").focusable();
1928        rect:         base() => base().width(80.0);
1929    }
1930
1931    /// The text a node is named by is not in its spec at all — it is the
1932    /// child text node's content, reached through the text system.
1933    #[test]
1934    fn the_text_a_node_reads_moves_the_tree() {
1935        let mut core = Core::new();
1936        let mut draw = |s: &str| {
1937            let mut ui = core.frame(Size::new(200.0, 100.0), 1.0);
1938            ui.configure_root(NodeSpec::column());
1939            ui.text(s, TextStyle::new(12.0));
1940            ui.finish();
1941            let h = core.access_tree().hash;
1942            (core.access_rebuilds, h)
1943        };
1944        let (b0, h0) = draw("hello");
1945        let (b1, h1) = draw("goodbye");
1946        assert!(b1 > b0 && h1 != h0, "a changed string kept its old node");
1947    }
1948
1949    /// The clip a node was emitted under is not in its spec either: a
1950    /// clipping parent narrowing cuts the rect of a node whose own box
1951    /// stayed where it was.
1952    #[test]
1953    fn a_parents_clip_moves_the_tree() {
1954        let mut core = Core::new();
1955        let mut draw = |w: f32| {
1956            let mut ui = core.frame(Size::new(200.0, 100.0), 1.0);
1957            ui.configure_root(NodeSpec::column());
1958            let clipper = NodeSpec::column().size(w, 40.0).clip();
1959            ui.with(clipper, |ui| {
1960                ui.leaf_keyed("node", base());
1961            });
1962            ui.finish();
1963            let hash = core.access_tree().hash;
1964            (core.access_rebuilds, hash)
1965        };
1966        let (b0, h0) = draw(100.0);
1967        let (b1, h1) = draw(30.0);
1968        assert!(b1 > b0 && h1 != h0, "the clip moved and the tree did not");
1969    }
1970
1971    /// Focus is the core's, not any node's spec.
1972    #[test]
1973    fn focus_moves_the_tree() {
1974        let mut core = Core::new();
1975        let (b0, h0) = frame(&mut core, base().focusable());
1976        core.set_key_focus(Some(Key::ROOT.str("node")));
1977        let (b1, h1) = frame(&mut core, base().focusable());
1978        assert!(b1 > b0 && h1 != h0, "focus moved and the tree did not");
1979    }
1980
1981    /// So is the scroll offset, which is retained across frames and only
1982    /// ever reaches the tree through the store.
1983    #[test]
1984    fn a_scroll_offset_moves_the_tree() {
1985        let mut core = Core::new();
1986        // Tall content, or the offset clamps to zero and nothing moved.
1987        let scroller = || NodeSpec::column().size(40.0, 20.0).scroll_y().label("list");
1988        let draw = |core: &mut Core| {
1989            let mut ui = core.frame(Size::new(200.0, 100.0), 1.0);
1990            ui.configure_root(NodeSpec::column());
1991            ui.with_keyed("node", scroller(), |ui| {
1992                ui.leaf_keyed("tall", NodeSpec::column().height(400.0));
1993            });
1994            ui.finish();
1995            let h = core.access_tree().hash;
1996            (core.access_rebuilds, h)
1997        };
1998        let (b0, h0) = draw(&mut core);
1999        core.set_scroll(Key::ROOT.str("node"), Vec2::new(0.0, 7.0));
2000        let (b1, h1) = draw(&mut core);
2001        assert!(b1 > b0 && h1 != h0, "the offset moved and the tree did not");
2002    }
2003
2004    /// An editor's text reaches the tree through the store, and its shaped
2005    /// runs through a version that stands in for them.
2006    #[test]
2007    fn editor_text_moves_the_tree() {
2008        let mut core = Core::new();
2009        let draw = |core: &mut Core, text: &str| {
2010            let mut ui = core.frame(Size::new(200.0, 100.0), 1.0);
2011            ui.configure_root(NodeSpec::column());
2012            let key = ui.text_edit(
2013                "name",
2014                text,
2015                &Default::default(),
2016                NodeSpec::column().size(120.0, 20.0),
2017            );
2018            ui.finish();
2019            let h = core.access_tree().hash;
2020            (core.access_rebuilds, h, key)
2021        };
2022        let (b0, h0, key) = draw(&mut core, "one");
2023        core.frame(Size::new(200.0, 100.0), 1.0).finish();
2024        core.set_edit_text(key, "typed");
2025        let (b1, h1, _) = draw(&mut core, "one");
2026        assert!(
2027            b1 > b0 && h1 != h0,
2028            "the editor's text moved and the tree did not"
2029        );
2030    }
2031
2032    /// And the viewport, which is the root node's whole rect.
2033    #[test]
2034    fn the_viewport_moves_the_tree() {
2035        let mut core = Core::new();
2036        let mut draw = |w: f32| {
2037            let mut ui = core.frame(Size::new(w, 100.0), 1.0);
2038            ui.configure_root(NodeSpec::column());
2039            ui.leaf_keyed("node", base());
2040            ui.finish();
2041            let h = core.access_tree().hash;
2042            (core.access_rebuilds, h)
2043        };
2044        let (b0, h0) = draw(200.0);
2045        let (b1, h1) = draw(300.0);
2046        assert!(
2047            b1 > b0 && h1 != h0,
2048            "the viewport moved and the tree did not"
2049        );
2050    }
2051}