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