Skip to main content

uzor_framework/engine/
input.rs

1//! InputEngine: focus scopes, pointer capture, cook, hover / press / click,
2//! text and IME, caret blink (design §3.4).
3//!
4//! The one writer of per-window interaction state. Each window has one
5//! library [`InputCoordinator`] as its storage (registrations, hit index,
6//! [`TextFieldStore`], widget state), one
7//! library [`CookState`] for event-level cooking, the pointer accumulator
8//! the coordinator's next frame is fed from, the focus-scope stack, the
9//! pointer capture and the caret-blink phase. Pure and deterministic: every
10//! time-dependent op carries the host clock.
11//!
12//! ## Coordinator access
13//!
14//! State-mutating coordinator methods (`begin_frame`, `end_frame`,
15//! `set_focus`, `clear_focus`, `focus_next` / `focus_prev`,
16//! `grab_pointer` / `release_pointer`, `on_char`, `on_key`, `process_*`,
17//! `push_layer` / `pop_layer`, `set_cursor_pos`) live on
18//! [`CoordinatorDriver`](uzor::input::driver::CoordinatorDriver). This
19//! engine is the one writer; ban F7 keeps that trait out of every other
20//! framework module except `kernel/`. [`InputEngine::registrar`] hands
21//! compose a `&mut InputCoordinator` for registration and reads only.
22//! `focus_text_field` and `text_fields_mut` stay inherent (L-F1 does not
23//! move them).
24//!
25//! ## Pointer (routing, design §4.3)
26//!
27//! - [`InputOp::Pointer`] is step 1: the engine's `CookState` counts clicks
28//!   (single / double / triple within `DOUBLE_CLICK_WINDOW_S` and
29//!   `MULTI_CLICK_MAX_DIST_PX`) and arms drags past `DRAG_THRESHOLD_PX`,
30//!   and the answer says whether a [`Capture`] owns the event (step 2). A
31//!   capture bypasses every hit test until the button is released (or the
32//!   OS cancels the gesture); the release itself still goes to the owner.
33//! - [`InputOp::Deliver`] is step 5: an event nothing above claimed enters
34//!   the coordinator's next-frame input (press / release edges; positions
35//!   always follow the pointer). Claimed presses never reach content. A
36//!   text-field drag writes the store selection on the press and on each
37//!   armed move: paint reads that store before `end_frame`, which only
38//!   commits the range on release.
39//! - [`InputOp::BeginFrame`] feeds the accumulated input to the coordinator
40//!   with `InputState::time` stamped from the host clock, so the
41//!   coordinator's own cook (fed in `end_frame`) reports real
42//!   `double_clicked` / `triple_clicked`. [`InputOp::EndFrame`] evaluates
43//!   the frame's registrations into hover and this frame's clicks.
44//!
45//! ## Focus scopes (H2 §3)
46//!
47//! A stack of `{ owner, members, saved focus }`. Pushing saves and clears
48//! the current focus; while a scope is active, focus can only move to one
49//! of its members (`FocusOp::Set` outside is a no-op, Tab / Shift+Tab cycle
50//! the members registered this frame in list order); popping the active
51//! scope with `restore` puts the saved focus back (a saved text field
52//! keeps its engagement), without `restore` clears it. Popping a scope
53//! below the top hands its saved focus to the scope above it. A click
54//! that focuses a text field outside the active scope is reverted at
55//! `EndFrame`, so focus is always inside the active scope. With no scope,
56//! Tab cycles every focusable widget (the coordinator's global order).
57//!
58//! ## Text and IME
59//!
60//! Key step 1 ([`InputOp::Key`]): with a focused text field, its editing
61//! chords (characters, Backspace / Delete, arrows with Shift / Ctrl word
62//! movement, Home / End, Ctrl+A / C / X / V, Enter) are consumed before any
63//! keymap binding; Tab / Shift+Tab move focus. Everything else is passed on
64//! ([`InputEffect::KeyPassed`]); Escape is never consumed here, so an
65//! overlay can close on it (step 2). IME preedit goes to
66//! `TextFieldStore::preedit_set` (an overlay span, never in the buffer);
67//! commit to `ime_commit`. Copy / cut report [`InputEffect::CopyText`]
68//! (masked fields never copy); paste asks the host with
69//! [`InputEffect::NeedPaste`] under an engine-minted ticket (at or above
70//! [`INPUT_TICKET_BASE`]) and inserts the [`InputOp::Clipboard`] answer if
71//! the same field is still focused. The IME caret area and the IME-allowed
72//! flag are reported only when they change.
73//!
74//! ## Clipboard for custom widgets
75//!
76//! One widget-facing contract on every host. Paste: the platform gesture's
77//! text ([`InputOp::Paste`], from `InputEvent::Paste` — the web host's DOM
78//! `paste` event) goes to the focused text field, else to the app as
79//! `UnhandledInput::Paste` ([`InputEffect::Pasted`]). Ctrl/Cmd+V with no
80//! field focused reads under an engine ticket like a field paste; a native
81//! host answers from the clipboard crate, the web host leaves it to the
82//! paste event of the same gesture (no `readText` permission prompt, no
83//! second insert: the paste settles the read). Copy / cut: the focused
84//! custom widget sets its answer ahead with `ClipboardCmd::Offer`; Ctrl/Cmd+C
85//! or X with no field and no page selection copies it
86//! ([`InputEffect::CopyText`]) and still passes the key on. The web host
87//! also writes the offer in the DOM `copy` / `cut` event (same gesture).
88//! A focused `BlackboxPanel` owns Ctrl/Cmd+A (no page-text escalation).
89//!
90//! Manual check (web): focus a non-field custom widget, put text on the OS
91//! clipboard, press Ctrl+V — the app gets `UnhandledInput::Paste` with it;
92//! in a text field the text lands once. Offer "x", press Ctrl+C, paste
93//! elsewhere: "x".
94//!
95//! ## Caret blink
96//!
97//! While a text field is focused and engaged (the user clicked or typed
98//! into it) and the window has OS focus, the engine keeps one deadline
99//! armed at the next blink edge ([`InputEffect::CaretDeadline`]; the kernel
100//! arms `TimerOwner::CaretBlink { win }`). Visibility is the store's
101//! `cursor_visible(now_ms)` (500 ms phases) anchored at the last caret
102//! change: any edit, caret move, selection, preedit or focus change
103//! restarts the phase visible. At each edge ([`InputEngine::tick`]) the
104//! engine flips visibility and asks for a repaint of only that field
105//! ([`InputEffect::InvalidateField`] with the field's last drawn rect; the
106//! kernel maps it to the region containing it). Blur, loss of window
107//! focus, un-engagement or the field being unregistered disarms it.
108//!
109//! ## Plain-text selection (T2)
110//!
111//! One selection owner per window, held here: selectable plain text has no
112//! store (unlike text fields), so the app reports each selectable widget's
113//! content and line geometry every frame through
114//! [`InputEngine::update_selectable`] (the compose-phase door, mirroring
115//! `TextFieldStore::update_field`; not revisioned — the change is evaluated
116//! at [`InputOp::EndFrame`]). A widget not reported this frame stops being
117//! selectable and its selection drops. The owner state is a small
118//! `Vec<(WidgetId, TextSelection)>` — usually one entry; a panel / window
119//! Ctrl+A escalation selects several widgets at once.
120//!
121//! A press on a selectable widget records the char under the pointer as
122//! the drag anchor; no pointer capture is taken — the cook state tracks
123//! the press window-wide, exactly the mechanism text fields use, and
124//! `char_at_point` clamps out-of-rect positions to the line ends. While
125//! the press is armed (or its release just ended the drag) the selection
126//! extends anchor → current pointer char every frame, so the highlight is
127//! live during the drag. A release that was not a drag and lands on the
128//! same selectable widget is a click: the selection collapses / expands to
129//! word / line by the press sequence's click count (the engine's own
130//! `CookState`, not the coordinator's click reporting — a label registers
131//! `Sense::HOVER` + `select`, no `click` bit, and must not start
132//! swallowing clicks). A press anywhere else clears the selection.
133//! Escape and focus changes do not clear it (browser-like).
134//!
135//! Keys, no focused text field: Ctrl+C with a non-empty selection reports
136//! [`InputEffect::CopyText`] (the same conduction as a field copy — the
137//! kernel enqueues `WindowCommand::ClipboardWrite`); with nothing selected
138//! the key routes on. Ctrl+A selects all with escalation
139//! widget → panel → window: the panel step takes every selectable whose
140//! rect is inside the nearest ancestor registered as `Panel` /
141//! `BlackboxPanel` (via `widget_parent`), the window step every selectable
142//! in the window; multi-widget selections copy in reading order
143//! (top-left, newline-joined). The escalation level resets on any
144//! pointer-driven selection.
145//!
146//! Every selection change repaints through the existing
147//! [`InputEffect::InvalidateField`] with the widget's rect, and is
148//! revisioned (the map is observable through
149//! [`InputEngineView::selections`]).
150//!
151//! Out of scope (recorded for the owner): word-granularity drag after a
152//! double click, Shift+click extend, drag-and-drop of selected text.
153//!
154//! ## Revision
155//!
156//! Bumped exactly when observable state changes: the window set, focus,
157//! scopes, capture, hover, pressed, this frame's clicks, the focused
158//! field's caret (text, cursor, selection, preedit, engagement), caret
159//! visibility and the plain-text selections. Pointer positions, cook
160//! bookkeeping, IME bookkeeping and a pending paste are not revisioned
161//! (they never appear in the snapshot).
162
163use crate::types::vecmap::VecMap;
164use std::collections::HashMap;
165use std::fmt;
166
167use smallvec::SmallVec;
168use uzor::input::core::cook::CookState;
169use uzor::input::driver::CoordinatorDriver;
170use uzor::input::text::selection::{char_at_point, SelectionLine, TextSelection};
171use uzor::input::{
172    InputCoordinator, InputState, KeyCode, KeyPress, ModifierKeys, MouseButton, TextAction,
173    TextFieldStore, WidgetKind,
174};
175use uzor::{Rect, WidgetId};
176
177use crate::types::bus::{
178    ClipboardResult, ImeInput, KeyInput, KeyState, PointerInput, WheelDelta, WheelInput,
179};
180use crate::types::ids::{Revision, ScopeId, Seconds, Ticket, WindowId};
181use crate::types::intent::TextIntent;
182use crate::types::ops::{
183    Capture, CookedPointer, FocusOp, InputEffect, InputOp, PointerTarget, ScopeOwner,
184};
185use crate::types::snapshot::InputView;
186
187/// Effects of one InputEngine op or tick.
188pub type InputEffects = SmallVec<[InputEffect; 2]>;
189
190/// First clipboard ticket the engine mints for paste. App tickets stay
191/// below it, so a `ClipboardResult` at or above it belongs to this engine.
192pub const INPUT_TICKET_BASE: u64 = 1 << 63;
193
194/// One caret blink phase (visible or hidden), the store's 500 ms.
195// Caret blink cadence a host applies when painting text fields.
196#[allow(dead_code)]
197pub const CARET_BLINK_INTERVAL: Seconds = Seconds(0.5);
198
199const CARET_BLINK_MS: u64 = 500;
200
201/// Logical pixels per wheel line, for pixel-unit wheel deltas (the same
202/// factor the desktop input bridge uses); the coordinator counts lines.
203const WHEEL_PIXELS_PER_LINE: f64 = 20.0;
204
205// ---------------------------------------------------------------------------
206// Per-window state
207// ---------------------------------------------------------------------------
208
209/// Pointer input gathered between two frames; becomes the coordinator's
210/// `InputState` at `BeginFrame`.
211#[derive(Clone, Debug, Default)]
212struct PointerAccum {
213    pos: Option<(f64, f64)>,
214    prev_pos: Option<(f64, f64)>,
215    button_down: Option<MouseButton>,
216    clicked: Option<MouseButton>,
217    /// Secondary-button release not yet read by a frame (context menus).
218    context: Option<(f64, f64)>,
219    mods: ModifierKeys,
220    scroll: (f64, f64),
221    /// The scroll came (at least partly) as pixel deltas (trackpad / smooth wheel).
222    scroll_precise: bool,
223}
224
225/// The focus the engine restores when a scope closes.
226#[derive(Clone, Debug, PartialEq, Eq)]
227struct SavedFocus {
228    id: WidgetId,
229    /// The saved widget was an engaged text field.
230    engaged: bool,
231}
232
233#[derive(Clone, Debug)]
234struct FocusScope {
235    owner: ScopeOwner,
236    members: Vec<WidgetId>,
237    saved: Option<SavedFocus>,
238}
239
240/// Plain selectable text reported for one frame through the compose door
241/// [`InputEngine::update_selectable`].
242#[derive(Clone, Debug)]
243struct SelectableText {
244    text: String,
245    lines: Vec<SelectionLine>,
246}
247
248/// The compose-phase sink a hook reports its selectable plain text into (the `Widgets`
249/// face): the DOM's "every text node is selectable" made explicit — a widget reported here
250/// gets press-drag / double / triple-click selection and Ctrl+C copy from the input engine.
251#[derive(Clone, Debug, Default)]
252pub struct Selectables(HashMap<WidgetId, SelectableText>, HashMap<WidgetId, WidgetId>);
253
254impl Selectables {
255    /// Report one selectable text widget for this frame: its text and, per wrapped line,
256    /// the char range, origin and glyph boundaries (`SelectionLine`).
257    pub fn report(&mut self, widget: impl Into<WidgetId>, text: impl Into<String>, lines: Vec<SelectionLine>) {
258        self.0.insert(widget.into(), SelectableText { text: text.into(), lines });
259    }
260    /// A press / click on `member` (a hit region, e.g. one wrapped line or one
261    /// bubble) acts on the selectable `owner`: one selection spans many regions,
262    /// like a DOM selection dragged across several elements of one container.
263    pub fn alias(&mut self, member: impl Into<WidgetId>, owner: impl Into<WidgetId>) {
264        self.1.insert(member.into(), owner.into());
265    }
266    fn contains_key(&self, w: &WidgetId) -> bool {
267        self.0.contains_key(w)
268    }
269}
270
271/// A press that began on a selectable widget: the selection drag anchor.
272#[derive(Clone, Debug)]
273struct PressSel {
274    widget: WidgetId,
275    anchor: usize,
276}
277
278/// Where a Ctrl+A escalation stands for its widget.
279#[derive(Clone, Copy, Debug, PartialEq, Eq)]
280enum EscLevel {
281    /// Last select-all covered only the widget itself.
282    Widget,
283    /// … every selectable inside the nearest panel ancestor.
284    Panel,
285    /// … every selectable in the window.
286    Window,
287}
288
289/// Everything about the focused text field whose change restarts the
290/// blink phase (geometry is deliberately not part of it).
291#[derive(Clone, Debug, PartialEq, Eq)]
292struct CaretKey {
293    field: WidgetId,
294    engaged: bool,
295    text: String,
296    cursor: usize,
297    selection: Option<usize>,
298    preedit: String,
299    preedit_cursor: usize,
300}
301
302/// The engine's own focus record: the widget the view reports.
303#[derive(Clone, Debug, PartialEq, Eq)]
304struct Focused {
305    id: WidgetId,
306    /// Focused through the text store (a registered text field).
307    field: bool,
308}
309
310struct PerWindowInput {
311    coord: InputCoordinator,
312    /// Per-widget persistent typed state (scroll offsets, expand flags);
313    /// the compose-phase door for the app hook's `Widgets` face (design
314    /// §3.4 names it here; F3 had no consumer, F7 does).
315    states: uzor::app_context::StateRegistry,
316    cook: CookState,
317    pointer: PointerAccum,
318    capture: Option<Capture>,
319    scopes: Vec<FocusScope>,
320    focus: Option<Focused>,
321    hover: Option<WidgetId>,
322    pressed: Option<WidgetId>,
323    clicked: SmallVec<[(WidgetId, u8); 2]>,
324    os_focused: bool,
325    caret: Option<CaretKey>,
326    blink_anchor_ms: u64,
327    caret_visible: bool,
328    armed: Option<Seconds>,
329    ime_area: Option<Rect>,
330    ime_allowed: bool,
331    /// An engine-minted paste read in flight: the field it was for, or
332    /// `None` (no text field: the answer goes to the app as pasted text).
333    pending_paste: Option<(Ticket, Option<WidgetId>)>,
334    /// The app's copy offer (`ClipboardCmd::Offer`).
335    offer: Option<String>,
336    // Plain-text selection (T2). `selectables` is last completed frame's
337    // reported set (read by pointer ops); the compose door fills
338    // `reported` and EndFrame swaps them.
339    selectables: HashMap<WidgetId, SelectableText>,
340    /// Hit regions acting on a selectable (last completed frame's `Selectables::alias`).
341    sel_alias: HashMap<WidgetId, WidgetId>,
342    reported: Selectables,
343    selections: Vec<(WidgetId, TextSelection)>,
344    press_sel: Option<PressSel>,
345    drag_ended: bool,
346    escalation: Option<(WidgetId, EscLevel)>,
347    /// `:focus-visible` modality: a non-modifier key press turns it on, a
348    /// pointer press turns it off; programmatic focus keeps the current one.
349    focus_visible: bool,
350    /// Clicks from Enter / Space on a focused control, joined to the next
351    /// `EndFrame`'s clicks.
352    key_clicks: Vec<WidgetId>,
353    /// The control a Space press armed; its release activates it.
354    space_armed: Option<WidgetId>,
355}
356
357/// Which keys activate a focused widget of `kind`, as `(Enter, Space)`,
358/// matching the DOM: a `<button>` clicks on Enter press and Space release,
359/// a link on Enter only, a checkbox / radio / switch on Space only.
360fn activation(kind: Option<WidgetKind>) -> (bool, bool) {
361    use WidgetKind as K;
362    match kind {
363        Some(K::Link) => (true, false),
364        Some(K::Checkbox | K::Radio | K::Toggle) => (false, true),
365        Some(K::Button | K::CloseButton | K::ChromeTab | K::DropdownTrigger | K::Item | K::ColorSwatch | K::Custom) | None => (true, true),
366        Some(_) => (false, false),
367    }
368}
369
370impl PerWindowInput {
371    fn new() -> Self {
372        Self {
373            coord: InputCoordinator::new(),
374            states: uzor::app_context::StateRegistry::new(),
375            cook: CookState::default(),
376            pointer: PointerAccum::default(),
377            capture: None,
378            scopes: Vec::new(),
379            focus: None,
380            hover: None,
381            pressed: None,
382            clicked: SmallVec::new(),
383            // A window the host just created is assumed focused until the
384            // host says otherwise (not every host sends the initial echo).
385            os_focused: true,
386            caret: None,
387            blink_anchor_ms: 0,
388            caret_visible: false,
389            armed: None,
390            ime_area: None,
391            ime_allowed: false,
392            pending_paste: None,
393            offer: None,
394            selectables: HashMap::new(),
395            sel_alias: HashMap::new(),
396            reported: Selectables::default(),
397            selections: Vec::new(),
398            press_sel: None,
399            drag_ended: false,
400            escalation: None,
401            focus_visible: false,
402            key_clicks: Vec::new(),
403            space_armed: None,
404        }
405    }
406
407    // -- focus ----------------------------------------------------------------
408
409    /// `id` may take focus: no scope is active, or it is a member of the
410    /// active one.
411    fn allowed(&self, id: &WidgetId) -> bool {
412        self.scopes.last().is_none_or(|s| s.members.contains(id))
413    }
414
415    /// Focus `id` in the coordinator (text fields through the store, which
416    /// also syncs widget focus; anything else blurs the store). No guard.
417    fn focus_raw(&mut self, id: WidgetId) {
418        let field = self.coord.text_fields().has_field(&id);
419        if field && self.coord.text_fields().is_focused(&id) {
420            // A click already focused the store (`begin_drag_at` runs
421            // before this record). `focus()` on that same field clears
422            // engagement, and the caret is drawn from the flag.
423            self.coord.set_focus(id.clone());
424        } else if field {
425            self.coord.focus_text_field(&id);
426        } else {
427            self.coord.set_focus(id.clone());
428        }
429        self.focus = Some(Focused { id, field });
430    }
431
432    fn clear_raw(&mut self) -> bool {
433        let had = self.focus.is_some() || self.coord.text_fields().focused().is_some();
434        self.coord.clear_focus();
435        self.focus = None;
436        had
437    }
438
439    fn focused_id(&self) -> Option<&WidgetId> {
440        self.focus.as_ref().map(|f| &f.id)
441    }
442
443    /// Tab order candidates: the active scope's members registered this
444    /// frame, in list order, without negative-`tabindex` ones.
445    fn scoped_candidates(&self) -> Option<Vec<WidgetId>> {
446        let scope = self.scopes.last()?;
447        Some(
448            scope
449                .members
450                .iter()
451                .filter(|m| self.coord.widget_rect(m).is_some() && self.coord.tab_index(m) >= 0)
452                .cloned()
453                .collect(),
454        )
455    }
456
457    /// Tab / Shift+Tab. `None` = there was nothing to move to.
458    fn cycle(&mut self, forward: bool) -> Option<bool> {
459        let before = self.focus.clone();
460        match self.scoped_candidates() {
461            Some(list) => {
462                if list.is_empty() {
463                    return None;
464                }
465                let n = list.len();
466                let at = self
467                    .focused_id()
468                    .and_then(|f| list.iter().position(|m| m == f));
469                let next = match (at, forward) {
470                    (Some(i), true) => (i + 1) % n,
471                    (None, true) => 0,
472                    (Some(i), false) => (i + n - 1) % n,
473                    (None, false) => n - 1,
474                };
475                if self.focused_id() != Some(&list[next]) {
476                    self.focus_raw(list[next].clone());
477                }
478            }
479            None => {
480                if forward {
481                    self.coord.focus_next();
482                } else {
483                    self.coord.focus_prev();
484                }
485                let target = self.coord.focused_widget().cloned()?;
486                if self.focused_id() != Some(&target) || !self.store_matches_focus() {
487                    self.focus_raw(target);
488                }
489            }
490        }
491        Some(self.focus != before)
492    }
493
494    /// The text store's focus agrees with the engine's record.
495    fn store_matches_focus(&self) -> bool {
496        let store = self.coord.text_fields().focused();
497        match &self.focus {
498            Some(f) if f.field => store == Some(&f.id),
499            _ => store.is_none(),
500        }
501    }
502
503    fn focus_op(
504        &mut self,
505        win: WindowId,
506        op: FocusOp,
507        next_scope: &mut u64,
508        fx: &mut InputEffects,
509    ) -> bool {
510        match op {
511            FocusOp::Set(id) => {
512                if !self.allowed(&id) || self.focused_id() == Some(&id) {
513                    return false;
514                }
515                self.focus_raw(id);
516                true
517            }
518            FocusOp::Clear => self.clear_raw(),
519            FocusOp::Next => self.cycle(true).unwrap_or(false),
520            FocusOp::Prev => self.cycle(false).unwrap_or(false),
521            FocusOp::PushScope { owner, members } => {
522                if self.scopes.iter().any(|s| s.owner == owner) {
523                    return self.set_members(&owner, members);
524                }
525                let saved = self.focus.as_ref().map(|f| SavedFocus {
526                    engaged: f.field && self.coord.text_fields().is_engaged(&f.id),
527                    id: f.id.clone(),
528                });
529                self.clear_raw();
530                self.scopes.push(FocusScope {
531                    owner: owner.clone(),
532                    members,
533                    saved,
534                });
535                *next_scope += 1;
536                fx.push(InputEffect::ScopePushed {
537                    win,
538                    owner,
539                    scope: ScopeId(*next_scope),
540                });
541                true
542            }
543            FocusOp::SetMembers { owner, members } => self.set_members(&owner, members),
544            FocusOp::PopScope { owner, restore } => self.pop_scope(&owner, restore),
545        }
546    }
547
548    fn set_members(&mut self, owner: &ScopeOwner, members: Vec<WidgetId>) -> bool {
549        let Some(i) = self.scopes.iter().position(|s| &s.owner == owner) else {
550            return false;
551        };
552        if self.scopes[i].members == members {
553            return false;
554        }
555        self.scopes[i].members = members;
556        let active = i + 1 == self.scopes.len();
557        if active {
558            if let Some(f) = self.focused_id().cloned() {
559                if !self.allowed(&f) {
560                    self.clear_raw();
561                }
562            }
563        }
564        true
565    }
566
567    fn pop_scope(&mut self, owner: &ScopeOwner, restore: bool) -> bool {
568        let Some(i) = self.scopes.iter().position(|s| &s.owner == owner) else {
569            return false;
570        };
571        let scope = self.scopes.remove(i);
572        if i < self.scopes.len() {
573            // A scope below the top closed: the scope above saved a focus
574            // inside it, which is gone; it inherits the closed scope's.
575            self.scopes[i].saved = scope.saved;
576            return true;
577        }
578        self.clear_raw();
579        if let (true, Some(saved)) = (restore, scope.saved) {
580            if self.allowed(&saved.id) {
581                self.focus_raw(saved.id.clone());
582                if saved.engaged {
583                    self.coord.text_fields_mut().engage(&saved.id);
584                }
585            }
586        }
587        true
588    }
589
590    /// After `end_frame`: accept a click-focus into a text field, revert
591    /// one outside the active scope, and forget a field that disappeared.
592    fn reconcile_focus(&mut self) -> bool {
593        let store = self.coord.text_fields().focused().cloned();
594        match (store, self.focus.clone()) {
595            (Some(s), Some(f)) if f.field && s == f.id => false,
596            (Some(s), _) if self.allowed(&s) => {
597                self.coord.set_focus(s.clone());
598                self.focus = Some(Focused { id: s, field: true });
599                true
600            }
601            (Some(_), prev) => {
602                // Clicked into a field the active scope does not contain.
603                self.coord.text_fields_mut().blur();
604                if let Some(f) = prev.filter(|f| f.field) {
605                    let engaged = self.coord.text_fields().is_engaged(&f.id);
606                    self.coord.focus_text_field(&f.id);
607                    if engaged {
608                        self.coord.text_fields_mut().engage(&f.id);
609                    }
610                }
611                false
612            }
613            (None, Some(f)) if f.field => {
614                // The focused field was unregistered or blurred.
615                self.coord.clear_focus();
616                self.focus = None;
617                true
618            }
619            (None, _) => false,
620        }
621    }
622
623    // -- pointer --------------------------------------------------------------
624
625    fn set_capture(&mut self, capture: Option<Capture>) -> bool {
626        if self.capture == capture {
627            return false;
628        }
629        if let Some(Capture::Widget(_)) = &self.capture {
630            self.coord.release_pointer();
631        }
632        if let Some(Capture::Widget(id)) = &capture {
633            self.coord.grab_pointer(id.clone());
634        }
635        self.capture = capture;
636        true
637    }
638
639    fn cook(&mut self, win: WindowId, now: Seconds, input: PointerInput) -> (bool, CookedPointer) {
640        let t = now.get();
641        let target = match &self.capture {
642            Some(c) => PointerTarget::Captured(c.clone()),
643            None => PointerTarget::HitTest,
644        };
645        let mut drag_started = false;
646        let mut ended_drag = false;
647        let mut changed = false;
648        // Any press (content, chrome, dock) ends keyboard modality; the
649        // ring it hides needs a repaint.
650        if matches!(input, PointerInput::Down { .. }) && self.focus_visible {
651            self.focus_visible = false;
652            changed = true;
653        }
654        match input {
655            PointerInput::Moved { pos, mods } => {
656                self.pointer.pos = Some((pos.x, pos.y));
657                self.pointer.mods = mods;
658                drag_started = self.cook.motion(pos.x, pos.y).drag_started;
659            }
660            PointerInput::Down { pos, button, mods } => {
661                self.pointer.pos = Some((pos.x, pos.y));
662                self.pointer.mods = mods;
663                // A second button during a held press does not restart it.
664                if self.cook.press_origin.is_none() {
665                    self.cook.press(pos.x, pos.y, button, t);
666                }
667            }
668            PointerInput::Up { pos, button, mods } => {
669                self.pointer.pos = Some((pos.x, pos.y));
670                self.pointer.mods = mods;
671                if self.cook.press_origin.map(|o| o.button) == Some(button) {
672                    ended_drag = self.cook.release(pos.x, pos.y, button, t);
673                    self.drag_ended |= ended_drag;
674                    changed = self.set_capture(None);
675                }
676            }
677            PointerInput::Entered | PointerInput::RawDelta { .. } => {}
678            PointerInput::Left => self.pointer.pos = None,
679            PointerInput::Cancelled => {
680                self.cook.press_origin = None;
681                self.cook.drag_armed = false;
682                self.pointer.button_down = None;
683                changed = self.set_capture(None);
684                changed |= self.pressed.take().is_some();
685                self.press_sel = None;
686                self.drag_ended = false;
687            }
688        }
689        // A drag starting on a pressed drag-sensitive widget captures the
690        // pointer for it (design §4.3, routing step 2): from here every
691        // event goes to the widget until pointer-up.
692        if drag_started {
693            let grab = self
694                .pressed
695                .clone()
696                .filter(|id| self.coord.widget_sense(id).is_some_and(|s| s.drag));
697            if let Some(id) = grab {
698                changed = self.set_capture(Some(Capture::Widget(id)));
699            }
700        }
701        let cooked = CookedPointer {
702            win,
703            input,
704            click_count: self.cook.click_count,
705            drag_armed: self.cook.drag_armed,
706            drag_started,
707            ended_drag,
708            target,
709        };
710        (changed, cooked)
711    }
712
713    /// The content widget a pointer at `pos` goes to: the capturing widget,
714    /// else the topmost hit of last frame's registrations.
715    fn content_target(&self, pos: Option<(f64, f64)>) -> Option<WidgetId> {
716        if let Some(Capture::Widget(id)) = &self.capture {
717            return Some(id.clone());
718        }
719        let (x, y) = pos?;
720        self.coord.hit_test_now(x, y)
721    }
722
723    fn deliver(
724        &mut self,
725        win: WindowId,
726        input: PointerInput,
727        fx: &mut InputEffects,
728    ) -> (bool, Option<WidgetId>) {
729        match input {
730            PointerInput::Moved { pos, .. } => {
731                self.pointer.pos = Some((pos.x, pos.y));
732                // A held drag repaints so hooks see the moving pointer; so does a move
733                // onto another widget (or off all of them), so hover paints without
734                // waiting for the next unrelated input.
735                let target = self.content_target(self.pointer.pos);
736                let mut changed = self.pointer.button_down.is_some() || target != self.hover;
737                // `cook` already armed this move. The highlight is the store
738                // range, and the frame paints it before `end_frame`.
739                if self.pointer.button_down == Some(MouseButton::Left)
740                    && self.cook.drag_armed
741                    && self.coord.text_fields().drag_active()
742                {
743                    self.coord.text_fields_mut().on_drag_move_xy(pos.x, pos.y);
744                    changed = true;
745                }
746                (changed, target)
747            }
748            PointerInput::Down { pos, button, .. } => {
749                self.pointer.pos = Some((pos.x, pos.y));
750                self.pointer.button_down = Some(button);
751                // A release no frame has evaluated yet belongs to the previous
752                // gesture; carried into this press it would click whatever is
753                // under the pointer now.
754                self.pointer.clicked = None;
755                let target = self.content_target(self.pointer.pos);
756                let changed = self.pressed != target;
757                self.pressed.clone_from(&target);
758                let t = target.as_ref().map(|t| self.sel_owner(t));
759                let sel_changed = self.press_down(win, t.as_ref(), pos.x, pos.y, fx);
760                if button == MouseButton::Left {
761                    self.arm_text_drag(target.as_ref(), pos.x, pos.y);
762                } else if self.coord.text_fields().drag_active() {
763                    self.coord.text_fields_mut().on_drag_end();
764                }
765                let blurred = self.blur_text_on_outside_press(target.as_ref());
766                (changed | sel_changed | blurred, target)
767            }
768            PointerInput::Up { pos, button, .. } => {
769                self.pointer.pos = Some((pos.x, pos.y));
770                self.pointer.button_down = None;
771                self.pointer.clicked = Some(button);
772                if button == MouseButton::Right {
773                    self.pointer.context = Some((pos.x, pos.y));
774                }
775                let target = self.content_target(self.pointer.pos);
776                let _ = self.pressed.take();
777                let t = target.as_ref().map(|t| self.sel_owner(t));
778                let _ = self.release_select(win, t.as_ref(), fx);
779                // A real drag keeps the range (`anchor != cursor`); a click
780                // drops the degenerate one. `end_frame` then commits either
781                // `select_drag` or `select_at_click_count`.
782                if button == MouseButton::Left && self.coord.text_fields().drag_active() {
783                    self.coord.text_fields_mut().on_drag_end();
784                }
785                // Always repaint on release: only a frame evaluates the click
786                // (`pointer.clicked`), on any cadence.
787                (true, target)
788            }
789            PointerInput::Entered
790            | PointerInput::Left
791            | PointerInput::Cancelled
792            | PointerInput::RawDelta { .. } => (false, None),
793        }
794    }
795
796    /// Press on a text field: place the caret and arm a drag so later moves
797    /// extend the selection while the button is held. A double or triple
798    /// click is left to `end_frame` (`select_at_click_count` selects the
799    /// word or the line). Any other press ends a stale text drag so it
800    /// cannot follow the pointer onto another control.
801    fn arm_text_drag(&mut self, target: Option<&WidgetId>, x: f64, y: f64) {
802        let field = match target {
803            Some(id)
804                if self.coord.widget_sense(id).is_some_and(|s| s.text)
805                    && self.coord.text_fields().has_field(id) =>
806            {
807                Some(id.clone())
808            }
809            _ => None,
810        };
811        if let Some(id) = field {
812            if self.cook.click_count <= 1 {
813                self.coord.text_fields_mut().begin_drag_at_xy(id, x, y);
814                return;
815            }
816        }
817        if self.coord.text_fields().drag_active() {
818            self.coord.text_fields_mut().on_drag_end();
819        }
820    }
821
822    /// A press that misses every text field drops the caret. Paint reads
823    /// focus before `end_frame`, so the store and the engine record have to
824    /// be clear on the press itself.
825    fn blur_text_on_outside_press(&mut self, target: Option<&WidgetId>) -> bool {
826        let on_field = target.is_some_and(|id| {
827            self.coord.text_fields().has_field(id)
828                && self.coord.widget_sense(id).is_some_and(|s| s.text)
829        });
830        if on_field || self.coord.text_fields().focused().is_none() {
831            return false;
832        }
833        self.coord.clear_focus();
834        if self.focus.as_ref().is_some_and(|f| f.field) {
835            self.focus = None;
836        }
837        true
838    }
839
840    /// A release on the same selectable widget the press began on, and
841    /// the press never crossed the drag threshold: a click. The selection
842    /// collapses / expands to word / line by the click count.
843    fn release_select(
844        &mut self,
845        win: WindowId,
846        target: Option<&WidgetId>,
847        fx: &mut InputEffects,
848    ) -> bool {
849        if self.drag_ended {
850            return false;
851        }
852        let Some(p) = self.press_sel.clone() else {
853            return false;
854        };
855        if target != Some(&p.widget) {
856            return false;
857        }
858        let Some(st) = self.selectables.get(&p.widget) else {
859            return false;
860        };
861        let sel = TextSelection::for_click_count(&st.text, p.anchor, self.cook.click_count.max(1));
862        let changed = self.set_selection(win, &p.widget, sel, fx);
863        self.escalation = Some((p.widget, EscLevel::Widget));
864        changed
865    }
866
867    fn wheel(&mut self, input: WheelInput) -> Option<WidgetId> {
868        let (dx, dy) = match input.delta {
869            WheelDelta::Lines { x, y } => (x, y),
870            WheelDelta::Pixels { x, y } => {
871                self.pointer.scroll_precise = true;
872                (x / WHEEL_PIXELS_PER_LINE, y / WHEEL_PIXELS_PER_LINE)
873            }
874        };
875        self.pointer.pos = Some((input.pos.x, input.pos.y));
876        self.pointer.mods = input.mods;
877        self.pointer.scroll.0 += dx;
878        self.pointer.scroll.1 += dy;
879        if let Some(Capture::Widget(id)) = &self.capture {
880            return Some(id.clone());
881        }
882        self.coord.process_scroll(input.pos.x, input.pos.y)
883    }
884
885    // -- plain-text selection (T2) -------------------------------------------
886
887    /// The selectable a hit widget acts on (itself unless aliased).
888    fn sel_owner(&self, w: &WidgetId) -> WidgetId {
889        self.sel_alias.get(w).unwrap_or(w).clone()
890    }
891
892    fn sel_get(&self, widget: &WidgetId) -> Option<TextSelection> {
893        self.selections
894            .iter()
895            .find(|(w, _)| w == widget)
896            .map(|(_, s)| *s)
897    }
898
899    fn sel_set(&mut self, widget: WidgetId, sel: TextSelection) -> bool {
900        if let Some(slot) = self.selections.iter_mut().find(|(w, _)| *w == widget) {
901            if slot.1 == sel {
902                return false;
903            }
904            slot.1 = sel;
905            return true;
906        }
907        self.selections.push((widget, sel));
908        true
909    }
910
911    fn sel_remove(&mut self, widget: &WidgetId) -> bool {
912        let before = self.selections.len();
913        self.selections.retain(|(w, _)| w != widget);
914        self.selections.len() != before
915    }
916
917    /// Set one widget's selection, repainting it on change.
918    fn set_selection(
919        &mut self,
920        win: WindowId,
921        widget: &WidgetId,
922        sel: TextSelection,
923        fx: &mut InputEffects,
924    ) -> bool {
925        if !self.sel_set(widget.clone(), sel) {
926            return false;
927        }
928        fx.push(InputEffect::InvalidateField {
929            win,
930            rect: self.coord.widget_rect(widget),
931        });
932        true
933    }
934
935    /// Drop every selection, repainting on change.
936    fn clear_selections(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
937        if self.selections.is_empty() {
938            return false;
939        }
940        for (w, _) in &self.selections {
941            fx.push(InputEffect::InvalidateField {
942                win,
943                rect: self.coord.widget_rect(w),
944            });
945        }
946        self.selections.clear();
947        self.escalation = None;
948        true
949    }
950
951    /// Selectable widget ids in reading order (top-left), for multi-widget
952    /// select-all and copy concatenation.
953    fn selectable_ids_by_row(&self) -> Vec<WidgetId> {
954        let mut ids: Vec<(f64, f64, WidgetId)> = self
955            .selectables
956            .keys()
957            .map(|w| {
958                let r = self
959                    .coord
960                    .widget_rect(w)
961                    .unwrap_or_else(|| Rect::new(0.0, 0.0, 0.0, 0.0));
962                (r.y, r.x, w.clone())
963            })
964            .collect();
965        uzor::sort::sort_by(&mut ids, |a, b| a.0.total_cmp(&b.0).then_with(|| a.1.total_cmp(&b.1)));
966        ids.into_iter().map(|(_, _, w)| w).collect()
967    }
968
969    /// The selected text of every selected widget, reading order, newline
970    /// joined; `None` when nothing (or only carets) is selected.
971    fn selected_text_concat(&self) -> Option<String> {
972        if self.selections.is_empty() {
973            return None;
974        }
975        let mut parts: Vec<String> = Vec::new();
976        for w in self.selectable_ids_by_row() {
977            if let (Some(sel), Some(st)) = (self.sel_get(&w), self.selectables.get(&w)) {
978                let s = sel.selected_text(&st.text);
979                if !s.is_empty() {
980                    parts.push(s.to_owned());
981                }
982            }
983        }
984        if parts.is_empty() {
985            None
986        } else {
987            Some(parts.join("\n"))
988        }
989    }
990
991    /// The rect of the nearest ancestor registered as `Panel` /
992    /// `BlackboxPanel`, if any — the Ctrl+A escalation boundary.
993    fn nearest_panel_rect(&self, widget: &WidgetId) -> Option<Rect> {
994        let mut cur = self.coord.widget_parent(widget);
995        while let Some(p) = cur {
996            if matches!(
997                self.coord.widget_kind(&p),
998                Some(WidgetKind::Panel | WidgetKind::BlackboxPanel)
999            ) {
1000                return self.coord.widget_rect(&p);
1001            }
1002            cur = self.coord.widget_parent(&p);
1003        }
1004        None
1005    }
1006
1007    /// Select-all of every selectable whose rect is inside `rect`.
1008    fn select_in_rect(&mut self, win: WindowId, rect: &Rect, fx: &mut InputEffects) -> bool {
1009        let mut changed = false;
1010        for w in self.selectable_ids_by_row() {
1011            if let Some(r) = self.coord.widget_rect(&w) {
1012                let inside = r.x >= rect.x
1013                    && r.y >= rect.y
1014                    && r.x + r.width <= rect.x + rect.width
1015                    && r.y + r.height <= rect.y + rect.height;
1016                if inside {
1017                    if let Some(st) = self.selectables.get(&w) {
1018                        let sel = TextSelection::all(&st.text);
1019                        changed |= self.set_selection(win, &w, sel, fx);
1020                    }
1021                }
1022            }
1023        }
1024        changed
1025    }
1026
1027    /// Select-all of every selectable in the window.
1028    fn select_everything(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
1029        let mut changed = false;
1030        for w in self.selectable_ids_by_row() {
1031            if let Some(st) = self.selectables.get(&w) {
1032                let sel = TextSelection::all(&st.text);
1033                changed |= self.set_selection(win, &w, sel, fx);
1034            }
1035        }
1036        changed
1037    }
1038
1039    /// A press landed on `target` (`None` = empty space): anything selected
1040    /// that is not the target clears; a selectable target starts a press.
1041    fn press_down(
1042        &mut self,
1043        win: WindowId,
1044        target: Option<&WidgetId>,
1045        x: f64,
1046        y: f64,
1047        fx: &mut InputEffects,
1048    ) -> bool {
1049        let mut changed = false;
1050        if !target.is_some_and(|t| self.sel_get(t).is_some()) {
1051            changed |= self.clear_selections(win, fx);
1052        }
1053        self.press_sel = None;
1054        if let Some(t) = target {
1055            if let Some(st) = self.selectables.get(t) {
1056                let anchor = char_at_point(&st.lines, x, y);
1057                self.press_sel = Some(PressSel {
1058                    widget: t.clone(),
1059                    anchor,
1060                });
1061            }
1062        }
1063        changed
1064    }
1065
1066    /// Selection bookkeeping at EndFrame: live drag extension, click
1067    /// selection, press-session cleanup, stale-widget pruning.
1068    fn selection_frame(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
1069        let mut changed = false;
1070
1071        // Live drag: the press is armed past the threshold (or its release
1072        // just ended the drag) — extend the selection to the current
1073        // pointer char every frame, so the highlight is live.
1074        if let Some(p) = self.press_sel.clone() {
1075            if self.cook.drag_armed || self.drag_ended {
1076                if let (Some(st), Some((x, y))) =
1077                    (self.selectables.get(&p.widget), self.pointer.pos)
1078                {
1079                    let sel = TextSelection::new(p.anchor, char_at_point(&st.lines, x, y));
1080                    changed |= self.set_selection(win, &p.widget, sel, fx);
1081                }
1082            }
1083        }
1084
1085        // Click selection happens at the release (Deliver Up), not here —
1086        // a label has no `click` sense, so the coordinator never reports
1087        // its clicks.
1088
1089        // The press session ends when the button is up.
1090        if self.pointer.button_down.is_none() {
1091            self.press_sel = None;
1092            self.drag_ended = false;
1093        }
1094
1095        // Prune: only widgets reported this frame stay selectable; their
1096        // selections drop with them.
1097        let fresh = std::mem::take(&mut self.reported);
1098        let gone: Vec<WidgetId> = self
1099            .selections
1100            .iter()
1101            .map(|(w, _)| w.clone())
1102            .filter(|w| !fresh.contains_key(w))
1103            .collect();
1104        if !gone.is_empty() {
1105            for w in &gone {
1106                fx.push(InputEffect::InvalidateField {
1107                    win,
1108                    rect: self.coord.widget_rect(w),
1109                });
1110                self.sel_remove(w);
1111            }
1112            if let Some((w, _)) = &self.escalation {
1113                if gone.contains(w) {
1114                    self.escalation = None;
1115                }
1116            }
1117            changed = true;
1118        }
1119        self.selectables = fresh.0;
1120        self.sel_alias = fresh.1;
1121
1122        changed
1123    }
1124
1125    /// Ctrl+A with no focused text field: select all, escalating widget →
1126    /// panel → window across repeated presses. `Some(changed)` = consumed;
1127    /// `None` = no selectable context (the key routes on).
1128    fn ctrl_a(&mut self, win: WindowId, fx: &mut InputEffects) -> Option<bool> {
1129        if let Some((w, level)) = self.escalation.clone() {
1130            let next = match level {
1131                EscLevel::Widget => match self.nearest_panel_rect(&w) {
1132                    Some(rect) => {
1133                        self.select_in_rect(win, &rect, fx);
1134                        EscLevel::Panel
1135                    }
1136                    None => {
1137                        self.select_everything(win, fx);
1138                        EscLevel::Window
1139                    }
1140                },
1141                EscLevel::Panel => {
1142                    self.select_everything(win, fx);
1143                    EscLevel::Window
1144                }
1145                EscLevel::Window => return Some(false),
1146            };
1147            self.escalation = Some((w, next));
1148            return Some(true);
1149        }
1150        // First press: the hovered selectable, else the single selection.
1151        let start = self
1152            .hover
1153            .clone()
1154            .filter(|h| self.selectables.contains_key(h))
1155            .or_else(|| (self.selections.len() == 1).then(|| self.selections[0].0.clone()));
1156        let w = start?;
1157        let st = self.selectables.get(&w)?;
1158        let sel = TextSelection::all(&st.text);
1159        let changed = self.set_selection(win, &w, sel, fx);
1160        self.escalation = Some((w, EscLevel::Widget));
1161        Some(changed)
1162    }
1163
1164    // -- frame ----------------------------------------------------------------
1165
1166    fn begin_frame(&mut self, now: Seconds) -> bool {
1167        let mut state = InputState::new();
1168        state.pointer.pos = self.pointer.pos;
1169        state.pointer.prev_pos = self.pointer.prev_pos;
1170        state.pointer.button_down = self.pointer.button_down;
1171        state.pointer.clicked = self.pointer.clicked.take();
1172        state.modifiers = self.pointer.mods;
1173        state.scroll_delta = std::mem::take(&mut self.pointer.scroll);
1174        self.pointer.scroll_precise = false;
1175        self.pointer.context = None;
1176        state.time = now.get();
1177        self.pointer.prev_pos = self.pointer.pos;
1178        self.coord.begin_frame(state);
1179        let had_clicks = !self.clicked.is_empty();
1180        self.clicked.clear();
1181        had_clicks
1182    }
1183
1184    fn end_frame(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
1185        let mut hover = None;
1186        let mut clicked = SmallVec::new();
1187        for (id, r) in self.coord.end_frame() {
1188            if r.hovered {
1189                hover = Some(id.clone());
1190            }
1191            if r.clicked {
1192                let count = if r.triple_clicked {
1193                    3
1194                } else if r.double_clicked {
1195                    2
1196                } else {
1197                    1
1198                };
1199                clicked.push((id, count));
1200            }
1201        }
1202        for w in self.key_clicks.drain(..) {
1203            if !clicked.iter().any(|(c, _)| *c == w) {
1204                clicked.push((w, 1));
1205            }
1206        }
1207        let mut changed = hover != self.hover || clicked != self.clicked;
1208        self.hover = hover;
1209        self.clicked = clicked.clone();
1210        // A click on a focusable widget inside the active scope focuses
1211        // it (design §4.3, routing step 6); text fields reconcile below.
1212        let clicked_focus = clicked
1213            .iter()
1214            .map(|(id, _)| id.clone())
1215            .find(|id| self.allowed(id) && self.coord.widget_sense(id).is_some_and(|s| s.focus));
1216        if let Some(id) = clicked_focus {
1217            if self.focused_id() != Some(&id) {
1218                self.focus_raw(id);
1219                changed = true;
1220            }
1221        }
1222        changed |= self.selection_frame(win, fx);
1223        changed |= self.reconcile_focus();
1224        changed
1225    }
1226
1227    // -- text -----------------------------------------------------------------
1228
1229    /// The focused text field, when the store and the record agree.
1230    fn text_focus(&self) -> Option<WidgetId> {
1231        let f = self.focus.as_ref().filter(|f| f.field)?;
1232        self.coord
1233            .text_fields()
1234            .is_focused(&f.id)
1235            .then(|| f.id.clone())
1236    }
1237
1238    fn key(
1239        &mut self,
1240        win: WindowId,
1241        input: KeyInput,
1242        next_ticket: &mut u64,
1243        fx: &mut InputEffects,
1244    ) -> bool {
1245        let m = input.mods;
1246        if input.code == KeyCode::Space && input.state == KeyState::Up {
1247            if let Some(w) = self.space_armed.take() {
1248                if self.focused_id() == Some(&w) {
1249                    self.key_clicks.push(w);
1250                    return true;
1251                }
1252            }
1253        }
1254        if input.state == KeyState::Up {
1255            fx.push(InputEffect::KeyPassed { win, key: input });
1256            return false;
1257        }
1258        if input.code != KeyCode::Unknown {
1259            self.focus_visible = true;
1260        }
1261        // Enter / Space on a focused control (not a text field) activate it.
1262        if matches!(input.code, KeyCode::Enter | KeyCode::Space) && !(m.ctrl || m.alt || m.meta) {
1263            if let Some(f) = self.focus.as_ref().filter(|f| !f.field).map(|f| f.id.clone()) {
1264                if self.coord.widget_sense(&f).is_some_and(|s| s.click) {
1265                    let (enter, space) = activation(self.coord.widget_kind(&f));
1266                    if input.code == KeyCode::Enter && enter {
1267                        self.key_clicks.push(f);
1268                        return true;
1269                    }
1270                    if input.code == KeyCode::Space && space {
1271                        self.space_armed = Some(f);
1272                        return false;
1273                    }
1274                }
1275            }
1276        }
1277        if input.code == KeyCode::Tab && !(m.ctrl || m.alt || m.meta) {
1278            return match self.cycle(!m.shift) {
1279                Some(changed) => changed,
1280                None => {
1281                    fx.push(InputEffect::KeyPassed { win, key: input });
1282                    false
1283                }
1284            };
1285        }
1286        let field = self.text_focus();
1287        let mut edit = editing_chord(&input);
1288        // A multiline field with laid lines moves its caret between them.
1289        if edit.is_none() && matches!(input.code, KeyCode::ArrowUp | KeyCode::ArrowDown) && !(m.ctrl || m.alt || m.meta) {
1290            if field.as_ref().is_some_and(|f| self.coord.text_fields().has_lines(f)) {
1291                edit = Some(Edit::Key(if input.code == KeyCode::ArrowUp { KeyPress::ArrowUp } else { KeyPress::ArrowDown }));
1292            }
1293        }
1294        let (field, edit) = match (field, edit) {
1295            (Some(f), Some(e)) => (f, e),
1296            // No focused text field: a plain-text selection takes the copy
1297            // / select-all chords; with nothing selected they route on.
1298            (None, Some(Edit::Copy)) => {
1299                if let Some(text) = self.selected_text_concat() {
1300                    fx.push(InputEffect::CopyText { win, text });
1301                } else {
1302                    // The focused custom widget's offer answers the copy;
1303                    // the key still reaches it.
1304                    if let Some(text) = self.offer.clone() {
1305                        fx.push(InputEffect::CopyText { win, text });
1306                    }
1307                    fx.push(InputEffect::KeyPassed { win, key: input });
1308                }
1309                return false;
1310            }
1311            (None, Some(Edit::Cut)) => {
1312                if let Some(text) = self.offer.clone() {
1313                    fx.push(InputEffect::CopyText { win, text });
1314                }
1315                fx.push(InputEffect::KeyPassed { win, key: input });
1316                return false;
1317            }
1318            (None, Some(Edit::Paste)) => {
1319                // No text field: the clipboard text goes to the app
1320                // (`UnhandledInput::Paste`). A web host answers with the DOM
1321                // paste event instead of a read.
1322                let ticket = Ticket(INPUT_TICKET_BASE.saturating_add(*next_ticket));
1323                *next_ticket = next_ticket.saturating_add(1);
1324                self.pending_paste = Some((ticket, None));
1325                fx.push(InputEffect::NeedPaste { win, ticket });
1326                return false;
1327            }
1328            (None, Some(Edit::Key(KeyPress::SelectAll)))
1329                if self.focus.as_ref().is_some_and(|f| !f.field && self.coord.widget_kind(&f.id).is_some_and(|k| k.is_blackbox())) =>
1330            {
1331                // A focused blackbox (terminal, remote view) owns its Ctrl+A.
1332                fx.push(InputEffect::KeyPassed { win, key: input });
1333                return false;
1334            }
1335            (None, Some(Edit::Key(KeyPress::SelectAll))) => {
1336                // `None` = no selectable context: the key routes on.
1337                return match self.ctrl_a(win, fx) {
1338                    Some(changed) => changed,
1339                    None => {
1340                        fx.push(InputEffect::KeyPassed { win, key: input });
1341                        false
1342                    }
1343                };
1344            }
1345            _ => {
1346                fx.push(InputEffect::KeyPassed { win, key: input });
1347                return false;
1348            }
1349        };
1350        let text_before = self.coord.text_fields().text(&field).to_owned();
1351        let changed_text = |action: &TextAction| matches!(action, TextAction::TextChanged(_));
1352        let mut changed = false;
1353        let multiline = self.coord.text_fields().field_state(&field).is_some_and(|s| s.config.multiline);
1354        let edit = match edit {
1355            Edit::Newline if multiline => Edit::Key(KeyPress::Paste("\n".into())),
1356            Edit::Newline => Edit::Submit,
1357            e => e,
1358        };
1359        match edit {
1360            Edit::Newline => {}
1361            Edit::Key(kp) => changed = changed_text(&self.coord.on_key(kp)),
1362            Edit::Char(c) => changed = changed_text(&self.coord.on_char(c)),
1363            Edit::Text(s) => {
1364                for c in s.chars() {
1365                    changed |= changed_text(&self.coord.on_char(c));
1366                }
1367            }
1368            Edit::Submit => {
1369                if let TextAction::Commit(_) = self.coord.on_char('\r') {
1370                    fx.push(InputEffect::Text(TextIntent::Submitted {
1371                        win,
1372                        field: field.clone(),
1373                    }));
1374                }
1375            }
1376            Edit::Copy => {
1377                // A field with no selection of its own (it kept focus while the user
1378                // selected page text): the page selection is what the user means.
1379                let own = if self.masked(&field) { None } else { self.coord.text_fields().copy_selection().filter(|t| !t.is_empty()) };
1380                if let Some(text) = own.or_else(|| self.selected_text_concat()) {
1381                    fx.push(InputEffect::CopyText { win, text });
1382                }
1383            }
1384            Edit::Cut => {
1385                if !self.masked(&field) {
1386                    if let Some(text) = self.coord.text_fields_mut().cut_selection(&field) {
1387                        fx.push(InputEffect::CopyText { win, text });
1388                    }
1389                }
1390            }
1391            Edit::Paste => {
1392                let ticket = Ticket(INPUT_TICKET_BASE.saturating_add(*next_ticket));
1393                *next_ticket = next_ticket.saturating_add(1);
1394                self.pending_paste = Some((ticket, Some(field.clone())));
1395                fx.push(InputEffect::NeedPaste { win, ticket });
1396            }
1397        }
1398        if changed || self.coord.text_fields().text(&field) != text_before {
1399            fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1400        }
1401        // Text and caret changes are revisioned by `settle`.
1402        false
1403    }
1404
1405    fn masked(&self, field: &WidgetId) -> bool {
1406        self.coord
1407            .text_fields()
1408            .field_state(field)
1409            .is_some_and(|s| s.config.masked)
1410    }
1411
1412    fn ime(&mut self, win: WindowId, input: ImeInput, fx: &mut InputEffects) {
1413        let Some(field) = self.text_focus() else {
1414            return;
1415        };
1416        match input {
1417            ImeInput::Enabled => {}
1418            ImeInput::Preedit { text, cursor } => {
1419                let chars = |b: usize| text.get(..b).map(|s| s.chars().count());
1420                let at = cursor
1421                    .and_then(|(b, _)| chars(b))
1422                    .unwrap_or_else(|| text.chars().count());
1423                self.coord.text_fields_mut().preedit_set(&field, text, at);
1424            }
1425            ImeInput::Commit(text) => {
1426                let action = self.coord.text_fields_mut().ime_commit(&field, text);
1427                if let TextAction::TextChanged(_) = action {
1428                    fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1429                }
1430            }
1431            ImeInput::Disabled => {
1432                self.coord
1433                    .text_fields_mut()
1434                    .preedit_set(&field, String::new(), 0);
1435            }
1436        }
1437    }
1438
1439    fn clipboard(&mut self, win: WindowId, result: ClipboardResult, fx: &mut InputEffects) {
1440        let Some((ticket, field)) = self.pending_paste.clone() else {
1441            return;
1442        };
1443        if ticket != result.ticket {
1444            return;
1445        }
1446        self.pending_paste = None;
1447        let Some(text) = result.text.filter(|t| !t.is_empty()) else {
1448            return;
1449        };
1450        let Some(field) = field else {
1451            fx.push(InputEffect::Pasted { win, text });
1452            return;
1453        };
1454        let Some(focused) = self.text_focus() else {
1455            return;
1456        };
1457        if focused != field {
1458            return;
1459        }
1460        if let TextAction::TextChanged(_) = self.coord.on_key(KeyPress::Paste(text)) {
1461            fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1462        }
1463    }
1464
1465    /// The platform paste gesture's text: into the focused text field,
1466    /// else to the app. Settles an engine read still waiting for it (the
1467    /// web answers Ctrl/Cmd+V this way), so the text lands once.
1468    fn paste(&mut self, win: WindowId, text: String, fx: &mut InputEffects) {
1469        self.pending_paste = None;
1470        if text.is_empty() {
1471            return;
1472        }
1473        match self.text_focus() {
1474            Some(field) => {
1475                if let TextAction::TextChanged(_) = self.coord.on_key(KeyPress::Paste(text)) {
1476                    fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1477                }
1478            }
1479            None => fx.push(InputEffect::Pasted { win, text }),
1480        }
1481    }
1482
1483    // -- caret ----------------------------------------------------------------
1484
1485    fn caret_key(&self) -> Option<CaretKey> {
1486        let store = self.coord.text_fields();
1487        let field = store.focused()?;
1488        let s = store.field_state(field)?;
1489        Some(CaretKey {
1490            field: field.clone(),
1491            engaged: s.engaged,
1492            text: s.text.clone(),
1493            cursor: s.cursor,
1494            selection: s.selection_start,
1495            preedit: s.preedit.clone(),
1496            preedit_cursor: s.preedit_cursor,
1497        })
1498    }
1499
1500    fn field_rect(&self, field: &WidgetId) -> Option<Rect> {
1501        let (x, y, w, h) = self.coord.text_fields().field_state(field)?.last_rect?;
1502        Some(Rect::new(x, y, w, h))
1503    }
1504
1505    /// The caret's rect: the char boundary at the cursor, full field height.
1506    fn caret_rect(&self, field: &WidgetId) -> Option<Rect> {
1507        let s = self.coord.text_fields().field_state(field)?;
1508        let (x, y, _, h) = s.last_rect?;
1509        let cx = s.last_char_positions.get(s.cursor).copied().unwrap_or(x);
1510        Some(Rect::new(cx, y, 1.0, h))
1511    }
1512
1513    /// Re-derive caret blink, repaint, IME area and IME-allowed state after
1514    /// any op. Returns whether observable state changed.
1515    fn settle(&mut self, win: WindowId, now: Seconds, fx: &mut InputEffects) -> bool {
1516        let now_ms = millis(now);
1517        let key = self.caret_key();
1518        let key_changed = key != self.caret;
1519        if key_changed {
1520            if let Some(old) = &self.caret {
1521                if key.as_ref().map(|k| &k.field) != Some(&old.field) {
1522                    fx.push(InputEffect::InvalidateField {
1523                        win,
1524                        rect: self.field_rect(&old.field),
1525                    });
1526                }
1527            }
1528            self.caret = key;
1529            self.blink_anchor_ms = now_ms;
1530        }
1531        self.coord
1532            .text_fields_mut()
1533            .set_blink_time(self.blink_anchor_ms);
1534        let active = self.os_focused && self.caret.as_ref().is_some_and(|k| k.engaged);
1535        let visible = active && self.coord.text_fields().cursor_visible(now_ms);
1536        let visible_changed = visible != self.caret_visible;
1537        self.caret_visible = visible;
1538        if key_changed || visible_changed {
1539            if let Some(k) = &self.caret {
1540                fx.push(InputEffect::InvalidateField {
1541                    win,
1542                    rect: self.field_rect(&k.field),
1543                });
1544            }
1545        }
1546        let at = active.then(|| next_blink_edge(self.blink_anchor_ms, now_ms));
1547        if at != self.armed {
1548            self.armed = at;
1549            fx.push(InputEffect::CaretDeadline { win, at });
1550        }
1551        let field = self.caret.as_ref().map(|k| k.field.clone());
1552        let allowed = field.is_some();
1553        if allowed != self.ime_allowed {
1554            self.ime_allowed = allowed;
1555            fx.push(InputEffect::ImeAllowed { win, allowed });
1556        }
1557        let area = field.and_then(|f| self.caret_rect(&f));
1558        if area != self.ime_area {
1559            self.ime_area = area;
1560            if let Some(rect) = area {
1561                fx.push(InputEffect::ImeArea { win, rect });
1562            }
1563        }
1564        key_changed || visible_changed
1565    }
1566}
1567
1568/// Host clock in whole milliseconds (the store's blink unit); negative and
1569/// NaN instants count as 0.
1570fn millis(t: Seconds) -> u64 {
1571    // `as` saturates: NaN -> 0, beyond u64::MAX -> u64::MAX.
1572    (t.get() * 1000.0).round().max(0.0) as u64
1573}
1574
1575/// The first blink edge strictly after `now_ms` for a phase anchored at
1576/// `anchor_ms`.
1577fn next_blink_edge(anchor_ms: u64, now_ms: u64) -> Seconds {
1578    let phases = now_ms.saturating_sub(anchor_ms) / CARET_BLINK_MS + 1;
1579    let edge = anchor_ms.saturating_add(phases.saturating_mul(CARET_BLINK_MS));
1580    Seconds(edge as f64 / 1000.0)
1581}
1582
1583/// What a key does to a focused text field.
1584#[derive(Clone, Debug, PartialEq, Eq)]
1585enum Edit {
1586    Key(KeyPress),
1587    Char(char),
1588    Text(String),
1589    Submit,
1590    /// Shift+Enter: a newline in a multiline field, else a submit.
1591    Newline,
1592    Copy,
1593    Cut,
1594    Paste,
1595}
1596
1597/// The editing chord a key press is for a focused text field, or `None`
1598/// when the field does not take it (it routes on to overlays and keymap).
1599fn editing_chord(input: &KeyInput) -> Option<Edit> {
1600    let m = input.mods;
1601    let cmd = m.ctrl || m.meta;
1602    let edit = match input.code {
1603        KeyCode::A if cmd => Edit::Key(KeyPress::SelectAll),
1604        KeyCode::Z if cmd && m.shift => Edit::Key(KeyPress::Redo),
1605        KeyCode::Z if cmd => Edit::Key(KeyPress::Undo),
1606        KeyCode::Y if m.ctrl && !m.alt => Edit::Key(KeyPress::Redo),
1607        KeyCode::C if cmd => Edit::Copy,
1608        KeyCode::X if cmd => Edit::Cut,
1609        KeyCode::V if cmd => Edit::Paste,
1610        KeyCode::ArrowLeft if cmd => Edit::Key(KeyPress::WordLeft),
1611        KeyCode::ArrowRight if cmd => Edit::Key(KeyPress::WordRight),
1612        KeyCode::Backspace if cmd => Edit::Key(KeyPress::DeleteWordBack),
1613        KeyCode::Delete if cmd => Edit::Key(KeyPress::DeleteWordForward),
1614        KeyCode::ArrowLeft if m.shift => Edit::Key(KeyPress::ShiftLeft),
1615        KeyCode::ArrowRight if m.shift => Edit::Key(KeyPress::ShiftRight),
1616        KeyCode::Home if m.shift => Edit::Key(KeyPress::ShiftHome),
1617        KeyCode::End if m.shift => Edit::Key(KeyPress::ShiftEnd),
1618        KeyCode::ArrowLeft => Edit::Key(KeyPress::ArrowLeft),
1619        KeyCode::ArrowRight => Edit::Key(KeyPress::ArrowRight),
1620        KeyCode::Home => Edit::Key(KeyPress::Home),
1621        KeyCode::End => Edit::Key(KeyPress::End),
1622        KeyCode::Backspace => Edit::Char('\x08'),
1623        KeyCode::Delete => Edit::Key(KeyPress::Delete),
1624        KeyCode::Enter if m.shift => Edit::Newline,
1625        KeyCode::Enter => Edit::Submit,
1626        // Other Ctrl / Cmd chords belong to the keymap; Ctrl+Alt is AltGr
1627        // on some layouts and does produce text.
1628        _ if cmd && !(m.ctrl && m.alt) => return None,
1629        _ => {
1630            let text: String = input
1631                .text
1632                .as_deref()?
1633                .chars()
1634                .filter(|c| !c.is_control())
1635                .collect();
1636            if text.is_empty() {
1637                return None;
1638            }
1639            match text.chars().count() {
1640                1 => Edit::Char(text.chars().next()?),
1641                _ => Edit::Text(text),
1642            }
1643        }
1644    };
1645    Some(edit)
1646}
1647
1648// ---------------------------------------------------------------------------
1649// InputEngine
1650// ---------------------------------------------------------------------------
1651
1652/// The InputEngine: see the module docs.
1653#[derive(Default)]
1654pub struct InputEngine {
1655    windows: VecMap<WindowId, PerWindowInput>,
1656    next_scope: u64,
1657    next_ticket: u64,
1658    rev: Revision,
1659}
1660
1661impl fmt::Debug for InputEngine {
1662    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1663        f.debug_struct("InputEngine")
1664            .field("windows", &self.windows.keys().collect::<Vec<_>>())
1665            .field("rev", &self.rev)
1666            .finish()
1667    }
1668}
1669
1670impl InputEngine {
1671    /// An engine with no windows.
1672    pub fn new() -> Self {
1673        Self::default()
1674    }
1675
1676    /// The only mutation door. Bumps the revision iff observable state
1677    /// changed (see the module docs).
1678    pub fn apply(&mut self, op: InputOp) -> InputEffects {
1679        let mut fx = InputEffects::new();
1680        let Self {
1681            windows,
1682            next_scope,
1683            next_ticket,
1684            rev,
1685        } = self;
1686        let changed = match op {
1687            InputOp::Open(win) => match windows.entry(win) {
1688                crate::types::vecmap::Entry::Occupied(_) => false,
1689                crate::types::vecmap::Entry::Vacant(slot) => {
1690                    slot.insert(PerWindowInput::new());
1691                    true
1692                }
1693            },
1694            InputOp::Close(win) => windows.remove(&win).is_some(),
1695            InputOp::WindowFocus { win, focused, now } => match windows.get_mut(&win) {
1696                Some(w) => {
1697                    w.os_focused = focused;
1698                    w.settle(win, now, &mut fx)
1699                }
1700                None => false,
1701            },
1702            InputOp::Pointer { win, now, input } => match windows.get_mut(&win) {
1703                Some(w) => {
1704                    let (changed, cooked) = w.cook(win, now, input);
1705                    fx.push(InputEffect::Pointer(cooked));
1706                    changed
1707                }
1708                None => false,
1709            },
1710            InputOp::Deliver { win, input } => match windows.get_mut(&win) {
1711                Some(w) => {
1712                    let (changed, target) = w.deliver(win, input, &mut fx);
1713                    fx.push(InputEffect::Content { win, target, changed });
1714                    changed
1715                }
1716                None => false,
1717            },
1718            InputOp::Wheel { win, input } => {
1719                if let Some(w) = windows.get_mut(&win) {
1720                    let target = w.wheel(input);
1721                    let changed = target.is_some();
1722                    fx.push(InputEffect::Content { win, target, changed });
1723                }
1724                false
1725            }
1726            InputOp::Key { win, now, input } => match windows.get_mut(&win) {
1727                Some(w) => {
1728                    let changed = w.key(win, input, next_ticket, &mut fx);
1729                    w.settle(win, now, &mut fx) | changed
1730                }
1731                None => false,
1732            },
1733            InputOp::Ime { win, now, input } => match windows.get_mut(&win) {
1734                Some(w) => {
1735                    w.ime(win, input, &mut fx);
1736                    w.settle(win, now, &mut fx)
1737                }
1738                None => false,
1739            },
1740            InputOp::Paste { win, now, text } => match windows.get_mut(&win) {
1741                Some(w) => {
1742                    w.paste(win, text, &mut fx);
1743                    w.settle(win, now, &mut fx)
1744                }
1745                None => false,
1746            },
1747            InputOp::Offer { win, text } => {
1748                if let Some(w) = windows.get_mut(&win) {
1749                    w.offer = text;
1750                }
1751                false
1752            }
1753            InputOp::Clipboard { win, now, result } => match windows.get_mut(&win) {
1754                Some(w) => {
1755                    w.clipboard(win, result, &mut fx);
1756                    w.settle(win, now, &mut fx)
1757                }
1758                None => false,
1759            },
1760            InputOp::Focus { win, now, op } => match windows.get_mut(&win) {
1761                Some(w) => {
1762                    let changed = w.focus_op(win, op, next_scope, &mut fx);
1763                    w.settle(win, now, &mut fx) | changed
1764                }
1765                None => false,
1766            },
1767            InputOp::SetCapture { win, capture } => windows
1768                .get_mut(&win)
1769                .is_some_and(|w| w.set_capture(capture)),
1770            InputOp::BeginFrame { win, now } => {
1771                windows.get_mut(&win).is_some_and(|w| w.begin_frame(now))
1772            }
1773            InputOp::EndFrame { win, now } => match windows.get_mut(&win) {
1774                Some(w) => {
1775                    let changed = w.end_frame(win, &mut fx);
1776                    w.settle(win, now, &mut fx) | changed
1777                }
1778                None => false,
1779            },
1780        };
1781        if changed {
1782            rev.bump();
1783        }
1784        fx
1785    }
1786
1787    /// Caret blink edges: every window whose armed edge is due at `now`
1788    /// flips its caret, asks for a repaint of that field and re-arms the
1789    /// next edge. The kernel calls it when `TimerOwner::CaretBlink` fires
1790    /// (calling it at any other time is harmless).
1791    pub fn tick(&mut self, now: Seconds) -> InputEffects {
1792        let mut fx = InputEffects::new();
1793        let mut changed = false;
1794        for (win, w) in &mut self.windows {
1795            if w.armed.is_some_and(|at| at.get() <= now.get()) {
1796                changed |= w.settle(*win, now, &mut fx);
1797            }
1798        }
1799        if changed {
1800            self.rev.bump();
1801        }
1802        fx
1803    }
1804
1805    /// The compose-phase door for widget registration (`register*`,
1806    /// `register_text_field`, `update_field`, `mark_seen`, `unregister`,
1807    /// layers). Not revisioned: what registration changes is evaluated by
1808    /// the following [`InputOp::EndFrame`]. Lib brief L6 narrows what this
1809    /// reference can reach (see the module docs).
1810    // Read doors for the native/web host briefs (F8+) - unused in-crate until then.
1811    #[allow(dead_code)]
1812    pub fn registrar(&mut self, win: WindowId) -> Option<&mut InputCoordinator> {
1813        self.windows.get_mut(&win).map(|w| &mut w.coord)
1814    }
1815
1816    /// The compose-phase door for the per-widget typed state store (the
1817    /// `Widgets` face of the app hook contexts). Not revisioned: the store
1818    /// holds no on-screen truth of its own.
1819    // Read doors for the native/web host briefs (F8+) - unused in-crate until then.
1820    #[allow(dead_code)]
1821    pub fn states_mut(&mut self, win: WindowId) -> Option<&mut uzor::app_context::StateRegistry> {
1822        self.windows.get_mut(&win).map(|w| &mut w.states)
1823    }
1824
1825    /// The compose-phase `Widgets` pair, borrow-split: a hook holds both
1826    /// halves at once, so the two single doors cannot produce them
1827    /// together. Same revision rules as the single doors.
1828    pub fn compose_parts(
1829        &mut self,
1830        win: WindowId,
1831    ) -> Option<(&mut InputCoordinator, &mut uzor::app_context::StateRegistry, &mut Selectables)> {
1832        self.windows
1833            .get_mut(&win)
1834            .map(|w| (&mut w.coord, &mut w.states, &mut w.reported))
1835    }
1836
1837    /// Compose-phase door (T2): report one selectable plain-text widget's
1838    /// content and line geometry for this frame — the input the selection
1839    /// owner resolves presses / drags against, mirroring
1840    /// `TextFieldStore::update_field`. A widget not reported in a frame
1841    /// stops being selectable and loses its selection. Not revisioned: the
1842    /// change is evaluated by the following [`InputOp::EndFrame`].
1843    // Read doors for the native/web host briefs (F8+) - unused in-crate until then.
1844    #[allow(dead_code)]
1845    pub fn update_selectable(
1846        &mut self,
1847        win: WindowId,
1848        widget: WidgetId,
1849        text: impl Into<String>,
1850        lines: Vec<SelectionLine>,
1851    ) {
1852        if let Some(w) = self.windows.get_mut(&win) {
1853            w.reported.report(widget, text, lines);
1854        }
1855    }
1856
1857    /// Route presses on the hit region `member` to the selectable `owner` for
1858    /// this frame (see `Selectables::alias`).
1859    #[allow(dead_code)]
1860    pub fn alias_selectable(&mut self, win: WindowId, member: WidgetId, owner: WidgetId) {
1861        if let Some(w) = self.windows.get_mut(&win) {
1862            w.reported.alias(member, owner);
1863        }
1864    }
1865
1866    /// Bumped on every observable state change.
1867    pub fn revision(&self) -> Revision {
1868        self.rev
1869    }
1870
1871    /// Read-only projection.
1872    pub fn view(&self) -> InputEngineView<'_> {
1873        InputEngineView { e: self }
1874    }
1875}
1876
1877/// Read-only projection of the [`InputEngine`].
1878#[derive(Clone, Copy, Debug)]
1879pub struct InputEngineView<'a> {
1880    e: &'a InputEngine,
1881}
1882
1883// Read doors for the native/web host briefs (F8+) - unused in-crate until then.
1884#[allow(dead_code)]
1885impl<'a> InputEngineView<'a> {
1886    fn w(&self, win: WindowId) -> Option<&'a PerWindowInput> {
1887        self.e.windows.get(&win)
1888    }
1889
1890    /// Tracked windows, ascending.
1891    pub fn ids(&self) -> impl Iterator<Item = WindowId> + 'a {
1892        self.e.windows.keys().copied()
1893    }
1894
1895    /// The published input state of one window.
1896    pub fn window(&self, win: WindowId) -> Option<InputView> {
1897        self.w(win).map(|w| InputView {
1898            hovered: w.hover.clone(),
1899            pressed: w.pressed.clone(),
1900            focused: w.focused_id().cloned(),
1901            focus_visible: w.focus_visible,
1902            captured: w.capture.is_some(),
1903            scope_depth: w.scopes.len(),
1904        })
1905    }
1906
1907    /// The widget with keyboard focus.
1908    pub fn focused(&self, win: WindowId) -> Option<&'a WidgetId> {
1909        self.w(win)?.focused_id()
1910    }
1911
1912    /// The owner of the active (innermost) focus scope.
1913    pub fn active_scope(&self, win: WindowId) -> Option<&'a ScopeOwner> {
1914        self.w(win)?.scopes.last().map(|s| &s.owner)
1915    }
1916
1917    /// The pointer capture.
1918    pub fn capture(&self, win: WindowId) -> Option<&'a Capture> {
1919        self.w(win)?.capture.as_ref()
1920    }
1921
1922    /// The event-level cook state (click count, drag arm).
1923    pub fn cook(&self, win: WindowId) -> Option<&'a CookState> {
1924        self.w(win).map(|w| &w.cook)
1925    }
1926
1927    /// Widgets clicked in the last evaluated frame, with their click count
1928    /// (1 single, 2 double, 3 triple).
1929    pub fn clicked(&self, win: WindowId) -> &'a [(WidgetId, u8)] {
1930        self.w(win).map_or(&[], |w| w.clicked.as_slice())
1931    }
1932
1933    /// The caret of the focused field is in its visible phase (and blinking
1934    /// is active).
1935    pub fn caret_visible(&self, win: WindowId) -> bool {
1936        self.w(win).is_some_and(|w| w.caret_visible)
1937    }
1938
1939    /// The armed caret blink edge.
1940    pub fn caret_deadline(&self, win: WindowId) -> Option<Seconds> {
1941        self.w(win)?.armed
1942    }
1943
1944    /// The window's text fields (text, cursor, selection, preedit).
1945    pub fn text_fields(&self, win: WindowId) -> Option<&'a TextFieldStore> {
1946        self.w(win).map(|w| w.coord.text_fields())
1947    }
1948
1949    /// The window's plain-text selections (widget → selection), the T2
1950    /// per-window owner state. The app reads this at compose time to draw
1951    /// highlights through the lib's `draw_text_with_selection`.
1952    pub fn selections(&self, win: WindowId) -> Option<&'a [(WidgetId, TextSelection)]> {
1953        self.w(win).map(|w| w.selections.as_slice())
1954    }
1955
1956    /// The window's coordinator, read-only (hit tests, widget state).
1957    pub fn coordinator(&self, win: WindowId) -> Option<&'a InputCoordinator> {
1958        self.w(win).map(|w| &w.coord)
1959    }
1960
1961    /// Scroll accumulated since the last `BeginFrame`, in lines. The
1962    /// compose phase reads it into the hook view before `BeginFrame`
1963    /// moves it into the coordinator's frame input.
1964    pub fn pending_scroll(&self, win: WindowId) -> (f64, f64) {
1965        self.w(win).map_or((0.0, 0.0), |w| w.pointer.scroll)
1966    }
1967
1968    /// Whether [`Self::pending_scroll`] came from pixel deltas (trackpad,
1969    /// smooth wheel): scroll containers then follow 1:1 and fling on release.
1970    pub fn pending_scroll_precise(&self, win: WindowId) -> bool {
1971        self.w(win).is_some_and(|w| w.pointer.scroll_precise)
1972    }
1973
1974    /// Last pointer position in window coordinates and whether a button is
1975    /// held (embedded surfaces that forward raw pointer events need both).
1976    /// Secondary-button release position since the last `BeginFrame`.
1977    pub fn context_click(&self, win: WindowId) -> Option<(f64, f64)> {
1978        self.w(win).and_then(|w| w.pointer.context)
1979    }
1980
1981    pub fn pointer(&self, win: WindowId) -> (Option<(f64, f64)>, bool) {
1982        self.w(win).map_or((None, false), |w| (w.pointer.pos, w.pointer.button_down.is_some()))
1983    }
1984
1985    /// Where the held press went down (window coords), while a button is held. A drag
1986    /// measures from here, not from the first pointer position a frame saw: the pointer
1987    /// may have moved several pixels between the press and that frame.
1988    pub fn press_origin(&self, win: WindowId) -> Option<(f64, f64)> {
1989        let w = self.w(win)?;
1990        w.pointer.button_down?;
1991        w.cook.press_origin.map(|o| (o.x, o.y))
1992    }
1993}
1994
1995#[cfg(test)]
1996mod tests;