repose-core 0.31.24

Repose's core runtime, view model, signals, composition locals, and animation clock.
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
use std::any::Any;
use std::cell::RefCell;
use std::collections::HashSet;
use std::panic::Location;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};

use rustc_hash::{FxHashMap, FxHashSet};

use crate::effects::Dispose;
use crate::scope::Scope;
use crate::{CursorIcon, Rect, Scene, View, input::PhysicalKey, semantics::Role};

thread_local! {
    pub static COMPOSER: RefCell<Composer> = RefCell::new(Composer::default());
    static ROOT_SCOPE: RefCell<Option<Scope>> = const { RefCell::new(None) };
    static INITIALIZER_STACK: RefCell<Vec<InitializerKind>> =
        const { RefCell::new(Vec::new()) };
    static PENDING_INITIALIZER_CURSOR: RefCell<Option<usize>> =
        const { RefCell::new(None) };
    static KEYED_DISPOSERS: RefCell<FxHashMap<String, KeyedDisposerEntry>> =
        RefCell::new(FxHashMap::default());
    static KEYED_DISPOSER_ORDER: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
    static PENDING_KEYED_REGISTRATIONS: RefCell<Vec<(String, Dispose, String)>> =
        const { RefCell::new(Vec::new()) };

    /// Programmatic focus requests queued by `FocusRequester`. A queue (not a
    /// single slot) so multiple requests in one frame are honored in order
    /// instead of last-wins. `CLEAR_FOCUS_MARKER` entries clear focus.
    static FOCUS_REQUESTS: RefCell<std::collections::VecDeque<u64>> =
        const { RefCell::new(std::collections::VecDeque::new()) };

    /// Captured-focus lock (`FocusRequester::capture_focus`). While set,
    /// queued requests for other targets are denied and focus stays pinned.
    static FOCUS_CAPTURED: RefCell<Option<u64>> = const { RefCell::new(None) };
}

pub const CLEAR_FOCUS_MARKER: u64 = u64::MAX;

const ROOT_OWNER: &str = "\0repose:root-owner";

struct KeyedDisposerEntry {
    disposer: Dispose,
    owners: FxHashSet<String>,
}

enum InitializerKind {
    Sequential,
    Keyed,
}

pub(crate) fn scope_owner_token(scope: Option<&str>) -> String {
    match scope {
        Some(scope) if !scope.is_empty() => scope.to_string(),
        _ => ROOT_OWNER.to_string(),
    }
}

fn queue_keyed_registration(key: String, disposer: Dispose, owner: String) {
    let queued = PENDING_KEYED_REGISTRATIONS.try_with(|pending| {
        pending.try_borrow_mut().ok().map(|mut pending| {
            pending.push((key, disposer, owner));
            true
        })
    });
    if !matches!(queued, Ok(Some(true))) {
        crate::request_frame();
    }
}

pub(crate) fn flush_keyed_disposer_registrations() {
    let pending = PENDING_KEYED_REGISTRATIONS.try_with(|pending| {
        pending
            .try_borrow_mut()
            .ok()
            .map(|mut pending| std::mem::take(&mut *pending))
    });
    let Ok(Some(pending)) = pending else {
        crate::request_frame();
        return;
    };
    for (key, disposer, owner) in pending {
        register_keyed_disposer_for_owner(key, disposer, owner);
    }
}

pub(crate) fn register_keyed_disposer(key: String, disposer: Dispose) {
    let owner = scope_owner_token(crate::scope_cache::current_scope_key().as_deref());
    register_keyed_disposer_for_owner(key, disposer, owner);
}

pub(crate) fn register_keyed_disposer_for_owner(key: String, disposer: Dispose, owner: String) {
    let result = KEYED_DISPOSERS
        .try_with(|registry| {
            let mut registry = match registry.try_borrow_mut() {
                Ok(registry) => registry,
                Err(_) => return Err(()),
            };
            if let Some(entry) = registry.get_mut(&key) {
                if entry.owners.contains(&owner) && !entry.disposer.ptr_eq(&disposer) {
                    let previous = std::mem::replace(&mut entry.disposer, disposer.clone());
                    return Ok((false, Some(previous)));
                }
                entry.owners.insert(owner.clone());
                return Ok((false, None));
            }
            registry.insert(
                key.clone(),
                KeyedDisposerEntry {
                    disposer: disposer.clone(),
                    owners: FxHashSet::from_iter([owner.clone()]),
                },
            );
            Ok((true, None))
        })
        .ok();
    match result {
        Some(Ok((true, previous))) => {
            let _ = KEYED_DISPOSER_ORDER.try_with(|order| {
                if let Ok(mut order) = order.try_borrow_mut()
                    && !order.iter().any(|registered| registered == &key)
                {
                    order.push(key.clone());
                }
            });
            drop(previous);
        }
        Some(Ok((false, previous))) => {
            if let Some(previous) = previous {
                run_keyed_disposer(previous);
            }
        }
        Some(Err(())) | None => queue_keyed_registration(key, disposer, owner),
    }
}

pub(crate) fn keyed_disposer_has_owner(key: &str, disposer: &Dispose, owner: &str) -> bool {
    KEYED_DISPOSERS
        .try_with(|registry| {
            registry.try_borrow().ok().and_then(|registry| {
                registry
                    .get(key)
                    .filter(|entry| entry.disposer.ptr_eq(disposer))
                    .map(|entry| entry.owners.contains(owner))
            })
        })
        .ok()
        .flatten()
        .unwrap_or(false)
}

pub(crate) fn remove_keyed_disposer_for_owner(key: &str, disposer: &Dispose, owner: &str) -> bool {
    let mut to_run = None;
    let mut owner_removed = false;
    let mut registry_removed = false;
    let result = KEYED_DISPOSERS.try_with(|registry| {
        let mut registry = match registry.try_borrow_mut() {
            Ok(registry) => registry,
            Err(_) => return false,
        };
        let Some(entry) = registry.get_mut(key) else {
            return true;
        };
        if !entry.disposer.ptr_eq(disposer) {
            return true;
        }
        owner_removed = entry.owners.remove(owner);
        if entry.owners.is_empty()
            && let Some(entry) = registry.remove(key)
        {
            to_run = Some(entry.disposer);
            registry_removed = true;
        }
        true
    });
    if !matches!(result, Ok(true)) {
        queue_keyed_registration(key.to_string(), disposer.clone(), owner.to_string());
        return false;
    }
    if registry_removed {
        let _ = KEYED_DISPOSER_ORDER.try_with(|order| {
            if let Ok(mut order) = order.try_borrow_mut() {
                order.retain(|registered| registered != key);
            }
        });
    }
    if let Some(disposer) = to_run {
        run_keyed_disposer(disposer);
        true
    } else {
        owner_removed
    }
}

pub(crate) fn take_keyed_disposer(key: &str) -> Option<Dispose> {
    let disposer = KEYED_DISPOSERS
        .try_with(|registry| {
            registry
                .try_borrow_mut()
                .ok()?
                .remove(key)
                .map(|entry| entry.disposer)
        })
        .ok()
        .flatten();
    if disposer.is_some() {
        let _ = KEYED_DISPOSER_ORDER.try_with(|order| {
            if let Ok(mut order) = order.try_borrow_mut() {
                order.retain(|registered| registered != key);
            }
        });
    }
    disposer
}

pub(crate) fn take_all_keyed_disposers() -> Vec<Dispose> {
    flush_keyed_disposer_registrations();
    let order = KEYED_DISPOSER_ORDER
        .try_with(|order| {
            order
                .try_borrow_mut()
                .ok()
                .map(|mut order| std::mem::take(&mut *order))
        })
        .ok()
        .flatten()
        .unwrap_or_default();

    KEYED_DISPOSERS
        .try_with(|registry| {
            registry.try_borrow_mut().ok().map(|mut registry| {
                let mut result = Vec::with_capacity(registry.len());
                for key in order.into_iter().rev() {
                    if let Some(entry) = registry.remove(&key) {
                        result.push(entry.disposer);
                    }
                }
                result.extend(registry.drain().map(|(_, entry)| entry.disposer));
                result
            })
        })
        .ok()
        .flatten()
        .unwrap_or_default()
}

pub(crate) fn run_keyed_disposer(disposer: Dispose) {
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| disposer.run()));
}

/// Process-wide unique id for namespacing `remember_with_key` slots
/// (dialogs, menus, sheets, tooltips, ...).
static COMPONENT_ID: AtomicU64 = AtomicU64::new(1);

/// Returns a fresh unique component id. See [`COMPONENT_ID`].
pub fn unique_component_id() -> u64 {
    COMPONENT_ID.fetch_add(1, Ordering::Relaxed)
}

pub fn take_focus_request() -> Option<u64> {
    FOCUS_REQUESTS.with(|r| r.borrow_mut().pop_front())
}

/// Drain all queued focus requests in FIFO order.
///
/// While a capture lock is held, requests for other targets are denied and
/// the captured id is returned instead, pinning focus.
pub fn drain_focus_requests() -> Vec<u64> {
    if let Some(captured) = FOCUS_CAPTURED.with(|c| *c.borrow()) {
        FOCUS_REQUESTS.with(|r| r.borrow_mut().clear());
        return vec![captured];
    }
    FOCUS_REQUESTS.with(|r| r.borrow_mut().drain(..).collect())
}

/// Currently captured focus target, if any.
pub fn focus_capture() -> Option<u64> {
    FOCUS_CAPTURED.with(|c| *c.borrow())
}

/// A handle that can programmatically request focus for a widget.
///
/// Similar to Compose's `FocusRequester`. Create one via `remember(FocusRequester::new)`,
/// attach it via `.focus_requester(...)` on a modifier, and call `request_focus()` to
/// move keyboard focus to the associated widget on the next frame.
#[derive(Clone)]
pub struct FocusRequester {
    /// Target view ID, set during layout/paint by the modifier system.
    pub target: Rc<RefCell<Option<u64>>>,
}

impl FocusRequester {
    pub fn new() -> Self {
        Self {
            target: Rc::new(RefCell::new(None)),
        }
    }

    /// Request focus for the associated widget on the next frame.
    /// Queued; unlike the old single-slot behavior, multiple requests in one
    /// frame are all honored in order. If the target is not laid out yet the
    /// request is dropped (target assigned during layout/paint).
    pub fn request_focus(&self) {
        let _ = self.try_request_focus();
    }

    /// Enqueue a focus request, reporting whether it was accepted.
    /// Returns `false` when the target is not laid out yet (request dropped)
    /// or when another target holds the capture lock.
    pub fn try_request_focus(&self) -> bool {
        let Some(id) = *self.target.borrow() else {
            return false;
        };
        if let Some(captured) = FOCUS_CAPTURED.with(|c| *c.borrow())
            && captured != id
        {
            return false;
        }
        FOCUS_REQUESTS.with(|r| r.borrow_mut().push_back(id));
        true
    }

    /// Request focus for the associated widget from a traversal direction.
    /// Directional enter delegation is not implemented (focus targets are
    /// flat, not containers), so this behaves like [`try_request_focus`](Self::try_request_focus)
    /// and reports acceptance the same way.
    pub fn request_focus_directed(&self, _direction: FocusDirection) -> bool {
        self.try_request_focus()
    }

    /// Free/clear focus from the associated widget on the next frame.
    /// If the associated widget currently has focus, focus is cleared entirely.
    /// Corresponds to Compose's `freeFocus()`. Releases this target's capture
    /// lock when held.
    pub fn free_focus(&self) {
        if let Some(id) = *self.target.borrow() {
            FOCUS_CAPTURED.with(|c| {
                if *c.borrow() == Some(id) {
                    *c.borrow_mut() = None;
                }
            });
        }
        FOCUS_REQUESTS.with(|r| r.borrow_mut().push_back(CLEAR_FOCUS_MARKER));
    }

    /// Capture focus for the associated widget: focus moves to the target and
    /// stays pinned there until [`free_focus`](Self::free_focus). Other
    /// targets' requests are denied while the lock is held.
    /// Returns `false` when the target is not laid out yet.
    pub fn capture_focus(&self) -> bool {
        let Some(id) = *self.target.borrow() else {
            return false;
        };
        FOCUS_CAPTURED.with(|c| *c.borrow_mut() = Some(id));
        FOCUS_REQUESTS.with(|r| r.borrow_mut().push_back(id));
        true
    }
}

impl Default for FocusRequester {
    fn default() -> Self {
        Self::new()
    }
}

/// Direction for focus movement.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FocusDirection {
    Next,
    Previous,
    Left,
    Right,
    Up,
    Down,
}

/// A manager for programmatic focus navigation.
///
/// Wraps a `&Scheduler` and provides methods to move focus.
/// Can also be used standalone with a focus chain and focused element.
#[derive(Clone)]
pub struct FocusManager {
    /// The ordered list of focusable element IDs.
    pub chain: Vec<u64>,
    /// The currently focused element (if any).
    pub focused: Option<u64>,
    /// Hit regions for focus group lookups.
    pub hit_regions: Vec<HitRegion>,
}

impl FocusManager {
    pub fn new(chain: Vec<u64>, focused: Option<u64>) -> Self {
        Self {
            chain,
            focused,
            hit_regions: Vec::new(),
        }
    }

    /// Move focus in the given direction.
    /// Returns the new focused element ID, or `None` if no movement is possible.
    pub fn move_focus(&mut self, dir: FocusDirection) -> Option<u64> {
        match dir {
            FocusDirection::Next | FocusDirection::Previous => {
                self.move_tab(dir == FocusDirection::Previous)
            }
            _ => None, // use move_focus_spatial when hit regions are available
        }
    }

    /// Clears focus entirely on the next frame.
    /// Corresponds to Compose's `FocusManager.clearFocus()`.
    /// The `force` parameter is accepted for API compatibility. In repose
    /// focus is always cleared immediately (no keep-focus mechanism).
    pub fn clear_focus(&self, _force: bool) {
        FOCUS_REQUESTS.with(|r| r.borrow_mut().push_back(CLEAR_FOCUS_MARKER));
    }

    /// Spatial focus navigation: find the closest focusable element in a given
    /// direction using bounding rect geometry.
    pub fn move_focus_spatial(
        &mut self,
        dir: FocusDirection,
        hit_regions: &[HitRegion],
    ) -> Option<u64> {
        let next = spatial_focus_next(&self.chain, hit_regions, self.focused, dir)?;
        self.focused = Some(next);
        Some(next)
    }

    /// Tab forward or backward in the focus chain.
    /// When the current focus belongs to a focus group, navigation is restricted
    /// to elements within that group.
    pub fn move_tab(&mut self, reverse: bool) -> Option<u64> {
        if self.chain.is_empty() {
            return None;
        }
        let next = if let Some(sub_chain) =
            focus_group_chain(&self.chain, &self.hit_regions, self.focused)
        {
            if sub_chain.is_empty() {
                return None;
            }
            if let Some(cur) = self.focused {
                if let Some(idx) = sub_chain.iter().position(|&id| id == cur) {
                    if reverse {
                        if idx == 0 {
                            sub_chain[sub_chain.len() - 1]
                        } else {
                            sub_chain[idx - 1]
                        }
                    } else {
                        sub_chain[(idx + 1) % sub_chain.len()]
                    }
                } else {
                    sub_chain[0]
                }
            } else if reverse {
                sub_chain[sub_chain.len() - 1]
            } else {
                sub_chain[0]
            }
        } else {
            if let Some(cur) = self.focused {
                if let Some(idx) = self.chain.iter().position(|&id| id == cur) {
                    if reverse {
                        if idx == 0 {
                            self.chain[self.chain.len() - 1]
                        } else {
                            self.chain[idx - 1]
                        }
                    } else {
                        self.chain[(idx + 1) % self.chain.len()]
                    }
                } else {
                    self.chain[0]
                }
            } else if reverse {
                self.chain[self.chain.len() - 1]
            } else {
                self.chain[0]
            }
        };
        self.focused = Some(next);
        Some(next)
    }

    /// Set target ID on a FocusRequester (called during layout).
    pub fn set_requester_target(requester: &FocusRequester, id: u64) {
        *requester.target.borrow_mut() = Some(id);
    }
}

/// Sub-chain of ids sharing the focused element's focus group.
/// Returns `None` when focus is outside any group (full chain applies).
/// Tab and spatial navigation both scope to this so modals trap focus.
pub fn focus_group_chain(
    chain: &[u64],
    hit_regions: &[HitRegion],
    current: Option<u64>,
) -> Option<Vec<u64>> {
    let cur = current?;
    let group_id = hit_regions.iter().find(|h| h.id == cur)?.focus_group_id?;
    Some(
        chain
            .iter()
            .copied()
            .filter(|&id| {
                id == group_id
                    || hit_regions
                        .iter()
                        .any(|h| h.id == id && h.focus_group_id == Some(group_id))
            })
            .collect(),
    )
}

/// Find the next focusable element in a given spatial direction.
///
/// Uses the bounding rects from `hit_regions` to determine which element is
/// "next" in the given direction from the currently focused element.
pub fn spatial_focus_next(
    chain: &[u64],
    hit_regions: &[HitRegion],
    current: Option<u64>,
    dir: FocusDirection,
) -> Option<u64> {
    if chain.is_empty() {
        return None;
    }

    let current_rect =
        current.and_then(|id| hit_regions.iter().find(|h| h.id == id).map(|h| h.rect));

    // For Next/Previous, use tab-order navigation
    match dir {
        FocusDirection::Next | FocusDirection::Previous => {
            let mut fm = FocusManager {
                chain: chain.to_vec(),
                focused: current,
                hit_regions: hit_regions.to_vec(),
            };
            return fm.move_tab(dir == FocusDirection::Previous);
        }
        _ => {}
    }

    let (cx, cy) = match current_rect {
        Some(r) => (r.x + r.w / 2.0, r.y + r.h / 2.0),
        None => {
            // For games: Tab/Shift-Tab should establish initial focus, not arrows.
            return None;
        }
    };

    let mut best: Option<(u64, f32)> = None;

    // Modal trap: arrows stay inside the focused element's focus group.
    let scoped: Vec<u64>;
    let chain: &[u64] = match focus_group_chain(chain, hit_regions, current) {
        Some(sub) => {
            scoped = sub;
            &scoped
        }
        None => chain,
    };

    for &id in chain {
        if Some(id) == current {
            continue;
        }
        let Some(hr) = hit_regions.iter().find(|h| h.id == id) else {
            continue;
        };
        let r = hr.rect;
        let other_cx = r.x + r.w / 2.0;
        let other_cy = r.y + r.h / 2.0;
        let dx = other_cx - cx;
        let dy = other_cy - cy;

        let in_direction = match dir {
            FocusDirection::Left => dx < 0.0 && dy.abs() <= r.h.max(1.0),
            FocusDirection::Right => dx > 0.0 && dy.abs() <= r.h.max(1.0),
            FocusDirection::Up => dy < 0.0 && dx.abs() <= r.w.max(1.0),
            FocusDirection::Down => dy > 0.0 && dx.abs() <= r.w.max(1.0),
            _ => false,
        };

        if !in_direction {
            continue;
        }

        let dist = dx * dx + dy * dy;
        let weight = dist / (r.w * r.h + 1.0).max(1.0);

        match best {
            Some((_, best_weight)) if weight >= best_weight => {}
            _ => best = Some((id, weight)),
        }
    }

    best.map(|(id, _)| id)
}

#[derive(Default)]
pub struct Composer {
    pub slots: Vec<Box<dyn Any>>,
    pub slot_callers: Vec<&'static Location<'static>>,
    pub cursor: usize,
    pub auto_counts: FxHashMap<String, usize>,
    pub keyed_slots: FxHashMap<String, Box<dyn Any>>,
    pub keyed_owner: FxHashMap<String, String>,
    pub keyed_owners: FxHashMap<String, rustc_hash::FxHashSet<String>>,
    /// Owner tokens of registered scopes visited this frame, plus the root token.
    pub live_keyed_owners: rustc_hash::FxHashSet<String>,
    /// Raw keys read through `remember_with_key` this frame.
    pub live_keyed_keys: rustc_hash::FxHashSet<String>,
    /// Owner tokens of scopes served from cache this frame. Their bodies did not
    /// re-run, so their keyed slots go unread and must not be collected.
    pub cache_preserved_owners: rustc_hash::FxHashSet<String>,
    pub scope_caches: FxHashMap<String, crate::scope_cache::ScopeCache>,
    pub live_scope_keys: rustc_hash::FxHashSet<String>,
}

pub struct ComposeGuard {
    scope: Scope,
}

pub(crate) fn keyed_disposer_order(key: &str) -> usize {
    KEYED_DISPOSER_ORDER
        .try_with(|order| {
            order
                .try_borrow()
                .ok()
                .and_then(|order| order.iter().position(|registered| registered == key))
        })
        .ok()
        .flatten()
        .unwrap_or(usize::MAX)
}

pub(crate) fn release_keyed_owner(key: &str, owner: &str) -> (bool, Option<Box<dyn Any>>) {
    let result = COMPOSER
        .try_with(|composer| {
            let mut composer = match composer.try_borrow_mut() {
                Ok(composer) => composer,
                Err(_) => return (false, None, None),
            };
            let owners = match composer.keyed_owners.get_mut(key) {
                Some(owners) => owners,
                None => return (false, None, None),
            };
            owners.remove(owner);
            if !owners.is_empty() {
                return (true, None, None);
            }
            composer.keyed_owners.remove(key);
            let old_owner = composer.keyed_owner.remove(key);
            (true, composer.keyed_slots.remove(key), old_owner)
        })
        .unwrap_or((false, None, None));
    drop(result.2);
    (result.0, result.1)
}

/// A keyed slot survives when both hold:
///
/// * an owning scope is live (registered and visited this frame, or root) —
///   unchanged rule, so slots whose owner is not a real scope (a bare
///   `with_scope_key`, as `produce_state` tests use) are still collected, and
///   `ProduceHandle::drop` can strip the reactive observer; and
/// * the key was read this frame, or an owning scope was served from cache and
///   so legitimately never read it.
///
/// The second condition is the fix. A scope that re-runs but stops reading a
/// key now drops it, so a slot abandoned inside a permanently mounted scope —
/// an overlay guard held by a component the host stopped composing, releases
/// its entry instead of pinning it for the life of the app.
pub(crate) fn take_dead_keyed_slots(composer: &mut Composer) -> Vec<(String, Box<dyn Any>)> {
    fn owners_of<'a>(composer: &'a Composer, key: &str) -> Vec<&'a String> {
        match composer.keyed_owners.get(key) {
            Some(owners) => owners.iter().collect(),
            None => composer.keyed_owner.get(key).into_iter().collect(),
        }
    }
    let dead: Vec<String> = composer
        .keyed_slots
        .keys()
        .filter(|key| {
            let owners = owners_of(composer, key);
            let scope_live = owners
                .iter()
                .any(|owner| composer.live_keyed_owners.contains(*owner));
            if !scope_live {
                return true;
            }
            if composer.live_keyed_keys.contains(*key) {
                return false;
            }
            !owners
                .iter()
                .any(|owner| composer.cache_preserved_owners.contains(*owner))
        })
        .cloned()
        .collect();
    let mut removed = Vec::with_capacity(dead.len());
    for key in dead {
        if let Some(value) = composer.keyed_slots.remove(&key) {
            removed.push((key.clone(), value));
        }
        composer.keyed_owner.remove(&key);
        composer.keyed_owners.remove(&key);
    }
    removed
}

pub(crate) fn current_scope_key_for_remember() -> Option<String> {
    crate::scope_cache::current_scope_key()
}

fn flush_initializer_cursor() {
    let pending = PENDING_INITIALIZER_CURSOR
        .try_with(|pending| {
            pending
                .try_borrow_mut()
                .ok()
                .and_then(|mut pending| pending.take())
        })
        .ok()
        .flatten();
    let Some(cursor) = pending else {
        return;
    };
    let restored = COMPOSER
        .try_with(|composer| {
            composer
                .try_borrow_mut()
                .ok()
                .map(|mut composer| composer.cursor = cursor)
        })
        .ok()
        .flatten();
    if restored.is_none() {
        let _ = PENDING_INITIALIZER_CURSOR.try_with(|pending| {
            if let Ok(mut pending) = pending.try_borrow_mut() {
                *pending = Some(cursor);
            }
        });
    }
}

impl ComposeGuard {
    pub fn begin() -> Self {
        flush_initializer_cursor();
        COMPOSER.with(|c| {
            let mut c = c.borrow_mut();
            c.cursor = 0;
            c.auto_counts.clear();
            c.live_scope_keys.clear();
            c.live_keyed_owners.clear();
            c.live_keyed_keys.clear();
            c.cache_preserved_owners.clear();
            c.live_scope_keys.insert(String::new());
            c.live_keyed_owners.insert(scope_owner_token(None));
        });

        let scope = ROOT_SCOPE.with(|rs| {
            if let Some(existing) = rs.borrow().clone() {
                existing
            } else {
                let s = Scope::new();
                *rs.borrow_mut() = Some(s.clone());
                s
            }
        });

        ComposeGuard { scope }
    }

    pub fn scope(&self) -> &Scope {
        &self.scope
    }

    pub fn live_scope_keys(&self) -> rustc_hash::FxHashSet<String> {
        COMPOSER.with(|c| c.borrow().live_scope_keys.clone())
    }
}

impl Drop for ComposeGuard {
    fn drop(&mut self) {
        let removed = COMPOSER.with(|c| {
            let mut c = c.borrow_mut();
            let n = c.cursor;
            let mut removed = Vec::new();
            if c.slots.len() > n {
                removed.extend(c.slots.drain(n..));
            }
            if c.slot_callers.len() > n {
                c.slot_callers.truncate(n);
            }
            removed
        });
        drop(removed);
        crate::scope_cache::gc_dead_scopes();
    }
}

/// Dispose the root composition scope and clear all composer caches.
///
/// Call once on process exit (desktop `exiting`, tests). After this the next
/// `ComposeGuard::begin` starts from a fresh root scope.
pub fn shutdown_composition() {
    let scope = ROOT_SCOPE.with(|rs| rs.borrow_mut().take());
    if let Some(scope) = scope {
        scope.dispose();
    }
    let removed = COMPOSER.with(|c| {
        let mut c = c.borrow_mut();
        let slots = std::mem::take(&mut c.slots);
        let callers = std::mem::take(&mut c.slot_callers);
        let keyed = std::mem::take(&mut c.keyed_slots);
        let caches = std::mem::take(&mut c.scope_caches);
        c.keyed_owner.clear();
        c.keyed_owners.clear();
        c.live_keyed_owners.clear();
        c.live_keyed_keys.clear();
        c.cache_preserved_owners.clear();
        c.live_scope_keys.clear();
        c.cursor = 0;
        c.auto_counts.clear();
        (slots, callers, keyed, caches)
    });
    drop(removed);
    for disposer in take_all_keyed_disposers() {
        run_keyed_disposer(disposer);
    }
    crate::animation_driver::shutdown();
    crate::scope_cache::clear_all_scope_deps();
    INITIALIZER_STACK.with(|stack| stack.borrow_mut().clear());
    PENDING_INITIALIZER_CURSOR.with(|pending| {
        let _ = pending.borrow_mut().take();
    });
}

struct InitializerGuard {
    active: bool,
    cursor: Option<usize>,
}

impl InitializerGuard {
    fn assert_sequential_allowed() {
        assert!(
            INITIALIZER_STACK.with(|stack| stack
                .try_borrow()
                .map(|stack| stack.is_empty())
                .unwrap_or(false)),
            "remember initializer re-entered composition; use an explicit keyed helper"
        );
    }

    fn enter_sequential() -> (Self, usize) {
        Self::assert_sequential_allowed();
        let cursor = COMPOSER.with(|composer| {
            let mut composer = composer.borrow_mut();
            let cursor = composer.cursor;
            composer.cursor = composer.cursor.wrapping_add(1);
            cursor
        });
        let pushed = INITIALIZER_STACK
            .try_with(|stack| {
                stack.try_borrow_mut().ok().map(|mut stack| {
                    stack.push(InitializerKind::Sequential);
                    true
                })
            })
            .ok()
            .flatten();
        if pushed != Some(true) {
            let _ = COMPOSER.try_with(|composer| {
                if let Ok(mut composer) = composer.try_borrow_mut() {
                    composer.cursor = cursor;
                }
            });
            panic!("initializer stack busy");
        }
        (
            Self {
                active: true,
                cursor: Some(cursor),
            },
            cursor,
        )
    }

    fn assert_keyed_allowed() {
        assert!(
            INITIALIZER_STACK.with(|stack| stack
                .try_borrow()
                .map(|stack| stack.is_empty())
                .unwrap_or(false)),
            "remember initializer re-entered composition; use an explicit keyed helper"
        );
    }

    fn enter_keyed() -> Self {
        Self::assert_keyed_allowed();
        INITIALIZER_STACK.with(|stack| {
            stack
                .try_borrow_mut()
                .expect("initializer stack busy")
                .push(InitializerKind::Keyed)
        });
        Self {
            active: true,
            cursor: None,
        }
    }

    fn commit(&mut self) {
        if !self.active {
            return;
        }
        let _ = INITIALIZER_STACK.try_with(|stack| {
            if let Ok(mut stack) = stack.try_borrow_mut() {
                stack.pop();
            }
        });
        self.active = false;
    }
}

impl Drop for InitializerGuard {
    fn drop(&mut self) {
        if !self.active {
            return;
        }
        if let Some(cursor) = self.cursor {
            let restored = COMPOSER
                .try_with(|composer| {
                    composer
                        .try_borrow_mut()
                        .ok()
                        .map(|mut composer| composer.cursor = cursor)
                })
                .ok()
                .flatten();
            if restored.is_none() {
                let _ = PENDING_INITIALIZER_CURSOR.try_with(|pending| {
                    if let Ok(mut pending) = pending.try_borrow_mut() {
                        *pending = Some(cursor);
                    }
                });
            }
        }
        let _ = INITIALIZER_STACK.try_with(|stack| {
            if let Ok(mut stack) = stack.try_borrow_mut() {
                stack.pop();
            }
        });
    }
}

/// Slot-based remember (sequential composition only).
/// This prevents state aliasing when the composition tree structure changes between frames
#[track_caller]
pub fn remember<T: 'static>(init: impl FnOnce() -> T) -> Rc<T> {
    flush_initializer_cursor();
    let caller = Location::caller();
    let (mut initializer, cursor) = InitializerGuard::enter_sequential();

    let existing = COMPOSER.with(|c| {
        let c = c.borrow();
        if cursor >= c.slots.len() || c.slot_callers.get(cursor).copied() != Some(caller) {
            return None;
        }
        c.slots[cursor].downcast_ref::<Rc<T>>().cloned()
    });
    if let Some(rc) = existing {
        initializer.commit();
        return rc;
    }

    if COMPOSER.with(|c| {
        let c = c.borrow();
        cursor < c.slots.len() && c.slot_callers.get(cursor).copied() == Some(caller)
    }) {
        log::warn!(
            "remember: slot {} type changed {}. \
             Use remember_with_key(key, || ...) for conditional branches.",
            cursor,
            std::any::type_name::<T>(),
        );
    }

    let rc = Rc::new(init());
    let old = COMPOSER.with(|c| {
        let mut c = c.borrow_mut();
        let value: Box<dyn Any> = Box::new(rc.clone());
        let old = if cursor < c.slots.len() {
            Some(std::mem::replace(&mut c.slots[cursor], value))
        } else {
            c.slots.push(value);
            None
        };
        if cursor < c.slot_callers.len() {
            c.slot_callers[cursor] = caller;
        } else {
            c.slot_callers.push(caller);
        }
        old
    });
    initializer.commit();
    drop(old);
    rc
}

fn push_key_part(key: &mut String, part: &str) {
    key.push_str(&part.len().to_string());
    key.push(':');
    key.push_str(part);
    key.push('|');
}

/// Auto-keyed variant of [`remember`]: identity is the call site plus an
/// occurrence index, so state follows a composition *position*, not an item.
/// Only safe where the number of calls at this site is fixed across frames —
/// list items and conditional branches need [`remember_with_key`].
#[track_caller]
pub fn remember_auto<T: 'static>(slot: &str, init: impl FnOnce() -> T) -> Rc<T> {
    let caller = Location::caller();
    let scope = current_scope_key_for_remember().unwrap_or_default();
    let mut base = String::from("auto:v1|");
    push_key_part(&mut base, &scope);
    push_key_part(&mut base, caller.file());
    push_key_part(&mut base, &caller.line().to_string());
    push_key_part(&mut base, &caller.column().to_string());
    push_key_part(&mut base, slot);
    let occurrence = COMPOSER.with(|composer| {
        let mut composer = composer.borrow_mut();
        let count = composer.auto_counts.entry(base.clone()).or_insert(0);
        let occurrence = *count;
        *count += 1;
        occurrence
    });
    push_key_part(&mut base, &occurrence.to_string());
    remember_with_key(base, init)
}

pub fn keyed<T>(key: impl Into<String>, f: impl FnOnce() -> T) -> T {
    let key = key.into();
    assert!(!key.is_empty(), "keyed scopes need non-empty keys");
    let parent = current_scope_key_for_remember().unwrap_or_default();
    let mut full_key = String::new();
    push_key_part(&mut full_key, &parent);
    push_key_part(&mut full_key, &key);
    crate::scope_cache::with_scope_key(&full_key, f)
}

/// Key-based remember.
pub fn remember_with_key<T: 'static>(key: impl Into<String>, init: impl FnOnce() -> T) -> Rc<T> {
    flush_initializer_cursor();
    InitializerGuard::assert_keyed_allowed();
    let key = key.into();
    let scope = current_scope_key_for_remember();
    let owner = scope_owner_token(scope.as_deref());
    let existing = COMPOSER.with(|composer| {
        let composer = composer.borrow();
        composer
            .keyed_slots
            .get(&key)
            .and_then(|value| value.downcast_ref::<Rc<T>>().cloned())
    });
    if let Some(existing) = existing {
        let old_owner = COMPOSER.with(|composer| {
            let mut composer = composer.borrow_mut();
            composer.live_keyed_keys.insert(key.clone());
            let old_owner = composer.keyed_owner.insert(key.clone(), owner.clone());
            composer
                .keyed_owners
                .entry(key.clone())
                .or_default()
                .insert(owner.clone());
            composer.live_keyed_owners.insert(owner);
            old_owner
        });
        drop(old_owner);
        return existing;
    }

    // Reaching here means the same-type early return above did not fire, so the
    // key is either absent or held under a different type. Keep the two signals
    // apart: fusing them made a type collision also log the "unbounded dynamic
    // keys" message, and left the real key-count check unable to fire outside
    // debug builds.
    let (wrong_type, key_count_high) = COMPOSER.with(|composer| {
        let composer = composer.borrow();
        (
            composer.keyed_slots.contains_key(&key),
            composer.keyed_slots.len() > 10_000,
        )
    });
    if wrong_type {
        log::warn!(
            "remember_with_key: key '{}' reused with a different type; replacing.",
            key
        );
    }
    if key_count_high {
        log::warn!(
            "remember_with_key: {} keys stored; are you generating unbounded dynamic keys?",
            COMPOSER.with(|composer| composer.borrow().keyed_slots.len())
        );
    }

    let mut initializer = InitializerGuard::enter_keyed();
    let value = Rc::new(init());
    let (result, old) = COMPOSER.with(|composer| {
        let mut composer = composer.borrow_mut();
        if let Some(existing) = composer.keyed_slots.get(&key)
            && let Some(existing) = existing.downcast_ref::<Rc<T>>()
        {
            let existing = existing.clone();
            composer.live_keyed_keys.insert(key.clone());
            composer.keyed_owner.insert(key.clone(), owner.clone());
            composer
                .keyed_owners
                .entry(key.clone())
                .or_default()
                .insert(owner.clone());
            composer.live_keyed_owners.insert(owner);
            return (existing, None);
        }
        let old = composer
            .keyed_slots
            .insert(key.clone(), Box::new(value.clone()));
        composer.live_keyed_keys.insert(key.clone());
        composer.keyed_owner.insert(key.clone(), owner.clone());
        composer
            .keyed_owners
            .entry(key)
            .or_default()
            .insert(owner.clone());
        (value, old)
    });
    initializer.commit();
    drop(old);
    result
}

/// Raw slot state (`Rc<RefCell<T>>`). Writes via `borrow_mut()` don't request a
/// frame - prefer [`remember_mutable`] if a write must always recompose.
#[track_caller]
pub fn remember_state<T: 'static>(init: impl FnOnce() -> T) -> Rc<RefCell<T>> {
    remember(|| RefCell::new(init()))
}

/// Key-based variant of [`remember_state`]. Same no-frame-on-write caveat.
pub fn remember_state_with_key<T: 'static>(
    key: impl Into<String>,
    init: impl FnOnce() -> T,
) -> Rc<RefCell<T>> {
    remember_with_key(key, || RefCell::new(init()))
}

/// Auto-keyed variant of [`remember_state`]. Same positional caveat as
/// [`remember_auto`] and the same no-frame-on-write caveat as [`remember_state`].
#[track_caller]
pub fn remember_state_auto<T: 'static>(slot: &str, init: impl FnOnce() -> T) -> Rc<RefCell<T>> {
    remember_auto(slot, || RefCell::new(init()))
}

/// Frame - output of composition for a tick: scene + input/semantics.
#[derive(Clone)]
pub struct Frame {
    pub scene: Scene,
    pub hit_regions: Vec<HitRegion>,
    pub semantics_nodes: Vec<SemNode>,
    pub focus_chain: Vec<u64>,
}

/// Hit-test region in physical pixels (`rect` carries px magnitudes,
/// like Compose `Rect`).
#[derive(Clone, Default)]
pub struct HitRegion {
    pub id: u64,
    pub rect: Rect,
    /// Tree depth: 0 = root, higher = deeper child. Used for three-pass
    /// pointer dispatch to determine ancestor/descendant ordering.
    pub depth: u32,
    pub parent: Option<u64>,
    pub on_click: Option<Rc<dyn Fn()>>,
    pub on_double_click: Option<Rc<dyn Fn()>>,
    pub on_long_click: Option<Rc<dyn Fn()>>,
    pub on_scroll: Option<Rc<dyn Fn(crate::Vec2) -> crate::Vec2>>,
    pub on_scroll_with_source:
        Option<Rc<dyn Fn(crate::Vec2, crate::input::ScrollSource) -> crate::Vec2>>,
    pub focusable: bool,
    pub on_pointer_down: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
    pub on_pointer_move: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
    pub on_pointer_up: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
    pub on_pointer_cancel: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
    pub on_pointer_enter: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
    pub on_pointer_leave: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
    pub z_index: f32,
    pub disabled: bool,
    pub on_text_change: Option<Rc<dyn Fn(String)>>,
    pub on_text_submit: Option<Rc<dyn Fn(String)>>,
    /// If this hit region belongs to a TextField, this persistent key is used
    /// for looking up platform-managed TextFieldState. Falls back to `id` if None.
    pub tf_state_key: Option<u64>,

    /// True if this hit region corresponds to a multiline text input (TextArea).
    pub tf_multiline: bool,

    /// Unclipped top-left of the TextField *content* box (padding-inset).
    /// Used for pointer->grapheme mapping so parent scroll clipping of `rect`
    /// does not shift selection into the top of the content.
    /// `None` for non-textfields.
    pub tf_content_origin: Option<(f32, f32)>,

    /// When false, the field rejects edits and is not focusable
    pub tf_enabled: bool,

    /// When true, selection/focus/copy are allowed but mutations are rejected
    pub tf_read_only: bool,

    pub tf_sensitive: bool,

    /// Controlled text snapshot for this field (last compose).
    pub tf_value: String,

    /// Font size for this text field in [`Sp`](crate::units::Sp)
    /// (for hit-test / caret mapping). `Sp::ZERO` means use `TF_FONT_SP` default.
    pub tf_font_size: crate::units::Sp,

    // internal
    pub on_drag_start: Option<Rc<dyn Fn(crate::dnd::DragStart) -> Option<crate::dnd::DragPayload>>>,
    pub on_drag_end: Option<Rc<dyn Fn(crate::dnd::DragEnd)>>,
    pub on_drag_enter: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
    pub on_drag_over: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
    pub on_drag_leave: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
    pub on_drop: Option<Rc<dyn Fn(crate::dnd::DropEvent) -> bool>>,
    /// Copied onto the drag session when a drag starts from this region.
    pub drag_preview: Option<crate::dnd::DragPreview>,

    pub on_action: Option<Rc<dyn Fn(crate::shortcuts::Action) -> bool>>,

    pub on_set_progress: Option<Rc<dyn Fn(f32)>>,
    pub on_expand: Option<Rc<dyn Fn()>>,
    pub on_collapse: Option<Rc<dyn Fn()>>,
    pub on_dismiss: Option<Rc<dyn Fn()>>,

    /// Called when a key event is received while this element is focused.
    /// Return `true` to consume the event.
    pub on_key_event: Option<Rc<dyn Fn(crate::input::KeyEvent) -> bool>>,
    /// Called before `on_key_event`. Return `true` to consume before normal dispatch.
    pub on_preview_key_event: Option<Rc<dyn Fn(crate::input::KeyEvent) -> bool>>,
    /// Called when an IME event (composition update/commit) is received
    /// while this element is focused. Return `true` to consume the event.
    pub on_ime: Option<Rc<dyn Fn(crate::input::ImeEvent) -> bool>>,

    /// Cursor hint for desktop/web.
    pub cursor: Option<crate::CursorIcon>,

    /// If `Some(group_id)`, this hit region belongs to a focus group with the
    /// given id. Tab navigation will cycle within the group instead of moving
    /// to elements outside it. Set automatically by the layout engine when the
    /// element is a descendant of a node with `focus_group: true`.
    pub focus_group_id: Option<u64>,

    /// IME keyboard hints, populated for text-field hit regions so the
    /// platform runner can configure the OS keyboard / IME on focus.
    pub keyboard_type: crate::text::KeyboardType,
    pub capitalization: crate::text::KeyboardCapitalization,
    pub ime_action: crate::text::ImeAction,
    /// Whether auto-correct is enabled. `None` = follow platform default;
    /// password keyboards always resolve to `false` in the layout engine.
    pub auto_correct: Option<bool>,

    /// Shared interaction source auto-wired by the layout engine
    /// (press/hover/focus/drag). Used by keyboard activation and focus
    /// transitions so they stay in parity with pointer input.
    /// `None` when the component does not need one (no indication/state colors).
    pub interaction_source: Option<crate::modifier::InteractionSource>,
}

impl HitRegion {
    /// Seed a HitRegion with all the modifier's event handlers + dnd + cursor.
    /// Call‑sites should only override the fields that differ (on_click, focusable, etc.)
    /// via struct‑update syntax: `HitRegion { focusable: true, ..from_modifier(..) }`.
    pub fn from_modifier(id: u64, rect: Rect, m: &crate::modifier::Modifier) -> Self {
        Self {
            id,
            rect,
            z_index: m.z_index,
            on_click: m.on_click.clone(),
            on_double_click: m.on_double_click.clone(),
            on_long_click: m.on_long_click.clone(),
            on_pointer_down: m.on_pointer_down.clone(),
            on_pointer_move: m.on_pointer_move.clone(),
            on_pointer_up: m.on_pointer_up.clone(),
            on_pointer_cancel: m.on_pointer_cancel.clone(),
            on_pointer_enter: m.on_pointer_enter.clone(),
            on_pointer_leave: m.on_pointer_leave.clone(),
            on_action: m.on_action.clone(),
            on_set_progress: m.on_set_progress.clone(),
            on_expand: m.on_expand.clone(),
            on_collapse: m.on_collapse.clone(),
            on_dismiss: m.on_dismiss.clone(),
            on_key_event: m.on_key_event.clone(),
            on_preview_key_event: m.on_preview_key_event.clone(),
            on_ime: m.on_ime.clone(),
            cursor: m.cursor.clone(),
            on_drag_start: m.on_drag_start.clone(),
            on_drag_end: m.on_drag_end.clone(),
            on_drag_enter: m.on_drag_enter.clone(),
            on_drag_over: m.on_drag_over.clone(),
            on_drag_leave: m.on_drag_leave.clone(),
            on_scroll: m.on_scroll.clone(),
            on_scroll_with_source: m.on_scroll_with_source.clone(),
            on_drop: m.on_drop.clone(),
            drag_preview: m.drag_preview.clone(),
            disabled: m.disabled,
            tf_enabled: true,
            tf_read_only: false,
            ..Default::default()
        }
    }
}

/// Route a gesture action to the topmost hit region under `center`,
/// walking up ancestors until one consumes it. Fallback for gestures that
/// miss the focused widget, matching Compose routing to the node under the
/// pointer. Coordinates are physical px, like [`HitRegion::rect`].
pub fn route_action_to_point(
    hits: &[HitRegion],
    action: &crate::shortcuts::Action,
    center: crate::Vec2,
) -> bool {
    let mut best: Option<&HitRegion> = None;
    for h in hits {
        if h.disabled || h.on_action.is_none() {
            continue;
        }
        let r = h.rect;
        if center.x < r.x || center.x > r.x + r.w || center.y < r.y || center.y > r.y + r.h {
            continue;
        }
        let better = match best {
            None => true,
            Some(b) => (h.z_index, h.depth) >= (b.z_index, b.depth),
        };
        if better {
            best = Some(h);
        }
    }
    let mut current = best.map(|h| h.id);
    while let Some(id) = current {
        let Some(h) = hits.iter().find(|h| h.id == id) else {
            break;
        };
        if !h.disabled
            && let Some(cb) = &h.on_action
            && cb(action.clone())
        {
            return true;
        }
        current = h.parent;
    }
    false
}

/// Flattened semantics node produced by `layout_and_paint`.
///
/// This is the source of truth for accessibility backends: it contains the
/// resolved screen rect, role, label, and focus/enabled state.
///
/// The platform runner should convert this into OS‑specific accessibility trees (when implemented)
/// (AT‑SPI on Linux, TalkBack on Android, etc.).
#[derive(Clone)]
pub struct SemNode {
    /// Stable id, shared with the associated `HitRegion` / `ViewId`.
    pub id: u64,

    /// `None` means direct child of the window root.
    pub parent: Option<u64>,

    pub role: Role,
    pub label: Option<String>,
    pub rect: Rect,
    pub focused: bool,
    pub enabled: bool,
    /// Marks this node as a collection of selectable children (e.g., Tabs).
    pub selectable_group: bool,
    pub checked: Option<bool>,
    pub selected: Option<bool>,
    pub value: Option<String>,
    pub heading: bool,
    pub live_region: Option<crate::semantics::LiveRegion>,
    pub state_description: Option<String>,
    pub traversal_index: Option<f32>,
    pub is_traversal_group: bool,
    pub hidden: bool,
    pub collection_rows: Option<usize>,
    pub collection_columns: Option<usize>,
    pub row_index: Option<usize>,
    pub column_index: Option<usize>,
    pub progress: Option<crate::semantics::ProgressRangeInfo>,
    pub error: Option<String>,
    pub expanded: Option<bool>,
    pub scrollable: bool,
    pub can_expand: bool,
    pub can_collapse: bool,
    pub can_dismiss: bool,
}

impl Default for SemNode {
    fn default() -> Self {
        Self {
            id: 0,
            parent: None,
            role: Role::default(),
            label: None,
            rect: Rect::default(),
            focused: false,
            enabled: true,
            selectable_group: false,
            checked: None,
            selected: None,
            value: None,
            heading: false,
            live_region: None,
            state_description: None,
            traversal_index: None,
            is_traversal_group: false,
            hidden: false,
            collection_rows: None,
            collection_columns: None,
            row_index: None,
            column_index: None,
            progress: None,
            error: None,
            expanded: None,
            scrollable: false,
            can_expand: false,
            can_collapse: false,
            can_dismiss: false,
        }
    }
}

pub struct Scheduler {
    next_id: u64,
    /// Per-scope unique IDs, assigned lazily when a scope first executes.
    /// Keyed by the scope key string from `scope!`.
    scope_key_to_id: FxHashMap<String, u32>,
    next_scope_id: u32,
    /// Stack of active scope keys. `id()` allocates from the innermost scope
    /// so nested `scope!` bodies get stable packed IDs and the outer scope
    /// resumes correctly after the inner exits (previously `exit_scope` reset
    /// to `None`, leaking outer IDs into the global sequence).
    current_scope: Vec<String>,
    /// Per-scope local ID counters. Reset to 0 when a scope re-executes.
    scope_local_counters: FxHashMap<String, u32>,
    pub focused: Option<u64>,
    pub size: (u32, u32),
    /// Last known mouse pointer position in physical px, updated on
    /// mouse move/press/release without passing through focus dispatch.
    pub pointer_pos_px: Option<(f32, f32)>,
    /// Polled physical keys currently down, layout-independent
    /// positions (see [`PhysicalKey`]). The platform runner maintains
    /// this from raw `KeyboardInput` events without passing through
    /// focus dispatch; games reconcile their event-staged held sets
    /// against it every frame (GML `keyboard_check` parity). Cleared
    /// on window focus loss (no key-ups arrive across an alt-tab).
    pub held_keys: HashSet<PhysicalKey>,
    /// Window focus as of the last platform event. `false` drops every
    /// held key on the game side.
    pub window_focused: bool,
    /// Live touch contacts in physical px: `(touch id, x, y)` per
    /// finger currently down. Written by the platform runners from
    /// raw `WindowEvent::Touch` (Started/Moved/Ended-Cancelled), read
    /// by games through `feed_polled`-style staging snapshots
    /// (GML `device_mouse_x_to_gui(i)` parity: stable per-finger slot
    /// ids, positions sampled every tick while held).
    pub touch_points: Vec<(u64, f32, f32)>,
    /// Polled mouse-button levels, same source as `held_keys`
    /// (GML `mouse_check_button` parity; repairs a missed button-up
    /// when the release lands outside the window).
    pub mouse_primary: bool,
    pub mouse_secondary: bool,
    pub mouse_middle: bool,
    /// App-requested cursor override. When `Some`, the platform
    /// applies it instead of the hover-derived icon: games hide the
    /// OS pointer here (`CursorIcon::Hidden`) while drawing their own
    /// crosshair, GML `window_set_cursor(cr_none)` parity. `None`
    /// restores hover behavior. Set during composition (any view can
    /// write it; last write per frame wins), consumed by the runner
    /// after `frame()`.
    pub cursor_override: Option<CursorIcon>,
}

impl Default for Scheduler {
    fn default() -> Self {
        Self::new()
    }
}

impl Scheduler {
    pub fn new() -> Self {
        Self {
            next_id: 1,
            scope_key_to_id: FxHashMap::default(),
            next_scope_id: 1,
            current_scope: Vec::new(),
            scope_local_counters: FxHashMap::default(),
            focused: None,
            size: (1280, 800),
            pointer_pos_px: None,
            held_keys: HashSet::new(),
            window_focused: true,
            touch_points: Vec::new(),
            mouse_primary: false,
            mouse_secondary: false,
            mouse_middle: false,
            cursor_override: None,
        }
    }

    /// Enter a named scope. Subsequent `id()` calls within this scope
    /// will allocate from the scope's local counter, producing packed
    /// `(scope_id << 32) | local_id` values that are stable across sibling
    /// recompositions. Nested scopes push; `exit_scope` pops.
    pub fn enter_scope(&mut self, key: &str) {
        if !self.current_scope.iter().any(|k| k == key) {
            self.scope_local_counters.insert(key.to_string(), 0);
        }
        self.current_scope.push(key.to_string());
        self.get_or_create_scope_id(key);
    }

    /// Exit the innermost scope. No-op if the stack is empty or the top does
    /// not match (defensive: never corrupt an outer scope).
    pub fn exit_scope(&mut self) {
        self.current_scope.pop();
    }

    /// RAII scope entry: pops on drop, so a panicking scope body cannot leave
    /// the scheduler stuck in the wrong scope (which previously leaked outer
    /// IDs into the global sequence).
    pub fn scope_guard<'a>(&'a mut self, key: &str) -> SchedulerScopeGuard<'a> {
        self.enter_scope(key);
        SchedulerScopeGuard { sched: self }
    }

    /// Panic-safe scope entry that does NOT hold a borrow: the guarded body
    /// (including nested `scope!`) can keep using the `Scheduler`. Used by
    /// the `scope!` macro.
    pub fn scope_guard_raw(&mut self, key: &str) -> SchedulerScopeGuardRaw {
        let ptr = self as *mut Scheduler;
        unsafe { SchedulerScopeGuardRaw::enter(ptr, key) }
    }

    fn get_or_create_scope_id(&mut self, key: &str) -> u32 {
        if let Some(&id) = self.scope_key_to_id.get(key) {
            id
        } else {
            let id = self.next_scope_id;
            self.next_scope_id += 1;
            self.scope_key_to_id.insert(key.to_string(), id);
            id
        }
    }

    pub fn id(&mut self) -> u64 {
        if let Some(key) = self.current_scope.last().cloned() {
            let scope_id = self.scope_key_to_id.get(&key).copied().unwrap_or(0);
            let local = self.scope_local_counters.get_mut(&key).unwrap();
            let id = *local;
            *local += 1;
            (scope_id as u64) << 32 | id as u64
        } else {
            // Global sequential ID (for non-scoped views)
            let id = self.next_id;
            self.next_id += 1;
            id
        }
    }

    pub fn id_count(&self) -> u64 {
        self.next_id - 1
    }

    /// True while the named physical key is in the polled snapshot.
    pub fn is_held(&self, key: PhysicalKey) -> bool {
        self.held_keys.contains(&key)
    }

    /// Snapshot the current ID counter (before executing a scope body) so the
    /// delta can be computed after the body returns.
    pub fn snapshot_id(&self) -> u64 {
        self.next_id
    }

    /// Advance the ID counter by `count` without assigning IDs.
    /// Used by the scope! macro to reserve IDs for a cached scope subtree.
    pub fn advance_id(&mut self, count: u32) {
        self.next_id += count as u64;
    }

    /// Number of IDs assigned since `prev_id` (the value returned by
    /// `snapshot_id()` before executing a scope body).
    pub fn ids_used_since(&self, prev_id: u64) -> u32 {
        (self.next_id - prev_id) as u32
    }

    pub fn gc_scope_state(&mut self, live_keys: &rustc_hash::FxHashSet<String>) {
        self.scope_key_to_id
            .retain(|key, _| live_keys.contains(key));
        self.scope_local_counters
            .retain(|key, _| live_keys.contains(key));
    }
}

/// RAII guard from [`Scheduler::scope_guard`]. Pops the scope on drop.
pub struct SchedulerScopeGuard<'a> {
    sched: &'a mut Scheduler,
}

impl Drop for SchedulerScopeGuard<'_> {
    fn drop(&mut self) {
        self.sched.exit_scope();
    }
}

/// Panic-safe scope guard that does NOT hold a borrow across the body.
///
/// The `scope!` macro uses this (not [`SchedulerScopeGuard`]) so the guarded
/// body, including nested `scope!` invocations, can keep using the
/// `Scheduler` normally. At drop time (normal or unwind) no other borrows of
/// the scheduler are live, since the body has ended.
pub struct SchedulerScopeGuardRaw {
    sched: *mut Scheduler,
}

impl SchedulerScopeGuardRaw {
    /// # Safety
    /// `sched` must point to a valid `Scheduler` for the guard's lifetime,
    /// and the scheduler must not be used while the guard is being dropped
    /// (guaranteed when the guard outlives the body it protects).
    pub unsafe fn enter(sched: *mut Scheduler, key: &str) -> Self {
        unsafe {
            (*sched).enter_scope(key);
        }
        Self { sched }
    }
}

impl Drop for SchedulerScopeGuardRaw {
    fn drop(&mut self) {
        unsafe {
            (*self.sched).exit_scope();
        }
    }
}

impl Scheduler {
    pub fn repose<F>(
        &mut self,
        mut build_root: F,
        layout_paint: impl Fn(&View, (u32, u32)) -> (Scene, Vec<HitRegion>, Vec<SemNode>),
    ) -> Frame
    where
        F: FnMut(&mut Scheduler) -> View,
    {
        let guard = ComposeGuard::begin();
        let root = guard.scope.run(|| build_root(self));
        let (scene, hits, sem) = layout_paint(&root, self.size);

        let focus_chain: Vec<u64> = hits.iter().filter(|h| h.focusable).map(|h| h.id).collect();

        let live_scope_keys = guard.live_scope_keys();
        let frame = Frame {
            scene,
            hit_regions: hits,
            semantics_nodes: sem,
            focus_chain,
        };
        drop(guard);
        self.gc_scope_state(&live_scope_keys);
        frame
    }
}

/// Test helper: full composer reset. Production shutdown should call
/// `shutdown_composition`.
#[cfg(test)]
pub fn clear_composer() {
    shutdown_composition();
}

#[cfg(test)]
mod focus_trap_tests {
    use super::*;

    fn region(id: u64, x: f32, group: Option<u64>) -> HitRegion {
        HitRegion {
            id,
            rect: Rect {
                x,
                y: 0.0,
                w: 10.0,
                h: 10.0,
            },
            focus_group_id: group,
            ..Default::default()
        }
    }

    #[test]
    fn arrows_stay_inside_group() {
        // Dialog buttons 2,3 in group 9; background button 4 outside;
        // outsider 1 sits left of button 2 and would win unconstrained.
        let chain = vec![1, 2, 3, 4];
        let regions = vec![
            region(1, 0.0, None),
            region(2, 20.0, Some(9)),
            region(3, 40.0, Some(9)),
            region(4, 60.0, None),
        ];
        assert_eq!(
            spatial_focus_next(&chain, &regions, Some(2), FocusDirection::Left),
            None,
            "outsider 1 is left of 2 but outside the group: trapped"
        );
        assert_eq!(
            spatial_focus_next(&chain, &regions, Some(2), FocusDirection::Right),
            Some(3)
        );
        assert_eq!(
            spatial_focus_next(&chain, &regions, Some(3), FocusDirection::Left),
            Some(2)
        );
        assert_eq!(
            spatial_focus_next(&chain, &regions, Some(1), FocusDirection::Right),
            Some(2),
            "ungrouped focus still sees the full chain"
        );
    }

    #[test]
    fn tab_cycles_inside_group() {
        let chain = vec![1, 2, 3, 4];
        let regions = vec![
            region(1, 0.0, None),
            region(2, 20.0, Some(9)),
            region(3, 40.0, Some(9)),
            region(4, 60.0, None),
        ];
        let mut fm = FocusManager::new(chain, Some(2));
        fm.hit_regions = regions;
        assert_eq!(fm.move_tab(false), Some(3));
        assert_eq!(fm.move_tab(false), Some(2));
        assert_eq!(fm.move_tab(true), Some(3));
    }

    #[test]
    fn tab_from_outside_can_enter_group() {
        let chain = vec![1, 2, 3, 4];
        let regions = vec![
            region(1, 0.0, None),
            region(2, 20.0, Some(9)),
            region(3, 40.0, Some(9)),
            region(4, 60.0, None),
        ];
        let mut fm = FocusManager::new(chain, Some(1));
        fm.hit_regions = regions;
        assert_eq!(fm.move_tab(false), Some(2));
        let mut fm = FocusManager::new(vec![1, 2, 3, 4], Some(1));
        fm.hit_regions = vec![
            region(1, 0.0, None),
            region(2, 20.0, Some(9)),
            region(3, 40.0, Some(9)),
            region(4, 60.0, None),
        ];
        assert_eq!(fm.move_tab(true), Some(4));
    }

    #[test]
    fn empty_group_never_moves() {
        let chain = vec![1, 4];
        let regions = vec![region(1, 0.0, None), region(4, 60.0, None)];
        let mut fm = FocusManager::new(chain, Some(1));
        fm.hit_regions = regions.clone();
        assert_eq!(fm.move_tab(false), Some(4));
        let chain = vec![1, 2, 4];
        let regions = vec![
            region(1, 0.0, None),
            region(2, 20.0, Some(77)),
            region(4, 60.0, None),
        ];
        let mut fm = FocusManager::new(chain, Some(2));
        fm.hit_regions = regions;
        assert_eq!(fm.move_tab(false), Some(2));
        assert_eq!(
            spatial_focus_next(&fm.chain, &fm.hit_regions, Some(2), FocusDirection::Right),
            None
        );
    }
}