Skip to main content

cranpose_app_shell/
shell_input.rs

1use super::*;
2
3impl<R> AppShell<R>
4where
5    R: Renderer,
6    R::Error: Debug,
7{
8    fn pointer_event(
9        &self,
10        kind: PointerEventKind,
11        position: Point,
12        global_position: Point,
13        event_time: PointerEventTime,
14    ) -> PointerEvent {
15        PointerEvent::new(kind, position, global_position)
16            .with_time_ms(event_time.platform_time_ms)
17            .with_animation_time_nanos(event_time.animation_time_nanos)
18    }
19
20    fn resolve_gesture_targets(
21        &self,
22        pointer: PointerId,
23    ) -> Vec<<<R as Renderer>::Scene as RenderScene>::HitTarget> {
24        self.resolve_hit_path(pointer)
25    }
26
27    /// Resolves cached NodeIds to fresh HitTargets from the current scene.
28    ///
29    /// This is the key to avoiding stale geometry during scroll/layout changes:
30    /// - We cache NodeIds on PointerDown (stable identity)
31    /// - On Move/Up/Cancel, we call find_target() to get fresh geometry
32    /// - Handler closures are preserved (same Rc), so gesture state survives
33    fn resolve_hit_path(
34        &self,
35        pointer: PointerId,
36    ) -> Vec<<<R as Renderer>::Scene as RenderScene>::HitTarget> {
37        let Some(node_ids) = self.hit_path_tracker.dispatch_order(pointer) else {
38            return Vec::new();
39        };
40
41        let scene = self.renderer.scene();
42        let targets: Vec<_> = node_ids
43            .iter()
44            .filter_map(|&id| scene.find_target(id))
45            .collect();
46        log::trace!(
47            target: "cranpose::input",
48            "resolve_hit_path pointer={pointer:?} cached={node_ids:?} resolved_count={}",
49            targets.len()
50        );
51        targets
52    }
53
54    fn dispatch_targets<I>(&mut self, targets: I, event: PointerEvent, stop_on_consume: bool)
55    where
56        I: IntoIterator<Item = <<R as Renderer>::Scene as RenderScene>::HitTarget>,
57    {
58        let mut applier = self.composition.applier_mut();
59        for target in targets {
60            let node_id = target.node_id();
61            target.dispatch_with_applier(&mut applier, event.clone());
62            log::trace!(
63                target: "cranpose::input",
64                "dispatch {:?} node={} consumed={} stop_on_consume={}",
65                event.kind,
66                node_id,
67                event.is_consumed(),
68                stop_on_consume,
69            );
70            if stop_on_consume && event.is_consumed() {
71                break;
72            }
73        }
74    }
75
76    /// Sets the device source (touch/mouse/stylus) of the pointer sample that
77    /// the platform is about to dispatch. Call this before `set_cursor` /
78    /// `pointer_pressed` / `pointer_released` so the resulting `PointerEvent`s
79    /// carry the source so consumers can preserve device-specific gesture
80    /// details without changing shared pointer UI.
81    pub fn set_pointer_source(&mut self, source: PointerSource) {
82        self.pointer_source = source;
83    }
84
85    /// The device source of the most recent pointer sample.
86    pub fn pointer_source(&self) -> PointerSource {
87        self.pointer_source
88    }
89
90    pub fn set_cursor(&mut self, x: f32, y: f32) -> bool {
91        self.set_cursor_at_time(x, y, None)
92    }
93
94    /// Like [`set_cursor`](Self::set_cursor), but carries the platform input
95    /// timestamp (milliseconds, platform-specific time base) of the sample.
96    ///
97    /// Platforms that deliver input batched/frame-aligned (Android) must use
98    /// this so gesture velocity is computed from real event times instead of
99    /// delivery times.
100    pub fn set_cursor_at_time(&mut self, x: f32, y: f32, time_ms: Option<i64>) -> bool {
101        let event_time = self.realtime_pointer_event_time(time_ms);
102        self.set_cursor_at_event_time(x, y, event_time)
103    }
104
105    /// Set the cursor using a timestamp already resolved into both clock domains.
106    pub fn set_cursor_at_event_time(
107        &mut self,
108        x: f32,
109        y: f32,
110        event_time: PointerEventTime,
111    ) -> bool {
112        let _event_handler = enter_event_handler_scope();
113        let app_context = Rc::clone(&self.app_context);
114        let result = app_context.enter(|| {
115            run_in_mutable_snapshot(|| self.set_cursor_inner(x, y, event_time)).unwrap_or(false)
116        });
117        if result {
118            self.mark_dirty();
119        }
120        log::trace!(
121            target: "cranpose::input",
122            "set_cursor ({x:.2},{y:.2}) time_ms={:?} animation_time_nanos={} -> {result}",
123            event_time.platform_time_ms,
124            event_time.animation_time_nanos,
125        );
126        result
127    }
128
129    fn set_cursor_inner(&mut self, x: f32, y: f32, event_time: PointerEventTime) -> bool {
130        self.cursor = (x, y);
131
132        // During a gesture (button pressed), ONLY dispatch to the tracked hit path.
133        // Never fall back to hover hit-testing while buttons are down.
134        // This maintains the invariant: the path that receives Down must receive Move and Up/Cancel.
135        if self.buttons_pressed != PointerButtons::NONE {
136            if self.hit_path_tracker.has_path(PointerId::PRIMARY) {
137                let targets = self.resolve_gesture_targets(PointerId::PRIMARY);
138                if !targets.is_empty() {
139                    let event = self
140                        .pointer_event(
141                            PointerEventKind::Move,
142                            Point { x, y },
143                            Point { x, y },
144                            event_time,
145                        )
146                        .with_buttons(self.buttons_pressed)
147                        .with_source(self.pointer_source);
148                    self.dispatch_targets(targets, event, false);
149                    return true;
150                }
151
152                return false;
153            }
154
155            // Button is down but we have no recorded path inside this app
156            // (e.g. drag started outside). Do not dispatch anything.
157            return false;
158        }
159
160        // No gesture in progress: regular hover move using hit-test.
161        // Diff against previous hover set to synthesize Enter/Exit events.
162        let hits = self.renderer.scene().hit_test(x, y);
163        let new_ids: Vec<NodeId> = hits.iter().map(|h| h.node_id()).collect();
164
165        // Dispatch Exit to nodes that are no longer hovered
166        let pos = Point { x, y };
167        let previously_hovered = self.hovered_nodes.clone();
168        for old_id in previously_hovered {
169            if !new_ids.contains(&old_id) {
170                if let Some(target) = self.renderer.scene().find_target(old_id) {
171                    let exit_event = self
172                        .pointer_event(PointerEventKind::Exit, pos, pos, event_time)
173                        .with_buttons(self.buttons_pressed)
174                        .with_source(self.pointer_source);
175                    self.dispatch_targets(std::iter::once(target), exit_event, false);
176                }
177            }
178        }
179
180        // Dispatch Enter to newly hovered nodes
181        for hit in &hits {
182            if !self.hovered_nodes.contains(&hit.node_id()) {
183                let enter_event = self
184                    .pointer_event(PointerEventKind::Enter, pos, pos, event_time)
185                    .with_buttons(self.buttons_pressed)
186                    .with_source(self.pointer_source);
187                self.dispatch_targets(std::iter::once(hit.clone()), enter_event, false);
188            }
189        }
190
191        self.hovered_nodes = new_ids;
192
193        if !hits.is_empty() {
194            let event = self
195                .pointer_event(PointerEventKind::Move, pos, pos, event_time)
196                .with_buttons(self.buttons_pressed)
197                .with_source(self.pointer_source);
198            self.dispatch_targets(hits, event, true);
199            true
200        } else {
201            false
202        }
203    }
204
205    pub fn pointer_pressed(&mut self) -> bool {
206        self.pointer_pressed_at_time(None)
207    }
208
209    /// Like [`pointer_pressed`](Self::pointer_pressed), but carries the
210    /// platform input timestamp (milliseconds) of the press sample.
211    pub fn pointer_pressed_at_time(&mut self, time_ms: Option<i64>) -> bool {
212        let event_time = self.realtime_pointer_event_time(time_ms);
213        self.pointer_pressed_at_event_time(event_time)
214    }
215
216    /// Dispatch primary-button down with an already resolved event timestamp.
217    pub fn pointer_pressed_at_event_time(&mut self, event_time: PointerEventTime) -> bool {
218        // The dev overlay is drawn over the composition and is not part of it,
219        // so it gets the press first and keeps it. Nothing below it is armed:
220        // no button state, no hit path, so the matching release is inert.
221        if self.dev_overlay_press(self.cursor.0, self.cursor.1) {
222            return true;
223        }
224        let _event_handler = enter_event_handler_scope();
225        let app_context = Rc::clone(&self.app_context);
226        let result = app_context.enter(|| {
227            run_in_mutable_snapshot(|| self.pointer_pressed_inner(event_time)).unwrap_or(false)
228        });
229        if result {
230            self.mark_dirty();
231        }
232        log::trace!(
233            target: "cranpose::input",
234            "pointer_pressed time_ms={:?} animation_time_nanos={} -> {result}",
235            event_time.platform_time_ms,
236            event_time.animation_time_nanos,
237        );
238        result
239    }
240
241    fn pointer_pressed_inner(&mut self, event_time: PointerEventTime) -> bool {
242        // Track button state
243        self.buttons_pressed.insert(PointerButton::Primary);
244
245        // Hit-test against the current (last rendered) scene.
246        // Even if the app is dirty, this scene is what the user actually saw and clicked.
247        // Frame N is rendered → user sees frame N and taps → we hit-test frame N's geometry.
248        // The pointer event may mark dirty → next frame runs update() → renders N+1.
249
250        // Perform hit test and cache the NodeIds (not geometry!)
251        // The key insight from Jetpack Compose: cache identity, resolve fresh geometry per dispatch
252        let hits = self.renderer.scene().hit_test(self.cursor.0, self.cursor.1);
253        if hits.is_empty() {
254            self.hit_path_tracker.remove_path(PointerId::PRIMARY);
255            false
256        } else {
257            let event = self
258                .pointer_event(
259                    PointerEventKind::Down,
260                    Point {
261                        x: self.cursor.0,
262                        y: self.cursor.1,
263                    },
264                    Point {
265                        x: self.cursor.0,
266                        y: self.cursor.1,
267                    },
268                    event_time,
269                )
270                .with_buttons(self.buttons_pressed)
271                .with_source(self.pointer_source);
272
273            let mut delivered_capture_paths = Vec::new();
274            let mut applier = self.composition.applier_mut();
275            for hit in hits {
276                let node_id = hit.node_id();
277                delivered_capture_paths.push(hit.capture_path());
278                hit.dispatch_with_applier(&mut applier, event.clone());
279                log::trace!(
280                    target: "cranpose::input",
281                    "dispatch {:?} node={} consumed={} stop_on_consume=true",
282                    event.kind,
283                    node_id,
284                    event.is_consumed(),
285                );
286                if event.is_consumed() {
287                    break;
288                }
289            }
290
291            self.hit_path_tracker
292                .add_hit_path(PointerId::PRIMARY, delivered_capture_paths);
293            log::trace!(
294                target: "cranpose::input",
295                "pointer_pressed_inner cached_hit_path={:?}",
296                self.hit_path_tracker.get_path(PointerId::PRIMARY),
297            );
298
299            true
300        }
301    }
302
303    pub fn pointer_released(&mut self) -> bool {
304        self.pointer_released_at_time(None)
305    }
306
307    /// Releases the pointer at the position carried by the platform's release
308    /// sample (Android `ACTION_UP`, web `pointerup`/`touchend`).
309    ///
310    /// The cursor is moved to `(x, y)` WITHOUT dispatching a Move event, then
311    /// the Up event is dispatched at that position. Platforms whose release
312    /// events carry their own coordinates must use this instead of
313    /// `set_cursor* + pointer_released*`: lift-off samples routinely roll back
314    /// a few dp against the travel direction as the finger peels off, and
315    /// feeding that jitter into gesture velocity trackers as a final Move
316    /// sample can flip the sign of the computed fling velocity (flings that
317    /// suddenly go the opposite way). Jetpack Compose likewise never feeds the
318    /// up sample into velocity tracking.
319    pub fn pointer_released_at_position(&mut self, x: f32, y: f32) -> bool {
320        self.pointer_released_at_position_time(x, y, None)
321    }
322
323    /// Like [`pointer_released_at_position`](Self::pointer_released_at_position),
324    /// but carries the platform input timestamp (milliseconds) of the release
325    /// sample.
326    pub fn pointer_released_at_position_time(
327        &mut self,
328        x: f32,
329        y: f32,
330        time_ms: Option<i64>,
331    ) -> bool {
332        let event_time = self.realtime_pointer_event_time(time_ms);
333        self.pointer_released_at_position_event_time(x, y, event_time)
334    }
335
336    /// Release at a position with an already resolved event timestamp.
337    pub fn pointer_released_at_position_event_time(
338        &mut self,
339        x: f32,
340        y: f32,
341        event_time: PointerEventTime,
342    ) -> bool {
343        let _event_handler = enter_event_handler_scope();
344        let app_context = Rc::clone(&self.app_context);
345        let result = app_context.enter(|| {
346            run_in_mutable_snapshot(|| {
347                self.cursor = (x, y);
348                self.pointer_released_inner(event_time)
349            })
350            .unwrap_or(false)
351        });
352        if result {
353            self.mark_dirty();
354        }
355        log::trace!(
356            target: "cranpose::input",
357            "pointer_released_at_position ({x:.2},{y:.2}) time_ms={:?} animation_time_nanos={} -> {result}",
358            event_time.platform_time_ms,
359            event_time.animation_time_nanos,
360        );
361        result
362    }
363
364    /// Like [`pointer_released`](Self::pointer_released), but carries the
365    /// platform input timestamp (milliseconds) of the release sample.
366    pub fn pointer_released_at_time(&mut self, time_ms: Option<i64>) -> bool {
367        let event_time = self.realtime_pointer_event_time(time_ms);
368        self.pointer_released_at_event_time(event_time)
369    }
370
371    /// Dispatch primary-button up with an already resolved event timestamp.
372    pub fn pointer_released_at_event_time(&mut self, event_time: PointerEventTime) -> bool {
373        let _event_handler = enter_event_handler_scope();
374        let app_context = Rc::clone(&self.app_context);
375        let result = app_context.enter(|| {
376            run_in_mutable_snapshot(|| self.pointer_released_inner(event_time)).unwrap_or(false)
377        });
378        if result {
379            self.mark_dirty();
380        }
381        log::trace!(
382            target: "cranpose::input",
383            "pointer_released time_ms={:?} animation_time_nanos={} -> {result}",
384            event_time.platform_time_ms,
385            event_time.animation_time_nanos,
386        );
387        result
388    }
389
390    fn pointer_released_inner(&mut self, event_time: PointerEventTime) -> bool {
391        // UP events report buttons as "currently pressed" (after release),
392        // matching typical platform semantics where primary is already gone.
393        self.buttons_pressed.remove(PointerButton::Primary);
394        let corrected_buttons = self.buttons_pressed;
395        let targets = self.resolve_gesture_targets(PointerId::PRIMARY);
396
397        // Always remove the path, even if targets is empty (node may have been removed)
398        self.hit_path_tracker.remove_path(PointerId::PRIMARY);
399
400        if !targets.is_empty() {
401            let event = self
402                .pointer_event(
403                    PointerEventKind::Up,
404                    Point {
405                        x: self.cursor.0,
406                        y: self.cursor.1,
407                    },
408                    Point {
409                        x: self.cursor.0,
410                        y: self.cursor.1,
411                    },
412                    event_time,
413                )
414                .with_buttons(corrected_buttons)
415                .with_source(self.pointer_source);
416
417            self.dispatch_targets(targets, event, false);
418            true
419        } else {
420            false
421        }
422    }
423
424    /// Dispatches an event for a secondary pointer (`pointer_id != 0`).
425    ///
426    /// Multi-touch gestures act on the element the first finger grabbed, so
427    /// secondary pointers are routed to the hit path captured by the primary
428    /// pointer's Down. They carry no hover/click semantics and are ignored
429    /// when no primary gesture is in progress.
430    ///
431    /// Returns `true` when the event was dispatched to at least one target.
432    pub fn secondary_pointer_pressed(
433        &mut self,
434        pointer_id: u64,
435        x: f32,
436        y: f32,
437        time_ms: Option<i64>,
438    ) -> bool {
439        let event_time = self.realtime_pointer_event_time(time_ms);
440        self.dispatch_secondary_pointer(PointerEventKind::Down, pointer_id, x, y, event_time)
441    }
442
443    /// Move counterpart of [`secondary_pointer_pressed`](Self::secondary_pointer_pressed).
444    pub fn secondary_pointer_moved(
445        &mut self,
446        pointer_id: u64,
447        x: f32,
448        y: f32,
449        time_ms: Option<i64>,
450    ) -> bool {
451        let event_time = self.realtime_pointer_event_time(time_ms);
452        self.dispatch_secondary_pointer(PointerEventKind::Move, pointer_id, x, y, event_time)
453    }
454
455    /// Release counterpart of [`secondary_pointer_pressed`](Self::secondary_pointer_pressed).
456    pub fn secondary_pointer_released(
457        &mut self,
458        pointer_id: u64,
459        x: f32,
460        y: f32,
461        time_ms: Option<i64>,
462    ) -> bool {
463        let event_time = self.realtime_pointer_event_time(time_ms);
464        self.dispatch_secondary_pointer(PointerEventKind::Up, pointer_id, x, y, event_time)
465    }
466
467    fn dispatch_secondary_pointer(
468        &mut self,
469        kind: PointerEventKind,
470        pointer_id: u64,
471        x: f32,
472        y: f32,
473        event_time: PointerEventTime,
474    ) -> bool {
475        if pointer_id == 0 {
476            log::warn!(
477                target: "cranpose::input",
478                "secondary pointer dispatch called with the primary pointer id"
479            );
480            return false;
481        }
482
483        let _event_handler = enter_event_handler_scope();
484        let app_context = Rc::clone(&self.app_context);
485        let result = app_context.enter(|| {
486            run_in_mutable_snapshot(|| {
487                if !self.hit_path_tracker.has_path(PointerId::PRIMARY) {
488                    return false;
489                }
490                let targets = self.resolve_gesture_targets(PointerId::PRIMARY);
491                if targets.is_empty() {
492                    return false;
493                }
494                let pos = Point { x, y };
495                let event = self
496                    .pointer_event(kind, pos, pos, event_time)
497                    .with_buttons(self.buttons_pressed)
498                    .with_id(pointer_id)
499                    .with_source(self.pointer_source);
500                self.dispatch_targets(targets, event, false);
501                true
502            })
503            .unwrap_or(false)
504        });
505        if result {
506            self.mark_dirty();
507        }
508        log::trace!(
509            target: "cranpose::input",
510            "secondary_pointer {kind:?} id={pointer_id} ({x:.2},{y:.2}) time_ms={:?} animation_time_nanos={} -> {result}",
511            event_time.platform_time_ms,
512            event_time.animation_time_nanos,
513        );
514        result
515    }
516
517    /// Dispatches a discrete zoom step (desktop ctrl+wheel, browser pinch)
518    /// to the pointer handlers under the cursor.
519    ///
520    /// `zoom_factor` is multiplicative: `> 1.0` zooms in, `< 1.0` zooms out.
521    /// Returns `true` if a handler consumed the event.
522    pub fn pointer_zoomed(&mut self, zoom_factor: f32) -> bool {
523        let event_time = self.realtime_pointer_event_time(None);
524        let _event_handler = enter_event_handler_scope();
525        let app_context = Rc::clone(&self.app_context);
526        let result = app_context.enter(|| {
527            run_in_mutable_snapshot(|| self.pointer_zoomed_inner(zoom_factor, event_time))
528                .unwrap_or(false)
529        });
530        if result {
531            self.mark_dirty();
532        }
533        log::trace!(
534            target: "cranpose::input",
535            "pointer_zoomed factor={zoom_factor:.4} -> {result}"
536        );
537        result
538    }
539
540    fn pointer_zoomed_inner(&mut self, zoom_factor: f32, event_time: PointerEventTime) -> bool {
541        if !zoom_factor.is_finite() || zoom_factor <= 0.0 || zoom_factor == 1.0 {
542            return false;
543        }
544
545        let hits = self.renderer.scene().hit_test(self.cursor.0, self.cursor.1);
546        if hits.is_empty() {
547            return false;
548        }
549
550        let pos = Point {
551            x: self.cursor.0,
552            y: self.cursor.1,
553        };
554        let event = self
555            .pointer_event(PointerEventKind::Zoom, pos, pos, event_time)
556            .with_buttons(self.buttons_pressed)
557            .with_zoom_delta(zoom_factor)
558            .with_source(self.pointer_source);
559
560        let capture_paths = hits
561            .iter()
562            .map(|hit| hit.capture_path())
563            .collect::<Vec<_>>();
564        let targets = crate::hit_path_tracker::dispatch_order_for_paths(&capture_paths)
565            .into_iter()
566            .filter_map(|node_id| self.renderer.scene().find_target(node_id))
567            .collect::<Vec<_>>();
568
569        self.dispatch_targets(targets, event.clone(), true);
570
571        event.is_consumed()
572    }
573
574    /// Dispatches a mouse wheel / trackpad scroll event to hovered pointer handlers.
575    ///
576    /// Returns `true` if a handler consumed the event.
577    pub fn pointer_scrolled(&mut self, delta_x: f32, delta_y: f32) -> bool {
578        let event_time = self.realtime_pointer_event_time(None);
579        let _event_handler = enter_event_handler_scope();
580        let app_context = Rc::clone(&self.app_context);
581        let result = app_context.enter(|| {
582            run_in_mutable_snapshot(|| self.pointer_scrolled_inner(delta_x, delta_y, event_time))
583                .unwrap_or(false)
584        });
585        if result {
586            self.mark_dirty();
587        }
588        log::trace!(
589            target: "cranpose::input",
590            "pointer_scrolled ({delta_x:.2},{delta_y:.2}) -> {result}"
591        );
592        result
593    }
594
595    fn pointer_scrolled_inner(
596        &mut self,
597        delta_x: f32,
598        delta_y: f32,
599        event_time: PointerEventTime,
600    ) -> bool {
601        if delta_x.abs() <= f32::EPSILON && delta_y.abs() <= f32::EPSILON {
602            return false;
603        }
604
605        let hits = self.renderer.scene().hit_test(self.cursor.0, self.cursor.1);
606        if hits.is_empty() {
607            return false;
608        }
609
610        let event = self
611            .pointer_event(
612                PointerEventKind::Scroll,
613                Point {
614                    x: self.cursor.0,
615                    y: self.cursor.1,
616                },
617                Point {
618                    x: self.cursor.0,
619                    y: self.cursor.1,
620                },
621                event_time,
622            )
623            .with_buttons(self.buttons_pressed)
624            .with_scroll_delta(Point {
625                x: delta_x,
626                y: delta_y,
627            })
628            .with_source(self.pointer_source);
629
630        let capture_paths = hits
631            .iter()
632            .map(|hit| hit.capture_path())
633            .collect::<Vec<_>>();
634        let targets = crate::hit_path_tracker::dispatch_order_for_paths(&capture_paths)
635            .into_iter()
636            .filter_map(|node_id| self.renderer.scene().find_target(node_id))
637            .collect::<Vec<_>>();
638
639        self.dispatch_targets(targets, event.clone(), true);
640
641        event.is_consumed()
642    }
643
644    /// Installs the window-level rotary (Wear OS crown / rotating bezel)
645    /// handler — the low-level escape hatch.
646    ///
647    /// The handler runs only after the routed modifier chain has declined the
648    /// event (see [`rotary_scrolled`](Self::rotary_scrolled)), so an app that
649    /// draws everything into a single canvas receives every rotary delta
650    /// without registering a focus target or a modifier. Returning `true`
651    /// reports the event as consumed to the platform.
652    ///
653    /// Passing a new handler replaces the previous one.
654    pub fn set_on_rotary_scroll<F>(&mut self, handler: F)
655    where
656        F: Fn(RotaryScrollEvent) -> bool + 'static,
657    {
658        self.on_rotary_scroll = Some(Rc::new(handler));
659    }
660
661    /// Removes the window-level rotary handler, if one is installed.
662    pub fn clear_on_rotary_scroll(&mut self) {
663        self.on_rotary_scroll = None;
664    }
665
666    /// Pixels per rotary detent used by
667    /// [`rotary_scrolled_by_detents`](Self::rotary_scrolled_by_detents).
668    pub fn rotary_scroll_factor(&self) -> f32 {
669        self.rotary_scroll_factor
670    }
671
672    /// Sets the pixels-per-detent factor for rotary input.
673    ///
674    /// On Wear OS this must be `ViewConfiguration.getScaledVerticalScrollFactor()`
675    /// for pixel-exact parity with Compose. The host activity can read it over
676    /// JNI once at startup and push it here; when it does not, the shell falls
677    /// back to [`DEFAULT_ROTARY_SCROLL_FACTOR_DP`] scaled by display density.
678    ///
679    /// Non-finite or non-positive values are ignored.
680    pub fn set_rotary_scroll_factor(&mut self, factor: f32) {
681        if factor.is_finite() && factor > 0.0 {
682            self.rotary_scroll_factor = factor;
683        }
684    }
685
686    /// Dispatches a rotary scroll expressed in raw detents (Android
687    /// `AXIS_SCROLL`), converting to pixels with the configured scroll factor.
688    ///
689    /// Applies Compose's sign convention: a positive detent value (crown turned
690    /// up/away) produces a negative `vertical_scroll_pixels`.
691    pub fn rotary_scrolled_by_detents(&mut self, detents: f32, uptime_millis: u64) -> bool {
692        let factor = self.rotary_scroll_factor;
693        self.rotary_scrolled(RotaryScrollEvent::from_detents(
694            detents,
695            factor,
696            factor,
697            uptime_millis,
698        ))
699    }
700
701    /// Dispatches a rotary scroll event (Wear OS crown, Galaxy Watch bezel, or
702    /// a desktop mouse wheel standing in for one during development).
703    ///
704    /// Routing mirrors Compose's `RotaryInputModifierNode` contract:
705    ///
706    /// 1. Resolve the target chain. When a focus target is registered
707    ///    ([`cranpose_ui::focus_dispatch::active_focus_target`]) and still
708    ///    exists in the current scene, its capture path is used, so rotary goes
709    ///    to the focused node exactly as on Wear OS. Cranpose does not yet wire
710    ///    focus automatically, so in practice this falls back to the chain
711    ///    under the current cursor position.
712    /// 2. **Capture pass**, root to leaf, invoking `on_pre_rotary_scroll_event`
713    ///    handlers.
714    /// 3. **Bubble pass**, leaf to root, invoking `on_rotary_scroll_event`
715    ///    handlers.
716    /// 4. If still unconsumed, the window-level handler installed by
717    ///    [`set_on_rotary_scroll`](Self::set_on_rotary_scroll).
718    ///
719    /// The first handler returning `true` consumes the event and stops every
720    /// remaining step. Returns `true` when the event was consumed.
721    pub fn rotary_scrolled(&mut self, event: RotaryScrollEvent) -> bool {
722        let _event_handler = enter_event_handler_scope();
723        let app_context = Rc::clone(&self.app_context);
724        let result = app_context.enter(|| {
725            run_in_mutable_snapshot(|| self.rotary_scrolled_inner(event)).unwrap_or(false)
726        });
727        if result {
728            self.mark_dirty();
729        }
730        log::trace!(
731            target: "cranpose::input",
732            "rotary_scrolled v={:.2} h={:.2} uptime={} -> {result}",
733            event.vertical_scroll_pixels,
734            event.horizontal_scroll_pixels,
735            event.uptime_millis,
736        );
737        result
738    }
739
740    fn rotary_scrolled_inner(&mut self, rotary: RotaryScrollEvent) -> bool {
741        if rotary.is_empty() {
742            return false;
743        }
744
745        // Leaf-first dispatch order (children before their ancestors), the
746        // same ordering pointer events use.
747        let bubble_order = self.rotary_dispatch_order();
748        let position = Point {
749            x: self.cursor.0,
750            y: self.cursor.1,
751        };
752
753        if !bubble_order.is_empty() {
754            // Capture pass: root -> leaf, so ancestors can intercept first.
755            let capture_targets = bubble_order
756                .iter()
757                .rev()
758                .filter_map(|&node_id| self.renderer.scene().find_target(node_id))
759                .collect::<Vec<_>>();
760            let capture_event =
761                PointerEvent::rotary(PointerEventKind::RotaryScrollPre, rotary, position);
762            self.dispatch_targets(capture_targets, capture_event.clone(), true);
763            if capture_event.is_consumed() {
764                return true;
765            }
766
767            // Bubble pass: leaf -> root.
768            let bubble_targets = bubble_order
769                .iter()
770                .filter_map(|&node_id| self.renderer.scene().find_target(node_id))
771                .collect::<Vec<_>>();
772            let bubble_event =
773                PointerEvent::rotary(PointerEventKind::RotaryScroll, rotary, position);
774            self.dispatch_targets(bubble_targets, bubble_event.clone(), true);
775            if bubble_event.is_consumed() {
776                return true;
777            }
778        }
779
780        // Window-level escape hatch for single-canvas apps.
781        if let Some(handler) = self.on_rotary_scroll.clone() {
782            return handler(rotary);
783        }
784
785        false
786    }
787
788    /// Resolves the leaf-to-root node order rotary events are dispatched over.
789    ///
790    /// Prefers the focused node's capture path; falls back to the chain under
791    /// the current cursor so rotary remains usable on a build where nothing has
792    /// claimed focus (the common case today).
793    fn rotary_dispatch_order(&self) -> Vec<NodeId> {
794        if let Some(focused) = cranpose_ui::active_focus_target() {
795            if let Some(target) = self.renderer.scene().find_target(focused) {
796                let path = target.capture_path();
797                if !path.is_empty() {
798                    return crate::hit_path_tracker::dispatch_order_for_paths(&[path]);
799                }
800            }
801        }
802
803        let hits = self.renderer.scene().hit_test(self.cursor.0, self.cursor.1);
804        if hits.is_empty() {
805            return Vec::new();
806        }
807        let capture_paths = hits
808            .iter()
809            .map(|hit| hit.capture_path())
810            .collect::<Vec<_>>();
811        crate::hit_path_tracker::dispatch_order_for_paths(&capture_paths)
812    }
813
814    /// Cancels any active gesture, dispatching Cancel events to cached targets.
815    /// Call this when:
816    /// - Window loses focus
817    /// - Mouse leaves window while button pressed
818    /// - Any other gesture abort scenario
819    pub fn cancel_gesture(&mut self) {
820        let event_time = self.realtime_pointer_event_time(None);
821        let _event_handler = enter_event_handler_scope();
822        let app_context = Rc::clone(&self.app_context);
823        let _ = app_context.enter(|| {
824            run_in_mutable_snapshot(|| {
825                self.cancel_gesture_inner(event_time);
826            })
827        });
828    }
829
830    fn cancel_gesture_inner(&mut self, event_time: PointerEventTime) {
831        let targets = self.resolve_gesture_targets(PointerId::PRIMARY);
832
833        // Clear tracker and button state
834        self.hit_path_tracker.clear();
835        self.buttons_pressed = PointerButtons::NONE;
836
837        if !targets.is_empty() {
838            let event = self
839                .pointer_event(
840                    PointerEventKind::Cancel,
841                    Point {
842                        x: self.cursor.0,
843                        y: self.cursor.1,
844                    },
845                    Point {
846                        x: self.cursor.0,
847                        y: self.cursor.1,
848                    },
849                    event_time,
850                )
851                .with_source(self.pointer_source);
852
853            self.dispatch_targets(targets, event, false);
854        }
855
856        // Dispatch Exit to all previously hovered nodes
857        let pos = Point {
858            x: self.cursor.0,
859            y: self.cursor.1,
860        };
861        let hovered_nodes = self.hovered_nodes.clone();
862        for node_id in hovered_nodes {
863            if let Some(target) = self.renderer.scene().find_target(node_id) {
864                let exit_event = self
865                    .pointer_event(PointerEventKind::Exit, pos, pos, event_time)
866                    .with_source(self.pointer_source);
867                self.dispatch_targets(std::iter::once(target), exit_event, false);
868            }
869        }
870        self.hovered_nodes.clear();
871    }
872
873    /// Installs the platform soft-keyboard handler for this shell's app context.
874    ///
875    /// The handler is invoked when a text field gains focus (`show_keyboard`)
876    /// or when text-field focus is cleared or goes stale (`hide_keyboard`).
877    /// Platform runtimes with an on-screen keyboard (Android, iOS) call this
878    /// once after creating the shell.
879    pub fn set_platform_text_input(
880        &mut self,
881        handler: Rc<dyn cranpose_ui::PlatformTextInputHandler>,
882    ) {
883        let app_context = Rc::clone(&self.app_context);
884        app_context
885            .enter(|| cranpose_ui::text_input_session::set_platform_text_input_handler(handler));
886    }
887
888    /// Removes the platform soft-keyboard handler, if one is installed.
889    pub fn clear_platform_text_input(&mut self) {
890        let app_context = Rc::clone(&self.app_context);
891        app_context.enter(cranpose_ui::text_input_session::clear_platform_text_input_handler);
892    }
893
894    /// Notifies the framework that the host app was paused/backgrounded.
895    ///
896    /// Withdraws any outstanding soft-keyboard request (and hides the keyboard)
897    /// so the "keyboard shown" state does not survive across the pause and get
898    /// restored on resume with no focused field. Platform runtimes call this
899    /// from their pause lifecycle event.
900    pub fn notify_app_paused(&mut self) {
901        let app_context = Rc::clone(&self.app_context);
902        app_context.enter(cranpose_ui::text_input_session::notify_app_paused);
903    }
904
905    /// Notifies the framework that the host app resumed/foregrounded.
906    ///
907    /// Never auto-shows the soft keyboard, even for a still-focused field: a
908    /// warm resume keeps the caret but must not resurrect the keyboard (the user
909    /// taps the field to bring it back). Always returns `false` so the platform
910    /// runtime force-hides the OS-restored keyboard. Platform runtimes call this
911    /// from their resume lifecycle event.
912    pub fn notify_app_resumed(&mut self) -> bool {
913        let app_context = Rc::clone(&self.app_context);
914        app_context.enter(cranpose_ui::text_input_session::notify_app_resumed)
915    }
916
917    /// Routes a keyboard event to the focused text field, if any.
918    ///
919    /// Returns `true` if the event was consumed by a text field.
920    ///
921    /// On desktop, Ctrl+C/X/V are handled here when native clipboard support is enabled.
922    /// On web, these keys are NOT handled here - they bubble to browser for native copy/paste events.
923    pub fn on_key_event(&mut self, event: &KeyEvent) -> bool {
924        let _event_handler = enter_event_handler_scope();
925        let app_context = Rc::clone(&self.app_context);
926        app_context.enter(|| self.on_key_event_inner(event))
927    }
928
929    /// Internal keyboard event handler wrapped by on_key_event.
930    fn on_key_event_inner(&mut self, event: &KeyEvent) -> bool {
931        use KeyEventType::KeyDown;
932
933        // Only process KeyDown events for clipboard shortcuts
934        if event.event_type == KeyDown && event.modifiers.command_or_ctrl() {
935            #[cfg(all(
936                feature = "clipboard-native",
937                not(target_arch = "wasm32"),
938                not(target_os = "android"),
939                not(target_os = "ios")
940            ))]
941            {
942                match event.key_code {
943                    // Ctrl+C - Copy
944                    KeyCode::C => {
945                        if let Some(text) = self.on_copy_inner() {
946                            cranpose_ui::clipboard_session::clipboard_write_text(&text);
947                            return true;
948                        }
949                    }
950                    // Ctrl+X - Cut
951                    KeyCode::X => {
952                        if let Some(text) = self.on_cut_inner() {
953                            cranpose_ui::clipboard_session::clipboard_write_text(&text);
954                            self.mark_dirty();
955                            self.request_layout_pass();
956                            return true;
957                        }
958                    }
959                    // Ctrl+V - Paste
960                    KeyCode::V => {
961                        if let Some(text) = cranpose_ui::clipboard_session::clipboard_read_text() {
962                            if self.on_paste_inner(&text) {
963                                return true;
964                            }
965                        }
966                    }
967                    _ => {}
968                }
969            }
970        }
971
972        // Pure O(1) dispatch - no tree walking needed
973        if !cranpose_ui::text_field_focus::has_focused_field() {
974            return false;
975        }
976
977        // Wrap key event handling in a mutable snapshot so changes are atomically applied.
978        // This ensures keyboard input modifications are visible to subsequent snapshot contexts
979        // (like button click handlers that run in their own mutable snapshots).
980        let handled = run_in_mutable_snapshot(|| {
981            // O(1) dispatch via stored handler - handles ALL text input key events
982            // No fallback needed since handler now handles arrows, Home/End, word nav
983            cranpose_ui::text_field_focus::dispatch_key_event(event)
984        })
985        .unwrap_or(false);
986
987        if handled {
988            // Mark both dirty (for redraw) and request a layout pass to rebuild semantics.
989            self.mark_dirty();
990            self.request_layout_pass();
991        }
992
993        handled
994    }
995
996    /// Handles paste event from platform clipboard.
997    /// Returns `true` if the paste was consumed by a focused text field.
998    /// O(1) operation using stored handler.
999    pub fn on_paste(&mut self, text: &str) -> bool {
1000        let _event_handler = enter_event_handler_scope();
1001        let app_context = Rc::clone(&self.app_context);
1002        app_context.enter(|| self.on_paste_inner(text))
1003    }
1004
1005    fn on_paste_inner(&mut self, text: &str) -> bool {
1006        // Wrap paste in a mutable snapshot so changes are atomically applied.
1007        // This ensures paste modifications are visible to subsequent snapshot contexts
1008        // (like button click handlers that run in their own mutable snapshots).
1009        let handled =
1010            run_in_mutable_snapshot(|| cranpose_ui::text_field_focus::dispatch_paste(text))
1011                .unwrap_or(false);
1012
1013        if handled {
1014            self.mark_dirty();
1015            self.request_layout_pass();
1016        }
1017
1018        handled
1019    }
1020
1021    /// Handles copy request from platform.
1022    /// Returns the selected text from focused text field, or None.
1023    /// O(1) operation using stored handler.
1024    pub fn on_copy(&mut self) -> Option<String> {
1025        let app_context = Rc::clone(&self.app_context);
1026        app_context.enter(|| self.on_copy_inner())
1027    }
1028
1029    fn on_copy_inner(&mut self) -> Option<String> {
1030        // Use O(1) dispatch instead of tree scan
1031        cranpose_ui::text_field_focus::dispatch_copy()
1032    }
1033
1034    /// Handles cut request from platform.
1035    /// Returns the cut text from focused text field, or None.
1036    /// O(1) operation using stored handler.
1037    pub fn on_cut(&mut self) -> Option<String> {
1038        let _event_handler = enter_event_handler_scope();
1039        let app_context = Rc::clone(&self.app_context);
1040        app_context.enter(|| self.on_cut_inner())
1041    }
1042
1043    fn on_cut_inner(&mut self) -> Option<String> {
1044        let text =
1045            run_in_mutable_snapshot(cranpose_ui::text_field_focus::dispatch_cut).unwrap_or(None);
1046
1047        if text.is_some() {
1048            self.mark_dirty();
1049            self.request_layout_pass();
1050        }
1051
1052        text
1053    }
1054
1055    /// Sets the Linux primary selection (for middle-click paste).
1056    /// This is called when text is selected in a text field.
1057    /// On non-Linux platforms, this is a no-op.
1058    #[cfg(all(
1059        feature = "clipboard-native",
1060        target_os = "linux",
1061        not(target_arch = "wasm32")
1062    ))]
1063    pub fn set_primary_selection(&mut self, text: &str) {
1064        use arboard::{LinuxClipboardKind, SetExtLinux};
1065        if let Some(ref mut clipboard) = self.clipboard {
1066            let result = clipboard
1067                .set()
1068                .clipboard(LinuxClipboardKind::Primary)
1069                .text(text.to_string());
1070            if let Err(e) = result {
1071                // Primary selection may not be available on all systems
1072                log::debug!("Primary selection set failed: {:?}", e);
1073            }
1074        }
1075    }
1076
1077    #[cfg(not(all(
1078        feature = "clipboard-native",
1079        target_os = "linux",
1080        not(target_arch = "wasm32")
1081    )))]
1082    pub fn set_primary_selection(&mut self, _text: &str) {}
1083
1084    /// Gets text from the Linux primary selection (for middle-click paste).
1085    /// On non-Linux platforms, returns None.
1086    #[cfg(all(
1087        feature = "clipboard-native",
1088        target_os = "linux",
1089        not(target_arch = "wasm32")
1090    ))]
1091    pub fn get_primary_selection(&mut self) -> Option<String> {
1092        use arboard::{GetExtLinux, LinuxClipboardKind};
1093        if let Some(ref mut clipboard) = self.clipboard {
1094            clipboard
1095                .get()
1096                .clipboard(LinuxClipboardKind::Primary)
1097                .text()
1098                .ok()
1099        } else {
1100            None
1101        }
1102    }
1103
1104    #[cfg(not(all(
1105        feature = "clipboard-native",
1106        target_os = "linux",
1107        not(target_arch = "wasm32")
1108    )))]
1109    pub fn get_primary_selection(&mut self) -> Option<String> {
1110        None
1111    }
1112
1113    /// Syncs the current text field selection to PRIMARY (Linux X11).
1114    /// Call this when selection changes in a text field.
1115    pub fn sync_selection_to_primary(&mut self) {
1116        #[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
1117        {
1118            if let Some(text) = self.on_copy() {
1119                self.set_primary_selection(&text);
1120            }
1121        }
1122    }
1123
1124    /// Handles IME preedit (composition) events.
1125    /// Called when the input method is composing text (e.g., typing CJK characters).
1126    ///
1127    /// - `text`: The current preedit text (empty to clear composition state)
1128    /// - `cursor`: Optional cursor position within the preedit text (start, end)
1129    ///
1130    /// Returns `true` if a text field consumed the event.
1131    pub fn on_ime_preedit(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1132        let _event_handler = enter_event_handler_scope();
1133        let app_context = Rc::clone(&self.app_context);
1134        app_context.enter(|| self.on_ime_preedit_inner(text, cursor))
1135    }
1136
1137    fn on_ime_preedit_inner(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1138        // Wrap in mutable snapshot for atomic changes
1139        let handled = run_in_mutable_snapshot(|| {
1140            cranpose_ui::text_field_focus::dispatch_ime_preedit(text, cursor)
1141        })
1142        .unwrap_or(false);
1143
1144        if handled {
1145            self.mark_dirty();
1146            // IME composition changes the visible text, needs layout update
1147            self.request_layout_pass();
1148        }
1149
1150        handled
1151    }
1152
1153    /// Finishes the active IME composition, keeping the composed text as
1154    /// committed text (Android `finishComposingText` semantics).
1155    /// Returns `true` if a text field consumed the event.
1156    pub fn on_ime_finish_composing(&mut self) -> bool {
1157        let _event_handler = enter_event_handler_scope();
1158        let app_context = Rc::clone(&self.app_context);
1159        app_context.enter(|| self.on_ime_finish_composing_inner())
1160    }
1161
1162    fn on_ime_finish_composing_inner(&mut self) -> bool {
1163        let handled =
1164            run_in_mutable_snapshot(cranpose_ui::text_field_focus::dispatch_ime_finish_composing)
1165                .unwrap_or(false);
1166
1167        if handled {
1168            self.mark_dirty();
1169            self.request_layout_pass();
1170        }
1171
1172        handled
1173    }
1174
1175    /// Marks existing text in the focused field as the composing region
1176    /// without changing it (Android `setComposingRegion` semantics). Offsets
1177    /// are UTF-8 bytes. Returns `true` if a text field consumed the event.
1178    pub fn on_ime_set_composing_region(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1179        let _event_handler = enter_event_handler_scope();
1180        let app_context = Rc::clone(&self.app_context);
1181        app_context.enter(|| {
1182            let handled = run_in_mutable_snapshot(|| {
1183                cranpose_ui::text_field_focus::dispatch_ime_set_composing_region(
1184                    start_bytes,
1185                    end_bytes,
1186                )
1187            })
1188            .unwrap_or(false);
1189
1190            if handled {
1191                self.mark_dirty();
1192                self.request_layout_pass();
1193            }
1194
1195            handled
1196        })
1197    }
1198
1199    /// Moves the focused field's selection/caret to `[start_bytes, end_bytes)`
1200    /// without editing text (Android `InputConnection.setSelection`; the path
1201    /// Gboard's spacebar-swipe uses to scrub the cursor). Offsets are UTF-8
1202    /// bytes. Returns `true` if a text field consumed the event.
1203    pub fn on_ime_set_selection(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1204        let _event_handler = enter_event_handler_scope();
1205        let app_context = Rc::clone(&self.app_context);
1206        app_context.enter(|| {
1207            let handled = run_in_mutable_snapshot(|| {
1208                cranpose_ui::text_field_focus::dispatch_ime_set_selection(start_bytes, end_bytes)
1209            })
1210            .unwrap_or(false);
1211
1212            // A selection-only change never reflows text, so it needs a redraw
1213            // but not a layout pass.
1214            if handled {
1215                self.mark_dirty();
1216            }
1217
1218            handled
1219        })
1220    }
1221
1222    /// Returns a snapshot of the focused text field's editable state for
1223    /// platform IMEs (text, selection and composition in UTF-8 bytes), or
1224    /// `None` when no text field is focused.
1225    pub fn ime_editor_state(&mut self) -> Option<cranpose_ui::text_field_focus::ImeEditorState> {
1226        let app_context = Rc::clone(&self.app_context);
1227        app_context.enter(cranpose_ui::text_field_focus::focused_editor_state)
1228    }
1229
1230    /// Window-space caret geometry of the focused field for coordinate-based
1231    /// platform text input (iOS trackpad cursor + tap-to-position), or `None`
1232    /// when no text field is focused.
1233    pub fn ime_caret_geometry(
1234        &mut self,
1235    ) -> Option<cranpose_ui::text_field_focus::ImeCaretGeometry> {
1236        let app_context = Rc::clone(&self.app_context);
1237        app_context.enter(cranpose_ui::text_field_focus::focused_caret_geometry)
1238    }
1239
1240    /// Clears text-field focus (used by platform IME actions such as
1241    /// Android's Done). The focus-loss notification hides the soft keyboard.
1242    pub fn clear_text_field_focus(&mut self) {
1243        let _event_handler = enter_event_handler_scope();
1244        let app_context = Rc::clone(&self.app_context);
1245        app_context.enter(cranpose_ui::text_field_focus::clear_focus);
1246        self.mark_dirty();
1247        self.request_layout_pass();
1248    }
1249
1250    /// Handles IME delete-surrounding events.
1251    /// Returns `true` if a text field consumed the event.
1252    pub fn on_ime_delete_surrounding(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
1253        let _event_handler = enter_event_handler_scope();
1254        let app_context = Rc::clone(&self.app_context);
1255        app_context.enter(|| self.on_ime_delete_surrounding_inner(before_bytes, after_bytes))
1256    }
1257
1258    fn on_ime_delete_surrounding_inner(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
1259        let handled = run_in_mutable_snapshot(|| {
1260            cranpose_ui::text_field_focus::dispatch_delete_surrounding(before_bytes, after_bytes)
1261        })
1262        .unwrap_or(false);
1263
1264        if handled {
1265            self.mark_dirty();
1266            self.request_layout_pass();
1267        }
1268
1269        handled
1270    }
1271}