martensite-window 0.5.0

Winit multi-window management, fractional DPI scaling, and decoupled VSync.
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
//! Event routing pipeline: normalized pointer events, pointer capture, hover
//! tracking, and winit event conversion.
//!
//! The [`EventRouter`] is the central object that decides *which widget*
//! receives a given input event. It combines three concerns:
//!
//! - **Pointer capture** ([`PointerCapture`]): when a widget grabs the pointer
//!   (e.g. during a drag), every subsequent pointer event is routed to that
//!   widget regardless of where the pointer actually is on screen.
//! - **Hover/mouse tracking** ([`MouseTracker`]): per-window last-known pointer
//!   position and the widget currently hovered, used for scroll routing and
//!   hover highlighting.
//! - **Hit-testing** (delegated to [`HitTester`]): when no capture is active,
//!   the widget beneath the pointer is resolved with the two-stage hit-tester
//!   from the [`crate::hit_test`] module.
//!
//! # Winit adaptation note
//!
//! The winit version pinned by the workspace (`0.31.0-beta.3`) unified mouse,
//! touch, and tablet input under the `WindowEvent::PointerMoved` /
//! `WindowEvent::PointerButton` variants. The older `CursorMoved`, `MouseInput`,
//! `Touch`, and `TouchpadPressure` variants no longer exist. Accordingly,
//! [`convert_window_event`] handles `PointerMoved` and `PointerButton` — which
//! cover mouse, touch (via [`PointerSource::Touch`]), and tablet sources — and
//! normalizes them into a single [`PointerEvent`].
//!
//! [`PointerSource::Touch`]: winit::event::PointerSource::Touch
//! [`HitTester`]: crate::hit_test::HitTester

use std::collections::HashMap;

use glam::Vec2;
use martensite_core::{WidgetArena, WidgetId};

use crate::dpi::DpiScale;
use crate::hit_test::HitTester;
use crate::WindowEvent;
use crate::WindowId;

bitflags::bitflags! {
    /// Bitfield tracking which keyboard modifier keys are currently active.
    ///
    /// This is a compact `u8` bitfield with one bit per logical modifier group
    /// (`Shift`, `Control`, `Alt`, and `Command`/`Super`/`Meta`). It is
    /// intentionally coarser than winit's per-side [`ModifiersKeys`] — event
    /// handlers rarely need to distinguish left vs. right shift, and the
    /// combined form keeps the normalized [`PointerEvent`] small and cheap to
    /// copy.
    ///
    /// [`ModifiersKeys`]: winit::keyboard::ModifiersKeys
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_window::event::ModifierKeys;
    ///
    /// let mut mods = ModifierKeys::SHIFT | ModifierKeys::CONTROL;
    /// assert!(mods.contains(ModifierKeys::SHIFT));
    /// assert!(mods.contains(ModifierKeys::CONTROL));
    /// assert!(!mods.contains(ModifierKeys::ALT));
    /// mods.remove(ModifierKeys::SHIFT);
    /// assert!(!mods.contains(ModifierKeys::SHIFT));
    /// ```
    #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
    pub struct ModifierKeys: u8 {
        /// The `Shift` key (either side).
        const SHIFT = 1 << 0;
        /// The `Control` key (either side).
        const CONTROL = 1 << 1;
        /// The `Alt` / `Option` key (either side).
        const ALT = 1 << 2;
        /// The `Command` (macOS) / `Super` / `Meta` / `Windows` key (either side).
        const COMMAND = 1 << 3;
    }
}

/// Identifier for an individual pointer (mouse or touch finger).
///
/// For mouse input a single primary pointer ([`PointerId::PRIMARY`]) is used.
/// For multi-touch, each finger is assigned a distinct id derived from winit's
/// [`FingerId`], so concurrent touches can be tracked independently.
///
/// [`FingerId`]: winit::event::FingerId
///
/// # Examples
///
/// ```
/// use martensite_window::event::PointerId;
///
/// let primary = PointerId::PRIMARY;
/// let finger = PointerId::new(3);
/// assert_ne!(primary, finger);
/// assert_eq!(finger.get(), 3);
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct PointerId(u32);

impl PointerId {
    /// The primary pointer id, used for mouse input and any single-pointer
    /// source that does not carry a distinct identifier.
    pub const PRIMARY: Self = Self::new(0);

    /// Creates a new pointer id from a raw `u32`.
    pub const fn new(id: u32) -> Self {
        Self(id)
    }

    /// Returns the raw `u32` value of this pointer id.
    pub const fn get(self) -> u32 {
        self.0
    }
}

/// The state of a pointer device in a [`PointerEvent`].
///
/// `Moved` events carry no button information (`button` is `None`); `Pressed`
/// and `Released` events carry the button whose state changed.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum PointerState {
    /// A pointer button was pressed.
    Pressed,
    /// A pointer button was released.
    Released,
    /// The pointer moved without a button state change.
    Moved,
}

/// A normalized mouse button, independent of winit.
///
/// This mirrors the common subset of [`winit::event::MouseButton`] while
/// collapsing the extended numbered buttons (`Button6`..`Button32`) into a
/// single [`MouseButton::Other`] variant carrying the 1-based button index.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum MouseButton {
    /// The primary (usually left) button.
    Left,
    /// The secondary (usually right) button.
    Right,
    /// The tertiary (usually middle) button.
    Middle,
    /// The first side button, frequently assigned a back function.
    Back,
    /// The second side button, frequently assigned a forward function.
    Forward,
    /// Any further numbered button, carrying its 1-based index.
    Other(u8),
}

/// A normalized pointer event, independent of winit.
///
/// All positions are in **logical** coordinates (already divided by the
/// window's DPI scale factor). The event is `Copy` so it can be passed around
/// cheaply during dispatch.
///
/// # Examples
///
/// ```
/// use martensite_window::event::{ModifierKeys, MouseButton, PointerEvent, PointerId, PointerState};
/// use glam::Vec2;
///
/// let event = PointerEvent {
///     pointer_id: PointerId::PRIMARY,
///     position: Vec2::new(42.0, 17.0),
///     state: PointerState::Pressed,
///     button: Some(MouseButton::Left),
///     modifiers: ModifierKeys::SHIFT,
/// };
/// assert_eq!(event.position, Vec2::new(42.0, 17.0));
/// assert_eq!(event.state, PointerState::Pressed);
/// ```
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct PointerEvent {
    /// The pointer (mouse or touch finger) this event belongs to.
    pub pointer_id: PointerId,
    /// The pointer position in logical coordinates.
    pub position: Vec2,
    /// Whether a button was pressed, released, or the pointer merely moved.
    pub state: PointerState,
    /// The button whose state changed, if any. `None` for `Moved` events.
    pub button: Option<MouseButton>,
    /// The keyboard modifier keys active at the time of the event.
    pub modifiers: ModifierKeys,
}

/// Tracks which widgets have captured pointer input, per pointer.
///
/// While a capture is active for a given pointer, [`EventRouter`] routes *all*
/// events for that pointer to the captured widget regardless of the pointer's
/// on-screen position. This is the mechanism behind drag operations, slider
/// grabs, and text selection that follows the pointer outside the originating
/// widget.
///
/// Each pointer ([`PointerId`]) is captured independently, so multi-touch
/// interactions can capture different fingers to different widgets at the same
/// time.
///
/// # Examples
///
/// ```
/// use martensite_core::WidgetId;
/// use martensite_window::event::{PointerCapture, PointerId};
///
/// let mut cap = PointerCapture::new();
/// assert!(cap.captured_primary().is_none());
///
/// // `WidgetId::from_parts` is used here only to fabricate a handle for the
/// // example; real code obtains ids from the arena.
/// let widget = WidgetId::from_parts(1, 1);
/// cap.capture_primary(widget);
/// assert_eq!(cap.captured_primary(), Some(widget));
///
/// cap.release_primary();
/// assert!(cap.captured_primary().is_none());
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PointerCapture {
    /// The widget currently holding the capture for each pointer, keyed by
    /// pointer id.
    targets: HashMap<PointerId, WidgetId>,
}

impl PointerCapture {
    /// Creates a new, empty pointer capture (no pointers captured).
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Captures all subsequent events for `pointer_id` to `widget_id`.
    ///
    /// Once captured, every event for that pointer is routed to `widget_id`
    /// until [`PointerCapture::release`] is called for the same pointer.
    pub fn capture(&mut self, pointer_id: PointerId, widget_id: WidgetId) {
        self.targets.insert(pointer_id, widget_id);
    }

    /// Captures all subsequent events for the primary pointer
    /// ([`PointerId::PRIMARY`]) to `widget_id`.
    ///
    /// Convenience delegate for [`PointerCapture::capture`].
    pub fn capture_primary(&mut self, widget_id: WidgetId) {
        self.capture(PointerId::PRIMARY, widget_id);
    }

    /// Releases the capture for `pointer_id`, if any.
    pub fn release(&mut self, pointer_id: PointerId) {
        self.targets.remove(&pointer_id);
    }

    /// Releases the capture for the primary pointer, if any.
    ///
    /// Convenience delegate for [`PointerCapture::release`].
    pub fn release_primary(&mut self) {
        self.release(PointerId::PRIMARY);
    }

    /// Returns the widget currently holding the capture for `pointer_id`, or
    /// `None` if that pointer is not captured.
    #[must_use]
    pub fn captured(&self, pointer_id: PointerId) -> Option<WidgetId> {
        self.targets.get(&pointer_id).copied()
    }

    /// Returns the widget currently holding the capture for the primary
    /// pointer, or `None`.
    ///
    /// Convenience delegate for [`PointerCapture::captured`].
    #[must_use]
    pub fn captured_primary(&self) -> Option<WidgetId> {
        self.captured(PointerId::PRIMARY)
    }

    /// Releases all active captures for every pointer.
    pub fn clear(&mut self) {
        self.targets.clear();
    }

    /// Returns the number of pointers currently captured.
    #[must_use]
    pub fn active_captures(&self) -> usize {
        self.targets.len()
    }
}

/// Tracks mouse position and hover state per window.
///
/// The tracker is keyed by [`WindowId`] so that a single instance can serve a
/// multi-window application. It records the last-known logical pointer
/// position and the widget currently considered hovered for each window.
///
/// # Examples
///
/// ```
/// use martensite_core::WidgetId;
/// use martensite_window::event::MouseTracker;
/// use martensite_window::WindowId;
/// use glam::Vec2;
///
/// let mut tracker = MouseTracker::new();
/// let win = WindowId::from_raw(7);
/// tracker.update_position(win, Vec2::new(10.0, 20.0));
/// assert_eq!(tracker.position(win), Some(Vec2::new(10.0, 20.0)));
///
/// let widget = WidgetId::from_parts(1, 1);
/// tracker.set_hovered(win, Some(widget));
/// assert_eq!(tracker.hovered_widget(win), Some(widget));
///
/// tracker.set_hovered(win, None);
/// assert_eq!(tracker.hovered_widget(win), None);
/// ```
#[derive(Debug, Default)]
pub struct MouseTracker {
    /// Last-known logical pointer position per window.
    positions: HashMap<WindowId, Vec2>,
    /// Currently hovered widget per window.
    hovered: HashMap<WindowId, WidgetId>,
}

impl MouseTracker {
    /// Creates a new, empty mouse tracker.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Records the latest pointer `pos` (logical coordinates) for `window_id`.
    pub fn update_position(&mut self, window_id: WindowId, pos: Vec2) {
        self.positions.insert(window_id, pos);
    }

    /// Returns the last-known pointer position for `window_id`, or `None` if
    /// no position has been recorded for that window.
    #[must_use]
    pub fn position(&self, window_id: WindowId) -> Option<Vec2> {
        self.positions.get(&window_id).copied()
    }

    /// Returns the widget currently hovered in `window_id`, or `None`.
    #[must_use]
    pub fn hovered_widget(&self, window_id: WindowId) -> Option<WidgetId> {
        self.hovered.get(&window_id).copied()
    }

    /// Sets or clears the hovered widget for `window_id`. Passing `None`
    /// clears any previously recorded hover state for that window.
    pub fn set_hovered(&mut self, window_id: WindowId, widget_id: Option<WidgetId>) {
        match widget_id {
            Some(id) => {
                self.hovered.insert(window_id, id);
            }
            None => {
                self.hovered.remove(&window_id);
            }
        }
    }

    /// Forgets all tracked state for `window_id` (position and hover).
    ///
    /// Should be called when a window is destroyed to avoid retaining stale
    /// entries.
    pub fn clear_window(&mut self, window_id: WindowId) {
        self.positions.remove(&window_id);
        self.hovered.remove(&window_id);
    }

    /// Returns the number of windows for which a position is currently tracked.
    #[must_use]
    pub fn tracked_window_count(&self) -> usize {
        self.positions.len()
    }
}

/// The outcome of dispatching an event to a widget.
///
/// Callers can use this to decide whether to keep bubbling an event, mark it
/// as consumed, or treat it as ignored (no target found).
///
/// - [`EventDispatchOutcome::Handled`] — a target widget was resolved and the
///   event was routed to it.
/// - [`EventDispatchOutcome::Unhandled`] — no target was found (e.g. the
///   pointer missed every widget, or no widget is hovered for a scroll).
/// - [`EventDispatchOutcome::Ignored`] — the event had no applicable target
///   (e.g. a keyboard event with no focused widget).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum EventDispatchOutcome {
    /// The event was handled by the given widget.
    Handled(WidgetId),
    /// No target widget was found for the event.
    Unhandled,
    /// The event had no applicable target and was ignored entirely.
    Ignored,
}

/// The main event routing pipeline.
///
/// An [`EventRouter`] owns a [`PointerCapture`] and a [`MouseTracker`] and
/// exposes the three routing entry points required by the v0.5.0 milestone:
///
/// - [`EventRouter::route_pointer_event`] — routes a normalized [`PointerEvent`]
///   to the captured widget (if any) or to the hit-tested widget under the
///   pointer.
/// - [`EventRouter::route_keyboard_event`] — routes to the currently focused
///   widget.
/// - [`EventRouter::route_scroll_event`] — routes a scroll to the widget under
///   the scroll position (the hovered widget for that window's tree).
///
/// # Examples
///
/// ```
/// use martensite_core::{ColdNode, HotNode, NodeFlags, Rect, WidgetArena};
/// use martensite_window::event::{
///     EventDispatchOutcome, EventRouter, ModifierKeys, MouseButton, PointerEvent, PointerId,
///     PointerState,
/// };
/// use martensite_window::WindowId;
/// use glam::Vec2;
///
/// let mut arena = WidgetArena::new();
/// let root = arena.insert(
///     HotNode {
///         bounds: Rect::new(0.0, 0.0, 100.0, 100.0),
///         flags: NodeFlags::VISIBLE | NodeFlags::HIT_TEST_ENABLED,
///         ..HotNode::default()
///     },
///     ColdNode::default(),
/// );
///
/// let mut router = EventRouter::new();
/// let win = WindowId::from_raw(1);
/// let event = PointerEvent {
///     pointer_id: PointerId::PRIMARY,
///     position: Vec2::new(50.0, 50.0),
///     state: PointerState::Moved,
///     button: None,
///     modifiers: ModifierKeys::empty(),
/// };
/// assert_eq!(
///     router.route_pointer_event(&arena, root, win, &event),
///     EventDispatchOutcome::Handled(root)
/// );
/// ```
#[derive(Debug, Default)]
pub struct EventRouter {
    /// The active pointer capture, if any.
    capture: PointerCapture,
    /// Per-window mouse position and hover state.
    mouse: MouseTracker,
}

impl EventRouter {
    /// Creates a new, empty event router with no capture and no tracked
    /// mouse state.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns a shared reference to the underlying [`PointerCapture`].
    #[must_use]
    pub fn pointer_capture(&self) -> &PointerCapture {
        &self.capture
    }

    /// Returns a mutable reference to the underlying [`PointerCapture`].
    pub fn pointer_capture_mut(&mut self) -> &mut PointerCapture {
        &mut self.capture
    }

    /// Returns a shared reference to the underlying [`MouseTracker`].
    #[must_use]
    pub fn mouse_tracker(&self) -> &MouseTracker {
        &self.mouse
    }

    /// Returns a mutable reference to the underlying [`MouseTracker`].
    pub fn mouse_tracker_mut(&mut self) -> &mut MouseTracker {
        &mut self.mouse
    }

    /// Captures all subsequent events for `pointer_id` to `widget_id`.
    ///
    /// Convenience delegate for [`PointerCapture::capture`].
    pub fn capture_pointer(&mut self, pointer_id: PointerId, widget_id: WidgetId) {
        self.capture.capture(pointer_id, widget_id);
    }

    /// Captures all subsequent events for the primary pointer to `widget_id`.
    ///
    /// Convenience delegate for [`PointerCapture::capture_primary`].
    pub fn capture_pointer_primary(&mut self, widget_id: WidgetId) {
        self.capture.capture_primary(widget_id);
    }

    /// Releases the capture for `pointer_id`, if any.
    ///
    /// Convenience delegate for [`PointerCapture::release`].
    pub fn release_pointer(&mut self, pointer_id: PointerId) {
        self.capture.release(pointer_id);
    }

    /// Releases the capture for the primary pointer, if any.
    ///
    /// Convenience delegate for [`PointerCapture::release_primary`].
    pub fn release_pointer_primary(&mut self) {
        self.capture.release_primary();
    }

    /// Returns the widget currently holding the capture for `pointer_id`, or
    /// `None`.
    ///
    /// Convenience delegate for [`PointerCapture::captured`].
    #[must_use]
    pub fn captured_widget(&self, pointer_id: PointerId) -> Option<WidgetId> {
        self.capture.captured(pointer_id)
    }

    /// Returns the widget currently holding the capture for the primary
    /// pointer, or `None`.
    ///
    /// Convenience delegate for [`PointerCapture::captured_primary`].
    #[must_use]
    pub fn captured_widget_primary(&self) -> Option<WidgetId> {
        self.capture.captured_primary()
    }

    /// Routes a normalized pointer event to its target widget.
    ///
    /// Routing priority:
    ///
    /// 1. If a pointer capture is active for `event.pointer_id` and the
    ///    captured widget is still alive in `arena`, the event is routed to
    ///    that widget regardless of `event.position`. (A capture whose target
    ///    has since been removed from the arena is automatically released.)
    /// 2. Otherwise the event is routed to the front-most widget beneath
    ///    `event.position` via the two-stage [`HitTester`].
    ///
    /// The per-window [`MouseTracker`] is kept in sync: the pointer position is
    /// updated for `window_id`, and the resolved target (captured or
    /// hit-tested) is recorded as the hovered widget so subsequent scroll
    /// events route correctly.
    ///
    /// Returns [`EventDispatchOutcome::Handled`] when a target was found, or
    /// [`EventDispatchOutcome::Unhandled`] when the pointer missed every
    /// widget (or `root` is dead).
    pub fn route_pointer_event(
        &mut self,
        arena: &WidgetArena,
        root: WidgetId,
        window_id: WindowId,
        event: &PointerEvent,
    ) -> EventDispatchOutcome {
        // Keep the per-window mouse position in sync so callers that read the
        // tracker after routing see the latest position.
        self.mouse.update_position(window_id, event.position);

        let target = if let Some(captured) = self.capture.captured(event.pointer_id) {
            if arena.is_alive(captured) {
                Some(captured)
            } else {
                // The captured widget is gone — release the stale capture so
                // subsequent events resume normal hit-testing.
                self.capture.release(event.pointer_id);
                let tester = HitTester::new(arena);
                tester.hit_test(root, event.position).map(|r| r.widget_id)
            }
        } else {
            let tester = HitTester::new(arena);
            tester.hit_test(root, event.position).map(|r| r.widget_id)
        };

        // Record the resolved target as the hovered widget for this window so
        // scroll routing can reuse it without re-hit-testing.
        self.mouse.set_hovered(window_id, target);

        match target {
            Some(id) => EventDispatchOutcome::Handled(id),
            None => EventDispatchOutcome::Unhandled,
        }
    }

    /// Routes a keyboard event to the currently focused widget.
    ///
    /// The router itself does not track focus (that is the responsibility of
    /// the focus crate); this method simply wraps `focused` so the caller can
    /// chain dispatch uniformly.
    ///
    /// Returns [`EventDispatchOutcome::Handled`] when a widget is focused, or
    /// [`EventDispatchOutcome::Ignored`] when no widget is focused.
    pub fn route_keyboard_event(&mut self, focused: Option<WidgetId>) -> EventDispatchOutcome {
        match focused {
            Some(id) => EventDispatchOutcome::Handled(id),
            None => EventDispatchOutcome::Ignored,
        }
    }

    /// Routes a scroll event to the widget currently hovered in `window_id`.
    ///
    /// The widget under the scroll position is, by definition, the hovered
    /// widget for that window's tree — which [`MouseTracker`] keeps up to date
    /// as pointer events are routed through [`route_pointer_event`]. This
    /// method therefore reads the tracked hover state directly instead of
    /// re-hit-testing. The `delta` is accepted for API completeness and future
    /// dispatch logic but does not affect target selection.
    ///
    /// Returns [`EventDispatchOutcome::Handled`] when a hovered widget exists,
    /// or [`EventDispatchOutcome::Unhandled`] when no widget is hovered (e.g.
    /// the pointer is outside every widget or no pointer event has been routed
    /// for this window yet).
    ///
    /// [`route_pointer_event`]: EventRouter::route_pointer_event
    pub fn route_scroll_event(&mut self, window_id: WindowId, delta: Vec2) -> EventDispatchOutcome {
        // `delta` is part of the routing contract but does not change *which*
        // widget receives the scroll; acknowledge it to avoid an unused
        // variable warning.
        let _ = delta;
        match self.mouse.hovered_widget(window_id) {
            Some(id) => EventDispatchOutcome::Handled(id),
            None => EventDispatchOutcome::Unhandled,
        }
    }
}

// ---------------------------------------------------------------------------
// Winit event conversion
// ---------------------------------------------------------------------------

/// Converts a winit [`MouseButton`] into the normalized [`MouseButton`].
///
/// The five named buttons map directly; all numbered buttons (`Button6`..
/// `Button32`) collapse into [`MouseButton::Other`] carrying their 1-based
/// index.
///
/// # Examples
///
/// ```
/// use martensite_window::event::{convert_mouse_button, MouseButton};
///
/// assert_eq!(convert_mouse_button(winit::event::MouseButton::Left), MouseButton::Left);
/// assert_eq!(convert_mouse_button(winit::event::MouseButton::Right), MouseButton::Right);
/// assert_eq!(convert_mouse_button(winit::event::MouseButton::Middle), MouseButton::Middle);
/// ```
#[must_use]
pub fn convert_mouse_button(button: winit::event::MouseButton) -> MouseButton {
    match button {
        winit::event::MouseButton::Left => MouseButton::Left,
        winit::event::MouseButton::Right => MouseButton::Right,
        winit::event::MouseButton::Middle => MouseButton::Middle,
        winit::event::MouseButton::Back => MouseButton::Back,
        winit::event::MouseButton::Forward => MouseButton::Forward,
        // The remaining variants are the numbered `Button6`..`Button32`. They
        // are `#[repr(u8)]` with values 5..=31, so casting to `u8` yields the
        // 0-based index; add 1 to make it 1-based as documented.
        _ => MouseButton::Other(button as u8 + 1),
    }
}

/// Converts winit's combined modifier state into the normalized
/// [`ModifierKeys`].
///
/// This accepts the [`Modifiers`] value carried by
/// [`WindowEvent::ModifiersChanged`] and extracts the four logical modifier
/// groups (Shift, Control, Alt, Meta/Command). Per-side distinctions (left vs.
/// right) are intentionally collapsed.
///
/// [`WindowEvent::ModifiersChanged`]: winit::event::WindowEvent::ModifiersChanged
/// [`Modifiers`]: winit::event::Modifiers
///
/// # Examples
///
/// ```
/// use martensite_window::event::{convert_modifiers, ModifierKeys};
/// use winit::event::Modifiers;
/// use winit::keyboard::ModifiersState;
///
/// let mods = Modifiers::new(ModifiersState::SHIFT | ModifiersState::CONTROL, winit::keyboard::ModifiersKeys::empty());
/// let keys = convert_modifiers(&mods);
/// assert!(keys.contains(ModifierKeys::SHIFT));
/// assert!(keys.contains(ModifierKeys::CONTROL));
/// assert!(!keys.contains(ModifierKeys::ALT));
/// ```
#[must_use]
pub fn convert_modifiers(modifiers: &winit::event::Modifiers) -> ModifierKeys {
    convert_modifiers_state(&modifiers.state())
}

/// Converts winit's [`ModifiersState`] bitflags into the normalized
/// [`ModifierKeys`].
///
/// This is the lower-level helper used by [`convert_modifiers`]; it is exposed
/// for callers that track a [`ModifiersState`] directly rather than a full
/// [`Modifiers`] value.
///
/// [`ModifiersState`]: winit::keyboard::ModifiersState
/// [`Modifiers`]: winit::event::Modifiers
#[must_use]
pub fn convert_modifiers_state(state: &winit::keyboard::ModifiersState) -> ModifierKeys {
    let mut keys = ModifierKeys::empty();
    if state.shift_key() {
        keys |= ModifierKeys::SHIFT;
    }
    if state.control_key() {
        keys |= ModifierKeys::CONTROL;
    }
    if state.alt_key() {
        keys |= ModifierKeys::ALT;
    }
    if state.meta_key() {
        keys |= ModifierKeys::COMMAND;
    }
    keys
}

/// Converts a winit [`WindowEvent`] into a normalized [`PointerEvent`].
///
/// The following variants produce a [`PointerEvent`]:
///
/// - [`WindowEvent::PointerMoved`] — becomes a [`PointerState::Moved`] event
///   with `button = None`. Mouse, touch, and tablet sources are all handled.
/// - [`WindowEvent::PointerButton`] — becomes a [`PointerState::Pressed`] or
///   [`PointerState::Released`] event carrying the affected button.
///
/// All other variants return `None`.
///
/// Physical coordinates from winit are converted to logical coordinates using
/// `scale`. The `modifiers` field of the returned event is left empty because
/// winit delivers modifier changes through a separate
/// [`WindowEvent::ModifiersChanged`] event; callers should overlay the
/// currently-tracked modifier state (see [`convert_modifiers`]) when they need
/// it.
///
/// [`WindowEvent::PointerMoved`]: winit::event::WindowEvent::PointerMoved
/// [`WindowEvent::PointerButton`]: winit::event::WindowEvent::PointerButton
/// [`WindowEvent::ModifiersChanged`]: winit::event::WindowEvent::ModifiersChanged
///
/// # Examples
///
/// ```
/// use martensite_window::dpi::DpiScale;
/// use martensite_window::event::{convert_window_event, PointerState};
/// use winit::dpi::PhysicalPosition;
/// use winit::event::{PointerSource, WindowEvent};
///
/// let scale = DpiScale::new(2.0);
/// let event = WindowEvent::PointerMoved {
///     device_id: None,
///     position: PhysicalPosition::new(100.0, 200.0),
///     primary: true,
///     source: PointerSource::Mouse,
/// };
/// let pe = convert_window_event(&event, &scale).expect("pointer moved converts");
/// assert_eq!(pe.state, PointerState::Moved);
/// // 100 physical / 2.0 scale = 50 logical.
/// assert_eq!(pe.position, glam::Vec2::new(50.0, 100.0));
/// ```
#[must_use]
pub fn convert_window_event(event: &WindowEvent, scale: &DpiScale) -> Option<PointerEvent> {
    use winit::event::{ElementState, WindowEvent};

    match event {
        WindowEvent::PointerMoved {
            position, source, ..
        } => {
            let pos = physical_to_logical(*position, scale);
            Some(PointerEvent {
                pointer_id: pointer_id_from_source(source),
                position: pos,
                state: PointerState::Moved,
                button: None,
                modifiers: ModifierKeys::empty(),
            })
        }
        WindowEvent::PointerButton {
            state,
            position,
            button,
            ..
        } => {
            let pos = physical_to_logical(*position, scale);
            let (pointer_id, mb) = button_source_info(button);
            let pointer_state = match state {
                ElementState::Pressed => PointerState::Pressed,
                ElementState::Released => PointerState::Released,
            };
            Some(PointerEvent {
                pointer_id,
                position: pos,
                state: pointer_state,
                button: mb,
                modifiers: ModifierKeys::empty(),
            })
        }
        _ => None,
    }
}

/// Converts a winit [`PhysicalPosition<f64>`] into a logical [`Vec2`] using
/// `scale`.
///
/// [`PhysicalPosition<f64>`]: winit::dpi::PhysicalPosition
fn physical_to_logical(position: winit::dpi::PhysicalPosition<f64>, scale: &DpiScale) -> Vec2 {
    Vec2::new(
        scale.to_logical(position.x) as f32,
        scale.to_logical(position.y) as f32,
    )
}

/// Derives a [`PointerId`] from a winit [`PointerSource`].
///
/// Mouse and tablet sources map to the primary pointer; touch sources carry a
/// distinct id per finger.
///
/// [`PointerSource`]: winit::event::PointerSource
fn pointer_id_from_source(source: &winit::event::PointerSource) -> PointerId {
    use winit::event::PointerSource;

    match source {
        PointerSource::Touch { finger_id, .. } => PointerId::new(finger_id.into_raw() as u32),
        // Mouse, tablet, and unknown sources share the primary pointer id.
        _ => PointerId::PRIMARY,
    }
}

/// Extracts the [`PointerId`] and normalized [`MouseButton`] from a winit
/// [`ButtonSource`].
///
/// Touch presses are reported as [`MouseButton::Left`] (the conventional
/// primary button for touch). Tablet buttons are mapped through their
/// standard mouse-button equivalents when available.
///
/// [`ButtonSource`]: winit::event::ButtonSource
fn button_source_info(button: &winit::event::ButtonSource) -> (PointerId, Option<MouseButton>) {
    use winit::event::{ButtonSource, TabletToolButton};

    match button {
        ButtonSource::Mouse(mouse) => (PointerId::PRIMARY, Some(convert_mouse_button(*mouse))),
        ButtonSource::Touch { finger_id, .. } => (
            PointerId::new(finger_id.into_raw() as u32),
            Some(MouseButton::Left),
        ),
        ButtonSource::TabletTool {
            button: tool_button,
            ..
        } => {
            let mb = match tool_button {
                TabletToolButton::Contact => Some(MouseButton::Left),
                TabletToolButton::Barrel => Some(MouseButton::Right),
                TabletToolButton::Other(raw) => match raw {
                    1 => Some(MouseButton::Middle),
                    3 => Some(MouseButton::Back),
                    4 => Some(MouseButton::Forward),
                    _ => Some(MouseButton::Other(*raw as u8)),
                },
            };
            (PointerId::PRIMARY, mb)
        }
        ButtonSource::Unknown(_) => (PointerId::PRIMARY, None),
        // `ButtonSource` is `#[non_exhaustive]`; future winit versions may
        // add sources. Route them to the primary pointer with no button.
        _ => (PointerId::PRIMARY, None),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use martensite_core::{ColdNode, HotNode, NodeFlags, Rect, WidgetArena};
    use winit::dpi::PhysicalPosition;
    use winit::event::{
        ButtonSource, ElementState, FingerId, Force, Modifiers, MouseButton as WinitMouseButton,
        PointerSource, WindowEvent,
    };
    use winit::keyboard::{ModifiersKeys, ModifiersState};

    /// Build a visible, hit-testable node with the given bounds.
    fn hot_node(x: f32, y: f32, w: f32, h: f32) -> HotNode {
        HotNode {
            bounds: Rect::new(x, y, w, h),
            flags: NodeFlags::VISIBLE | NodeFlags::HIT_TEST_ENABLED,
            ..HotNode::default()
        }
    }

    /// Insert a node and return its id.
    fn insert(arena: &mut WidgetArena, x: f32, y: f32, w: f32, h: f32) -> WidgetId {
        arena.insert(hot_node(x, y, w, h), ColdNode::default())
    }

    // -----------------------------------------------------------------
    // PointerCapture
    // -----------------------------------------------------------------

    #[test]
    fn pointer_capture_starts_empty() {
        let cap = PointerCapture::new();
        assert!(cap.captured_primary().is_none());
        assert_eq!(cap.active_captures(), 0);
    }

    #[test]
    fn pointer_capture_routes_all_events_to_captured_widget() {
        let mut arena = WidgetArena::new();
        let a = insert(&mut arena, 0.0, 0.0, 100.0, 100.0);
        let b = insert(&mut arena, 200.0, 0.0, 100.0, 100.0);

        let win = WindowId::from_raw(1);
        let mut router = EventRouter::new();
        router.capture_pointer_primary(a);

        // Event positioned over `b` should still route to captured `a`.
        let event = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(250.0, 50.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        assert_eq!(
            router.route_pointer_event(&arena, a, win, &event),
            EventDispatchOutcome::Handled(a)
        );
        // Root is `a`; capture overrides hit-test even when the point is over
        // a different subtree root `b`.
        assert_eq!(
            router.route_pointer_event(&arena, b, win, &event),
            EventDispatchOutcome::Handled(a)
        );
    }

    #[test]
    fn pointer_capture_release_resumes_hit_testing() {
        let mut arena = WidgetArena::new();
        let a = insert(&mut arena, 0.0, 0.0, 100.0, 100.0);
        let b = insert(&mut arena, 200.0, 0.0, 100.0, 100.0);

        let win = WindowId::from_raw(1);
        let mut router = EventRouter::new();
        router.capture_pointer_primary(a);

        let event = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(250.0, 50.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        assert_eq!(
            router.route_pointer_event(&arena, a, win, &event),
            EventDispatchOutcome::Handled(a)
        );

        router.release_pointer_primary();
        // Now routing should hit-test; point is over `b`.
        assert_eq!(
            router.route_pointer_event(&arena, b, win, &event),
            EventDispatchOutcome::Handled(b)
        );
    }

    #[test]
    fn pointer_capture_dead_widget_auto_releases() {
        let mut arena = WidgetArena::new();
        let a = insert(&mut arena, 0.0, 0.0, 100.0, 100.0);

        let win = WindowId::from_raw(1);
        let mut router = EventRouter::new();
        router.capture_pointer_primary(a);

        // Remove the captured widget from the arena.
        arena.remove(a);

        let event = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(50.0, 50.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        // No other live widget to hit; capture is stale and should release.
        assert_eq!(
            router.route_pointer_event(&arena, a, win, &event),
            EventDispatchOutcome::Unhandled
        );
        assert!(router.captured_widget_primary().is_none());
    }

    #[test]
    fn pointer_capture_default_is_empty() {
        let cap = PointerCapture::default();
        assert!(cap.captured_primary().is_none());
        assert_eq!(cap.active_captures(), 0);
    }

    #[test]
    fn pointer_capture_multi_pointer_independent() {
        let mut cap = PointerCapture::new();
        let widget_a = WidgetId::from_parts(1, 1);
        let widget_b = WidgetId::from_parts(2, 1);
        let finger_1 = PointerId::new(1);
        let finger_2 = PointerId::new(2);

        // Two different fingers captured to two different widgets.
        cap.capture(finger_1, widget_a);
        cap.capture(finger_2, widget_b);
        assert_eq!(cap.active_captures(), 2);
        assert_eq!(cap.captured(finger_1), Some(widget_a));
        assert_eq!(cap.captured(finger_2), Some(widget_b));

        // Releasing one finger does not affect the other.
        cap.release(finger_1);
        assert_eq!(cap.active_captures(), 1);
        assert!(cap.captured(finger_1).is_none());
        assert_eq!(cap.captured(finger_2), Some(widget_b));

        // `clear` releases every remaining capture.
        cap.clear();
        assert_eq!(cap.active_captures(), 0);
        assert!(cap.captured(finger_2).is_none());
    }

    // -----------------------------------------------------------------
    // MouseTracker
    // -----------------------------------------------------------------

    #[test]
    fn mouse_tracker_position_tracking_per_window() {
        let mut tracker = MouseTracker::new();
        let w1 = WindowId::from_raw(1);
        let w2 = WindowId::from_raw(2);

        assert_eq!(tracker.position(w1), None);
        tracker.update_position(w1, Vec2::new(10.0, 20.0));
        tracker.update_position(w2, Vec2::new(30.0, 40.0));

        assert_eq!(tracker.position(w1), Some(Vec2::new(10.0, 20.0)));
        assert_eq!(tracker.position(w2), Some(Vec2::new(30.0, 40.0)));

        // Updating one window does not affect the other.
        tracker.update_position(w1, Vec2::new(99.0, 99.0));
        assert_eq!(tracker.position(w1), Some(Vec2::new(99.0, 99.0)));
        assert_eq!(tracker.position(w2), Some(Vec2::new(30.0, 40.0)));
        assert_eq!(tracker.tracked_window_count(), 2);
    }

    #[test]
    fn mouse_tracker_hover_state_tracking() {
        let mut tracker = MouseTracker::new();
        let win = WindowId::from_raw(1);
        let widget = WidgetId::from_parts(1, 1);

        assert_eq!(tracker.hovered_widget(win), None);
        tracker.set_hovered(win, Some(widget));
        assert_eq!(tracker.hovered_widget(win), Some(widget));
        tracker.set_hovered(win, None);
        assert_eq!(tracker.hovered_widget(win), None);
    }

    #[test]
    fn mouse_tracker_hover_is_per_window() {
        let mut tracker = MouseTracker::new();
        let w1 = WindowId::from_raw(1);
        let w2 = WindowId::from_raw(2);
        let widget_a = WidgetId::from_parts(1, 1);
        let widget_b = WidgetId::from_parts(2, 1);

        tracker.set_hovered(w1, Some(widget_a));
        tracker.set_hovered(w2, Some(widget_b));
        assert_eq!(tracker.hovered_widget(w1), Some(widget_a));
        assert_eq!(tracker.hovered_widget(w2), Some(widget_b));
    }

    #[test]
    fn mouse_tracker_clear_window_removes_all_state() {
        let mut tracker = MouseTracker::new();
        let win = WindowId::from_raw(1);
        let widget = WidgetId::from_parts(1, 1);

        tracker.update_position(win, Vec2::new(5.0, 5.0));
        tracker.set_hovered(win, Some(widget));
        assert_eq!(tracker.tracked_window_count(), 1);

        tracker.clear_window(win);
        assert_eq!(tracker.position(win), None);
        assert_eq!(tracker.hovered_widget(win), None);
        assert_eq!(tracker.tracked_window_count(), 0);
    }

    // -----------------------------------------------------------------
    // EventRouter — hit-test routing
    // -----------------------------------------------------------------

    #[test]
    fn router_routes_to_correct_widget_by_position() {
        let mut arena = WidgetArena::new();
        let root = insert(&mut arena, 0.0, 0.0, 200.0, 200.0);
        let child = insert(&mut arena, 50.0, 50.0, 100.0, 100.0);
        arena.append_child(root, child).unwrap();

        let win = WindowId::from_raw(1);
        let mut router = EventRouter::new();

        // Point over child → child wins (topmost).
        let over_child = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(75.0, 75.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        assert_eq!(
            router.route_pointer_event(&arena, root, win, &over_child),
            EventDispatchOutcome::Handled(child)
        );

        // Point over root only → root wins.
        let over_root = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(10.0, 10.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        assert_eq!(
            router.route_pointer_event(&arena, root, win, &over_root),
            EventDispatchOutcome::Handled(root)
        );
    }

    #[test]
    fn router_captured_widget_takes_priority_over_hit_test() {
        let mut arena = WidgetArena::new();
        let root = insert(&mut arena, 0.0, 0.0, 200.0, 200.0);
        let child = insert(&mut arena, 50.0, 50.0, 100.0, 100.0);
        arena.append_child(root, child).unwrap();

        let win = WindowId::from_raw(1);
        let mut router = EventRouter::new();
        router.capture_pointer_primary(root);

        // Point is over child, but capture forces routing to root.
        let event = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(75.0, 75.0),
            state: PointerState::Pressed,
            button: Some(MouseButton::Left),
            modifiers: ModifierKeys::empty(),
        };
        assert_eq!(
            router.route_pointer_event(&arena, root, win, &event),
            EventDispatchOutcome::Handled(root)
        );
    }

    #[test]
    fn router_keyboard_event_routes_to_focused() {
        let mut router = EventRouter::new();
        let focused = WidgetId::from_parts(3, 1);
        assert_eq!(
            router.route_keyboard_event(Some(focused)),
            EventDispatchOutcome::Handled(focused)
        );
        assert_eq!(
            router.route_keyboard_event(None),
            EventDispatchOutcome::Ignored
        );
    }

    // -----------------------------------------------------------------
    // Scroll event routing
    // -----------------------------------------------------------------

    #[test]
    fn router_scroll_routes_to_hovered_widget() {
        let mut arena = WidgetArena::new();
        let root = insert(&mut arena, 0.0, 0.0, 200.0, 200.0);
        let child = insert(&mut arena, 50.0, 50.0, 100.0, 100.0);
        arena.append_child(root, child).unwrap();

        let win = WindowId::from_raw(1);
        let mut router = EventRouter::new();

        // Establish hover over the child by routing a pointer event first.
        let over_child = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(75.0, 75.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        router.route_pointer_event(&arena, root, win, &over_child);
        assert_eq!(
            router.route_scroll_event(win, Vec2::new(0.0, 10.0)),
            EventDispatchOutcome::Handled(child)
        );

        // Move the pointer over the root only and scroll again.
        let over_root = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(10.0, 10.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        router.route_pointer_event(&arena, root, win, &over_root);
        assert_eq!(
            router.route_scroll_event(win, Vec2::new(0.0, 10.0)),
            EventDispatchOutcome::Handled(root)
        );
    }

    #[test]
    fn router_scroll_unhandled_when_no_hover() {
        let mut router = EventRouter::new();
        let win = WindowId::from_raw(1);
        // No pointer event has been routed for this window, so nothing is
        // hovered and the scroll is unhandled.
        assert_eq!(
            router.route_scroll_event(win, Vec2::new(0.0, 1.0)),
            EventDispatchOutcome::Unhandled
        );
    }

    // -----------------------------------------------------------------
    // ModifierKeys
    // -----------------------------------------------------------------

    #[test]
    fn modifier_keys_all_combinations() {
        assert_eq!(ModifierKeys::empty(), ModifierKeys::empty());
        assert!(ModifierKeys::SHIFT.contains(ModifierKeys::SHIFT));
        assert!(!ModifierKeys::SHIFT.contains(ModifierKeys::CONTROL));

        let all =
            ModifierKeys::SHIFT | ModifierKeys::CONTROL | ModifierKeys::ALT | ModifierKeys::COMMAND;
        assert!(all.contains(ModifierKeys::SHIFT));
        assert!(all.contains(ModifierKeys::CONTROL));
        assert!(all.contains(ModifierKeys::ALT));
        assert!(all.contains(ModifierKeys::COMMAND));

        let shift_ctrl = ModifierKeys::SHIFT | ModifierKeys::CONTROL;
        assert_eq!(shift_ctrl, ModifierKeys::SHIFT | ModifierKeys::CONTROL);
        assert_ne!(shift_ctrl, ModifierKeys::SHIFT | ModifierKeys::ALT);

        // Removal.
        let mut m = shift_ctrl;
        m.remove(ModifierKeys::SHIFT);
        assert_eq!(m, ModifierKeys::CONTROL);
    }

    #[test]
    fn convert_modifiers_state_all_combinations() {
        let empty = convert_modifiers_state(&ModifiersState::empty());
        assert_eq!(empty, ModifierKeys::empty());

        let shift = convert_modifiers_state(&ModifiersState::SHIFT);
        assert_eq!(shift, ModifierKeys::SHIFT);

        let ctrl = convert_modifiers_state(&ModifiersState::CONTROL);
        assert_eq!(ctrl, ModifierKeys::CONTROL);

        let alt = convert_modifiers_state(&ModifiersState::ALT);
        assert_eq!(alt, ModifierKeys::ALT);

        let meta = convert_modifiers_state(&ModifiersState::META);
        assert_eq!(meta, ModifierKeys::COMMAND);

        let combo = convert_modifiers_state(&(ModifiersState::SHIFT | ModifiersState::CONTROL));
        assert_eq!(combo, ModifierKeys::SHIFT | ModifierKeys::CONTROL);

        let all = convert_modifiers_state(
            &(ModifiersState::SHIFT
                | ModifiersState::CONTROL
                | ModifiersState::ALT
                | ModifiersState::META),
        );
        assert_eq!(
            all,
            ModifierKeys::SHIFT | ModifierKeys::CONTROL | ModifierKeys::ALT | ModifierKeys::COMMAND
        );
    }

    #[test]
    fn convert_modifiers_from_modifiers_value() {
        let mods = Modifiers::new(
            ModifiersState::SHIFT | ModifiersState::ALT,
            ModifiersKeys::empty(),
        );
        assert_eq!(
            convert_modifiers(&mods),
            ModifierKeys::SHIFT | ModifierKeys::ALT
        );
    }

    // -----------------------------------------------------------------
    // Winit event conversion
    // -----------------------------------------------------------------

    #[test]
    fn convert_mouse_button_named() {
        assert_eq!(
            convert_mouse_button(WinitMouseButton::Left),
            MouseButton::Left
        );
        assert_eq!(
            convert_mouse_button(WinitMouseButton::Right),
            MouseButton::Right
        );
        assert_eq!(
            convert_mouse_button(WinitMouseButton::Middle),
            MouseButton::Middle
        );
        assert_eq!(
            convert_mouse_button(WinitMouseButton::Back),
            MouseButton::Back
        );
        assert_eq!(
            convert_mouse_button(WinitMouseButton::Forward),
            MouseButton::Forward
        );
    }

    #[test]
    fn convert_mouse_button_extended() {
        // Button6 is repr(u8) value 5 → Other(6) (1-based).
        assert_eq!(
            convert_mouse_button(WinitMouseButton::Button6),
            MouseButton::Other(6)
        );
        assert_eq!(
            convert_mouse_button(WinitMouseButton::Button32),
            MouseButton::Other(32)
        );
    }

    #[test]
    fn convert_window_event_pointer_moved_mouse() {
        let scale = DpiScale::new(2.0);
        let event = WindowEvent::PointerMoved {
            device_id: None,
            position: PhysicalPosition::new(100.0, 200.0),
            primary: true,
            source: PointerSource::Mouse,
        };
        let pe = convert_window_event(&event, &scale).expect("pointer moved converts");
        assert_eq!(pe.pointer_id, PointerId::PRIMARY);
        assert_eq!(pe.state, PointerState::Moved);
        assert_eq!(pe.button, None);
        assert_eq!(pe.position, Vec2::new(50.0, 100.0));
        assert_eq!(pe.modifiers, ModifierKeys::empty());
    }

    #[test]
    fn convert_window_event_pointer_moved_touch() {
        let scale = DpiScale::new(1.0);
        let event = WindowEvent::PointerMoved {
            device_id: None,
            position: PhysicalPosition::new(10.0, 20.0),
            primary: false,
            source: PointerSource::Touch {
                finger_id: FingerId::from_raw(3),
                force: Some(Force::Normalized(0.5)),
            },
        };
        let pe = convert_window_event(&event, &scale).expect("touch moved converts");
        assert_eq!(pe.pointer_id, PointerId::new(3));
        assert_eq!(pe.state, PointerState::Moved);
        assert_eq!(pe.position, Vec2::new(10.0, 20.0));
    }

    #[test]
    fn convert_window_event_pointer_button_pressed() {
        let scale = DpiScale::new(1.0);
        let event = WindowEvent::PointerButton {
            device_id: None,
            state: ElementState::Pressed,
            position: PhysicalPosition::new(42.0, 17.0),
            primary: true,
            button: ButtonSource::Mouse(WinitMouseButton::Left),
            is_macos_activation_click: false,
        };
        let pe = convert_window_event(&event, &scale).expect("pointer button converts");
        assert_eq!(pe.state, PointerState::Pressed);
        assert_eq!(pe.button, Some(MouseButton::Left));
        assert_eq!(pe.position, Vec2::new(42.0, 17.0));
        assert_eq!(pe.pointer_id, PointerId::PRIMARY);
    }

    #[test]
    fn convert_window_event_pointer_button_released() {
        let scale = DpiScale::new(1.0);
        let event = WindowEvent::PointerButton {
            device_id: None,
            state: ElementState::Released,
            position: PhysicalPosition::new(42.0, 17.0),
            primary: true,
            button: ButtonSource::Mouse(WinitMouseButton::Right),
            is_macos_activation_click: false,
        };
        let pe = convert_window_event(&event, &scale).expect("pointer button converts");
        assert_eq!(pe.state, PointerState::Released);
        assert_eq!(pe.button, Some(MouseButton::Right));
    }

    #[test]
    fn convert_window_event_pointer_button_touch() {
        let scale = DpiScale::new(1.0);
        let event = WindowEvent::PointerButton {
            device_id: None,
            state: ElementState::Pressed,
            position: PhysicalPosition::new(5.0, 5.0),
            primary: false,
            button: ButtonSource::Touch {
                finger_id: FingerId::from_raw(7),
                force: None,
            },
            is_macos_activation_click: false,
        };
        let pe = convert_window_event(&event, &scale).expect("touch button converts");
        assert_eq!(pe.pointer_id, PointerId::new(7));
        assert_eq!(pe.button, Some(MouseButton::Left));
        assert_eq!(pe.state, PointerState::Pressed);
    }

    #[test]
    fn convert_window_event_non_pointer_returns_none() {
        let scale = DpiScale::new(1.0);
        assert!(convert_window_event(&WindowEvent::CloseRequested, &scale).is_none());
        assert!(convert_window_event(&WindowEvent::Destroyed, &scale).is_none());
    }

    #[test]
    fn convert_window_event_scales_coordinates() {
        let scale = DpiScale::new(1.5);
        let event = WindowEvent::PointerMoved {
            device_id: None,
            position: PhysicalPosition::new(150.0, 300.0),
            primary: true,
            source: PointerSource::Mouse,
        };
        let pe = convert_window_event(&event, &scale).expect("converts");
        // 150 / 1.5 = 100; 300 / 1.5 = 200.
        assert_eq!(pe.position, Vec2::new(100.0, 200.0));
    }

    // -----------------------------------------------------------------
    // Multi-window
    // -----------------------------------------------------------------

    #[test]
    fn multi_window_events_routed_to_correct_window() {
        // Two independent arenas model two windows' widget trees. The router
        // is shared; the caller selects the root per window.
        let mut arena_a = WidgetArena::new();
        let root_a = insert(&mut arena_a, 0.0, 0.0, 100.0, 100.0);

        let mut arena_b = WidgetArena::new();
        let root_b = insert(&mut arena_b, 0.0, 0.0, 100.0, 100.0);

        let w1 = WindowId::from_raw(1);
        let w2 = WindowId::from_raw(2);
        let mut router = EventRouter::new();

        let event = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(50.0, 50.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };

        assert_eq!(
            router.route_pointer_event(&arena_a, root_a, w1, &event),
            EventDispatchOutcome::Handled(root_a)
        );
        assert_eq!(
            router.route_pointer_event(&arena_b, root_b, w2, &event),
            EventDispatchOutcome::Handled(root_b)
        );

        // `route_pointer_event` keeps the per-window mouse position in sync.
        assert_eq!(
            router.mouse_tracker().position(w1),
            Some(Vec2::new(50.0, 50.0))
        );
        assert_eq!(
            router.mouse_tracker().position(w2),
            Some(Vec2::new(50.0, 50.0))
        );

        // Mouse tracker keeps per-window state distinct when updated directly.
        router
            .mouse_tracker_mut()
            .update_position(w1, Vec2::new(1.0, 2.0));
        router
            .mouse_tracker_mut()
            .update_position(w2, Vec2::new(3.0, 4.0));
        assert_eq!(
            router.mouse_tracker().position(w1),
            Some(Vec2::new(1.0, 2.0))
        );
        assert_eq!(
            router.mouse_tracker().position(w2),
            Some(Vec2::new(3.0, 4.0))
        );
    }

    // -----------------------------------------------------------------
    // Edge cases
    // -----------------------------------------------------------------

    #[test]
    fn empty_arena_dead_root_returns_unhandled() {
        let arena = WidgetArena::new();
        let win = WindowId::from_raw(1);
        let mut router = EventRouter::new();
        let dead = WidgetId::from_parts(999, 1);
        let event = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(50.0, 50.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        assert_eq!(
            router.route_pointer_event(&arena, dead, win, &event),
            EventDispatchOutcome::Unhandled
        );
    }

    #[test]
    fn root_only_tree_hit_inside_and_outside() {
        let mut arena = WidgetArena::new();
        let root = insert(&mut arena, 0.0, 0.0, 100.0, 100.0);
        let win = WindowId::from_raw(1);
        let mut router = EventRouter::new();

        let inside = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(50.0, 50.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        assert_eq!(
            router.route_pointer_event(&arena, root, win, &inside),
            EventDispatchOutcome::Handled(root)
        );

        let outside = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(500.0, 500.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        assert_eq!(
            router.route_pointer_event(&arena, root, win, &outside),
            EventDispatchOutcome::Unhandled
        );
    }

    #[test]
    fn point_outside_all_widgets_returns_unhandled() {
        let mut arena = WidgetArena::new();
        let root = insert(&mut arena, 0.0, 0.0, 100.0, 100.0);
        let other = insert(&mut arena, 200.0, 200.0, 100.0, 100.0);
        arena.append_child(root, other).unwrap();

        let win = WindowId::from_raw(1);
        let mut router = EventRouter::new();
        let event = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(150.0, 150.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        assert_eq!(
            router.route_pointer_event(&arena, root, win, &event),
            EventDispatchOutcome::Unhandled
        );
    }

    #[test]
    fn route_pointer_event_updates_hovered_widget() {
        let mut arena = WidgetArena::new();
        let root = insert(&mut arena, 0.0, 0.0, 200.0, 200.0);
        let child = insert(&mut arena, 50.0, 50.0, 100.0, 100.0);
        arena.append_child(root, child).unwrap();

        let win = WindowId::from_raw(1);
        let mut router = EventRouter::new();

        let over_child = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(75.0, 75.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        router.route_pointer_event(&arena, root, win, &over_child);
        assert_eq!(router.mouse_tracker().hovered_widget(win), Some(child));

        // A miss clears the hovered widget for that window.
        let miss = PointerEvent {
            pointer_id: PointerId::PRIMARY,
            position: Vec2::new(500.0, 500.0),
            state: PointerState::Moved,
            button: None,
            modifiers: ModifierKeys::empty(),
        };
        router.route_pointer_event(&arena, root, win, &miss);
        assert_eq!(router.mouse_tracker().hovered_widget(win), None);
    }

    #[test]
    fn event_dispatch_outcome_variants_distinct() {
        let w = WidgetId::from_parts(1, 1);
        assert_ne!(
            EventDispatchOutcome::Handled(w),
            EventDispatchOutcome::Unhandled
        );
        assert_ne!(
            EventDispatchOutcome::Unhandled,
            EventDispatchOutcome::Ignored
        );
        assert_eq!(
            EventDispatchOutcome::Handled(w),
            EventDispatchOutcome::Handled(w)
        );
    }

    #[test]
    fn pointer_id_primary_is_zero() {
        assert_eq!(PointerId::PRIMARY, PointerId::new(0));
        assert_eq!(PointerId::PRIMARY.get(), 0);
    }
}