Skip to main content

cranpose_app_shell/
shell_input.rs

1use cranpose_ui::FocusDirection;
2
3use super::*;
4
5mod dispatch_stop;
6pub(crate) mod extra_pointers;
7pub(crate) mod key_activation;
8mod key_navigation;
9
10use dispatch_stop::Stop;
11use extra_pointers::Hover;
12
13impl<R> SurfaceMut<'_, R>
14where
15    R: Renderer,
16    R::Error: Debug,
17{
18    fn pointer_event(
19        &self,
20        kind: PointerEventKind,
21        position: Point,
22        global_position: Point,
23        event_time: PointerEventTime,
24    ) -> PointerEvent {
25        let screen_position = self.surface().screen_origin.map(|origin| Point {
26            x: origin.x + global_position.x,
27            y: origin.y + global_position.y,
28        });
29        let mut event = event_time
30            .stamp(PointerEvent::new(kind, position, global_position))
31            .with_screen_position(screen_position);
32        event.modifiers = self.shell.app.modifiers;
33        event
34    }
35
36    fn resolve_gesture_targets(
37        &self,
38        pointer: PointerId,
39    ) -> Vec<<<R as Renderer>::Scene as RenderScene>::HitTarget> {
40        self.resolve_hit_path(pointer)
41    }
42
43    fn resolve_hit_path(
44        &self,
45        pointer: PointerId,
46    ) -> Vec<<<R as Renderer>::Scene as RenderScene>::HitTarget> {
47        let Some(node_ids) = self.surface().hit_path_tracker.dispatch_order(pointer) else {
48            return Vec::new();
49        };
50
51        let scene = self.surface().renderer.scene();
52        let targets: Vec<_> = node_ids
53            .iter()
54            .filter_map(|&id| scene.find_target(id))
55            .collect();
56        log::trace!(
57            target: "cranpose::input",
58            "resolve_hit_path pointer={pointer:?} cached={node_ids:?} resolved_count={}",
59            targets.len()
60        );
61        targets
62    }
63
64    fn dispatch_targets<I>(&mut self, targets: I, event: PointerEvent, stop: Stop)
65    where
66        I: IntoIterator<Item = <<R as Renderer>::Scene as RenderScene>::HitTarget>,
67    {
68        let mut applier = self.shell.app.composition.applier_mut();
69        for target in targets {
70            let node_id = target.node_id();
71            target.dispatch_with_applier(&mut applier, event.clone());
72            log::trace!(
73                target: "cranpose::input",
74                "dispatch {:?} node={} consumed={} stop={:?}",
75                event.kind,
76                node_id,
77                event.is_consumed(),
78                stop,
79            );
80            if stop == Stop::AtConsumer && event.is_consumed() {
81                break;
82            }
83        }
84        event.finish_post_dispatch();
85    }
86
87    fn dispatch_to_hits(
88        &mut self,
89        hits: &[<<R as Renderer>::Scene as RenderScene>::HitTarget],
90        event: PointerEvent,
91    ) -> bool {
92        let capture_paths = hits
93            .iter()
94            .map(HitTestTarget::capture_path)
95            .collect::<Vec<_>>();
96        let targets = hit_path_tracker::dispatch_order_for_paths(&capture_paths)
97            .into_iter()
98            .filter_map(|node_id| self.surface().renderer.scene().find_target(node_id))
99            .collect::<Vec<_>>();
100
101        self.dispatch_targets(targets, event.clone(), Stop::AtConsumer);
102
103        event.is_consumed()
104    }
105
106    /// Sets the device source (touch/mouse/stylus) of the pointer sample that
107    /// the platform is about to dispatch. Call this before `set_cursor` /
108    /// `pointer_pressed` / `pointer_released` so the resulting `PointerEvent`s
109    /// carry the source so consumers can preserve device-specific gesture
110    /// details without changing shared pointer UI.
111    pub fn set_pointer_source(&mut self, source: PointerSource) {
112        self.surface_mut().pointer_source = source;
113    }
114
115    /// The device source of the most recent pointer sample.
116    pub fn pointer_source(&self) -> PointerSource {
117        self.surface().pointer_source
118    }
119
120    /// Moves the pointer to `(x, y)` in logical pixels and sends the enter, exit, move or drag
121    /// events that follow. Returns `true` when a control or overlay handled the move.
122    pub fn set_cursor(&mut self, x: f32, y: f32) -> bool {
123        self.set_cursor_at_time(x, y, None)
124    }
125
126    /// Like [`set_cursor`](Self::set_cursor), but carries the platform input
127    /// timestamp (milliseconds, platform-specific time base) of the sample.
128    ///
129    /// Platforms that deliver input batched/frame-aligned (Android) must use
130    /// this so gesture velocity is computed from real event times instead of
131    /// delivery times.
132    pub fn set_cursor_at_time(&mut self, x: f32, y: f32, time_ms: Option<i64>) -> bool {
133        let event_time = self.shell.app.realtime_pointer_event_time(time_ms);
134        self.set_cursor_at_event_time(x, y, event_time)
135    }
136
137    /// Set the cursor using a timestamp already resolved into both clock domains.
138    pub fn set_cursor_at_event_time(
139        &mut self,
140        x: f32,
141        y: f32,
142        event_time: PointerEventTime,
143    ) -> bool {
144        let _event_handler = enter_event_handler_scope();
145        let result = {
146            let _app_context = self.shell.app.app_context.enter_scope();
147            run_in_mutable_snapshot(|| self.set_cursor_inner(x, y, event_time)).unwrap_or(false)
148        };
149        self.route_drag_and_drop();
150        if result {
151            self.mark_dirty();
152        }
153        log::trace!(
154            target: "cranpose::input",
155            "set_cursor ({x:.2},{y:.2}) time_ms={:?} animation_time_nanos={} -> {result}",
156            event_time.platform_time_ms,
157            event_time.animation_time_nanos,
158        );
159        result
160    }
161
162    fn set_cursor_inner(&mut self, x: f32, y: f32, event_time: PointerEventTime) -> bool {
163        self.surface_mut().cursor = (x, y);
164        if self.inspector_move(x, y) {
165            return true;
166        }
167
168        if self.surface().buttons_pressed != PointerButtons::NONE {
169            if self.surface().hit_path_tracker.has_path(PointerId::PRIMARY) {
170                let targets = self.resolve_gesture_targets(PointerId::PRIMARY);
171                if !targets.is_empty() {
172                    let event = self
173                        .pointer_event(
174                            PointerEventKind::Move,
175                            Point { x, y },
176                            Point { x, y },
177                            event_time,
178                        )
179                        .with_buttons(self.surface().buttons_pressed)
180                        .with_source(self.surface().pointer_source);
181                    self.dispatch_targets(targets, event, Stop::Never);
182                    return true;
183                }
184
185                return false;
186            }
187
188            return false;
189        }
190
191        let hits = if self.inspector_blocks_pointer(x, y) {
192            Vec::new()
193        } else {
194            self.surface().renderer.scene().hit_test(x, y)
195        };
196        let new_ids: Vec<NodeId> = hits.iter().map(HitTestTarget::node_id).collect();
197
198        let pos = Point { x, y };
199        let previously_hovered = self.surface().hovered_nodes.clone();
200        self.send_hover_changes(
201            Hover {
202                pointer: PointerId::PRIMARY,
203                hovered: &previously_hovered,
204                at: pos,
205                buttons: self.surface().buttons_pressed,
206                time: event_time,
207            },
208            &hits,
209        );
210        self.surface_mut().hovered_nodes = new_ids;
211        self.apply_hovered_pointer_icon(&hits);
212
213        if !hits.is_empty() {
214            let event = self
215                .pointer_event(PointerEventKind::Move, pos, pos, event_time)
216                .with_buttons(self.surface().buttons_pressed)
217                .with_source(self.surface().pointer_source);
218            self.dispatch_targets(hits, event, Stop::AtConsumer);
219            true
220        } else {
221            false
222        }
223    }
224
225    /// Presses the primary pointer button at the position set by `set_cursor`. Returns `true` when
226    /// a control or overlay handled the press.
227    pub fn pointer_pressed(&mut self) -> bool {
228        self.pointer_pressed_at_time(None)
229    }
230
231    /// Like [`pointer_pressed`](Self::pointer_pressed), but carries the
232    /// platform input timestamp (milliseconds) of the press sample.
233    pub fn pointer_pressed_at_time(&mut self, time_ms: Option<i64>) -> bool {
234        let event_time = self.shell.app.realtime_pointer_event_time(time_ms);
235        self.pointer_pressed_at_event_time(event_time)
236    }
237
238    /// Dispatch primary-button down with an already resolved event timestamp.
239    pub fn pointer_pressed_at_event_time(&mut self, event_time: PointerEventTime) -> bool {
240        let (cursor_x, cursor_y) = self.surface().cursor;
241        if self.inspector_press(cursor_x, cursor_y) {
242            return true;
243        }
244        if self.dev_overlay_press(cursor_x, cursor_y) {
245            return true;
246        }
247        let _event_handler = enter_event_handler_scope();
248        let result = {
249            let _app_context = self.shell.app.app_context.enter_scope();
250            run_in_mutable_snapshot(|| self.pointer_pressed_inner(event_time)).unwrap_or(false)
251        };
252        if result {
253            self.mark_dirty();
254        }
255        log::trace!(
256            target: "cranpose::input",
257            "pointer_pressed time_ms={:?} animation_time_nanos={} -> {result}",
258            event_time.platform_time_ms,
259            event_time.animation_time_nanos,
260        );
261        result
262    }
263
264    fn pointer_pressed_inner(&mut self, event_time: PointerEventTime) -> bool {
265        self.activate();
266        self.note_focus_moved_by_keyboard(false);
267        self.surface_mut()
268            .buttons_pressed
269            .insert(PointerButton::Primary);
270
271        let (cursor_x, cursor_y) = self.surface().cursor;
272        let mut hits = self.surface().renderer.scene().hit_test(cursor_x, cursor_y);
273        if self.surface().pointer_source.is_touch_like()
274            && let Some(near) = self
275                .surface()
276                .renderer
277                .scene()
278                .hit_test_near(cursor_x, cursor_y)
279            && hits.iter().all(|hit| {
280                hit.node_id() != near.node_id() && near.capture_path().contains(&hit.node_id())
281            })
282        {
283            hits.insert(0, near);
284        }
285        let event = self.cursor_event(PointerEventKind::Down, event_time);
286        self.press_hits(hits, event, PointerId::PRIMARY)
287    }
288
289    /// An event of `kind` at the cursor, with the buttons held and the
290    /// pointer's source.
291    fn cursor_event(&self, kind: PointerEventKind, event_time: PointerEventTime) -> PointerEvent {
292        let (x, y) = self.surface().cursor;
293        self.pointer_event(kind, Point { x, y }, Point { x, y }, event_time)
294            .with_buttons(self.surface().buttons_pressed)
295            .with_source(self.surface().pointer_source)
296    }
297
298    /// Delivers a press to `hits`, nearest first, until one consumes it, and
299    /// keeps the paths it reached as `pointer`'s gesture targets.
300    fn press_hits(
301        &mut self,
302        hits: Vec<<<R as Renderer>::Scene as RenderScene>::HitTarget>,
303        event: PointerEvent,
304        pointer: PointerId,
305    ) -> bool {
306        if hits.is_empty() {
307            self.surface_mut().hit_path_tracker.remove_path(pointer);
308            return false;
309        }
310        let mut delivered_capture_paths = Vec::new();
311        let (app, surface) = self.parts();
312        let mut applier = app.composition.applier_mut();
313        for hit in hits {
314            let node_id = hit.node_id();
315            delivered_capture_paths.push(hit.capture_path());
316            hit.dispatch_with_applier(&mut applier, event.clone());
317            log::trace!(
318                target: "cranpose::input",
319                "dispatch {:?} node={} consumed={} stop=AtConsumer",
320                event.kind,
321                node_id,
322                event.is_consumed(),
323            );
324            if event.is_consumed() {
325                break;
326            }
327        }
328
329        surface
330            .hit_path_tracker
331            .add_hit_path(pointer, delivered_capture_paths);
332        log::trace!(
333            target: "cranpose::input",
334            "press cached_hit_path={:?}",
335            surface.hit_path_tracker.get_path(pointer),
336        );
337        true
338    }
339
340    /// Presses `button` of the mouse at the position set by `set_cursor`.
341    /// The primary button presses as [`pointer_pressed`](Self::pointer_pressed)
342    /// does. Another button reaches the nodes under the pointer as a
343    /// [`PointerEventKind::ButtonDown`], or, while a button is already down,
344    /// the nodes that took its press; those nodes take the moves until the
345    /// last button goes up. Returns `true` when a node received the press.
346    pub fn mouse_button_pressed(&mut self, button: PointerButton) -> bool {
347        if button == PointerButton::Primary {
348            return self.pointer_pressed();
349        }
350        self.mouse_button_change(|surface, event_time| {
351            surface.other_button_pressed(button, event_time)
352        })
353    }
354
355    /// Releases `button` of the mouse. The primary button releases as
356    /// [`pointer_released`](Self::pointer_released) does; another reaches the
357    /// nodes that took the press as a [`PointerEventKind::ButtonUp`]. Returns
358    /// `true` when a node received the release.
359    pub fn mouse_button_released(&mut self, button: PointerButton) -> bool {
360        if button == PointerButton::Primary {
361            return self.pointer_released();
362        }
363        self.mouse_button_change(|surface, event_time| {
364            surface.other_button_released(button, event_time)
365        })
366    }
367
368    fn mouse_button_change(
369        &mut self,
370        change: impl FnOnce(&mut Self, PointerEventTime) -> bool,
371    ) -> bool {
372        let event_time = self.shell.app.realtime_pointer_event_time(None);
373        let _event_handler = enter_event_handler_scope();
374        let result = {
375            let _app_context = self.shell.app.app_context.enter_scope();
376            run_in_mutable_snapshot(|| change(self, event_time)).unwrap_or(false)
377        };
378        if result {
379            self.mark_dirty();
380        }
381        result
382    }
383
384    fn other_button_pressed(
385        &mut self,
386        button: PointerButton,
387        event_time: PointerEventTime,
388    ) -> bool {
389        self.activate();
390        let first = self.surface().buttons_pressed == PointerButtons::NONE;
391        self.surface_mut().buttons_pressed.insert(button);
392        let event = self.cursor_event(PointerEventKind::ButtonDown(button), event_time);
393        if first {
394            let (x, y) = self.surface().cursor;
395            let hits = self.surface().renderer.scene().hit_test(x, y);
396            return self.press_hits(hits, event, PointerId::PRIMARY);
397        }
398        let targets = self.resolve_gesture_targets(PointerId::PRIMARY);
399        if targets.is_empty() {
400            return false;
401        }
402        self.dispatch_targets(targets, event, Stop::Never);
403        true
404    }
405
406    fn other_button_released(
407        &mut self,
408        button: PointerButton,
409        event_time: PointerEventTime,
410    ) -> bool {
411        if !self.surface().buttons_pressed.contains(button) {
412            return false;
413        }
414        self.surface_mut().buttons_pressed.remove(button);
415        let targets = self.resolve_gesture_targets(PointerId::PRIMARY);
416        if self.surface().buttons_pressed == PointerButtons::NONE {
417            self.surface_mut()
418                .hit_path_tracker
419                .remove_path(PointerId::PRIMARY);
420        }
421        if targets.is_empty() {
422            return false;
423        }
424        let event = self.cursor_event(PointerEventKind::ButtonUp(button), event_time);
425        self.dispatch_targets(targets, event, Stop::Never);
426        true
427    }
428
429    /// Releases the primary pointer button at the position set by `set_cursor`. Returns `true` when
430    /// a control or overlay handled the release.
431    pub fn pointer_released(&mut self) -> bool {
432        self.pointer_released_at_time(None)
433    }
434
435    /// Releases the pointer at the position carried by the platform's release
436    /// sample (Android `ACTION_UP`, web `pointerup`/`touchend`).
437    ///
438    /// The cursor is moved to `(x, y)` WITHOUT dispatching a Move event, then
439    /// the Up event is dispatched at that position. Platforms whose release
440    /// events carry their own coordinates must use this instead of
441    /// `set_cursor* + pointer_released*`: lift-off samples routinely roll back
442    /// a few dp against the travel direction as the finger peels off, and
443    /// feeding that jitter into gesture velocity trackers as a final Move
444    /// sample can flip the sign of the computed fling velocity (flings that
445    /// suddenly go the opposite way). Jetpack Compose likewise never feeds the
446    /// up sample into velocity tracking.
447    pub fn pointer_released_at_position(&mut self, x: f32, y: f32) -> bool {
448        self.pointer_released_at_position_time(x, y, None)
449    }
450
451    /// Like [`pointer_released_at_position`](Self::pointer_released_at_position),
452    /// but carries the platform input timestamp (milliseconds) of the release
453    /// sample.
454    pub fn pointer_released_at_position_time(
455        &mut self,
456        x: f32,
457        y: f32,
458        time_ms: Option<i64>,
459    ) -> bool {
460        let event_time = self.shell.app.realtime_pointer_event_time(time_ms);
461        self.pointer_released_at_position_event_time(x, y, event_time)
462    }
463
464    /// Release at a position with an already resolved event timestamp.
465    pub fn pointer_released_at_position_event_time(
466        &mut self,
467        x: f32,
468        y: f32,
469        event_time: PointerEventTime,
470    ) -> bool {
471        let _event_handler = enter_event_handler_scope();
472        let result = {
473            let _app_context = self.shell.app.app_context.enter_scope();
474            run_in_mutable_snapshot(|| {
475                self.surface_mut().cursor = (x, y);
476                self.pointer_released_inner(event_time)
477            })
478            .unwrap_or(false)
479        };
480        self.route_drag_and_drop();
481        if result {
482            self.mark_dirty();
483        }
484        log::trace!(
485            target: "cranpose::input",
486            "pointer_released_at_position ({x:.2},{y:.2}) time_ms={:?} animation_time_nanos={} -> {result}",
487            event_time.platform_time_ms,
488            event_time.animation_time_nanos,
489        );
490        result
491    }
492
493    /// Like [`pointer_released`](Self::pointer_released), but carries the
494    /// platform input timestamp (milliseconds) of the release sample.
495    pub fn pointer_released_at_time(&mut self, time_ms: Option<i64>) -> bool {
496        let event_time = self.shell.app.realtime_pointer_event_time(time_ms);
497        self.pointer_released_at_event_time(event_time)
498    }
499
500    /// Dispatch primary-button up with an already resolved event timestamp.
501    pub fn pointer_released_at_event_time(&mut self, event_time: PointerEventTime) -> bool {
502        let _event_handler = enter_event_handler_scope();
503        let result = {
504            let _app_context = self.shell.app.app_context.enter_scope();
505            run_in_mutable_snapshot(|| self.pointer_released_inner(event_time)).unwrap_or(false)
506        };
507        self.route_drag_and_drop();
508        if result {
509            self.mark_dirty();
510        }
511        log::trace!(
512            target: "cranpose::input",
513            "pointer_released time_ms={:?} animation_time_nanos={} -> {result}",
514            event_time.platform_time_ms,
515            event_time.animation_time_nanos,
516        );
517        result
518    }
519
520    fn pointer_released_inner(&mut self, event_time: PointerEventTime) -> bool {
521        if self.surface_mut().inspector.release_pointer() {
522            return true;
523        }
524        self.release_app_pointer(event_time)
525    }
526
527    fn release_app_pointer(&mut self, event_time: PointerEventTime) -> bool {
528        self.surface_mut()
529            .buttons_pressed
530            .remove(PointerButton::Primary);
531        let corrected_buttons = self.surface().buttons_pressed;
532        let targets = self.resolve_gesture_targets(PointerId::PRIMARY);
533
534        // Another button still down keeps the gesture's targets for its
535        // moves and its release.
536        if corrected_buttons == PointerButtons::NONE {
537            self.surface_mut()
538                .hit_path_tracker
539                .remove_path(PointerId::PRIMARY);
540        }
541
542        if !targets.is_empty() {
543            let event = self
544                .pointer_event(
545                    PointerEventKind::Up,
546                    Point {
547                        x: self.surface().cursor.0,
548                        y: self.surface().cursor.1,
549                    },
550                    Point {
551                        x: self.surface().cursor.0,
552                        y: self.surface().cursor.1,
553                    },
554                    event_time,
555                )
556                .with_buttons(corrected_buttons)
557                .with_source(self.surface().pointer_source);
558
559            self.dispatch_targets(targets, event, Stop::Never);
560            true
561        } else {
562            false
563        }
564    }
565
566    /// Dispatches a discrete zoom step (desktop ctrl+wheel, browser pinch)
567    /// to the pointer handlers under the cursor.
568    ///
569    /// `zoom_factor` is multiplicative: `> 1.0` zooms in, `< 1.0` zooms out.
570    /// Returns `true` if a handler consumed the event.
571    pub fn pointer_zoomed(&mut self, zoom_factor: f32) -> bool {
572        let event_time = self.shell.app.realtime_pointer_event_time(None);
573        let _event_handler = enter_event_handler_scope();
574        let result = {
575            let _app_context = self.shell.app.app_context.enter_scope();
576            run_in_mutable_snapshot(|| self.pointer_zoomed_inner(zoom_factor, event_time))
577                .unwrap_or(false)
578        };
579        if result {
580            self.mark_dirty();
581        }
582        log::trace!(
583            target: "cranpose::input",
584            "pointer_zoomed factor={zoom_factor:.4} -> {result}"
585        );
586        result
587    }
588
589    fn pointer_zoomed_inner(&mut self, zoom_factor: f32, event_time: PointerEventTime) -> bool {
590        if !zoom_factor.is_finite() || zoom_factor <= 0.0 || zoom_factor == 1.0 {
591            return false;
592        }
593
594        let hits = self
595            .surface()
596            .renderer
597            .scene()
598            .hit_test(self.surface().cursor.0, self.surface().cursor.1);
599        if hits.is_empty() {
600            return false;
601        }
602
603        let pos = Point {
604            x: self.surface().cursor.0,
605            y: self.surface().cursor.1,
606        };
607        let event = self
608            .pointer_event(PointerEventKind::Zoom, pos, pos, event_time)
609            .with_buttons(self.surface().buttons_pressed)
610            .with_zoom_delta(zoom_factor)
611            .with_source(self.surface().pointer_source);
612
613        self.dispatch_to_hits(&hits, event)
614    }
615
616    /// Dispatches one mouse-wheel / trackpad sample through the whole wheel
617    /// policy, and returns `true` when something consumed it.
618    ///
619    /// This is the single entry point every host with a wheel calls, after
620    /// placing the cursor. A wheel sample is not just a scroll — it is whichever
621    /// of four things the modifiers and the tree make it, in this order:
622    ///
623    /// 1. **Zoom** when ctrl is held. That is the desktop convention and the
624    ///    way browsers deliver a trackpad pinch, so both arrive here as the
625    ///    same gesture.
626    /// 2. **Rotary**, offered to [`rotary_scrolled`](Self::rotary_scrolled)
627    ///    before anything else can take it, so the Wear OS crown stack is
628    ///    developable on a machine with a wheel. Nothing consumes rotary unless
629    ///    the app opts in via `Modifier::on_rotary_scroll_event` or
630    ///    [`set_on_rotary_scroll`](Self::set_on_rotary_scroll), so ordinary
631    ///    scrolling is unaffected.
632    /// 3. **Horizontal scroll** when alt is held on a wheel that only reports a
633    ///    vertical axis.
634    /// 4. **Scroll**, to the hovered scrollable.
635    ///
636    /// Hosts must not re-implement this order. Doing so is how the browser
637    /// ended up scrolling backwards and never delivering rotary at all: the
638    /// policy lived in the desktop event loop, and the second host that grew a
639    /// wheel reimplemented the parts of it that were obvious from the outside.
640    pub fn wheel_scrolled(&mut self, wheel: WheelScroll) -> bool {
641        if self.inspector_scroll(wheel.delta.y) {
642            return true;
643        }
644        if wheel.is_zoom() {
645            let zoom_factor = wheel.zoom_factor();
646            log::trace!(
647                target: "cranpose::input",
648                "wheel zoom factor={zoom_factor:.4}"
649            );
650            return self.pointer_zoomed(zoom_factor);
651        }
652
653        let rotary =
654            RotaryScrollEvent::from_wheel_pixels(wheel.delta.y, wheel.delta.x, wheel.uptime_millis);
655        if self.rotary_scrolled(rotary) {
656            return true;
657        }
658
659        let delta = wheel.scroll_delta();
660        log::trace!(
661            target: "cranpose::input",
662            "wheel delta ({:.2},{:.2}) alt={}",
663            delta.x,
664            delta.y,
665            wheel.modifiers.alt
666        );
667        self.pointer_scrolled(delta.x, delta.y)
668    }
669
670    /// Dispatches a mouse wheel / trackpad scroll event to hovered pointer handlers.
671    ///
672    /// Returns `true` if a handler consumed the event.
673    ///
674    /// This is the last step of the wheel policy, not its entry point: hosts
675    /// call [`wheel_scrolled`](Self::wheel_scrolled), which reaches here once
676    /// zoom and rotary have declined the sample.
677    pub fn pointer_scrolled(&mut self, delta_x: f32, delta_y: f32) -> bool {
678        if self.inspector_scroll(delta_y) {
679            return true;
680        }
681        let event_time = self.shell.app.realtime_pointer_event_time(None);
682        let _event_handler = enter_event_handler_scope();
683        let result = {
684            let _app_context = self.shell.app.app_context.enter_scope();
685            run_in_mutable_snapshot(|| self.pointer_scrolled_inner(delta_x, delta_y, event_time))
686                .unwrap_or(false)
687        };
688        if result {
689            self.mark_dirty();
690        }
691        log::trace!(
692            target: "cranpose::input",
693            "pointer_scrolled ({delta_x:.2},{delta_y:.2}) -> {result}"
694        );
695        result
696    }
697
698    fn pointer_scrolled_inner(
699        &mut self,
700        delta_x: f32,
701        delta_y: f32,
702        event_time: PointerEventTime,
703    ) -> bool {
704        if delta_x.abs() <= f32::EPSILON && delta_y.abs() <= f32::EPSILON {
705            return false;
706        }
707
708        let hits = self
709            .surface()
710            .renderer
711            .scene()
712            .hit_test(self.surface().cursor.0, self.surface().cursor.1);
713        if hits.is_empty() {
714            return false;
715        }
716
717        let event = self
718            .pointer_event(
719                PointerEventKind::Scroll,
720                Point {
721                    x: self.surface().cursor.0,
722                    y: self.surface().cursor.1,
723                },
724                Point {
725                    x: self.surface().cursor.0,
726                    y: self.surface().cursor.1,
727                },
728                event_time,
729            )
730            .with_buttons(self.surface().buttons_pressed)
731            .with_scroll_delta(Point {
732                x: delta_x,
733                y: delta_y,
734            })
735            .with_source(self.surface().pointer_source);
736
737        self.dispatch_to_hits(&hits, event)
738    }
739
740    /// Installs the window-level rotary (Wear OS crown / rotating bezel)
741    /// handler — the low-level escape hatch.
742    ///
743    /// The handler runs only after the routed modifier chain has declined the
744    /// event (see [`rotary_scrolled`](Self::rotary_scrolled)), so an app that
745    /// draws everything into a single canvas receives every rotary delta
746    /// without registering a focus target or a modifier. Returning `true`
747    /// reports the event as consumed to the platform.
748    ///
749    /// Passing a new handler replaces the previous one.
750    pub fn set_on_rotary_scroll<F>(&mut self, handler: F)
751    where
752        F: Fn(RotaryScrollEvent) -> bool + 'static,
753    {
754        self.surface_mut().on_rotary_scroll = Some(Rc::new(handler));
755    }
756
757    /// Removes the window-level rotary handler, if one is installed.
758    pub fn clear_on_rotary_scroll(&mut self) {
759        self.surface_mut().on_rotary_scroll = None;
760    }
761
762    /// Dispatches a rotary scroll expressed in raw detents (Android
763    /// `AXIS_SCROLL`), converting to pixels with the configured scroll factor.
764    ///
765    /// Applies Compose's sign convention: a positive detent value (crown turned
766    /// up/away) produces a negative `vertical_scroll_pixels`.
767    pub fn rotary_scrolled_by_detents(&mut self, detents: f32, uptime_millis: u64) -> bool {
768        let factor = self.shell.app.rotary_scroll_factor;
769        self.rotary_scrolled(RotaryScrollEvent::from_detents(
770            detents,
771            factor,
772            factor,
773            uptime_millis,
774        ))
775    }
776
777    /// Dispatches a rotary scroll event (Wear OS crown, Galaxy Watch bezel, or
778    /// a desktop mouse wheel standing in for one during development).
779    ///
780    /// Routing mirrors Compose's `RotaryInputModifierNode` contract:
781    ///
782    /// 1. Resolve the target chain. When a focus target is registered
783    ///    (`cranpose_ui::focus_dispatch::active_focus_target`) and still
784    ///    exists in the current scene, rotary uses the focus target's capture
785    ///    path. Otherwise, rotary uses the hit-test chain under the cursor.
786    /// 2. **Capture pass**, root to leaf, invoking `on_pre_rotary_scroll_event`
787    ///    handlers.
788    /// 3. **Bubble pass**, leaf to root, invoking `on_rotary_scroll_event`
789    ///    handlers.
790    /// 4. If still unconsumed, the window-level handler installed by
791    ///    [`set_on_rotary_scroll`](Self::set_on_rotary_scroll).
792    ///
793    /// The first handler returning `true` consumes the event and stops every
794    /// remaining step. Returns `true` when the event was consumed.
795    pub fn rotary_scrolled(&mut self, event: RotaryScrollEvent) -> bool {
796        let _event_handler = enter_event_handler_scope();
797        let result = {
798            let _app_context = self.shell.app.app_context.enter_scope();
799            run_in_mutable_snapshot(|| self.rotary_scrolled_inner(event)).unwrap_or(false)
800        };
801        if result {
802            self.mark_dirty();
803        }
804        log::trace!(
805            target: "cranpose::input",
806            "rotary_scrolled v={:.2} h={:.2} uptime={} -> {result}",
807            event.vertical_scroll_pixels,
808            event.horizontal_scroll_pixels,
809            event.uptime_millis,
810        );
811        result
812    }
813
814    fn rotary_scrolled_inner(&mut self, rotary: RotaryScrollEvent) -> bool {
815        if rotary.is_empty() {
816            return false;
817        }
818
819        let bubble_order = self.rotary_dispatch_order();
820        let position = Point {
821            x: self.surface().cursor.0,
822            y: self.surface().cursor.1,
823        };
824
825        if !bubble_order.is_empty() {
826            let capture_targets = bubble_order
827                .iter()
828                .rev()
829                .filter_map(|&node_id| self.surface().renderer.scene().find_target(node_id))
830                .collect::<Vec<_>>();
831            let mut capture_event =
832                PointerEvent::rotary(PointerEventKind::RotaryScrollPre, rotary, position);
833            capture_event.modifiers = self.shell.app.modifiers;
834            self.dispatch_targets(capture_targets, capture_event.clone(), Stop::AtConsumer);
835            if capture_event.is_consumed() {
836                return true;
837            }
838
839            let bubble_targets = bubble_order
840                .iter()
841                .filter_map(|&node_id| self.surface().renderer.scene().find_target(node_id))
842                .collect::<Vec<_>>();
843            let mut bubble_event =
844                PointerEvent::rotary(PointerEventKind::RotaryScroll, rotary, position);
845            bubble_event.modifiers = self.shell.app.modifiers;
846            self.dispatch_targets(bubble_targets, bubble_event.clone(), Stop::AtConsumer);
847            if bubble_event.is_consumed() {
848                return true;
849            }
850        }
851
852        if let Some(handler) = self.surface().on_rotary_scroll.clone() {
853            return handler(rotary);
854        }
855
856        false
857    }
858
859    fn rotary_dispatch_order(&self) -> Vec<NodeId> {
860        if let Some(focused) = cranpose_ui::active_focus_target()
861            && let Some(target) = self.surface().renderer.scene().find_target(focused)
862        {
863            let path = target.capture_path();
864            if !path.is_empty() {
865                return hit_path_tracker::dispatch_order_for_paths(&[path]);
866            }
867        }
868
869        let hits = self
870            .surface()
871            .renderer
872            .scene()
873            .hit_test(self.surface().cursor.0, self.surface().cursor.1);
874        if hits.is_empty() {
875            return Vec::new();
876        }
877        let capture_paths = hits
878            .iter()
879            .map(HitTestTarget::capture_path)
880            .collect::<Vec<_>>();
881        hit_path_tracker::dispatch_order_for_paths(&capture_paths)
882    }
883
884    /// Cancels any active gesture, dispatching Cancel events to cached targets.
885    /// Call this when:
886    /// - Window loses focus
887    /// - Mouse leaves window while button pressed
888    /// - Any other gesture abort scenario
889    pub fn cancel_gesture(&mut self) {
890        let event_time = self.shell.app.realtime_pointer_event_time(None);
891        let _event_handler = enter_event_handler_scope();
892        let _ = {
893            let _app_context = self.shell.app.app_context.enter_scope();
894            run_in_mutable_snapshot(|| {
895                self.cancel_gesture_inner(event_time);
896            })
897        };
898        self.route_drag_and_drop();
899    }
900
901    /// Gives the press that `pointer` holds to `node` alone, as a long press does once it
902    /// fires: every handler under the press sees it cancelled, the other
903    /// handlers on `node` too, so a button does not click when the press
904    /// ends, and the rest of the press reaches `node` alone. Does nothing on
905    /// a surface whose press does not reach `node`.
906    pub(crate) fn give_press_to(&mut self, node: NodeId, pointer: PointerId) {
907        let holds = self
908            .surface()
909            .hit_path_tracker
910            .get_path(pointer)
911            .is_some_and(|paths| paths.iter().any(|path| path.contains(&node)));
912        if !holds {
913            return;
914        }
915        let event_time = self.shell.app.realtime_pointer_event_time(None);
916        let targets = self.resolve_gesture_targets(pointer);
917        self.surface_mut()
918            .hit_path_tracker
919            .add_hit_path(pointer, vec![vec![node]]);
920        let cursor = self.pointer_position(pointer);
921        let event = self
922            .pointer_event(PointerEventKind::Cancel, cursor, cursor, event_time)
923            .with_source(self.surface().pointer_source)
924            .with_id(pointer);
925        let _event_handler = enter_event_handler_scope();
926        let _ = run_in_mutable_snapshot(|| self.dispatch_targets(targets, event, Stop::Never));
927    }
928
929    fn route_drag_and_drop(&mut self) {
930        let source = self.index;
931        let shell = &*self.shell;
932        let app_context = &shell.app.app_context;
933        let routed = app_context.enter(|| {
934            run_in_mutable_snapshot(|| {
935                app_context
936                    .drag_and_drop()
937                    .route(|point| shell.drag_and_drop_target_at(point, source))
938            })
939            .unwrap_or(false)
940        });
941        if routed {
942            self.shell.mark_all_dirty();
943        }
944    }
945
946    /// Ends the gesture only when the pointer leaving really ended it.
947    ///
948    /// A held button belongs to the surface that received the press until
949    /// the release: a window drawn over the cursor, or a drag carried past
950    /// an edge, both leave the press where it started and deliver the
951    /// release there too. Cancelling on either would drop a gesture the
952    /// user has not finished, so a pressed pointer is left alone and only
953    /// an idle one cancels.
954    pub fn cancel_gesture_unless_pressed(&mut self) {
955        if self.surface().buttons_pressed != PointerButtons::NONE
956            || self.surface().inspector.pointer_captured
957        {
958            return;
959        }
960        self.cancel_gesture();
961    }
962
963    fn cancel_gesture_inner(&mut self, event_time: PointerEventTime) {
964        self.surface_mut().inspector.cancel_pointer();
965        let targets = self.resolve_gesture_targets(PointerId::PRIMARY);
966
967        self.surface_mut().hit_path_tracker.clear();
968        self.surface_mut().buttons_pressed = PointerButtons::NONE;
969
970        if !targets.is_empty() {
971            let event = self
972                .pointer_event(
973                    PointerEventKind::Cancel,
974                    Point {
975                        x: self.surface().cursor.0,
976                        y: self.surface().cursor.1,
977                    },
978                    Point {
979                        x: self.surface().cursor.0,
980                        y: self.surface().cursor.1,
981                    },
982                    event_time,
983                )
984                .with_source(self.surface().pointer_source);
985
986            self.dispatch_targets(targets, event, Stop::Never);
987        }
988
989        let pos = Point {
990            x: self.surface().cursor.0,
991            y: self.surface().cursor.1,
992        };
993        let hovered_nodes = self.surface().hovered_nodes.clone();
994        for node_id in hovered_nodes {
995            if let Some(target) = self.surface().renderer.scene().find_target(node_id) {
996                let exit_event = self
997                    .pointer_event(PointerEventKind::Exit, pos, pos, event_time)
998                    .with_source(self.surface().pointer_source);
999                self.dispatch_targets(std::iter::once(target), exit_event, Stop::Never);
1000            }
1001        }
1002        self.surface_mut().hovered_nodes.clear();
1003        self.surface().pointer_icon.set(PointerIcon::DEFAULT);
1004    }
1005
1006    fn apply_hovered_pointer_icon(
1007        &self,
1008        hits: &[<<R as Renderer>::Scene as RenderScene>::HitTarget],
1009    ) {
1010        let icon = hits
1011            .iter()
1012            .find_map(HitTestTarget::pointer_icon)
1013            .unwrap_or(PointerIcon::DEFAULT);
1014        self.surface().pointer_icon.set(icon);
1015    }
1016
1017    /// Sends a key event to the focused control, the key handlers above it and the focus traversal.
1018    /// Returns `true` when the event was handled and the platform should not process it further.
1019    pub fn on_key_event(&mut self, event: &KeyEvent) -> bool {
1020        let _event_handler = enter_event_handler_scope();
1021        let _app_context = self.shell.app.app_context.enter_scope();
1022        let handled = self.on_key_event_inner(event);
1023        self.run_requested_focus_move();
1024        handled
1025    }
1026
1027    /// Makes the focus move a keyboard action asked for during the event.
1028    fn run_requested_focus_move(&mut self) {
1029        if let Some(direction) = cranpose_ui::take_requested_focus_move() {
1030            self.move_focus_in_context(direction);
1031        }
1032    }
1033
1034    fn on_key_event_inner(&mut self, event: &KeyEvent) -> bool {
1035        if self.inspector_key(event) {
1036            return true;
1037        }
1038        let root = self.key_event_root();
1039        if root.is_none() && self.id() != RootId::Primary {
1040            return false;
1041        }
1042        let route =
1043            cranpose_ui::KeyEventRoute::new(&mut self.shell.app.composition.applier_mut(), root);
1044        if self.dispatch_modifier_key(&route, event, true) {
1045            return true;
1046        }
1047        if route.focus_is_current() && self.on_focused_key_event(event) {
1048            return true;
1049        }
1050        if self.dispatch_modifier_key(&route, event, false) {
1051            return true;
1052        }
1053        route.focus_is_current() && self.on_unconsumed_key(event)
1054    }
1055
1056    fn dispatch_modifier_key(
1057        &mut self,
1058        route: &cranpose_ui::KeyEventRoute,
1059        event: &KeyEvent,
1060        preview: bool,
1061    ) -> bool {
1062        let handled = run_in_mutable_snapshot(|| {
1063            let mut applier = self.shell.app.composition.applier_mut();
1064            if preview {
1065                route.dispatch_preview(&mut applier, event)
1066            } else {
1067                route.dispatch_bubble(&mut applier, event)
1068            }
1069        })
1070        .unwrap_or(false);
1071        if handled {
1072            self.mark_dirty();
1073            self.shell.app.request_layout_pass();
1074        }
1075        handled
1076    }
1077
1078    fn key_event_root(&self) -> Option<NodeId> {
1079        self.surface()
1080            .modal_focus
1081            .last()
1082            .map(|entry| entry.0)
1083            .or_else(|| self.surface().root)
1084            .or_else(|| match self.id() {
1085                RootId::Primary => self.shell.app.composition.root(),
1086                RootId::Window(_) => None,
1087            })
1088    }
1089
1090    fn receives_focused_input(&mut self) -> bool {
1091        let root = self.key_event_root();
1092        cranpose_ui::KeyEventRoute::contains_focus(
1093            &mut self.shell.app.composition.applier_mut(),
1094            root,
1095        )
1096    }
1097
1098    fn on_focused_key_event(&mut self, event: &KeyEvent) -> bool {
1099        use KeyEventType::KeyDown;
1100
1101        if event.type_() == KeyDown && event.modifiers().command_or_ctrl() {
1102            #[cfg(all(
1103                feature = "clipboard-native",
1104                not(target_arch = "wasm32"),
1105                not(target_os = "android"),
1106                not(target_os = "ios")
1107            ))]
1108            {
1109                match event.key() {
1110                    Key::C => {
1111                        if let Some(text) = self.on_copy_inner() {
1112                            cranpose_ui::clipboard_session::clipboard_write_text(&text);
1113                            return true;
1114                        }
1115                    }
1116                    Key::X => {
1117                        if let Some(text) = self.on_cut_inner() {
1118                            cranpose_ui::clipboard_session::clipboard_write_text(&text);
1119                            self.mark_dirty();
1120                            self.shell.app.request_layout_pass();
1121                            return true;
1122                        }
1123                    }
1124                    Key::V => {
1125                        if let Some(text) = cranpose_ui::clipboard_session::clipboard_read_text()
1126                            && self.on_paste_inner(&text)
1127                        {
1128                            return true;
1129                        }
1130                    }
1131                    _ => {}
1132                }
1133            }
1134        }
1135
1136        if self.on_focus_key(event) {
1137            return true;
1138        }
1139
1140        if self.on_escape_key(event) {
1141            return true;
1142        }
1143
1144        if self.on_activation_key(event) || self.on_field_dpad_key(event) {
1145            return true;
1146        }
1147
1148        let handled =
1149            run_in_mutable_snapshot(|| cranpose_ui::text_field_focus::dispatch_key_event(event))
1150                .unwrap_or(false);
1151
1152        if handled {
1153            self.mark_dirty();
1154            self.shell.app.request_layout_pass();
1155        }
1156
1157        handled
1158    }
1159
1160    /// Handles paste event from platform clipboard.
1161    /// Returns `true` if a focused text field in this surface consumed the paste.
1162    pub fn on_paste(&mut self, text: &str) -> bool {
1163        if self.inspector_owns_keyboard() {
1164            return true;
1165        }
1166        let _event_handler = enter_event_handler_scope();
1167        let _app_context = self.shell.app.app_context.enter_scope();
1168        self.on_paste_inner(text)
1169    }
1170
1171    fn on_paste_inner(&mut self, text: &str) -> bool {
1172        if !self.receives_focused_input() {
1173            return false;
1174        }
1175        let handled =
1176            run_in_mutable_snapshot(|| cranpose_ui::text_field_focus::dispatch_paste(text))
1177                .unwrap_or(false);
1178
1179        if handled {
1180            self.mark_dirty();
1181            self.shell.app.request_layout_pass();
1182        }
1183
1184        handled
1185    }
1186
1187    /// Handles copy request from platform.
1188    /// Returns the selected text from this surface's focused field, or `None`.
1189    pub fn on_copy(&mut self) -> Option<String> {
1190        if self.inspector_owns_keyboard() {
1191            return None;
1192        }
1193        let _app_context = self.shell.app.app_context.enter_scope();
1194        self.on_copy_inner()
1195    }
1196
1197    fn on_copy_inner(&mut self) -> Option<String> {
1198        if !self.receives_focused_input() {
1199            return None;
1200        }
1201        cranpose_ui::text_field_focus::dispatch_copy()
1202    }
1203
1204    /// Handles cut request from platform.
1205    /// Returns the cut text from this surface's focused field, or `None`.
1206    pub fn on_cut(&mut self) -> Option<String> {
1207        let _event_handler = enter_event_handler_scope();
1208        if self.inspector_owns_keyboard() {
1209            return None;
1210        }
1211        let _app_context = self.shell.app.app_context.enter_scope();
1212        self.on_cut_inner()
1213    }
1214
1215    fn on_cut_inner(&mut self) -> Option<String> {
1216        if !self.receives_focused_input() {
1217            return None;
1218        }
1219        let text =
1220            run_in_mutable_snapshot(cranpose_ui::text_field_focus::dispatch_cut).unwrap_or(None);
1221
1222        if text.is_some() {
1223            self.mark_dirty();
1224            self.shell.app.request_layout_pass();
1225        }
1226
1227        text
1228    }
1229
1230    /// Handles IME preedit (composition) events.
1231    /// Called when the input method is composing text (e.g., typing CJK characters).
1232    ///
1233    /// - `text`: The current preedit text (empty to clear composition state)
1234    /// - `cursor`: Optional cursor position within the preedit text (start, end)
1235    ///
1236    /// Returns `true` if a text field consumed the event.
1237    pub fn on_ime_preedit(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1238        if self.inspector_owns_keyboard() {
1239            return true;
1240        }
1241        let _event_handler = enter_event_handler_scope();
1242        let _app_context = self.shell.app.app_context.enter_scope();
1243        self.on_ime_preedit_inner(text, cursor)
1244    }
1245
1246    fn on_ime_preedit_inner(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1247        if !self.receives_focused_input() {
1248            return false;
1249        }
1250        let handled = run_in_mutable_snapshot(|| {
1251            cranpose_ui::text_field_focus::dispatch_ime_preedit(text, cursor)
1252        })
1253        .unwrap_or(false);
1254
1255        if handled {
1256            self.mark_dirty();
1257            self.shell.app.request_layout_pass();
1258        }
1259
1260        handled
1261    }
1262
1263    /// Finishes the active IME composition, keeping the composed text as
1264    /// committed text (Android `finishComposingText` semantics).
1265    /// Returns `true` if a text field consumed the event.
1266    pub fn on_ime_finish_composing(&mut self) -> bool {
1267        if self.inspector_owns_keyboard() {
1268            return true;
1269        }
1270        let _event_handler = enter_event_handler_scope();
1271        let _app_context = self.shell.app.app_context.enter_scope();
1272        self.on_ime_finish_composing_inner()
1273    }
1274
1275    fn on_ime_finish_composing_inner(&mut self) -> bool {
1276        if !self.receives_focused_input() {
1277            return false;
1278        }
1279        let handled =
1280            run_in_mutable_snapshot(cranpose_ui::text_field_focus::dispatch_ime_finish_composing)
1281                .unwrap_or(false);
1282
1283        if handled {
1284            self.mark_dirty();
1285            self.shell.app.request_layout_pass();
1286        }
1287
1288        handled
1289    }
1290
1291    /// Runs the focused field's keyboard action, as the software keyboard's
1292    /// action key asks: Android's editor action, iOS's return key, the web
1293    /// editor's Enter. [`ImeAction::Default`](cranpose_ui::ImeAction::Default)
1294    /// stands for the field's own action. Returns `true` if a text field
1295    /// handled it.
1296    pub fn on_ime_action(&mut self, action: cranpose_ui::ImeAction) -> bool {
1297        if self.inspector_owns_keyboard() {
1298            return true;
1299        }
1300        let _event_handler = enter_event_handler_scope();
1301        let _app_context = self.shell.app.app_context.enter_scope();
1302        if !self.receives_focused_input() {
1303            return false;
1304        }
1305        let handled =
1306            run_in_mutable_snapshot(|| cranpose_ui::text_field_focus::dispatch_ime_action(action))
1307                .unwrap_or(false);
1308        if handled {
1309            self.mark_dirty();
1310            self.shell.app.request_layout_pass();
1311        }
1312        self.run_requested_focus_move();
1313        handled
1314    }
1315
1316    /// Marks existing text in the focused field as the composing region
1317    /// without changing it (Android `setComposingRegion` semantics). Offsets
1318    /// are UTF-8 bytes. Returns `true` if a text field consumed the event.
1319    pub fn on_ime_set_composing_region(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1320        if self.inspector_owns_keyboard() {
1321            return true;
1322        }
1323        let _event_handler = enter_event_handler_scope();
1324        let _app_context = self.shell.app.app_context.enter_scope();
1325        if !self.receives_focused_input() {
1326            return false;
1327        }
1328        let handled = run_in_mutable_snapshot(|| {
1329            cranpose_ui::text_field_focus::dispatch_ime_set_composing_region(start_bytes, end_bytes)
1330        })
1331        .unwrap_or(false);
1332
1333        if handled {
1334            self.mark_dirty();
1335            self.shell.app.request_layout_pass();
1336        }
1337
1338        handled
1339    }
1340
1341    /// Moves the focused field's selection/caret to `[start_bytes, end_bytes)`
1342    /// without editing text (Android `InputConnection.setSelection`; the path
1343    /// Gboard's spacebar-swipe uses to scrub the cursor). Offsets are UTF-8
1344    /// bytes. Returns `true` if a text field consumed the event.
1345    pub fn on_ime_set_selection(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1346        if self.inspector_owns_keyboard() {
1347            return true;
1348        }
1349        let _event_handler = enter_event_handler_scope();
1350        let _app_context = self.shell.app.app_context.enter_scope();
1351        if !self.receives_focused_input() {
1352            return false;
1353        }
1354        let handled = run_in_mutable_snapshot(|| {
1355            cranpose_ui::text_field_focus::dispatch_ime_set_selection(start_bytes, end_bytes)
1356        })
1357        .unwrap_or(false);
1358
1359        if handled {
1360            self.mark_dirty();
1361        }
1362
1363        handled
1364    }
1365
1366    /// Returns a snapshot of the focused text field's editable state for
1367    /// platform IMEs (text, selection and composition in UTF-8 bytes), or
1368    /// `None` when this surface has no focused text field.
1369    pub fn ime_editor_state(&mut self) -> Option<ImeEditorState> {
1370        let _app_context = self.shell.app.app_context.enter_scope();
1371        self.receives_focused_input()
1372            .then(cranpose_ui::text_field_focus::focused_editor_state)
1373            .flatten()
1374    }
1375
1376    /// Window-space caret geometry of the focused field for coordinate-based
1377    /// platform text input (iOS trackpad cursor + tap-to-position), or `None`
1378    /// when this surface has no focused text field.
1379    pub fn ime_caret_geometry(
1380        &mut self,
1381    ) -> Option<cranpose_ui::text_field_focus::ImeCaretGeometry> {
1382        let _app_context = self.shell.app.app_context.enter_scope();
1383        self.receives_focused_input()
1384            .then(cranpose_ui::text_field_focus::focused_caret_geometry)
1385            .flatten()
1386    }
1387
1388    /// Window bounds of the focused field in logical pixels, for platforms
1389    /// that place a native editor over it, or `None` when this surface has
1390    /// no focused text field that has been laid out.
1391    pub fn ime_field_bounds(&mut self) -> Option<Rect> {
1392        let _app_context = self.shell.app.app_context.enter_scope();
1393        self.receives_focused_input()
1394            .then(cranpose_ui::text_field_focus::focused_field_bounds)
1395            .flatten()
1396    }
1397
1398    /// Whether the focused text field holds a secret, as
1399    /// `Modifier::password()` marks one. Only the semantics of the field's
1400    /// own node are read, so no semantics tree is built, and the answer holds
1401    /// with semantics off. A platform gives such a field a protected editor,
1402    /// which a software keyboard neither learns from nor suggests for.
1403    /// `false` when this surface has no focused text field.
1404    pub fn ime_field_is_password(&mut self) -> bool {
1405        let _app_context = self.shell.app.app_context.enter_scope();
1406        let Some(field) = self
1407            .receives_focused_input()
1408            .then(cranpose_ui::text_field_focus::focused_field_target)
1409            .flatten()
1410        else {
1411            return false;
1412        };
1413        let mut applier = self.shell.app.composition.applier_mut();
1414        applier
1415            .with_node::<LayoutNode, _>(field, |node| node.semantics_configuration())
1416            .or_else(|_| {
1417                applier.with_node::<SubcomposeLayoutNode, _>(field, |node| {
1418                    node.semantics_configuration()
1419                })
1420            })
1421            .ok()
1422            .flatten()
1423            .is_some_and(|config| config.password)
1424    }
1425
1426    /// Clears text-field focus (used by platform IME actions such as
1427    /// Android's Done). The focus-loss notification hides the soft keyboard.
1428    pub fn clear_text_field_focus(&mut self) {
1429        let _event_handler = enter_event_handler_scope();
1430        let _app_context = self.shell.app.app_context.enter_scope();
1431        if self.receives_focused_input() {
1432            cranpose_ui::text_field_focus::clear_focus();
1433            self.mark_dirty();
1434            self.shell.app.request_layout_pass();
1435        }
1436    }
1437
1438    /// Handles IME delete-surrounding events.
1439    /// Returns `true` if a text field consumed the event.
1440    pub fn on_ime_delete_surrounding(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
1441        if self.inspector_owns_keyboard() {
1442            return true;
1443        }
1444        let _event_handler = enter_event_handler_scope();
1445        let _app_context = self.shell.app.app_context.enter_scope();
1446        self.on_ime_delete_surrounding_inner(before_bytes, after_bytes)
1447    }
1448
1449    fn on_ime_delete_surrounding_inner(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
1450        if !self.receives_focused_input() {
1451            return false;
1452        }
1453        let handled = run_in_mutable_snapshot(|| {
1454            cranpose_ui::text_field_focus::dispatch_delete_surrounding(before_bytes, after_bytes)
1455        })
1456        .unwrap_or(false);
1457
1458        if handled {
1459            self.mark_dirty();
1460            self.shell.app.request_layout_pass();
1461        }
1462
1463        handled
1464    }
1465}
1466
1467impl<R> AppShell<R>
1468where
1469    R: Renderer,
1470    R::Error: Debug,
1471{
1472    /// Sets the keyboard modifiers held right now, so the platform's live
1473    /// modifier state (winit's `ModifiersChanged`, a DOM event's
1474    /// `shiftKey`/`ctrlKey`/`altKey`/`metaKey`) reaches every `PointerEvent`
1475    /// the shell dispatches from here on -- the same state the wheel path
1476    /// already carries via [`WheelScroll::with_modifiers`](crate::WheelScroll::with_modifiers).
1477    /// A platform that never calls this leaves pointer events reporting
1478    /// `None` (see [`PointerEvent::modifiers`]) rather than a silently wrong
1479    /// "nothing held".
1480    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
1481        self.app.modifiers = Some(modifiers);
1482    }
1483
1484    /// The keyboard modifiers most recently set via
1485    /// [`set_modifiers`](Self::set_modifiers), or `None` if the platform has
1486    /// never reported them.
1487    pub fn modifiers(&self) -> Option<Modifiers> {
1488        self.app.modifiers
1489    }
1490
1491    /// Pixels per rotary detent used by
1492    /// [`rotary_scrolled_by_detents`](Self::rotary_scrolled_by_detents).
1493    pub fn rotary_scroll_factor(&self) -> f32 {
1494        self.app.rotary_scroll_factor
1495    }
1496
1497    /// Sets the pixels-per-detent factor for rotary input.
1498    ///
1499    /// On Wear OS this must be `ViewConfiguration.getScaledVerticalScrollFactor()`
1500    /// for pixel-exact parity with Compose. The host activity can read it over
1501    /// JNI once at startup and push it here; when it does not, the shell falls
1502    /// back to [`DEFAULT_ROTARY_SCROLL_FACTOR_DP`] scaled by display density.
1503    ///
1504    /// Non-finite or non-positive values are ignored.
1505    pub fn set_rotary_scroll_factor(&mut self, factor: f32) {
1506        if factor.is_finite() && factor > 0.0 {
1507            self.app.rotary_scroll_factor = factor;
1508        }
1509    }
1510
1511    /// Notifies the framework that the host app was paused/backgrounded.
1512    ///
1513    /// Withdraws any outstanding soft-keyboard request (and hides the keyboard)
1514    /// so the "keyboard shown" state does not survive across the pause and get
1515    /// restored on resume with no focused field. Platform runtimes call this
1516    /// from their pause lifecycle event.
1517    pub fn notify_app_paused(&mut self) {
1518        self.app
1519            .app_context
1520            .enter(cranpose_ui::text_input_session::notify_app_paused);
1521    }
1522
1523    /// Notifies the framework that the host app resumed/foregrounded.
1524    ///
1525    /// Never auto-shows the soft keyboard, even for a still-focused field: a
1526    /// warm resume keeps the caret but must not resurrect the keyboard (the user
1527    /// taps the field to bring it back). Always returns `false` so the platform
1528    /// runtime force-hides the OS-restored keyboard. Platform runtimes call this
1529    /// from their resume lifecycle event.
1530    pub fn notify_app_resumed(&mut self) -> bool {
1531        self.app
1532            .app_context
1533            .enter(cranpose_ui::text_input_session::notify_app_resumed)
1534    }
1535
1536    /// Copies `text` to the Linux PRIMARY selection, which a middle click pastes.
1537    #[cfg(all(
1538        feature = "clipboard-native",
1539        target_os = "linux",
1540        not(target_arch = "wasm32")
1541    ))]
1542    pub fn set_primary_selection(&mut self, text: &str) {
1543        use arboard::{LinuxClipboardKind, SetExtLinux};
1544        if let Some(ref mut clipboard) = self.app.clipboard {
1545            let result = clipboard
1546                .set()
1547                .clipboard(LinuxClipboardKind::Primary)
1548                .text(text.to_string());
1549            if let Err(e) = result {
1550                log::debug!("Primary selection set failed: {e:?}");
1551            }
1552        }
1553    }
1554
1555    /// Copies `text` to the Linux PRIMARY selection, which a middle click pastes. Does nothing
1556    /// here, because this build has no PRIMARY selection.
1557    #[cfg(not(all(
1558        feature = "clipboard-native",
1559        target_os = "linux",
1560        not(target_arch = "wasm32")
1561    )))]
1562    pub fn set_primary_selection(&mut self, _text: &str) {}
1563
1564    /// Returns the text in the Linux PRIMARY selection, or `None` when it is empty or unavailable.
1565    #[cfg(all(
1566        feature = "clipboard-native",
1567        target_os = "linux",
1568        not(target_arch = "wasm32")
1569    ))]
1570    pub fn get_primary_selection(&mut self) -> Option<String> {
1571        use arboard::{GetExtLinux, LinuxClipboardKind};
1572        if let Some(ref mut clipboard) = self.app.clipboard {
1573            clipboard
1574                .get()
1575                .clipboard(LinuxClipboardKind::Primary)
1576                .text()
1577                .ok()
1578        } else {
1579            None
1580        }
1581    }
1582
1583    /// Returns `None` always, because this build has no PRIMARY selection.
1584    #[cfg(not(all(
1585        feature = "clipboard-native",
1586        target_os = "linux",
1587        not(target_arch = "wasm32")
1588    )))]
1589    pub fn get_primary_selection(&mut self) -> Option<String> {
1590        None
1591    }
1592
1593    /// Syncs the current text field selection to PRIMARY (Linux X11).
1594    /// Call this when selection changes in a text field.
1595    pub fn sync_selection_to_primary(&mut self) {
1596        #[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
1597        {
1598            if let Some(text) = self.on_copy() {
1599                self.set_primary_selection(&text);
1600            }
1601        }
1602    }
1603
1604    /// Primary-surface form of [`SurfaceMut::set_pointer_source`].
1605    pub fn set_pointer_source(&mut self, source: PointerSource) {
1606        self.primary().set_pointer_source(source);
1607    }
1608
1609    /// Primary-surface form of [`SurfaceMut::pointer_source`].
1610    pub fn pointer_source(&self) -> PointerSource {
1611        self.surfaces[0].pointer_source
1612    }
1613
1614    /// Primary-surface form of [`SurfaceMut::set_cursor`].
1615    pub fn set_cursor(&mut self, x: f32, y: f32) -> bool {
1616        self.primary().set_cursor(x, y)
1617    }
1618
1619    /// Primary-surface form of [`SurfaceMut::set_cursor_at_time`].
1620    pub fn set_cursor_at_time(&mut self, x: f32, y: f32, time_ms: Option<i64>) -> bool {
1621        self.primary().set_cursor_at_time(x, y, time_ms)
1622    }
1623
1624    /// Primary-surface form of [`SurfaceMut::set_cursor_at_event_time`].
1625    pub fn set_cursor_at_event_time(
1626        &mut self,
1627        x: f32,
1628        y: f32,
1629        event_time: PointerEventTime,
1630    ) -> bool {
1631        self.primary().set_cursor_at_event_time(x, y, event_time)
1632    }
1633
1634    /// Primary-surface form of [`SurfaceMut::pointer_pressed`].
1635    pub fn pointer_pressed(&mut self) -> bool {
1636        self.primary().pointer_pressed()
1637    }
1638
1639    /// Primary-surface form of [`SurfaceMut::accessibility_activate`].
1640    pub fn accessibility_activate(&mut self, node_id: NodeId, canvas_key: Option<u64>) -> bool {
1641        self.primary().accessibility_activate(node_id, canvas_key)
1642    }
1643
1644    /// Primary-surface form of [`SurfaceMut::pointer_pressed_at_time`].
1645    pub fn pointer_pressed_at_time(&mut self, time_ms: Option<i64>) -> bool {
1646        self.primary().pointer_pressed_at_time(time_ms)
1647    }
1648
1649    /// Primary-surface form of [`SurfaceMut::pointer_pressed_at_event_time`].
1650    pub fn pointer_pressed_at_event_time(&mut self, event_time: PointerEventTime) -> bool {
1651        self.primary().pointer_pressed_at_event_time(event_time)
1652    }
1653
1654    /// Primary-surface form of [`SurfaceMut::pointer_released`].
1655    pub fn pointer_released(&mut self) -> bool {
1656        self.primary().pointer_released()
1657    }
1658
1659    /// Primary-surface form of [`SurfaceMut::pointer_released_at_position`].
1660    pub fn pointer_released_at_position(&mut self, x: f32, y: f32) -> bool {
1661        self.primary().pointer_released_at_position(x, y)
1662    }
1663
1664    /// Primary-surface form of
1665    /// [`SurfaceMut::pointer_released_at_position_time`].
1666    pub fn pointer_released_at_position_time(
1667        &mut self,
1668        x: f32,
1669        y: f32,
1670        time_ms: Option<i64>,
1671    ) -> bool {
1672        self.primary()
1673            .pointer_released_at_position_time(x, y, time_ms)
1674    }
1675
1676    /// Primary-surface form of
1677    /// [`SurfaceMut::pointer_released_at_position_event_time`].
1678    pub fn pointer_released_at_position_event_time(
1679        &mut self,
1680        x: f32,
1681        y: f32,
1682        event_time: PointerEventTime,
1683    ) -> bool {
1684        self.primary()
1685            .pointer_released_at_position_event_time(x, y, event_time)
1686    }
1687
1688    /// Primary-surface form of [`SurfaceMut::pointer_released_at_time`].
1689    pub fn pointer_released_at_time(&mut self, time_ms: Option<i64>) -> bool {
1690        self.primary().pointer_released_at_time(time_ms)
1691    }
1692
1693    /// Primary-surface form of [`SurfaceMut::pointer_released_at_event_time`].
1694    pub fn pointer_released_at_event_time(&mut self, event_time: PointerEventTime) -> bool {
1695        self.primary().pointer_released_at_event_time(event_time)
1696    }
1697
1698    /// Primary-surface form of [`SurfaceMut::pointer_zoomed`].
1699    pub fn pointer_zoomed(&mut self, zoom_factor: f32) -> bool {
1700        self.primary().pointer_zoomed(zoom_factor)
1701    }
1702
1703    /// Primary-surface form of [`SurfaceMut::wheel_scrolled`].
1704    pub fn wheel_scrolled(&mut self, wheel: WheelScroll) -> bool {
1705        self.primary().wheel_scrolled(wheel)
1706    }
1707
1708    /// Primary-surface form of [`SurfaceMut::pointer_scrolled`].
1709    pub fn pointer_scrolled(&mut self, delta_x: f32, delta_y: f32) -> bool {
1710        self.primary().pointer_scrolled(delta_x, delta_y)
1711    }
1712
1713    /// Primary-surface form of [`SurfaceMut::set_on_rotary_scroll`].
1714    pub fn set_on_rotary_scroll<F>(&mut self, handler: F)
1715    where
1716        F: Fn(RotaryScrollEvent) -> bool + 'static,
1717    {
1718        self.primary().set_on_rotary_scroll(handler);
1719    }
1720
1721    /// Primary-surface form of [`SurfaceMut::clear_on_rotary_scroll`].
1722    pub fn clear_on_rotary_scroll(&mut self) {
1723        self.primary().clear_on_rotary_scroll();
1724    }
1725
1726    /// Primary-surface form of [`SurfaceMut::rotary_scrolled_by_detents`].
1727    pub fn rotary_scrolled_by_detents(&mut self, detents: f32, uptime_millis: u64) -> bool {
1728        self.primary()
1729            .rotary_scrolled_by_detents(detents, uptime_millis)
1730    }
1731
1732    /// Primary-surface form of [`SurfaceMut::rotary_scrolled`].
1733    pub fn rotary_scrolled(&mut self, event: RotaryScrollEvent) -> bool {
1734        self.primary().rotary_scrolled(event)
1735    }
1736
1737    /// Primary-surface form of [`SurfaceMut::cancel_gesture`].
1738    pub fn cancel_gesture(&mut self) {
1739        self.primary().cancel_gesture();
1740    }
1741
1742    /// Primary-surface form of [`SurfaceMut::cancel_gesture_unless_pressed`].
1743    pub fn cancel_gesture_unless_pressed(&mut self) {
1744        self.primary().cancel_gesture_unless_pressed();
1745    }
1746
1747    /// Offers the primary window's current pointer icon to the platform
1748    /// again, for the moments a windowing system has drawn its own default
1749    /// over it.
1750    pub fn refresh_pointer_icon(&self) {
1751        self.surfaces[0].pointer_icon.refresh();
1752    }
1753
1754    /// The pointer icon the platform has not applied to the primary window
1755    /// yet, or `None` when the icon has not changed since the last call.
1756    ///
1757    /// Platform backends call this after handing the shell a batch of input and
1758    /// set the returned icon on the window they own. Platforms with no pointing
1759    /// device never call it.
1760    pub fn take_pointer_icon_change(&self) -> Option<PointerIcon> {
1761        self.surfaces[0].pointer_icon.take_change()
1762    }
1763
1764    /// Installs the platform soft-keyboard handler for the primary window.
1765    ///
1766    /// The handler is invoked when a text field gains focus (`show_keyboard`)
1767    /// or when text-field focus is cleared or goes stale (`hide_keyboard`).
1768    /// Platform runtimes with an on-screen keyboard (Android, iOS) call this
1769    /// once after creating the shell.
1770    pub fn set_platform_text_input(&mut self, handler: Rc<dyn PlatformTextInputHandler>) {
1771        self.primary().set_platform_text_input(handler);
1772    }
1773
1774    /// Primary-surface form of [`SurfaceMut::dismiss_top_modal`].
1775    pub fn dismiss_top_modal(&mut self) -> bool {
1776        self.primary().dismiss_top_modal()
1777    }
1778
1779    /// Primary-surface form of [`SurfaceMut::move_focus_in_context`].
1780    pub fn move_focus_in_context(&mut self, direction: FocusDirection) -> bool {
1781        self.primary().move_focus_in_context(direction)
1782    }
1783
1784    /// Primary-surface form of [`SurfaceMut::on_key_event`].
1785    pub fn on_key_event(&mut self, event: &KeyEvent) -> bool {
1786        self.primary().on_key_event(event)
1787    }
1788
1789    /// Primary-surface form of [`SurfaceMut::on_paste`].
1790    pub fn on_paste(&mut self, text: &str) -> bool {
1791        self.primary().on_paste(text)
1792    }
1793
1794    /// Primary-surface form of [`SurfaceMut::on_copy`].
1795    pub fn on_copy(&mut self) -> Option<String> {
1796        self.primary().on_copy()
1797    }
1798
1799    /// Primary-surface form of [`SurfaceMut::on_cut`].
1800    pub fn on_cut(&mut self) -> Option<String> {
1801        self.primary().on_cut()
1802    }
1803
1804    /// Primary-surface form of [`SurfaceMut::on_ime_preedit`].
1805    pub fn on_ime_preedit(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1806        self.primary().on_ime_preedit(text, cursor)
1807    }
1808
1809    /// Primary-surface form of [`SurfaceMut::on_ime_finish_composing`].
1810    pub fn on_ime_finish_composing(&mut self) -> bool {
1811        self.primary().on_ime_finish_composing()
1812    }
1813
1814    /// Primary-surface form of [`SurfaceMut::on_ime_action`].
1815    pub fn on_ime_action(&mut self, action: cranpose_ui::ImeAction) -> bool {
1816        self.primary().on_ime_action(action)
1817    }
1818
1819    /// Primary-surface form of [`SurfaceMut::on_ime_set_composing_region`].
1820    pub fn on_ime_set_composing_region(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1821        self.primary()
1822            .on_ime_set_composing_region(start_bytes, end_bytes)
1823    }
1824
1825    /// Primary-surface form of [`SurfaceMut::on_ime_set_selection`].
1826    pub fn on_ime_set_selection(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1827        self.primary().on_ime_set_selection(start_bytes, end_bytes)
1828    }
1829
1830    /// Primary-surface form of [`SurfaceMut::ime_editor_state`].
1831    pub fn ime_editor_state(&mut self) -> Option<ImeEditorState> {
1832        self.primary().ime_editor_state()
1833    }
1834
1835    /// Primary-surface form of [`SurfaceMut::ime_caret_geometry`].
1836    pub fn ime_caret_geometry(
1837        &mut self,
1838    ) -> Option<cranpose_ui::text_field_focus::ImeCaretGeometry> {
1839        self.primary().ime_caret_geometry()
1840    }
1841
1842    /// Primary-surface form of [`SurfaceMut::ime_field_bounds`].
1843    pub fn ime_field_bounds(&mut self) -> Option<Rect> {
1844        self.primary().ime_field_bounds()
1845    }
1846
1847    /// Primary-surface form of [`SurfaceMut::ime_field_is_password`].
1848    pub fn ime_field_is_password(&mut self) -> bool {
1849        self.primary().ime_field_is_password()
1850    }
1851
1852    /// Primary-surface form of [`SurfaceMut::clear_text_field_focus`].
1853    pub fn clear_text_field_focus(&mut self) {
1854        self.primary().clear_text_field_focus();
1855    }
1856
1857    /// Primary-surface form of [`SurfaceMut::on_ime_delete_surrounding`].
1858    pub fn on_ime_delete_surrounding(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
1859        self.primary()
1860            .on_ime_delete_surrounding(before_bytes, after_bytes)
1861    }
1862}