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