i-slint-core 1.16.0

Internal Slint Runtime Library.
Documentation
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
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0

use super::{
    EventResult, FocusReasonArg, Item, ItemConsts, ItemRc, ItemRendererRef, KeyEventArg,
    MouseCursor, PointerEvent, PointerEventArg, PointerEventButton, PointerEventKind,
    PointerScrollEvent, PointerScrollEventArg, RenderingResult, VoidArg,
};
use crate::api::LogicalPosition;
use crate::input::{
    FocusEvent, FocusEventResult, FocusReason, InputEventFilterResult, InputEventResult,
    InternalKeyEvent, KeyEventResult, KeyEventType, Keys, MouseEvent,
};
use crate::item_rendering::CachedRenderingData;
use crate::items::ItemTreeVTable;
use crate::layout::{LayoutInfo, Orientation};
use crate::lengths::{LogicalLength, LogicalPoint, LogicalRect, LogicalSize, PointLengths};
use crate::properties::PropertyTracker;
#[cfg(feature = "rtti")]
use crate::rtti::*;
use crate::window::{WindowAdapter, WindowInner};
use crate::{Callback, Coord, Property};
use alloc::{boxed::Box, rc::Rc, vec::Vec};
use const_field_offset::FieldOffsets;
use core::cell::Cell;
use core::pin::Pin;
use i_slint_core_macros::*;
use vtable::{VRcMapped, VWeakMapped};

/// The implementation of the `TouchArea` element
#[repr(C)]
#[derive(FieldOffsets, SlintElement, Default)]
#[pin]
pub struct TouchArea {
    pub enabled: Property<bool>,
    /// FIXME: We should annotate this as an "output" property.
    pub pressed: Property<bool>,
    pub has_hover: Property<bool>,
    /// FIXME: there should be just one property for the point instead of two.
    /// Could even be merged with pressed in a `Property<Option<Point>>` (of course, in the
    /// implementation item only, for the compiler it would stay separate properties)
    pub pressed_x: Property<LogicalLength>,
    pub pressed_y: Property<LogicalLength>,
    /// FIXME: should maybe be as parameter to the mouse event instead. Or at least just one property
    pub mouse_x: Property<LogicalLength>,
    pub mouse_y: Property<LogicalLength>,
    pub mouse_cursor: Property<MouseCursor>,
    pub clicked: Callback<VoidArg>,
    pub double_clicked: Callback<VoidArg>,
    pub moved: Callback<VoidArg>,
    pub pointer_event: Callback<PointerEventArg>,
    pub scroll_event: Callback<PointerScrollEventArg, EventResult>,
    /// FIXME: remove this
    pub cached_rendering_data: CachedRenderingData,
    /// true when we are currently grabbing the mouse
    grabbed: Cell<bool>,
}

impl Item for TouchArea {
    fn init(self: Pin<&Self>, _self_rc: &ItemRc) {}

    fn deinit(self: Pin<&Self>, _window_adapter: &Rc<dyn WindowAdapter>) {}

    fn layout_info(
        self: Pin<&Self>,
        _orientation: Orientation,
        _cross_axis_constraint: Coord,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> LayoutInfo {
        LayoutInfo { stretch: 1., ..LayoutInfo::default() }
    }

    fn input_event_filter_before_children(
        self: Pin<&Self>,
        event: &MouseEvent,
        window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        cursor: &mut MouseCursor,
    ) -> InputEventFilterResult {
        if !self.enabled() {
            self.has_hover.set(false);
            if self.grabbed.replace(false) {
                self.pressed.set(false);
                Self::FIELD_OFFSETS.pointer_event().apply_pin(self).call(&(PointerEvent {
                    button: PointerEventButton::Other,
                    kind: PointerEventKind::Cancel,
                    modifiers: window_adapter.window().0.context().0.modifiers.get().into(),
                    is_touch: false,
                },));
            }
            return InputEventFilterResult::ForwardAndIgnore;
        }
        if matches!(event, MouseEvent::DragMove(..) | MouseEvent::Drop(..)) {
            // Someone else has the grab, don't handle hover
            return InputEventFilterResult::ForwardAndIgnore;
        }
        if let Some(pos) = event.position() {
            Self::FIELD_OFFSETS.mouse_x().apply_pin(self).set(pos.x_length());
            Self::FIELD_OFFSETS.mouse_y().apply_pin(self).set(pos.y_length());
        }
        let hovering = !matches!(event, MouseEvent::Exit);
        Self::FIELD_OFFSETS.has_hover().apply_pin(self).set(hovering);
        if hovering {
            *cursor = self.mouse_cursor();
        }
        InputEventFilterResult::ForwardAndInterceptGrab
    }

    fn input_event(
        self: Pin<&Self>,
        event: &MouseEvent,
        window_adapter: &Rc<dyn WindowAdapter>,
        self_rc: &ItemRc,
        _: &mut MouseCursor,
    ) -> InputEventResult {
        if matches!(event, MouseEvent::Exit) {
            Self::FIELD_OFFSETS.has_hover().apply_pin(self).set(false);
        }
        if !self.enabled() {
            return InputEventResult::EventIgnored;
        }
        match event {
            MouseEvent::Pressed { position, button, is_touch, .. } => {
                self.grabbed.set(true);
                if *button == PointerEventButton::Left {
                    Self::FIELD_OFFSETS.pressed_x().apply_pin(self).set(position.x_length());
                    Self::FIELD_OFFSETS.pressed_y().apply_pin(self).set(position.y_length());
                    Self::FIELD_OFFSETS.pressed().apply_pin(self).set(true);
                }
                Self::FIELD_OFFSETS.pointer_event().apply_pin(self).call(&(PointerEvent {
                    button: *button,
                    kind: PointerEventKind::Down,
                    modifiers: window_adapter.window().0.context().0.modifiers.get().into(),
                    is_touch: *is_touch,
                },));

                InputEventResult::GrabMouse
            }
            MouseEvent::Exit => {
                Self::FIELD_OFFSETS.pressed().apply_pin(self).set(false);
                if self.grabbed.replace(false) {
                    Self::FIELD_OFFSETS.pointer_event().apply_pin(self).call(&(PointerEvent {
                        button: PointerEventButton::Other,
                        kind: PointerEventKind::Cancel,
                        modifiers: window_adapter.window().0.context().0.modifiers.get().into(),
                        is_touch: false,
                    },));
                }

                InputEventResult::EventAccepted
            }

            MouseEvent::Released { button, position, click_count, is_touch } => {
                let geometry = self_rc.geometry();
                if *button == PointerEventButton::Left
                    && LogicalRect::new(LogicalPoint::default(), geometry.size).contains(*position)
                    && self.pressed()
                {
                    Self::FIELD_OFFSETS.clicked().apply_pin(self).call(&());
                    if (click_count % 2) == 1 {
                        Self::FIELD_OFFSETS.double_clicked().apply_pin(self).call(&())
                    }
                }

                self.grabbed.set(false);
                if *button == PointerEventButton::Left {
                    Self::FIELD_OFFSETS.pressed().apply_pin(self).set(false);
                }
                Self::FIELD_OFFSETS.pointer_event().apply_pin(self).call(&(PointerEvent {
                    button: *button,
                    kind: PointerEventKind::Up,
                    modifiers: window_adapter.window().0.context().0.modifiers.get().into(),
                    is_touch: *is_touch,
                },));

                InputEventResult::EventAccepted
            }
            MouseEvent::Moved { is_touch, .. } => {
                Self::FIELD_OFFSETS.pointer_event().apply_pin(self).call(&(PointerEvent {
                    button: PointerEventButton::Other,
                    kind: PointerEventKind::Move,
                    modifiers: window_adapter.window().0.context().0.modifiers.get().into(),
                    is_touch: *is_touch,
                },));
                if self.grabbed.get() {
                    Self::FIELD_OFFSETS.moved().apply_pin(self).call(&());
                    InputEventResult::GrabMouse
                } else {
                    InputEventResult::EventAccepted
                }
            }
            MouseEvent::Wheel { delta_x, delta_y, .. } => {
                let modifiers = window_adapter.window().0.context().0.modifiers.get().into();
                let r = Self::FIELD_OFFSETS.scroll_event().apply_pin(self).call(&(
                    PointerScrollEvent { delta_x: *delta_x, delta_y: *delta_y, modifiers },
                ));
                if self.grabbed.get() {
                    InputEventResult::GrabMouse
                } else {
                    match r {
                        EventResult::Reject => {
                            // We are ignoring the event, so we will be removed from the item_stack,
                            // therefore we must remove the has_hover flag as there might be a scroll under us.
                            // It will be put back later.
                            Self::FIELD_OFFSETS.has_hover().apply_pin(self).set(false);
                            InputEventResult::EventIgnored
                        }
                        EventResult::Accept => InputEventResult::EventAccepted,
                    }
                }
            }
            MouseEvent::PinchGesture { .. } | MouseEvent::RotationGesture { .. } => {
                InputEventResult::EventIgnored
            }
            MouseEvent::DragMove(..) | MouseEvent::Drop(..) => InputEventResult::EventIgnored,
        }
    }

    fn capture_key_event(
        self: Pin<&Self>,
        _: &InternalKeyEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> KeyEventResult {
        KeyEventResult::EventIgnored
    }

    fn key_event(
        self: Pin<&Self>,
        _: &InternalKeyEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> KeyEventResult {
        KeyEventResult::EventIgnored
    }

    fn focus_event(
        self: Pin<&Self>,
        _: &FocusEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> FocusEventResult {
        FocusEventResult::FocusIgnored
    }

    fn render(
        self: Pin<&Self>,
        _backend: &mut ItemRendererRef,
        _self_rc: &ItemRc,
        _size: LogicalSize,
    ) -> RenderingResult {
        RenderingResult::ContinueRenderingChildren
    }

    fn bounding_rect(
        self: core::pin::Pin<&Self>,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        mut geometry: LogicalRect,
    ) -> LogicalRect {
        geometry.size = LogicalSize::zero();
        geometry
    }

    fn clips_children(self: core::pin::Pin<&Self>) -> bool {
        false
    }
}

impl ItemConsts for TouchArea {
    const cached_rendering_data_offset: const_field_offset::FieldOffset<
        TouchArea,
        CachedRenderingData,
    > = TouchArea::FIELD_OFFSETS.cached_rendering_data().as_unpinned_projection();
}

impl ItemConsts for KeyBinding {
    const cached_rendering_data_offset: const_field_offset::FieldOffset<
        KeyBinding,
        CachedRenderingData,
    > = KeyBinding::FIELD_OFFSETS.cached_rendering_data().as_unpinned_projection();
}

#[repr(C)]
#[derive(FieldOffsets, Default, SlintElement)]
#[pin]
pub struct KeyBinding {
    pub keys: Property<Keys>,
    pub enabled: Property<bool>,
    pub activated: Callback<VoidArg>,
    pub cached_rendering_data: CachedRenderingData,
}

impl Item for KeyBinding {
    fn init(self: Pin<&Self>, _self_rc: &ItemRc) {}

    fn deinit(self: Pin<&Self>, _window_adapter: &Rc<dyn WindowAdapter>) {}

    fn layout_info(
        self: Pin<&Self>,
        _orientation: crate::items::Orientation,
        _cross_axis_constraint: Coord,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> crate::layout::LayoutInfo {
        Default::default()
    }

    fn input_event_filter_before_children(
        self: Pin<&Self>,
        _: &crate::input::MouseEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        _: &mut crate::items::MouseCursor,
    ) -> crate::input::InputEventFilterResult {
        Default::default()
    }

    fn input_event(
        self: Pin<&Self>,
        _: &crate::input::MouseEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        _: &mut crate::items::MouseCursor,
    ) -> crate::input::InputEventResult {
        Default::default()
    }

    fn capture_key_event(
        self: Pin<&Self>,
        _: &InternalKeyEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> crate::input::KeyEventResult {
        crate::input::KeyEventResult::EventIgnored
    }

    fn key_event(
        self: Pin<&Self>,
        _: &InternalKeyEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> crate::input::KeyEventResult {
        Default::default()
    }

    fn focus_event(
        self: Pin<&Self>,
        _: &crate::input::FocusEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> crate::input::FocusEventResult {
        Default::default()
    }

    fn render(
        self: Pin<&Self>,
        _backend: &mut &mut dyn crate::item_rendering::ItemRenderer,
        _self_rc: &ItemRc,
        _size: crate::lengths::LogicalSize,
    ) -> crate::items::RenderingResult {
        Default::default()
    }

    fn bounding_rect(
        self: Pin<&Self>,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        geometry: crate::lengths::LogicalRect,
    ) -> crate::lengths::LogicalRect {
        geometry
    }

    fn clips_children(self: core::pin::Pin<&Self>) -> bool {
        false
    }
}

/// An optimized ShortcutList that is only initialized when it is
/// first accessed.
#[repr(C)]
#[derive(Default)] // results in a null pointer, which we will initialize on first access
pub struct MaybeKeyBindingList(Cell<*const KeyBindingList>);

impl MaybeKeyBindingList {
    fn ensure_init(&self) {
        // This would be a race condition in Multi-threaded code, but
        // this type isn't Sync, so this function cannot race with another thread.
        if self.0.get().is_null() {
            self.0.set(Box::leak(Box::default()));
        }
    }
}

impl Drop for MaybeKeyBindingList {
    fn drop(&mut self) {
        let ptr = self.0.replace(core::ptr::null());
        if !ptr.is_null() {
            // SAFETY: Must be a pointer returned by `Box::leak`, which is guaranteed by `ensure_init`.
            drop(unsafe { Box::from_raw(ptr as *mut KeyBindingList) });
        }
    }
}

impl MaybeKeyBindingList {
    fn deref_pin(self: Pin<&Self>) -> Pin<&KeyBindingList> {
        self.ensure_init();
        // SAFETY: Must be non-null and properly aligned, which is guaranteed by `ensure_init`.
        unsafe { Pin::new_unchecked(&*self.get_ref().0.get()) }
    }
}

#[derive(Default)]
#[pin_project::pin_project]
pub struct KeyBindingList {
    found: core::cell::RefCell<Vec<VWeakMapped<ItemTreeVTable, KeyBinding>>>,
    #[pin]
    property_tracker: PropertyTracker,
}

/// A runtime item that exposes key events
#[repr(C)]
#[derive(FieldOffsets, Default, SlintElement)]
#[pin]
pub struct FocusScope {
    pub enabled: Property<bool>,
    pub has_focus: Property<bool>,
    pub focus_on_click: Property<bool>,
    pub focus_on_tab_navigation: Property<bool>,
    pub key_pressed: Callback<KeyEventArg, EventResult>,
    pub key_released: Callback<KeyEventArg, EventResult>,
    pub capture_key_pressed: Callback<KeyEventArg, EventResult>,
    pub capture_key_released: Callback<KeyEventArg, EventResult>,
    pub focus_changed_event: Callback<FocusReasonArg>,
    pub focus_gained: Callback<FocusReasonArg>,
    pub focus_lost: Callback<FocusReasonArg>,
    pub key_bindings: MaybeKeyBindingList,
    /// FIXME: remove this
    pub cached_rendering_data: CachedRenderingData,
}

impl FocusScope {
    fn visit_enabled_key_bindings<R>(
        self: Pin<&Self>,
        self_rc: &ItemRc,
        mut fun: impl FnMut(&VRcMapped<ItemTreeVTable, KeyBinding>) -> Option<R>,
    ) -> Option<R> {
        let list = Self::FIELD_OFFSETS.key_bindings().apply_pin(self);
        let list = list.deref_pin();

        list.project_ref().property_tracker.evaluate_if_dirty(|| {
            let mut found = list.found.borrow_mut();
            found.clear();

            let mut next = self_rc.first_child();
            while let Some(child) = next {
                if let Some(key_binding) = ItemRc::downcast::<KeyBinding>(&child)
                    && key_binding.as_pin_ref().enabled()
                {
                    found.push(VRcMapped::downgrade(&key_binding));
                }
                next = child.next_sibling();
            }
        });

        let list = list.found.borrow();
        for key_binding in &*list {
            let Some(shortcut) = key_binding.upgrade() else {
                crate::debug_log!("Warning: Found a dropped KeyBinding!");
                continue;
            };
            if let Some(result) = fun(&shortcut) {
                return Some(result);
            }
        }

        None
    }

    /// Returns the first matching key binding and whether there are multiple matches.
    fn key_binding_for_event(
        self: Pin<&Self>,
        self_rc: &ItemRc,
        inter_key_event: &InternalKeyEvent,
    ) -> Option<(VRcMapped<ItemTreeVTable, KeyBinding>, bool)> {
        let mut first_match = None;

        let ambiguous = self.visit_enabled_key_bindings(self_rc, |key_binding| {
            let keys = key_binding.as_pin_ref().keys();
            if keys.matches(&inter_key_event.key_event) {
                match &first_match {
                    Some(key_binding) => {
                        return Some(VRcMapped::clone(key_binding));
                    }
                    None => {
                        first_match = Some(VRcMapped::clone(key_binding));
                    }
                };
            }
            None
        });

        first_match.map(|binding| (VRcMapped::clone(&binding), ambiguous.is_some()))
    }
}

impl Item for FocusScope {
    fn init(self: Pin<&Self>, _self_rc: &ItemRc) {}

    fn deinit(self: Pin<&Self>, _window_adapter: &Rc<dyn WindowAdapter>) {}

    fn layout_info(
        self: Pin<&Self>,
        _orientation: Orientation,
        _cross_axis_constraint: Coord,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> LayoutInfo {
        LayoutInfo { stretch: 1., ..LayoutInfo::default() }
    }

    fn input_event_filter_before_children(
        self: Pin<&Self>,
        _: &MouseEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        _: &mut MouseCursor,
    ) -> InputEventFilterResult {
        InputEventFilterResult::ForwardEvent
    }

    fn input_event(
        self: Pin<&Self>,
        event: &MouseEvent,
        window_adapter: &Rc<dyn WindowAdapter>,
        self_rc: &ItemRc,
        _: &mut MouseCursor,
    ) -> InputEventResult {
        if self.enabled()
            && self.focus_on_click()
            && matches!(event, MouseEvent::Pressed { .. })
            && !self.has_focus()
        {
            WindowInner::from_pub(window_adapter.window()).set_focus_item(
                self_rc,
                true,
                FocusReason::PointerClick,
            );
            InputEventResult::EventAccepted
        } else {
            InputEventResult::EventIgnored
        }
    }

    fn capture_key_event(
        self: Pin<&Self>,
        event: &InternalKeyEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> KeyEventResult {
        let r = match event.event_type {
            KeyEventType::KeyPressed => Self::FIELD_OFFSETS
                .capture_key_pressed()
                .apply_pin(self)
                .call(&(event.key_event.clone(),)),
            KeyEventType::KeyReleased => Self::FIELD_OFFSETS
                .capture_key_released()
                .apply_pin(self)
                .call(&(event.key_event.clone(),)),
            KeyEventType::UpdateComposition | KeyEventType::CommitComposition => {
                EventResult::Reject
            }
        };
        match r {
            EventResult::Accept => KeyEventResult::EventAccepted,
            EventResult::Reject => KeyEventResult::EventIgnored,
        }
    }

    fn key_event(
        self: Pin<&Self>,
        event: &InternalKeyEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        self_rc: &ItemRc,
    ) -> KeyEventResult {
        let r = match event.event_type {
            KeyEventType::KeyPressed => {
                if let Some((key_binding, ambiguous)) = self.key_binding_for_event(self_rc, event) {
                    if ambiguous {
                        let keys = KeyBinding::FIELD_OFFSETS
                            .keys()
                            .apply_pin(key_binding.as_pin_ref())
                            .get();
                        crate::debug_log!(
                            "Warning: Multiple matching KeyBinding elements for keys {:?}!",
                            keys
                        );
                    }
                    KeyBinding::FIELD_OFFSETS
                        .activated()
                        .apply_pin(key_binding.as_pin_ref())
                        .call(&());
                    EventResult::Accept
                } else {
                    Self::FIELD_OFFSETS
                        .key_pressed()
                        .apply_pin(self)
                        .call(&(event.key_event.clone(),))
                }
            }
            KeyEventType::KeyReleased => {
                let binding = self.key_binding_for_event(self_rc, event);
                if binding.is_some() {
                    // The binding should have already handled the key press,
                    // so we just accept the release event if it matches a binding,
                    // to ensure the events remain "symmetric" in the key-pressed and key-released callbacks.
                    // Either both events appear in the callbacks, or neither do.
                    EventResult::Accept
                } else {
                    Self::FIELD_OFFSETS
                        .key_released()
                        .apply_pin(self)
                        .call(&(event.key_event.clone(),))
                }
            }
            KeyEventType::UpdateComposition | KeyEventType::CommitComposition => {
                EventResult::Reject
            }
        };
        match r {
            EventResult::Accept => KeyEventResult::EventAccepted,
            EventResult::Reject => KeyEventResult::EventIgnored,
        }
    }

    fn focus_event(
        self: Pin<&Self>,
        event: &FocusEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> FocusEventResult {
        if !self.enabled() {
            return FocusEventResult::FocusIgnored;
        }

        match event {
            FocusEvent::FocusIn(reason) => {
                match reason {
                    FocusReason::TabNavigation if !self.focus_on_tab_navigation() => {
                        return FocusEventResult::FocusIgnored;
                    }
                    FocusReason::PointerClick if !self.focus_on_click() => {
                        return FocusEventResult::FocusIgnored;
                    }
                    _ => (),
                };

                self.has_focus.set(true);
                Self::FIELD_OFFSETS.focus_changed_event().apply_pin(self).call(&(*reason,));
                Self::FIELD_OFFSETS.focus_gained().apply_pin(self).call(&(*reason,));
            }
            FocusEvent::FocusOut(reason) => {
                self.has_focus.set(false);
                Self::FIELD_OFFSETS.focus_changed_event().apply_pin(self).call(&(*reason,));
                Self::FIELD_OFFSETS.focus_lost().apply_pin(self).call(&(*reason,));
            }
        }
        FocusEventResult::FocusAccepted
    }

    fn render(
        self: Pin<&Self>,
        _backend: &mut ItemRendererRef,
        _self_rc: &ItemRc,
        _size: LogicalSize,
    ) -> RenderingResult {
        RenderingResult::ContinueRenderingChildren
    }

    fn bounding_rect(
        self: core::pin::Pin<&Self>,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        mut geometry: LogicalRect,
    ) -> LogicalRect {
        geometry.size = LogicalSize::zero();
        geometry
    }

    fn clips_children(self: core::pin::Pin<&Self>) -> bool {
        false
    }
}

impl ItemConsts for FocusScope {
    const cached_rendering_data_offset: const_field_offset::FieldOffset<
        FocusScope,
        CachedRenderingData,
    > = FocusScope::FIELD_OFFSETS.cached_rendering_data().as_unpinned_projection();
}

#[repr(C)]
#[derive(FieldOffsets, Default, SlintElement)]
#[pin]
pub struct SwipeGestureHandler {
    pub enabled: Property<bool>,
    pub handle_swipe_left: Property<bool>,
    pub handle_swipe_right: Property<bool>,
    pub handle_swipe_up: Property<bool>,
    pub handle_swipe_down: Property<bool>,

    pub moved: Callback<VoidArg>,
    pub swiped: Callback<VoidArg>,
    pub cancelled: Callback<VoidArg>,

    pub pressed_position: Property<LogicalPosition>,
    pub current_position: Property<LogicalPosition>,
    pub swiping: Property<bool>,

    // true when the cursor is pressed down and we haven't cancelled yet for another reason
    pressed: Cell<bool>,
    // capture_events: Cell<bool>,
    /// FIXME: remove this
    pub cached_rendering_data: CachedRenderingData,
}

impl Item for SwipeGestureHandler {
    fn init(self: Pin<&Self>, _self_rc: &ItemRc) {}

    fn deinit(self: Pin<&Self>, _window_adapter: &Rc<dyn WindowAdapter>) {}

    fn layout_info(
        self: Pin<&Self>,
        _orientation: Orientation,
        _cross_axis_constraint: Coord,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> LayoutInfo {
        LayoutInfo { stretch: 1., ..LayoutInfo::default() }
    }

    fn input_event_filter_before_children(
        self: Pin<&Self>,
        event: &MouseEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        _: &mut MouseCursor,
    ) -> InputEventFilterResult {
        if !self.enabled() {
            if self.pressed.get() {
                self.cancel_impl();
            }
            return InputEventFilterResult::ForwardAndIgnore;
        }

        match event {
            MouseEvent::Pressed { position, button: PointerEventButton::Left, .. } => {
                Self::FIELD_OFFSETS
                    .pressed_position()
                    .apply_pin(self)
                    .set(crate::lengths::logical_position_to_api(*position));
                self.pressed.set(true);
                InputEventFilterResult::DelayForwarding(
                    super::flickable::FORWARD_DELAY.as_millis() as _
                )
            }
            MouseEvent::Exit => {
                self.cancel_impl();
                InputEventFilterResult::ForwardAndIgnore
            }
            MouseEvent::Released { button: PointerEventButton::Left, .. } => {
                if self.swiping() {
                    InputEventFilterResult::Intercept
                } else {
                    self.pressed.set(false);
                    InputEventFilterResult::ForwardEvent
                }
            }
            MouseEvent::Moved { position, .. } => {
                if self.swiping() {
                    InputEventFilterResult::Intercept
                } else if !self.pressed.get() {
                    InputEventFilterResult::ForwardEvent
                } else if self.is_over_threshold(position) {
                    InputEventFilterResult::Intercept
                } else {
                    InputEventFilterResult::ForwardAndInterceptGrab
                }
            }
            MouseEvent::Wheel { .. } => InputEventFilterResult::ForwardAndIgnore,
            // Not the left button
            MouseEvent::Pressed { .. } | MouseEvent::Released { .. } => {
                InputEventFilterResult::ForwardAndIgnore
            }
            MouseEvent::PinchGesture { .. } | MouseEvent::RotationGesture { .. } => {
                InputEventFilterResult::ForwardAndIgnore
            }
            MouseEvent::DragMove(..) | MouseEvent::Drop(..) => {
                InputEventFilterResult::ForwardAndIgnore
            }
        }
    }

    fn input_event(
        self: Pin<&Self>,
        event: &MouseEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        _: &mut MouseCursor,
    ) -> InputEventResult {
        match event {
            MouseEvent::Pressed { .. } => InputEventResult::GrabMouse,
            MouseEvent::Exit => {
                self.cancel_impl();
                InputEventResult::EventIgnored
            }
            MouseEvent::Released { position, .. } => {
                if !self.pressed.get() && !self.swiping() {
                    return InputEventResult::EventIgnored;
                }
                self.current_position.set(crate::lengths::logical_position_to_api(*position));
                self.pressed.set(false);
                if self.swiping() {
                    Self::FIELD_OFFSETS.swiping().apply_pin(self).set(false);
                    Self::FIELD_OFFSETS.swiped().apply_pin(self).call(&());
                    InputEventResult::EventAccepted
                } else {
                    InputEventResult::EventIgnored
                }
            }
            MouseEvent::Moved { position, .. } => {
                if !self.pressed.get() {
                    return InputEventResult::EventAccepted;
                }
                self.current_position.set(crate::lengths::logical_position_to_api(*position));
                let mut swiping = self.swiping();
                if !swiping && self.is_over_threshold(position) {
                    Self::FIELD_OFFSETS.swiping().apply_pin(self).set(true);
                    swiping = true;
                }
                Self::FIELD_OFFSETS.moved().apply_pin(self).call(&());
                if swiping { InputEventResult::GrabMouse } else { InputEventResult::EventAccepted }
            }
            MouseEvent::Wheel { .. } => InputEventResult::EventIgnored,
            MouseEvent::PinchGesture { .. } | MouseEvent::RotationGesture { .. } => {
                InputEventResult::EventIgnored
            }
            MouseEvent::DragMove(..) | MouseEvent::Drop(..) => InputEventResult::EventIgnored,
        }
    }

    fn capture_key_event(
        self: Pin<&Self>,
        _: &InternalKeyEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> KeyEventResult {
        KeyEventResult::EventIgnored
    }

    fn key_event(
        self: Pin<&Self>,
        _event: &InternalKeyEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> KeyEventResult {
        KeyEventResult::EventIgnored
    }

    fn focus_event(
        self: Pin<&Self>,
        _: &FocusEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> FocusEventResult {
        FocusEventResult::FocusIgnored
    }

    fn render(
        self: Pin<&Self>,
        _backend: &mut ItemRendererRef,
        _self_rc: &ItemRc,
        _size: LogicalSize,
    ) -> RenderingResult {
        RenderingResult::ContinueRenderingChildren
    }

    fn bounding_rect(
        self: core::pin::Pin<&Self>,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        mut geometry: LogicalRect,
    ) -> LogicalRect {
        geometry.size = LogicalSize::zero();
        geometry
    }

    fn clips_children(self: core::pin::Pin<&Self>) -> bool {
        false
    }
}

impl ItemConsts for SwipeGestureHandler {
    const cached_rendering_data_offset: const_field_offset::FieldOffset<Self, CachedRenderingData> =
        Self::FIELD_OFFSETS.cached_rendering_data().as_unpinned_projection();
}

impl SwipeGestureHandler {
    pub fn cancel(self: Pin<&Self>, _: &Rc<dyn WindowAdapter>, _: &ItemRc) {
        self.cancel_impl();
    }

    fn cancel_impl(self: Pin<&Self>) {
        if !self.pressed.replace(false) {
            debug_assert!(!self.swiping());
            return;
        }
        if self.swiping() {
            Self::FIELD_OFFSETS.swiping().apply_pin(self).set(false);
            Self::FIELD_OFFSETS.cancelled().apply_pin(self).call(&());
        }
    }

    fn is_over_threshold(self: Pin<&Self>, position: &LogicalPoint) -> bool {
        let pressed_pos = self.pressed_position();
        let dx = position.x - pressed_pos.x as Coord;
        let dy = position.y - pressed_pos.y as Coord;
        let threshold = super::flickable::DISTANCE_THRESHOLD.get();
        (self.handle_swipe_down() && dy > threshold && dy > dx.abs() / 2 as Coord)
            || (self.handle_swipe_up() && dy < -threshold && dy < -dx.abs() / 2 as Coord)
            || (self.handle_swipe_left() && dx < -threshold && dx < -dy.abs() / 2 as Coord)
            || (self.handle_swipe_right() && dx > threshold && dx > dy.abs() / 2 as Coord)
    }
}

#[cfg(feature = "ffi")]
mod ffi {
    use super::*;

    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn slint_swipegesturehandler_cancel(
        s: Pin<&SwipeGestureHandler>,
        window_adapter: *const crate::window::ffi::WindowAdapterRcOpaque,
        self_component: &vtable::VRc<crate::item_tree::ItemTreeVTable>,
        self_index: u32,
    ) {
        unsafe {
            let window_adapter = &*(window_adapter as *const Rc<dyn WindowAdapter>);
            let self_rc = ItemRc::new(self_component.clone(), self_index);
            s.cancel(window_adapter, &self_rc);
        }
    }

    /// # Safety
    /// This must be called using a non-null pointer pointing to a chunk of memory big enough to
    /// hold a MaybeKeybindingList
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn slint_maybe_key_binding_list_init(list: *mut MaybeKeyBindingList) {
        unsafe {
            core::ptr::write(list, MaybeKeyBindingList::default());
        }
    }

    /// # Safety
    /// This must be called using a non-null pointer pointing to an initialized MaybeKeybindingList
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn slint_maybe_key_binding_list_free(list: *mut MaybeKeyBindingList) {
        unsafe { core::ptr::drop_in_place(list) };
    }
}

/// The implementation of the `ScaleRotateGestureHandler` element.
///
/// Provides an API surface for platform-recognized pinch gesture events.
/// Receives `MouseEvent::PinchGesture` events via the normal mouse event
/// tree-walk and exposes cumulative scale, center position, and lifecycle callbacks.
#[repr(C)]
#[derive(FieldOffsets, Default, SlintElement)]
#[pin]
pub struct ScaleRotateGestureHandler {
    pub enabled: Property<bool>,

    // Output properties
    pub active: Property<bool>,
    /// Cumulative scale factor relative to gesture start. Always 1.0 when the
    /// gesture starts, then updated as the gesture progresses (e.g., 2.0 means
    /// doubled, 0.5 means halved).
    pub scale: Property<f32>,
    /// Cumulative rotation in degrees relative to gesture start. Always 0.0 when
    /// the gesture starts.
    pub rotation: Property<f32>,
    pub center: Property<LogicalPosition>,

    // Callbacks
    pub started: Callback<VoidArg>,
    pub updated: Callback<VoidArg>,
    pub ended: Callback<VoidArg>,
    pub cancelled: Callback<VoidArg>,

    /// FIXME: remove this
    pub cached_rendering_data: CachedRenderingData,
}

impl Item for ScaleRotateGestureHandler {
    fn init(self: Pin<&Self>, _self_rc: &ItemRc) {
        self.scale.set(1.0);
    }

    fn deinit(self: Pin<&Self>, _window_adapter: &Rc<dyn WindowAdapter>) {}

    fn layout_info(
        self: Pin<&Self>,
        _orientation: Orientation,
        _cross_axis_constraint: Coord,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> LayoutInfo {
        LayoutInfo { stretch: 1., ..LayoutInfo::default() }
    }

    fn input_event_filter_before_children(
        self: Pin<&Self>,
        event: &MouseEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        _: &mut MouseCursor,
    ) -> InputEventFilterResult {
        match event {
            // Forward gesture events so inner handlers get first shot
            MouseEvent::PinchGesture { .. } | MouseEvent::RotationGesture { .. }
                if self.enabled() =>
            {
                InputEventFilterResult::ForwardEvent
            }
            // While a gesture is active, intercept non-gesture events to
            // prevent Flickable and other items from processing them concurrently.
            _ if self.active() => InputEventFilterResult::Intercept,
            _ => InputEventFilterResult::ForwardAndIgnore,
        }
    }

    fn input_event(
        self: Pin<&Self>,
        event: &MouseEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        _: &mut MouseCursor,
    ) -> InputEventResult {
        use crate::input::TouchPhase;
        match event {
            MouseEvent::PinchGesture { delta, phase, position } => {
                if !self.enabled() {
                    if self.active() {
                        self.cancel_impl();
                    }
                    return InputEventResult::EventIgnored;
                }
                let new_scale = self.scale() * (1.0 + delta);
                Self::FIELD_OFFSETS.scale().apply_pin(self).set(new_scale);
                let center = crate::lengths::logical_position_to_api(*position);
                Self::FIELD_OFFSETS.center().apply_pin(self).set(center);
                match phase {
                    TouchPhase::Started => {
                        if !self.active() {
                            Self::FIELD_OFFSETS.active().apply_pin(self).set(true);
                            Self::FIELD_OFFSETS.started().apply_pin(self).call(&());
                        }
                        InputEventResult::GrabMouse
                    }
                    TouchPhase::Moved => {
                        if !self.active() {
                            return InputEventResult::EventIgnored;
                        }
                        Self::FIELD_OFFSETS.updated().apply_pin(self).call(&());
                        InputEventResult::GrabMouse
                    }
                    TouchPhase::Ended => self.end_impl(),
                    TouchPhase::Cancelled => {
                        self.cancel_impl();
                        InputEventResult::EventAccepted
                    }
                }
            }
            MouseEvent::RotationGesture { delta, phase, position } => {
                if !self.enabled() {
                    return InputEventResult::EventIgnored;
                }
                let center = crate::lengths::logical_position_to_api(*position);
                Self::FIELD_OFFSETS.center().apply_pin(self).set(center);
                let new_rotation = self.rotation() + delta;
                Self::FIELD_OFFSETS.rotation().apply_pin(self).set(new_rotation);
                match phase {
                    TouchPhase::Started => {
                        if !self.active() {
                            Self::FIELD_OFFSETS.active().apply_pin(self).set(true);
                            Self::FIELD_OFFSETS.started().apply_pin(self).call(&());
                        }
                        InputEventResult::GrabMouse
                    }
                    TouchPhase::Moved => {
                        if !self.active() {
                            return InputEventResult::EventIgnored;
                        }
                        Self::FIELD_OFFSETS.updated().apply_pin(self).call(&());
                        InputEventResult::GrabMouse
                    }
                    TouchPhase::Ended => self.end_impl(),
                    TouchPhase::Cancelled => {
                        self.cancel_impl();
                        InputEventResult::EventAccepted
                    }
                }
            }
            // Grab mouse during active gesture to maintain exclusivity.
            _ if self.active() => InputEventResult::GrabMouse,
            _ => InputEventResult::EventIgnored,
        }
    }

    fn capture_key_event(
        self: Pin<&Self>,
        _: &InternalKeyEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> KeyEventResult {
        KeyEventResult::EventIgnored
    }

    fn key_event(
        self: Pin<&Self>,
        _event: &InternalKeyEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> KeyEventResult {
        KeyEventResult::EventIgnored
    }

    fn focus_event(
        self: Pin<&Self>,
        _: &FocusEvent,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
    ) -> FocusEventResult {
        FocusEventResult::FocusIgnored
    }

    fn render(
        self: Pin<&Self>,
        _backend: &mut ItemRendererRef,
        _self_rc: &ItemRc,
        _size: LogicalSize,
    ) -> RenderingResult {
        RenderingResult::ContinueRenderingChildren
    }

    fn bounding_rect(
        self: core::pin::Pin<&Self>,
        _window_adapter: &Rc<dyn WindowAdapter>,
        _self_rc: &ItemRc,
        mut geometry: LogicalRect,
    ) -> LogicalRect {
        geometry.size = LogicalSize::zero();
        geometry
    }

    fn clips_children(self: core::pin::Pin<&Self>) -> bool {
        false
    }
}

impl ItemConsts for ScaleRotateGestureHandler {
    const cached_rendering_data_offset: const_field_offset::FieldOffset<Self, CachedRenderingData> =
        Self::FIELD_OFFSETS.cached_rendering_data().as_unpinned_projection();
}

impl ScaleRotateGestureHandler {
    fn cancel_impl(self: Pin<&Self>) {
        if !self.active() {
            return;
        }
        Self::FIELD_OFFSETS.active().apply_pin(self).set(false);
        Self::FIELD_OFFSETS.cancelled().apply_pin(self).call(&());
        // Reset after the callback so handlers can read the last known values
        // to animate back smoothly, matching the pattern where `ended` leaves
        // scale/rotation at their final values.
        Self::FIELD_OFFSETS.scale().apply_pin(self).set(1.0);
        Self::FIELD_OFFSETS.rotation().apply_pin(self).set(0.0);
    }

    fn end_impl(self: Pin<&Self>) -> InputEventResult {
        if !self.active() {
            return InputEventResult::EventIgnored;
        }
        Self::FIELD_OFFSETS.ended().apply_pin(self).call(&());
        Self::FIELD_OFFSETS.active().apply_pin(self).set(false);
        Self::FIELD_OFFSETS.scale().apply_pin(self).set(1.0);
        Self::FIELD_OFFSETS.rotation().apply_pin(self).set(0.0);
        InputEventResult::EventAccepted
    }
}