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        use KeyEventType::KeyDown;
1195
1196        if event.event_type == KeyDown && event.modifiers.command_or_ctrl() {
1197            #[cfg(all(
1198                feature = "clipboard-native",
1199                not(target_arch = "wasm32"),
1200                not(target_os = "android"),
1201                not(target_os = "ios")
1202            ))]
1203            {
1204                match event.key_code {
1205                    KeyCode::C => {
1206                        if let Some(text) = self.on_copy_inner() {
1207                            cranpose_ui::clipboard_session::clipboard_write_text(&text);
1208                            return true;
1209                        }
1210                    }
1211                    KeyCode::X => {
1212                        if let Some(text) = self.on_cut_inner() {
1213                            cranpose_ui::clipboard_session::clipboard_write_text(&text);
1214                            self.mark_dirty();
1215                            self.shell.app.request_layout_pass();
1216                            return true;
1217                        }
1218                    }
1219                    KeyCode::V => {
1220                        if let Some(text) = cranpose_ui::clipboard_session::clipboard_read_text()
1221                            && self.on_paste_inner(&text)
1222                        {
1223                            return true;
1224                        }
1225                    }
1226                    _ => {}
1227                }
1228            }
1229        }
1230
1231        if self.on_focus_key(event) {
1232            return true;
1233        }
1234
1235        if self.on_escape_key(event) {
1236            return true;
1237        }
1238
1239        if self.on_activation_key(event) || self.on_arrow_key(event) {
1240            return true;
1241        }
1242
1243        let handled = if cranpose_ui::text_field_focus::has_focused_field() {
1244            run_in_mutable_snapshot(|| cranpose_ui::text_field_focus::dispatch_key_event(event))
1245        } else {
1246            run_in_mutable_snapshot(|| cranpose_ui::dispatch_unhandled_key_event(event))
1247        }
1248        .unwrap_or(false);
1249
1250        if handled {
1251            self.mark_dirty();
1252            self.shell.app.request_layout_pass();
1253        }
1254
1255        handled
1256    }
1257
1258    /// Handles paste event from platform clipboard.
1259    /// Returns `true` if the paste was consumed by a focused text field.
1260    /// O(1) operation using stored handler.
1261    pub fn on_paste(&mut self, text: &str) -> bool {
1262        if self.inspector_owns_keyboard() {
1263            return true;
1264        }
1265        let _event_handler = enter_event_handler_scope();
1266        let app_context = Rc::clone(&self.shell.app.app_context);
1267        app_context.enter(|| self.on_paste_inner(text))
1268    }
1269
1270    fn on_paste_inner(&mut self, text: &str) -> bool {
1271        let handled =
1272            run_in_mutable_snapshot(|| cranpose_ui::text_field_focus::dispatch_paste(text))
1273                .unwrap_or(false);
1274
1275        if handled {
1276            self.mark_dirty();
1277            self.shell.app.request_layout_pass();
1278        }
1279
1280        handled
1281    }
1282
1283    /// Handles copy request from platform.
1284    /// Returns the selected text from focused text field, or None.
1285    /// O(1) operation using stored handler.
1286    pub fn on_copy(&mut self) -> Option<String> {
1287        let app_context = Rc::clone(&self.shell.app.app_context);
1288        if self.inspector_owns_keyboard() {
1289            return None;
1290        }
1291        app_context.enter(|| self.on_copy_inner())
1292    }
1293
1294    fn on_copy_inner(&mut self) -> Option<String> {
1295        cranpose_ui::text_field_focus::dispatch_copy()
1296    }
1297
1298    /// Handles cut request from platform.
1299    /// Returns the cut text from focused text field, or None.
1300    /// O(1) operation using stored handler.
1301    pub fn on_cut(&mut self) -> Option<String> {
1302        let _event_handler = enter_event_handler_scope();
1303        if self.inspector_owns_keyboard() {
1304            return None;
1305        }
1306        let app_context = Rc::clone(&self.shell.app.app_context);
1307        app_context.enter(|| self.on_cut_inner())
1308    }
1309
1310    fn on_cut_inner(&mut self) -> Option<String> {
1311        let text =
1312            run_in_mutable_snapshot(cranpose_ui::text_field_focus::dispatch_cut).unwrap_or(None);
1313
1314        if text.is_some() {
1315            self.mark_dirty();
1316            self.shell.app.request_layout_pass();
1317        }
1318
1319        text
1320    }
1321
1322    /// Handles IME preedit (composition) events.
1323    /// Called when the input method is composing text (e.g., typing CJK characters).
1324    ///
1325    /// - `text`: The current preedit text (empty to clear composition state)
1326    /// - `cursor`: Optional cursor position within the preedit text (start, end)
1327    ///
1328    /// Returns `true` if a text field consumed the event.
1329    pub fn on_ime_preedit(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1330        if self.inspector_owns_keyboard() {
1331            return true;
1332        }
1333        let _event_handler = enter_event_handler_scope();
1334        let app_context = Rc::clone(&self.shell.app.app_context);
1335        app_context.enter(|| self.on_ime_preedit_inner(text, cursor))
1336    }
1337
1338    fn on_ime_preedit_inner(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1339        let handled = run_in_mutable_snapshot(|| {
1340            cranpose_ui::text_field_focus::dispatch_ime_preedit(text, cursor)
1341        })
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    /// Finishes the active IME composition, keeping the composed text as
1353    /// committed text (Android `finishComposingText` semantics).
1354    /// Returns `true` if a text field consumed the event.
1355    pub fn on_ime_finish_composing(&mut self) -> bool {
1356        if self.inspector_owns_keyboard() {
1357            return true;
1358        }
1359        let _event_handler = enter_event_handler_scope();
1360        let app_context = Rc::clone(&self.shell.app.app_context);
1361        app_context.enter(|| self.on_ime_finish_composing_inner())
1362    }
1363
1364    fn on_ime_finish_composing_inner(&mut self) -> bool {
1365        let handled =
1366            run_in_mutable_snapshot(cranpose_ui::text_field_focus::dispatch_ime_finish_composing)
1367                .unwrap_or(false);
1368
1369        if handled {
1370            self.mark_dirty();
1371            self.shell.app.request_layout_pass();
1372        }
1373
1374        handled
1375    }
1376
1377    /// Marks existing text in the focused field as the composing region
1378    /// without changing it (Android `setComposingRegion` semantics). Offsets
1379    /// are UTF-8 bytes. Returns `true` if a text field consumed the event.
1380    pub fn on_ime_set_composing_region(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1381        if self.inspector_owns_keyboard() {
1382            return true;
1383        }
1384        let _event_handler = enter_event_handler_scope();
1385        let app_context = Rc::clone(&self.shell.app.app_context);
1386        app_context.enter(|| {
1387            let handled = run_in_mutable_snapshot(|| {
1388                cranpose_ui::text_field_focus::dispatch_ime_set_composing_region(
1389                    start_bytes,
1390                    end_bytes,
1391                )
1392            })
1393            .unwrap_or(false);
1394
1395            if handled {
1396                self.mark_dirty();
1397                self.shell.app.request_layout_pass();
1398            }
1399
1400            handled
1401        })
1402    }
1403
1404    /// Moves the focused field's selection/caret to `[start_bytes, end_bytes)`
1405    /// without editing text (Android `InputConnection.setSelection`; the path
1406    /// Gboard's spacebar-swipe uses to scrub the cursor). Offsets are UTF-8
1407    /// bytes. Returns `true` if a text field consumed the event.
1408    pub fn on_ime_set_selection(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1409        if self.inspector_owns_keyboard() {
1410            return true;
1411        }
1412        let _event_handler = enter_event_handler_scope();
1413        let app_context = Rc::clone(&self.shell.app.app_context);
1414        app_context.enter(|| {
1415            let handled = run_in_mutable_snapshot(|| {
1416                cranpose_ui::text_field_focus::dispatch_ime_set_selection(start_bytes, end_bytes)
1417            })
1418            .unwrap_or(false);
1419
1420            if handled {
1421                self.mark_dirty();
1422            }
1423
1424            handled
1425        })
1426    }
1427
1428    /// Returns a snapshot of the focused text field's editable state for
1429    /// platform IMEs (text, selection and composition in UTF-8 bytes), or
1430    /// `None` when no text field is focused.
1431    pub fn ime_editor_state(&mut self) -> Option<cranpose_ui::text_field_focus::ImeEditorState> {
1432        let app_context = Rc::clone(&self.shell.app.app_context);
1433        app_context.enter(cranpose_ui::text_field_focus::focused_editor_state)
1434    }
1435
1436    /// Window-space caret geometry of the focused field for coordinate-based
1437    /// platform text input (iOS trackpad cursor + tap-to-position), or `None`
1438    /// when no text field is focused.
1439    pub fn ime_caret_geometry(
1440        &mut self,
1441    ) -> Option<cranpose_ui::text_field_focus::ImeCaretGeometry> {
1442        let app_context = Rc::clone(&self.shell.app.app_context);
1443        app_context.enter(cranpose_ui::text_field_focus::focused_caret_geometry)
1444    }
1445
1446    /// Clears text-field focus (used by platform IME actions such as
1447    /// Android's Done). The focus-loss notification hides the soft keyboard.
1448    pub fn clear_text_field_focus(&mut self) {
1449        let _event_handler = enter_event_handler_scope();
1450        let app_context = Rc::clone(&self.shell.app.app_context);
1451        app_context.enter(cranpose_ui::text_field_focus::clear_focus);
1452        self.mark_dirty();
1453        self.shell.app.request_layout_pass();
1454    }
1455
1456    /// Handles IME delete-surrounding events.
1457    /// Returns `true` if a text field consumed the event.
1458    pub fn on_ime_delete_surrounding(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
1459        if self.inspector_owns_keyboard() {
1460            return true;
1461        }
1462        let _event_handler = enter_event_handler_scope();
1463        let app_context = Rc::clone(&self.shell.app.app_context);
1464        app_context.enter(|| self.on_ime_delete_surrounding_inner(before_bytes, after_bytes))
1465    }
1466
1467    fn on_ime_delete_surrounding_inner(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
1468        let handled = run_in_mutable_snapshot(|| {
1469            cranpose_ui::text_field_focus::dispatch_delete_surrounding(before_bytes, after_bytes)
1470        })
1471        .unwrap_or(false);
1472
1473        if handled {
1474            self.mark_dirty();
1475            self.shell.app.request_layout_pass();
1476        }
1477
1478        handled
1479    }
1480}
1481
1482impl<R> AppShell<R>
1483where
1484    R: Renderer,
1485    R::Error: Debug,
1486{
1487    /// Sets the keyboard modifiers held right now, so the platform's live
1488    /// modifier state (winit's `ModifiersChanged`, a DOM event's
1489    /// `shiftKey`/`ctrlKey`/`altKey`/`metaKey`) reaches every `PointerEvent`
1490    /// the shell dispatches from here on -- the same state the wheel path
1491    /// already carries via [`WheelScroll::with_modifiers`](crate::WheelScroll::with_modifiers).
1492    /// A platform that never calls this leaves pointer events reporting
1493    /// `None` (see [`PointerEvent::modifiers`]) rather than a silently wrong
1494    /// "nothing held".
1495    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
1496        self.app.modifiers = Some(modifiers);
1497    }
1498
1499    /// The keyboard modifiers most recently set via
1500    /// [`set_modifiers`](Self::set_modifiers), or `None` if the platform has
1501    /// never reported them.
1502    pub fn modifiers(&self) -> Option<Modifiers> {
1503        self.app.modifiers
1504    }
1505
1506    /// Pixels per rotary detent used by
1507    /// [`rotary_scrolled_by_detents`](Self::rotary_scrolled_by_detents).
1508    pub fn rotary_scroll_factor(&self) -> f32 {
1509        self.app.rotary_scroll_factor
1510    }
1511
1512    /// Sets the pixels-per-detent factor for rotary input.
1513    ///
1514    /// On Wear OS this must be `ViewConfiguration.getScaledVerticalScrollFactor()`
1515    /// for pixel-exact parity with Compose. The host activity can read it over
1516    /// JNI once at startup and push it here; when it does not, the shell falls
1517    /// back to [`DEFAULT_ROTARY_SCROLL_FACTOR_DP`] scaled by display density.
1518    ///
1519    /// Non-finite or non-positive values are ignored.
1520    pub fn set_rotary_scroll_factor(&mut self, factor: f32) {
1521        if factor.is_finite() && factor > 0.0 {
1522            self.app.rotary_scroll_factor = factor;
1523        }
1524    }
1525
1526    /// Notifies the framework that the host app was paused/backgrounded.
1527    ///
1528    /// Withdraws any outstanding soft-keyboard request (and hides the keyboard)
1529    /// so the "keyboard shown" state does not survive across the pause and get
1530    /// restored on resume with no focused field. Platform runtimes call this
1531    /// from their pause lifecycle event.
1532    pub fn notify_app_paused(&mut self) {
1533        let app_context = Rc::clone(&self.app.app_context);
1534        app_context.enter(cranpose_ui::text_input_session::notify_app_paused);
1535    }
1536
1537    /// Notifies the framework that the host app resumed/foregrounded.
1538    ///
1539    /// Never auto-shows the soft keyboard, even for a still-focused field: a
1540    /// warm resume keeps the caret but must not resurrect the keyboard (the user
1541    /// taps the field to bring it back). Always returns `false` so the platform
1542    /// runtime force-hides the OS-restored keyboard. Platform runtimes call this
1543    /// from their resume lifecycle event.
1544    pub fn notify_app_resumed(&mut self) -> bool {
1545        let app_context = Rc::clone(&self.app.app_context);
1546        app_context.enter(cranpose_ui::text_input_session::notify_app_resumed)
1547    }
1548
1549    #[cfg(all(
1550        feature = "clipboard-native",
1551        target_os = "linux",
1552        not(target_arch = "wasm32")
1553    ))]
1554    pub fn set_primary_selection(&mut self, text: &str) {
1555        use arboard::{LinuxClipboardKind, SetExtLinux};
1556        if let Some(ref mut clipboard) = self.app.clipboard {
1557            let result = clipboard
1558                .set()
1559                .clipboard(LinuxClipboardKind::Primary)
1560                .text(text.to_string());
1561            if let Err(e) = result {
1562                log::debug!("Primary selection set failed: {e:?}");
1563            }
1564        }
1565    }
1566
1567    #[cfg(not(all(
1568        feature = "clipboard-native",
1569        target_os = "linux",
1570        not(target_arch = "wasm32")
1571    )))]
1572    pub fn set_primary_selection(&mut self, _text: &str) {}
1573
1574    #[cfg(all(
1575        feature = "clipboard-native",
1576        target_os = "linux",
1577        not(target_arch = "wasm32")
1578    ))]
1579    pub fn get_primary_selection(&mut self) -> Option<String> {
1580        use arboard::{GetExtLinux, LinuxClipboardKind};
1581        if let Some(ref mut clipboard) = self.app.clipboard {
1582            clipboard
1583                .get()
1584                .clipboard(LinuxClipboardKind::Primary)
1585                .text()
1586                .ok()
1587        } else {
1588            None
1589        }
1590    }
1591
1592    #[cfg(not(all(
1593        feature = "clipboard-native",
1594        target_os = "linux",
1595        not(target_arch = "wasm32")
1596    )))]
1597    pub fn get_primary_selection(&mut self) -> Option<String> {
1598        None
1599    }
1600
1601    /// Syncs the current text field selection to PRIMARY (Linux X11).
1602    /// Call this when selection changes in a text field.
1603    pub fn sync_selection_to_primary(&mut self) {
1604        #[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
1605        {
1606            if let Some(text) = self.on_copy() {
1607                self.set_primary_selection(&text);
1608            }
1609        }
1610    }
1611
1612    /// Primary-surface form of [`SurfaceMut::set_pointer_source`].
1613    pub fn set_pointer_source(&mut self, source: PointerSource) {
1614        self.primary().set_pointer_source(source);
1615    }
1616
1617    /// Primary-surface form of [`SurfaceMut::pointer_source`].
1618    pub fn pointer_source(&self) -> PointerSource {
1619        self.surfaces[0].pointer_source
1620    }
1621
1622    /// Primary-surface form of [`SurfaceMut::set_cursor`].
1623    pub fn set_cursor(&mut self, x: f32, y: f32) -> bool {
1624        self.primary().set_cursor(x, y)
1625    }
1626
1627    /// Primary-surface form of [`SurfaceMut::set_cursor_at_time`].
1628    pub fn set_cursor_at_time(&mut self, x: f32, y: f32, time_ms: Option<i64>) -> bool {
1629        self.primary().set_cursor_at_time(x, y, time_ms)
1630    }
1631
1632    /// Primary-surface form of [`SurfaceMut::set_cursor_at_event_time`].
1633    pub fn set_cursor_at_event_time(
1634        &mut self,
1635        x: f32,
1636        y: f32,
1637        event_time: PointerEventTime,
1638    ) -> bool {
1639        self.primary().set_cursor_at_event_time(x, y, event_time)
1640    }
1641
1642    /// Primary-surface form of [`SurfaceMut::pointer_pressed`].
1643    pub fn pointer_pressed(&mut self) -> bool {
1644        self.primary().pointer_pressed()
1645    }
1646
1647    /// Primary-surface form of [`SurfaceMut::accessibility_activate`].
1648    pub fn accessibility_activate(&mut self, node_id: NodeId, canvas_key: Option<u64>) -> bool {
1649        self.primary().accessibility_activate(node_id, canvas_key)
1650    }
1651
1652    /// Primary-surface form of [`SurfaceMut::pointer_pressed_at_time`].
1653    pub fn pointer_pressed_at_time(&mut self, time_ms: Option<i64>) -> bool {
1654        self.primary().pointer_pressed_at_time(time_ms)
1655    }
1656
1657    /// Primary-surface form of [`SurfaceMut::pointer_pressed_at_event_time`].
1658    pub fn pointer_pressed_at_event_time(&mut self, event_time: PointerEventTime) -> bool {
1659        self.primary().pointer_pressed_at_event_time(event_time)
1660    }
1661
1662    /// Primary-surface form of [`SurfaceMut::pointer_released`].
1663    pub fn pointer_released(&mut self) -> bool {
1664        self.primary().pointer_released()
1665    }
1666
1667    /// Primary-surface form of [`SurfaceMut::pointer_released_at_position`].
1668    pub fn pointer_released_at_position(&mut self, x: f32, y: f32) -> bool {
1669        self.primary().pointer_released_at_position(x, y)
1670    }
1671
1672    /// Primary-surface form of
1673    /// [`SurfaceMut::pointer_released_at_position_time`].
1674    pub fn pointer_released_at_position_time(
1675        &mut self,
1676        x: f32,
1677        y: f32,
1678        time_ms: Option<i64>,
1679    ) -> bool {
1680        self.primary()
1681            .pointer_released_at_position_time(x, y, time_ms)
1682    }
1683
1684    /// Primary-surface form of
1685    /// [`SurfaceMut::pointer_released_at_position_event_time`].
1686    pub fn pointer_released_at_position_event_time(
1687        &mut self,
1688        x: f32,
1689        y: f32,
1690        event_time: PointerEventTime,
1691    ) -> bool {
1692        self.primary()
1693            .pointer_released_at_position_event_time(x, y, event_time)
1694    }
1695
1696    /// Primary-surface form of [`SurfaceMut::pointer_released_at_time`].
1697    pub fn pointer_released_at_time(&mut self, time_ms: Option<i64>) -> bool {
1698        self.primary().pointer_released_at_time(time_ms)
1699    }
1700
1701    /// Primary-surface form of [`SurfaceMut::pointer_released_at_event_time`].
1702    pub fn pointer_released_at_event_time(&mut self, event_time: PointerEventTime) -> bool {
1703        self.primary().pointer_released_at_event_time(event_time)
1704    }
1705
1706    /// Primary-surface form of [`SurfaceMut::secondary_pointer_pressed`].
1707    pub fn secondary_pointer_pressed(
1708        &mut self,
1709        pointer_id: u64,
1710        x: f32,
1711        y: f32,
1712        time_ms: Option<i64>,
1713    ) -> bool {
1714        self.primary()
1715            .secondary_pointer_pressed(pointer_id, x, y, time_ms)
1716    }
1717
1718    /// Primary-surface form of [`SurfaceMut::secondary_pointer_moved`].
1719    pub fn secondary_pointer_moved(
1720        &mut self,
1721        pointer_id: u64,
1722        x: f32,
1723        y: f32,
1724        time_ms: Option<i64>,
1725    ) -> bool {
1726        self.primary()
1727            .secondary_pointer_moved(pointer_id, x, y, time_ms)
1728    }
1729
1730    /// Primary-surface form of [`SurfaceMut::secondary_pointer_released`].
1731    pub fn secondary_pointer_released(
1732        &mut self,
1733        pointer_id: u64,
1734        x: f32,
1735        y: f32,
1736        time_ms: Option<i64>,
1737    ) -> bool {
1738        self.primary()
1739            .secondary_pointer_released(pointer_id, x, y, time_ms)
1740    }
1741
1742    /// Primary-surface form of [`SurfaceMut::pointer_zoomed`].
1743    pub fn pointer_zoomed(&mut self, zoom_factor: f32) -> bool {
1744        self.primary().pointer_zoomed(zoom_factor)
1745    }
1746
1747    /// Primary-surface form of [`SurfaceMut::wheel_scrolled`].
1748    pub fn wheel_scrolled(&mut self, wheel: crate::WheelScroll) -> bool {
1749        self.primary().wheel_scrolled(wheel)
1750    }
1751
1752    /// Primary-surface form of [`SurfaceMut::pointer_scrolled`].
1753    pub fn pointer_scrolled(&mut self, delta_x: f32, delta_y: f32) -> bool {
1754        self.primary().pointer_scrolled(delta_x, delta_y)
1755    }
1756
1757    /// Primary-surface form of [`SurfaceMut::set_on_rotary_scroll`].
1758    pub fn set_on_rotary_scroll<F>(&mut self, handler: F)
1759    where
1760        F: Fn(RotaryScrollEvent) -> bool + 'static,
1761    {
1762        self.primary().set_on_rotary_scroll(handler);
1763    }
1764
1765    /// Primary-surface form of [`SurfaceMut::clear_on_rotary_scroll`].
1766    pub fn clear_on_rotary_scroll(&mut self) {
1767        self.primary().clear_on_rotary_scroll();
1768    }
1769
1770    /// Primary-surface form of [`SurfaceMut::rotary_scrolled_by_detents`].
1771    pub fn rotary_scrolled_by_detents(&mut self, detents: f32, uptime_millis: u64) -> bool {
1772        self.primary()
1773            .rotary_scrolled_by_detents(detents, uptime_millis)
1774    }
1775
1776    /// Primary-surface form of [`SurfaceMut::rotary_scrolled`].
1777    pub fn rotary_scrolled(&mut self, event: RotaryScrollEvent) -> bool {
1778        self.primary().rotary_scrolled(event)
1779    }
1780
1781    /// Primary-surface form of [`SurfaceMut::cancel_gesture`].
1782    pub fn cancel_gesture(&mut self) {
1783        self.primary().cancel_gesture();
1784    }
1785
1786    /// Primary-surface form of [`SurfaceMut::cancel_gesture_unless_pressed`].
1787    pub fn cancel_gesture_unless_pressed(&mut self) {
1788        self.primary().cancel_gesture_unless_pressed();
1789    }
1790
1791    /// Offers the primary window's current pointer icon to the platform
1792    /// again, for the moments a windowing system has drawn its own default
1793    /// over it.
1794    pub fn refresh_pointer_icon(&self) {
1795        self.surfaces[0].pointer_icon.refresh();
1796    }
1797
1798    /// The pointer icon the platform has not applied to the primary window
1799    /// yet, or `None` when the icon has not changed since the last call.
1800    ///
1801    /// Platform backends call this after handing the shell a batch of input and
1802    /// set the returned icon on the window they own. Platforms with no pointing
1803    /// device never call it.
1804    pub fn take_pointer_icon_change(&self) -> Option<PointerIcon> {
1805        self.surfaces[0].pointer_icon.take_change()
1806    }
1807
1808    /// Installs the platform soft-keyboard handler for the primary window.
1809    ///
1810    /// The handler is invoked when a text field gains focus (`show_keyboard`)
1811    /// or when text-field focus is cleared or goes stale (`hide_keyboard`).
1812    /// Platform runtimes with an on-screen keyboard (Android, iOS) call this
1813    /// once after creating the shell.
1814    pub fn set_platform_text_input(
1815        &mut self,
1816        handler: Rc<dyn cranpose_ui::PlatformTextInputHandler>,
1817    ) {
1818        self.primary().set_platform_text_input(handler);
1819    }
1820
1821    /// Primary-surface form of [`SurfaceMut::dismiss_top_modal`].
1822    pub fn dismiss_top_modal(&mut self) -> bool {
1823        self.primary().dismiss_top_modal()
1824    }
1825
1826    /// Primary-surface form of [`SurfaceMut::move_focus_in_context`].
1827    pub fn move_focus_in_context(&mut self, direction: FocusDirection) -> bool {
1828        self.primary().move_focus_in_context(direction)
1829    }
1830
1831    /// Primary-surface form of [`SurfaceMut::on_key_event`].
1832    pub fn on_key_event(&mut self, event: &KeyEvent) -> bool {
1833        self.primary().on_key_event(event)
1834    }
1835
1836    /// Primary-surface form of [`SurfaceMut::on_paste`].
1837    pub fn on_paste(&mut self, text: &str) -> bool {
1838        self.primary().on_paste(text)
1839    }
1840
1841    /// Primary-surface form of [`SurfaceMut::on_copy`].
1842    pub fn on_copy(&mut self) -> Option<String> {
1843        self.primary().on_copy()
1844    }
1845
1846    /// Primary-surface form of [`SurfaceMut::on_cut`].
1847    pub fn on_cut(&mut self) -> Option<String> {
1848        self.primary().on_cut()
1849    }
1850
1851    /// Primary-surface form of [`SurfaceMut::on_ime_preedit`].
1852    pub fn on_ime_preedit(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
1853        self.primary().on_ime_preedit(text, cursor)
1854    }
1855
1856    /// Primary-surface form of [`SurfaceMut::on_ime_finish_composing`].
1857    pub fn on_ime_finish_composing(&mut self) -> bool {
1858        self.primary().on_ime_finish_composing()
1859    }
1860
1861    /// Primary-surface form of [`SurfaceMut::on_ime_set_composing_region`].
1862    pub fn on_ime_set_composing_region(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1863        self.primary()
1864            .on_ime_set_composing_region(start_bytes, end_bytes)
1865    }
1866
1867    /// Primary-surface form of [`SurfaceMut::on_ime_set_selection`].
1868    pub fn on_ime_set_selection(&mut self, start_bytes: usize, end_bytes: usize) -> bool {
1869        self.primary().on_ime_set_selection(start_bytes, end_bytes)
1870    }
1871
1872    /// Primary-surface form of [`SurfaceMut::ime_editor_state`].
1873    pub fn ime_editor_state(&mut self) -> Option<cranpose_ui::text_field_focus::ImeEditorState> {
1874        self.primary().ime_editor_state()
1875    }
1876
1877    /// Primary-surface form of [`SurfaceMut::ime_caret_geometry`].
1878    pub fn ime_caret_geometry(
1879        &mut self,
1880    ) -> Option<cranpose_ui::text_field_focus::ImeCaretGeometry> {
1881        self.primary().ime_caret_geometry()
1882    }
1883
1884    /// Primary-surface form of [`SurfaceMut::clear_text_field_focus`].
1885    pub fn clear_text_field_focus(&mut self) {
1886        self.primary().clear_text_field_focus();
1887    }
1888
1889    /// Primary-surface form of [`SurfaceMut::on_ime_delete_surrounding`].
1890    pub fn on_ime_delete_surrounding(&mut self, before_bytes: usize, after_bytes: usize) -> bool {
1891        self.primary()
1892            .on_ime_delete_surrounding(before_bytes, after_bytes)
1893    }
1894}
1895
1896enum ActivationTarget {
1897    Direct(cranpose_foundation::SemanticsCustomAction),
1898    Edit(NodeId),
1899    Pointer(NodeId, Option<Rect>),
1900}
1901
1902fn activation_target(
1903    node: &cranpose_ui::SemanticsNode,
1904    node_id: NodeId,
1905    canvas_key: Option<u64>,
1906) -> Option<ActivationTarget> {
1907    if node.hidden {
1908        return None;
1909    }
1910    if node.node_id != node_id {
1911        return node
1912            .children
1913            .iter()
1914            .find_map(|child| activation_target(child, node_id, canvas_key));
1915    }
1916    if !node.enabled {
1917        return None;
1918    }
1919    if let Some(key) = canvas_key {
1920        let child = node.canvas_children.iter().find(|child| child.key == key)?;
1921        return (child.enabled && child.clickable)
1922            .then_some(ActivationTarget::Pointer(node_id, Some(child.bounds)));
1923    }
1924    if let Some(action) = &node.on_click {
1925        return Some(ActivationTarget::Direct(action.clone()));
1926    }
1927    if node.editable_text && node.focusable {
1928        return Some(ActivationTarget::Edit(node_id));
1929    }
1930    node.actions.first().map(|action| match action {
1931        cranpose_ui::SemanticsAction::Click { handler } => {
1932            ActivationTarget::Pointer(handler.node_id(), None)
1933        }
1934    })
1935}
1936
1937fn activation_input(
1938    root: &LayoutBox,
1939    node_id: NodeId,
1940    canvas_bounds: Option<Rect>,
1941) -> Option<(Point, Point, Rc<cranpose_ui::ModifierNodeSlices>)> {
1942    if root.node_id != node_id {
1943        return root
1944            .children
1945            .iter()
1946            .find_map(|child| activation_input(child, node_id, canvas_bounds));
1947    }
1948    let bounds = canvas_bounds.map_or(root.rect, |bounds| Rect {
1949        x: root.rect.x + bounds.x,
1950        y: root.rect.y + bounds.y,
1951        ..bounds
1952    });
1953    let position = Point {
1954        x: bounds.x + bounds.width * 0.5,
1955        y: bounds.y + bounds.height * 0.5,
1956    };
1957    let local = Point {
1958        x: position.x - root.rect.x,
1959        y: position.y - root.rect.y,
1960    };
1961    (bounds.width > 0.0 && bounds.height > 0.0 && position.x.is_finite() && position.y.is_finite())
1962        .then(|| (position, local, Rc::clone(&root.node_data.modifier_slices)))
1963}
1964
1965fn plain_key_down(event: &KeyEvent) -> bool {
1966    event.event_type == KeyEventType::KeyDown
1967        && !event.modifiers.ctrl
1968        && !event.modifiers.meta
1969        && !event.modifiers.alt
1970}