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
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
// 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

/*! Module handling mouse events
*/
#![warn(missing_docs)]

use crate::item_tree::ItemTreeRc;
use crate::item_tree::{ItemRc, ItemWeak, VisitChildrenResult};
use crate::items::{DropEvent, ItemRef, MouseCursor, OperatingSystemType, TextCursorDirection};
pub use crate::items::{FocusReason, KeyEvent, KeyboardModifiers, PointerEventButton};
use crate::lengths::{ItemTransform, LogicalPoint, LogicalVector};
use crate::timers::Timer;
use crate::window::{WindowAdapter, WindowInner};
use crate::{Coord, Property, SharedString};
use alloc::rc::Rc;
use alloc::vec::Vec;
use const_field_offset::FieldOffsets;
use core::cell::Cell;
use core::fmt::Display;
use core::pin::Pin;
use core::time::Duration;

/// A mouse or touch event
///
/// The only difference with [`crate::platform::WindowEvent`] is that it uses untyped `Point`
/// TODO: merge with platform::WindowEvent
#[repr(C)]
#[derive(Debug, Clone, PartialEq)]
pub enum MouseEvent {
    /// The mouse or finger was pressed
    Pressed {
        /// The position of the pointer when the event happened.
        position: LogicalPoint,
        /// The button that was pressed.
        button: PointerEventButton,
        /// The current click count reported for this press.
        click_count: u8,
        /// Whether the event originated from touch input.
        is_touch: bool,
    },
    /// The mouse or finger was released
    Released {
        /// The position of the pointer when the event happened.
        position: LogicalPoint,
        /// The button that was released.
        button: PointerEventButton,
        /// The current click count reported for this release.
        click_count: u8,
        /// Whether the event originated from touch input.
        is_touch: bool,
    },
    /// The position of the pointer has changed
    Moved {
        /// The new position of the pointer.
        position: LogicalPoint,
        /// Whether the event originated from touch input.
        is_touch: bool,
    },
    /// Wheel was operated.
    Wheel {
        /// The position of the pointer when the event happened.
        position: LogicalPoint,
        /// The horizontal scroll delta in logical pixels.
        delta_x: Coord,
        /// The vertical scroll delta in logical pixels.
        delta_y: Coord,
        /// The gesture phase reported for the wheel event.
        phase: TouchPhase,
    },
    /// The mouse is being dragged over this item.
    /// [`InputEventResult::EventIgnored`] means that the item does not handle the drag operation
    /// and [`InputEventResult::EventAccepted`] means that the item can accept it.
    DragMove(DropEvent),
    /// The mouse is released while dragging over this item.
    Drop(DropEvent),
    /// A platform-recognized pinch gesture (macOS/iOS trackpad, Qt).
    PinchGesture {
        /// The focal position of the gesture.
        position: LogicalPoint,
        /// The incremental scale delta for this gesture update.
        delta: f32,
        /// The gesture phase reported by the platform.
        phase: TouchPhase,
    },
    /// A platform-recognized rotation gesture (macOS/iOS trackpad, Qt).
    RotationGesture {
        /// The focal position of the gesture.
        position: LogicalPoint,
        /// The incremental rotation in degrees, where positive means clockwise.
        delta: f32,
        /// The gesture phase reported by the platform.
        phase: TouchPhase,
    },
    /// The mouse exited the item or component
    Exit,
}

impl MouseEvent {
    /// The flag for when event generated from touch
    pub fn is_touch(&self) -> Option<bool> {
        match self {
            MouseEvent::Pressed { is_touch, .. } => Some(*is_touch),
            MouseEvent::Released { is_touch, .. } => Some(*is_touch),
            MouseEvent::Moved { is_touch, .. } => Some(*is_touch),
            MouseEvent::Wheel { .. } => None,
            MouseEvent::PinchGesture { .. } | MouseEvent::RotationGesture { .. } => Some(true),
            MouseEvent::DragMove(..) | MouseEvent::Drop(..) => None,
            MouseEvent::Exit => None,
        }
    }

    /// The position of the cursor for this event, if any
    pub fn position(&self) -> Option<LogicalPoint> {
        match self {
            MouseEvent::Pressed { position, .. } => Some(*position),
            MouseEvent::Released { position, .. } => Some(*position),
            MouseEvent::Moved { position, .. } => Some(*position),
            MouseEvent::Wheel { position, .. } => Some(*position),
            MouseEvent::PinchGesture { position, .. } => Some(*position),
            MouseEvent::RotationGesture { position, .. } => Some(*position),
            MouseEvent::DragMove(e) | MouseEvent::Drop(e) => {
                Some(crate::lengths::logical_point_from_api(e.position))
            }
            MouseEvent::Exit => None,
        }
    }

    /// Translate the position by the given value
    pub fn translate(&mut self, vec: LogicalVector) {
        let pos = match self {
            MouseEvent::Pressed { position, .. } => Some(position),
            MouseEvent::Released { position, .. } => Some(position),
            MouseEvent::Moved { position, .. } => Some(position),
            MouseEvent::Wheel { position, .. } => Some(position),
            MouseEvent::PinchGesture { position, .. } => Some(position),
            MouseEvent::RotationGesture { position, .. } => Some(position),
            MouseEvent::DragMove(e) | MouseEvent::Drop(e) => {
                e.position = crate::api::LogicalPosition::from_euclid(
                    crate::lengths::logical_point_from_api(e.position) + vec,
                );
                None
            }
            MouseEvent::Exit => None,
        };
        if let Some(pos) = pos {
            *pos += vec;
        }
    }

    /// Transform the position by the given item transform.
    pub fn transform(&mut self, transform: ItemTransform) {
        let pos = match self {
            MouseEvent::Pressed { position, .. } => Some(position),
            MouseEvent::Released { position, .. } => Some(position),
            MouseEvent::Moved { position, .. } => Some(position),
            MouseEvent::Wheel { position, .. } => Some(position),
            MouseEvent::PinchGesture { position, .. } => Some(position),
            MouseEvent::RotationGesture { position, .. } => Some(position),
            MouseEvent::DragMove(e) | MouseEvent::Drop(e) => {
                e.position = crate::api::LogicalPosition::from_euclid(
                    transform
                        .transform_point(crate::lengths::logical_point_from_api(e.position).cast())
                        .cast(),
                );
                None
            }
            MouseEvent::Exit => None,
        };
        if let Some(pos) = pos {
            *pos = transform.transform_point(pos.cast()).cast();
        }
    }

    /// Set the click count of the pressed or released event
    fn set_click_count(&mut self, count: u8) {
        match self {
            MouseEvent::Pressed { click_count, .. } | MouseEvent::Released { click_count, .. } => {
                *click_count = count
            }
            _ => (),
        }
    }
}

/// Phase of a touch, gesture event or wheel event.
/// A touchpad is recognized as wheel event and therefore
/// we need to find out when the touch event starts and ends
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TouchPhase {
    /// The gesture began (e.g., first finger touched or platform gesture started).
    Started,
    /// The gesture is ongoing (e.g., fingers moved or platform gesture updated).
    Moved,
    /// The gesture completed normally.
    Ended,
    /// The gesture was cancelled (e.g., interrupted by the system) or the mouse wheel was used
    Cancelled,
}

/// This value is returned by the `input_event` function of an Item
/// to notify the run-time about how the event was handled and
/// what the next steps are.
/// See [`crate::items::ItemVTable::input_event`].
#[repr(u8)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub enum InputEventResult {
    /// The event was accepted. This may result in additional events, for example
    /// accepting a mouse move will result in a MouseExit event later.
    EventAccepted,
    /// The event was ignored.
    #[default]
    EventIgnored,
    /// All further mouse events need to be sent to this item or component
    GrabMouse,
    /// Will start a drag operation. Can only be returned from a [`crate::items::DragArea`] item.
    StartDrag,
}

/// This value is returned by the `input_event_filter_before_children` function, which
/// can specify how to further process the event.
/// See [`crate::items::ItemVTable::input_event_filter_before_children`].
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Default)]
pub enum InputEventFilterResult {
    /// The event is going to be forwarded to children, then the [`crate::items::ItemVTable::input_event`]
    /// function is called
    #[default]
    ForwardEvent,
    /// The event will be forwarded to the children, but the [`crate::items::ItemVTable::input_event`] is not
    /// going to be called for this item
    ForwardAndIgnore,
    /// Just like `ForwardEvent`, but even in the case that children grabs the mouse, this function
    /// will still be called for further events
    ForwardAndInterceptGrab,
    /// The event will not be forwarded to children, if a child already had the grab, the
    /// grab will be cancelled with a [`MouseEvent::Exit`] event
    Intercept,
    /// The event will be forwarded to the children with a delay (in milliseconds), unless it is
    /// being intercepted.
    /// This is what happens when the flickable wants to delay the event.
    /// This should only be used for Press event, and the event will be sent after the delay, or
    /// if a release event is seen before that delay
    /// If any other component is handling the event it will be not handled by the component returned this result
    //(Can't use core::time::Duration because it is not repr(c))
    DelayForwarding(u64),
}

/// This module contains the constant character code used to represent the keys.
#[allow(missing_docs, non_upper_case_globals)]
pub mod key_codes {
    macro_rules! declare_consts_for_special_keys {
       ($($char:literal # $name:ident # $($shifted:ident)? # $($_muda:ident)? $(=> $($_qt:ident)|* # $($_winit:ident $(($_pos:ident))?)|*    # $($_xkb:ident)|* )? ;)*) => {
            $(pub const $name : char = $char;)*

            #[allow(missing_docs)]
            #[derive(Debug, Copy, Clone, PartialEq)]
            #[non_exhaustive]
            /// The `Key` enum is used to map a specific key by name e.g. `Key::Control` to an
            /// internal used unicode representation. The enum is convertible to [`std::char`] and [`slint::SharedString`](`crate::SharedString`).
            /// Use this with [`slint::platform::WindowEvent`](`crate::platform::WindowEvent`) to supply key events to Slint's platform abstraction.
            ///
            /// # Example
            ///
            /// Send an tab key press event to a window
            ///
            /// ```
            /// use slint::platform::{WindowEvent, Key};
            /// fn send_tab_pressed(window: &slint::Window) {
            ///     window.dispatch_event(WindowEvent::KeyPressed { text: Key::Tab.into() });
            /// }
            /// ```
            pub enum Key {
                $($name,)*
            }

            impl From<Key> for char {
                fn from(k: Key) -> Self {
                    match k {
                        $(Key::$name => $name,)*
                    }
                }
            }

            impl From<Key> for crate::SharedString {
                fn from(k: Key) -> Self {
                    char::from(k).into()
                }
            }
        };
    }

    i_slint_common::for_each_keys!(declare_consts_for_special_keys);
}

/// Internal struct to maintain the pressed/released state of the keys that
/// map to keyboard modifiers.
#[derive(Clone, Copy, Default, Debug)]
pub(crate) struct InternalKeyboardModifierState {
    left_alt: bool,
    right_alt: bool,
    altgr: bool,
    left_control: bool,
    right_control: bool,
    left_meta: bool,
    right_meta: bool,
    left_shift: bool,
    right_shift: bool,
}

impl InternalKeyboardModifierState {
    /// Updates a flag of the modifiers if the key of the given text is pressed.
    /// Returns an updated modifier if detected; None otherwise;
    pub(crate) fn state_update(mut self, pressed: bool, text: &SharedString) -> Option<Self> {
        if let Some(key_code) = text.chars().next() {
            match key_code {
                key_codes::Alt => self.left_alt = pressed,
                key_codes::AltGr => self.altgr = pressed,
                key_codes::Control => self.left_control = pressed,
                key_codes::ControlR => self.right_control = pressed,
                key_codes::Shift => self.left_shift = pressed,
                key_codes::ShiftR => self.right_shift = pressed,
                key_codes::Meta => self.left_meta = pressed,
                key_codes::MetaR => self.right_meta = pressed,
                _ => return None,
            };

            // Encoded keyboard modifiers must appear as individual key events. This could
            // be relaxed by implementing a string split, but right now WindowEvent::KeyPressed
            // holds only a single char.
            debug_assert_eq!(key_code.len_utf8(), text.len());
        }

        Some(self)
    }

    pub fn shift(&self) -> bool {
        self.right_shift || self.left_shift
    }
    pub fn alt(&self) -> bool {
        self.right_alt || self.left_alt
    }
    pub fn meta(&self) -> bool {
        self.right_meta || self.left_meta
    }
    pub fn control(&self) -> bool {
        self.right_control || self.left_control
    }

    pub fn modifiers_for(&self, _event: &InternalKeyEvent) -> KeyboardModifiers {
        #[allow(unused_mut)]
        let mut alt = self.alt();
        #[allow(unused_mut)]
        let mut control = self.control();

        // Windows treats Ctrl+Alt as implying AltGr, but not vice-versa
        // Unfortunately, our different backends produce different key combinations here.
        //
        // ## Qt
        // Qt always sends Ctrl + Alt instead of AltGr, and does not tell us whether this
        // was interpreted as AltGr or not. So with Qt we have no way of telling whether
        // AltGr is pressed, and we have to assume that it is pressed whenever Ctrl + Alt is pressed.
        // In that case the `text_without_modifiers` is also not set.
        //
        // ## Winit
        // Winit sends the actual Ctrl/Alt/AltGr keypresses correctly.
        // With winit we can detect whether ctrl+alt actually caused a AltGr conversion or not,
        // by checking whether the text_without_modifiers is different from the event text.
        //
        // ## Wasm
        // Winit on the web for some reasons sends first a Ctrl and then AltGr event when only AltGr
        // is pressed.
        // So there we need to get rid of the additional Ctrl event whenever AltGr is pressed.
        #[cfg(target_os = "windows")]
        {
            // Non-web windows (Usually winit or Qt)
            if !self.altgr && self.control() && self.alt() {
                // AltGr is not pressed, but Ctrl+Alt is pressed.
                // Try to detect if an AltGr conversion occured.
                // If so, disable Ctrl and Alt
                //
                // On platforms that don't provide text_without_modifiers, fall back to a simple
                // heuristic that assumes A-Z & 0-9 are not produced with AltGr, but all other keys are.
                let implies_altgr = if _event.text_without_modifiers.is_empty() {
                    _event.key_event.text.chars().any(|c| !c.is_ascii_alphanumeric())
                } else {
                    _event.text_without_modifiers.to_lowercase()
                        != _event.key_event.text.to_lowercase()
                };
                if implies_altgr {
                    alt = false;
                    control = false;
                }
            }
        }
        #[cfg(target_family = "wasm")]
        if crate::detect_operating_system() == OperatingSystemType::Windows {
            // Non-native windows (e.g. Winit on the web)
            // This currently injects additional Ctrl events, so remove those if AltGr is
            // pressed.
            let is_altgr = self.altgr
                || (self.control()
                    && self.alt()
                    && _event.key_event.text.chars().any(|c| !c.is_ascii_alphanumeric()));
            if is_altgr {
                alt = false;
                control = false;
            }
        }

        KeyboardModifiers { alt, control, meta: self.meta(), shift: self.shift() }
    }
}

impl From<InternalKeyboardModifierState> for KeyboardModifiers {
    fn from(internal_state: InternalKeyboardModifierState) -> Self {
        Self {
            alt: internal_state.alt(),
            control: internal_state.control(),
            meta: internal_state.meta(),
            shift: internal_state.shift(),
        }
    }
}

#[i_slint_core_macros::slint_doc]
/// The `Keys` type is the Rust representation of Slint's `keys` primitive type.
///
/// It can be created with the `@keys` macro in Slint and defines which key event(s) activate a KeyBinding.
///
/// See also the Slint documentation on [Key Bindings](slint:KeyBindingOverview).
#[derive(Clone, Eq, PartialEq, Default)]
#[repr(C)]
pub struct Keys {
    inner: KeysInner,
}

/// Re-exported in private_unstable_api to create a Keys struct.
pub fn make_keys(
    key: SharedString,
    modifiers: KeyboardModifiers,
    ignore_shift: bool,
    ignore_alt: bool,
) -> Keys {
    Keys {
        inner: KeysInner { key: key.to_lowercase().into(), modifiers, ignore_shift, ignore_alt },
    }
}

#[cfg(feature = "ffi")]
#[allow(unsafe_code)]
pub(crate) mod ffi {
    use crate::api::ToSharedString as _;

    use super::*;

    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn slint_keys(
        key: &SharedString,
        alt: bool,
        control: bool,
        shift: bool,
        meta: bool,
        ignore_shift: bool,
        ignore_alt: bool,
        out: &mut Keys,
    ) {
        *out = make_keys(
            key.clone(),
            KeyboardModifiers { alt, control, shift, meta },
            ignore_shift,
            ignore_alt,
        );
    }

    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn slint_keys_debug_string(shortcut: &Keys, out: &mut SharedString) {
        *out = crate::format!("{shortcut:?}");
    }

    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn slint_keys_to_string(shortcut: &Keys, out: &mut SharedString) {
        *out = shortcut.to_shared_string();
    }
}

/// Internal representation of the `Keys` type.
/// This is semver exempt and is only used to set up the native menu in the backends.
#[derive(PartialEq, Eq, Clone, Default)]
#[repr(C)]
pub struct KeysInner {
    /// The `key` used to trigger the shortcut
    ///
    /// Note: This is currently converted to lowercase when the shortcut is created!
    pub key: SharedString,
    /// `KeyboardModifier`s that need to be pressed for the shortcut to fire
    pub modifiers: KeyboardModifiers,
    /// Whether to ignore shift state when matching the shortcut
    pub ignore_shift: bool,
    /// Whether to ignore alt state when matching the shortcut
    pub ignore_alt: bool,
}

impl KeysInner {
    /// Private access to the KeysInner for a given Keys value.
    pub fn from_pub(keys: &Keys) -> &Self {
        &keys.inner
    }
}

impl Keys {
    /// Check whether a `Keys` can be triggered by the given `KeyEvent`
    pub(crate) fn matches(&self, key_event: &KeyEvent) -> bool {
        let inner = &self.inner;
        // An empty Keys is never triggered, even if the modifiers match.
        if inner.key.is_empty() {
            return false;
        }

        // TODO: Should this check the event_type and only match on KeyReleased?
        let mut expected_modifiers = inner.modifiers;
        if inner.ignore_shift {
            expected_modifiers.shift = key_event.modifiers.shift;
        }
        if inner.ignore_alt {
            expected_modifiers.alt = key_event.modifiers.alt;
        }
        // Note: The shortcut's key is already in lowercase and NFC-normalized
        // (by the compiler and backends respectively), so we only need to
        // lowercase the event text. Backends are expected to NFC-normalize
        // key event text before dispatching.
        //
        // This improves our handling of CapsLock and Shift, as the event text will be in uppercase
        // if caps lock is active, even if shift is not pressed.
        let event_text = key_event.text.chars().flat_map(|character| character.to_lowercase());

        event_text.eq(inner.key.chars()) && key_event.modifiers == expected_modifiers
    }

    fn format_key_for_display(&self) -> crate::SharedString {
        let key_str = self.inner.key.as_str();
        let first_char = key_str.chars().next();

        if let Some(first_char) = first_char {
            macro_rules! check_special_key {
                ($($char:literal # $name:ident # $($shifted:ident)? # $($_muda:ident)? $(=> $($qt:ident)|* # $($winit:ident $(($_pos:ident))?)|* # $($xkb:ident)|*)? ;)*) => {
                    match first_char {
                    $($(
                        // Use $qt as a marker - if it exists, generate the check
                        $char => {
                            let _ = stringify!($($qt)|*); // Use $qt to enable this branch
                            return stringify!($name).into();
                        }
                    )?)*
                        _ => ()
                    }
                };
            }
            i_slint_common::for_each_keys!(check_special_key);
        }

        if key_str.chars().count() == 1 {
            return key_str.to_uppercase().into();
        }

        key_str.into()
    }
}

impl Display for Keys {
    /// Converts the [`Keys`] to a string that looks native on the current platform.
    ///
    /// For example, the shortcut created with `@keys(Meta + Control + A)`
    /// will be converted like this:
    /// - **macOS**: `⌃⌘A`
    /// - **Windows**: `Win+Ctrl+A`
    /// - **Linux**: `Super+Ctrl+A`
    ///
    /// Note that this functions output is best-effort and may be adjusted/improved at any time,
    /// do not rely on this output to be stable!
    //
    // References for implementation
    // - macOS: <https://developer.apple.com/design/human-interface-guidelines/keyboards>
    // - Windows: <https://learn.microsoft.com/en-us/windows/apps/design/input/keyboard-accelerators>
    // - Linux: <https://developer.gnome.org/hig/guidelines/keyboard.html>
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let inner = &self.inner;
        if inner.key.is_empty() {
            return Ok(());
        }

        if crate::is_apple_platform() {
            // Slint remaps modifiers on macOS: control → Command, meta → Control
            // From Apple's documentation:
            //
            // List modifier keys in the correct order.
            // If you use more than one modifier key in a custom shortcut, always list them in this order:
            //  Control, Option, Shift, Command
            if inner.modifiers.meta {
                f.write_str("")?;
            }
            if !inner.ignore_alt && inner.modifiers.alt {
                f.write_str("")?;
            }
            if !inner.ignore_shift && inner.modifiers.shift {
                f.write_str("")?;
            }
            if inner.modifiers.control {
                f.write_str("")?;
            }
        } else {
            let separator = "+";

            // TODO: These should probably be translated, but better to have at least
            // platform-local names than nothing.
            let (ctrl_str, alt_str, shift_str, meta_str) =
                if crate::detect_operating_system() == OperatingSystemType::Windows {
                    ("Ctrl", "Alt", "Shift", "Win")
                } else {
                    ("Ctrl", "Alt", "Shift", "Super")
                };

            if inner.modifiers.meta {
                f.write_str(meta_str)?;
                f.write_str(separator)?;
            }
            if inner.modifiers.control {
                f.write_str(ctrl_str)?;
                f.write_str(separator)?;
            }
            if !inner.ignore_alt && inner.modifiers.alt {
                f.write_str(alt_str)?;
                f.write_str(separator)?;
            }
            if !inner.ignore_shift && inner.modifiers.shift {
                f.write_str(shift_str)?;
                f.write_str(separator)?;
            }
        }
        f.write_str(&self.format_key_for_display())
    }
}

impl core::fmt::Debug for Keys {
    /// Formats the keyboard shortcut so that the output would be accepted by the @keys macro in Slint.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let inner = &self.inner;
        // Make sure to keep this in sync with the implemenation in compiler/langtype.rs
        if inner.key.is_empty() {
            write!(f, "")
        } else {
            let alt = inner
                .ignore_alt
                .then_some("Alt?+")
                .or(inner.modifiers.alt.then_some("Alt+"))
                .unwrap_or_default();
            let ctrl = if inner.modifiers.control { "Control+" } else { "" };
            let meta = if inner.modifiers.meta { "Meta+" } else { "" };
            let shift = inner
                .ignore_shift
                .then_some("Shift?+")
                .or(inner.modifiers.shift.then_some("Shift+"))
                .unwrap_or_default();
            let keycode: SharedString = inner
                .key
                .chars()
                .flat_map(|character| {
                    let mut escaped = alloc::vec![];
                    if character.is_control() {
                        escaped.extend(character.escape_unicode());
                    } else {
                        escaped.push(character);
                    }
                    escaped
                })
                .collect();
            write!(f, "{meta}{ctrl}{alt}{shift}\"{keycode}\"")
        }
    }
}

/// This enum defines the different kinds of key events that can happen.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum KeyEventType {
    /// A key on a keyboard was pressed.
    #[default]
    KeyPressed = 0,
    /// A key on a keyboard was released.
    KeyReleased = 1,
    /// The input method updates the currently composed text. The KeyEvent's text field is the pre-edit text and
    /// composition_selection specifies the placement of the cursor within the pre-edit text.
    UpdateComposition = 2,
    /// The input method replaces the currently composed text with the final result of the composition.
    CommitComposition = 3,
}

#[derive(Default)]
/// This struct is used to pass key events to the runtime.
pub struct InternalKeyEvent {
    /// That's the public type with only public fields
    pub key_event: KeyEvent,
    /// Indicates whether the key was pressed or released
    pub event_type: KeyEventType,
    /// The key without any modifiers held
    /// Important on Windows, to distinguish between key presses when Ctrl+Alt was pressed
    /// vs. AltGr.
    /// This is optional, and we will fall back to a heuristic for Ctrl+Alt on Windows if this
    /// isn't provided.
    #[cfg(target_os = "windows")]
    pub text_without_modifiers: SharedString,
    /// If the event type is KeyEventType::UpdateComposition or KeyEventType::CommitComposition,
    /// then this field specifies what part of the current text to replace.
    /// Relative to the offset of the pre-edit text within the text input element's text.
    pub replacement_range: Option<core::ops::Range<i32>>,
    /// If the event type is KeyEventType::UpdateComposition, this is the new pre-edit text
    pub preedit_text: SharedString,
    /// The selection within the preedit_text
    pub preedit_selection: Option<core::ops::Range<i32>>,
    /// The new cursor position, when None, the cursor is put after the text that was just inserted
    pub cursor_position: Option<i32>,
    /// The anchor position, when None, the cursor is put after the text that was just inserted
    pub anchor_position: Option<i32>,
}

impl InternalKeyEvent {
    /// If a shortcut was pressed, this function returns `Some(StandardShortcut)`.
    /// Otherwise it returns None.
    pub fn shortcut(&self) -> Option<StandardShortcut> {
        if self.key_event.modifiers.control && !self.key_event.modifiers.shift {
            match self.key_event.text.as_str() {
                #[cfg(not(target_arch = "wasm32"))]
                "c" => Some(StandardShortcut::Copy),
                #[cfg(not(target_arch = "wasm32"))]
                "x" => Some(StandardShortcut::Cut),
                #[cfg(not(target_arch = "wasm32"))]
                "v" => Some(StandardShortcut::Paste),
                "a" => Some(StandardShortcut::SelectAll),
                "f" => Some(StandardShortcut::Find),
                "s" => Some(StandardShortcut::Save),
                "p" => Some(StandardShortcut::Print),
                "z" => Some(StandardShortcut::Undo),
                #[cfg(target_os = "windows")]
                "y" => Some(StandardShortcut::Redo),
                "r" => Some(StandardShortcut::Refresh),
                _ => None,
            }
        } else if self.key_event.modifiers.control && self.key_event.modifiers.shift {
            match self.key_event.text.as_str() {
                #[cfg(not(target_os = "windows"))]
                "z" | "Z" => Some(StandardShortcut::Redo),
                _ => None,
            }
        } else {
            None
        }
    }

    /// If a shortcut concerning text editing was pressed, this function
    /// returns `Some(TextShortcut)`. Otherwise it returns None.
    pub fn text_shortcut(&self) -> Option<TextShortcut> {
        let ke = &self.key_event;
        let keycode = ke.text.chars().next()?;

        let is_apple = crate::is_apple_platform();

        let move_mod = if is_apple {
            ke.modifiers.alt && !ke.modifiers.control && !ke.modifiers.meta
        } else {
            ke.modifiers.control && !ke.modifiers.alt && !ke.modifiers.meta
        };

        if move_mod {
            match keycode {
                key_codes::LeftArrow => {
                    return Some(TextShortcut::Move(TextCursorDirection::BackwardByWord));
                }
                key_codes::RightArrow => {
                    return Some(TextShortcut::Move(TextCursorDirection::ForwardByWord));
                }
                key_codes::UpArrow => {
                    return Some(TextShortcut::Move(TextCursorDirection::StartOfParagraph));
                }
                key_codes::DownArrow => {
                    return Some(TextShortcut::Move(TextCursorDirection::EndOfParagraph));
                }
                key_codes::Backspace => {
                    return Some(TextShortcut::DeleteWordBackward);
                }
                key_codes::Delete => {
                    return Some(TextShortcut::DeleteWordForward);
                }
                _ => (),
            };
        }

        #[cfg(not(target_os = "macos"))]
        {
            if ke.modifiers.control && !ke.modifiers.alt && !ke.modifiers.meta {
                match keycode {
                    key_codes::Home => {
                        return Some(TextShortcut::Move(TextCursorDirection::StartOfText));
                    }
                    key_codes::End => {
                        return Some(TextShortcut::Move(TextCursorDirection::EndOfText));
                    }
                    _ => (),
                };
            }
        }

        if is_apple && ke.modifiers.control {
            match keycode {
                key_codes::LeftArrow => {
                    return Some(TextShortcut::Move(TextCursorDirection::StartOfLine));
                }
                key_codes::RightArrow => {
                    return Some(TextShortcut::Move(TextCursorDirection::EndOfLine));
                }
                key_codes::UpArrow => {
                    return Some(TextShortcut::Move(TextCursorDirection::StartOfText));
                }
                key_codes::DownArrow => {
                    return Some(TextShortcut::Move(TextCursorDirection::EndOfText));
                }
                key_codes::Backspace => {
                    return Some(TextShortcut::DeleteToStartOfLine);
                }
                _ => (),
            };
        }

        if let Ok(direction) = TextCursorDirection::try_from(keycode) {
            Some(TextShortcut::Move(direction))
        } else {
            match keycode {
                key_codes::Backspace => Some(TextShortcut::DeleteBackward),
                key_codes::Delete => Some(TextShortcut::DeleteForward),
                _ => None,
            }
        }
    }
}

/// Represents a non context specific shortcut.
pub enum StandardShortcut {
    /// Copy Something
    Copy,
    /// Cut Something
    Cut,
    /// Paste Something
    Paste,
    /// Select All
    SelectAll,
    /// Find/Search Something
    Find,
    /// Save Something
    Save,
    /// Print Something
    Print,
    /// Undo the last action
    Undo,
    /// Redo the last undone action
    Redo,
    /// Refresh
    Refresh,
}

/// Shortcuts that are used when editing text
pub enum TextShortcut {
    /// Move the cursor
    Move(TextCursorDirection),
    /// Delete the Character to the right of the cursor
    DeleteForward,
    /// Delete the Character to the left of the cursor (aka Backspace).
    DeleteBackward,
    /// Delete the word to the right of the cursor
    DeleteWordForward,
    /// Delete the word to the left of the cursor (aka Ctrl + Backspace).
    DeleteWordBackward,
    /// Delete to the left of the cursor until the start of the line
    DeleteToStartOfLine,
}

/// Represents how an item's key_event handler dealt with a key event.
/// An accepted event results in no further event propagation.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum KeyEventResult {
    /// The event was handled.
    EventAccepted,
    /// The event was not handled and should be sent to other items.
    #[default]
    EventIgnored,
}

/// Represents how an item's focus_event handler dealt with a focus event.
/// An accepted event results in no further event propagation.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum FocusEventResult {
    /// The event was handled.
    FocusAccepted,
    /// The event was not handled and should be sent to other items.
    #[default]
    FocusIgnored,
}

/// This event is sent to a component and items when they receive or lose
/// the keyboard focus.
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(u8)]
pub enum FocusEvent {
    /// This event is sent when an item receives the focus.
    FocusIn(FocusReason),
    /// This event is sent when an item loses the focus.
    FocusOut(FocusReason),
}

/// This state is used to count the clicks separated by [`crate::platform::Platform::click_interval`]
#[derive(Default)]
pub struct ClickState {
    click_count_time_stamp: Cell<Option<crate::animations::Instant>>,
    click_count: Cell<u8>,
    click_position: Cell<LogicalPoint>,
    click_button: Cell<PointerEventButton>,
}

impl ClickState {
    /// Resets the timer and count.
    fn restart(&self, position: LogicalPoint, button: PointerEventButton) {
        self.click_count.set(0);
        self.click_count_time_stamp.set(Some(crate::animations::Instant::now()));
        self.click_position.set(position);
        self.click_button.set(button);
    }

    /// Reset to an invalid state
    pub fn reset(&self) {
        self.click_count.set(0);
        self.click_count_time_stamp.replace(None);
    }

    /// Check if the click is repeated.
    pub fn check_repeat(&self, mouse_event: MouseEvent, click_interval: Duration) -> MouseEvent {
        match mouse_event {
            MouseEvent::Pressed { position, button, is_touch, .. } => {
                let instant_now = crate::animations::Instant::now();

                if let Some(click_count_time_stamp) = self.click_count_time_stamp.get() {
                    if instant_now - click_count_time_stamp < click_interval
                        && button == self.click_button.get()
                        && (position - self.click_position.get()).square_length() < 100 as _
                    {
                        self.click_count.set(self.click_count.get().wrapping_add(1));
                        self.click_count_time_stamp.set(Some(instant_now));
                    } else {
                        self.restart(position, button);
                    }
                } else {
                    self.restart(position, button);
                }

                return MouseEvent::Pressed {
                    position,
                    button,
                    click_count: self.click_count.get(),
                    is_touch,
                };
            }
            MouseEvent::Released { position, button, is_touch, .. } => {
                return MouseEvent::Released {
                    position,
                    button,
                    click_count: self.click_count.get(),
                    is_touch,
                };
            }
            _ => {}
        };

        mouse_event
    }
}

/// The state which a window should hold for the mouse input
#[derive(Default)]
pub struct MouseInputState {
    /// The stack of item which contain the mouse cursor (or grab),
    /// along with the last result from the input function
    item_stack: Vec<(ItemWeak, InputEventFilterResult)>,
    /// Offset to apply to the first item of the stack (used if there is a popup)
    pub(crate) offset: LogicalPoint,
    /// true if the top item of the stack has the mouse grab
    grabbed: bool,
    /// When this is Some, it means we are in the middle of a drag-drop operation and it contains the dragged data.
    /// The `position` field has no signification
    pub(crate) drag_data: Option<DropEvent>,
    delayed: Option<(crate::timers::Timer, MouseEvent)>,
    delayed_exit_items: Vec<ItemWeak>,
    pub(crate) cursor: MouseCursor,
}

impl MouseInputState {
    /// Return the item in the top of the stack
    fn top_item(&self) -> Option<ItemRc> {
        self.item_stack.last().and_then(|x| x.0.upgrade())
    }

    /// Returns the item in the top of the stack, if there is a delayed event, this would be the top of the delayed stack
    pub fn top_item_including_delayed(&self) -> Option<ItemRc> {
        self.delayed_exit_items.last().and_then(|x| x.upgrade()).or_else(|| self.top_item())
    }
}

/// Try to handle the mouse grabber. Return None if the event has been handled, otherwise
/// return the event that must be handled
pub(crate) fn handle_mouse_grab(
    mouse_event: &MouseEvent,
    window_adapter: &Rc<dyn WindowAdapter>,
    mouse_input_state: &mut MouseInputState,
) -> Option<MouseEvent> {
    if !mouse_input_state.grabbed || mouse_input_state.item_stack.is_empty() {
        return Some(mouse_event.clone());
    };

    let mut event = mouse_event.clone();
    let mut intercept = false;
    let mut invalid = false;

    event.translate(-mouse_input_state.offset.to_vector());

    mouse_input_state.item_stack.retain(|it| {
        if invalid {
            return false;
        }
        let item = if let Some(item) = it.0.upgrade() {
            item
        } else {
            invalid = true;
            return false;
        };
        if intercept {
            item.borrow().as_ref().input_event(
                &MouseEvent::Exit,
                window_adapter,
                &item,
                &mut mouse_input_state.cursor,
            );
            return false;
        }
        let g = item.geometry();
        event.translate(-g.origin.to_vector());
        if window_adapter.renderer().supports_transformations()
            && let Some(inverse_transform) = item.inverse_children_transform()
        {
            event.transform(inverse_transform);
        }

        let interested = matches!(
            it.1,
            InputEventFilterResult::ForwardAndInterceptGrab
                | InputEventFilterResult::DelayForwarding(_)
        );

        if interested
            && item.borrow().as_ref().input_event_filter_before_children(
                &event,
                window_adapter,
                &item,
                &mut mouse_input_state.cursor,
            ) == InputEventFilterResult::Intercept
        {
            intercept = true;
        }
        true
    });
    if invalid {
        return Some(mouse_event.clone());
    }

    let grabber = mouse_input_state.top_item().unwrap();
    let input_result = grabber.borrow().as_ref().input_event(
        &event,
        window_adapter,
        &grabber,
        &mut mouse_input_state.cursor,
    );
    match input_result {
        InputEventResult::GrabMouse => None,
        InputEventResult::StartDrag => {
            mouse_input_state.grabbed = false;
            let drag_area_item = grabber.downcast::<crate::items::DragArea>().unwrap();
            mouse_input_state.drag_data = Some(DropEvent {
                mime_type: drag_area_item.as_pin_ref().mime_type(),
                data: drag_area_item.as_pin_ref().data(),
                position: Default::default(),
            });
            None
        }
        _ => {
            mouse_input_state.grabbed = false;
            // Return a move event so that the new position can be registered properly
            Some(mouse_event.position().map_or(MouseEvent::Exit, |position| MouseEvent::Moved {
                position,
                is_touch: mouse_event.is_touch().unwrap_or(false),
            }))
        }
    }
}

pub(crate) fn send_exit_events(
    old_input_state: &MouseInputState,
    new_input_state: &mut MouseInputState,
    mut pos: Option<LogicalPoint>,
    window_adapter: &Rc<dyn WindowAdapter>,
) {
    // Note that exit events can't actually change the cursor from default so we'll ignore the result
    let cursor = &mut MouseCursor::Default;

    for it in core::mem::take(&mut new_input_state.delayed_exit_items) {
        let Some(item) = it.upgrade() else { continue };
        item.borrow().as_ref().input_event(&MouseEvent::Exit, window_adapter, &item, cursor);
    }

    let mut clipped = false;
    for (idx, it) in old_input_state.item_stack.iter().enumerate() {
        let Some(item) = it.0.upgrade() else { break };
        let g = item.geometry();
        let contains = pos.is_some_and(|p| g.contains(p));
        if let Some(p) = pos.as_mut() {
            *p -= g.origin.to_vector();
            if window_adapter.renderer().supports_transformations()
                && let Some(inverse_transform) = item.inverse_children_transform()
            {
                *p = inverse_transform.transform_point(p.cast()).cast();
            }
        }
        if !contains || clipped {
            if item.borrow().as_ref().clips_children() {
                clipped = true;
            }
            item.borrow().as_ref().input_event(&MouseEvent::Exit, window_adapter, &item, cursor);
        } else if new_input_state.item_stack.get(idx).is_none_or(|(x, _)| *x != it.0) {
            // The item is still under the mouse, but no longer in the item stack. We should also sent the exit event, unless we delay it
            if new_input_state.delayed.is_some() {
                new_input_state.delayed_exit_items.push(it.0.clone());
            } else {
                item.borrow().as_ref().input_event(
                    &MouseEvent::Exit,
                    window_adapter,
                    &item,
                    cursor,
                );
            }
        }
    }
}

/// Process the `mouse_event` on the `component`, the `mouse_grabber_stack` is the previous stack
/// of mouse grabber.
/// Returns a new mouse grabber stack.
pub fn process_mouse_input(
    root: ItemRc,
    mouse_event: &MouseEvent,
    window_adapter: &Rc<dyn WindowAdapter>,
    mouse_input_state: MouseInputState,
) -> MouseInputState {
    let mut result = MouseInputState {
        drag_data: mouse_input_state.drag_data.clone(),
        cursor: mouse_input_state.cursor,
        ..Default::default()
    };
    let r = send_mouse_event_to_item(
        mouse_event,
        root.clone(),
        window_adapter,
        &mut result,
        mouse_input_state.top_item().as_ref(),
        false,
    );
    if mouse_input_state.delayed.is_some()
        && (!r.has_aborted()
            || Option::zip(result.item_stack.last(), mouse_input_state.item_stack.last())
                .is_none_or(|(a, b)| a.0 != b.0))
    {
        // Keep the delayed event
        return mouse_input_state;
    }
    send_exit_events(&mouse_input_state, &mut result, mouse_event.position(), window_adapter);

    if let MouseEvent::Wheel { position, .. } = mouse_event
        && r.has_aborted()
    {
        // An accepted wheel event might have moved things. Send a move event at the position to reset the has-hover
        return process_mouse_input(
            root,
            &MouseEvent::Moved { position: *position, is_touch: false },
            window_adapter,
            result,
        );
    }

    result
}

pub(crate) fn process_delayed_event(
    window_adapter: &Rc<dyn WindowAdapter>,
    mut mouse_input_state: MouseInputState,
) -> MouseInputState {
    // the take bellow will also destroy the Timer
    let event = match mouse_input_state.delayed.take() {
        Some(e) => e.1,
        None => return mouse_input_state,
    };

    let top_item = match mouse_input_state.top_item() {
        Some(i) => i,
        None => return MouseInputState::default(),
    };

    let mut actual_visitor =
        |component: &ItemTreeRc, index: u32, _: Pin<ItemRef>| -> VisitChildrenResult {
            send_mouse_event_to_item(
                &event,
                ItemRc::new(component.clone(), index),
                window_adapter,
                &mut mouse_input_state,
                Some(&top_item),
                true,
            )
        };
    vtable::new_vref!(let mut actual_visitor : VRefMut<crate::item_tree::ItemVisitorVTable> for crate::item_tree::ItemVisitor = &mut actual_visitor);
    vtable::VRc::borrow_pin(top_item.item_tree()).as_ref().visit_children_item(
        top_item.index() as isize,
        crate::item_tree::TraversalOrder::FrontToBack,
        actual_visitor,
    );
    mouse_input_state
}

fn send_mouse_event_to_item(
    mouse_event: &MouseEvent,
    item_rc: ItemRc,
    window_adapter: &Rc<dyn WindowAdapter>,
    result: &mut MouseInputState,
    last_top_item: Option<&ItemRc>,
    ignore_delays: bool,
) -> VisitChildrenResult {
    let item = item_rc.borrow();
    let geom = item_rc.geometry();
    // translated in our coordinate
    let mut event_for_children = mouse_event.clone();
    // Unapply the translation to go from 'world' space to local space
    event_for_children.translate(-geom.origin.to_vector());
    if window_adapter.renderer().supports_transformations() {
        // Unapply other transforms.
        if let Some(inverse_transform) = item_rc.inverse_children_transform() {
            event_for_children.transform(inverse_transform);
        }
    }

    let filter_result = if mouse_event.position().is_some_and(|p| geom.contains(p))
        || item.as_ref().clips_children()
    {
        item.as_ref().input_event_filter_before_children(
            &event_for_children,
            window_adapter,
            &item_rc,
            &mut result.cursor,
        )
    } else {
        InputEventFilterResult::ForwardAndIgnore
    };

    let (forward_to_children, ignore) = match filter_result {
        InputEventFilterResult::ForwardEvent => (true, false),
        InputEventFilterResult::ForwardAndIgnore => (true, true),
        InputEventFilterResult::ForwardAndInterceptGrab => (true, false),
        InputEventFilterResult::Intercept => (false, false),
        InputEventFilterResult::DelayForwarding(_) if ignore_delays => (true, false),
        InputEventFilterResult::DelayForwarding(duration) => {
            let timer = Timer::default();
            let w = Rc::downgrade(window_adapter);
            timer.start(
                crate::timers::TimerMode::SingleShot,
                Duration::from_millis(duration),
                move || {
                    if let Some(w) = w.upgrade() {
                        WindowInner::from_pub(w.window()).process_delayed_event();
                    }
                },
            );
            result.delayed = Some((timer, event_for_children));
            result
                .item_stack
                .push((item_rc.downgrade(), InputEventFilterResult::DelayForwarding(duration)));
            return VisitChildrenResult::abort(item_rc.index(), 0);
        }
    };

    result.item_stack.push((item_rc.downgrade(), filter_result));
    if forward_to_children {
        let mut actual_visitor =
            |component: &ItemTreeRc, index: u32, _: Pin<ItemRef>| -> VisitChildrenResult {
                send_mouse_event_to_item(
                    &event_for_children,
                    ItemRc::new(component.clone(), index),
                    window_adapter,
                    result,
                    last_top_item,
                    ignore_delays,
                )
            };
        vtable::new_vref!(let mut actual_visitor : VRefMut<crate::item_tree::ItemVisitorVTable> for crate::item_tree::ItemVisitor = &mut actual_visitor);
        let r = vtable::VRc::borrow_pin(item_rc.item_tree()).as_ref().visit_children_item(
            item_rc.index() as isize,
            crate::item_tree::TraversalOrder::FrontToBack,
            actual_visitor,
        );
        if r.has_aborted() {
            return r;
        }
    };

    let r = if ignore {
        InputEventResult::EventIgnored
    } else {
        let mut event = mouse_event.clone();
        event.translate(-geom.origin.to_vector());
        if last_top_item.is_none_or(|x| *x != item_rc) {
            event.set_click_count(0);
        }
        item.as_ref().input_event(&event, window_adapter, &item_rc, &mut result.cursor)
    };
    match r {
        InputEventResult::EventAccepted => VisitChildrenResult::abort(item_rc.index(), 0),
        InputEventResult::EventIgnored => {
            let _pop = result.item_stack.pop();
            debug_assert_eq!(
                _pop.map(|x| (x.0.upgrade().unwrap().index(), x.1)).unwrap(),
                (item_rc.index(), filter_result)
            );
            VisitChildrenResult::CONTINUE
        }
        InputEventResult::GrabMouse => {
            result.item_stack.last_mut().unwrap().1 =
                InputEventFilterResult::ForwardAndInterceptGrab;
            result.grabbed = true;
            VisitChildrenResult::abort(item_rc.index(), 0)
        }
        InputEventResult::StartDrag => {
            result.item_stack.last_mut().unwrap().1 =
                InputEventFilterResult::ForwardAndInterceptGrab;
            result.grabbed = false;
            let drag_area_item = item_rc.downcast::<crate::items::DragArea>().unwrap();
            result.drag_data = Some(DropEvent {
                mime_type: drag_area_item.as_pin_ref().mime_type(),
                data: drag_area_item.as_pin_ref().data(),
                position: Default::default(),
            });
            VisitChildrenResult::abort(item_rc.index(), 0)
        }
    }
}

/// The TextCursorBlinker takes care of providing a toggled boolean property
/// that can be used to animate a blinking cursor. It's typically stored in the
/// Window using a Weak and set_binding() can be used to set up a binding on a given
/// property that'll keep it up-to-date. That binding keeps a strong reference to the
/// blinker. If the underlying item that uses it goes away, the binding goes away and
/// so does the blinker.
#[derive(FieldOffsets)]
#[repr(C)]
#[pin]
pub(crate) struct TextCursorBlinker {
    cursor_visible: Property<bool>,
    cursor_blink_timer: crate::timers::Timer,
}

impl TextCursorBlinker {
    /// Creates a new instance, wrapped in a Pin<Rc<_>> because the boolean property
    /// the blinker properties uses the property system that requires pinning.
    pub fn new() -> Pin<Rc<Self>> {
        Rc::pin(Self {
            cursor_visible: Property::new(true),
            cursor_blink_timer: Default::default(),
        })
    }

    /// Sets a binding on the provided property that will ensure that the property value
    /// is true when the cursor should be shown and false if not.
    pub fn set_binding(
        instance: Pin<Rc<TextCursorBlinker>>,
        prop: &Property<bool>,
        cycle_duration: Duration,
    ) {
        instance.as_ref().cursor_visible.set(true);
        // Re-start timer, in case.
        Self::start(&instance, cycle_duration);
        prop.set_binding(move || {
            TextCursorBlinker::FIELD_OFFSETS.cursor_visible().apply_pin(instance.as_ref()).get()
        });
    }

    /// Starts the blinking cursor timer that will toggle the cursor and update all bindings that
    /// were installed on properties with set_binding call.
    pub fn start(self: &Pin<Rc<Self>>, cycle_duration: Duration) {
        if self.cursor_blink_timer.running() {
            self.cursor_blink_timer.restart();
        } else {
            let toggle_cursor = {
                let weak_blinker = pin_weak::rc::PinWeak::downgrade(self.clone());
                move || {
                    if let Some(blinker) = weak_blinker.upgrade() {
                        let visible = TextCursorBlinker::FIELD_OFFSETS
                            .cursor_visible()
                            .apply_pin(blinker.as_ref())
                            .get();
                        blinker.cursor_visible.set(!visible);
                    }
                }
            };
            if !cycle_duration.is_zero() {
                self.cursor_blink_timer.start(
                    crate::timers::TimerMode::Repeated,
                    cycle_duration / 2,
                    toggle_cursor,
                );
            }
        }
    }

    /// Stops the blinking cursor timer. This is usually used for example when the window that contains
    /// text editable elements looses the focus or is hidden.
    pub fn stop(&self) {
        self.cursor_blink_timer.stop()
    }
}

/// A single active touch point.
#[derive(Clone, Copy, Default)]
struct TouchPoint {
    id: u64,
    position: LogicalPoint,
}

/// Fixed-capacity map of touch IDs to touch points.
///
/// Touchscreens rarely report more than 5 simultaneous contacts, and gesture
/// recognition only uses the first two. A linear-scan array avoids the heap
/// allocation and pointer-chasing overhead of `BTreeMap` for this tiny collection.
const MAX_TRACKED_TOUCHES: usize = 5;

#[derive(Clone)]
struct TouchMap {
    entries: [TouchPoint; MAX_TRACKED_TOUCHES],
    len: usize,
}

impl Default for TouchMap {
    fn default() -> Self {
        Self { entries: [TouchPoint::default(); MAX_TRACKED_TOUCHES], len: 0 }
    }
}

impl TouchMap {
    fn get(&self, id: u64) -> Option<&TouchPoint> {
        self.entries[..self.len].iter().find(|tp| tp.id == id)
    }

    fn get_mut(&mut self, id: u64) -> Option<&mut TouchPoint> {
        self.entries[..self.len].iter_mut().find(|tp| tp.id == id)
    }

    fn insert(&mut self, point: TouchPoint) {
        if let Some(existing) = self.entries[..self.len].iter_mut().find(|tp| tp.id == point.id) {
            *existing = point;
        } else if self.len < MAX_TRACKED_TOUCHES {
            self.entries[self.len] = point;
            self.len += 1;
        }
    }

    fn remove(&mut self, id: u64) {
        if let Some(idx) = self.entries[..self.len].iter().position(|tp| tp.id == id) {
            self.len -= 1;
            self.entries[idx] = self.entries[self.len];
        }
    }

    fn len(&self) -> usize {
        self.len
    }

    /// Returns the first two distinct IDs, or `None` if fewer than 2 entries.
    fn first_two_ids(&self) -> Option<(u64, u64)> {
        if self.len >= 2 { Some((self.entries[0].id, self.entries[1].id)) } else { None }
    }

    /// Returns the first entry, if any.
    fn first(&self) -> Option<&TouchPoint> {
        if self.len > 0 { Some(&self.entries[0]) } else { None }
    }
}

/// Fixed-capacity buffer for [`MouseEvent`]s produced by the touch state machine.
///
/// No branch in [`TouchState::process`] emits more than 3 events (gesture end
/// produces PinchEnded + RotationEnded + Pressed/Exit). Capacity 4 provides a
/// margin without heap allocation.
const MAX_TOUCH_EVENTS: usize = 4;

#[derive(Clone)]
pub(crate) struct TouchEventBuffer {
    events: [Option<MouseEvent>; MAX_TOUCH_EVENTS],
    len: usize,
}

impl TouchEventBuffer {
    fn new() -> Self {
        Self { events: [None, None, None, None], len: 0 }
    }

    fn push(&mut self, event: MouseEvent) {
        debug_assert!(self.len < MAX_TOUCH_EVENTS, "TouchEventBuffer overflow");
        if self.len < MAX_TOUCH_EVENTS {
            self.events[self.len] = Some(event);
            self.len += 1;
        }
    }

    /// Returns an iterator over the buffered events.
    pub(crate) fn into_iter(self) -> impl Iterator<Item = MouseEvent> {
        let len = self.len;
        self.events.into_iter().take(len).flatten()
    }
}

/// State of the multi-touch gesture recognizer.
#[derive(Default, Debug, Clone, Copy)]
enum GestureRecognitionState {
    /// 0-1 fingers; forwarding as mouse events.
    #[default]
    Idle,
    /// 2 fingers down, waiting for movement to exceed threshold.
    TwoFingersDown { finger_ids: (u64, u64), initial_distance: f32, last_angle: euclid::Angle<f32> },
    /// Actively synthesizing PinchGesture/RotationGesture events.
    Pinching {
        finger_ids: (u64, u64),
        initial_distance: f32,
        last_scale: f32,
        last_angle: euclid::Angle<f32>,
    },
}

/// Tracks all active touch points and recognizes pinch/rotation gestures.
///
/// When only one finger is down, touch events are forwarded as mouse events.
/// When two fingers are down and move beyond a threshold, synthesized
/// `PinchGesture` and `RotationGesture` events are emitted — the same events
/// that platform gesture recognition (e.g. macOS trackpad) produces.
pub(crate) struct TouchState {
    active_touches: TouchMap,
    /// The finger forwarded as mouse events during single-touch.
    primary_touch_id: Option<u64>,
    gesture_state: GestureRecognitionState,
}

impl Default for TouchState {
    fn default() -> Self {
        Self {
            active_touches: TouchMap::default(),
            primary_touch_id: None,
            gesture_state: GestureRecognitionState::Idle,
        }
    }
}

impl TouchState {
    /// Minimum movement (in logical pixels) before two fingers are recognized as a pinch.
    const PINCH_THRESHOLD: f32 = 8.0;

    /// Minimum angular change (in degrees) before two fingers are recognized as a rotation.
    const ROTATION_THRESHOLD: f32 = 5.0;

    /// Returns the finger IDs from the current gesture state, if any.
    fn gesture_finger_ids(&self) -> Option<(u64, u64)> {
        match self.gesture_state {
            GestureRecognitionState::TwoFingersDown { finger_ids, .. }
            | GestureRecognitionState::Pinching { finger_ids, .. } => Some(finger_ids),
            GestureRecognitionState::Idle => None,
        }
    }

    /// Returns (distance, angle) between two specific touch points.
    fn geometry_for(&self, (id_a, id_b): (u64, u64)) -> Option<(f32, euclid::Angle<f32>)> {
        let a = self.active_touches.get(id_a)?;
        let b = self.active_touches.get(id_b)?;
        let delta = (b.position - a.position).cast::<f32>();
        Some((delta.length(), delta.angle_from_x_axis()))
    }

    /// Returns the positions of the two gesture fingers, or `None` if not available.
    fn gesture_finger_positions(&self) -> Option<(&TouchPoint, &TouchPoint)> {
        let (id_a, id_b) = self.gesture_finger_ids()?;
        let a = self.active_touches.get(id_a)?;
        let b = self.active_touches.get(id_b)?;
        Some((a, b))
    }

    /// Returns the midpoint between the two gesture fingers, or `None`.
    fn gesture_midpoint(&self) -> Option<LogicalPoint> {
        let (a, b) = self.gesture_finger_positions()?;
        let mid = a.position.cast::<f32>().lerp(b.position.cast::<f32>(), 0.5);
        Some(mid.cast())
    }

    /// Returns (distance, angle) between the two gesture fingers.
    fn gesture_geometry(&self) -> Option<(f32, euclid::Angle<f32>)> {
        let (a, b) = self.gesture_finger_positions()?;
        let delta = (b.position - a.position).cast::<f32>();
        Some((delta.length(), delta.angle_from_x_axis()))
    }

    /// Returns true if the given touch ID is one of the two gesture fingers.
    fn is_gesture_finger(&self, id: u64) -> bool {
        self.gesture_finger_ids().is_some_and(|(a, b)| id == a || id == b)
    }

    /// Run the touch state machine for a single event and return the
    /// [`MouseEvent`]s to dispatch.
    ///
    /// This is intentionally separated from [`crate::window::WindowInner::process_touch_input`]
    /// so that the `RefCell` borrow can be dropped *once* before dispatching,
    /// rather than requiring a manual `drop` at every branch.
    pub(crate) fn process(
        &mut self,
        id: u64,
        position: LogicalPoint,
        phase: TouchPhase,
    ) -> TouchEventBuffer {
        let mut events = TouchEventBuffer::new();
        match phase {
            TouchPhase::Started => self.process_started(id, position, &mut events),
            TouchPhase::Moved => self.process_moved(id, position, &mut events),
            TouchPhase::Ended => self.process_ended(id, position, false, &mut events),
            TouchPhase::Cancelled => self.process_ended(id, position, true, &mut events),
        }
        events
    }

    fn process_started(&mut self, id: u64, position: LogicalPoint, events: &mut TouchEventBuffer) {
        self.active_touches.insert(TouchPoint { id, position });

        let total = self.active_touches.len();
        if total == 1 {
            // First finger: become primary, forward as mouse press.
            self.primary_touch_id = Some(id);
            self.gesture_state = GestureRecognitionState::Idle;
            events.push(MouseEvent::Pressed {
                position,
                button: PointerEventButton::Left,
                click_count: 0,
                is_touch: true,
            });
        } else if total == 2 {
            // Second finger: transition Idle → TwoFingersDown.
            let finger_ids = self.active_touches.first_two_ids().unwrap_or((0, 0));

            // Synthesize a Release for the primary finger to clear any
            // Flickable grab / delay state.
            let primary_pos = self
                .primary_touch_id
                .and_then(|pid| self.active_touches.get(pid))
                .map(|tp| tp.position)
                .unwrap_or(position);

            // Compute initial geometry for threshold detection.
            let (initial_distance, last_angle) =
                self.geometry_for(finger_ids).unwrap_or((0.0, euclid::Angle::zero()));
            self.gesture_state = GestureRecognitionState::TwoFingersDown {
                finger_ids,
                initial_distance,
                last_angle,
            };

            events.push(MouseEvent::Released {
                position: primary_pos,
                button: PointerEventButton::Left,
                click_count: 0,
                is_touch: true,
            });
        }
        // 3+ fingers: tracked in active_touches but ignored for gesture.
    }

    fn process_moved(&mut self, id: u64, position: LogicalPoint, events: &mut TouchEventBuffer) {
        if let Some(tp) = self.active_touches.get_mut(id) {
            tp.position = position;
        }

        let is_gesture_finger = self.is_gesture_finger(id);

        match self.gesture_state {
            GestureRecognitionState::Idle => {
                if self.primary_touch_id == Some(id) {
                    events.push(MouseEvent::Moved { position, is_touch: true });
                }
            }
            GestureRecognitionState::TwoFingersDown {
                finger_ids,
                initial_distance,
                last_angle,
            } if is_gesture_finger => {
                if let Some((dist, angle)) = self.gesture_geometry() {
                    let delta_dist = (dist - initial_distance).abs();
                    let delta_angle = (angle - last_angle).signed().to_degrees().abs();
                    if delta_dist > Self::PINCH_THRESHOLD || delta_angle > Self::ROTATION_THRESHOLD
                    {
                        // Re-snapshot so the first gesture event starts from
                        // the current geometry rather than accumulating the
                        // threshold movement.
                        self.gesture_state = GestureRecognitionState::Pinching {
                            finger_ids,
                            initial_distance: dist,
                            last_scale: 1.0,
                            last_angle: angle,
                        };

                        let midpoint = self.gesture_midpoint().unwrap_or(position);

                        events.push(MouseEvent::PinchGesture {
                            position: midpoint,
                            delta: 0.0,
                            phase: TouchPhase::Started,
                        });
                        events.push(MouseEvent::RotationGesture {
                            position: midpoint,
                            delta: 0.0,
                            phase: TouchPhase::Started,
                        });
                    }
                }
            }
            GestureRecognitionState::Pinching {
                initial_distance, last_scale, last_angle, ..
            } if is_gesture_finger => {
                if let Some((dist, angle)) = self.gesture_geometry() {
                    let midpoint = self.gesture_midpoint().unwrap_or(position);

                    let current_scale =
                        if initial_distance > 0.0 { dist / initial_distance } else { 1.0 };
                    let scale_delta = current_scale - last_scale;

                    // `.signed()` wraps to [-pi, pi] so crossing the ±180°
                    // atan2 boundary doesn't produce a full-revolution jump.
                    let rotation_delta = (angle - last_angle).signed().to_degrees();

                    // Update the mutable state for next frame.
                    if let GestureRecognitionState::Pinching {
                        last_scale: ref mut ls,
                        last_angle: ref mut la,
                        ..
                    } = self.gesture_state
                    {
                        *ls = current_scale;
                        *la = angle;
                    }

                    events.push(MouseEvent::PinchGesture {
                        position: midpoint,
                        delta: scale_delta,
                        phase: TouchPhase::Moved,
                    });
                    events.push(MouseEvent::RotationGesture {
                        position: midpoint,
                        delta: rotation_delta,
                        phase: TouchPhase::Moved,
                    });
                }
            }
            _ => {}
        }
    }

    fn process_ended(
        &mut self,
        id: u64,
        position: LogicalPoint,
        is_cancelled: bool,
        events: &mut TouchEventBuffer,
    ) {
        // Check gesture membership *before* removing from the map.
        let is_gesture_finger = self.is_gesture_finger(id);
        let midpoint = self.gesture_midpoint().unwrap_or(position);
        self.active_touches.remove(id);

        match self.gesture_state {
            GestureRecognitionState::Idle => {
                if self.primary_touch_id == Some(id) {
                    self.primary_touch_id = None;
                    events.push(MouseEvent::Released {
                        position,
                        button: PointerEventButton::Left,
                        click_count: 0,
                        is_touch: true,
                    });
                    events.push(MouseEvent::Exit);
                }
            }
            GestureRecognitionState::TwoFingersDown { .. } if is_gesture_finger => {
                self.gesture_state = GestureRecognitionState::Idle;
                if !is_cancelled {
                    if let Some(remaining) = self.active_touches.first() {
                        let remaining_pos = remaining.position;
                        self.primary_touch_id = Some(remaining.id);
                        events.push(MouseEvent::Pressed {
                            position: remaining_pos,
                            button: PointerEventButton::Left,
                            click_count: 0,
                            is_touch: true,
                        });
                    } else {
                        self.primary_touch_id = None;
                        events.push(MouseEvent::Exit);
                    }
                } else {
                    self.primary_touch_id = None;
                    events.push(MouseEvent::Exit);
                }
            }
            GestureRecognitionState::Pinching { .. } if is_gesture_finger => {
                self.gesture_state = GestureRecognitionState::Idle;

                let gesture_phase =
                    if is_cancelled { TouchPhase::Cancelled } else { TouchPhase::Ended };

                let remaining = if !is_cancelled {
                    self.active_touches.first().map(|tp| (tp.id, tp.position))
                } else {
                    None
                };
                if let Some((rid, _)) = remaining {
                    self.primary_touch_id = Some(rid);
                } else {
                    self.primary_touch_id = None;
                }

                events.push(MouseEvent::PinchGesture {
                    position: midpoint,
                    delta: 0.0,
                    phase: gesture_phase,
                });
                events.push(MouseEvent::RotationGesture {
                    position: midpoint,
                    delta: 0.0,
                    phase: gesture_phase,
                });

                if let Some((_, rpos)) = remaining {
                    events.push(MouseEvent::Pressed {
                        position: rpos,
                        button: PointerEventButton::Left,
                        click_count: 0,
                        is_touch: true,
                    });
                } else {
                    events.push(MouseEvent::Exit);
                }
            }
            _ => {}
        }
    }
}

#[cfg(test)]
mod touch_tests {
    extern crate alloc;
    use alloc::vec;
    use alloc::vec::Vec;

    use super::*;
    use crate::lengths::LogicalPoint;

    fn pt(x: f32, y: f32) -> LogicalPoint {
        euclid::point2(x, y)
    }

    // -----------------------------------------------------------------------
    // TouchMap tests
    // -----------------------------------------------------------------------

    #[test]
    fn touch_map_insert_and_get() {
        let mut map = TouchMap::default();
        assert_eq!(map.len(), 0);
        map.insert(TouchPoint { id: 1, position: pt(10.0, 20.0) });
        assert_eq!(map.len(), 1);
        assert!(map.get(1).is_some());
        assert!((map.get(1).unwrap().position.x - 10.0).abs() < f32::EPSILON);
        assert!(map.get(2).is_none());
    }

    #[test]
    fn touch_map_update_existing() {
        let mut map = TouchMap::default();
        map.insert(TouchPoint { id: 1, position: pt(10.0, 20.0) });
        map.insert(TouchPoint { id: 1, position: pt(30.0, 40.0) });
        assert_eq!(map.len(), 1);
        assert!((map.get(1).unwrap().position.x - 30.0).abs() < f32::EPSILON);
    }

    #[test]
    fn touch_map_remove() {
        let mut map = TouchMap::default();
        map.insert(TouchPoint { id: 1, position: pt(10.0, 20.0) });
        map.insert(TouchPoint { id: 2, position: pt(30.0, 40.0) });
        assert_eq!(map.len(), 2);
        map.remove(1);
        assert_eq!(map.len(), 1);
        assert!(map.get(1).is_none());
        assert!(map.get(2).is_some());
    }

    #[test]
    fn touch_map_remove_nonexistent() {
        let mut map = TouchMap::default();
        map.insert(TouchPoint { id: 1, position: pt(10.0, 20.0) });
        map.remove(99);
        assert_eq!(map.len(), 1);
    }

    #[test]
    fn touch_map_capacity() {
        let mut map = TouchMap::default();
        for i in 0..MAX_TRACKED_TOUCHES {
            map.insert(TouchPoint { id: i as u64, position: pt(i as f32, 0.0) });
        }
        assert_eq!(map.len(), MAX_TRACKED_TOUCHES);
        // Inserting beyond capacity is silently ignored.
        map.insert(TouchPoint { id: 99, position: pt(99.0, 0.0) });
        assert_eq!(map.len(), MAX_TRACKED_TOUCHES);
        assert!(map.get(99).is_none());
    }

    #[test]
    fn touch_map_first_two_ids() {
        let mut map = TouchMap::default();
        assert!(map.first_two_ids().is_none());
        map.insert(TouchPoint { id: 5, position: pt(0.0, 0.0) });
        assert!(map.first_two_ids().is_none());
        map.insert(TouchPoint { id: 10, position: pt(0.0, 0.0) });
        assert_eq!(map.first_two_ids(), Some((5, 10)));
    }

    #[test]
    fn touch_map_first() {
        let mut map = TouchMap::default();
        assert!(map.first().is_none());
        map.insert(TouchPoint { id: 7, position: pt(1.0, 2.0) });
        let tp = map.first().unwrap();
        assert_eq!(tp.id, 7);
        assert!((tp.position.x - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn touch_map_get_mut() {
        let mut map = TouchMap::default();
        map.insert(TouchPoint { id: 1, position: pt(0.0, 0.0) });
        map.get_mut(1).unwrap().position = pt(5.0, 6.0);
        assert!((map.get(1).unwrap().position.x - 5.0).abs() < f32::EPSILON);
    }

    // -----------------------------------------------------------------------
    // Helper: extract event types for readable assertions
    // -----------------------------------------------------------------------

    #[derive(Debug, PartialEq)]
    enum Ev {
        Pressed(f32, f32),
        Released(f32, f32),
        Moved(f32, f32),
        Exit,
        PinchStarted,
        PinchMoved(f32),
        PinchEnded,
        PinchCancelled,
        RotationStarted,
        RotationMoved(f32),
        RotationEnded,
        RotationCancelled,
    }

    fn classify(events: &TouchEventBuffer) -> Vec<Ev> {
        events
            .clone()
            .into_iter()
            .map(|e| match e {
                MouseEvent::Pressed { position, .. } => Ev::Pressed(position.x, position.y),
                MouseEvent::Released { position, .. } => Ev::Released(position.x, position.y),
                MouseEvent::Moved { position, .. } => Ev::Moved(position.x, position.y),
                MouseEvent::Exit => Ev::Exit,
                MouseEvent::PinchGesture { delta, phase, .. } => match phase {
                    TouchPhase::Started => Ev::PinchStarted,
                    TouchPhase::Moved => Ev::PinchMoved(delta),
                    TouchPhase::Ended => Ev::PinchEnded,
                    TouchPhase::Cancelled => Ev::PinchCancelled,
                },
                MouseEvent::RotationGesture { delta, phase, .. } => match phase {
                    TouchPhase::Started => Ev::RotationStarted,
                    TouchPhase::Moved => Ev::RotationMoved(delta),
                    TouchPhase::Ended => Ev::RotationEnded,
                    TouchPhase::Cancelled => Ev::RotationCancelled,
                },
                _ => panic!("unexpected event: {:?}", e),
            })
            .collect()
    }

    // -----------------------------------------------------------------------
    // TouchState: single-finger forwarding
    // -----------------------------------------------------------------------

    #[test]
    fn single_finger_press_move_release() {
        let mut state = TouchState::default();

        let evs = state.process(1, pt(100.0, 200.0), TouchPhase::Started);
        assert_eq!(classify(&evs), vec![Ev::Pressed(100.0, 200.0)]);

        let evs = state.process(1, pt(110.0, 200.0), TouchPhase::Moved);
        assert_eq!(classify(&evs), vec![Ev::Moved(110.0, 200.0)]);

        let evs = state.process(1, pt(110.0, 200.0), TouchPhase::Ended);
        assert_eq!(classify(&evs), vec![Ev::Released(110.0, 200.0), Ev::Exit]);
    }

    #[test]
    fn single_finger_cancel() {
        let mut state = TouchState::default();

        state.process(1, pt(100.0, 200.0), TouchPhase::Started);

        let evs = state.process(1, pt(100.0, 200.0), TouchPhase::Cancelled);
        assert_eq!(classify(&evs), vec![Ev::Released(100.0, 200.0), Ev::Exit]);
    }

    #[test]
    fn non_primary_move_ignored() {
        let mut state = TouchState::default();
        // Touch 1 is primary.
        state.process(1, pt(100.0, 200.0), TouchPhase::Started);

        // Move for a different ID that was never started (edge case).
        let evs = state.process(99, pt(50.0, 50.0), TouchPhase::Moved);
        assert!(classify(&evs).is_empty());
    }

    // -----------------------------------------------------------------------
    // TouchState: two-finger → gesture transition
    // -----------------------------------------------------------------------

    #[test]
    fn two_fingers_synthesize_release_then_gesture() {
        let mut state = TouchState::default();

        // Finger 1 down.
        let evs = state.process(1, pt(100.0, 200.0), TouchPhase::Started);
        assert_eq!(classify(&evs), vec![Ev::Pressed(100.0, 200.0)]);

        // Finger 2 down → synthesized release for finger 1.
        let evs = state.process(2, pt(200.0, 200.0), TouchPhase::Started);
        assert_eq!(classify(&evs), vec![Ev::Released(100.0, 200.0)]);
        assert!(matches!(state.gesture_state, GestureRecognitionState::TwoFingersDown { .. }));

        // Move finger 2 far enough to trigger pinch (> 8px threshold).
        let evs = state.process(2, pt(220.0, 200.0), TouchPhase::Moved);
        assert_eq!(classify(&evs), vec![Ev::PinchStarted, Ev::RotationStarted]);
        assert!(matches!(state.gesture_state, GestureRecognitionState::Pinching { .. }));
    }

    #[test]
    fn two_fingers_below_threshold_no_gesture() {
        let mut state = TouchState::default();

        state.process(1, pt(100.0, 200.0), TouchPhase::Started);
        state.process(2, pt(200.0, 200.0), TouchPhase::Started);

        // Small movement within threshold.
        let evs = state.process(2, pt(202.0, 200.0), TouchPhase::Moved);
        assert!(classify(&evs).is_empty());
        assert!(matches!(state.gesture_state, GestureRecognitionState::TwoFingersDown { .. }));
    }

    #[test]
    fn pinch_produces_scale_deltas() {
        let mut state = TouchState::default();

        // Set up: finger 1 at (0, 0), finger 2 at (100, 0) → distance = 100.
        state.process(1, pt(0.0, 0.0), TouchPhase::Started);
        state.process(2, pt(100.0, 0.0), TouchPhase::Started);

        // Move finger 2 to (120, 0) to exceed threshold and start pinching.
        state.process(2, pt(120.0, 0.0), TouchPhase::Moved);
        assert!(matches!(state.gesture_state, GestureRecognitionState::Pinching { .. }));

        // Now move finger 2 further to (180, 0).
        // New distance = 180, initial distance (re-snapshotted) = 120.
        // Scale = 180/120 = 1.5, delta = 1.5 - 1.0 = 0.5.
        let evs = state.process(2, pt(180.0, 0.0), TouchPhase::Moved);
        let classified = classify(&evs);
        assert_eq!(classified.len(), 2);
        if let Ev::PinchMoved(delta) = classified[0] {
            assert!((delta - 0.5).abs() < 0.01, "expected ~0.5, got {}", delta);
        } else {
            panic!("expected PinchMoved, got {:?}", classified[0]);
        }
    }

    #[test]
    fn rotation_produces_correct_deltas() {
        let mut state = TouchState::default();

        // Finger 1 at origin, finger 2 on the X axis at (100, 0).
        // Initial angle = atan2(0, 100) = 0°.
        state.process(1, pt(0.0, 0.0), TouchPhase::Started);
        state.process(2, pt(100.0, 0.0), TouchPhase::Started);

        // Move finger 2 far enough to trigger gesture.
        state.process(2, pt(120.0, 0.0), TouchPhase::Moved);
        assert!(matches!(state.gesture_state, GestureRecognitionState::Pinching { .. }));

        // Rotate ~45° clockwise: move finger 2 from (120, 0) to roughly
        // (70.7, 70.7) which is at 45° from origin.
        // atan2(70.7, 70.7) ≈ 45°. Delta from re-snapshotted 0° = +45°.
        // Slint convention: positive = clockwise → delta ≈ +45°.
        let evs = state.process(2, pt(70.7, 70.7), TouchPhase::Moved);
        let classified = classify(&evs);
        assert_eq!(classified.len(), 2);
        if let Ev::RotationMoved(delta) = classified[1] {
            assert!((delta - 45.0).abs() < 1.0, "expected ~45.0 (clockwise), got {}", delta);
        } else {
            panic!("expected RotationMoved, got {:?}", classified[1]);
        }
    }

    #[test]
    fn rotation_across_180_degree_boundary() {
        let mut state = TouchState::default();

        // Finger 1 at origin, finger 2 at (-100, -10).
        // angle = atan2(-10, -100) ≈ -174.3°.
        state.process(1, pt(0.0, 0.0), TouchPhase::Started);
        state.process(2, pt(-100.0, -10.0), TouchPhase::Started);

        // Trigger gesture by moving far enough.
        state.process(2, pt(-120.0, -10.0), TouchPhase::Moved);
        assert!(matches!(state.gesture_state, GestureRecognitionState::Pinching { .. }));

        // Rotate across the ±180° boundary: move finger 2 to (-100, 10).
        // New angle = atan2(10, -100) ≈ 174.3°.
        // Raw angular change crosses ±180°, but per-frame delta should be
        // small (~11.4° which is 2 * 5.7°), NOT a ~349° jump.
        let evs = state.process(2, pt(-100.0, 10.0), TouchPhase::Moved);
        let classified = classify(&evs);
        if let Ev::RotationMoved(delta) = classified[1] {
            assert!(
                delta.abs() < 20.0,
                "rotation should be a small delta (~11°), got {} (discontinuity!)",
                delta
            );
        } else {
            panic!("expected RotationMoved, got {:?}", classified[1]);
        }
    }

    // -----------------------------------------------------------------------
    // TouchState: gesture end transitions
    // -----------------------------------------------------------------------

    #[test]
    fn pinch_end_with_remaining_finger() {
        let mut state = TouchState::default();

        state.process(1, pt(0.0, 0.0), TouchPhase::Started);
        state.process(2, pt(100.0, 0.0), TouchPhase::Started);
        // Trigger pinch.
        state.process(2, pt(120.0, 0.0), TouchPhase::Moved);

        // Lift finger 2 → gesture ends, finger 1 gets re-pressed.
        let evs = state.process(2, pt(120.0, 0.0), TouchPhase::Ended);
        let classified = classify(&evs);
        assert_eq!(classified, vec![Ev::PinchEnded, Ev::RotationEnded, Ev::Pressed(0.0, 0.0)]);
        assert!(matches!(state.gesture_state, GestureRecognitionState::Idle));
        assert_eq!(state.primary_touch_id, Some(1));
    }

    #[test]
    fn pinch_cancel_emits_cancelled_and_exit() {
        let mut state = TouchState::default();

        state.process(1, pt(0.0, 0.0), TouchPhase::Started);
        state.process(2, pt(100.0, 0.0), TouchPhase::Started);
        state.process(2, pt(120.0, 0.0), TouchPhase::Moved);

        // Cancel finger 2.
        let evs = state.process(2, pt(120.0, 0.0), TouchPhase::Cancelled);
        let classified = classify(&evs);
        assert_eq!(classified, vec![Ev::PinchCancelled, Ev::RotationCancelled, Ev::Exit]);
        assert!(state.primary_touch_id.is_none());
    }

    #[test]
    fn two_fingers_down_lift_before_threshold_returns_to_idle() {
        let mut state = TouchState::default();

        state.process(1, pt(100.0, 200.0), TouchPhase::Started);
        state.process(2, pt(200.0, 200.0), TouchPhase::Started);
        assert!(matches!(state.gesture_state, GestureRecognitionState::TwoFingersDown { .. }));

        // Lift finger 2 without exceeding movement threshold.
        let evs = state.process(2, pt(200.0, 200.0), TouchPhase::Ended);
        let classified = classify(&evs);
        // Remaining finger 1 gets re-pressed.
        assert_eq!(classified, vec![Ev::Pressed(100.0, 200.0)]);
        assert!(matches!(state.gesture_state, GestureRecognitionState::Idle));
        assert_eq!(state.primary_touch_id, Some(1));
    }

    #[test]
    fn two_fingers_down_cancel_both_emits_exit() {
        let mut state = TouchState::default();

        state.process(1, pt(100.0, 200.0), TouchPhase::Started);
        state.process(2, pt(200.0, 200.0), TouchPhase::Started);

        // Cancel finger 2 (gesture finger, no remaining → Exit).
        let evs = state.process(2, pt(200.0, 200.0), TouchPhase::Cancelled);
        assert_eq!(classify(&evs), vec![Ev::Exit]);

        // Cancel finger 1 (now in Idle, but not primary since cancel cleared it).
        let evs = state.process(1, pt(100.0, 200.0), TouchPhase::Cancelled);
        assert!(classify(&evs).is_empty());
    }

    // -----------------------------------------------------------------------
    // TouchState: 3+ fingers
    // -----------------------------------------------------------------------

    #[test]
    fn third_finger_ignored_for_gesture() {
        let mut state = TouchState::default();

        state.process(1, pt(0.0, 0.0), TouchPhase::Started);
        state.process(2, pt(100.0, 0.0), TouchPhase::Started);

        // Third finger: no additional events.
        let evs = state.process(3, pt(50.0, 50.0), TouchPhase::Started);
        assert!(classify(&evs).is_empty());
        assert_eq!(state.active_touches.len(), 3);
    }

    // -----------------------------------------------------------------------
    // Angle wrapping via Euclid
    // -----------------------------------------------------------------------

    #[test]
    fn euclid_angle_signed_wrapping() {
        use euclid::Angle;
        let wrap = |deg: f32| Angle::degrees(deg).signed().to_degrees();
        assert!(wrap(0.0).abs() < f32::EPSILON);
        assert!((wrap(180.0) - 180.0).abs() < 0.01);
        assert!((wrap(181.0) - (-179.0)).abs() < 0.01);
        assert!((wrap(-181.0) - 179.0).abs() < 0.01);
        assert!(wrap(360.0).abs() < 0.01);
    }

    #[test]
    fn zero_distance_fingers_no_division_by_zero() {
        let mut state = TouchState::default();

        // Two fingers at the exact same position → distance = 0.
        state.process(1, pt(100.0, 100.0), TouchPhase::Started);
        state.process(2, pt(100.0, 100.0), TouchPhase::Started);
        assert!(matches!(state.gesture_state, GestureRecognitionState::TwoFingersDown { .. }));

        // Move one finger far enough to trigger gesture.
        let evs = state.process(2, pt(120.0, 100.0), TouchPhase::Moved);
        assert!(matches!(state.gesture_state, GestureRecognitionState::Pinching { .. }));
        let classified = classify(&evs);
        assert_eq!(classified.len(), 2);
        assert_eq!(classified[0], Ev::PinchStarted);

        // Move further — scale should not be inf/NaN despite initial_distance
        // having been 0 (re-snapshotted to 20.0 at threshold crossing).
        let evs = state.process(2, pt(140.0, 100.0), TouchPhase::Moved);
        let classified = classify(&evs);
        if let Ev::PinchMoved(delta) = classified[0] {
            assert!(delta.is_finite(), "scale delta should be finite, got {}", delta);
        } else {
            panic!("expected PinchMoved, got {:?}", classified[0]);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    extern crate alloc;

    #[test]
    fn test_to_string() {
        let test_cases = [
            (
                "a",
                KeyboardModifiers { alt: false, control: true, shift: false, meta: false },
                false,
                false,
                "⌘A",
                "Ctrl+A",
                "Ctrl+A",
            ),
            (
                "a",
                KeyboardModifiers { alt: true, control: true, shift: true, meta: true },
                false,
                false,
                "⌃⌥⇧⌘A",
                "Win+Ctrl+Alt+Shift+A",
                "Super+Ctrl+Alt+Shift+A",
            ),
            (
                "\u{001b}",
                KeyboardModifiers { alt: false, control: true, shift: true, meta: false },
                false,
                false,
                "⇧⌘Escape",
                "Ctrl+Shift+Escape",
                "Ctrl+Shift+Escape",
            ),
            (
                "+",
                KeyboardModifiers { alt: false, control: true, shift: false, meta: false },
                true,
                false,
                "⌘+",
                "Ctrl++",
                "Ctrl++",
            ),
            (
                "a",
                KeyboardModifiers { alt: true, control: true, shift: false, meta: false },
                false,
                true,
                "⌘A",
                "Ctrl+A",
                "Ctrl+A",
            ),
            (
                "",
                KeyboardModifiers { alt: false, control: true, shift: false, meta: false },
                false,
                false,
                "",
                "",
                "",
            ),
            (
                "\u{000a}",
                KeyboardModifiers { alt: false, control: false, shift: false, meta: false },
                false,
                false,
                "Return",
                "Return",
                "Return",
            ),
            (
                "\u{0009}",
                KeyboardModifiers { alt: false, control: false, shift: false, meta: false },
                false,
                false,
                "Tab",
                "Tab",
                "Tab",
            ),
            (
                "\u{0020}",
                KeyboardModifiers { alt: false, control: false, shift: false, meta: false },
                false,
                false,
                "Space",
                "Space",
                "Space",
            ),
            (
                "\u{0008}",
                KeyboardModifiers { alt: false, control: false, shift: false, meta: false },
                false,
                false,
                "Backspace",
                "Backspace",
                "Backspace",
            ),
        ];

        for (
            key,
            modifiers,
            ignore_shift,
            ignore_alt,
            _expected_macos,
            _expected_windows,
            _expected_linux,
        ) in test_cases
        {
            let shortcut = make_keys(key.into(), modifiers, ignore_shift, ignore_alt);

            use crate::alloc::string::ToString;
            let result = shortcut.to_string();

            #[cfg(target_os = "macos")]
            assert_eq!(result.as_str(), _expected_macos, "Failed for key: {:?}", key);

            #[cfg(target_os = "windows")]
            assert_eq!(result.as_str(), _expected_windows, "Failed for key: {:?}", key);

            #[cfg(not(any(target_os = "macos", target_os = "windows")))]
            assert_eq!(result.as_str(), _expected_linux, "Failed for key: {:?}", key);
        }
    }
}