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