Skip to main content

repose_app/
runtime.rs

1use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet};
3use std::rc::Rc;
4
5use repose_core::dnd;
6use repose_core::input::{
7    GamepadAxis, GamepadButton, GamepadEvent, GamepadId, ImeEvent, Key, KeyEvent, KeyEventType,
8    Modifiers, PointerButton, PointerEvent, PointerEventKind, PointerId, PointerKind, SensorKind,
9    SensorSample,
10};
11use repose_core::locals::{Density, set_density_default, with_density};
12use repose_core::runtime::{Frame, Scheduler};
13use repose_core::scroll::set_touch_gesture_active;
14use repose_core::shortcuts::DragAction;
15use repose_core::{
16    CursorIcon, HitRegion, Interaction, Modifier, RenderContext, Scene, Vec2, View, request_frame,
17};
18use repose_ui::textfield::TextFieldState;
19use repose_ui::{Interactions, layout_and_paint};
20
21fn ensure_tf_state(
22    map: &mut HashMap<u64, Rc<RefCell<TextFieldState>>>,
23    key: u64,
24    seed: &str,
25) -> Rc<RefCell<TextFieldState>> {
26    map.entry(key)
27        .or_insert_with(|| {
28            Rc::new(RefCell::new(if seed.is_empty() {
29                TextFieldState::new()
30            } else {
31                TextFieldState::with_text(seed.to_string())
32            }))
33        })
34        .clone()
35}
36
37fn ensure_all_tf_states_from_frame(
38    map: &mut HashMap<u64, Rc<RefCell<TextFieldState>>>,
39    frame: &Frame,
40) {
41    for hit in &frame.hit_regions {
42        if let Some(key) = hit.tf_state_key {
43            let st = ensure_tf_state(map, key, hit.tf_value.as_str());
44            // Only sync text; do not move caret.
45            st.borrow_mut()
46                .apply_controlled_value(hit.tf_value.as_str());
47        }
48    }
49}
50
51fn is_tf_hit(f: &Frame, id: u64) -> bool {
52    f.hit_regions
53        .iter()
54        .any(|h| h.id == id && h.tf_state_key.is_some())
55        || is_textfield_in_frame(f, id)
56}
57
58/// Platform-directed side effects requested by the UI.
59#[derive(Clone, Default)]
60pub struct PlatformOutput {
61    /// Cursor to display (None = default/system cursor).
62    pub cursor: Option<CursorIcon>,
63    /// Pointer confinement the app declared this frame. The host
64    /// applies it to the window and releases on `None`; the field is
65    /// always a declaration for the frame, not an edge, so a host can
66    /// dedupe it however it likes.
67    pub cursor_grab: repose_core::CursorGrabMode,
68    /// Whether IME input is allowed for the currently focused widget.
69    pub ime_allowed: bool,
70    /// IME cursor area in logical (DPI-scaled) coordinates: (x, y, width, height).
71    pub ime_cursor_area: Option<(f64, f64, f64, f64)>,
72    /// Text to write to the clipboard (transient - set once per frame, cleared after read).
73    pub clipboard_text: Option<String>,
74
75    /// IME / soft-keyboard hints for the focused text field. The host should
76    /// apply these to the OS keyboard and to `set_ime_purpose` / web attrs.
77    pub ime_purpose: repose_core::ImePurposeHint,
78    pub ime_auto_correct: bool,
79    pub ime_capitalization: repose_core::KeyboardCapitalization,
80    pub keyboard_type: repose_core::KeyboardType,
81
82    /// Whether the app theme is dark, so the host can sync OS window chrome
83    /// (titlebar, caption buttons). `None` = don't touch the OS chrome.
84    pub window_theme_dark: Option<bool>,
85}
86
87/// Output of a single frame: the rendered scene plus metadata for the host.
88pub struct FrameOutput {
89    /// The scene graph for rendering.
90    pub scene: Scene,
91    /// Hit regions for pointer dispatch between frames.
92    pub hit_regions: Vec<HitRegion>,
93    /// Semantics nodes for a11y.
94    pub semantics_nodes: Vec<repose_core::runtime::SemNode>,
95    /// Focus chain for tab navigation.
96    pub focus_chain: Vec<u64>,
97    /// Platform-side effects (cursor, IME, clipboard).
98    pub platform: PlatformOutput,
99    /// Whether the UI wants pointer events (if false, host can pass events through).
100    pub wants_pointer: bool,
101    /// Whether the UI wants keyboard events (if false, host can pass events through).
102    pub wants_keyboard: bool,
103}
104
105impl FrameOutput {
106    /// Consume the frame into a `repose_core::Frame` for hit-testing/caching
107    /// by the host. Drops the platform-output and pointer metadata.
108    pub fn into_frame(self) -> Frame {
109        Frame {
110            scene: self.scene,
111            hit_regions: self.hit_regions,
112            semantics_nodes: self.semantics_nodes,
113            focus_chain: self.focus_chain,
114        }
115    }
116
117    pub fn into_shared_frame(self) -> Rc<Frame> {
118        Rc::new(self.into_frame())
119    }
120}
121
122/// Result of a pointer-move event processed by the runtime.
123pub struct PointerMoveResult {
124    /// Updated cursor suggestion for the host.
125    pub cursor: Option<CursorIcon>,
126    /// The id of the element under the pointer, if any.
127    pub hover_id: Option<u64>,
128}
129
130/// Result of a pointer-button event processed by the runtime.
131#[derive(Debug)]
132pub struct PointerButtonResult {
133    /// Id of the element that received focus (if any).
134    pub focused: Option<u64>,
135    /// Id of the captured element.
136    pub capture_id: Option<u64>,
137    /// Whether the event was consumed by the UI.
138    pub consumed: bool,
139    /// Whether an accessibility announcement was triggered.
140    pub needs_a11y_announce: bool,
141    /// Set on release when a click fired, so hosts can announce activation
142    /// without re-reading runtime state that has already been cleared.
143    pub clicked_id: Option<u64>,
144}
145
146// ViewConfiguration defaults
147const LONG_PRESS_MS: u128 = 500;
148const DOUBLE_CLICK_MS: u128 = 300;
149const DOUBLE_TAP_MIN_MS: u128 = 40;
150const LONG_PRESS_SLOP_DP: f32 = 18.0;
151/// Pointer travel that cancels a pending tap, in dp. Compose's
152/// `detectTapGestures` treats a press that moves past the platform touch slop
153/// as a drag, so the tap never fires. This is the same value Compose's
154/// `ViewConfiguration.touchSlop` resolves to on Android.
155pub(crate) const TAP_SLOP_DP: f32 = 18.0;
156pub(crate) const MOUSE_TAP_SLOP_DP: f32 = 2.25;
157
158/// Did the pointer travel from `(x0, y0)` past `slop` dp? Compared squared to
159/// keep the per-move path allocation-free.
160fn moved_past_slop(x0: f32, y0: f32, pos: Vec2, slop_dp: f32, scale: f32) -> bool {
161    let slop = slop_dp * scale;
162    let dx = pos.x - x0;
163    let dy = pos.y - y0;
164    dx * dx + dy * dy > slop * slop
165}
166
167struct TouchPressState {
168    capture_id: u64,
169    pressed_ids: HashSet<u64>,
170}
171
172struct DndPointerCapture {
173    touch: Option<u64>,
174    source_id: u64,
175}
176
177/// Embeddable Repose runtime.
178///
179/// Manages composition scheduling, input routing, text-field state, and
180/// pointer/key dispatch.  The host owns the event loop and GPU device. This
181/// is purely the UI logic layer.
182pub struct ReposeRuntime {
183    pub sched: Scheduler,
184    pub scale: f32,
185    /// Ambient host layer for floating surfaces. Installed around
186    /// composition each frame; entries render at the root.
187    pub overlay: repose_ui::overlay::OverlayHandle,
188    pub dnd_context: repose_core::dnd::DndContext,
189    lifecycle_events: std::sync::Arc<crate::lifecycle::LifecycleDispatcher>,
190    deeplink_events: std::sync::Arc<crate::lifecycle::DeeplinkDispatcher>,
191
192    pub modifiers: Modifiers,
193    pub mouse_pos_px: (f32, f32),
194    /// Whether the pointer is currently inside the window.
195    pub pointer_inside: bool,
196    pub hover_id: Option<u64>,
197    pub hover_ancestors: std::collections::HashSet<u64>,
198    /// Needed so `Leave` still fires
199    /// even when the hovered hit region is removed from the tree between frames.
200    /// Rebuilt on every `cache_frame`.
201    hover_leave: HashMap<u64, repose_ui::HitRegionSnapshot>,
202    pub capture_id: Option<u64>,
203    /// Hit path captured at pointer-down: every region under the pointer,
204    /// ordered bottom-up (deepest child first, ancestors last).
205    pub hit_path: Option<Vec<u64>>,
206    /// Per-finger press table: every concurrent touch owns its own
207    /// hit path (unlike the single mouse `hit_path`/`capture_id`,
208    /// which is the single-primary tap emulation's). Game viewports
209    /// stage per-finger contacts off the dispatched events, so the
210    /// second finger's joystick/button press stages alongside the
211    /// first instead of stealing its path. UI press arbitration
212    /// (tap/click/scroll) stays single-primary in `touch_gesture`;
213    /// this only routes the per-finger event stream.
214    pub touch_paths: HashMap<u64, Vec<u64>>,
215    mouse_targets: Option<Vec<repose_ui::HitRegionSnapshot>>,
216    touch_targets: HashMap<u64, Vec<repose_ui::HitRegionSnapshot>>,
217    touch_positions: HashMap<u64, Vec2>,
218    touch_presses: HashMap<u64, TouchPressState>,
219    touch_move_consumers: HashSet<u64>,
220    dnd_capture: Option<DndPointerCapture>,
221    touch_primary: Option<u64>,
222    suppressed_touch_clicks: HashSet<u64>,
223    /// Which scroll consumer currently owns the wheel gesture.
224    pub scroll_capture_id: Option<u64>,
225    last_scroll_at: Option<web_time::Instant>,
226    pub pressed_ids: HashSet<u64>,
227    pub ime_preedit: bool,
228    pub key_pressed_active: Option<u64>,
229    key_pressed: HashMap<Key, u64>,
230    down_keys: HashSet<Key>,
231    pub last_focus: Option<u64>,
232    /// Bounds of the focused hit in the last frame, used to fire
233    /// `on_focused_bounds_changed` only on real changes.
234    last_focused_bounds: Option<repose_core::Rect>,
235    /// Polled physical-key state, keyed by debug name (`KeyCode::KeyW`,
236    /// `Digit1`, ...). Platform runners report every `KeyboardInput`
237    /// press/release here so games can poll held keys GML-style
238    /// (`keyboard_check`) instead of reconstructing them from
239    /// focus-routed key events, which miss keys when focus moves or
240    /// a key-up is swallowed (alt-tab, overlay, layout).
241    /// Cleared on window focus loss.
242    pub held_keys: HashSet<String>,
243    /// Polled mouse-button state. `handle_pointer_press/release`
244    /// maintain this for Primary/Secondary/Tertiary so games can read
245    /// held buttons (`mouse_check_button`) without tracking
246    /// press/release edges themselves.
247    pub held_mouse: HashSet<PointerButton>,
248
249    last_up: Option<(u64, web_time::Instant, f32, f32)>,
250    /// Position/time of the most recent pointer-down, used to time the second
251    /// tap of a double click (Compose: window + min time measured to the
252    /// second DOWN, not its up).
253    last_down: Option<(u64, web_time::Instant)>,
254    /// Origin of the press that produced the current capture, so release can
255    /// tell a tap from a drag (Compose `detectTapGestures` cancels the tap once
256    /// the pointer moves past touch slop).
257    press_origin: Option<(u64, f32, f32)>,
258    /// Set when the second tap of a double-click qualifies (within
259    /// [DOUBLE_TAP_MIN_MS, DOUBLE_CLICK_MS] of the first tap's up, and within
260    /// tap slop of it). Its up confirms the double click. A canceled second tap
261    /// falls back to the first tap's onClick.
262    double_candidate: Option<u64>,
263    long_press: Option<(u64, web_time::Instant, f32, f32)>,
264    long_press_touch: Option<u64>,
265    /// Keyboard long-press (Compose combinedClickable: holding Space/Enter
266    /// past LONG_PRESS_MS fires on_long_click). `bool` = already fired.
267    key_long_press: HashMap<Key, (u64, web_time::Instant, bool)>,
268    suppress_next_click: bool,
269    pending_click: Option<(u64, web_time::Instant, Rc<dyn Fn()>)>,
270    /// Focus candidate from a press on a non-text focusable. Compose moves
271    /// focus to a clickable on click (pointer-up), not on pointer-down: doing
272    /// it on down steals focus from a focused TextField the moment the gesture
273    /// might become a scroll, hiding the soft keyboard. Applied on release
274    /// only when the press was a tap, dropped when it became a drag.
275    pending_focus_on_click: Option<u64>,
276
277    pub frame_cache: Option<Rc<Frame>>,
278
279    cursor: Option<CursorIcon>,
280    frame_cursor_override: Option<CursorIcon>,
281
282    pub shortcuts: repose_core::shortcuts::ShortcutState,
283
284    pub textfield_states: HashMap<u64, Rc<RefCell<TextFieldState>>>,
285    /// Connected gamepads by backend id: display name plus live button/axis
286    /// state. Fed by [`ReposeRuntime::handle_gamepad`].
287    pub gamepads: HashMap<u32, GamepadPad>,
288    /// Queued dual-motor rumble requests.
289    pub pending_rumble: Vec<(u32, f32, f32, u32)>,
290    /// Latest motion-sensor reading per pad and sensor, fed by
291    /// [`ReposeRuntime::handle_sensor_sample`].
292    pub sensors: HashMap<(u32, SensorKind), [f32; 3]>,
293}
294
295/// Live state of one connected gamepad, mirrored from [`GamepadEvent`]s.
296pub use repose_core::input::GamepadPad;
297
298impl ReposeRuntime {
299    pub fn new() -> Self {
300        Self::with_overlay(repose_ui::overlay::OverlayHandle::new())
301    }
302
303    /// Create a runtime sharing `overlay` as the ambient host layer.
304    /// Entries posted through this handle render at the root; per-frame
305    /// `show_guard` state can still target other handles as an escape hatch.
306    pub fn with_overlay(overlay: repose_ui::overlay::OverlayHandle) -> Self {
307        Self {
308            overlay,
309            dnd_context: repose_core::dnd::DndContext::default(),
310            lifecycle_events: std::sync::Arc::new(crate::lifecycle::LifecycleDispatcher::default()),
311            deeplink_events: std::sync::Arc::new(crate::lifecycle::DeeplinkDispatcher::default()),
312            sched: Scheduler::new(),
313            scale: 1.0,
314            modifiers: Modifiers::default(),
315            mouse_pos_px: (0.0, 0.0),
316            pointer_inside: false,
317            hover_id: None,
318            hover_ancestors: std::collections::HashSet::new(),
319            hover_leave: HashMap::new(),
320            capture_id: None,
321            hit_path: None,
322            touch_paths: HashMap::new(),
323            mouse_targets: None,
324            touch_targets: HashMap::new(),
325            touch_positions: HashMap::new(),
326            touch_presses: HashMap::new(),
327            touch_move_consumers: HashSet::new(),
328            dnd_capture: None,
329            touch_primary: None,
330            suppressed_touch_clicks: HashSet::new(),
331            scroll_capture_id: None,
332            last_scroll_at: None,
333            pressed_ids: HashSet::new(),
334            ime_preedit: false,
335            key_pressed_active: None,
336            key_pressed: HashMap::new(),
337            down_keys: HashSet::new(),
338            last_focus: None,
339            last_focused_bounds: None,
340            held_keys: HashSet::new(),
341            held_mouse: HashSet::new(),
342            last_up: None,
343            last_down: None,
344            press_origin: None,
345            double_candidate: None,
346            long_press: None,
347            long_press_touch: None,
348            key_long_press: HashMap::new(),
349            suppress_next_click: false,
350            pending_click: None,
351            pending_focus_on_click: None,
352            frame_cache: None,
353            cursor: None,
354            frame_cursor_override: None,
355            shortcuts: repose_core::shortcuts::ShortcutState::new().without_global_fallback(),
356            textfield_states: HashMap::new(),
357            gamepads: HashMap::new(),
358            pending_rumble: Vec::new(),
359            sensors: HashMap::new(),
360        }
361    }
362
363    pub fn event_dispatchers(&self) -> crate::lifecycle::RuntimeDispatchers {
364        crate::lifecycle::RuntimeDispatchers {
365            lifecycle: self.lifecycle_events.clone(),
366            deeplink: self.deeplink_events.clone(),
367        }
368    }
369
370    pub fn set_lifecycle_callback(
371        &mut self,
372        callback: Box<dyn Fn(crate::lifecycle::AppLifecycle) + Send>,
373    ) {
374        self.lifecycle_events.set_callback(callback);
375    }
376
377    pub fn add_lifecycle_listener(
378        &mut self,
379        callback: Box<dyn Fn(crate::lifecycle::AppLifecycle) + Send>,
380    ) -> u64 {
381        self.lifecycle_events.add_listener(callback)
382    }
383
384    pub fn remove_lifecycle_listener(&mut self, id: u64) -> bool {
385        self.lifecycle_events.remove_listener(id)
386    }
387
388    pub fn current_lifecycle(&self) -> Option<crate::lifecycle::AppLifecycle> {
389        self.lifecycle_events.current()
390    }
391
392    pub fn push_lifecycle(&mut self, state: crate::lifecycle::AppLifecycle) {
393        self.lifecycle_events.push(state);
394    }
395
396    pub fn process_lifecycle(&mut self) {
397        self.lifecycle_events.process();
398    }
399
400    pub fn set_deeplink_callback(&mut self, callback: Box<dyn Fn(Vec<u8>) + Send>) {
401        self.deeplink_events.set_callback(callback);
402    }
403
404    pub fn add_deeplink_listener(&mut self, callback: Box<dyn Fn(Vec<u8>) + Send>) -> u64 {
405        self.deeplink_events.add_listener(callback)
406    }
407
408    pub fn remove_deeplink_listener(&mut self, id: u64) -> bool {
409        self.deeplink_events.remove_listener(id)
410    }
411
412    pub fn push_deeplink(&mut self, data: Vec<u8>) {
413        self.deeplink_events.push(data);
414    }
415
416    pub fn process_deeplinks(&mut self) {
417        self.deeplink_events.process();
418    }
419
420    /// Set the logical viewport size (in device pixels).
421    pub fn set_viewport(&mut self, width_px: u32, height_px: u32) {
422        self.sched.size = (width_px, height_px);
423    }
424
425    /// Set viewport size and DPI scale factor.
426    pub fn set_viewport_and_scale(&mut self, width_px: u32, height_px: u32, scale: f32) {
427        self.scale = scale;
428        self.sched.size = (width_px, height_px);
429        self.sched.scale = scale;
430    }
431
432    /// Advance animations. Call before `compose` each frame.
433    pub fn tick_animations(&self) {
434        repose_core::animation_driver::tick();
435    }
436
437    pub fn poll_gesture_timers(&mut self) {
438        self.poll_long_press();
439        self.flush_pending_click();
440        self.poll_key_long_press();
441        repose_ui::scrollbar_repeat::poll_track_repeat();
442    }
443
444    /// Resolve queued bring-into-view requests against the last painted frame
445    /// and mutate scroll state before the next frame is composed.
446    fn process_bring_into_view_requests(&mut self) {
447        let queued = repose_core::runtime::drain_bring_into_view_requests();
448        if queued.is_empty() {
449            return;
450        }
451        let Some(frame) = self.frame_cache.clone() else {
452            return;
453        };
454        for id in queued {
455            bring_target_into_view(&frame.hit_regions, id);
456        }
457    }
458
459    /// Compose and layout a frame, returning the output for rendering.
460    ///
461    /// Call `tick_animations` before this and `cache_frame` after (once you
462    /// have applied any host-specific overlays like the devtools inspector).
463    pub fn compose<F>(&mut self, root_fn: &mut F, render_ctx: &RenderContext) -> Frame
464    where
465        F: FnMut(&mut Scheduler, &RenderContext) -> View,
466    {
467        let _dnd_guard = self.dnd_context.enter();
468        let _event_scope = crate::lifecycle::enter_dispatchers(self.event_dispatchers());
469        self.process_bring_into_view_requests();
470        self.poll_long_press();
471        self.flush_pending_click();
472        self.poll_key_long_press();
473        repose_ui::scrollbar_repeat::poll_track_repeat();
474
475        let pads: Vec<GamepadPad> = self.gamepads.values().cloned().collect();
476        self.sched.gamepads = pads;
477
478        let size = self.sched.size;
479        let rc = render_ctx.clone();
480        let overlay = self.overlay.clone();
481        let mut compose_once = |this: &mut Self| {
482            let overlay = overlay.clone();
483            let ambient = this.overlay.clone();
484            let mut inner = |s: &mut Scheduler| {
485                repose_ui::overlay::with_ambient_overlay(ambient.clone(), || {
486                    let content = (root_fn)(s, &rc);
487                    overlay.host(Modifier::new().fill_max_size(), content)
488                })
489            };
490            match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
491                compose_frame_inner_with_ancestors(
492                    &mut this.sched,
493                    &mut inner,
494                    this.scale,
495                    size,
496                    this.hover_id,
497                    &this.hover_ancestors,
498                    &this.pressed_ids,
499                    &this.textfield_states,
500                )
501            })) {
502                Ok(frame) => frame,
503                Err(_) => {
504                    log::error!("compose panicked; presenting last good frame");
505                    this.frame_cache
506                        .as_deref()
507                        .cloned()
508                        .unwrap_or_else(|| Frame {
509                            scene: Default::default(),
510                            hit_regions: Vec::new(),
511                            semantics_nodes: Vec::new(),
512                            focus_chain: Vec::new(),
513                        })
514                }
515            }
516        };
517
518        let shortcut_state = self.shortcuts.clone();
519        let frame =
520            repose_core::shortcuts::with_runtime_state(&shortcut_state, || compose_once(self));
521
522        // Reconcile hover against the *new* hit list before presenting. If the
523        // hover target changed, recompose once so paint uses the correct
524        // Interactions.hover (eliminates 1-frame sticky/wrong hover).
525        let hover_before = self.hover_id;
526        self.reconcile_hover_from_mouse_pos(&frame);
527        if self.hover_id != hover_before {
528            // Refresh the retained leave map from the first frame so Leave on
529            // further changes still works (cache_frame does this fully).
530            self.hover_leave.clear();
531            for h in &frame.hit_regions {
532                if h.on_pointer_leave.is_some() {
533                    self.hover_leave
534                        .insert(h.id, repose_ui::HitRegionSnapshot::new(h));
535                }
536            }
537            // Hover should be stable: same geometry + same pointer. Do not loop.
538            return repose_core::shortcuts::with_runtime_state(&shortcut_state, || {
539                compose_once(self)
540            });
541        }
542        frame
543    }
544
545    /// Compose a frame and return structured output for the host.
546    pub fn frame(
547        &mut self,
548        mut root_fn: impl FnMut(&mut Scheduler, &RenderContext) -> View,
549        render_ctx: &RenderContext,
550    ) -> FrameOutput {
551        let (f, clipboard_text) = repose_core::clipboard::with_captured_clipboard(|| {
552            self.compose(&mut root_fn, render_ctx)
553        });
554
555        let wants_pointer = self.hover_id.is_some() || self.capture_id.is_some();
556
557        let focused_hit = self
558            .sched
559            .focused
560            .and_then(|fid| f.hit_regions.iter().find(|h| h.id == fid));
561        let ime_allowed = focused_hit.is_some_and(|hit| {
562            hit.on_ime.is_some()
563                || (hit.tf_enabled
564                    && !hit.tf_read_only
565                    && f.semantics_nodes.iter().any(|node| {
566                        node.id == hit.id && node.role == repose_core::semantics::Role::TextField
567                    }))
568        });
569
570        let ime_cursor_area = if ime_allowed {
571            focused_hit.map(|hit| {
572                let sf = self.scale as f64;
573                let origin = repose_ui::hit_region_transformed_origin(hit);
574                let local = repose_ui::hit_region_local_rect(hit);
575                (
576                    origin.x as f64 / sf,
577                    origin.y as f64 / sf,
578                    local.w as f64 / sf,
579                    local.h as f64 / sf,
580                )
581            })
582        } else {
583            None
584        };
585
586        let focused_is_textfield = ime_allowed
587            || self.sched.focused.is_some_and(|fid| {
588                f.hit_regions
589                    .iter()
590                    .any(|h| h.id == fid && h.tf_state_key.is_some())
591            });
592        let wants_keyboard = focused_is_textfield || self.ime_preedit;
593
594        let (ime_purpose, ime_auto_correct, ime_capitalization, keyboard_type) =
595            match (ime_allowed, focused_hit) {
596                (true, Some(hit)) => (
597                    hit.keyboard_type.ime_purpose_hint(),
598                    hit.auto_correct.unwrap_or(true),
599                    hit.capitalization,
600                    hit.keyboard_type,
601                ),
602                _ => (
603                    repose_core::ImePurposeHint::Normal,
604                    true,
605                    repose_core::KeyboardCapitalization::Unspecified,
606                    repose_core::KeyboardType::Unspecified,
607                ),
608            };
609
610        let declared = self.sched.cursor_override.take();
611        self.frame_cursor_override = declared.clone();
612        let cursor_grab = std::mem::take(&mut self.sched.cursor_grab);
613        let platform = PlatformOutput {
614            cursor: declared.or_else(|| self.take_cursor_suggestion()),
615            cursor_grab,
616            ime_allowed,
617            ime_cursor_area,
618            clipboard_text,
619            ime_purpose,
620            ime_auto_correct,
621            ime_capitalization,
622            keyboard_type,
623            window_theme_dark: Some(repose_core::locals::theme().is_dark()),
624        };
625        FrameOutput {
626            scene: f.scene,
627            hit_regions: f.hit_regions,
628            semantics_nodes: f.semantics_nodes,
629            focus_chain: f.focus_chain,
630            platform,
631            wants_pointer,
632            wants_keyboard,
633        }
634    }
635
636    /// Store the composed frame for event hit testing.
637    pub fn cache_frame(&mut self, frame: impl Into<Rc<Frame>>) {
638        let frame = frame.into();
639        let _dnd_guard = self.dnd_context.enter();
640        let stale_keys: Vec<Key> = self
641            .key_pressed
642            .iter()
643            .filter(|(_, id)| {
644                self.sched.focused != Some(**id)
645                    || !frame
646                        .hit_regions
647                        .iter()
648                        .any(|hit| hit.id == **id && !hit.disabled)
649            })
650            .map(|(key, _)| key.clone())
651            .collect();
652        for key in &stale_keys {
653            self.cancel_key_press(key);
654        }
655        self.hover_leave.clear();
656        for hit in &frame.hit_regions {
657            if hit.on_pointer_leave.is_some() {
658                self.hover_leave
659                    .insert(hit.id, repose_ui::HitRegionSnapshot::new(hit));
660            }
661        }
662        self.frame_cache = Some(frame);
663        self.reconcile_cached_targets();
664    }
665
666    /// Post-compose host-agnostic bookkeeping.
667    /// this lazy-initializes text-field state for focus-requester paths, reconciles
668    /// hover against the new hit list, and publishes the frame to the DnD
669    /// registry. Replaces platform-local copies of this logic.
670    pub fn after_compose(&mut self, frame: &Frame, scale: f32) {
671        self.after_compose_shared(Rc::new(frame.clone()), scale);
672    }
673
674    pub fn after_compose_shared(&mut self, frame: Rc<Frame>, scale: f32) {
675        let _dnd_guard = self.dnd_context.enter();
676        ensure_all_tf_states_from_frame(&mut self.textfield_states, &frame);
677        self.prune_textfield_states(&frame);
678        self.ensure_focused_state_in_frame(&frame);
679        self.reconcile_hover_from_mouse_pos(&frame);
680        self.dispatch_focused_bounds_callbacks(&frame);
681        repose_core::dnd::set_shared_dnd_frame(Some(frame));
682        repose_core::dnd::set_dnd_scale(scale);
683    }
684
685    fn prune_textfield_states(&mut self, frame: &Frame) {
686        if self.textfield_states.is_empty() {
687            return;
688        }
689        let live: std::collections::HashSet<u64> = frame
690            .hit_regions
691            .iter()
692            .filter_map(|h| h.tf_state_key)
693            .collect();
694        self.textfield_states.retain(|k, _| live.contains(k));
695    }
696
697    fn end_textfield_drag(&mut self, id: u64) {
698        let key = self
699            .frame_cache
700            .as_ref()
701            .and_then(|frame| is_tf_hit(frame, id).then(|| tf_key_of(frame, id)));
702        if let Some(key) = key {
703            self.end_textfield_drag_key(key);
704        }
705    }
706
707    fn end_textfield_drag_key(&mut self, key: u64) {
708        if let Some(state) = self.textfield_states.get(&key) {
709            state.borrow_mut().end_drag();
710        }
711    }
712
713    /// Lazy-init the focused textfield's persistent state (FocusRequester
714    /// paths don't create it until first click). Resets the caret blink.
715    pub fn ensure_focused_textfield_state(&mut self) {
716        let Some(f) = self.frame_cache.clone() else {
717            return;
718        };
719        self.ensure_focused_state_in_frame(&f);
720    }
721
722    /// Shared helper: create a persistent `TextFieldState` for the focused
723    /// widget (if it is a textfield with a state key) and reset its caret
724    /// blink. No-op when the focused widget already has state.
725    fn ensure_focused_state_in_frame(&mut self, frame: &Frame) {
726        let Some(fid) = self.sched.focused else {
727            return;
728        };
729        if let Some(hit) = frame.hit_regions.iter().find(|h| h.id == fid)
730            && let Some(key) = hit.tf_state_key
731        {
732            let st = ensure_tf_state(&mut self.textfield_states, key, hit.tf_value.as_str());
733            st.borrow_mut().apply_controlled_value(&hit.tf_value);
734        }
735    }
736
737    /// Fire `on_focused_bounds_changed` on every hit region that installed the
738    /// callback, passing the focused element's rect in physical pixels. Fires
739    /// only when focus or the focused bounds actually changed.
740    fn dispatch_focused_bounds_callbacks(&mut self, frame: &Frame) {
741        let focused = self.sched.focused;
742        let bounds = focused.and_then(|id| {
743            frame
744                .hit_regions
745                .iter()
746                .find(|h| h.id == id)
747                .map(|h| h.rect)
748        });
749        if bounds == self.last_focused_bounds {
750            return;
751        }
752        for hit in &frame.hit_regions {
753            if let Some(cb) = &hit.on_focused_bounds_changed
754                && let Some(rect) = bounds
755            {
756                cb(rect);
757            }
758        }
759        self.last_focused_bounds = bounds;
760    }
761
762    /// Cache a composed [`FrameOutput`] for hit-testing: rebuilds the retained
763    /// hover-leave map, reconciles hover, lazy-initializes focused textfield
764    /// state, and publishes the DnD frame/scale to the input registry.
765    pub fn cache_from_output(&mut self, out: &FrameOutput) {
766        let frame = Rc::new(Frame {
767            scene: out.scene.clone(),
768            hit_regions: out.hit_regions.clone(),
769            semantics_nodes: out.semantics_nodes.clone(),
770            focus_chain: out.focus_chain.clone(),
771        });
772        self.cache_frame(frame.clone());
773        self.after_compose_shared(frame, self.scale);
774    }
775
776    /// One-shot host tick: advance animations, compose a frame, and publish
777    /// the result (hover reconciliation, focused textfield lazy-init, DnD
778    /// frame/scale) in a single call.
779    pub fn compose_frame_output<F>(
780        &mut self,
781        root: &mut F,
782        render_ctx: &RenderContext,
783    ) -> FrameOutput
784    where
785        F: FnMut(&mut Scheduler, &RenderContext) -> View,
786    {
787        self.tick_animations();
788        let out = self.frame(root, render_ctx);
789        self.cache_from_output(&out);
790        out
791    }
792
793    fn dispatch_pointer_to_targets(
794        &self,
795        kind: PointerEventKind,
796        pos: Vec2,
797        targets: &[repose_ui::HitRegionSnapshot],
798        touch: Option<u64>,
799    ) -> bool {
800        let (id, pkind) = match touch {
801            Some(tid) => (PointerId(tid), PointerKind::Touch),
802            None => (PointerId(0), PointerKind::Mouse),
803        };
804        let base = PointerEvent::new(id, pkind, kind, pos, 1.0, self.modifiers);
805        let mut move_consumed = false;
806        for target in targets {
807            let hit = target.hit();
808            let callback = match kind {
809                PointerEventKind::Down(_) => &hit.on_pointer_down,
810                PointerEventKind::Up(_) => &hit.on_pointer_up,
811                PointerEventKind::Move => &hit.on_pointer_move,
812                PointerEventKind::Cancel => &hit.on_pointer_cancel,
813                PointerEventKind::Enter | PointerEventKind::Leave => continue,
814            };
815            let Some(callback) = callback else {
816                continue;
817            };
818            let mut event = base.clone();
819            let (origin, local) = target.pointer_coordinates(pos);
820            event.origin = origin;
821            event.position = local;
822            callback(event);
823            if base.is_consumed() {
824                if matches!(kind, PointerEventKind::Move) {
825                    move_consumed = true;
826                }
827                if !matches!(kind, PointerEventKind::Cancel) {
828                    break;
829                }
830            }
831        }
832        move_consumed
833    }
834
835    fn dispatch_pointer_to_path(
836        &self,
837        kind: PointerEventKind,
838        pos: Vec2,
839        path: &[u64],
840        touch: Option<u64>,
841    ) -> bool {
842        let Some(frame) = &self.frame_cache else {
843            return false;
844        };
845        let targets: Vec<_> = path
846            .iter()
847            .filter_map(|id| frame.hit_regions.iter().find(|hit| hit.id == *id))
848            .map(repose_ui::HitRegionSnapshot::new)
849            .collect();
850        self.dispatch_pointer_to_targets(kind, pos, &targets, touch)
851    }
852
853    /// Splits captured targets into live/stale against the current frame.
854    /// Live targets keep the snapshot captured at press time so the whole
855    /// gesture dispatches to the original closures (pointer-capture
856    /// semantics); stale targets (gone or disabled) keep their snapshot so
857    /// the cancel reaches the handlers that received the press.
858    fn refreshed_capture_targets(
859        &self,
860        targets: &[repose_ui::HitRegionSnapshot],
861    ) -> (
862        Vec<repose_ui::HitRegionSnapshot>,
863        Vec<repose_ui::HitRegionSnapshot>,
864    ) {
865        let Some(frame) = &self.frame_cache else {
866            return (targets.to_vec(), Vec::new());
867        };
868        let mut live = Vec::with_capacity(targets.len());
869        let mut stale = Vec::new();
870        for target in targets {
871            if frame
872                .hit_regions
873                .iter()
874                .any(|hit| hit.id == target.id() && !hit.disabled)
875            {
876                live.push(target.clone());
877            } else {
878                stale.push(target.clone());
879            }
880        }
881        (live, stale)
882    }
883
884    fn cancel_dnd_capture(&mut self, touch: Option<u64>, source_id: u64) -> bool {
885        if !self
886            .dnd_capture
887            .as_ref()
888            .is_some_and(|capture| capture.touch == touch && capture.source_id == source_id)
889        {
890            return false;
891        }
892        self.dnd_capture = None;
893        dnd::handle_drag_action(&DragAction::Cancel)
894    }
895
896    fn cancel_active_dnd(&mut self) -> bool {
897        if self.dnd_capture.take().is_none() {
898            return false;
899        }
900        dnd::handle_drag_action(&DragAction::Cancel)
901    }
902
903    fn reconcile_cached_targets(&mut self) {
904        let mouse_pos = Vec2 {
905            x: self.mouse_pos_px.0,
906            y: self.mouse_pos_px.1,
907        };
908        if let Some(targets) = self.mouse_targets.take() {
909            let capture_id = targets.first().map(|target| target.id());
910            let capture_key = targets.first().and_then(|target| target.hit().tf_state_key);
911            let (live, stale) = self.refreshed_capture_targets(&targets);
912            if !stale.is_empty() {
913                self.dispatch_pointer_to_targets(PointerEventKind::Cancel, mouse_pos, &stale, None);
914            }
915            let capture_stale =
916                capture_id.is_some_and(|id| stale.iter().any(|target| target.id() == id));
917            if capture_stale {
918                self.pressed_ids.remove(&capture_id.unwrap_or_default());
919                self.capture_id = None;
920                self.hit_path = None;
921                if let Some(key) = capture_key {
922                    self.end_textfield_drag_key(key);
923                }
924                if self
925                    .long_press
926                    .is_some_and(|(id, _, _, _)| Some(id) == capture_id)
927                {
928                    self.long_press = None;
929                    self.long_press_touch = None;
930                }
931                self.cancel_dnd_capture(None, capture_id.unwrap_or_default());
932            } else {
933                self.mouse_targets = (!live.is_empty()).then_some(live);
934                self.hit_path = self
935                    .mouse_targets
936                    .as_ref()
937                    .map(|targets| targets.iter().map(|target| target.id()).collect());
938            }
939            if !stale.is_empty() {
940                request_frame();
941            }
942        }
943
944        let mut touch_ids: Vec<u64> = self.touch_targets.keys().copied().collect();
945        touch_ids.sort_unstable();
946        let mut changed = false;
947        for tid in touch_ids {
948            let Some(targets) = self.touch_targets.remove(&tid) else {
949                continue;
950            };
951            let pos = self.touch_positions.get(&tid).copied().unwrap_or(mouse_pos);
952            let old_capture = self.touch_presses.get(&tid).map(|state| state.capture_id);
953            let old_capture_key = targets.first().and_then(|target| target.hit().tf_state_key);
954            let (live, stale) = self.refreshed_capture_targets(&targets);
955            if !stale.is_empty() {
956                self.dispatch_pointer_to_targets(PointerEventKind::Cancel, pos, &stale, Some(tid));
957                changed = true;
958            }
959            let capture_stale =
960                old_capture.is_some_and(|id| stale.iter().any(|target| target.id() == id));
961            if capture_stale {
962                self.touch_targets.remove(&tid);
963                self.touch_paths.remove(&tid);
964                self.touch_presses.remove(&tid);
965                self.touch_move_consumers.remove(&tid);
966                self.suppressed_touch_clicks.remove(&tid);
967                if let Some(key) = old_capture_key {
968                    self.end_textfield_drag_key(key);
969                }
970                if self.long_press_touch == Some(tid)
971                    && old_capture.is_some_and(|id| {
972                        self.long_press
973                            .is_some_and(|(long_id, _, _, _)| long_id == id)
974                    })
975                {
976                    self.long_press = None;
977                    self.long_press_touch = None;
978                }
979                if self.touch_primary == Some(tid) {
980                    set_touch_gesture_active(false);
981                    self.long_press = None;
982                    self.long_press_touch = None;
983                    self.touch_primary = None;
984                    self.double_candidate = None;
985                    self.pending_click = None;
986                    self.pending_focus_on_click = None;
987                    self.last_up = None;
988                    self.last_down = None;
989                    self.press_origin = None;
990                    self.suppress_next_click = false;
991                    self.scroll_capture_id = None;
992                    if let Some(source_id) = old_capture {
993                        self.cancel_dnd_capture(Some(tid), source_id);
994                    }
995                }
996            } else if live.is_empty() {
997                self.touch_paths.remove(&tid);
998                self.touch_presses.remove(&tid);
999                self.touch_move_consumers.remove(&tid);
1000                self.suppressed_touch_clicks.remove(&tid);
1001            } else {
1002                self.touch_targets.insert(tid, live.clone());
1003                self.touch_paths
1004                    .insert(tid, live.iter().map(|target| target.id()).collect());
1005            }
1006        }
1007        if changed {
1008            self.rebuild_pressed_ids();
1009            request_frame();
1010        }
1011    }
1012
1013    /// Process a pointer-move event. Returns cursor suggestion.
1014    pub fn handle_pointer_move(&mut self, pos: Vec2) -> PointerMoveResult {
1015        self.handle_touch_move(None, pos)
1016    }
1017
1018    /// Touch move with a stable finger id (same pairing as
1019    /// [`Self::handle_touch_press`]).
1020    ///
1021    /// Touch never hovers: Compose feeds `collectIsHovered` from pointer
1022    /// *hover* events only, so finger motion must not raise hover state
1023    /// layers or the ripple's hover circle. `pointer_inside` and
1024    /// `hover_id` stay mouse-owned (driven by `CursorMoved`/`CursorEnter`).
1025    pub fn handle_touch_move(&mut self, touch: Option<u64>, pos: Vec2) -> PointerMoveResult {
1026        let _event_scope = crate::lifecycle::enter_dispatchers(self.event_dispatchers());
1027        let _dnd_guard = self.dnd_context.enter();
1028        self.mouse_pos_px = (pos.x, pos.y);
1029        if let Some(tid) = touch {
1030            self.touch_positions.insert(tid, pos);
1031        }
1032        let from_mouse = touch.is_none();
1033        if from_mouse {
1034            self.pointer_inside = true;
1035            self.sched.pointer_pos_px = Some((pos.x, pos.y));
1036        }
1037
1038        let owns_dnd_move = self
1039            .dnd_capture
1040            .as_ref()
1041            .is_some_and(|capture| capture.touch == touch);
1042        let dnd_move_consumed = owns_dnd_move
1043            && dnd::handle_drag_action(&DragAction::Move {
1044                position: pos,
1045                modifiers: self.modifiers,
1046            });
1047        if dnd_move_consumed {
1048            self.cancel_keyboard_press();
1049            request_frame();
1050        }
1051
1052        let Some(f) = &self.frame_cache else {
1053            return PointerMoveResult {
1054                cursor: self.move_cursor_suggestion(),
1055                hover_id: None,
1056            };
1057        };
1058
1059        let active_long_press_matches = match (touch, self.long_press_touch) {
1060            (Some(tid), Some(active)) => tid == active,
1061            (None, None) => true,
1062            _ => false,
1063        };
1064        if active_long_press_matches && let Some((_, _, x0, y0)) = self.long_press {
1065            let slop_dp = if touch.is_none() {
1066                MOUSE_TAP_SLOP_DP
1067            } else {
1068                LONG_PRESS_SLOP_DP
1069            };
1070            let slop = slop_dp * self.scale;
1071            let dx = pos.x - x0;
1072            let dy = pos.y - y0;
1073            if dx * dx + dy * dy > slop * slop {
1074                self.long_press = None;
1075                self.long_press_touch = None;
1076            }
1077        }
1078
1079        // Cancel the long press once the pointer leaves the element's bounds
1080        if active_long_press_matches
1081            && self.long_press.is_some()
1082            && let Some(lid) = self.long_press.map(|(id, _, _, _)| id)
1083            && f.hit_regions
1084                .iter()
1085                .find(|h| h.id == lid)
1086                .is_none_or(|h| !repose_ui::hit_region_contains(h, pos))
1087        {
1088            self.long_press = None;
1089            self.long_press_touch = None;
1090        }
1091
1092        let text_capture = match touch {
1093            Some(tid) => self.touch_presses.get(&tid).map(|state| state.capture_id),
1094            None => self.capture_id,
1095        };
1096        let owns_text_drag = touch.is_none() || self.touch_primary == touch;
1097        if owns_text_drag
1098            && let Some(cid) = text_capture
1099            && is_tf_hit(f, cid)
1100            && let Some(hit) = f.hit_regions.iter().find(|h| h.id == cid)
1101        {
1102            let key = tf_key_of(f, cid);
1103            if let Some(st_rc) = self.textfield_states.get(&key) {
1104                let mut st = st_rc.borrow_mut();
1105                let local = repose_ui::hit_region_to_local(hit, pos);
1106                let local_rect = repose_ui::hit_region_local_rect(hit);
1107                let content_origin = hit
1108                    .tf_content_origin
1109                    .map(|(x, y)| repose_ui::hit_region_to_local(hit, Vec2 { x, y }))
1110                    .unwrap_or(Vec2 {
1111                        x: local_rect.x,
1112                        y: local_rect.y,
1113                    });
1114                let content_x = (local.x - content_origin.x + st.scroll_offset).max(0.0);
1115                let content_y = (local.y - content_origin.y + st.scroll_offset_y).max(0.0);
1116                let metrics = repose_ui::textfield::textfield_metrics(hit);
1117                let wrap_w = st.inner_width.max(1.0);
1118                let idx = if hit.tf_multiline {
1119                    index_for_xy_bytes_vt(&st, &metrics, wrap_w, content_x, content_y)
1120                } else {
1121                    index_for_x_bytes_vt(&st, &metrics, content_x)
1122                };
1123                st.drag_to(idx);
1124            }
1125        }
1126
1127        let top = repose_ui::hit_test_enabled_frame(f, pos);
1128
1129        if from_mouse {
1130            self.cursor = top
1131                .and_then(|h| h.cursor.clone())
1132                .or(Some(CursorIcon::Default));
1133            if dnd_move_consumed && dnd::is_dragging() {
1134                self.cursor = Some(CursorIcon::Grabbing);
1135            }
1136
1137            let new_hover = top.map(|h| h.id);
1138
1139            let old_chain = hover_chain_for(Some(f), self.hover_id);
1140            let new_chain = hover_chain_for(Some(f), new_hover);
1141            if new_chain != old_chain {
1142                dispatch_hover_change_bubbled(
1143                    Some(f),
1144                    &self.hover_leave,
1145                    &mut self.hover_id,
1146                    &mut self.hover_ancestors,
1147                    new_hover,
1148                    pos,
1149                    self.modifiers,
1150                );
1151                request_frame();
1152            }
1153        }
1154
1155        if let Some(tid) = touch {
1156            let move_consumed = if let Some(targets) = self.touch_targets.get(&tid) {
1157                self.dispatch_pointer_to_targets(PointerEventKind::Move, pos, targets, Some(tid))
1158            } else if let Some(path) = self.touch_paths.get(&tid).cloned() {
1159                self.dispatch_pointer_to_path(PointerEventKind::Move, pos, &path, Some(tid))
1160            } else {
1161                false
1162            };
1163            if move_consumed {
1164                self.touch_move_consumers.insert(tid);
1165            }
1166            return PointerMoveResult {
1167                cursor: self.move_cursor_suggestion(),
1168                hover_id: self.hover_id,
1169            };
1170        }
1171
1172        if let Some(targets) = &self.mouse_targets {
1173            self.dispatch_pointer_to_targets(PointerEventKind::Move, pos, targets, None);
1174        } else if let Some(path) = self.hit_path.clone() {
1175            self.dispatch_pointer_to_path(PointerEventKind::Move, pos, &path, None);
1176        }
1177        if self.hit_path.is_none()
1178            && let Some(h) = top
1179            && let Some(cb) = &h.on_pointer_move
1180        {
1181            let (id, kind) = match touch {
1182                Some(tid) => (PointerId(tid), PointerKind::Touch),
1183                None => (PointerId(0), PointerKind::Mouse),
1184            };
1185            let mut pe =
1186                PointerEvent::new(id, kind, PointerEventKind::Move, pos, 1.0, self.modifiers);
1187            let (origin, local) = repose_ui::hit_region_pointer_coordinates(h, pos);
1188            pe.origin = origin;
1189            pe.position = local;
1190            cb(pe);
1191        }
1192
1193        PointerMoveResult {
1194            cursor: self.move_cursor_suggestion(),
1195            hover_id: self.hover_id,
1196        }
1197    }
1198
1199    /// Process a pointer button press. Returns focus/capture info.
1200    pub fn handle_pointer_press(
1201        &mut self,
1202        pos: Vec2,
1203        button: PointerButton,
1204    ) -> PointerButtonResult {
1205        self.handle_touch_press(None, pos, button)
1206    }
1207
1208    /// Touch press with a stable finger id: same hit-path dispatch as
1209    /// the mouse press, but the event carries `PointerKind::Touch` +
1210    /// the finger id, so game viewports stage per-finger contacts
1211    /// instead of one shared mouse point (GML `device_mouse_*` parity).
1212    pub fn handle_touch_press(
1213        &mut self,
1214        touch: Option<u64>,
1215        pos: Vec2,
1216        button: PointerButton,
1217    ) -> PointerButtonResult {
1218        let _event_scope = crate::lifecycle::enter_dispatchers(self.event_dispatchers());
1219        let _dnd_guard = self.dnd_context.enter();
1220        self.mouse_pos_px = (pos.x, pos.y);
1221        if let Some(tid) = touch {
1222            self.touch_positions.insert(tid, pos);
1223        }
1224        if touch.is_none() {
1225            self.sched.pointer_pos_px = Some((pos.x, pos.y));
1226        }
1227        if touch.is_none() {
1228            self.held_mouse.insert(button);
1229        }
1230        let _ = repose_core::request_input_mode(repose_core::InputMode::Touch);
1231
1232        if touch.is_none() && (self.capture_id.is_some() || self.hit_path.is_some()) {
1233            self.handle_pointer_cancel();
1234        }
1235        // A new press supersedes any held track-press repeat for this pointer;
1236        // the dispatch below may begin a fresh one.
1237        repose_ui::scrollbar_repeat::cancel_track_repeat_for_touch(touch);
1238        if let Some(tid) = touch
1239            && self.touch_presses.contains_key(&tid)
1240        {
1241            self.handle_touch_cancel(Some(tid));
1242        }
1243        if let Some(tid) = touch {
1244            self.touch_positions.insert(tid, pos);
1245        }
1246
1247        let Some(frame) = self.frame_cache.clone() else {
1248            return PointerButtonResult {
1249                focused: None,
1250                capture_id: None,
1251                consumed: false,
1252                needs_a11y_announce: false,
1253                clicked_id: None,
1254            };
1255        };
1256        let f = &frame;
1257
1258        let mut result = PointerButtonResult {
1259            focused: None,
1260            capture_id: None,
1261            consumed: false,
1262            needs_a11y_announce: false,
1263            clicked_id: None,
1264        };
1265        let primary_pointer = match touch {
1266            Some(tid) => {
1267                if self.touch_primary.is_none() {
1268                    self.touch_primary = Some(tid);
1269                }
1270                self.touch_primary == Some(tid)
1271            }
1272            None => true,
1273        };
1274
1275        if primary_pointer {
1276            self.cancel_keyboard_press();
1277        }
1278
1279        let path = repose_ui::hit_test_frame_path(f, pos);
1280        if let Some(&capture_id) = path.first()
1281            && let Some(hit) = f.hit_regions.iter().find(|hit| hit.id == capture_id)
1282        {
1283            if touch.is_none() {
1284                self.hit_path = Some(path.clone());
1285            }
1286
1287            if touch.is_none() || primary_pointer {
1288                dnd::handle_drag_action(&DragAction::Press {
1289                    position: pos,
1290                    capture_id: hit.id,
1291                    kind: match touch {
1292                        Some(_) => PointerKind::Touch,
1293                        None => PointerKind::Mouse,
1294                    },
1295                    modifiers: self.modifiers,
1296                });
1297                self.dnd_capture = Some(DndPointerCapture {
1298                    touch,
1299                    source_id: hit.id,
1300                });
1301            }
1302
1303            if touch.is_none() {
1304                self.capture_id = Some(hit.id);
1305            }
1306            result.capture_id = Some(hit.id);
1307            result.consumed = true;
1308            let targets: Vec<_> = path
1309                .iter()
1310                .filter_map(|id| f.hit_regions.iter().find(|hit| hit.id == *id))
1311                .map(repose_ui::HitRegionSnapshot::new)
1312                .collect();
1313            if let Some(tid) = touch {
1314                self.touch_paths.insert(tid, path.clone());
1315                self.touch_targets.insert(tid, targets);
1316                self.touch_move_consumers.remove(&tid);
1317                self.touch_presses.insert(
1318                    tid,
1319                    TouchPressState {
1320                        capture_id: hit.id,
1321                        pressed_ids: HashSet::from([hit.id]),
1322                    },
1323                );
1324            } else {
1325                self.mouse_targets = Some(targets);
1326            }
1327
1328            // A new press cancels a still-pending delayed single click only
1329            // when it qualifies as the second tap of a double click on the
1330            // same element (Compose detectTapGestures).
1331            if primary_pointer {
1332                self.last_down = Some((hit.id, web_time::Instant::now()));
1333                self.press_origin = Some((hit.id, pos.x, pos.y));
1334                // The second DOWN must land within
1335                // [doubleTapMinTimeMillis, doubleTapTimeoutMillis] after the first
1336                // tap's UP, and within tap slop of it. Compose requires both: two
1337                // taps far apart are two taps, not a double tap.
1338                self.double_candidate = if hit.on_double_click.is_some()
1339                    && self.last_up.is_some_and(|(pid, t0, ux, uy)| {
1340                        pid == hit.id
1341                            && !moved_past_slop(ux, uy, pos, TAP_SLOP_DP, self.scale)
1342                            && self.last_down.is_some_and(|(did, dt)| {
1343                                did == hit.id
1344                                    && dt.duration_since(t0).as_millis() >= DOUBLE_TAP_MIN_MS
1345                                    && dt.duration_since(t0).as_millis() <= DOUBLE_CLICK_MS
1346                            })
1347                    }) {
1348                    Some(hit.id)
1349                } else {
1350                    None
1351                };
1352                if self.double_candidate.is_some() {
1353                    // The pair is a double tap: drop the deferred first click.
1354                    self.pending_click = None;
1355                } else if self
1356                    .pending_click
1357                    .as_ref()
1358                    .is_some_and(|(pid, ..)| *pid == hit.id)
1359                {
1360                    // A new press on the same element that cannot be the second
1361                    // half of a double tap settles the deferred click. It has to
1362                    // fire now, or this press would overwrite it in the single
1363                    // pending slot and the tap would be lost.
1364                    if let Some((_, _, cb)) = self.pending_click.take() {
1365                        cb();
1366                    }
1367                }
1368
1369                if let PointerButton::Primary = button {
1370                    self.long_press = if hit.on_long_click.is_some() {
1371                        Some((hit.id, web_time::Instant::now(), pos.x, pos.y))
1372                    } else {
1373                        None
1374                    };
1375                    self.long_press_touch = touch;
1376                    self.suppress_next_click = false;
1377                }
1378            }
1379
1380            if primary_pointer
1381                && hit.tf_enabled
1382                && (hit.tf_state_key.is_some() || is_textfield_in_frame(f, hit.id))
1383            {
1384                let key = tf_key_of(f, hit.id);
1385                let seed = hit.tf_value.as_str();
1386                let st_rc = ensure_tf_state(&mut self.textfield_states, key, seed);
1387                {
1388                    let mut st = st_rc.borrow_mut();
1389                    // Sync text only; never place-at-end here.
1390                    st.apply_controlled_value(seed);
1391
1392                    if st.inner_width <= 0.0 {
1393                        let local_rect = repose_ui::hit_region_local_rect(hit);
1394                        st.set_inner_width(local_rect.w.max(1.0));
1395                        st.set_inner_height(local_rect.h.max(1.0));
1396                    }
1397
1398                    let local = repose_ui::hit_region_to_local(hit, pos);
1399                    let local_rect = repose_ui::hit_region_local_rect(hit);
1400                    let content_origin = hit
1401                        .tf_content_origin
1402                        .map(|(x, y)| repose_ui::hit_region_to_local(hit, Vec2 { x, y }))
1403                        .unwrap_or(Vec2 {
1404                            x: local_rect.x,
1405                            y: local_rect.y,
1406                        });
1407                    let content_x = (local.x - content_origin.x + st.scroll_offset).max(0.0);
1408                    let content_y = (local.y - content_origin.y + st.scroll_offset_y).max(0.0);
1409                    let metrics = repose_ui::textfield::textfield_metrics(hit);
1410                    let wrap_w = st.inner_width.max(1.0);
1411
1412                    let idx = if hit.tf_multiline {
1413                        index_for_xy_bytes_vt(&st, &metrics, wrap_w, content_x, content_y)
1414                    } else {
1415                        index_for_x_bytes_vt(&st, &metrics, content_x)
1416                    };
1417                    st.handle_pointer_down(idx, (pos.x, pos.y), self.modifiers.shift);
1418                    // caret was placed by pointer this gesture
1419                }
1420            }
1421
1422            self.pressed_ids.insert(hit.id);
1423
1424            if primary_pointer && hit.focusable {
1425                if hit.tf_state_key.is_some() || is_textfield_in_frame(f, hit.id) {
1426                    // Text fields take focus on pointer-down so the caret is
1427                    // placed and the IME opens immediately (Compose parity).
1428                    if self.sched.focused != Some(hit.id) {
1429                        self.finish_compositions();
1430                    }
1431                    self.sched.focused = Some(hit.id);
1432                    result.focused = Some(hit.id);
1433                    let key = tf_key_of(f, hit.id);
1434                    let st =
1435                        ensure_tf_state(&mut self.textfield_states, key, hit.tf_value.as_str());
1436                    let mut s = st.borrow_mut();
1437                    s.apply_controlled_value(&hit.tf_value);
1438                    s.reset_caret_blink();
1439                } else {
1440                    // Buttons and other clickables receive focus on click, not
1441                    // on pointer-down. Deferring keeps focus on a previously
1442                    // focused TextField when the press turns into a scroll.
1443                    self.pending_focus_on_click = Some(hit.id);
1444                    result.focused = self.sched.focused;
1445                }
1446            }
1447
1448            let targets = if touch.is_some() {
1449                self.touch_targets.get(&touch.unwrap()).cloned()
1450            } else {
1451                self.mouse_targets.clone()
1452            };
1453            if let Some(targets) = targets {
1454                self.dispatch_pointer_to_targets(
1455                    PointerEventKind::Down(button),
1456                    pos,
1457                    &targets,
1458                    touch,
1459                );
1460            }
1461
1462            request_frame();
1463        } else if primary_pointer {
1464            if touch.is_none() {
1465                self.hit_path = None;
1466                self.mouse_targets = None;
1467                self.capture_id = None;
1468                self.pressed_ids.clear();
1469            } else if let Some(tid) = touch {
1470                self.touch_paths.remove(&tid);
1471                self.touch_targets.remove(&tid);
1472                self.touch_positions.remove(&tid);
1473            }
1474            self.finish_compositions();
1475            self.sched.focused = None;
1476            request_frame();
1477        }
1478
1479        result
1480    }
1481
1482    /// Process a pointer button release.
1483    pub fn handle_pointer_release(
1484        &mut self,
1485        pos: Vec2,
1486        button: PointerButton,
1487    ) -> PointerButtonResult {
1488        self.handle_touch_release(None, pos, button)
1489    }
1490
1491    /// Touch release with a stable finger id (same pairing as
1492    /// [`Self::handle_touch_press`]).
1493    pub fn handle_touch_release(
1494        &mut self,
1495        touch: Option<u64>,
1496        pos: Vec2,
1497        button: PointerButton,
1498    ) -> PointerButtonResult {
1499        let _event_scope = crate::lifecycle::enter_dispatchers(self.event_dispatchers());
1500        let _dnd_guard = self.dnd_context.enter();
1501        self.mouse_pos_px = (pos.x, pos.y);
1502        if let Some(tid) = touch {
1503            self.touch_positions.insert(tid, pos);
1504        } else {
1505            self.sched.pointer_pos_px = Some((pos.x, pos.y));
1506            self.held_mouse.remove(&button);
1507        }
1508        // The pointer is up: any track-press repeat it drove ends here even if
1509        // the track hit itself is gone (recomposed away) and never sees Up.
1510        repose_ui::scrollbar_repeat::cancel_track_repeat_for_touch(touch);
1511        let mut result = PointerButtonResult {
1512            focused: self.sched.focused,
1513            capture_id: self.capture_id,
1514            consumed: false,
1515            needs_a11y_announce: false,
1516            clicked_id: None,
1517        };
1518        if let Some(tid) = touch {
1519            return self.finish_touch_release(tid, pos, button, result);
1520        }
1521
1522        let owns_dnd_release = self.dnd_capture.as_ref().is_some_and(|capture| {
1523            capture.touch.is_none() && Some(capture.source_id) == self.capture_id
1524        });
1525        let drag_consumed = if owns_dnd_release {
1526            self.dnd_capture = None;
1527            dnd::handle_drag_action(&DragAction::Release {
1528                position: pos,
1529                modifiers: self.modifiers,
1530            })
1531        } else {
1532            false
1533        };
1534        if let Some(targets) = &self.mouse_targets {
1535            self.dispatch_pointer_to_targets(PointerEventKind::Up(button), pos, targets, None);
1536            result.consumed = true;
1537        } else if let Some(path) = &self.hit_path {
1538            self.dispatch_pointer_to_path(PointerEventKind::Up(button), pos, path, None);
1539            result.consumed = true;
1540        }
1541        if let Some(cid) = self.capture_id {
1542            self.pressed_ids.remove(&cid);
1543            self.end_textfield_drag(cid);
1544        }
1545        if drag_consumed {
1546            self.capture_id = None;
1547            self.hit_path = None;
1548            self.mouse_targets = None;
1549            request_frame();
1550            result.consumed = true;
1551            return result;
1552        }
1553
1554        let f = match &self.frame_cache {
1555            Some(f) => f.clone(),
1556            None => {
1557                self.capture_id = None;
1558                self.hit_path = None;
1559                self.mouse_targets = None;
1560                self.pressed_ids.clear();
1561                return result;
1562            }
1563        };
1564
1565        // Long-press resolution: `poll_long_press` normally fires on timeout when held.
1566        if self.long_press_touch.is_none()
1567            && let Some((lid, t0, _, _)) = self.long_press.take()
1568            && Some(lid) == self.capture_id
1569            && t0.elapsed().as_millis() >= LONG_PRESS_MS
1570            && let Some(hit) = f.hit_regions.iter().find(|h| h.id == lid && !h.disabled)
1571            && let Some(cb) = &hit.on_long_click
1572        {
1573            cb();
1574            self.suppress_next_click = true;
1575            self.pending_click = None;
1576            result.clicked_id = Some(lid);
1577            result.needs_a11y_announce = true;
1578            result.consumed = true;
1579        }
1580
1581        // A press that travelled past tap slop is a drag, not a tap, so nothing
1582        // below may activate the element. Compose `detectTapGestures` drops the
1583        // tap on the same condition; without this, releasing after a drag fires
1584        // onClick anyway.
1585        let dragged = self.drag_cancelled_tap(self.capture_id, pos, true);
1586        if dragged {
1587            self.pending_click = None;
1588            self.pending_focus_on_click = None;
1589        }
1590
1591        if button == PointerButton::Primary
1592            && self.double_candidate.is_none()
1593            && !dragged
1594            && !self.suppress_next_click
1595            && let Some(cid) = self.capture_id
1596            && let Some(hit) = f.hit_regions.iter().find(|h| h.id == cid && !h.disabled)
1597            && repose_ui::hit_region_contains(hit, pos)
1598        {
1599            if self.pending_focus_on_click.take() == Some(cid) {
1600                if self.sched.focused != Some(cid) {
1601                    self.finish_compositions();
1602                }
1603                self.sched.focused = Some(cid);
1604                result.focused = Some(cid);
1605            }
1606            let now = web_time::Instant::now();
1607            // With onDoubleTap present, single
1608            // clicks are delayed until the double-tap window elapses.
1609            if hit.on_double_click.is_some() {
1610                if let Some(cb) = hit.on_click.clone() {
1611                    self.pending_click = Some((cid, now, cb));
1612                }
1613                self.last_up = Some((cid, now, pos.x, pos.y));
1614                result.consumed = true;
1615                request_frame(); // need another frame to flush pending
1616            } else {
1617                if let Some(cb) = &hit.on_click {
1618                    cb();
1619                }
1620                self.last_up = Some((cid, now, pos.x, pos.y));
1621                result.clicked_id = Some(cid);
1622                result.needs_a11y_announce = true;
1623                result.consumed = true;
1624            }
1625        }
1626        self.suppress_next_click = false;
1627
1628        // Double-click resolution. The second DOWN (handle_pointer_down)
1629        // qualifies the pair; the second UP confirms it. A canceled second tap
1630        // (moved out of bounds, or dragged) falls back to the first tap's
1631        // onClick, unless it dragged in which case nothing activates.
1632        if let Some(dc) = self.double_candidate.take() {
1633            self.pending_click = None;
1634            self.last_up = None;
1635            self.last_down = None;
1636            if dragged {
1637                // The second press turned into a drag: the pair is not a double
1638                // tap and the deferred first click is dropped with it.
1639            } else if self.capture_id == Some(dc)
1640                && let Some(hit) = f.hit_regions.iter().find(|h| h.id == dc && !h.disabled)
1641                && repose_ui::hit_region_contains(hit, pos)
1642            {
1643                if let Some(cb) = &hit.on_double_click {
1644                    cb();
1645                }
1646                result.clicked_id = Some(dc);
1647                result.needs_a11y_announce = true;
1648                result.consumed = true;
1649            } else if self.capture_id == Some(dc)
1650                && let Some(hit) = f.hit_regions.iter().find(|h| h.id == dc && !h.disabled)
1651            {
1652                // Second tap canceled -> the first tap counts as a click.
1653                if let Some(cb) = &hit.on_click {
1654                    cb();
1655                }
1656                result.clicked_id = Some(dc);
1657                result.needs_a11y_announce = true;
1658                result.consumed = true;
1659            }
1660        }
1661
1662        self.capture_id = None;
1663        self.hit_path = None;
1664        self.mouse_targets = None;
1665        self.press_origin = None;
1666        request_frame();
1667        result
1668    }
1669
1670    fn finish_touch_release(
1671        &mut self,
1672        tid: u64,
1673        pos: Vec2,
1674        button: PointerButton,
1675        mut result: PointerButtonResult,
1676    ) -> PointerButtonResult {
1677        let capture_id = self
1678            .touch_presses
1679            .remove(&tid)
1680            .map(|state| state.capture_id);
1681        self.touch_move_consumers.remove(&tid);
1682        result.capture_id = capture_id;
1683        let targets = self.touch_targets.remove(&tid);
1684        if let Some(targets) = &targets {
1685            self.dispatch_pointer_to_targets(PointerEventKind::Up(button), pos, targets, Some(tid));
1686            result.consumed = true;
1687        } else if let Some(path) = self.touch_paths.remove(&tid) {
1688            self.dispatch_pointer_to_path(PointerEventKind::Up(button), pos, &path, Some(tid));
1689            result.consumed = true;
1690        }
1691        self.touch_paths.remove(&tid);
1692        self.touch_positions.remove(&tid);
1693        let primary = self.touch_primary == Some(tid);
1694        if let Some(cid) = capture_id {
1695            self.end_textfield_drag(cid);
1696        }
1697        let owns_dnd_release = self.dnd_capture.as_ref().is_some_and(|capture| {
1698            capture.touch == Some(tid) && Some(capture.source_id) == capture_id
1699        });
1700        let drag_consumed = if owns_dnd_release {
1701            self.dnd_capture = None;
1702            dnd::handle_drag_action(&DragAction::Release {
1703                position: pos,
1704                modifiers: self.modifiers,
1705            })
1706        } else {
1707            false
1708        };
1709        let suppressed = self.suppressed_touch_clicks.remove(&tid);
1710        if primary
1711            && !drag_consumed
1712            && !suppressed
1713            && let Some(frame) = self.frame_cache.clone()
1714            && let Some(cid) = capture_id
1715        {
1716            if self.long_press_touch == Some(tid)
1717                && let Some((lid, t0, _, _)) = self.long_press.take()
1718                && lid == cid
1719                && t0.elapsed().as_millis() >= LONG_PRESS_MS
1720                && let Some(hit) = frame
1721                    .hit_regions
1722                    .iter()
1723                    .find(|hit| hit.id == lid && !hit.disabled)
1724                && let Some(callback) = &hit.on_long_click
1725            {
1726                callback();
1727                self.suppress_next_click = true;
1728                self.pending_click = None;
1729                result.clicked_id = Some(lid);
1730                result.needs_a11y_announce = true;
1731                result.consumed = true;
1732            }
1733
1734            // Same drag-cancels-tap rule as the mouse path.
1735            let dragged = self.drag_cancelled_tap(capture_id, pos, false);
1736            if dragged {
1737                self.pending_click = None;
1738                self.pending_focus_on_click = None;
1739            }
1740
1741            if self.double_candidate.is_none()
1742                && !dragged
1743                && !self.suppress_next_click
1744                && let Some(hit) = frame
1745                    .hit_regions
1746                    .iter()
1747                    .find(|hit| hit.id == cid && !hit.disabled)
1748                && repose_ui::hit_region_contains(hit, pos)
1749            {
1750                if self.pending_focus_on_click.take() == Some(cid) {
1751                    if self.sched.focused != Some(cid) {
1752                        self.finish_compositions();
1753                    }
1754                    self.sched.focused = Some(cid);
1755                    result.focused = Some(cid);
1756                }
1757                let now = web_time::Instant::now();
1758                if hit.on_double_click.is_some() {
1759                    if let Some(callback) = hit.on_click.clone() {
1760                        self.pending_click = Some((cid, now, callback));
1761                    }
1762                    self.last_up = Some((cid, now, pos.x, pos.y));
1763                    result.consumed = true;
1764                    request_frame();
1765                } else {
1766                    if let Some(callback) = &hit.on_click {
1767                        callback();
1768                    }
1769                    self.last_up = Some((cid, now, pos.x, pos.y));
1770                    result.clicked_id = Some(cid);
1771                    result.needs_a11y_announce = true;
1772                    result.consumed = true;
1773                }
1774            }
1775            self.suppress_next_click = false;
1776
1777            if let Some(double_id) = self.double_candidate.take() {
1778                self.pending_click = None;
1779                self.last_up = None;
1780                self.last_down = None;
1781                if let Some(hit) = frame
1782                    .hit_regions
1783                    .iter()
1784                    .find(|hit| hit.id == double_id && !hit.disabled)
1785                    && !dragged
1786                {
1787                    if repose_ui::hit_region_contains(hit, pos) {
1788                        if let Some(callback) = &hit.on_double_click {
1789                            callback();
1790                        }
1791                    } else if let Some(callback) = &hit.on_click {
1792                        callback();
1793                    }
1794                    result.clicked_id = Some(double_id);
1795                    result.needs_a11y_announce = true;
1796                    result.consumed = true;
1797                }
1798            }
1799        }
1800        if self.long_press_touch == Some(tid) {
1801            self.long_press = None;
1802            self.long_press_touch = None;
1803        }
1804        if primary {
1805            self.press_origin = None;
1806        }
1807        self.rebuild_pressed_ids();
1808        if primary {
1809            self.touch_primary = None;
1810        }
1811        request_frame();
1812        result
1813    }
1814
1815    /// Did the press behind `capture_id` travel past tap slop? When it did, the
1816    /// release is a drag and must not activate the element (Compose
1817    /// `detectTapGestures`).
1818    fn drag_cancelled_tap(&self, capture_id: Option<u64>, pos: Vec2, mouse: bool) -> bool {
1819        let Some(cid) = capture_id else {
1820            return false;
1821        };
1822        if self.press_origin.is_some_and(|(oid, x0, y0)| {
1823            oid == cid && moved_past_slop(x0, y0, pos, TAP_SLOP_DP, self.scale)
1824        }) {
1825            return true;
1826        }
1827        mouse
1828            && self.frame_cache.as_ref().is_some_and(|frame| {
1829                frame
1830                    .hit_regions
1831                    .iter()
1832                    .find(|hit| hit.id == cid)
1833                    .is_some_and(|hit| !repose_ui::hit_region_contains(hit, pos))
1834            })
1835    }
1836
1837    fn sync_key_pressed_mirror(&mut self) {
1838        self.key_pressed_active = self.key_pressed.values().next().copied();
1839    }
1840
1841    fn cancel_key_press(&mut self, key: &Key) {
1842        let Some(id) = self.key_pressed.remove(key) else {
1843            return;
1844        };
1845        self.key_long_press.remove(key);
1846        self.pressed_ids.remove(&id);
1847        self.sync_key_pressed_mirror();
1848        let hit = self
1849            .frame_cache
1850            .as_ref()
1851            .and_then(|frame| frame.hit_regions.iter().find(|hit| hit.id == id))
1852            .cloned();
1853        if let Some(hit) = hit
1854            && let Some(source) = &hit.interaction_source
1855        {
1856            let press_id = source.collect_last_press_id().unwrap_or(0);
1857            source.to_mutable().emit(Interaction::Cancel(press_id));
1858        }
1859    }
1860
1861    fn cancel_keyboard_press(&mut self) {
1862        let keys: Vec<Key> = self.key_pressed.keys().cloned().collect();
1863        for key in &keys {
1864            self.cancel_key_press(key);
1865        }
1866    }
1867
1868    fn rebuild_pressed_ids(&mut self) {
1869        self.pressed_ids = self
1870            .touch_presses
1871            .values()
1872            .flat_map(|state| state.pressed_ids.iter().copied())
1873            .collect();
1874        for id in self.key_pressed.values() {
1875            self.pressed_ids.insert(*id);
1876        }
1877    }
1878
1879    pub fn suppress_touch_click(&mut self, tid: u64) {
1880        self.suppressed_touch_clicks.insert(tid);
1881        if self.touch_primary == Some(tid) {
1882            self.suppress_next_click = true;
1883            self.long_press = None;
1884            self.pending_click = None;
1885            self.double_candidate = None;
1886        }
1887    }
1888
1889    /// Does the touch captured by `tid` drive the gesture through pointer
1890    /// moves, so an ancestor scroll container must not also scroll?
1891    ///
1892    /// True while a drag session is live (long-press drag and drop) or when
1893    /// the captured target consumed a pointer move. Compose's rule: a child
1894    /// that consumes the position change wins over the parent `scrollable`;
1895    /// merely having an `on_pointer_move` handler is not enough.
1896    pub fn touch_owns_drag(&self, tid: u64) -> bool {
1897        if dnd::is_dragging() {
1898            return true;
1899        }
1900        if let Some(cid) = self.touch_presses.get(&tid).map(|state| state.capture_id)
1901            && self.frame_cache.as_ref().is_some_and(|frame| {
1902                frame
1903                    .hit_regions
1904                    .iter()
1905                    .any(|hit| hit.id == cid && hit.drag_owner)
1906            })
1907        {
1908            return true;
1909        }
1910        self.touch_move_consumers.contains(&tid)
1911    }
1912
1913    /// Cancel mouse pointer state (focus lost). Touch fingers never feed
1914    /// the polled mouse position, so only a mouse cancel clears it.
1915    /// A touch cancel drops just that finger's path (the viewport
1916    /// must drop the contact); a mouse cancel (`None`) keeps the old
1917    /// full-reset behavior for the single mouse path.
1918    pub fn handle_touch_cancel(&mut self, touch: Option<u64>) {
1919        if let Some(tid) = touch {
1920            let pos = self.touch_positions.get(&tid).copied().unwrap_or(Vec2 {
1921                x: self.mouse_pos_px.0,
1922                y: self.mouse_pos_px.1,
1923            });
1924            self.handle_touch_cancel_at(tid, pos);
1925        } else {
1926            self.handle_pointer_cancel();
1927        }
1928    }
1929
1930    pub fn handle_touch_cancel_at(&mut self, tid: u64, pos: Vec2) {
1931        let _event_scope = crate::lifecycle::enter_dispatchers(self.event_dispatchers());
1932        let _dnd_guard = self.dnd_context.enter();
1933        repose_ui::scrollbar_repeat::cancel_track_repeat_for_touch(Some(tid));
1934        let was_primary = self.touch_primary == Some(tid);
1935        let capture_id = self
1936            .touch_presses
1937            .remove(&tid)
1938            .map(|state| state.capture_id);
1939        let targets = self.touch_targets.remove(&tid);
1940        self.touch_move_consumers.remove(&tid);
1941        if let Some(targets) = &targets {
1942            self.dispatch_pointer_to_targets(PointerEventKind::Cancel, pos, targets, Some(tid));
1943        } else if let Some(path) = self.touch_paths.remove(&tid) {
1944            self.dispatch_pointer_to_path(PointerEventKind::Cancel, pos, &path, Some(tid));
1945        }
1946        self.touch_paths.remove(&tid);
1947        self.touch_positions.remove(&tid);
1948        if let Some(cid) = capture_id {
1949            self.end_textfield_drag(cid);
1950        }
1951        self.suppressed_touch_clicks.remove(&tid);
1952        if was_primary {
1953            set_touch_gesture_active(false);
1954            self.touch_primary = None;
1955            self.double_candidate = None;
1956            self.pending_click = None;
1957            self.pending_focus_on_click = None;
1958            self.last_up = None;
1959            self.last_down = None;
1960            self.suppress_next_click = false;
1961            self.scroll_capture_id = None;
1962        }
1963        if self.long_press_touch == Some(tid) {
1964            self.long_press = None;
1965            self.long_press_touch = None;
1966        }
1967        self.rebuild_pressed_ids();
1968        if let Some(source_id) = capture_id {
1969            self.cancel_dnd_capture(Some(tid), source_id);
1970        }
1971        request_frame();
1972    }
1973
1974    pub fn handle_pointer_cancel(&mut self) {
1975        let _event_scope = crate::lifecycle::enter_dispatchers(self.event_dispatchers());
1976        let _dnd_guard = self.dnd_context.enter();
1977        repose_ui::scrollbar_repeat::cancel_all_track_repeats();
1978        self.sched.pointer_pos_px = None;
1979        self.held_mouse.clear();
1980        self.sched.mouse_primary = false;
1981        self.sched.mouse_secondary = false;
1982        self.sched.mouse_middle = false;
1983        self.scroll_capture_id = None;
1984        self.last_scroll_at = None;
1985        if let Some(cid) = self.capture_id {
1986            self.end_textfield_drag(cid);
1987        }
1988        let touch_targets = std::mem::take(&mut self.touch_targets);
1989        let touch_paths = std::mem::take(&mut self.touch_paths);
1990        let mut touch_ids: Vec<u64> = touch_targets
1991            .keys()
1992            .chain(touch_paths.keys())
1993            .copied()
1994            .collect();
1995        touch_ids.sort_unstable();
1996        touch_ids.dedup();
1997        for tid in touch_ids {
1998            let pos = self.touch_positions.remove(&tid).unwrap_or(Vec2 {
1999                x: self.mouse_pos_px.0,
2000                y: self.mouse_pos_px.1,
2001            });
2002            if let Some(targets) = touch_targets.get(&tid) {
2003                self.dispatch_pointer_to_targets(PointerEventKind::Cancel, pos, targets, Some(tid));
2004            } else if let Some(path) = touch_paths.get(&tid) {
2005                self.dispatch_pointer_to_path(PointerEventKind::Cancel, pos, path, Some(tid));
2006            }
2007        }
2008        let touch_presses = std::mem::take(&mut self.touch_presses);
2009        for (tid, state) in &touch_presses {
2010            let source_id = state.capture_id;
2011            self.cancel_dnd_capture(Some(*tid), source_id);
2012            self.end_textfield_drag(source_id);
2013        }
2014        self.touch_primary = None;
2015        self.suppressed_touch_clicks.clear();
2016        self.cancel_keyboard_press();
2017        self.long_press = None;
2018        self.long_press_touch = None;
2019        self.last_up = None;
2020        self.last_down = None;
2021        self.press_origin = None;
2022        self.double_candidate = None;
2023        self.suppress_next_click = false;
2024        if self.dnd_capture.is_some() {
2025            self.cancel_active_dnd();
2026        }
2027        let pos = Vec2 {
2028            x: self.mouse_pos_px.0,
2029            y: self.mouse_pos_px.1,
2030        };
2031        dispatch_hover_change_bubbled(
2032            self.frame_cache.as_deref(),
2033            &self.hover_leave,
2034            &mut self.hover_id,
2035            &mut self.hover_ancestors,
2036            None,
2037            pos,
2038            self.modifiers,
2039        );
2040        if let Some(targets) = &self.mouse_targets {
2041            self.dispatch_pointer_to_targets(PointerEventKind::Cancel, pos, targets, None);
2042        } else if let Some(path) = &self.hit_path {
2043            self.dispatch_pointer_to_path(PointerEventKind::Cancel, pos, path, None);
2044        }
2045        self.reset_pointer_state();
2046        request_frame();
2047    }
2048
2049    /// Clear hover state, emitting HoverLeave for the currently hovered region.
2050    pub fn clear_hover(&mut self) {
2051        if self.hover_id.is_none() && self.hover_ancestors.is_empty() {
2052            return;
2053        }
2054        let pos = Vec2 {
2055            x: self.mouse_pos_px.0,
2056            y: self.mouse_pos_px.1,
2057        };
2058        dispatch_hover_change_bubbled(
2059            self.frame_cache.as_deref(),
2060            &self.hover_leave,
2061            &mut self.hover_id,
2062            &mut self.hover_ancestors,
2063            None,
2064            pos,
2065            self.modifiers,
2066        );
2067    }
2068
2069    /// Reconcile hover state when the composed frame changes.
2070    pub fn reconcile_hover_from_mouse_pos(&mut self, new_frame: &Frame) {
2071        let pos = Vec2 {
2072            x: self.mouse_pos_px.0,
2073            y: self.mouse_pos_px.1,
2074        };
2075
2076        // If the previous hover target vanished from the new frame, deliver
2077        // Leave via the retained map (which survives tree removal), then clear.
2078        if let Some(prev_id) = self.hover_id
2079            && !new_frame.hit_regions.iter().any(|h| h.id == prev_id)
2080        {
2081            dispatch_hover_change_bubbled(
2082                Some(new_frame),
2083                &self.hover_leave,
2084                &mut self.hover_id,
2085                &mut self.hover_ancestors,
2086                None,
2087                pos,
2088                self.modifiers,
2089            );
2090        }
2091
2092        if !self.pointer_inside {
2093            if self.hover_id.is_some() || !self.hover_ancestors.is_empty() {
2094                dispatch_hover_change_bubbled(
2095                    Some(new_frame),
2096                    &self.hover_leave,
2097                    &mut self.hover_id,
2098                    &mut self.hover_ancestors,
2099                    None,
2100                    pos,
2101                    self.modifiers,
2102                );
2103                request_frame();
2104            }
2105            return;
2106        }
2107
2108        let new_hover = repose_ui::hit_test_enabled_frame(new_frame, pos).map(|hit| hit.id);
2109
2110        self.cursor = if dnd::is_dragging() {
2111            Some(CursorIcon::Grabbing)
2112        } else {
2113            new_hover
2114                .and_then(|id| new_frame.hit_regions.iter().find(|h| h.id == id))
2115                .and_then(|h| h.cursor.clone())
2116                .or(Some(CursorIcon::Default))
2117        };
2118
2119        let new_chain = hover_chain_for(Some(new_frame), new_hover);
2120        let old_chain = hover_chain_for(Some(new_frame), self.hover_id);
2121        if new_chain == old_chain {
2122            return;
2123        }
2124
2125        dispatch_hover_change_bubbled(
2126            Some(new_frame),
2127            &self.hover_leave,
2128            &mut self.hover_id,
2129            &mut self.hover_ancestors,
2130            new_hover,
2131            pos,
2132            self.modifiers,
2133        );
2134        request_frame();
2135    }
2136
2137    fn reset_pointer_state(&mut self) {
2138        set_touch_gesture_active(false);
2139        self.capture_id = None;
2140        self.hit_path = None;
2141        self.mouse_targets = None;
2142        self.touch_paths.clear();
2143        self.touch_targets.clear();
2144        self.touch_positions.clear();
2145        self.touch_presses.clear();
2146        self.touch_move_consumers.clear();
2147        self.dnd_capture = None;
2148        self.touch_primary = None;
2149        self.suppressed_touch_clicks.clear();
2150        self.pressed_ids.clear();
2151        self.pending_click = None;
2152        self.pending_focus_on_click = None;
2153        self.last_down = None;
2154        self.press_origin = None;
2155        self.double_candidate = None;
2156        self.key_pressed.clear();
2157        self.key_long_press.clear();
2158        self.key_pressed_active = None;
2159        self.last_up = None;
2160        self.last_down = None;
2161        self.double_candidate = None;
2162        self.suppress_next_click = false;
2163    }
2164
2165    fn flush_pending_click(&mut self) {
2166        let Some((id, t0, cb)) = self.pending_click.take() else {
2167            return;
2168        };
2169        if t0.elapsed().as_millis() >= DOUBLE_CLICK_MS {
2170            cb();
2171            request_frame();
2172        } else {
2173            self.pending_click = Some((id, t0, cb));
2174        }
2175    }
2176
2177    fn poll_long_press(&mut self) {
2178        let Some((lid, t0, _, _)) = self.long_press else {
2179            return;
2180        };
2181        if t0.elapsed().as_millis() < LONG_PRESS_MS {
2182            return;
2183        }
2184        let Some(f) = self.frame_cache.clone() else {
2185            return;
2186        };
2187        // Still captured and within the element bounds? (Compose cancels the
2188        // long press when the pointer leaves the element.)
2189        let captured = self
2190            .long_press_touch
2191            .and_then(|tid| self.touch_presses.get(&tid).map(|state| state.capture_id))
2192            .or(self.capture_id);
2193        if captured != Some(lid) {
2194            self.long_press = None;
2195            self.long_press_touch = None;
2196            return;
2197        }
2198        let (mx, my) = self.mouse_pos_px;
2199        let in_bounds = f
2200            .hit_regions
2201            .iter()
2202            .find(|h| h.id == lid)
2203            .is_some_and(|h| repose_ui::hit_region_contains(h, Vec2 { x: mx, y: my }));
2204        if !in_bounds {
2205            self.long_press = None;
2206            return;
2207        }
2208        if let Some(hit) = f.hit_regions.iter().find(|h| h.id == lid && !h.disabled)
2209            && let Some(cb) = &hit.on_long_click
2210        {
2211            self.long_press = None;
2212            self.suppress_next_click = true;
2213            self.pending_click = None;
2214            self.last_up = None;
2215            cb();
2216            request_frame();
2217        } else {
2218            self.long_press = None;
2219        }
2220    }
2221
2222    /// Holding Space/Enter past LONG_PRESS_MS fires long-click. The following KeyUp must not fire onClick.
2223    fn poll_key_long_press(&mut self) {
2224        let Some(f) = self.frame_cache.clone() else {
2225            return;
2226        };
2227        let expired: Vec<Key> = self
2228            .key_long_press
2229            .iter()
2230            .filter(|(_, (_, t0, fired))| !*fired && t0.elapsed().as_millis() >= LONG_PRESS_MS)
2231            .map(|(key, _)| key.clone())
2232            .collect();
2233        for key in expired {
2234            let Some((kid, _, fired)) = self.key_long_press.get(&key).copied() else {
2235                continue;
2236            };
2237            if fired {
2238                continue;
2239            }
2240            if let Some(hit) = f.hit_regions.iter().find(|h| h.id == kid && !h.disabled)
2241                && let Some(cb) = &hit.on_long_click
2242            {
2243                cb();
2244            }
2245            if let Some(entry) = self.key_long_press.get_mut(&key) {
2246                entry.2 = true;
2247            }
2248            request_frame();
2249        }
2250    }
2251
2252    /// Process a scroll event. Returns true if consumed.
2253    pub fn handle_scroll(&mut self, delta: Vec2) -> bool {
2254        let Some(f) = &self.frame_cache else {
2255            return false;
2256        };
2257
2258        let now = web_time::Instant::now();
2259        if let Some(last) = self.last_scroll_at
2260            && now.duration_since(last).as_millis() > 250
2261        {
2262            self.scroll_capture_id = None;
2263        }
2264        self.last_scroll_at = Some(now);
2265
2266        let pos = Vec2 {
2267            x: self.mouse_pos_px.0,
2268            y: self.mouse_pos_px.1,
2269        };
2270        let (consumed, cap) = dispatch_scroll(
2271            f,
2272            pos,
2273            delta,
2274            self.scroll_capture_id,
2275            repose_core::input::ScrollSource::Wheel,
2276        );
2277        self.scroll_capture_id = cap;
2278        if consumed {
2279            request_frame();
2280        }
2281        consumed
2282    }
2283
2284    fn resolve_shortcut_action(
2285        &self,
2286        chord: &repose_core::shortcuts::KeyChord,
2287    ) -> Option<repose_core::shortcuts::Action> {
2288        self.shortcuts.resolve_action(chord)
2289    }
2290
2291    fn handle_shortcut_action(&self, action: repose_core::shortcuts::Action) -> bool {
2292        self.shortcuts.handle(action)
2293    }
2294
2295    /// Process a keyboard key event. Returns true if consumed.
2296    pub fn handle_key(&mut self, event: &KeyEvent) -> bool {
2297        match event.event_type {
2298            KeyEventType::Down => {
2299                self.down_keys.insert(event.key.clone());
2300            }
2301            KeyEventType::Up => {
2302                if !self.down_keys.remove(&event.key) {
2303                    return false;
2304                }
2305            }
2306            KeyEventType::Unknown => {}
2307        }
2308        let _event_scope = crate::lifecycle::enter_dispatchers(self.event_dispatchers());
2309        let shortcut_state = self.shortcuts.clone();
2310        repose_core::shortcuts::with_runtime_state(&shortcut_state, || self.handle_key_inner(event))
2311    }
2312
2313    fn handle_key_inner(&mut self, event: &KeyEvent) -> bool {
2314        let _dnd_guard = self.dnd_context.enter();
2315        if event.event_type == KeyEventType::Down {
2316            let _ = repose_core::request_input_mode(repose_core::InputMode::Keyboard);
2317        }
2318
2319        let Some(frame) = self.frame_cache.clone() else {
2320            if event.event_type == KeyEventType::Down
2321                && !event.is_repeat
2322                && let Some(action) = self.resolve_shortcut_action(
2323                    &repose_core::shortcuts::KeyChord::new(event.key.clone(), event.modifiers),
2324                )
2325            {
2326                return self.dispatch_action(action);
2327            }
2328            return false;
2329        };
2330        let f = &frame;
2331
2332        if event.event_type == KeyEventType::Down && !event.is_repeat && event.key == Key::Escape {
2333            self.cancel_keyboard_press();
2334            if self.cancel_active_dnd() {
2335                request_frame();
2336                return true;
2337            }
2338        }
2339
2340        if event.event_type == KeyEventType::Down && !event.is_repeat {
2341            let is_back = event.key == Key::Escape
2342                || self
2343                    .resolve_shortcut_action(&repose_core::shortcuts::KeyChord::new(
2344                        event.key.clone(),
2345                        event.modifiers,
2346                    ))
2347                    .is_some_and(|action| matches!(action, repose_core::shortcuts::Action::Back));
2348            if is_back && self.overlay.handle_back() {
2349                request_frame();
2350                return true;
2351            }
2352        }
2353
2354        if self.dispatch_key_event(f, event) {
2355            request_frame();
2356            return true;
2357        }
2358
2359        // Action dispatch (shortcuts like Ctrl+C, Tab, etc.)
2360        if event.event_type == KeyEventType::Down
2361            && !event.is_repeat
2362            && let Some(action) = self.resolve_shortcut_action(
2363                &repose_core::shortcuts::KeyChord::new(event.key.clone(), event.modifiers),
2364            )
2365        {
2366            // `dispatch_action` covers focus navigation internally.
2367            if self.dispatch_action(action.clone()) {
2368                return true;
2369            }
2370        }
2371
2372        // Keyboard activation (Space/Enter on focused non-textfield)
2373        if let Some(fid) = self.sched.focused {
2374            let is_tf = f
2375                .semantics_nodes
2376                .iter()
2377                .any(|n| n.id == fid && n.role == repose_core::semantics::Role::TextField);
2378            if !is_tf {
2379                if event.event_type == KeyEventType::Down && !event.is_repeat {
2380                    if event.key == Key::Space
2381                        || event.key == Key::Enter
2382                        || event.key == Key::NumpadEnter
2383                    {
2384                        let Some(hit) = f.hit_regions.iter().find(|h| h.id == fid) else {
2385                            return false;
2386                        };
2387                        if hit.disabled {
2388                            return false;
2389                        }
2390                        if hit.on_click.is_none()
2391                            && hit.on_long_click.is_none()
2392                            && hit.on_double_click.is_none()
2393                        {
2394                            return false; // don't steal keys from non-clickable focusables
2395                        }
2396                        self.cancel_key_press(&event.key);
2397                        self.pressed_ids.insert(fid);
2398                        self.key_pressed.insert(event.key.clone(), fid);
2399                        self.sync_key_pressed_mirror();
2400                        if hit.on_long_click.is_some() {
2401                            self.key_long_press
2402                                .insert(event.key.clone(), (fid, web_time::Instant::now(), false));
2403                        } else {
2404                            self.key_long_press.remove(&event.key);
2405                        }
2406
2407                        if let Some(hit) = f.hit_regions.iter().find(|h| h.id == fid)
2408                            && let Some(src) = &hit.interaction_source
2409                        {
2410                            let local = Vec2 {
2411                                x: hit.rect.w * 0.5,
2412                                y: hit.rect.h * 0.5,
2413                            };
2414                            src.to_mutable().emit(Interaction::new_press(local));
2415                        }
2416
2417                        request_frame();
2418                        return true;
2419                    }
2420                } else if event.event_type == KeyEventType::Up
2421                    && let Some(active_id) = self.key_pressed.remove(&event.key)
2422                {
2423                    self.pressed_ids.remove(&active_id);
2424                    self.sync_key_pressed_mirror();
2425
2426                    let long_fired = self
2427                        .key_long_press
2428                        .remove(&event.key)
2429                        .map(|(_, _, fired)| fired)
2430                        .unwrap_or(false);
2431
2432                    if let Some(hit) = f
2433                        .hit_regions
2434                        .iter()
2435                        .find(|h| h.id == active_id && !h.disabled)
2436                    {
2437                        if let Some(src) = &hit.interaction_source {
2438                            let pid = src.collect_last_press_id().unwrap_or(0);
2439                            src.to_mutable().emit(Interaction::Release(pid));
2440                        }
2441                        if !long_fired && let Some(cb) = &hit.on_click {
2442                            cb();
2443                        }
2444                    }
2445                    request_frame();
2446                    return true;
2447                }
2448            }
2449        }
2450
2451        // Enter submission for focused TextField
2452        if event.event_type == KeyEventType::Down
2453            && !event.is_repeat
2454            && event.key == Key::Enter
2455            && let Some(fid) = self.sched.focused
2456            && let Some(hit) = f.hit_regions.iter().find(|h| h.id == fid)
2457        {
2458            let is_multiline = hit.tf_multiline;
2459            let should_submit = if is_multiline {
2460                self.modifiers.ctrl || self.modifiers.meta
2461            } else {
2462                true
2463            };
2464            if should_submit {
2465                let key = tf_key_of(f, fid);
2466                if let Some(state_rc) = self.textfield_states.get(&key) {
2467                    let text = state_rc.borrow().text.clone();
2468                    let action = match hit.ime_action {
2469                        repose_core::text::ImeAction::Unspecified => {
2470                            repose_core::text::ImeAction::Done
2471                        }
2472                        action => action,
2473                    };
2474                    let advance: Cell<Option<repose_core::shortcuts::Action>> = Cell::new(None);
2475                    repose_ui::textfield::dispatch_textfield_keyboard_action(hit, action, &|| {
2476                        match action {
2477                            repose_core::text::ImeAction::Next => {
2478                                advance.set(Some(repose_core::shortcuts::Action::FocusNext));
2479                            }
2480                            repose_core::text::ImeAction::Previous => {
2481                                advance.set(Some(repose_core::shortcuts::Action::FocusPrevious));
2482                            }
2483                            _ => {
2484                                if let Some(on_submit) = &hit.on_text_submit {
2485                                    on_submit(text.clone());
2486                                }
2487                            }
2488                        }
2489                    });
2490                    if let Some(step) = advance.take() {
2491                        self.dispatch_action(step);
2492                    }
2493                    request_frame();
2494                    return true;
2495                }
2496            } else {
2497                // Multiline plain Enter: insert newline
2498                let key = tf_key_of(f, fid);
2499                if !is_tf_editable(f, fid) {
2500                    return true;
2501                }
2502                if let Some(state_rc) = self.textfield_states.get(&key) {
2503                    let mut edited = state_rc.borrow().clone();
2504                    repose_ui::textfield::insert_text_with_input_transformation(
2505                        hit,
2506                        &mut edited,
2507                        "\n",
2508                        false,
2509                    );
2510                    tf_ensure_caret_visible_for_hit(hit, &mut edited);
2511                    let new_text = edited.text.clone();
2512                    *state_rc.borrow_mut() = edited;
2513                    notify_text_change(f, fid, new_text);
2514                    request_frame();
2515                    return true;
2516                }
2517            }
2518        }
2519
2520        // TextField navigation / edit keys
2521        if event.event_type == KeyEventType::Down
2522            && let Some(fid) = self.sched.focused
2523            && self.handle_text_navigation_key(f, fid, &event.key)
2524        {
2525            return true;
2526        }
2527
2528        if event.event_type == KeyEventType::Down {
2529            // Plain text input (non-IME)
2530            if !self.ime_preedit
2531                && !self.modifiers.ctrl
2532                && !self.modifiers.alt
2533                && !self.modifiers.meta
2534                && let Key::Character(c) = event.key
2535                && !c.is_control()
2536                && c != '\n'
2537                && c != '\r'
2538                && let Some(fid) = self.sched.focused
2539            {
2540                let key = tf_key_of(f, fid);
2541                if !is_tf_editable(f, fid) {
2542                    return true;
2543                }
2544                if let Some(state_rc) = self.textfield_states.get(&key) {
2545                    let new_text = if let Some(hit) = f.hit_regions.iter().find(|h| h.id == fid) {
2546                        let mut edited = state_rc.borrow().clone();
2547                        repose_ui::textfield::insert_text_with_input_transformation(
2548                            hit,
2549                            &mut edited,
2550                            &c.to_string(),
2551                            false,
2552                        );
2553                        tf_ensure_caret_visible_for_hit(hit, &mut edited);
2554                        let text = edited.text.clone();
2555                        *state_rc.borrow_mut() = edited;
2556                        text
2557                    } else {
2558                        return false;
2559                    };
2560                    notify_text_change(f, fid, new_text);
2561                    request_frame();
2562                    return true;
2563                }
2564            }
2565        }
2566
2567        false
2568    }
2569
2570    fn display_text_for_state(
2571        state: &TextFieldState,
2572    ) -> (String, usize, Option<Box<dyn repose_core::OffsetMapping>>) {
2573        let caret = state.caret_index();
2574        let Some(transformation) = state.visual_transformation.clone() else {
2575            return (state.text.clone(), caret, None);
2576        };
2577        let annotated = repose_core::AnnotatedString::new(state.text.clone(), vec![]);
2578        let transformed = transformation.filter(&annotated);
2579        let display_caret = transformed.offset_mapping.original_to_transformed(caret);
2580        (
2581            transformed.text.text,
2582            display_caret,
2583            Some(transformed.offset_mapping),
2584        )
2585    }
2586
2587    fn handle_text_navigation_key(&mut self, frame: &Frame, id: u64, key: &Key) -> bool {
2588        let Some(hit) = frame.hit_regions.iter().find(|hit| hit.id == id) else {
2589            return false;
2590        };
2591        let state_key = tf_key_of(frame, id);
2592        let Some(state) = self.textfield_states.get(&state_key) else {
2593            return false;
2594        };
2595        let editable = is_tf_editable(frame, id);
2596        let metrics = repose_ui::textfield::textfield_metrics(hit);
2597        let shift = self.modifiers.shift;
2598        let word = self.modifiers.command;
2599        let mut edited = state.borrow().clone();
2600        let (display, display_caret, mapping) = Self::display_text_for_state(&edited);
2601        let mut changed = false;
2602        let consumed = match key {
2603            Key::Backspace => {
2604                changed = editable
2605                    && repose_ui::textfield::delete_backward_with_input_transformation(
2606                        hit,
2607                        &mut edited,
2608                    );
2609                true
2610            }
2611            Key::Delete => {
2612                changed = editable
2613                    && repose_ui::textfield::delete_forward_with_input_transformation(
2614                        hit,
2615                        &mut edited,
2616                    );
2617                true
2618            }
2619            Key::ArrowLeft => {
2620                edited.move_cursor(-1, shift, word);
2621                edited.preferred_x_px = None;
2622                true
2623            }
2624            Key::ArrowRight => {
2625                edited.move_cursor(1, shift, word);
2626                edited.preferred_x_px = None;
2627                true
2628            }
2629            Key::ArrowUp if hit.tf_multiline => {
2630                let (next_display, preferred) =
2631                    repose_ui::textfield::move_caret_vertical_with_metrics(
2632                        &display,
2633                        edited.inner_width.max(1.0),
2634                        display_caret,
2635                        -1,
2636                        edited.preferred_x_px,
2637                        &metrics,
2638                    );
2639                let next = mapping.as_ref().map_or(next_display, |mapping| {
2640                    mapping.transformed_to_original(next_display)
2641                });
2642                set_caret(&mut edited, next, shift);
2643                edited.preferred_x_px = Some(preferred);
2644                true
2645            }
2646            Key::ArrowDown if hit.tf_multiline => {
2647                let (next_display, preferred) =
2648                    repose_ui::textfield::move_caret_vertical_with_metrics(
2649                        &display,
2650                        edited.inner_width.max(1.0),
2651                        display_caret,
2652                        1,
2653                        edited.preferred_x_px,
2654                        &metrics,
2655                    );
2656                let next = mapping.as_ref().map_or(next_display, |mapping| {
2657                    mapping.transformed_to_original(next_display)
2658                });
2659                set_caret(&mut edited, next, shift);
2660                edited.preferred_x_px = Some(preferred);
2661                true
2662            }
2663            Key::Home => {
2664                let next_display = if hit.tf_multiline {
2665                    repose_ui::textfield::line_home_end_with_metrics(
2666                        &display,
2667                        edited.inner_width.max(1.0),
2668                        display_caret,
2669                        false,
2670                        &metrics,
2671                    )
2672                } else {
2673                    0
2674                };
2675                let next = mapping.as_ref().map_or(next_display, |mapping| {
2676                    mapping.transformed_to_original(next_display)
2677                });
2678                set_caret(&mut edited, next, shift);
2679                edited.preferred_x_px = None;
2680                true
2681            }
2682            Key::End => {
2683                let next_display = if hit.tf_multiline {
2684                    repose_ui::textfield::line_home_end_with_metrics(
2685                        &display,
2686                        edited.inner_width.max(1.0),
2687                        display_caret,
2688                        true,
2689                        &metrics,
2690                    )
2691                } else {
2692                    display.len()
2693                };
2694                let next = mapping.as_ref().map_or(next_display, |mapping| {
2695                    mapping.transformed_to_original(next_display)
2696                });
2697                set_caret(&mut edited, next, shift);
2698                edited.preferred_x_px = None;
2699                true
2700            }
2701            _ => false,
2702        };
2703        if !consumed {
2704            return false;
2705        }
2706        tf_ensure_caret_visible_for_hit(hit, &mut edited);
2707        let text = changed.then(|| edited.text.clone());
2708        *state.borrow_mut() = edited;
2709        if let Some(text) = text {
2710            notify_text_change(frame, id, text);
2711        }
2712        request_frame();
2713        true
2714    }
2715
2716    /// Dispatch a key event through the compose hierarchy, mirroring
2717    /// Compose `FocusOwner.dispatchKeyEvent`: resolve the focused key-input
2718    /// node (falling back to the root when unfocused), then run the preview
2719    /// tunnel root -> focused and the bubble focused -> root.
2720    fn dispatch_key_event(&self, f: &Frame, event: &KeyEvent) -> bool {
2721        let chain = key_ancestor_chain(f, self.sched.focused);
2722        let hit_by_id: HashMap<u64, &HitRegion> = f.hit_regions.iter().map(|h| (h.id, h)).collect();
2723
2724        for &id in &chain {
2725            let Some(hit) = hit_by_id.get(&id) else {
2726                continue;
2727            };
2728            if hit.disabled {
2729                continue;
2730            }
2731            if let Some(cb) = &hit.on_preview_key_event
2732                && cb(event.clone())
2733            {
2734                return true;
2735            }
2736        }
2737
2738        for &id in chain.iter().rev() {
2739            let Some(hit) = hit_by_id.get(&id) else {
2740                continue;
2741            };
2742            if hit.disabled {
2743                continue;
2744            }
2745            if let Some(cb) = &hit.on_key_event
2746                && cb(event.clone())
2747            {
2748                return true;
2749            }
2750        }
2751
2752        false
2753    }
2754
2755    /// Dispatch a shortcut action: widget handler first, then built-in
2756    /// textfield editing, then the global shortcut map, then focus navigation.
2757    /// Returns true if the action was consumed.
2758    pub fn dispatch_action(&mut self, action: repose_core::shortcuts::Action) -> bool {
2759        // 1) Widget-level handler
2760        if let Some(f) = &self.frame_cache
2761            && let Some(fid) = self.sched.focused
2762            && let Some(hit) = f.hit_regions.iter().find(|h| h.id == fid)
2763            && let Some(cb) = &hit.on_action
2764            && cb(action.clone())
2765        {
2766            request_frame();
2767            return true;
2768        }
2769
2770        // 1b) Multi-touch gestures missed the focused widget: route to the
2771        // node under the gesture centroid, walking up until consumed.
2772        if let Some(center) = gesture_centroid(&action)
2773            && let Some(f) = &self.frame_cache
2774            && repose_core::runtime::route_action_to_point(&f.hit_regions, &action, center)
2775        {
2776            request_frame();
2777            return true;
2778        }
2779
2780        // 2) Built-in textfield editing (undo/redo/copy/cut/paste/select-all)
2781        if self.apply_text_editing_action(&action) {
2782            return true;
2783        }
2784
2785        // 3) Global shortcut handler
2786        if self.handle_shortcut_action(action.clone()) {
2787            request_frame();
2788            return true;
2789        }
2790
2791        // 4) Focus navigation (Tab / arrows)
2792        if let Some(f) = self.frame_cache.clone()
2793            && let Some(new_id) = repose_core::focus::handle_action(&action, &mut self.sched, &f)
2794        {
2795            // End any in-flight keyboard press (e.g. Space held on the old focus).
2796            self.cancel_keyboard_press();
2797            // Lazy-init + reset the caret blink for the newly focused text field.
2798            if let Some(hit) = f.hit_regions.iter().find(|h| h.id == new_id)
2799                && let Some(key) = hit.tf_state_key
2800            {
2801                let st = ensure_tf_state(&mut self.textfield_states, key, hit.tf_value.as_str());
2802                {
2803                    let mut s = st.borrow_mut();
2804                    s.apply_controlled_value(&hit.tf_value);
2805                    s.reset_caret_blink();
2806                }
2807            }
2808            request_frame();
2809            return true;
2810        }
2811
2812        false
2813    }
2814
2815    /// Apply built-in textfield editing actions (Undo/Redo/SelectAll/Copy/
2816    /// Cut/Paste) to the focused text field. Returns true if consumed.
2817    fn apply_text_editing_action(&mut self, action: &repose_core::shortcuts::Action) -> bool {
2818        use repose_core::shortcuts::Action;
2819        let Some(fid) = self.sched.focused else {
2820            return false;
2821        };
2822        let Some(f) = self.frame_cache.clone() else {
2823            return false;
2824        };
2825        if !is_tf_hit(&f, fid) {
2826            return false;
2827        }
2828        let key = tf_key_of(&f, fid);
2829        let Some(state_rc) = self.textfield_states.get(&key).cloned() else {
2830            return false;
2831        };
2832        let hit = f.hit_regions.iter().find(|hit| hit.id == fid);
2833
2834        match action {
2835            Action::Undo => {
2836                if !is_tf_editable(&f, fid) {
2837                    return true;
2838                }
2839                let Some(hit) = hit else {
2840                    return false;
2841                };
2842                let mut edited = state_rc.borrow().clone();
2843                if !repose_ui::textfield::undo_with_input_transformation(hit, &mut edited) {
2844                    return false;
2845                }
2846                tf_ensure_caret_visible_for_hit(hit, &mut edited);
2847                let new_text = edited.text.clone();
2848                *state_rc.borrow_mut() = edited;
2849                notify_text_change(&f, fid, new_text);
2850                request_frame();
2851                true
2852            }
2853            Action::Redo => {
2854                if !is_tf_editable(&f, fid) {
2855                    return true;
2856                }
2857                let Some(hit) = hit else {
2858                    return false;
2859                };
2860                let mut edited = state_rc.borrow().clone();
2861                if !repose_ui::textfield::redo_with_input_transformation(hit, &mut edited) {
2862                    return false;
2863                }
2864                tf_ensure_caret_visible_for_hit(hit, &mut edited);
2865                let new_text = edited.text.clone();
2866                *state_rc.borrow_mut() = edited;
2867                notify_text_change(&f, fid, new_text);
2868                request_frame();
2869                true
2870            }
2871            Action::SelectAll => {
2872                let mut st = state_rc.borrow_mut();
2873                let len = st.text.len();
2874                st.selection = 0..len;
2875                if let Some(hit) = hit {
2876                    tf_ensure_caret_visible_for_hit(hit, &mut st);
2877                }
2878                request_frame();
2879                true
2880            }
2881            Action::Copy => {
2882                if hit.is_some_and(tf_is_sensitive) {
2883                    return true;
2884                }
2885                let st = state_rc.borrow();
2886                let (a, b) = (
2887                    st.selection.start.min(st.selection.end),
2888                    st.selection.start.max(st.selection.end),
2889                );
2890                if a == b {
2891                    return false;
2892                }
2893                let slice = st.text.get(a..b).unwrap_or("").to_string();
2894                drop(st);
2895                if !slice.is_empty() {
2896                    repose_core::clipboard::copy_to_clipboard(&slice);
2897                }
2898                true
2899            }
2900            Action::Cut => {
2901                if hit.is_some_and(tf_is_sensitive) {
2902                    return true;
2903                }
2904                if !is_tf_editable(&f, fid) {
2905                    return true;
2906                }
2907                let Some(hit) = hit else {
2908                    return false;
2909                };
2910                let mut edited = state_rc.borrow().clone();
2911                let Some(slice) =
2912                    repose_ui::textfield::cut_with_input_transformation(hit, &mut edited)
2913                else {
2914                    return false;
2915                };
2916                tf_ensure_caret_visible_for_hit(hit, &mut edited);
2917                let new_text = edited.text.clone();
2918                *state_rc.borrow_mut() = edited;
2919                repose_core::clipboard::copy_to_clipboard(&slice);
2920                notify_text_change(&f, fid, new_text);
2921                request_frame();
2922                true
2923            }
2924            Action::Paste => {
2925                if let Some(txt) = repose_core::clipboard::paste_text() {
2926                    self.paste_into_focused(&txt);
2927                    return true;
2928                }
2929                false
2930            }
2931            _ => false,
2932        }
2933    }
2934
2935    fn cancel_ime_compositions(&mut self) {
2936        let mut changed = None;
2937        for (key, state) in &self.textfield_states {
2938            let mut edited = state.borrow().clone();
2939            if edited.composition.is_none() {
2940                continue;
2941            }
2942            edited.cancel_composition();
2943            *state.borrow_mut() = edited;
2944            changed = Some((*key, self.textfield_states[key].borrow().text.clone()));
2945        }
2946        self.ime_preedit = false;
2947        if let (Some((key, text)), Some(frame)) = (changed, &self.frame_cache)
2948            && let Some(id) = frame
2949                .hit_regions
2950                .iter()
2951                .find(|hit| hit.tf_state_key.unwrap_or(hit.id) == key)
2952                .map(|hit| hit.id)
2953        {
2954            notify_text_change(frame, id, text);
2955        }
2956        request_frame();
2957    }
2958
2959    /// Process an IME event.
2960    pub fn handle_ime(&mut self, event: &ImeEvent) {
2961        if matches!(event, ImeEvent::Cancel) {
2962            self.cancel_ime_compositions();
2963        }
2964        let Some(fid) = self.sched.focused else {
2965            return;
2966        };
2967        let Some(frame) = self.frame_cache.clone() else {
2968            return;
2969        };
2970        if !(is_tf_editable(&frame, fid) && is_textfield_in_frame(&frame, fid)) {
2971            if let Some(hit) = frame.hit_regions.iter().find(|hit| hit.id == fid)
2972                && !hit.disabled
2973                && let Some(cb) = &hit.on_ime
2974                && cb(event.clone())
2975            {
2976                request_frame();
2977            }
2978            return;
2979        }
2980        if matches!(event, ImeEvent::Cancel) {
2981            return;
2982        }
2983        let key = tf_key_of(&frame, fid);
2984        let Some(state) = self.textfield_states.get(&key).cloned() else {
2985            return;
2986        };
2987        let hit = frame.hit_regions.iter().find(|hit| hit.id == fid);
2988        let mut edited = state.borrow().clone();
2989        let changed = match event {
2990            ImeEvent::Start => {
2991                self.ime_preedit = false;
2992                None
2993            }
2994            ImeEvent::Update { text, cursor } => {
2995                edited.set_composition(text.clone(), *cursor);
2996                if let Some(hit) = hit {
2997                    repose_ui::textfield::apply_textfield_input_transformation(hit, &mut edited);
2998                    tf_ensure_caret_visible_for_hit(hit, &mut edited);
2999                }
3000                self.ime_preedit = !text.is_empty();
3001                Some(edited.text.clone())
3002            }
3003            ImeEvent::Commit(text) => {
3004                if let Some(hit) = hit {
3005                    repose_ui::textfield::commit_composition_with_input_transformation(
3006                        hit,
3007                        &mut edited,
3008                        text.clone(),
3009                    );
3010                    tf_ensure_caret_visible_for_hit(hit, &mut edited);
3011                } else {
3012                    edited.commit_composition(text.clone());
3013                }
3014                self.ime_preedit = false;
3015                Some(edited.text.clone())
3016            }
3017            ImeEvent::Cancel => unreachable!(),
3018        };
3019        *state.borrow_mut() = edited;
3020        if let Some(text) = changed {
3021            notify_text_change(&frame, fid, text);
3022        }
3023        request_frame();
3024    }
3025
3026    /// Finish the active composition in every field without deleting text.
3027    /// Used for focus changes and IME disconnects where the confirmed text
3028    /// must be kept; distinct from cancelling, which discards the preedit.
3029    pub fn finish_compositions(&mut self) {
3030        for state_rc in self.textfield_states.values() {
3031            let mut st = state_rc.borrow_mut();
3032            if st.composition.is_some() {
3033                st.finish_composition();
3034            }
3035        }
3036        self.ime_preedit = false;
3037    }
3038
3039    /// Handle focus lost (window unfocused, etc.). Physical-key and
3040    /// mouse-button levels clear too: winit does not deliver key-ups
3041    /// for keys still down across an alt-tab, so without this the
3042    /// polled `held_keys` set sticks until the next press of that key.
3043    pub fn handle_focus_lost(&mut self) {
3044        self.pointer_inside = false;
3045        self.sched.window_focused = false;
3046        self.handle_pointer_cancel();
3047        self.held_keys.clear();
3048        self.held_mouse.clear();
3049        self.sched.held_keys.clear();
3050        self.sched.mouse_primary = false;
3051        self.sched.mouse_secondary = false;
3052        self.sched.mouse_middle = false;
3053        self.sched.touch_points.clear();
3054        self.key_pressed.clear();
3055        self.key_long_press.clear();
3056        self.down_keys.clear();
3057        self.key_pressed_active = None;
3058        self.pressed_ids.clear();
3059        self.pending_click = None;
3060        self.pending_focus_on_click = None;
3061        self.last_down = None;
3062        self.press_origin = None;
3063        self.last_up = None;
3064        self.double_candidate = None;
3065        self.scroll_capture_id = None;
3066        self.last_scroll_at = None;
3067        self.finish_compositions();
3068    }
3069
3070    /// Report one physical key transition (`true` = down). Platform
3071    /// runners call this from the raw `KeyboardInput` event alongside
3072    /// the focus-routed `handle_key_with_text`, so `held` reflects
3073    /// hardware even when no widget has focus.
3074    pub fn set_physical_key(&mut self, name: &str, down: bool) {
3075        if down {
3076            self.held_keys.insert(name.to_string());
3077        } else {
3078            self.held_keys.remove(name);
3079        }
3080    }
3081
3082    /// Snapshot of currently held physical keys (debug names).
3083    pub fn held_physical_keys(&self) -> Vec<String> {
3084        let mut out: Vec<String> = self.held_keys.iter().cloned().collect();
3085        out.sort();
3086        out
3087    }
3088
3089    /// True while the named physical key is down (`KeyCode::KeyW`, ...).
3090    pub fn physical_key_held(&self, name: &str) -> bool {
3091        self.held_keys.contains(name)
3092    }
3093
3094    /// True while the mouse button is down.
3095    pub fn mouse_button_held(&self, button: PointerButton) -> bool {
3096        self.held_mouse.contains(&button)
3097    }
3098
3099    /// Get or create a text field state by its key.
3100    pub fn ensure_textfield_state(&mut self, key: u64) -> Rc<RefCell<TextFieldState>> {
3101        self.textfield_states
3102            .entry(key)
3103            .or_insert_with(|| Rc::new(RefCell::new(TextFieldState::new())))
3104            .clone()
3105    }
3106
3107    pub fn ensure_textfield_state_seeded(
3108        &mut self,
3109        key: u64,
3110        seed: &str,
3111    ) -> Rc<RefCell<TextFieldState>> {
3112        ensure_tf_state(&mut self.textfield_states, key, seed)
3113    }
3114
3115    /// Look up the persistent state key for a visual hit-region id.
3116    pub fn tf_key_of(&self, visual_id: u64) -> u64 {
3117        self.frame_cache
3118            .as_ref()
3119            .map(|f| tf_key_of(f, visual_id))
3120            .unwrap_or(visual_id)
3121    }
3122
3123    /// True if the given id belongs to a TextField.
3124    pub fn is_textfield(&self, id: u64) -> bool {
3125        self.frame_cache
3126            .as_ref()
3127            .map(|f| is_textfield_in_frame(f, id))
3128            .unwrap_or(false)
3129    }
3130
3131    /// True if the given id is an enabled, editable text field.
3132    pub fn is_editable_textfield(&self, id: u64) -> bool {
3133        self.frame_cache
3134            .as_ref()
3135            .map(|f| is_tf_editable(f, id))
3136            .unwrap_or(false)
3137    }
3138
3139    /// True if the given textfield id is multiline.
3140    pub fn is_multiline(&self, id: u64) -> bool {
3141        self.frame_cache
3142            .as_ref()
3143            .map(|f| is_multiline_id(f, id))
3144            .unwrap_or(false)
3145    }
3146
3147    /// Keyboard hints of the currently focused text field, or defaults if none.
3148    /// Returns `(purpose, auto_correct, capitalization)` for the platform runner.
3149    pub fn focused_keyboard_hints(
3150        &self,
3151    ) -> (
3152        repose_core::ImePurposeHint,
3153        bool,
3154        repose_core::KeyboardCapitalization,
3155    ) {
3156        let defaults = || {
3157            (
3158                repose_core::ImePurposeHint::Normal,
3159                true,
3160                repose_core::KeyboardCapitalization::Unspecified,
3161            )
3162        };
3163        let Some(fid) = self.sched.focused else {
3164            return defaults();
3165        };
3166        let Some(f) = &self.frame_cache else {
3167            return defaults();
3168        };
3169        match f.hit_regions.iter().find(|h| h.id == fid) {
3170            Some(hit) => (
3171                hit.keyboard_type.ime_purpose_hint(),
3172                hit.auto_correct.unwrap_or(true),
3173                hit.capitalization,
3174            ),
3175            None => defaults(),
3176        }
3177    }
3178
3179    pub fn focused_ime_action(&self) -> repose_core::text::ImeAction {
3180        self.frame_cache
3181            .as_ref()
3182            .and_then(|frame| {
3183                self.sched
3184                    .focused
3185                    .and_then(|id| frame.hit_regions.iter().find(|hit| hit.id == id))
3186            })
3187            .map(|hit| hit.ime_action)
3188            .unwrap_or_default()
3189    }
3190
3191    /// Delete text the soft keyboard removed around the caret, reported as byte
3192    /// counts before and after the caret. Counts rather than key chords, because
3193    /// deleting a selection is one operation however long the selection is.
3194    pub fn delete_surrounding_into_focused(&mut self, before: usize, after: usize) -> bool {
3195        if self.ime_preedit {
3196            return false;
3197        }
3198        let Some(fid) = self.sched.focused else {
3199            return false;
3200        };
3201        let Some(f) = self.frame_cache.clone() else {
3202            return false;
3203        };
3204        if !(is_textfield_in_frame(&f, fid) && is_tf_editable(&f, fid)) {
3205            return false;
3206        }
3207        let key = tf_key_of(&f, fid);
3208        let Some(state_rc) = self.textfield_states.get(&key).cloned() else {
3209            return false;
3210        };
3211        let Some(hit) = f.hit_regions.iter().find(|hit| hit.id == fid) else {
3212            return false;
3213        };
3214        let mut edited = state_rc.borrow().clone();
3215        let changed = repose_ui::textfield::delete_surrounding_with_input_transformation(
3216            hit,
3217            &mut edited,
3218            before,
3219            after,
3220        );
3221        if changed {
3222            tf_ensure_caret_visible_for_hit(hit, &mut edited);
3223        }
3224        let text = changed.then(|| edited.text.clone());
3225        *state_rc.borrow_mut() = edited;
3226        if let Some(text) = text {
3227            notify_text_change(&f, fid, text);
3228        }
3229        if changed {
3230            request_frame();
3231        }
3232        changed
3233    }
3234
3235    /// Insert arbitrary text into the focused text field (composed keyboard
3236    /// text, clipboard paste, hardware-keyboard fallback, ...).
3237    /// Returns true if text was inserted.
3238    ///
3239    /// Control chars are filtered. Newlines are dropped for single-line fields. Skipped during IME preedit.
3240    pub fn insert_text_into_focused(&mut self, text: &str) -> bool {
3241        if text.is_empty()
3242            || self.ime_preedit
3243            || self.modifiers.ctrl
3244            || self.modifiers.alt
3245            || self.modifiers.meta
3246        {
3247            return false;
3248        }
3249        let Some(fid) = self.sched.focused else {
3250            return false;
3251        };
3252        let Some(f) = self.frame_cache.clone() else {
3253            return false;
3254        };
3255        if !is_textfield_in_frame(&f, fid) {
3256            return false;
3257        }
3258        if !is_tf_editable(&f, fid) {
3259            return false;
3260        }
3261        let key = tf_key_of(&f, fid);
3262        let Some(state_rc) = self.textfield_states.get(&key).cloned() else {
3263            return false;
3264        };
3265        let multiline = is_multiline_id(&f, fid);
3266        let filtered: String = text
3267            .chars()
3268            .filter(|c| {
3269                // Keep newlines for multiline fields; otherwise drop control
3270                // chars and CR (\n is a control char, so it needs an explicit
3271                // exception or it never survives for multiline fields).
3272                (*c == '\n' && multiline) || (!c.is_control() && *c != '\r')
3273            })
3274            .collect();
3275        if filtered.is_empty() {
3276            return false;
3277        }
3278        let new_text = if let Some(hit) = f.hit_regions.iter().find(|hit| hit.id == fid) {
3279            let mut edited = state_rc.borrow().clone();
3280            repose_ui::textfield::insert_text_with_input_transformation(
3281                hit,
3282                &mut edited,
3283                &filtered,
3284                false,
3285            );
3286            tf_ensure_caret_visible_for_hit(hit, &mut edited);
3287            let text = edited.text.clone();
3288            *state_rc.borrow_mut() = edited;
3289            text
3290        } else {
3291            return false;
3292        };
3293        notify_text_change(&f, fid, new_text);
3294        request_frame();
3295        true
3296    }
3297
3298    /// Insert plain text into the focused textfield (winit `key_event.text`,
3299    /// Android soft-keyboard text, web paste). Alias for
3300    /// [`Self::insert_text_into_focused`].
3301    pub fn insert_text(&mut self, text: &str) -> bool {
3302        self.insert_text_into_focused(text)
3303    }
3304
3305    /// Insert text into a focused text field (used for paste). Uses an atomic
3306    /// (non-mergeable) edit so Ctrl+V doesn't merge with adjacent typing.
3307    pub fn paste_into_focused(&mut self, text: &str) {
3308        let Some(fid) = self.sched.focused else {
3309            return;
3310        };
3311        let Some(f) = &self.frame_cache.clone() else {
3312            return;
3313        };
3314        if !is_tf_editable(f, fid) {
3315            return;
3316        }
3317        let key = tf_key_of(f, fid);
3318        let Some(state_rc) = self.textfield_states.get(&key) else {
3319            return;
3320        };
3321        let Some(hit) = f.hit_regions.iter().find(|hit| hit.id == fid) else {
3322            return;
3323        };
3324        let filtered: String = text
3325            .chars()
3326            .filter(|c| (*c == '\n' && hit.tf_multiline) || (!c.is_control() && *c != '\r'))
3327            .collect();
3328        if filtered.is_empty() {
3329            return;
3330        }
3331        let new_text = {
3332            let mut edited = state_rc.borrow().clone();
3333            repose_ui::textfield::insert_text_with_input_transformation(
3334                hit,
3335                &mut edited,
3336                &filtered,
3337                true,
3338            );
3339            tf_ensure_caret_visible_for_hit(hit, &mut edited);
3340            let text = edited.text.clone();
3341            *state_rc.borrow_mut() = edited;
3342            text
3343        };
3344        notify_text_change(f, fid, new_text);
3345        request_frame();
3346    }
3347
3348    /// Process a gamepad event: mirror connection/button/axis state into
3349    /// [`ReposeRuntime::gamepads`]. Sticks, shoulders and face extras stay raw
3350    /// gameplay input for the game to read from [`ReposeRuntime::gamepads`].
3351    ///
3352    /// Returns `true` when the event drove UI navigation.
3353    pub fn handle_gamepad(&mut self, event: &GamepadEvent) -> bool {
3354        match event {
3355            GamepadEvent::Connected {
3356                id,
3357                name,
3358                vendor_id,
3359                product_id,
3360            } => {
3361                self.gamepads.insert(
3362                    id.0,
3363                    GamepadPad {
3364                        id: id.0,
3365                        name: name.clone(),
3366                        vendor_id: *vendor_id,
3367                        product_id: *product_id,
3368                        ..GamepadPad::default()
3369                    },
3370                );
3371                request_frame();
3372                false
3373            }
3374            GamepadEvent::Disconnected { id } => {
3375                self.gamepads.remove(&id.0);
3376                self.sensors.retain(|(pad, _), _| *pad != id.0);
3377                request_frame();
3378                false
3379            }
3380            GamepadEvent::Button {
3381                id,
3382                button,
3383                pressed,
3384            } => {
3385                if let Some(pad) = self.gamepads.get_mut(&id.0) {
3386                    if *pressed {
3387                        pad.pressed.insert(*button);
3388                    } else {
3389                        pad.pressed.remove(button);
3390                    }
3391                }
3392                if *pressed {
3393                    let _ = repose_core::request_input_mode(repose_core::InputMode::Keyboard);
3394                }
3395                let key = match button {
3396                    GamepadButton::South => Key::Space,
3397                    GamepadButton::East => Key::Escape,
3398                    GamepadButton::Start => Key::Enter,
3399                    GamepadButton::DPadUp => Key::ArrowUp,
3400                    GamepadButton::DPadDown => Key::ArrowDown,
3401                    GamepadButton::DPadLeft => Key::ArrowLeft,
3402                    GamepadButton::DPadRight => Key::ArrowRight,
3403                    _ => return false,
3404                };
3405                let synthetic = KeyEvent {
3406                    key,
3407                    modifiers: self.modifiers,
3408                    is_repeat: false,
3409                    event_type: if *pressed {
3410                        KeyEventType::Down
3411                    } else {
3412                        KeyEventType::Up
3413                    },
3414                    utf16_code_point: 0,
3415                    physical: None,
3416                };
3417                self.handle_key(&synthetic)
3418            }
3419            GamepadEvent::Axis { id, axis, value } => {
3420                if let Some(pad) = self.gamepads.get_mut(&id.0) {
3421                    pad.axes.insert(*axis, *value);
3422                }
3423                false
3424            }
3425        }
3426    }
3427
3428    /// Queue a dual-motor rumble for `id` (SDL-style: low = strong motor,
3429    /// high = weak motor, 0.0..=1.0, `duration_ms`). The platform runner
3430    /// drains the queue each frame into `GamepadBackend::set_rumble`.
3431    /// A `duration_ms` of 0 stops. No-op when the pad is unknown.
3432    pub fn request_rumble(
3433        &mut self,
3434        id: repose_core::input::GamepadId,
3435        low_freq: f32,
3436        high_freq: f32,
3437        duration_ms: u32,
3438    ) {
3439        self.pending_rumble.push((
3440            id.0,
3441            low_freq.clamp(0.0, 1.0),
3442            high_freq.clamp(0.0, 1.0),
3443            duration_ms,
3444        ));
3445    }
3446
3447    /// Queue a rumble stop for `id`.
3448    pub fn stop_rumble(&mut self, id: repose_core::input::GamepadId) {
3449        self.pending_rumble.push((id.0, 0.0, 0.0, 0));
3450    }
3451
3452    /// Drain queued rumble requests (platform runners call this after `poll`).
3453    /// [`repose_core::rumble`] entries broadcast to every connected pad.
3454    pub fn take_rumble_requests(&mut self) -> Vec<(u32, f32, f32, u32)> {
3455        let mut requests = std::mem::take(&mut self.pending_rumble);
3456        let global = repose_core::rumble::take();
3457        if !global.is_empty() {
3458            let pads: Vec<u32> = self.gamepads.keys().copied().collect();
3459            for (low, high, duration_ms) in global {
3460                for &id in &pads {
3461                    requests.push((id, low, high, duration_ms));
3462                }
3463            }
3464        }
3465        requests
3466    }
3467
3468    /// Record a motion-sensor reading for `id` (platform runners call this
3469    /// once per polled sample). A frame is requested only once the reading
3470    /// moves past its deadband, compared against the reading that last asked
3471    /// for one: resting noise then cannot pin the app at display rate, while
3472    /// slow drift keeps accumulating until it counts as motion.
3473    pub fn handle_sensor_sample(&mut self, id: GamepadId, sample: SensorSample) {
3474        let key = (id.0, sample.kind);
3475        let deadband = match sample.kind {
3476            SensorKind::Gyroscope => SENSOR_GYRO_DEADBAND,
3477            SensorKind::Accelerometer => SENSOR_ACCEL_DEADBAND,
3478        };
3479        let moved = self.sensors.get(&key).is_none_or(|stored| {
3480            sample
3481                .data
3482                .iter()
3483                .zip(stored)
3484                .any(|(now, was)| (now - was).abs() > deadband)
3485        });
3486        if moved {
3487            self.sensors.insert(key, sample.data);
3488            request_frame();
3489        }
3490    }
3491
3492    /// Reading for `id`'s `kind`, or `None` while the pad has never reported
3493    /// it. Gyroscope values are degrees per second, accelerometer values g,
3494    /// both in the device frame. A reading holds until the sensor moves past
3495    /// its deadband, so a resting pad reports a stable value instead of noise.
3496    pub fn gamepad_sensor(&self, id: GamepadId, kind: SensorKind) -> Option<[f32; 3]> {
3497        self.sensors.get(&(id.0, kind)).copied()
3498    }
3499
3500    /// Which sensors `id` has reported, in gyroscope-then-accelerometer order.
3501    pub fn gamepad_sensor_kinds(&self, id: GamepadId) -> Vec<SensorKind> {
3502        [SensorKind::Gyroscope, SensorKind::Accelerometer]
3503            .into_iter()
3504            .filter(|kind| self.sensors.contains_key(&(id.0, *kind)))
3505            .collect()
3506    }
3507
3508    /// Vendor and product ids of a connected pad, `None` while it is not
3509    /// connected. Both `0` where the platform reports no ids.
3510    pub fn gamepad_vendor_product(&self, id: GamepadId) -> Option<(u16, u16)> {
3511        self.gamepads
3512            .get(&id.0)
3513            .map(|pad| (pad.vendor_id, pad.product_id))
3514    }
3515
3516    /// Resolve a sensor driver's device name to a connected pad. Sensor nodes
3517    /// are separate from the pad node, so they are matched by name: exact
3518    /// first, then case- and punctuation-insensitively, since drivers append
3519    /// interface suffixes ("Wireless Controller (Vendor: 054c)"). Ambiguous
3520    /// names resolve to nothing rather than picking a pad at random.
3521    pub fn gamepad_id_by_sensor_device(&self, device: &str) -> Option<GamepadId> {
3522        let exact: Vec<u32> = self
3523            .gamepads
3524            .iter()
3525            .filter(|(_, pad)| pad.name == device)
3526            .map(|(id, _)| *id)
3527            .collect();
3528        if exact.len() == 1 {
3529            return Some(GamepadId(exact[0]));
3530        }
3531        if !exact.is_empty() {
3532            return None;
3533        }
3534        let needle = repose_core::input::normalize_device_name(device);
3535        let matches: Vec<u32> = self
3536            .gamepads
3537            .iter()
3538            .filter(|(_, pad)| repose_core::input::normalize_device_name(&pad.name) == needle)
3539            .map(|(id, _)| *id)
3540            .collect();
3541        if matches.len() == 1 {
3542            Some(GamepadId(matches[0]))
3543        } else {
3544            None
3545        }
3546    }
3547
3548    /// Process a key event with an optional host-composed `text` payload
3549    /// (winit `key_event.text`, Android soft-keyboard text, ...).
3550    ///
3551    /// The key event is dispatched first; printable text is inserted only
3552    /// when no handler consumed it.
3553    pub fn handle_key_with_text(&mut self, event: &KeyEvent, composed_text: Option<&str>) -> bool {
3554        if event.event_type == KeyEventType::Down {
3555            let _ = repose_core::request_input_mode(repose_core::InputMode::Keyboard);
3556        }
3557        if self.handle_key(event) {
3558            return true;
3559        }
3560        if event.event_type == KeyEventType::Down
3561            && !event.is_repeat
3562            && !self.ime_preedit
3563            && !event.modifiers.ctrl
3564            && !event.modifiers.alt
3565            && !event.modifiers.meta
3566            && let Some(text) = composed_text
3567            && !text.chars().all(|c| c.is_control())
3568        {
3569            return self.insert_text_into_focused(text);
3570        }
3571        false
3572    }
3573
3574    /// Process a scroll event at an explicit position, honoring a caller-owned
3575    /// scroll capture id (touch gestures initialize the capture themselves).
3576    /// Returns `(consumed, updated_capture_id)`.
3577    pub fn handle_scroll_at(
3578        &mut self,
3579        pos: Vec2,
3580        delta: Vec2,
3581        scroll_capture: Option<u64>,
3582    ) -> (bool, Option<u64>) {
3583        let Some(f) = &self.frame_cache else {
3584            return (false, scroll_capture);
3585        };
3586        // Only the one-finger drag path calls this; the wheel goes through
3587        // `handle_scroll`. Two-finger pan/pinch never becomes a scroll at all.
3588        let (consumed, cap) = dispatch_scroll(
3589            f,
3590            pos,
3591            delta,
3592            scroll_capture,
3593            repose_core::input::ScrollSource::Touch,
3594        );
3595        if consumed {
3596            request_frame();
3597        }
3598        (consumed, cap)
3599    }
3600
3601    /// Next caret blink edge (`Instant`) for the focused text field, if any.
3602    /// Internal - platform should use `next_wakeup_deadline()` instead.
3603    fn next_caret_blink_deadline(&self) -> Option<web_time::Instant> {
3604        let fid = self.sched.focused?;
3605        let frame = self.frame_cache.as_ref()?;
3606        let hit = frame.hit_regions.iter().find(|h| h.id == fid)?;
3607        let key = hit.tf_state_key?;
3608        self.textfield_states
3609            .get(&key)?
3610            .borrow()
3611            .next_blink_deadline()
3612    }
3613
3614    fn next_gesture_deadline(&self) -> Option<web_time::Instant> {
3615        [
3616            self.pending_click
3617                .as_ref()
3618                .map(|(_, at, _)| *at + web_time::Duration::from_millis(DOUBLE_CLICK_MS as u64)),
3619            self.long_press
3620                .as_ref()
3621                .map(|(_, at, _, _)| *at + web_time::Duration::from_millis(LONG_PRESS_MS as u64)),
3622            self.key_long_press
3623                .values()
3624                .filter(|(_, _, fired)| !*fired)
3625                .map(|(_, at, _)| *at + web_time::Duration::from_millis(LONG_PRESS_MS as u64))
3626                .min(),
3627            repose_ui::scrollbar_repeat::track_repeat_deadline(),
3628            repose_ui::scrollbar_fade::scrollbar_fade_deadline(),
3629        ]
3630        .into_iter()
3631        .flatten()
3632        .min()
3633    }
3634
3635    /// Centralized wakeup helper for platform runners (caret, snackbar, timers, etc.).
3636    /// Debounced entries live on the shared timer queue, so `timer` covers them.
3637    pub fn next_wakeup_deadline(&self) -> Option<web_time::Instant> {
3638        [
3639            self.next_caret_blink_deadline(),
3640            self.next_gesture_deadline(),
3641            repose_ui::overlay::SnackbarController::next_deadline(),
3642            repose_core::timer::next_deadline(),
3643        ]
3644        .into_iter()
3645        .flatten()
3646        .min()
3647    }
3648
3649    /// Whether a scheduled wakeup is due at `now` (deadline <= now).
3650    pub fn is_wakeup_due(&self, now: web_time::Instant) -> bool {
3651        self.next_wakeup_deadline().is_some_and(|d| d <= now)
3652    }
3653
3654    /// Whether a caret blink edge is due at `now` (deadline <= now).
3655    /// Deprecated: use `is_wakeup_due`.
3656    pub fn is_caret_blink_due(&self, now: web_time::Instant) -> bool {
3657        self.is_wakeup_due(now)
3658    }
3659
3660    /// Desktop-style deadline with idle keep-alive fallback.
3661    /// `idle_cap` is the maximum time the host should sleep without a
3662    /// scheduled wakeup (e.g. 1s on desktop to handle tray Deeplinks).
3663    pub fn next_frame_deadline(
3664        &self,
3665        now: web_time::Instant,
3666        idle_cap: web_time::Duration,
3667    ) -> web_time::Instant {
3668        self.next_wakeup_deadline().unwrap_or(now + idle_cap)
3669    }
3670
3671    /// Tick host-facing overlays (snackbar timeouts) and timers (including
3672    /// debounced entries, which live on the shared timer queue).
3673    /// Call once per redraw.
3674    pub fn tick_overlays(&self) {
3675        repose_ui::overlay::SnackbarController::tick_all();
3676        repose_core::timer::poll();
3677    }
3678
3679    /// Get the cursor suggestion (set during pointer-move handling).
3680    pub fn cursor_suggestion(&self) -> Option<CursorIcon> {
3681        self.cursor.clone()
3682    }
3683
3684    /// Take the cursor suggestion (clears it).
3685    pub fn take_cursor_suggestion(&mut self) -> Option<CursorIcon> {
3686        self.cursor.take()
3687    }
3688
3689    /// Ask the runner for borderless fullscreen on or off, as dock and
3690    /// handheld mode switches need. Read back with
3691    /// [`take_fullscreen_request`](Self::take_fullscreen_request).
3692    ///
3693    /// Kept here as well as on the scheduler because the two are the same
3694    /// request: the field lives on [`Scheduler`] so a game holding only a
3695    /// scheduler can ask for the same thing, and these are the shell's own way
3696    /// in to it.
3697    pub fn request_fullscreen(&mut self, fullscreen: bool) {
3698        self.sched.request_fullscreen(fullscreen);
3699    }
3700
3701    /// Whether the window is currently fullscreen, as far as requests go.
3702    pub fn fullscreen(&self) -> Option<bool> {
3703        self.sched.fullscreen_request
3704    }
3705
3706    /// Take the pending fullscreen request (clears it).
3707    pub fn take_fullscreen_request(&mut self) -> Option<bool> {
3708        self.sched.fullscreen_request.take()
3709    }
3710
3711    fn move_cursor_suggestion(&self) -> Option<CursorIcon> {
3712        self.frame_cursor_override
3713            .clone()
3714            .or_else(|| self.cursor.clone())
3715    }
3716}
3717
3718impl Default for ReposeRuntime {
3719    fn default() -> Self {
3720        Self::new()
3721    }
3722}
3723
3724/// Inner compose frame logic (no dependency on repose-platform).
3725pub fn compose_frame_inner<F>(
3726    sched: &mut Scheduler,
3727    root_fn: &mut F,
3728    scale: f32,
3729    size_px_u32: (u32, u32),
3730    hover_id: Option<u64>,
3731    pressed_ids: &HashSet<u64>,
3732    tf_states: &HashMap<u64, Rc<RefCell<TextFieldState>>>,
3733) -> Frame
3734where
3735    F: FnMut(&mut Scheduler) -> View,
3736{
3737    compose_frame_inner_with_ancestors(
3738        sched,
3739        root_fn,
3740        scale,
3741        size_px_u32,
3742        hover_id,
3743        &std::collections::HashSet::new(),
3744        pressed_ids,
3745        tf_states,
3746    )
3747}
3748
3749pub fn compose_frame_inner_with_ancestors<F>(
3750    sched: &mut Scheduler,
3751    root_fn: &mut F,
3752    scale: f32,
3753    size_px_u32: (u32, u32),
3754    hover_id: Option<u64>,
3755    hover_ancestors: &std::collections::HashSet<u64>,
3756    pressed_ids: &HashSet<u64>,
3757    tf_states: &HashMap<u64, Rc<RefCell<TextFieldState>>>,
3758) -> Frame
3759where
3760    F: FnMut(&mut Scheduler) -> View,
3761{
3762    for requested_id in repose_core::runtime::drain_focus_requests() {
3763        if requested_id == repose_core::runtime::CLEAR_FOCUS_MARKER {
3764            sched.focused = None;
3765            continue;
3766        }
3767        sched.focused = Some(requested_id);
3768    }
3769
3770    set_density_default(Density { scale });
3771
3772    let current_focused = sched.focused;
3773
3774    let frame = sched.repose(
3775        move |s: &mut Scheduler| with_density(Density { scale }, || (root_fn)(s)),
3776        {
3777            let hover_ancestors = hover_ancestors.clone();
3778            let pressed_ids = pressed_ids.clone();
3779            move |view, _size| {
3780                let interactions = Interactions {
3781                    hover: hover_id,
3782                    hover_ancestors: hover_ancestors.clone(),
3783                    pressed: pressed_ids.clone(),
3784                };
3785                with_density(Density { scale }, || {
3786                    layout_and_paint(view, size_px_u32, tf_states, &interactions, current_focused)
3787                })
3788            }
3789        },
3790    );
3791
3792    for requested_id in repose_core::runtime::drain_focus_requests() {
3793        if requested_id == repose_core::runtime::CLEAR_FOCUS_MARKER {
3794            sched.focused = None;
3795        } else if frame.focus_chain.contains(&requested_id) {
3796            sched.focused = Some(requested_id);
3797        }
3798    }
3799
3800    if repose_core::runtime::focus_capture().is_some() {
3801        sched.focused = repose_core::runtime::focus_capture();
3802    } else if let Some(fid) = sched.focused
3803        && !frame.focus_chain.contains(&fid)
3804    {
3805        // A keyed subtree (e.g. a Dialog's measure/probe regenerated when the
3806        // IME inset changes) can reassign layout view ids. If a FocusRequester
3807        // that was pointing at the now-stale focused id has moved to a new id
3808        // that is in this frame's chain, follow it instead of dropping focus.
3809        // Dropping focus here hides the soft keyboard mid-edit on Android.
3810        let remapped = repose_core::runtime::take_focus_target_remaps()
3811            .into_iter()
3812            .find(|(old, new)| *old == fid && frame.focus_chain.contains(new))
3813            .map(|(_, new)| new);
3814        sched.focused = remapped;
3815    } else {
3816        // No stale focus, but still drain any remaps recorded this frame so
3817        // they cannot leak into a later frame's reconciliation.
3818        let _ = repose_core::runtime::take_focus_target_remaps();
3819    }
3820
3821    frame
3822}
3823
3824/// Compose `FocusOwner.dispatchKeyEvent` chain: focused node up through its
3825/// hit-region ancestors, root first. Empty when nothing is focused.
3826fn key_ancestor_chain(f: &Frame, focused: Option<u64>) -> Vec<u64> {
3827    let parent_of: HashMap<u64, Option<u64>> =
3828        f.hit_regions.iter().map(|h| (h.id, h.parent)).collect();
3829    let Some(mut cur) = focused.filter(|id| parent_of.contains_key(id)) else {
3830        return Vec::new();
3831    };
3832    let mut chain = vec![cur];
3833    while let Some(parent) = parent_of.get(&cur).copied().flatten() {
3834        if chain.contains(&parent) {
3835            break;
3836        }
3837        chain.push(parent);
3838        cur = parent;
3839    }
3840    chain.reverse();
3841    chain
3842}
3843
3844fn hover_chain_for(frame: Option<&Frame>, hover: Option<u64>) -> std::collections::HashSet<u64> {
3845    let Some(f) = frame else {
3846        return std::collections::HashSet::new();
3847    };
3848    let Some(mut cur) = hover else {
3849        return std::collections::HashSet::new();
3850    };
3851    let map: std::collections::HashMap<u64, Option<u64>> =
3852        f.hit_regions.iter().map(|h| (h.id, h.parent)).collect();
3853    let mut set = std::collections::HashSet::new();
3854    loop {
3855        set.insert(cur);
3856        if let Some(Some(parent)) = map.get(&cur).copied() {
3857            cur = parent;
3858        } else {
3859            break;
3860        }
3861    }
3862    set
3863}
3864
3865fn dispatch_hover_change_bubbled(
3866    frame: Option<&Frame>,
3867    leave_map: &HashMap<u64, repose_ui::HitRegionSnapshot>,
3868    hover_id: &mut Option<u64>,
3869    hover_ancestors: &mut std::collections::HashSet<u64>,
3870    new_hover: Option<u64>,
3871    pos: Vec2,
3872    modifiers: Modifiers,
3873) {
3874    let old_hover = *hover_id;
3875    let mut old_chain = hover_ancestors.clone();
3876    if let Some(id) = old_hover {
3877        old_chain.insert(id);
3878    }
3879    let new_chain = hover_chain_for(frame, new_hover);
3880    if old_chain == new_chain {
3881        return;
3882    }
3883    for leave_id in old_chain.difference(&new_chain) {
3884        let current = frame.and_then(|f| f.hit_regions.iter().find(|h| h.id == *leave_id));
3885        if let Some(hit) = current
3886            && let Some(cb) = &hit.on_pointer_leave
3887        {
3888            let mut pe = PointerEvent::new(
3889                PointerId(0),
3890                PointerKind::Mouse,
3891                PointerEventKind::Leave,
3892                pos,
3893                1.0,
3894                modifiers,
3895            );
3896            let (origin, local) = repose_ui::hit_region_pointer_coordinates(hit, pos);
3897            pe.origin = origin;
3898            pe.position = local;
3899            cb(pe);
3900            continue;
3901        }
3902        if let Some(snapshot) = leave_map.get(leave_id)
3903            && let Some(callback) = &snapshot.hit().on_pointer_leave
3904        {
3905            let mut pe = PointerEvent::new(
3906                PointerId(0),
3907                PointerKind::Mouse,
3908                PointerEventKind::Leave,
3909                pos,
3910                1.0,
3911                modifiers,
3912            );
3913            let (origin, local) = snapshot.pointer_coordinates(pos);
3914            pe.origin = origin;
3915            pe.position = local;
3916            callback(pe);
3917        }
3918    }
3919    for enter_id in new_chain.difference(&old_chain) {
3920        if let Some(f) = frame
3921            && let Some(h) = f.hit_regions.iter().find(|h| h.id == *enter_id)
3922            && let Some(cb) = &h.on_pointer_enter
3923        {
3924            let mut pe = PointerEvent::new(
3925                PointerId(0),
3926                PointerKind::Mouse,
3927                PointerEventKind::Enter,
3928                pos,
3929                1.0,
3930                modifiers,
3931            );
3932            let (origin, local) = repose_ui::hit_region_pointer_coordinates(h, pos);
3933            pe.origin = origin;
3934            pe.position = local;
3935            cb(pe);
3936        }
3937    }
3938    *hover_id = new_hover;
3939    hover_ancestors.clear();
3940    for id in &new_chain {
3941        if Some(*id) != new_hover {
3942            hover_ancestors.insert(*id);
3943        }
3944    }
3945}
3946
3947pub fn is_textfield_in_frame(f: &Frame, id: u64) -> bool {
3948    f.semantics_nodes
3949        .iter()
3950        .any(|n| n.id == id && n.role == repose_core::semantics::Role::TextField)
3951}
3952
3953pub fn is_textfield_in_frame_cache(frame_cache: &Option<Rc<Frame>>, id: u64) -> bool {
3954    if let Some(f) = frame_cache {
3955        is_textfield_in_frame(f, id)
3956    } else {
3957        false
3958    }
3959}
3960
3961pub fn hit_index_by_id(frame: &Frame, id: u64) -> Option<usize> {
3962    frame.hit_regions.iter().position(|h| h.id == id)
3963}
3964
3965fn is_multiline_id(f: &Frame, id: u64) -> bool {
3966    f.hit_regions
3967        .iter()
3968        .find(|h| h.id == id)
3969        .map(|h| h.tf_multiline)
3970        .unwrap_or(false)
3971}
3972
3973/// `enabled=false` rejects edits. `readOnly` also rejects
3974/// edits but keeps selection/focus/copy working.
3975fn tf_can_edit(hit: &HitRegion) -> bool {
3976    hit.tf_enabled && !hit.tf_read_only
3977}
3978
3979/// Movement a sensor must show before the app is asked to redraw, in the
3980/// units [`ReposeRuntime::gamepad_sensor`] reports. Each sits above its
3981/// drivers' resting noise and per-count quantization (gyro 0.5 °/s against
3982/// hid-steam's 0.0625 °/s per count, accel 0.02 g against hid-sony's 0.0088
3983/// g), so a connected but untouched pad lets the app idle.
3984const SENSOR_GYRO_DEADBAND: f32 = 0.5;
3985const SENSOR_ACCEL_DEADBAND: f32 = 0.02;
3986
3987fn tf_is_sensitive(hit: &HitRegion) -> bool {
3988    hit.tf_sensitive
3989        || matches!(
3990            hit.keyboard_type,
3991            repose_core::KeyboardType::Password
3992                | repose_core::KeyboardType::NumberPassword
3993                | repose_core::KeyboardType::DecimalPassword
3994                | repose_core::KeyboardType::NumberPasswordSigned
3995                | repose_core::KeyboardType::DecimalPasswordSigned
3996        )
3997}
3998
3999fn is_tf_editable(f: &Frame, id: u64) -> bool {
4000    f.hit_regions
4001        .iter()
4002        .find(|h| h.id == id)
4003        .is_some_and(tf_can_edit)
4004}
4005
4006fn tf_key_of(frame: &Frame, visual_id: u64) -> u64 {
4007    if let Some(i) = frame.hit_regions.iter().position(|h| h.id == visual_id) {
4008        let hr = &frame.hit_regions[i];
4009        return hr.tf_state_key.unwrap_or(hr.id);
4010    }
4011    visual_id
4012}
4013
4014fn set_caret(state: &mut TextFieldState, position: usize, extend: bool) {
4015    if extend {
4016        state.selection.end = position;
4017    } else {
4018        state.selection = position..position;
4019    }
4020}
4021
4022fn notify_text_change(f: &Frame, id: u64, text: String) {
4023    if let Some(h) = f.hit_regions.iter().find(|h| h.id == id)
4024        && let Some(cb) = &h.on_text_change
4025    {
4026        cb(text);
4027    }
4028}
4029
4030fn tf_ensure_caret_visible_for_hit(hit: &HitRegion, state: &mut TextFieldState) {
4031    let metrics = repose_ui::textfield::textfield_metrics(hit);
4032    tf_ensure_caret_visible_with_metrics(state, hit.tf_multiline, &metrics);
4033}
4034
4035fn tf_ensure_caret_visible_with_metrics(
4036    state: &mut TextFieldState,
4037    is_multiline: bool,
4038    metrics: &repose_ui::textfield::TextFieldMetrics,
4039) {
4040    repose_ui::textfield::ensure_caret_visible_with_metrics(state, is_multiline, metrics);
4041}
4042
4043fn index_for_x_bytes_vt(
4044    state: &TextFieldState,
4045    metrics: &repose_ui::textfield::TextFieldMetrics,
4046    x_px: f32,
4047) -> usize {
4048    if let Some(transformation) = &state.visual_transformation {
4049        let annotated = repose_core::AnnotatedString::new(state.text.clone(), vec![]);
4050        let transformed = transformation.filter(&annotated);
4051        let display = repose_ui::textfield::index_for_x_bytes_with_config(
4052            transformed.text.as_str(),
4053            metrics.font_px,
4054            x_px,
4055            metrics.measure_config(),
4056        );
4057        transformed.offset_mapping.transformed_to_original(display)
4058    } else {
4059        repose_ui::textfield::index_for_x_bytes_with_config(
4060            &state.text,
4061            metrics.font_px,
4062            x_px,
4063            metrics.measure_config(),
4064        )
4065    }
4066}
4067
4068fn index_for_xy_bytes_vt(
4069    state: &TextFieldState,
4070    metrics: &repose_ui::textfield::TextFieldMetrics,
4071    wrap_width: f32,
4072    x_px: f32,
4073    y_px: f32,
4074) -> usize {
4075    if let Some(transformation) = &state.visual_transformation {
4076        let annotated = repose_core::AnnotatedString::new(state.text.clone(), vec![]);
4077        let transformed = transformation.filter(&annotated);
4078        let display = repose_ui::textfield::index_for_xy_bytes_with_metrics(
4079            transformed.text.as_str(),
4080            wrap_width,
4081            x_px,
4082            y_px,
4083            metrics,
4084        );
4085        transformed.offset_mapping.transformed_to_original(display)
4086    } else {
4087        repose_ui::textfield::index_for_xy_bytes_with_metrics(
4088            &state.text,
4089            wrap_width,
4090            x_px,
4091            y_px,
4092            metrics,
4093        )
4094    }
4095}
4096
4097/// Dispatch scroll to scroll consumers. Returns (consumed, optional capture id).
4098fn dispatch_scroll(
4099    frame: &Frame,
4100    pos: Vec2,
4101    delta: Vec2,
4102    scroll_capture: Option<u64>,
4103    source: repose_core::input::ScrollSource,
4104) -> (bool, Option<u64>) {
4105    let mut remaining = delta;
4106    let mut first_consumer: Option<u64> = None;
4107    if let Some(cid) = scroll_capture
4108        && let Some(hit) = frame
4109            .hit_regions
4110            .iter()
4111            .find(|h| h.id == cid && !h.disabled)
4112        && let Some(leftover) = run_scroll_handler(hit, delta, source)
4113    {
4114        if (delta.x - leftover.x).abs() > 0.001 || (delta.y - leftover.y).abs() > 0.001 {
4115            first_consumer = Some(cid);
4116        }
4117        remaining = leftover;
4118        if remaining.x.abs() <= 0.001 && remaining.y.abs() <= 0.001 {
4119            return (true, Some(cid));
4120        }
4121    }
4122
4123    let mut consumed_any = first_consumer.is_some();
4124    for id in repose_ui::hit_test_frame_regions(frame, pos) {
4125        if Some(id) == scroll_capture {
4126            continue;
4127        }
4128        let Some(hit) = frame
4129            .hit_regions
4130            .iter()
4131            .find(|hit| hit.id == id && !hit.disabled)
4132        else {
4133            continue;
4134        };
4135        if remaining.x.abs() <= 0.001 && remaining.y.abs() <= 0.001 {
4136            break;
4137        }
4138        if let Some(leftover) = run_scroll_handler(hit, remaining, source) {
4139            let before = remaining;
4140            if (before.x - leftover.x).abs() > 0.001 || (before.y - leftover.y).abs() > 0.001 {
4141                consumed_any = true;
4142                if first_consumer.is_none() {
4143                    first_consumer = Some(hit.id);
4144                }
4145            }
4146            remaining = leftover;
4147        }
4148    }
4149    if consumed_any {
4150        (true, first_consumer)
4151    } else {
4152        (false, None)
4153    }
4154}
4155
4156/// Walk a target's hit-region ancestors and dispatch the scroll delta each
4157/// scroll container needs to reveal it. The target rect is translated by the
4158/// delta each ancestor actually consumes so higher containers see the updated
4159/// position.
4160fn bring_target_into_view(hits: &[HitRegion], target_id: u64) {
4161    let Some(target) = hits
4162        .iter()
4163        .find(|h| h.id == target_id && !h.disabled && h.visible != Some(false))
4164    else {
4165        return;
4166    };
4167    let mut rect = target.rect;
4168    let mut current = target.parent;
4169    let mut seen = HashSet::new();
4170    while let Some(id) = current {
4171        if !seen.insert(id) {
4172            break;
4173        }
4174        let Some(hit) = hits.iter().find(|h| h.id == id) else {
4175            break;
4176        };
4177        if hit.on_scroll.is_some() || hit.on_scroll_with_source.is_some() {
4178            let delta = repose_core::scroll::scroll_delta_to_reveal(
4179                rect,
4180                hit.rect,
4181                repose_core::scroll::ScrollAxis::Both,
4182            );
4183            if delta.x.abs() > 0.5 || delta.y.abs() > 0.5 {
4184                if let Some(leftover) =
4185                    run_scroll_handler(hit, delta, repose_core::input::ScrollSource::Wheel)
4186                {
4187                    let consumed_x = delta.x - leftover.x;
4188                    let consumed_y = delta.y - leftover.y;
4189                    rect.x -= consumed_x;
4190                    rect.y -= consumed_y;
4191                }
4192            }
4193        }
4194        current = hit.parent;
4195    }
4196}
4197
4198/// Invoke whichever scroll handler a hit region installed, returning the
4199/// unconsumed remainder. `on_scroll_with_source` wins when both are present.
4200fn run_scroll_handler(
4201    hit: &HitRegion,
4202    delta: Vec2,
4203    source: repose_core::input::ScrollSource,
4204) -> Option<Vec2> {
4205    if let Some(cb) = &hit.on_scroll_with_source {
4206        return Some(cb(delta, source));
4207    }
4208    hit.on_scroll.as_ref().map(|cb| cb(delta))
4209}
4210
4211#[cfg(test)]
4212mod scroll_source_tests {
4213    use super::*;
4214    use repose_core::input::ScrollSource;
4215    use std::cell::RefCell;
4216    use std::rc::Rc;
4217
4218    /// A frame with one source-aware region that records every source it sees
4219    /// and swallows the whole delta.
4220    fn recording_frame(id: u64) -> (Frame, Rc<RefCell<Vec<ScrollSource>>>) {
4221        let seen: Rc<RefCell<Vec<ScrollSource>>> = Rc::new(RefCell::new(Vec::new()));
4222        let recorder = seen.clone();
4223        let frame = Frame {
4224            scene: Default::default(),
4225            hit_regions: vec![HitRegion {
4226                id,
4227                rect: repose_core::Rect {
4228                    x: 0.0,
4229                    y: 0.0,
4230                    w: 200.0,
4231                    h: 200.0,
4232                },
4233                on_scroll_with_source: Some(Rc::new(move |_d: Vec2, s: ScrollSource| {
4234                    recorder.borrow_mut().push(s);
4235                    // Consume everything, so dispatch reports the region as hit.
4236                    Vec2 { x: 0.0, y: 0.0 }
4237                })),
4238                ..Default::default()
4239            }],
4240            semantics_nodes: vec![],
4241            focus_chain: vec![id],
4242        };
4243        (frame, seen)
4244    }
4245
4246    #[test]
4247    fn dispatch_passes_the_source_through_to_the_handler() {
4248        let (frame, seen) = recording_frame(1);
4249        let pos = Vec2 { x: 50.0, y: 50.0 };
4250        let delta = Vec2 { x: 0.0, y: 4.0 };
4251
4252        let (consumed, _) = dispatch_scroll(&frame, pos, delta, None, ScrollSource::Wheel);
4253        assert!(consumed, "handler consumed the delta");
4254        let (consumed, _) = dispatch_scroll(&frame, pos, delta, None, ScrollSource::Touch);
4255        assert!(consumed);
4256
4257        assert_eq!(
4258            *seen.borrow(),
4259            vec![ScrollSource::Wheel, ScrollSource::Touch]
4260        );
4261    }
4262
4263    #[test]
4264    fn legacy_on_scroll_still_runs_and_reports_its_leftover() {
4265        let hit = HitRegion {
4266            id: 3,
4267            on_scroll: Some(Rc::new(|d: Vec2| Vec2 { x: 0.0, y: d.y })),
4268            ..Default::default()
4269        };
4270        let leftover = run_scroll_handler(&hit, Vec2 { x: 7.0, y: 5.0 }, ScrollSource::Touch);
4271        assert_eq!(leftover, Some(Vec2 { x: 0.0, y: 5.0 }));
4272    }
4273
4274    #[test]
4275    fn source_aware_handler_takes_precedence_over_legacy() {
4276        let legacy = Rc::new(RefCell::new(0u32));
4277        let aware = Rc::new(RefCell::new(0u32));
4278        let (legacy_cb, aware_cb) = (legacy.clone(), aware.clone());
4279        let hit = HitRegion {
4280            id: 4,
4281            on_scroll: Some(Rc::new(move |d: Vec2| {
4282                *legacy_cb.borrow_mut() += 1;
4283                d
4284            })),
4285            on_scroll_with_source: Some(Rc::new(move |d: Vec2, _s: ScrollSource| {
4286                *aware_cb.borrow_mut() += 1;
4287                d
4288            })),
4289            ..Default::default()
4290        };
4291        run_scroll_handler(&hit, Vec2 { x: 1.0, y: 1.0 }, ScrollSource::Wheel);
4292        assert_eq!(*aware.borrow(), 1, "source-aware handler runs");
4293        assert_eq!(*legacy.borrow(), 0, "legacy handler is not also run");
4294    }
4295
4296    #[test]
4297    fn region_without_any_scroll_handler_is_skipped() {
4298        let hit = HitRegion {
4299            id: 5,
4300            ..Default::default()
4301        };
4302        assert_eq!(
4303            run_scroll_handler(&hit, Vec2 { x: 1.0, y: 1.0 }, ScrollSource::Wheel),
4304            None
4305        );
4306    }
4307}
4308
4309#[cfg(test)]
4310mod ime_tests {
4311    use super::*;
4312    use repose_core::input::ImeEvent;
4313
4314    const TF_ID: u64 = 100;
4315
4316    fn editable_frame(id: u64) -> Frame {
4317        let rect = repose_core::Rect {
4318            x: 0.0,
4319            y: 0.0,
4320            w: 200.0,
4321            h: 30.0,
4322        };
4323        Frame {
4324            scene: Default::default(),
4325            hit_regions: vec![HitRegion {
4326                id,
4327                rect,
4328                focusable: true,
4329                tf_state_key: Some(id),
4330                tf_multiline: false,
4331                tf_enabled: true,
4332                tf_read_only: false,
4333                ..Default::default()
4334            }],
4335            semantics_nodes: vec![repose_core::runtime::SemNode {
4336                id,
4337                role: repose_core::semantics::Role::TextField,
4338                label: Some("Field".into()),
4339                rect,
4340                focused: true,
4341                ..Default::default()
4342            }],
4343            focus_chain: vec![id],
4344        }
4345    }
4346
4347    fn focused_rt() -> ReposeRuntime {
4348        let mut rt = ReposeRuntime::new();
4349        rt.sched.focused = Some(TF_ID);
4350        rt.cache_frame(editable_frame(TF_ID));
4351        let _ = rt.ensure_textfield_state(TF_ID);
4352        rt
4353    }
4354
4355    #[test]
4356    fn preedit_cursor_uses_byte_offsets_for_non_ascii() {
4357        let mut rt = focused_rt();
4358        rt.handle_ime(&ImeEvent::Update {
4359            text: "あb".to_string(),
4360            cursor: Some((3, 3)),
4361        });
4362        let st = rt.textfield_states[&TF_ID].borrow();
4363        assert_eq!(st.text, "あb");
4364        assert_eq!(st.selection, 3..3);
4365    }
4366
4367    #[test]
4368    fn cancel_discards_preedit() {
4369        let mut rt = focused_rt();
4370        rt.handle_ime(&ImeEvent::Update {
4371            text: "あ".to_string(),
4372            cursor: None,
4373        });
4374        assert!(rt.ime_preedit);
4375        rt.handle_ime(&ImeEvent::Cancel);
4376        let st = rt.textfield_states[&TF_ID].borrow();
4377        assert_eq!(st.text, "");
4378        assert!(st.composition.is_none());
4379        assert!(!rt.ime_preedit);
4380    }
4381
4382    #[test]
4383    fn defocus_finish_keeps_text() {
4384        let mut rt = focused_rt();
4385        rt.handle_ime(&ImeEvent::Update {
4386            text: "x".to_string(),
4387            cursor: None,
4388        });
4389        rt.sched.focused = None;
4390        rt.handle_focus_lost();
4391        assert_eq!(rt.textfield_states[&TF_ID].borrow().text, "x");
4392        assert!(!rt.ime_preedit);
4393    }
4394
4395    #[test]
4396    fn focused_game_node_receives_events() {
4397        let mut rt = ReposeRuntime::new();
4398        rt.sched.focused = Some(TF_ID);
4399        let mut frame = editable_frame(TF_ID);
4400        frame.hit_regions[0].tf_state_key = None;
4401        frame.hit_regions[0].tf_enabled = false;
4402        frame.semantics_nodes.clear();
4403        let seen: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
4404        let sink = seen.clone();
4405        frame.hit_regions[0].on_ime = Some(Rc::new(move |event| {
4406            if let ImeEvent::Commit(text) = event {
4407                sink.borrow_mut().push(text);
4408            }
4409            true
4410        }));
4411        rt.cache_frame(frame);
4412        rt.handle_ime(&ImeEvent::Commit("あ".to_string()));
4413        rt.handle_ime(&ImeEvent::Cancel);
4414        assert_eq!(&*seen.borrow(), &["あ".to_string()]);
4415        assert!(rt.textfield_states.is_empty());
4416    }
4417
4418    #[test]
4419    fn unconsumed_events_leave_textfields_untouched() {
4420        let mut rt = ReposeRuntime::new();
4421        rt.sched.focused = Some(TF_ID);
4422        let mut frame = editable_frame(TF_ID);
4423        frame.hit_regions[0].tf_state_key = None;
4424        frame.hit_regions[0].tf_enabled = false;
4425        frame.semantics_nodes.clear();
4426        frame.hit_regions[0].on_ime = Some(Rc::new(|_| false));
4427        rt.cache_frame(frame);
4428        rt.handle_ime(&ImeEvent::Commit("x".to_string()));
4429        assert!(rt.textfield_states.is_empty());
4430    }
4431}
4432
4433#[cfg(test)]
4434mod gamepad_tests {
4435    use super::*;
4436    use repose_core::input::{GamepadAxis, GamepadButton, GamepadEvent, GamepadId};
4437
4438    #[test]
4439    fn gamepad_state_mirrors_connection_and_inputs() {
4440        let mut rt = ReposeRuntime::new();
4441        rt.handle_gamepad(&GamepadEvent::Connected {
4442            id: GamepadId(0),
4443            name: "Pad".to_string(),
4444            vendor_id: 0,
4445            product_id: 0,
4446        });
4447        assert_eq!(rt.gamepads.len(), 1);
4448
4449        rt.handle_gamepad(&GamepadEvent::Button {
4450            id: GamepadId(0),
4451            button: GamepadButton::West,
4452            pressed: true,
4453        });
4454        assert!(rt.gamepads[&0].button(GamepadButton::West));
4455
4456        rt.handle_gamepad(&GamepadEvent::Axis {
4457            id: GamepadId(0),
4458            axis: GamepadAxis::LeftStickX,
4459            value: 0.5,
4460        });
4461        assert_eq!(rt.gamepads[&0].axis(GamepadAxis::LeftStickX), 0.5);
4462
4463        rt.handle_gamepad(&GamepadEvent::Button {
4464            id: GamepadId(0),
4465            button: GamepadButton::West,
4466            pressed: false,
4467        });
4468        assert!(!rt.gamepads[&0].button(GamepadButton::West));
4469
4470        rt.handle_gamepad(&GamepadEvent::Disconnected { id: GamepadId(0) });
4471        assert!(rt.gamepads.is_empty());
4472    }
4473
4474    #[test]
4475    fn rumble_requests_queue_and_drain() {
4476        let mut rt = ReposeRuntime::new();
4477        assert!(rt.take_rumble_requests().is_empty());
4478        rt.request_rumble(GamepadId(1), 2.0, -1.0, 150);
4479        rt.stop_rumble(GamepadId(1));
4480        let reqs = rt.take_rumble_requests();
4481        assert_eq!(reqs.len(), 2);
4482        assert_eq!(reqs[0], (1, 1.0, 0.0, 150));
4483        assert_eq!(reqs[1], (1, 0.0, 0.0, 0));
4484        assert!(rt.take_rumble_requests().is_empty());
4485    }
4486
4487    #[test]
4488    fn global_rumble_broadcasts_to_connected_pads() {
4489        let mut rt = ReposeRuntime::new();
4490        rt.handle_gamepad(&GamepadEvent::Connected {
4491            id: GamepadId(1),
4492            name: "Pad".to_string(),
4493            vendor_id: 0,
4494            product_id: 0,
4495        });
4496        repose_core::rumble::push(0.9, 0.5, 200);
4497        repose_core::rumble::push(0.0, 0.0, 0);
4498        let reqs = rt.take_rumble_requests();
4499        assert_eq!(reqs, vec![(1, 0.9, 0.5, 200), (1, 0.0, 0.0, 0)]);
4500        assert!(rt.take_rumble_requests().is_empty());
4501    }
4502
4503    #[test]
4504    fn global_rumble_without_pads_is_dropped() {
4505        let mut rt = ReposeRuntime::new();
4506        repose_core::rumble::push(0.5, 0.5, 100);
4507        assert!(rt.take_rumble_requests().is_empty());
4508        assert!(repose_core::rumble::take().is_empty());
4509    }
4510
4511    #[test]
4512    fn sensor_samples_are_latest_wins_per_pad_and_kind() {
4513        let mut rt = ReposeRuntime::new();
4514        rt.handle_sensor_sample(GamepadId(0), SensorSample::gyroscope(1.0, 2.0, 3.0));
4515        rt.handle_sensor_sample(GamepadId(0), SensorSample::gyroscope(4.0, 5.0, 6.0));
4516        rt.handle_sensor_sample(GamepadId(0), SensorSample::accelerometer(0.0, 0.0, 1.0));
4517        rt.handle_sensor_sample(GamepadId(2), SensorSample::gyroscope(-1.0, 0.0, 0.0));
4518
4519        assert_eq!(
4520            rt.gamepad_sensor(GamepadId(0), SensorKind::Gyroscope),
4521            Some([4.0, 5.0, 6.0])
4522        );
4523        assert_eq!(
4524            rt.gamepad_sensor(GamepadId(0), SensorKind::Accelerometer),
4525            Some([0.0, 0.0, 1.0])
4526        );
4527        assert_eq!(
4528            rt.gamepad_sensor(GamepadId(2), SensorKind::Gyroscope),
4529            Some([-1.0, 0.0, 0.0])
4530        );
4531        assert_eq!(rt.gamepad_sensor(GamepadId(1), SensorKind::Gyroscope), None);
4532        assert_eq!(
4533            rt.gamepad_sensor_kinds(GamepadId(0)),
4534            vec![SensorKind::Gyroscope, SensorKind::Accelerometer]
4535        );
4536        assert_eq!(
4537            rt.gamepad_sensor_kinds(GamepadId(2)),
4538            vec![SensorKind::Gyroscope]
4539        );
4540    }
4541
4542    #[test]
4543    fn resting_sensor_noise_holds_still_until_motion_accumulates() {
4544        let mut rt = ReposeRuntime::new();
4545        rt.handle_sensor_sample(GamepadId(0), SensorSample::gyroscope(0.0, 0.0, 0.0));
4546        rt.handle_sensor_sample(GamepadId(0), SensorSample::gyroscope(0.1, -0.1, 0.05));
4547        rt.handle_sensor_sample(GamepadId(0), SensorSample::accelerometer(1.0, 0.004, 0.0));
4548        rt.handle_sensor_sample(GamepadId(0), SensorSample::accelerometer(1.0, -0.004, 0.0));
4549
4550        assert_eq!(
4551            rt.gamepad_sensor(GamepadId(0), SensorKind::Gyroscope),
4552            Some([0.0, 0.0, 0.0])
4553        );
4554        assert_eq!(
4555            rt.gamepad_sensor(GamepadId(0), SensorKind::Accelerometer),
4556            Some([1.0, 0.004, 0.0])
4557        );
4558
4559        rt.handle_sensor_sample(GamepadId(0), SensorSample::gyroscope(40.0, 0.0, 0.0));
4560        rt.handle_sensor_sample(GamepadId(0), SensorSample::accelerometer(1.03, 0.0, 0.0));
4561
4562        assert_eq!(
4563            rt.gamepad_sensor(GamepadId(0), SensorKind::Gyroscope),
4564            Some([40.0, 0.0, 0.0])
4565        );
4566        assert_eq!(
4567            rt.gamepad_sensor(GamepadId(0), SensorKind::Accelerometer),
4568            Some([1.03, 0.0, 0.0])
4569        );
4570    }
4571
4572    #[test]
4573    fn sensor_state_drops_with_the_pad() {
4574        let mut rt = ReposeRuntime::new();
4575        rt.handle_gamepad(&GamepadEvent::Connected {
4576            id: GamepadId(0),
4577            name: "Pad".to_string(),
4578            vendor_id: 0,
4579            product_id: 0,
4580        });
4581        rt.handle_sensor_sample(GamepadId(0), SensorSample::gyroscope(1.0, 1.0, 1.0));
4582        assert!(
4583            rt.gamepad_sensor(GamepadId(0), SensorKind::Gyroscope)
4584                .is_some()
4585        );
4586
4587        rt.handle_gamepad(&GamepadEvent::Disconnected { id: GamepadId(0) });
4588        assert_eq!(rt.gamepad_sensor(GamepadId(0), SensorKind::Gyroscope), None);
4589    }
4590
4591    #[test]
4592    fn sensor_devices_resolve_to_connected_pads_by_name() {
4593        let mut rt = ReposeRuntime::new();
4594        rt.handle_gamepad(&GamepadEvent::Connected {
4595            id: GamepadId(3),
4596            name: "Wireless Controller (Vendor: 054c)".to_string(),
4597            vendor_id: 0,
4598            product_id: 0,
4599        });
4600
4601        assert_eq!(
4602            rt.gamepad_id_by_sensor_device("Wireless Controller (Vendor: 054c)"),
4603            Some(GamepadId(3))
4604        );
4605        assert_eq!(
4606            rt.gamepad_id_by_sensor_device("wireless controller vendor 054c"),
4607            Some(GamepadId(3))
4608        );
4609        assert_eq!(rt.gamepad_id_by_sensor_device("Some Other Pad"), None);
4610    }
4611
4612    #[test]
4613    fn ambiguous_sensor_device_names_resolve_to_nothing() {
4614        let mut rt = ReposeRuntime::new();
4615        for (id, name) in [(0, "Wireless Controller"), (1, "wireless controller!")] {
4616            rt.handle_gamepad(&GamepadEvent::Connected {
4617                id: GamepadId(id),
4618                name: name.to_string(),
4619                vendor_id: 0,
4620                product_id: 0,
4621            });
4622        }
4623        assert_eq!(rt.gamepad_id_by_sensor_device("WIRELESS CONTROLLER"), None);
4624        assert_eq!(
4625            rt.gamepad_id_by_sensor_device("Wireless Controller"),
4626            Some(GamepadId(0))
4627        );
4628    }
4629
4630    #[test]
4631    fn two_pads_sharing_one_name_never_win_by_hash_order() {
4632        let mut rt = ReposeRuntime::new();
4633        for id in 0..2 {
4634            rt.handle_gamepad(&GamepadEvent::Connected {
4635                id: GamepadId(id),
4636                name: "Nintendo Switch Pro Controller".to_string(),
4637                vendor_id: 0,
4638                product_id: 0,
4639            });
4640        }
4641        assert_eq!(
4642            rt.gamepad_id_by_sensor_device("Nintendo Switch Pro Controller"),
4643            None,
4644            "an identical name cannot pick a pad by map order"
4645        );
4646    }
4647}
4648
4649#[cfg(test)]
4650mod focus_click_tests {
4651    use super::*;
4652    use repose_core::Rect;
4653
4654    fn frame_with_field_and_button() -> Frame {
4655        let field = HitRegion {
4656            id: 1,
4657            rect: Rect {
4658                x: 0.0,
4659                y: 0.0,
4660                w: 100.0,
4661                h: 40.0,
4662            },
4663            focusable: true,
4664            tf_enabled: false,
4665            ..Default::default()
4666        };
4667        let button = HitRegion {
4668            id: 2,
4669            rect: Rect {
4670                x: 0.0,
4671                y: 60.0,
4672                w: 100.0,
4673                h: 40.0,
4674            },
4675            focusable: true,
4676            on_click: Some(Rc::new(|| {})),
4677            ..Default::default()
4678        };
4679        Frame {
4680            scene: Default::default(),
4681            hit_regions: vec![field, button],
4682            semantics_nodes: vec![],
4683            focus_chain: vec![1, 2],
4684        }
4685    }
4686
4687    #[test]
4688    fn focused_textfield_survives_drag_started_on_clickable() {
4689        let mut rt = ReposeRuntime::new();
4690        rt.frame_cache = Some(Rc::new(frame_with_field_and_button()));
4691        rt.sched.focused = Some(1);
4692
4693        rt.handle_touch_press(Some(10), Vec2 { x: 50.0, y: 80.0 }, PointerButton::Primary);
4694        assert_eq!(
4695            rt.sched.focused,
4696            Some(1),
4697            "pointer-down on a clickable must not steal focus from the field"
4698        );
4699
4700        rt.handle_touch_release(Some(10), Vec2 { x: 50.0, y: 400.0 }, PointerButton::Primary);
4701        assert_eq!(
4702            rt.sched.focused,
4703            Some(1),
4704            "a press that became a drag must leave the field focused"
4705        );
4706        assert_eq!(rt.pending_focus_on_click, None);
4707    }
4708
4709    #[test]
4710    fn clickable_receives_focus_on_tap() {
4711        let mut rt = ReposeRuntime::new();
4712        rt.frame_cache = Some(Rc::new(frame_with_field_and_button()));
4713        rt.sched.focused = Some(1);
4714
4715        rt.handle_touch_press(Some(11), Vec2 { x: 50.0, y: 80.0 }, PointerButton::Primary);
4716        rt.handle_touch_release(Some(11), Vec2 { x: 50.0, y: 80.0 }, PointerButton::Primary);
4717        assert_eq!(
4718            rt.sched.focused,
4719            Some(2),
4720            "a completed tap moves focus to the clickable"
4721        );
4722    }
4723}
4724
4725fn gesture_centroid(action: &repose_core::shortcuts::Action) -> Option<repose_core::Vec2> {
4726    match action {
4727        repose_core::shortcuts::Action::Gesture(g) => match g {
4728            repose_core::shortcuts::Gesture::PinchWithCenter { center, .. }
4729            | repose_core::shortcuts::Gesture::Rotate { center, .. }
4730            | repose_core::shortcuts::Gesture::Pan { center, .. } => Some(*center),
4731            _ => None,
4732        },
4733        _ => None,
4734    }
4735}
4736
4737#[cfg(test)]
4738mod dialog_focus_repro_tests {
4739    use super::*;
4740    use repose_core::{Dp, FocusRequester, Modifier, View, ViewKind};
4741
4742    /// Reproduce the dialog auto-focus lifecycle: a field with a focus requester,
4743    /// and a zero-size probe whose on_globally_positioned requests focus once
4744    /// (mirrors repose-material Dialog's focus_probe).
4745    #[test]
4746    fn focus_survives_ime_padding_change() {
4747        let mut rt = ReposeRuntime::new();
4748        let fr = FocusRequester::new();
4749        let requested = Rc::new(Cell::new(false));
4750        let fr_probe = fr.clone();
4751        let padding = Rc::new(Cell::new(0.0f32));
4752
4753        let tf_states: HashMap<u64, Rc<RefCell<TextFieldState>>> = HashMap::new();
4754        let pressed = HashSet::new();
4755
4756        let mut root = |_s: &mut Scheduler| {
4757            let p = padding.get();
4758            let rp = requested.clone();
4759            let fp = fr_probe.clone();
4760            let probe = View::new(0, ViewKind::Box).modifier(
4761                Modifier::new()
4762                    .size(Dp(0.0), Dp(0.0))
4763                    .on_globally_positioned(move |_| {
4764                        if !rp.get() && fp.target.borrow().is_some() {
4765                            fp.request_focus();
4766                            rp.set(true);
4767                        }
4768                    }),
4769            );
4770            let field = View::new(0, ViewKind::Box).modifier(
4771                Modifier::new()
4772                    .fill_max_width()
4773                    .height(Dp(40.0))
4774                    .focusable(true)
4775                    .focus_requester(fr.clone()),
4776            );
4777            let container = View::new(0, ViewKind::Column)
4778                .modifier(Modifier::new().padding(Dp(p)))
4779                .with_children(vec![field, probe]);
4780            container
4781        };
4782
4783        let frame1 = compose_frame_inner(
4784            &mut rt.sched,
4785            &mut root,
4786            1.0,
4787            (400, 800),
4788            None,
4789            &pressed,
4790            &tf_states,
4791        );
4792        let focused1 = rt.sched.focused;
4793        assert!(
4794            focused1.is_some(),
4795            "frame1: focus requested by probe should be applied"
4796        );
4797        assert!(
4798            frame1.focus_chain.contains(&focused1.unwrap()),
4799            "frame1: focused id in chain"
4800        );
4801
4802        // IME inset grows: padding on the container changes, like Dialog's platform padding.
4803        padding.set(300.0);
4804        let frame2 = compose_frame_inner(
4805            &mut rt.sched,
4806            &mut root,
4807            1.0,
4808            (400, 800),
4809            None,
4810            &pressed,
4811            &tf_states,
4812        );
4813        let focused2 = rt.sched.focused;
4814        assert!(
4815            focused2.is_some(),
4816            "frame2: focus should survive padding change (got None)"
4817        );
4818        assert!(
4819            frame2.focus_chain.contains(&focused2.unwrap()),
4820            "frame2: focused id in chain"
4821        );
4822    }
4823
4824    /// Change the STRUCTURE before the field (not just padding), mirroring
4825    /// Dialog's keyed `measure` subtree regenerating on IME inset change.
4826    #[test]
4827    fn focus_survives_structure_change_before_field() {
4828        use repose_ui::subcompose::box_with_constraints_with_key;
4829        let mut rt = ReposeRuntime::new();
4830        let fr = FocusRequester::new();
4831        let requested = Rc::new(Cell::new(false));
4832        let key = Rc::new(Cell::new(0u32));
4833        let tf_states: HashMap<u64, Rc<RefCell<TextFieldState>>> = HashMap::new();
4834        let pressed = HashSet::new();
4835
4836        let mut root = |_s: &mut Scheduler| {
4837            let k = key.get();
4838            let rp = requested.clone();
4839            let fp = fr.clone();
4840            let probe = View::new(0, ViewKind::Box).modifier(
4841                Modifier::new()
4842                    .size(Dp(0.0), Dp(0.0))
4843                    .on_globally_positioned(move |_| {
4844                        if !rp.get() && fp.target.borrow().is_some() {
4845                            fp.request_focus();
4846                            rp.set(true);
4847                        }
4848                    }),
4849            );
4850            let field = View::new(0, ViewKind::Box).modifier(
4851                Modifier::new()
4852                    .fill_max_width()
4853                    .height(Dp(40.0))
4854                    .focusable(true)
4855                    .focus_requester(fr.clone()),
4856            );
4857            let measure = box_with_constraints_with_key(
4858                k,
4859                Modifier::new().size(Dp(10.0), Dp(10.0)),
4860                |_scope| {
4861                    View::new(0, ViewKind::Box).modifier(Modifier::new().size(Dp(10.0), Dp(10.0)))
4862                },
4863            );
4864            View::new(0, ViewKind::Column).with_children(vec![measure, field, probe])
4865        };
4866
4867        let frame1 = compose_frame_inner(
4868            &mut rt.sched,
4869            &mut root,
4870            1.0,
4871            (400, 800),
4872            None,
4873            &pressed,
4874            &tf_states,
4875        );
4876        let focused1 = rt.sched.focused.expect("frame1 focus");
4877        assert!(frame1.focus_chain.contains(&focused1));
4878
4879        key.set(1);
4880        let frame2 = compose_frame_inner(
4881            &mut rt.sched,
4882            &mut root,
4883            1.0,
4884            (400, 800),
4885            None,
4886            &pressed,
4887            &tf_states,
4888        );
4889        let focused2 = rt.sched.focused;
4890        assert!(
4891            focused2.is_some(),
4892            "frame2: focus should survive keyed structure change, got None"
4893        );
4894        assert!(frame2.focus_chain.contains(&focused2.unwrap()));
4895    }
4896}