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, rotary uses the focus target's capture
842    ///    path. Otherwise, rotary uses the hit-test chain under the cursor.
843    /// 2. **Capture pass**, root to leaf, invoking `on_pre_rotary_scroll_event`
844    ///    handlers.
845    /// 3. **Bubble pass**, leaf to root, invoking `on_rotary_scroll_event`
846    ///    handlers.
847    /// 4. If still unconsumed, the window-level handler installed by
848    ///    [`set_on_rotary_scroll`](Self::set_on_rotary_scroll).
849    ///
850    /// The first handler returning `true` consumes the event and stops every
851    /// remaining step. Returns `true` when the event was consumed.
852    pub fn rotary_scrolled(&mut self, event: RotaryScrollEvent) -> bool {
853        let _event_handler = enter_event_handler_scope();
854        let app_context = Rc::clone(&self.shell.app.app_context);
855        let result = app_context.enter(|| {
856            run_in_mutable_snapshot(|| self.rotary_scrolled_inner(event)).unwrap_or(false)
857        });
858        if result {
859            self.mark_dirty();
860        }
861        log::trace!(
862            target: "cranpose::input",
863            "rotary_scrolled v={:.2} h={:.2} uptime={} -> {result}",
864            event.vertical_scroll_pixels,
865            event.horizontal_scroll_pixels,
866            event.uptime_millis,
867        );
868        result
869    }
870
871    fn rotary_scrolled_inner(&mut self, rotary: RotaryScrollEvent) -> bool {
872        if rotary.is_empty() {
873            return false;
874        }
875
876        let bubble_order = self.rotary_dispatch_order();
877        let position = Point {
878            x: self.surface().cursor.0,
879            y: self.surface().cursor.1,
880        };
881
882        if !bubble_order.is_empty() {
883            let capture_targets = bubble_order
884                .iter()
885                .rev()
886                .filter_map(|&node_id| self.surface().renderer.scene().find_target(node_id))
887                .collect::<Vec<_>>();
888            let mut capture_event =
889                PointerEvent::rotary(PointerEventKind::RotaryScrollPre, rotary, position);
890            capture_event.modifiers = self.shell.app.modifiers;
891            self.dispatch_targets(capture_targets, capture_event.clone(), true);
892            if capture_event.is_consumed() {
893                return true;
894            }
895
896            let bubble_targets = bubble_order
897                .iter()
898                .filter_map(|&node_id| self.surface().renderer.scene().find_target(node_id))
899                .collect::<Vec<_>>();
900            let mut bubble_event =
901                PointerEvent::rotary(PointerEventKind::RotaryScroll, rotary, position);
902            bubble_event.modifiers = self.shell.app.modifiers;
903            self.dispatch_targets(bubble_targets, bubble_event.clone(), true);
904            if bubble_event.is_consumed() {
905                return true;
906            }
907        }
908
909        if let Some(handler) = self.surface().on_rotary_scroll.clone() {
910            return handler(rotary);
911        }
912
913        false
914    }
915
916    fn rotary_dispatch_order(&self) -> Vec<NodeId> {
917        if let Some(focused) = cranpose_ui::active_focus_target()
918            && let Some(target) = self.surface().renderer.scene().find_target(focused)
919        {
920            let path = target.capture_path();
921            if !path.is_empty() {
922                return crate::hit_path_tracker::dispatch_order_for_paths(&[path]);
923            }
924        }
925
926        let hits = self
927            .surface()
928            .renderer
929            .scene()
930            .hit_test(self.surface().cursor.0, self.surface().cursor.1);
931        if hits.is_empty() {
932            return Vec::new();
933        }
934        let capture_paths = hits
935            .iter()
936            .map(cranpose_render_common::HitTestTarget::capture_path)
937            .collect::<Vec<_>>();
938        crate::hit_path_tracker::dispatch_order_for_paths(&capture_paths)
939    }
940
941    /// Cancels any active gesture, dispatching Cancel events to cached targets.
942    /// Call this when:
943    /// - Window loses focus
944    /// - Mouse leaves window while button pressed
945    /// - Any other gesture abort scenario
946    pub fn cancel_gesture(&mut self) {
947        let event_time = self.shell.app.realtime_pointer_event_time(None);
948        let _event_handler = enter_event_handler_scope();
949        let app_context = Rc::clone(&self.shell.app.app_context);
950        let _ = app_context.enter(|| {
951            run_in_mutable_snapshot(|| {
952                self.cancel_gesture_inner(event_time);
953            })
954        });
955        self.route_drag_and_drop();
956    }
957
958    fn route_drag_and_drop(&mut self) {
959        let app_context = Rc::clone(&self.shell.app.app_context);
960        let source = self.index;
961        let shell = &mut *self.shell;
962        let routed = app_context.enter(|| {
963            run_in_mutable_snapshot(|| {
964                app_context
965                    .drag_and_drop()
966                    .route(|point| shell.drag_and_drop_target_at(point, source))
967            })
968            .unwrap_or(false)
969        });
970        if routed {
971            shell.mark_all_dirty();
972        }
973    }
974
975    /// Ends the gesture only when the pointer leaving really ended it.
976    ///
977    /// A held button belongs to the surface that received the press until
978    /// the release: a window drawn over the cursor, or a drag carried past
979    /// an edge, both leave the press where it started and deliver the
980    /// release there too. Cancelling on either would drop a gesture the
981    /// user has not finished, so a pressed pointer is left alone and only
982    /// an idle one cancels.
983    pub fn cancel_gesture_unless_pressed(&mut self) {
984        if self.surface().buttons_pressed != PointerButtons::NONE
985            || self.surface().inspector.pointer_captured
986        {
987            return;
988        }
989        self.cancel_gesture();
990    }
991
992    fn cancel_gesture_inner(&mut self, event_time: PointerEventTime) {
993        self.surface_mut().inspector.cancel_pointer();
994        let targets = self.resolve_gesture_targets(PointerId::PRIMARY);
995
996        self.surface_mut().hit_path_tracker.clear();
997        self.surface_mut().buttons_pressed = PointerButtons::NONE;
998
999        if !targets.is_empty() {
1000            let event = self
1001                .pointer_event(
1002                    PointerEventKind::Cancel,
1003                    Point {
1004                        x: self.surface().cursor.0,
1005                        y: self.surface().cursor.1,
1006                    },
1007                    Point {
1008                        x: self.surface().cursor.0,
1009                        y: self.surface().cursor.1,
1010                    },
1011                    event_time,
1012                )
1013                .with_source(self.surface().pointer_source);
1014
1015            self.dispatch_targets(targets, event, false);
1016        }
1017
1018        let pos = Point {
1019            x: self.surface().cursor.0,
1020            y: self.surface().cursor.1,
1021        };
1022        let hovered_nodes = self.surface().hovered_nodes.clone();
1023        for node_id in hovered_nodes {
1024            if let Some(target) = self.surface().renderer.scene().find_target(node_id) {
1025                let exit_event = self
1026                    .pointer_event(PointerEventKind::Exit, pos, pos, event_time)
1027                    .with_source(self.surface().pointer_source);
1028                self.dispatch_targets(std::iter::once(target), exit_event, false);
1029            }
1030        }
1031        self.surface_mut().hovered_nodes.clear();
1032        self.surface().pointer_icon.set(PointerIcon::DEFAULT);
1033    }
1034
1035    fn apply_hovered_pointer_icon(
1036        &self,
1037        hits: &[<<R as Renderer>::Scene as RenderScene>::HitTarget],
1038    ) {
1039        let icon = hits
1040            .iter()
1041            .find_map(HitTestTarget::pointer_icon)
1042            .unwrap_or(PointerIcon::DEFAULT);
1043        self.surface().pointer_icon.set(icon);
1044    }
1045
1046    fn on_focus_key(&mut self, event: &KeyEvent) -> bool {
1047        if !plain_key_down(event) || event.key_code != KeyCode::Tab {
1048            return false;
1049        }
1050        self.on_group_navigation_key(event)
1051    }
1052
1053    fn on_group_navigation_key(&mut self, event: &KeyEvent) -> bool {
1054        let focused = cranpose_ui::active_focus_target();
1055        let target = self.with_layout_tree(|tree| {
1056            cranpose_ui::keyboard_focus_target(
1057                tree?,
1058                focused,
1059                event.key_code,
1060                event.modifiers.shift,
1061            )
1062        });
1063        let Some(target) = target else {
1064            return false;
1065        };
1066        let moved =
1067            run_in_mutable_snapshot(|| cranpose_ui::request_focus_from_platform(target.node_id))
1068                .unwrap_or(false);
1069        if moved {
1070            self.mark_dirty();
1071            self.note_focus_moved_by_keyboard(true);
1072            if target.activate {
1073                self.on_activation_key(&KeyEvent::key_down(KeyCode::Space, " "));
1074            }
1075        }
1076        moved
1077    }
1078
1079    fn on_activation_key(&mut self, event: &KeyEvent) -> bool {
1080        if !plain_key_down(event)
1081            || !matches!(event.key_code, KeyCode::Enter | KeyCode::Space)
1082            || cranpose_ui::text_field_focus::has_focused_field()
1083        {
1084            return false;
1085        }
1086        let Some(focused) = cranpose_ui::active_focus_target() else {
1087            return false;
1088        };
1089        let activated = self.accessibility_activate(focused, None);
1090        self.note_focus_moved_by_keyboard(true);
1091        activated
1092    }
1093
1094    fn on_arrow_key(&mut self, event: &KeyEvent) -> bool {
1095        if !plain_key_down(event) || cranpose_ui::text_field_focus::has_focused_field() {
1096            return false;
1097        }
1098        if self.on_group_navigation_key(event) {
1099            return true;
1100        }
1101        let direction = match event.key_code {
1102            KeyCode::ArrowLeft => FocusDirection::Left,
1103            KeyCode::ArrowRight => FocusDirection::Right,
1104            KeyCode::ArrowUp => FocusDirection::Up,
1105            KeyCode::ArrowDown => FocusDirection::Down,
1106            _ => return false,
1107        };
1108        let Some(focused) = cranpose_ui::active_focus_target() else {
1109            return false;
1110        };
1111        let order = self.with_layout_tree(|layout_tree| {
1112            let layout_tree = layout_tree?;
1113            let group = cranpose_ui::selectable_group_of(layout_tree, focused)?;
1114            Some(cranpose_ui::collect_focus_order_under(layout_tree, group))
1115        });
1116        order.is_some_and(|order| self.move_focus_in_order(order, direction))
1117    }
1118
1119    fn note_focus_moved_by_keyboard(&mut self, keyboard: bool) {
1120        if cranpose_ui::set_keyboard_focus_visible(keyboard) {
1121            cranpose_ui::request_render_invalidation();
1122            self.mark_dirty();
1123        }
1124    }
1125
1126    fn on_escape_key(&mut self, event: &KeyEvent) -> bool {
1127        if event.event_type != KeyEventType::KeyDown || event.key_code != KeyCode::Escape {
1128            return false;
1129        }
1130        self.dismiss_top_modal_in_context()
1131    }
1132
1133    /// Asks the innermost open dialog or popup to close, the way the platform
1134    /// back gesture does. Answers whether one was open to take the request.
1135    pub fn dismiss_top_modal(&mut self) -> bool {
1136        let _event_handler = enter_event_handler_scope();
1137        let app_context = Rc::clone(&self.shell.app.app_context);
1138        app_context.enter(|| self.dismiss_top_modal_in_context())
1139    }
1140
1141    fn dismiss_top_modal_in_context(&mut self) -> bool {
1142        let closed = run_in_mutable_snapshot(|| {
1143            if cranpose_ui::modal_depth() > 0 {
1144                cranpose_ui::dispatch_modal_back()
1145            } else {
1146                cranpose_ui::dismiss_top_popup()
1147            }
1148        })
1149        .unwrap_or(false);
1150        if closed {
1151            self.mark_dirty();
1152        }
1153        closed
1154    }
1155
1156    /// Publishes the focus order layout left behind and moves focus one step.
1157    /// Answers whether focus moved.
1158    pub fn move_focus_in_context(&mut self, direction: FocusDirection) -> bool {
1159        let order = self.with_layout_tree(|layout_tree| {
1160            layout_tree
1161                .map(cranpose_ui::collect_focus_order)
1162                .unwrap_or_default()
1163        });
1164        self.move_focus_in_order(order, direction)
1165    }
1166
1167    fn move_focus_in_order(
1168        &mut self,
1169        order: Vec<cranpose_ui::FocusEntry>,
1170        direction: FocusDirection,
1171    ) -> bool {
1172        cranpose_ui::set_focus_order(order);
1173        let moved = run_in_mutable_snapshot(|| cranpose_ui::FocusManager.move_focus(direction))
1174            .unwrap_or(false);
1175        if moved {
1176            self.mark_dirty();
1177            self.note_focus_moved_by_keyboard(true);
1178        }
1179        moved
1180    }
1181
1182    pub fn on_key_event(&mut self, event: &KeyEvent) -> bool {
1183        let _event_handler = enter_event_handler_scope();
1184        let app_context = Rc::clone(&self.shell.app.app_context);
1185        app_context.enter(|| self.on_key_event_inner(event))
1186    }
1187
1188    fn on_key_event_inner(&mut self, event: &KeyEvent) -> bool {
1189        if self.inspector_key(event) {
1190            return true;
1191        }
1192        let root = self.key_event_root();
1193        if root.is_none() && self.id() != RootId::Primary {
1194            return false;
1195        }
1196        let route =
1197            cranpose_ui::KeyEventRoute::new(&mut self.shell.app.composition.applier_mut(), root);
1198        if self.dispatch_modifier_key(&route, event, true) {
1199            return true;
1200        }
1201        if route.focus_is_current() && self.on_focused_key_event(event) {
1202            return true;
1203        }
1204        if self.dispatch_modifier_key(&route, event, false) {
1205            return true;
1206        }
1207        if !route.focus_is_current() || cranpose_ui::text_field_focus::has_focused_field() {
1208            return false;
1209        }
1210        let handled = run_in_mutable_snapshot(|| cranpose_ui::dispatch_unhandled_key_event(event))
1211            .unwrap_or(false);
1212        if handled {
1213            self.mark_dirty();
1214            self.shell.app.request_layout_pass();
1215        }
1216        handled
1217    }
1218
1219    fn dispatch_modifier_key(
1220        &mut self,
1221        route: &cranpose_ui::KeyEventRoute,
1222        event: &KeyEvent,
1223        preview: bool,
1224    ) -> bool {
1225        let handled = run_in_mutable_snapshot(|| {
1226            let mut applier = self.shell.app.composition.applier_mut();
1227            if preview {
1228                route.dispatch_preview(&mut applier, event)
1229            } else {
1230                route.dispatch_bubble(&mut applier, event)
1231            }
1232        })
1233        .unwrap_or(false);
1234        if handled {
1235            self.mark_dirty();
1236            self.shell.app.request_layout_pass();
1237        }
1238        handled
1239    }
1240
1241    fn key_event_root(&self) -> Option<cranpose_core::NodeId> {
1242        self.surface()
1243            .modal_focus
1244            .last()
1245            .map(|entry| entry.0)
1246            .or_else(|| self.surface().root)
1247            .or_else(|| match self.id() {
1248                RootId::Primary => self.shell.app.composition.root(),
1249                RootId::Window(_) => None,
1250            })
1251    }
1252
1253    fn receives_focused_input(&mut self) -> bool {
1254        let root = self.key_event_root();
1255        cranpose_ui::KeyEventRoute::contains_focus(
1256            &mut self.shell.app.composition.applier_mut(),
1257            root,
1258        )
1259    }
1260
1261    fn on_focused_key_event(&mut self, event: &KeyEvent) -> bool {
1262        use KeyEventType::KeyDown;
1263
1264        if event.event_type == KeyDown && event.modifiers.command_or_ctrl() {
1265            #[cfg(all(
1266                feature = "clipboard-native",
1267                not(target_arch = "wasm32"),
1268                not(target_os = "android"),
1269                not(target_os = "ios")
1270            ))]
1271            {
1272                match event.key_code {
1273                    KeyCode::C => {
1274                        if let Some(text) = self.on_copy_inner() {
1275                            cranpose_ui::clipboard_session::clipboard_write_text(&text);
1276                            return true;
1277                        }
1278                    }
1279                    KeyCode::X => {
1280                        if let Some(text) = self.on_cut_inner() {
1281                            cranpose_ui::clipboard_session::clipboard_write_text(&text);
1282                            self.mark_dirty();
1283                            self.shell.app.request_layout_pass();
1284                            return true;
1285                        }
1286                    }
1287                    KeyCode::V => {
1288                        if let Some(text) = cranpose_ui::clipboard_session::clipboard_read_text()
1289                            && self.on_paste_inner(&text)
1290                        {
1291                            return true;
1292                        }
1293                    }
1294                    _ => {}
1295                }
1296            }
1297        }
1298
1299        if self.on_focus_key(event) {
1300            return true;
1301        }
1302
1303        if self.on_escape_key(event) {
1304            return true;
1305        }
1306
1307        if self.on_activation_key(event) || self.on_arrow_key(event) {
1308            return true;
1309        }
1310
1311        let handled =
1312            run_in_mutable_snapshot(|| cranpose_ui::text_field_focus::dispatch_key_event(event))
1313                .unwrap_or(false);
1314
1315        if handled {
1316            self.mark_dirty();
1317            self.shell.app.request_layout_pass();
1318        }
1319
1320        handled
1321    }
1322
1323    /// Handles paste event from platform clipboard.
1324    /// Returns `true` if a focused text field in this surface consumed the paste.
1325    pub fn on_paste(&mut self, text: &str) -> bool {
1326        if self.inspector_owns_keyboard() {
1327            return true;
1328        }
1329        let _event_handler = enter_event_handler_scope();
1330        let app_context = Rc::clone(&self.shell.app.app_context);
1331        app_context.enter(|| self.on_paste_inner(text))
1332    }
1333
1334    fn on_paste_inner(&mut self, text: &str) -> bool {
1335        if !self.receives_focused_input() {
1336            return false;
1337        }
1338        let handled =
1339            run_in_mutable_snapshot(|| cranpose_ui::text_field_focus::dispatch_paste(text))
1340                .unwrap_or(false);
1341
1342        if handled {
1343            self.mark_dirty();
1344            self.shell.app.request_layout_pass();
1345        }
1346
1347        handled
1348    }
1349
1350    /// Handles copy request from platform.
1351    /// Returns the selected text from this surface's focused field, or `None`.
1352    pub fn on_copy(&mut self) -> Option<String> {
1353        let app_context = Rc::clone(&self.shell.app.app_context);
1354        if self.inspector_owns_keyboard() {
1355            return None;
1356        }
1357        app_context.enter(|| self.on_copy_inner())
1358    }
1359
1360    fn on_copy_inner(&mut self) -> Option<String> {
1361        if !self.receives_focused_input() {
1362            return None;
1363        }
1364        cranpose_ui::text_field_focus::dispatch_copy()
1365    }
1366
1367    /// Handles cut request from platform.
1368    /// Returns the cut text from this surface's focused field, or `None`.
1369    pub fn on_cut(&mut self) -> Option<String> {
1370        let _event_handler = enter_event_handler_scope();
1371        if self.inspector_owns_keyboard() {
1372            return None;
1373        }
1374        let app_context = Rc::clone(&self.shell.app.app_context);
1375        app_context.enter(|| self.on_cut_inner())
1376    }
1377
1378    fn on_cut_inner(&mut self) -> Option<String> {
1379        if !self.receives_focused_input() {
1380            return None;
1381        }
1382        let text =
1383            run_in_mutable_snapshot(cranpose_ui::text_field_focus::dispatch_cut).unwrap_or(None);
1384
1385        if text.is_some() {
1386            self.mark_dirty();
1387            self.shell.app.request_layout_pass();
1388        }
1389
1390        text
1391    }
1392
1393    /// Handles IME preedit (composition) events.
1394    /// Called when the input method is composing text (e.g., typing CJK characters).
1395    ///
1396    /// - `text`: The current preedit text (empty to clear composition state)
1397    /// - `cursor`: Optional cursor position within the preedit text (start, end)
1398    ///
1399    /// Returns `true` if a text field consumed the event.
1400    pub fn on_ime_preedit(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1401        if self.inspector_owns_keyboard() {
1402            return true;
1403        }
1404        let _event_handler = enter_event_handler_scope();
1405        let app_context = Rc::clone(&self.shell.app.app_context);
1406        app_context.enter(|| self.on_ime_preedit_inner(text, cursor))
1407    }
1408
1409    fn on_ime_preedit_inner(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1410        if !self.receives_focused_input() {
1411            return false;
1412        }
1413        let handled = run_in_mutable_snapshot(|| {
1414            cranpose_ui::text_field_focus::dispatch_ime_preedit(text, cursor)
1415        })
1416        .unwrap_or(false);
1417
1418        if handled {
1419            self.mark_dirty();
1420            self.shell.app.request_layout_pass();
1421        }
1422
1423        handled
1424    }
1425
1426    /// Finishes the active IME composition, keeping the composed text as
1427    /// committed text (Android `finishComposingText` semantics).
1428    /// Returns `true` if a text field consumed the event.
1429    pub fn on_ime_finish_composing(&mut self) -> bool {
1430        if self.inspector_owns_keyboard() {
1431            return true;
1432        }
1433        let _event_handler = enter_event_handler_scope();
1434        let app_context = Rc::clone(&self.shell.app.app_context);
1435        app_context.enter(|| self.on_ime_finish_composing_inner())
1436    }
1437
1438    fn on_ime_finish_composing_inner(&mut self) -> bool {
1439        if !self.receives_focused_input() {
1440            return false;
1441        }
1442        let handled =
1443            run_in_mutable_snapshot(cranpose_ui::text_field_focus::dispatch_ime_finish_composing)
1444                .unwrap_or(false);
1445
1446        if handled {
1447            self.mark_dirty();
1448            self.shell.app.request_layout_pass();
1449        }
1450
1451        handled
1452    }
1453
1454    /// Marks existing text in the focused field as the composing region
1455    /// without changing it (Android `setComposingRegion` semantics). Offsets
1456    /// are UTF-8 bytes. Returns `true` if a text field consumed the event.
1457    pub fn on_ime_set_composing_region(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1458        if self.inspector_owns_keyboard() {
1459            return true;
1460        }
1461        let _event_handler = enter_event_handler_scope();
1462        let app_context = Rc::clone(&self.shell.app.app_context);
1463        app_context.enter(|| {
1464            if !self.receives_focused_input() {
1465                return false;
1466            }
1467            let handled = run_in_mutable_snapshot(|| {
1468                cranpose_ui::text_field_focus::dispatch_ime_set_composing_region(
1469                    start_bytes,
1470                    end_bytes,
1471                )
1472            })
1473            .unwrap_or(false);
1474
1475            if handled {
1476                self.mark_dirty();
1477                self.shell.app.request_layout_pass();
1478            }
1479
1480            handled
1481        })
1482    }
1483
1484    /// Moves the focused field's selection/caret to `[start_bytes, end_bytes)`
1485    /// without editing text (Android `InputConnection.setSelection`; the path
1486    /// Gboard's spacebar-swipe uses to scrub the cursor). Offsets are UTF-8
1487    /// bytes. Returns `true` if a text field consumed the event.
1488    pub fn on_ime_set_selection(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1489        if self.inspector_owns_keyboard() {
1490            return true;
1491        }
1492        let _event_handler = enter_event_handler_scope();
1493        let app_context = Rc::clone(&self.shell.app.app_context);
1494        app_context.enter(|| {
1495            if !self.receives_focused_input() {
1496                return false;
1497            }
1498            let handled = run_in_mutable_snapshot(|| {
1499                cranpose_ui::text_field_focus::dispatch_ime_set_selection(start_bytes, end_bytes)
1500            })
1501            .unwrap_or(false);
1502
1503            if handled {
1504                self.mark_dirty();
1505            }
1506
1507            handled
1508        })
1509    }
1510
1511    /// Returns a snapshot of the focused text field's editable state for
1512    /// platform IMEs (text, selection and composition in UTF-8 bytes), or
1513    /// `None` when this surface has no focused text field.
1514    pub fn ime_editor_state(&mut self) -> Option<cranpose_ui::text_field_focus::ImeEditorState> {
1515        let app_context = Rc::clone(&self.shell.app.app_context);
1516        app_context.enter(|| {
1517            self.receives_focused_input()
1518                .then(cranpose_ui::text_field_focus::focused_editor_state)
1519                .flatten()
1520        })
1521    }
1522
1523    /// Window-space caret geometry of the focused field for coordinate-based
1524    /// platform text input (iOS trackpad cursor + tap-to-position), or `None`
1525    /// when this surface has no focused text field.
1526    pub fn ime_caret_geometry(
1527        &mut self,
1528    ) -> Option<cranpose_ui::text_field_focus::ImeCaretGeometry> {
1529        let app_context = Rc::clone(&self.shell.app.app_context);
1530        app_context.enter(|| {
1531            self.receives_focused_input()
1532                .then(cranpose_ui::text_field_focus::focused_caret_geometry)
1533                .flatten()
1534        })
1535    }
1536
1537    /// Whether the focused text field holds a secret, as
1538    /// `Modifier::password()` marks one. Only the semantics of the field's
1539    /// own node are read, so no semantics tree is built, and the answer holds
1540    /// with semantics off. A platform gives such a field a protected editor,
1541    /// which a software keyboard neither learns from nor suggests for.
1542    /// `false` when this surface has no focused text field.
1543    pub fn ime_field_is_password(&mut self) -> bool {
1544        let app_context = Rc::clone(&self.shell.app.app_context);
1545        app_context.enter(|| {
1546            let Some(field) = self
1547                .receives_focused_input()
1548                .then(cranpose_ui::text_field_focus::focused_field_target)
1549                .flatten()
1550            else {
1551                return false;
1552            };
1553            let mut applier = self.shell.app.composition.applier_mut();
1554            applier
1555                .with_node::<LayoutNode, _>(field, |node| node.semantics_configuration())
1556                .or_else(|_| {
1557                    applier.with_node::<SubcomposeLayoutNode, _>(field, |node| {
1558                        node.semantics_configuration()
1559                    })
1560                })
1561                .ok()
1562                .flatten()
1563                .is_some_and(|config| config.password)
1564        })
1565    }
1566
1567    /// Clears text-field focus (used by platform IME actions such as
1568    /// Android's Done). The focus-loss notification hides the soft keyboard.
1569    pub fn clear_text_field_focus(&mut self) {
1570        let _event_handler = enter_event_handler_scope();
1571        let app_context = Rc::clone(&self.shell.app.app_context);
1572        app_context.enter(|| {
1573            if self.receives_focused_input() {
1574                cranpose_ui::text_field_focus::clear_focus();
1575                self.mark_dirty();
1576                self.shell.app.request_layout_pass();
1577            }
1578        });
1579    }
1580
1581    /// Handles IME delete-surrounding events.
1582    /// Returns `true` if a text field consumed the event.
1583    pub fn on_ime_delete_surrounding(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
1584        if self.inspector_owns_keyboard() {
1585            return true;
1586        }
1587        let _event_handler = enter_event_handler_scope();
1588        let app_context = Rc::clone(&self.shell.app.app_context);
1589        app_context.enter(|| self.on_ime_delete_surrounding_inner(before_bytes, after_bytes))
1590    }
1591
1592    fn on_ime_delete_surrounding_inner(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
1593        if !self.receives_focused_input() {
1594            return false;
1595        }
1596        let handled = run_in_mutable_snapshot(|| {
1597            cranpose_ui::text_field_focus::dispatch_delete_surrounding(before_bytes, after_bytes)
1598        })
1599        .unwrap_or(false);
1600
1601        if handled {
1602            self.mark_dirty();
1603            self.shell.app.request_layout_pass();
1604        }
1605
1606        handled
1607    }
1608}
1609
1610impl<R> AppShell<R>
1611where
1612    R: Renderer,
1613    R::Error: Debug,
1614{
1615    /// Sets the keyboard modifiers held right now, so the platform's live
1616    /// modifier state (winit's `ModifiersChanged`, a DOM event's
1617    /// `shiftKey`/`ctrlKey`/`altKey`/`metaKey`) reaches every `PointerEvent`
1618    /// the shell dispatches from here on -- the same state the wheel path
1619    /// already carries via [`WheelScroll::with_modifiers`](crate::WheelScroll::with_modifiers).
1620    /// A platform that never calls this leaves pointer events reporting
1621    /// `None` (see [`PointerEvent::modifiers`]) rather than a silently wrong
1622    /// "nothing held".
1623    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
1624        self.app.modifiers = Some(modifiers);
1625    }
1626
1627    /// The keyboard modifiers most recently set via
1628    /// [`set_modifiers`](Self::set_modifiers), or `None` if the platform has
1629    /// never reported them.
1630    pub fn modifiers(&self) -> Option<Modifiers> {
1631        self.app.modifiers
1632    }
1633
1634    /// Pixels per rotary detent used by
1635    /// [`rotary_scrolled_by_detents`](Self::rotary_scrolled_by_detents).
1636    pub fn rotary_scroll_factor(&self) -> f32 {
1637        self.app.rotary_scroll_factor
1638    }
1639
1640    /// Sets the pixels-per-detent factor for rotary input.
1641    ///
1642    /// On Wear OS this must be `ViewConfiguration.getScaledVerticalScrollFactor()`
1643    /// for pixel-exact parity with Compose. The host activity can read it over
1644    /// JNI once at startup and push it here; when it does not, the shell falls
1645    /// back to [`DEFAULT_ROTARY_SCROLL_FACTOR_DP`] scaled by display density.
1646    ///
1647    /// Non-finite or non-positive values are ignored.
1648    pub fn set_rotary_scroll_factor(&mut self, factor: f32) {
1649        if factor.is_finite() && factor > 0.0 {
1650            self.app.rotary_scroll_factor = factor;
1651        }
1652    }
1653
1654    /// Notifies the framework that the host app was paused/backgrounded.
1655    ///
1656    /// Withdraws any outstanding soft-keyboard request (and hides the keyboard)
1657    /// so the "keyboard shown" state does not survive across the pause and get
1658    /// restored on resume with no focused field. Platform runtimes call this
1659    /// from their pause lifecycle event.
1660    pub fn notify_app_paused(&mut self) {
1661        let app_context = Rc::clone(&self.app.app_context);
1662        app_context.enter(cranpose_ui::text_input_session::notify_app_paused);
1663    }
1664
1665    /// Notifies the framework that the host app resumed/foregrounded.
1666    ///
1667    /// Never auto-shows the soft keyboard, even for a still-focused field: a
1668    /// warm resume keeps the caret but must not resurrect the keyboard (the user
1669    /// taps the field to bring it back). Always returns `false` so the platform
1670    /// runtime force-hides the OS-restored keyboard. Platform runtimes call this
1671    /// from their resume lifecycle event.
1672    pub fn notify_app_resumed(&mut self) -> bool {
1673        let app_context = Rc::clone(&self.app.app_context);
1674        app_context.enter(cranpose_ui::text_input_session::notify_app_resumed)
1675    }
1676
1677    #[cfg(all(
1678        feature = "clipboard-native",
1679        target_os = "linux",
1680        not(target_arch = "wasm32")
1681    ))]
1682    pub fn set_primary_selection(&mut self, text: &str) {
1683        use arboard::{LinuxClipboardKind, SetExtLinux};
1684        if let Some(ref mut clipboard) = self.app.clipboard {
1685            let result = clipboard
1686                .set()
1687                .clipboard(LinuxClipboardKind::Primary)
1688                .text(text.to_string());
1689            if let Err(e) = result {
1690                log::debug!("Primary selection set failed: {e:?}");
1691            }
1692        }
1693    }
1694
1695    #[cfg(not(all(
1696        feature = "clipboard-native",
1697        target_os = "linux",
1698        not(target_arch = "wasm32")
1699    )))]
1700    pub fn set_primary_selection(&mut self, _text: &str) {}
1701
1702    #[cfg(all(
1703        feature = "clipboard-native",
1704        target_os = "linux",
1705        not(target_arch = "wasm32")
1706    ))]
1707    pub fn get_primary_selection(&mut self) -> Option<String> {
1708        use arboard::{GetExtLinux, LinuxClipboardKind};
1709        if let Some(ref mut clipboard) = self.app.clipboard {
1710            clipboard
1711                .get()
1712                .clipboard(LinuxClipboardKind::Primary)
1713                .text()
1714                .ok()
1715        } else {
1716            None
1717        }
1718    }
1719
1720    #[cfg(not(all(
1721        feature = "clipboard-native",
1722        target_os = "linux",
1723        not(target_arch = "wasm32")
1724    )))]
1725    pub fn get_primary_selection(&mut self) -> Option<String> {
1726        None
1727    }
1728
1729    /// Syncs the current text field selection to PRIMARY (Linux X11).
1730    /// Call this when selection changes in a text field.
1731    pub fn sync_selection_to_primary(&mut self) {
1732        #[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
1733        {
1734            if let Some(text) = self.on_copy() {
1735                self.set_primary_selection(&text);
1736            }
1737        }
1738    }
1739
1740    /// Primary-surface form of [`SurfaceMut::set_pointer_source`].
1741    pub fn set_pointer_source(&mut self, source: PointerSource) {
1742        self.primary().set_pointer_source(source);
1743    }
1744
1745    /// Primary-surface form of [`SurfaceMut::pointer_source`].
1746    pub fn pointer_source(&self) -> PointerSource {
1747        self.surfaces[0].pointer_source
1748    }
1749
1750    /// Primary-surface form of [`SurfaceMut::set_cursor`].
1751    pub fn set_cursor(&mut self, x: f32, y: f32) -> bool {
1752        self.primary().set_cursor(x, y)
1753    }
1754
1755    /// Primary-surface form of [`SurfaceMut::set_cursor_at_time`].
1756    pub fn set_cursor_at_time(&mut self, x: f32, y: f32, time_ms: Option<i64>) -> bool {
1757        self.primary().set_cursor_at_time(x, y, time_ms)
1758    }
1759
1760    /// Primary-surface form of [`SurfaceMut::set_cursor_at_event_time`].
1761    pub fn set_cursor_at_event_time(
1762        &mut self,
1763        x: f32,
1764        y: f32,
1765        event_time: PointerEventTime,
1766    ) -> bool {
1767        self.primary().set_cursor_at_event_time(x, y, event_time)
1768    }
1769
1770    /// Primary-surface form of [`SurfaceMut::pointer_pressed`].
1771    pub fn pointer_pressed(&mut self) -> bool {
1772        self.primary().pointer_pressed()
1773    }
1774
1775    /// Primary-surface form of [`SurfaceMut::accessibility_activate`].
1776    pub fn accessibility_activate(&mut self, node_id: NodeId, canvas_key: Option<u64>) -> bool {
1777        self.primary().accessibility_activate(node_id, canvas_key)
1778    }
1779
1780    /// Primary-surface form of [`SurfaceMut::pointer_pressed_at_time`].
1781    pub fn pointer_pressed_at_time(&mut self, time_ms: Option<i64>) -> bool {
1782        self.primary().pointer_pressed_at_time(time_ms)
1783    }
1784
1785    /// Primary-surface form of [`SurfaceMut::pointer_pressed_at_event_time`].
1786    pub fn pointer_pressed_at_event_time(&mut self, event_time: PointerEventTime) -> bool {
1787        self.primary().pointer_pressed_at_event_time(event_time)
1788    }
1789
1790    /// Primary-surface form of [`SurfaceMut::pointer_released`].
1791    pub fn pointer_released(&mut self) -> bool {
1792        self.primary().pointer_released()
1793    }
1794
1795    /// Primary-surface form of [`SurfaceMut::pointer_released_at_position`].
1796    pub fn pointer_released_at_position(&mut self, x: f32, y: f32) -> bool {
1797        self.primary().pointer_released_at_position(x, y)
1798    }
1799
1800    /// Primary-surface form of
1801    /// [`SurfaceMut::pointer_released_at_position_time`].
1802    pub fn pointer_released_at_position_time(
1803        &mut self,
1804        x: f32,
1805        y: f32,
1806        time_ms: Option<i64>,
1807    ) -> bool {
1808        self.primary()
1809            .pointer_released_at_position_time(x, y, time_ms)
1810    }
1811
1812    /// Primary-surface form of
1813    /// [`SurfaceMut::pointer_released_at_position_event_time`].
1814    pub fn pointer_released_at_position_event_time(
1815        &mut self,
1816        x: f32,
1817        y: f32,
1818        event_time: PointerEventTime,
1819    ) -> bool {
1820        self.primary()
1821            .pointer_released_at_position_event_time(x, y, event_time)
1822    }
1823
1824    /// Primary-surface form of [`SurfaceMut::pointer_released_at_time`].
1825    pub fn pointer_released_at_time(&mut self, time_ms: Option<i64>) -> bool {
1826        self.primary().pointer_released_at_time(time_ms)
1827    }
1828
1829    /// Primary-surface form of [`SurfaceMut::pointer_released_at_event_time`].
1830    pub fn pointer_released_at_event_time(&mut self, event_time: PointerEventTime) -> bool {
1831        self.primary().pointer_released_at_event_time(event_time)
1832    }
1833
1834    /// Primary-surface form of [`SurfaceMut::secondary_pointer_pressed`].
1835    pub fn secondary_pointer_pressed(
1836        &mut self,
1837        pointer_id: u64,
1838        x: f32,
1839        y: f32,
1840        time_ms: Option<i64>,
1841    ) -> bool {
1842        self.primary()
1843            .secondary_pointer_pressed(pointer_id, x, y, time_ms)
1844    }
1845
1846    /// Primary-surface form of [`SurfaceMut::secondary_pointer_moved`].
1847    pub fn secondary_pointer_moved(
1848        &mut self,
1849        pointer_id: u64,
1850        x: f32,
1851        y: f32,
1852        time_ms: Option<i64>,
1853    ) -> bool {
1854        self.primary()
1855            .secondary_pointer_moved(pointer_id, x, y, time_ms)
1856    }
1857
1858    /// Primary-surface form of [`SurfaceMut::secondary_pointer_released`].
1859    pub fn secondary_pointer_released(
1860        &mut self,
1861        pointer_id: u64,
1862        x: f32,
1863        y: f32,
1864        time_ms: Option<i64>,
1865    ) -> bool {
1866        self.primary()
1867            .secondary_pointer_released(pointer_id, x, y, time_ms)
1868    }
1869
1870    /// Primary-surface form of [`SurfaceMut::pointer_zoomed`].
1871    pub fn pointer_zoomed(&mut self, zoom_factor: f32) -> bool {
1872        self.primary().pointer_zoomed(zoom_factor)
1873    }
1874
1875    /// Primary-surface form of [`SurfaceMut::wheel_scrolled`].
1876    pub fn wheel_scrolled(&mut self, wheel: crate::WheelScroll) -> bool {
1877        self.primary().wheel_scrolled(wheel)
1878    }
1879
1880    /// Primary-surface form of [`SurfaceMut::pointer_scrolled`].
1881    pub fn pointer_scrolled(&mut self, delta_x: f32, delta_y: f32) -> bool {
1882        self.primary().pointer_scrolled(delta_x, delta_y)
1883    }
1884
1885    /// Primary-surface form of [`SurfaceMut::set_on_rotary_scroll`].
1886    pub fn set_on_rotary_scroll<F>(&mut self, handler: F)
1887    where
1888        F: Fn(RotaryScrollEvent) -> bool + 'static,
1889    {
1890        self.primary().set_on_rotary_scroll(handler);
1891    }
1892
1893    /// Primary-surface form of [`SurfaceMut::clear_on_rotary_scroll`].
1894    pub fn clear_on_rotary_scroll(&mut self) {
1895        self.primary().clear_on_rotary_scroll();
1896    }
1897
1898    /// Primary-surface form of [`SurfaceMut::rotary_scrolled_by_detents`].
1899    pub fn rotary_scrolled_by_detents(&mut self, detents: f32, uptime_millis: u64) -> bool {
1900        self.primary()
1901            .rotary_scrolled_by_detents(detents, uptime_millis)
1902    }
1903
1904    /// Primary-surface form of [`SurfaceMut::rotary_scrolled`].
1905    pub fn rotary_scrolled(&mut self, event: RotaryScrollEvent) -> bool {
1906        self.primary().rotary_scrolled(event)
1907    }
1908
1909    /// Primary-surface form of [`SurfaceMut::cancel_gesture`].
1910    pub fn cancel_gesture(&mut self) {
1911        self.primary().cancel_gesture();
1912    }
1913
1914    /// Primary-surface form of [`SurfaceMut::cancel_gesture_unless_pressed`].
1915    pub fn cancel_gesture_unless_pressed(&mut self) {
1916        self.primary().cancel_gesture_unless_pressed();
1917    }
1918
1919    /// Offers the primary window's current pointer icon to the platform
1920    /// again, for the moments a windowing system has drawn its own default
1921    /// over it.
1922    pub fn refresh_pointer_icon(&self) {
1923        self.surfaces[0].pointer_icon.refresh();
1924    }
1925
1926    /// The pointer icon the platform has not applied to the primary window
1927    /// yet, or `None` when the icon has not changed since the last call.
1928    ///
1929    /// Platform backends call this after handing the shell a batch of input and
1930    /// set the returned icon on the window they own. Platforms with no pointing
1931    /// device never call it.
1932    pub fn take_pointer_icon_change(&self) -> Option<PointerIcon> {
1933        self.surfaces[0].pointer_icon.take_change()
1934    }
1935
1936    /// Installs the platform soft-keyboard handler for the primary window.
1937    ///
1938    /// The handler is invoked when a text field gains focus (`show_keyboard`)
1939    /// or when text-field focus is cleared or goes stale (`hide_keyboard`).
1940    /// Platform runtimes with an on-screen keyboard (Android, iOS) call this
1941    /// once after creating the shell.
1942    pub fn set_platform_text_input(
1943        &mut self,
1944        handler: Rc<dyn cranpose_ui::PlatformTextInputHandler>,
1945    ) {
1946        self.primary().set_platform_text_input(handler);
1947    }
1948
1949    /// Primary-surface form of [`SurfaceMut::dismiss_top_modal`].
1950    pub fn dismiss_top_modal(&mut self) -> bool {
1951        self.primary().dismiss_top_modal()
1952    }
1953
1954    /// Primary-surface form of [`SurfaceMut::move_focus_in_context`].
1955    pub fn move_focus_in_context(&mut self, direction: FocusDirection) -> bool {
1956        self.primary().move_focus_in_context(direction)
1957    }
1958
1959    /// Primary-surface form of [`SurfaceMut::on_key_event`].
1960    pub fn on_key_event(&mut self, event: &KeyEvent) -> bool {
1961        self.primary().on_key_event(event)
1962    }
1963
1964    /// Primary-surface form of [`SurfaceMut::on_paste`].
1965    pub fn on_paste(&mut self, text: &str) -> bool {
1966        self.primary().on_paste(text)
1967    }
1968
1969    /// Primary-surface form of [`SurfaceMut::on_copy`].
1970    pub fn on_copy(&mut self) -> Option<String> {
1971        self.primary().on_copy()
1972    }
1973
1974    /// Primary-surface form of [`SurfaceMut::on_cut`].
1975    pub fn on_cut(&mut self) -> Option<String> {
1976        self.primary().on_cut()
1977    }
1978
1979    /// Primary-surface form of [`SurfaceMut::on_ime_preedit`].
1980    pub fn on_ime_preedit(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1981        self.primary().on_ime_preedit(text, cursor)
1982    }
1983
1984    /// Primary-surface form of [`SurfaceMut::on_ime_finish_composing`].
1985    pub fn on_ime_finish_composing(&mut self) -> bool {
1986        self.primary().on_ime_finish_composing()
1987    }
1988
1989    /// Primary-surface form of [`SurfaceMut::on_ime_set_composing_region`].
1990    pub fn on_ime_set_composing_region(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1991        self.primary()
1992            .on_ime_set_composing_region(start_bytes, end_bytes)
1993    }
1994
1995    /// Primary-surface form of [`SurfaceMut::on_ime_set_selection`].
1996    pub fn on_ime_set_selection(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1997        self.primary().on_ime_set_selection(start_bytes, end_bytes)
1998    }
1999
2000    /// Primary-surface form of [`SurfaceMut::ime_editor_state`].
2001    pub fn ime_editor_state(&mut self) -> Option<cranpose_ui::text_field_focus::ImeEditorState> {
2002        self.primary().ime_editor_state()
2003    }
2004
2005    /// Primary-surface form of [`SurfaceMut::ime_caret_geometry`].
2006    pub fn ime_caret_geometry(
2007        &mut self,
2008    ) -> Option<cranpose_ui::text_field_focus::ImeCaretGeometry> {
2009        self.primary().ime_caret_geometry()
2010    }
2011
2012    /// Primary-surface form of [`SurfaceMut::ime_field_is_password`].
2013    pub fn ime_field_is_password(&mut self) -> bool {
2014        self.primary().ime_field_is_password()
2015    }
2016
2017    /// Primary-surface form of [`SurfaceMut::clear_text_field_focus`].
2018    pub fn clear_text_field_focus(&mut self) {
2019        self.primary().clear_text_field_focus();
2020    }
2021
2022    /// Primary-surface form of [`SurfaceMut::on_ime_delete_surrounding`].
2023    pub fn on_ime_delete_surrounding(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
2024        self.primary()
2025            .on_ime_delete_surrounding(before_bytes, after_bytes)
2026    }
2027}
2028
2029enum ActivationTarget {
2030    Direct(cranpose_foundation::SemanticsCustomAction),
2031    Edit(NodeId),
2032    Pointer(NodeId, Option<Rect>),
2033}
2034
2035fn activation_target(
2036    node: &cranpose_ui::SemanticsNode,
2037    node_id: NodeId,
2038    canvas_key: Option<u64>,
2039) -> Option<ActivationTarget> {
2040    if node.hidden {
2041        return None;
2042    }
2043    if node.node_id != node_id {
2044        return node
2045            .children
2046            .iter()
2047            .find_map(|child| activation_target(child, node_id, canvas_key));
2048    }
2049    if !node.enabled {
2050        return None;
2051    }
2052    if let Some(key) = canvas_key {
2053        let child = node
2054            .details()
2055            .canvas_children
2056            .iter()
2057            .find(|child| child.key == key)?;
2058        return (child.enabled && child.clickable)
2059            .then_some(ActivationTarget::Pointer(node_id, Some(child.bounds)));
2060    }
2061    if let Some(action) = &node.on_click {
2062        return Some(ActivationTarget::Direct(action.clone()));
2063    }
2064    if node.details().editable_text && node.focusable {
2065        return Some(ActivationTarget::Edit(node_id));
2066    }
2067    node.actions.first().map(|action| match action {
2068        cranpose_ui::SemanticsAction::Click { handler } => {
2069            ActivationTarget::Pointer(handler.node_id(), None)
2070        }
2071    })
2072}
2073
2074fn activation_input(
2075    root: &LayoutBox,
2076    node_id: NodeId,
2077    canvas_bounds: Option<Rect>,
2078) -> Option<(Point, Point, Rc<cranpose_ui::ModifierNodeSlices>)> {
2079    if root.node_id != node_id {
2080        return root
2081            .children
2082            .iter()
2083            .find_map(|child| activation_input(child, node_id, canvas_bounds));
2084    }
2085    let bounds = canvas_bounds.map_or(root.rect, |bounds| Rect {
2086        x: root.rect.x + bounds.x,
2087        y: root.rect.y + bounds.y,
2088        ..bounds
2089    });
2090    let position = Point {
2091        x: bounds.x + bounds.width * 0.5,
2092        y: bounds.y + bounds.height * 0.5,
2093    };
2094    let local = Point {
2095        x: position.x - root.rect.x,
2096        y: position.y - root.rect.y,
2097    };
2098    (bounds.width > 0.0 && bounds.height > 0.0 && position.x.is_finite() && position.y.is_finite())
2099        .then(|| (position, local, Rc::clone(&root.node_data.modifier_slices)))
2100}
2101
2102fn plain_key_down(event: &KeyEvent) -> bool {
2103    event.event_type == KeyEventType::KeyDown
2104        && !event.modifiers.ctrl
2105        && !event.modifiers.meta
2106        && !event.modifiers.alt
2107}