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