Skip to main content

cranpose_app_shell/
shell_input.rs

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