uzor-framework 1.5.35

uzor app engine: one kernel of single-writer engines driven by a typed input bus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
//! InputEngine: focus scopes, pointer capture, cook, hover / press / click,
//! text and IME, caret blink (design §3.4).
//!
//! The one writer of per-window interaction state. Each window has one
//! library [`InputCoordinator`] as its storage (registrations, hit index,
//! [`TextFieldStore`], widget state), one
//! library [`CookState`] for event-level cooking, the pointer accumulator
//! the coordinator's next frame is fed from, the focus-scope stack, the
//! pointer capture and the caret-blink phase. Pure and deterministic: every
//! time-dependent op carries the host clock.
//!
//! ## Coordinator access
//!
//! State-mutating coordinator methods (`begin_frame`, `end_frame`,
//! `set_focus`, `clear_focus`, `focus_next` / `focus_prev`,
//! `grab_pointer` / `release_pointer`, `on_char`, `on_key`, `process_*`,
//! `push_layer` / `pop_layer`, `set_cursor_pos`) live on
//! [`CoordinatorDriver`](uzor::input::driver::CoordinatorDriver). This
//! engine is the one writer; ban F7 keeps that trait out of every other
//! framework module except `kernel/`. [`InputEngine::registrar`] hands
//! compose a `&mut InputCoordinator` for registration and reads only.
//! `focus_text_field` and `text_fields_mut` stay inherent (L-F1 does not
//! move them).
//!
//! ## Pointer (routing, design §4.3)
//!
//! - [`InputOp::Pointer`] is step 1: the engine's `CookState` counts clicks
//!   (single / double / triple within `DOUBLE_CLICK_WINDOW_S` and
//!   `MULTI_CLICK_MAX_DIST_PX`) and arms drags past `DRAG_THRESHOLD_PX`,
//!   and the answer says whether a [`Capture`] owns the event (step 2). A
//!   capture bypasses every hit test until the button is released (or the
//!   OS cancels the gesture); the release itself still goes to the owner.
//! - [`InputOp::Deliver`] is step 5: an event nothing above claimed enters
//!   the coordinator's next-frame input (press / release edges; positions
//!   always follow the pointer). Claimed presses never reach content. A
//!   text-field drag writes the store selection on the press and on each
//!   armed move: paint reads that store before `end_frame`, which only
//!   commits the range on release.
//! - [`InputOp::BeginFrame`] feeds the accumulated input to the coordinator
//!   with `InputState::time` stamped from the host clock, so the
//!   coordinator's own cook (fed in `end_frame`) reports real
//!   `double_clicked` / `triple_clicked`. [`InputOp::EndFrame`] evaluates
//!   the frame's registrations into hover and this frame's clicks.
//!
//! ## Focus scopes (H2 §3)
//!
//! A stack of `{ owner, members, saved focus }`. Pushing saves and clears
//! the current focus; while a scope is active, focus can only move to one
//! of its members (`FocusOp::Set` outside is a no-op, Tab / Shift+Tab cycle
//! the members registered this frame in list order); popping the active
//! scope with `restore` puts the saved focus back (a saved text field
//! keeps its engagement), without `restore` clears it. Popping a scope
//! below the top hands its saved focus to the scope above it. A click
//! that focuses a text field outside the active scope is reverted at
//! `EndFrame`, so focus is always inside the active scope. With no scope,
//! Tab cycles every focusable widget (the coordinator's global order).
//!
//! ## Text and IME
//!
//! Key step 1 ([`InputOp::Key`]): with a focused text field, its editing
//! chords (characters, Backspace / Delete, arrows with Shift / Ctrl word
//! movement, Home / End, Ctrl+A / C / X / V, Enter) are consumed before any
//! keymap binding; Tab / Shift+Tab move focus. Everything else is passed on
//! ([`InputEffect::KeyPassed`]); Escape is never consumed here, so an
//! overlay can close on it (step 2). IME preedit goes to
//! `TextFieldStore::preedit_set` (an overlay span, never in the buffer);
//! commit to `ime_commit`. Copy / cut report [`InputEffect::CopyText`]
//! (masked fields never copy); paste asks the host with
//! [`InputEffect::NeedPaste`] under an engine-minted ticket (at or above
//! [`INPUT_TICKET_BASE`]) and inserts the [`InputOp::Clipboard`] answer if
//! the same field is still focused. The IME caret area and the IME-allowed
//! flag are reported only when they change.
//!
//! ## Clipboard for custom widgets
//!
//! One widget-facing contract on every host. Paste: the platform gesture's
//! text ([`InputOp::Paste`], from `InputEvent::Paste` — the web host's DOM
//! `paste` event) goes to the focused text field, else to the app as
//! `UnhandledInput::Paste` ([`InputEffect::Pasted`]). Ctrl/Cmd+V with no
//! field focused reads under an engine ticket like a field paste; a native
//! host answers from the clipboard crate, the web host leaves it to the
//! paste event of the same gesture (no `readText` permission prompt, no
//! second insert: the paste settles the read). Copy / cut: the focused
//! custom widget sets its answer ahead with `ClipboardCmd::Offer`; Ctrl/Cmd+C
//! or X with no field and no page selection copies it
//! ([`InputEffect::CopyText`]) and still passes the key on. The web host
//! also writes the offer in the DOM `copy` / `cut` event (same gesture).
//! A focused `BlackboxPanel` owns Ctrl/Cmd+A (no page-text escalation).
//!
//! Manual check (web): focus a non-field custom widget, put text on the OS
//! clipboard, press Ctrl+V — the app gets `UnhandledInput::Paste` with it;
//! in a text field the text lands once. Offer "x", press Ctrl+C, paste
//! elsewhere: "x".
//!
//! ## Caret blink
//!
//! While a text field is focused and engaged (the user clicked or typed
//! into it) and the window has OS focus, the engine keeps one deadline
//! armed at the next blink edge ([`InputEffect::CaretDeadline`]; the kernel
//! arms `TimerOwner::CaretBlink { win }`). Visibility is the store's
//! `cursor_visible(now_ms)` (500 ms phases) anchored at the last caret
//! change: any edit, caret move, selection, preedit or focus change
//! restarts the phase visible. At each edge ([`InputEngine::tick`]) the
//! engine flips visibility and asks for a repaint of only that field
//! ([`InputEffect::InvalidateField`] with the field's last drawn rect; the
//! kernel maps it to the region containing it). Blur, loss of window
//! focus, un-engagement or the field being unregistered disarms it.
//!
//! ## Plain-text selection (T2)
//!
//! One selection owner per window, held here: selectable plain text has no
//! store (unlike text fields), so the app reports each selectable widget's
//! content and line geometry every frame through
//! [`InputEngine::update_selectable`] (the compose-phase door, mirroring
//! `TextFieldStore::update_field`; not revisioned — the change is evaluated
//! at [`InputOp::EndFrame`]). A widget not reported this frame stops being
//! selectable and its selection drops. The owner state is a small
//! `Vec<(WidgetId, TextSelection)>` — usually one entry; a panel / window
//! Ctrl+A escalation selects several widgets at once.
//!
//! A press on a selectable widget records the char under the pointer as
//! the drag anchor; no pointer capture is taken — the cook state tracks
//! the press window-wide, exactly the mechanism text fields use, and
//! `char_at_point` clamps out-of-rect positions to the line ends. While
//! the press is armed (or its release just ended the drag) the selection
//! extends anchor → current pointer char every frame, so the highlight is
//! live during the drag. A release that was not a drag and lands on the
//! same selectable widget is a click: the selection collapses / expands to
//! word / line by the press sequence's click count (the engine's own
//! `CookState`, not the coordinator's click reporting — a label registers
//! `Sense::HOVER` + `select`, no `click` bit, and must not start
//! swallowing clicks). A press anywhere else clears the selection.
//! Escape and focus changes do not clear it (browser-like).
//!
//! Keys, no focused text field: Ctrl+C with a non-empty selection reports
//! [`InputEffect::CopyText`] (the same conduction as a field copy — the
//! kernel enqueues `WindowCommand::ClipboardWrite`); with nothing selected
//! the key routes on. Ctrl+A selects all with escalation
//! widget → panel → window: the panel step takes every selectable whose
//! rect is inside the nearest ancestor registered as `Panel` /
//! `BlackboxPanel` (via `widget_parent`), the window step every selectable
//! in the window; multi-widget selections copy in reading order
//! (top-left, newline-joined). The escalation level resets on any
//! pointer-driven selection.
//!
//! Every selection change repaints through the existing
//! [`InputEffect::InvalidateField`] with the widget's rect, and is
//! revisioned (the map is observable through
//! [`InputEngineView::selections`]).
//!
//! Out of scope (recorded for the owner): word-granularity drag after a
//! double click, Shift+click extend, drag-and-drop of selected text.
//!
//! ## Revision
//!
//! Bumped exactly when observable state changes: the window set, focus,
//! scopes, capture, hover, pressed, this frame's clicks, the focused
//! field's caret (text, cursor, selection, preedit, engagement), caret
//! visibility and the plain-text selections. Pointer positions, cook
//! bookkeeping, IME bookkeeping and a pending paste are not revisioned
//! (they never appear in the snapshot).

use crate::types::vecmap::VecMap;
use std::collections::HashMap;
use std::fmt;

use smallvec::SmallVec;
use uzor::input::core::cook::CookState;
use uzor::input::driver::CoordinatorDriver;
use uzor::input::text::selection::{char_at_point, SelectionLine, TextSelection};
use uzor::input::{
    InputCoordinator, InputState, KeyCode, KeyPress, ModifierKeys, MouseButton, TextAction,
    TextFieldStore, WidgetKind,
};
use uzor::{Rect, WidgetId};

use crate::types::bus::{
    ClipboardResult, ImeInput, KeyInput, KeyState, PointerInput, WheelDelta, WheelInput,
};
use crate::types::ids::{Revision, ScopeId, Seconds, Ticket, WindowId};
use crate::types::intent::TextIntent;
use crate::types::ops::{
    Capture, CookedPointer, FocusOp, InputEffect, InputOp, PointerTarget, ScopeOwner,
};
use crate::types::snapshot::InputView;

/// Effects of one InputEngine op or tick.
pub type InputEffects = SmallVec<[InputEffect; 2]>;

/// First clipboard ticket the engine mints for paste. App tickets stay
/// below it, so a `ClipboardResult` at or above it belongs to this engine.
pub const INPUT_TICKET_BASE: u64 = 1 << 63;

/// One caret blink phase (visible or hidden), the store's 500 ms.
// Caret blink cadence a host applies when painting text fields.
#[allow(dead_code)]
pub const CARET_BLINK_INTERVAL: Seconds = Seconds(0.5);

const CARET_BLINK_MS: u64 = 500;

/// Logical pixels per wheel line, for pixel-unit wheel deltas (the same
/// factor the desktop input bridge uses); the coordinator counts lines.
const WHEEL_PIXELS_PER_LINE: f64 = 20.0;

// ---------------------------------------------------------------------------
// Per-window state
// ---------------------------------------------------------------------------

/// Pointer input gathered between two frames; becomes the coordinator's
/// `InputState` at `BeginFrame`.
#[derive(Clone, Debug, Default)]
struct PointerAccum {
    pos: Option<(f64, f64)>,
    prev_pos: Option<(f64, f64)>,
    button_down: Option<MouseButton>,
    clicked: Option<MouseButton>,
    /// Secondary-button release not yet read by a frame (context menus).
    context: Option<(f64, f64)>,
    mods: ModifierKeys,
    scroll: (f64, f64),
    /// The scroll came (at least partly) as pixel deltas (trackpad / smooth wheel).
    scroll_precise: bool,
    /// The scroll came from a touch pan or its fling.
    scroll_touch: bool,
}

/// The focus the engine restores when a scope closes.
#[derive(Clone, Debug, PartialEq, Eq)]
struct SavedFocus {
    id: WidgetId,
    /// The saved widget was an engaged text field.
    engaged: bool,
}

#[derive(Clone, Debug)]
struct FocusScope {
    owner: ScopeOwner,
    members: Vec<WidgetId>,
    saved: Option<SavedFocus>,
}

/// Plain selectable text reported for one frame through the compose door
/// [`InputEngine::update_selectable`].
#[derive(Clone, Debug)]
struct SelectableText {
    text: String,
    lines: Vec<SelectionLine>,
}

/// The compose-phase sink a hook reports its selectable plain text into (the `Widgets`
/// face): the DOM's "every text node is selectable" made explicit — a widget reported here
/// gets press-drag / double / triple-click selection and Ctrl+C copy from the input engine.
#[derive(Clone, Debug, Default)]
pub struct Selectables(HashMap<WidgetId, SelectableText>, HashMap<WidgetId, WidgetId>);

impl Selectables {
    /// Report one selectable text widget for this frame: its text and, per wrapped line,
    /// the char range, origin and glyph boundaries (`SelectionLine`).
    pub fn report(&mut self, widget: impl Into<WidgetId>, text: impl Into<String>, lines: Vec<SelectionLine>) {
        self.0.insert(widget.into(), SelectableText { text: text.into(), lines });
    }
    /// A press / click on `member` (a hit region, e.g. one wrapped line or one
    /// bubble) acts on the selectable `owner`: one selection spans many regions,
    /// like a DOM selection dragged across several elements of one container.
    pub fn alias(&mut self, member: impl Into<WidgetId>, owner: impl Into<WidgetId>) {
        self.1.insert(member.into(), owner.into());
    }
    fn contains_key(&self, w: &WidgetId) -> bool {
        self.0.contains_key(w)
    }
}

/// A press that began on a selectable widget: the selection drag anchor.
#[derive(Clone, Debug)]
struct PressSel {
    widget: WidgetId,
    anchor: usize,
}

/// Where a Ctrl+A escalation stands for its widget.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EscLevel {
    /// Last select-all covered only the widget itself.
    Widget,
    /// … every selectable inside the nearest panel ancestor.
    Panel,
    /// … every selectable in the window.
    Window,
}

/// Everything about the focused text field whose change restarts the
/// blink phase (geometry is deliberately not part of it).
#[derive(Clone, Debug, PartialEq, Eq)]
struct CaretKey {
    field: WidgetId,
    engaged: bool,
    text: String,
    cursor: usize,
    selection: Option<usize>,
    preedit: String,
    preedit_cursor: usize,
}

/// The engine's own focus record: the widget the view reports.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Focused {
    id: WidgetId,
    /// Focused through the text store (a registered text field).
    field: bool,
}

struct PerWindowInput {
    coord: InputCoordinator,
    /// Per-widget persistent typed state (scroll offsets, expand flags);
    /// the compose-phase door for the app hook's `Widgets` face (design
    /// §3.4 names it here; F3 had no consumer, F7 does).
    states: uzor::app_context::StateRegistry,
    cook: CookState,
    pointer: PointerAccum,
    capture: Option<Capture>,
    scopes: Vec<FocusScope>,
    focus: Option<Focused>,
    hover: Option<WidgetId>,
    pressed: Option<WidgetId>,
    clicked: SmallVec<[(WidgetId, u8); 2]>,
    os_focused: bool,
    caret: Option<CaretKey>,
    blink_anchor_ms: u64,
    caret_visible: bool,
    armed: Option<Seconds>,
    ime_area: Option<Rect>,
    ime_allowed: bool,
    /// An engine-minted paste read in flight: the field it was for, or
    /// `None` (no text field: the answer goes to the app as pasted text).
    pending_paste: Option<(Ticket, Option<WidgetId>)>,
    /// The app's copy offer (`ClipboardCmd::Offer`).
    offer: Option<String>,
    // Plain-text selection (T2). `selectables` is last completed frame's
    // reported set (read by pointer ops); the compose door fills
    // `reported` and EndFrame swaps them.
    selectables: HashMap<WidgetId, SelectableText>,
    /// Hit regions acting on a selectable (last completed frame's `Selectables::alias`).
    sel_alias: HashMap<WidgetId, WidgetId>,
    reported: Selectables,
    selections: Vec<(WidgetId, TextSelection)>,
    press_sel: Option<PressSel>,
    drag_ended: bool,
    escalation: Option<(WidgetId, EscLevel)>,
    /// `:focus-visible` modality: a non-modifier key press turns it on, a
    /// pointer press turns it off; programmatic focus keeps the current one.
    focus_visible: bool,
    /// Clicks from Enter / Space on a focused control, joined to the next
    /// `EndFrame`'s clicks.
    key_clicks: Vec<WidgetId>,
    /// The control a Space press armed; its release activates it.
    space_armed: Option<WidgetId>,
}

/// Which keys activate a focused widget of `kind`, as `(Enter, Space)`,
/// matching the DOM: a `<button>` clicks on Enter press and Space release,
/// a link on Enter only, a checkbox / radio / switch on Space only.
fn activation(kind: Option<WidgetKind>) -> (bool, bool) {
    use WidgetKind as K;
    match kind {
        Some(K::Link) => (true, false),
        Some(K::Checkbox | K::Radio | K::Toggle) => (false, true),
        Some(K::Button | K::CloseButton | K::ChromeTab | K::DropdownTrigger | K::Item | K::ColorSwatch | K::Custom) | None => (true, true),
        Some(_) => (false, false),
    }
}

impl PerWindowInput {
    fn new() -> Self {
        Self {
            coord: InputCoordinator::new(),
            states: uzor::app_context::StateRegistry::new(),
            cook: CookState::default(),
            pointer: PointerAccum::default(),
            capture: None,
            scopes: Vec::new(),
            focus: None,
            hover: None,
            pressed: None,
            clicked: SmallVec::new(),
            // A window the host just created is assumed focused until the
            // host says otherwise (not every host sends the initial echo).
            os_focused: true,
            caret: None,
            blink_anchor_ms: 0,
            caret_visible: false,
            armed: None,
            ime_area: None,
            ime_allowed: false,
            pending_paste: None,
            offer: None,
            selectables: HashMap::new(),
            sel_alias: HashMap::new(),
            reported: Selectables::default(),
            selections: Vec::new(),
            press_sel: None,
            drag_ended: false,
            escalation: None,
            focus_visible: false,
            key_clicks: Vec::new(),
            space_armed: None,
        }
    }

    // -- focus ----------------------------------------------------------------

    /// `id` may take focus: no scope is active, or it is a member of the
    /// active one.
    fn allowed(&self, id: &WidgetId) -> bool {
        self.scopes.last().is_none_or(|s| s.members.contains(id))
    }

    /// Focus `id` in the coordinator (text fields through the store, which
    /// also syncs widget focus; anything else blurs the store). No guard.
    fn focus_raw(&mut self, id: WidgetId) {
        let field = self.coord.text_fields().has_field(&id);
        if field && self.coord.text_fields().is_focused(&id) {
            // A click already focused the store (`begin_drag_at` runs
            // before this record). `focus()` on that same field clears
            // engagement, and the caret is drawn from the flag.
            self.coord.set_focus(id.clone());
        } else if field {
            self.coord.focus_text_field(&id);
        } else {
            self.coord.set_focus(id.clone());
        }
        self.focus = Some(Focused { id, field });
    }

    fn clear_raw(&mut self) -> bool {
        let had = self.focus.is_some() || self.coord.text_fields().focused().is_some();
        self.coord.clear_focus();
        self.focus = None;
        had
    }

    fn focused_id(&self) -> Option<&WidgetId> {
        self.focus.as_ref().map(|f| &f.id)
    }

    /// Tab order candidates: the active scope's members registered this
    /// frame, in list order, without negative-`tabindex` ones.
    fn scoped_candidates(&self) -> Option<Vec<WidgetId>> {
        let scope = self.scopes.last()?;
        Some(
            scope
                .members
                .iter()
                .filter(|m| self.coord.widget_rect(m).is_some() && self.coord.tab_index(m) >= 0)
                .cloned()
                .collect(),
        )
    }

    /// Tab / Shift+Tab. `None` = there was nothing to move to.
    fn cycle(&mut self, forward: bool) -> Option<bool> {
        let before = self.focus.clone();
        match self.scoped_candidates() {
            Some(list) => {
                if list.is_empty() {
                    return None;
                }
                let n = list.len();
                let at = self
                    .focused_id()
                    .and_then(|f| list.iter().position(|m| m == f));
                let next = match (at, forward) {
                    (Some(i), true) => (i + 1) % n,
                    (None, true) => 0,
                    (Some(i), false) => (i + n - 1) % n,
                    (None, false) => n - 1,
                };
                if self.focused_id() != Some(&list[next]) {
                    self.focus_raw(list[next].clone());
                }
            }
            None => {
                if forward {
                    self.coord.focus_next();
                } else {
                    self.coord.focus_prev();
                }
                let target = self.coord.focused_widget().cloned()?;
                if self.focused_id() != Some(&target) || !self.store_matches_focus() {
                    self.focus_raw(target);
                }
            }
        }
        Some(self.focus != before)
    }

    /// The text store's focus agrees with the engine's record.
    fn store_matches_focus(&self) -> bool {
        let store = self.coord.text_fields().focused();
        match &self.focus {
            Some(f) if f.field => store == Some(&f.id),
            _ => store.is_none(),
        }
    }

    fn focus_op(
        &mut self,
        win: WindowId,
        op: FocusOp,
        next_scope: &mut u64,
        fx: &mut InputEffects,
    ) -> bool {
        match op {
            FocusOp::Set(id) => {
                if !self.allowed(&id) || self.focused_id() == Some(&id) {
                    return false;
                }
                self.focus_raw(id);
                true
            }
            FocusOp::Clear => self.clear_raw(),
            FocusOp::Next => self.cycle(true).unwrap_or(false),
            FocusOp::Prev => self.cycle(false).unwrap_or(false),
            FocusOp::PushScope { owner, members } => {
                if self.scopes.iter().any(|s| s.owner == owner) {
                    return self.set_members(&owner, members);
                }
                let saved = self.focus.as_ref().map(|f| SavedFocus {
                    engaged: f.field && self.coord.text_fields().is_engaged(&f.id),
                    id: f.id.clone(),
                });
                self.clear_raw();
                self.scopes.push(FocusScope {
                    owner: owner.clone(),
                    members,
                    saved,
                });
                *next_scope += 1;
                fx.push(InputEffect::ScopePushed {
                    win,
                    owner,
                    scope: ScopeId(*next_scope),
                });
                true
            }
            FocusOp::SetMembers { owner, members } => self.set_members(&owner, members),
            FocusOp::PopScope { owner, restore } => self.pop_scope(&owner, restore),
        }
    }

    fn set_members(&mut self, owner: &ScopeOwner, members: Vec<WidgetId>) -> bool {
        let Some(i) = self.scopes.iter().position(|s| &s.owner == owner) else {
            return false;
        };
        if self.scopes[i].members == members {
            return false;
        }
        self.scopes[i].members = members;
        let active = i + 1 == self.scopes.len();
        if active {
            if let Some(f) = self.focused_id().cloned() {
                if !self.allowed(&f) {
                    self.clear_raw();
                }
            }
        }
        true
    }

    fn pop_scope(&mut self, owner: &ScopeOwner, restore: bool) -> bool {
        let Some(i) = self.scopes.iter().position(|s| &s.owner == owner) else {
            return false;
        };
        let scope = self.scopes.remove(i);
        if i < self.scopes.len() {
            // A scope below the top closed: the scope above saved a focus
            // inside it, which is gone; it inherits the closed scope's.
            self.scopes[i].saved = scope.saved;
            return true;
        }
        self.clear_raw();
        if let (true, Some(saved)) = (restore, scope.saved) {
            if self.allowed(&saved.id) {
                self.focus_raw(saved.id.clone());
                if saved.engaged {
                    self.coord.text_fields_mut().engage(&saved.id);
                }
            }
        }
        true
    }

    /// After `end_frame`: accept a click-focus into a text field, revert
    /// one outside the active scope, and forget a field that disappeared.
    fn reconcile_focus(&mut self) -> bool {
        let store = self.coord.text_fields().focused().cloned();
        match (store, self.focus.clone()) {
            (Some(s), Some(f)) if f.field && s == f.id => false,
            (Some(s), _) if self.allowed(&s) => {
                self.coord.set_focus(s.clone());
                self.focus = Some(Focused { id: s, field: true });
                true
            }
            (Some(_), prev) => {
                // Clicked into a field the active scope does not contain.
                self.coord.text_fields_mut().blur();
                if let Some(f) = prev.filter(|f| f.field) {
                    let engaged = self.coord.text_fields().is_engaged(&f.id);
                    self.coord.focus_text_field(&f.id);
                    if engaged {
                        self.coord.text_fields_mut().engage(&f.id);
                    }
                }
                false
            }
            (None, Some(f)) if f.field => {
                // The focused field was unregistered or blurred.
                self.coord.clear_focus();
                self.focus = None;
                true
            }
            (None, _) => false,
        }
    }

    // -- pointer --------------------------------------------------------------

    fn set_capture(&mut self, capture: Option<Capture>) -> bool {
        if self.capture == capture {
            return false;
        }
        if let Some(Capture::Widget(_)) = &self.capture {
            self.coord.release_pointer();
        }
        if let Some(Capture::Widget(id)) = &capture {
            self.coord.grab_pointer(id.clone());
        }
        self.capture = capture;
        true
    }

    fn cook(&mut self, win: WindowId, now: Seconds, input: PointerInput) -> (bool, CookedPointer) {
        let t = now.get();
        let target = match &self.capture {
            Some(c) => PointerTarget::Captured(c.clone()),
            None => PointerTarget::HitTest,
        };
        let mut drag_started = false;
        let mut ended_drag = false;
        let mut changed = false;
        // Any press (content, chrome, dock) ends keyboard modality; the
        // ring it hides needs a repaint.
        if matches!(input, PointerInput::Down { .. }) && self.focus_visible {
            self.focus_visible = false;
            changed = true;
        }
        match input {
            PointerInput::Moved { pos, mods } => {
                self.pointer.pos = Some((pos.x, pos.y));
                self.pointer.mods = mods;
                drag_started = self.cook.motion(pos.x, pos.y).drag_started;
            }
            PointerInput::Down { pos, button, mods } => {
                self.pointer.pos = Some((pos.x, pos.y));
                self.pointer.mods = mods;
                // A second button during a held press does not restart it.
                if self.cook.press_origin.is_none() {
                    self.cook.press(pos.x, pos.y, button, t);
                }
            }
            PointerInput::Up { pos, button, mods } => {
                self.pointer.pos = Some((pos.x, pos.y));
                self.pointer.mods = mods;
                if self.cook.press_origin.map(|o| o.button) == Some(button) {
                    ended_drag = self.cook.release(pos.x, pos.y, button, t);
                    self.drag_ended |= ended_drag;
                    changed = self.set_capture(None);
                }
            }
            PointerInput::Entered | PointerInput::RawDelta { .. } => {}
            PointerInput::Left => self.pointer.pos = None,
            PointerInput::Cancelled => {
                // A cancelled press (a touch that became a scroll) ends a text drag.
                if self.coord.text_fields().drag_active() {
                    self.coord.text_fields_mut().on_drag_end();
                }
                self.cook.press_origin = None;
                self.cook.drag_armed = false;
                self.pointer.button_down = None;
                changed = self.set_capture(None);
                changed |= self.pressed.take().is_some();
                self.press_sel = None;
                self.drag_ended = false;
            }
        }
        // A drag starting on a pressed drag-sensitive widget captures the
        // pointer for it (design §4.3, routing step 2): from here every
        // event goes to the widget until pointer-up.
        if drag_started {
            let grab = self
                .pressed
                .clone()
                .filter(|id| self.coord.widget_sense(id).is_some_and(|s| s.drag));
            if let Some(id) = grab {
                changed = self.set_capture(Some(Capture::Widget(id)));
            }
        }
        let cooked = CookedPointer {
            win,
            input,
            click_count: self.cook.click_count,
            drag_armed: self.cook.drag_armed,
            drag_started,
            ended_drag,
            target,
        };
        (changed, cooked)
    }

    /// The content widget a pointer at `pos` goes to: the capturing widget,
    /// else the topmost hit of last frame's registrations.
    fn content_target(&self, pos: Option<(f64, f64)>) -> Option<WidgetId> {
        if let Some(Capture::Widget(id)) = &self.capture {
            return Some(id.clone());
        }
        let (x, y) = pos?;
        self.coord.hit_test_now(x, y)
    }

    fn deliver(
        &mut self,
        win: WindowId,
        input: PointerInput,
        fx: &mut InputEffects,
    ) -> (bool, Option<WidgetId>) {
        match input {
            PointerInput::Moved { pos, .. } => {
                self.pointer.pos = Some((pos.x, pos.y));
                // A held drag repaints so hooks see the moving pointer; so does a move
                // onto another widget (or off all of them), so hover paints without
                // waiting for the next unrelated input.
                let target = self.content_target(self.pointer.pos);
                let mut changed = self.pointer.button_down.is_some() || target != self.hover;
                // `cook` already armed this move. The highlight is the store
                // range, and the frame paints it before `end_frame`.
                if self.pointer.button_down == Some(MouseButton::Left)
                    && self.cook.drag_armed
                    && self.coord.text_fields().drag_active()
                {
                    self.coord.text_fields_mut().on_drag_move_xy(pos.x, pos.y);
                    changed = true;
                }
                (changed, target)
            }
            PointerInput::Down { pos, button, .. } => {
                self.pointer.pos = Some((pos.x, pos.y));
                self.pointer.button_down = Some(button);
                // A release no frame has evaluated yet belongs to the previous
                // gesture; carried into this press it would click whatever is
                // under the pointer now.
                self.pointer.clicked = None;
                let target = self.content_target(self.pointer.pos);
                let changed = self.pressed != target;
                self.pressed.clone_from(&target);
                let t = target.as_ref().map(|t| self.sel_owner(t));
                let sel_changed = self.press_down(win, t.as_ref(), pos.x, pos.y, fx);
                if button == MouseButton::Left {
                    self.arm_text_drag(target.as_ref(), pos.x, pos.y);
                } else if self.coord.text_fields().drag_active() {
                    self.coord.text_fields_mut().on_drag_end();
                }
                let blurred = self.blur_text_on_outside_press(target.as_ref());
                (changed | sel_changed | blurred, target)
            }
            PointerInput::Up { pos, button, .. } => {
                self.pointer.pos = Some((pos.x, pos.y));
                self.pointer.button_down = None;
                self.pointer.clicked = Some(button);
                if button == MouseButton::Right {
                    self.pointer.context = Some((pos.x, pos.y));
                }
                let target = self.content_target(self.pointer.pos);
                let _ = self.pressed.take();
                let t = target.as_ref().map(|t| self.sel_owner(t));
                let _ = self.release_select(win, t.as_ref(), fx);
                // A real drag keeps the range (`anchor != cursor`); a click
                // drops the degenerate one. `end_frame` then commits either
                // `select_drag` or `select_at_click_count`.
                if button == MouseButton::Left && self.coord.text_fields().drag_active() {
                    self.coord.text_fields_mut().on_drag_end();
                }
                // Always repaint on release: only a frame evaluates the click
                // (`pointer.clicked`), on any cadence.
                (true, target)
            }
            PointerInput::Entered
            | PointerInput::Left
            | PointerInput::Cancelled
            | PointerInput::RawDelta { .. } => (false, None),
        }
    }

    /// Press on a text field: place the caret and arm a drag so later moves
    /// extend the selection while the button is held. A double or triple
    /// click is left to `end_frame` (`select_at_click_count` selects the
    /// word or the line). Any other press ends a stale text drag so it
    /// cannot follow the pointer onto another control.
    fn arm_text_drag(&mut self, target: Option<&WidgetId>, x: f64, y: f64) {
        let field = match target {
            Some(id)
                if self.coord.widget_sense(id).is_some_and(|s| s.text)
                    && self.coord.text_fields().has_field(id) =>
            {
                Some(id.clone())
            }
            _ => None,
        };
        if let Some(id) = field {
            if self.cook.click_count <= 1 {
                self.coord.text_fields_mut().begin_drag_at_xy(id, x, y);
                return;
            }
        }
        if self.coord.text_fields().drag_active() {
            self.coord.text_fields_mut().on_drag_end();
        }
    }

    /// A press that misses every text field drops the caret. Paint reads
    /// focus before `end_frame`, so the store and the engine record have to
    /// be clear on the press itself.
    fn blur_text_on_outside_press(&mut self, target: Option<&WidgetId>) -> bool {
        let on_field = target.is_some_and(|id| {
            self.coord.text_fields().has_field(id)
                && self.coord.widget_sense(id).is_some_and(|s| s.text)
        });
        if on_field || self.coord.text_fields().focused().is_none() {
            return false;
        }
        self.coord.clear_focus();
        if self.focus.as_ref().is_some_and(|f| f.field) {
            self.focus = None;
        }
        true
    }

    /// A release on the same selectable widget the press began on, and
    /// the press never crossed the drag threshold: a click. The selection
    /// collapses / expands to word / line by the click count.
    fn release_select(
        &mut self,
        win: WindowId,
        target: Option<&WidgetId>,
        fx: &mut InputEffects,
    ) -> bool {
        if self.drag_ended {
            return false;
        }
        let Some(p) = self.press_sel.clone() else {
            return false;
        };
        if target != Some(&p.widget) {
            return false;
        }
        let Some(st) = self.selectables.get(&p.widget) else {
            return false;
        };
        let sel = TextSelection::for_click_count(&st.text, p.anchor, self.cook.click_count.max(1));
        let changed = self.set_selection(win, &p.widget, sel, fx);
        self.escalation = Some((p.widget, EscLevel::Widget));
        changed
    }

    fn wheel(&mut self, input: WheelInput) -> Option<WidgetId> {
        let (dx, dy) = match input.delta {
            WheelDelta::Lines { x, y } => (x, y),
            WheelDelta::Pixels { x, y } => {
                self.pointer.scroll_precise = true;
                (x / WHEEL_PIXELS_PER_LINE, y / WHEEL_PIXELS_PER_LINE)
            }
        };
        self.pointer.pos = Some((input.pos.x, input.pos.y));
        self.pointer.mods = input.mods;
        self.pointer.scroll.0 += dx;
        self.pointer.scroll.1 += dy;
        if let Some(Capture::Widget(id)) = &self.capture {
            return Some(id.clone());
        }
        self.coord.process_scroll(input.pos.x, input.pos.y)
    }

    // -- plain-text selection (T2) -------------------------------------------

    /// The selectable a hit widget acts on (itself unless aliased).
    fn sel_owner(&self, w: &WidgetId) -> WidgetId {
        self.sel_alias.get(w).unwrap_or(w).clone()
    }

    fn sel_get(&self, widget: &WidgetId) -> Option<TextSelection> {
        self.selections
            .iter()
            .find(|(w, _)| w == widget)
            .map(|(_, s)| *s)
    }

    fn sel_set(&mut self, widget: WidgetId, sel: TextSelection) -> bool {
        if let Some(slot) = self.selections.iter_mut().find(|(w, _)| *w == widget) {
            if slot.1 == sel {
                return false;
            }
            slot.1 = sel;
            return true;
        }
        self.selections.push((widget, sel));
        true
    }

    fn sel_remove(&mut self, widget: &WidgetId) -> bool {
        let before = self.selections.len();
        self.selections.retain(|(w, _)| w != widget);
        self.selections.len() != before
    }

    /// Set one widget's selection, repainting it on change.
    fn set_selection(
        &mut self,
        win: WindowId,
        widget: &WidgetId,
        sel: TextSelection,
        fx: &mut InputEffects,
    ) -> bool {
        if !self.sel_set(widget.clone(), sel) {
            return false;
        }
        fx.push(InputEffect::InvalidateField {
            win,
            rect: self.coord.widget_rect(widget),
        });
        true
    }

    /// Drop every selection, repainting on change.
    fn clear_selections(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
        if self.selections.is_empty() {
            return false;
        }
        for (w, _) in &self.selections {
            fx.push(InputEffect::InvalidateField {
                win,
                rect: self.coord.widget_rect(w),
            });
        }
        self.selections.clear();
        self.escalation = None;
        true
    }

    /// Selectable widget ids in reading order (top-left), for multi-widget
    /// select-all and copy concatenation.
    fn selectable_ids_by_row(&self) -> Vec<WidgetId> {
        let mut ids: Vec<(f64, f64, WidgetId)> = self
            .selectables
            .keys()
            .map(|w| {
                let r = self
                    .coord
                    .widget_rect(w)
                    .unwrap_or_else(|| Rect::new(0.0, 0.0, 0.0, 0.0));
                (r.y, r.x, w.clone())
            })
            .collect();
        uzor::sort::sort_by(&mut ids, |a, b| a.0.total_cmp(&b.0).then_with(|| a.1.total_cmp(&b.1)));
        ids.into_iter().map(|(_, _, w)| w).collect()
    }

    /// The selected text of every selected widget, reading order, newline
    /// joined; `None` when nothing (or only carets) is selected.
    fn selected_text_concat(&self) -> Option<String> {
        if self.selections.is_empty() {
            return None;
        }
        let mut parts: Vec<String> = Vec::new();
        for w in self.selectable_ids_by_row() {
            if let (Some(sel), Some(st)) = (self.sel_get(&w), self.selectables.get(&w)) {
                let s = sel.selected_text(&st.text);
                if !s.is_empty() {
                    parts.push(s.to_owned());
                }
            }
        }
        if parts.is_empty() {
            None
        } else {
            Some(parts.join("\n"))
        }
    }

    /// The rect of the nearest ancestor registered as `Panel` /
    /// `BlackboxPanel`, if any — the Ctrl+A escalation boundary.
    fn nearest_panel_rect(&self, widget: &WidgetId) -> Option<Rect> {
        let mut cur = self.coord.widget_parent(widget);
        while let Some(p) = cur {
            if matches!(
                self.coord.widget_kind(&p),
                Some(WidgetKind::Panel | WidgetKind::BlackboxPanel)
            ) {
                return self.coord.widget_rect(&p);
            }
            cur = self.coord.widget_parent(&p);
        }
        None
    }

    /// Select-all of every selectable whose rect is inside `rect`.
    fn select_in_rect(&mut self, win: WindowId, rect: &Rect, fx: &mut InputEffects) -> bool {
        let mut changed = false;
        for w in self.selectable_ids_by_row() {
            if let Some(r) = self.coord.widget_rect(&w) {
                let inside = r.x >= rect.x
                    && r.y >= rect.y
                    && r.x + r.width <= rect.x + rect.width
                    && r.y + r.height <= rect.y + rect.height;
                if inside {
                    if let Some(st) = self.selectables.get(&w) {
                        let sel = TextSelection::all(&st.text);
                        changed |= self.set_selection(win, &w, sel, fx);
                    }
                }
            }
        }
        changed
    }

    /// Select-all of every selectable in the window.
    fn select_everything(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
        let mut changed = false;
        for w in self.selectable_ids_by_row() {
            if let Some(st) = self.selectables.get(&w) {
                let sel = TextSelection::all(&st.text);
                changed |= self.set_selection(win, &w, sel, fx);
            }
        }
        changed
    }

    /// A press landed on `target` (`None` = empty space): anything selected
    /// that is not the target clears; a selectable target starts a press.
    fn press_down(
        &mut self,
        win: WindowId,
        target: Option<&WidgetId>,
        x: f64,
        y: f64,
        fx: &mut InputEffects,
    ) -> bool {
        let mut changed = false;
        if !target.is_some_and(|t| self.sel_get(t).is_some()) {
            changed |= self.clear_selections(win, fx);
        }
        self.press_sel = None;
        if let Some(t) = target {
            if let Some(st) = self.selectables.get(t) {
                let anchor = char_at_point(&st.lines, x, y);
                self.press_sel = Some(PressSel {
                    widget: t.clone(),
                    anchor,
                });
            }
        }
        changed
    }

    /// Selection bookkeeping at EndFrame: live drag extension, click
    /// selection, press-session cleanup, stale-widget pruning.
    fn selection_frame(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
        let mut changed = false;

        // Live drag: the press is armed past the threshold (or its release
        // just ended the drag) — extend the selection to the current
        // pointer char every frame, so the highlight is live.
        if let Some(p) = self.press_sel.clone() {
            if self.cook.drag_armed || self.drag_ended {
                if let (Some(st), Some((x, y))) =
                    (self.selectables.get(&p.widget), self.pointer.pos)
                {
                    let sel = TextSelection::new(p.anchor, char_at_point(&st.lines, x, y));
                    changed |= self.set_selection(win, &p.widget, sel, fx);
                }
            }
        }

        // Click selection happens at the release (Deliver Up), not here —
        // a label has no `click` sense, so the coordinator never reports
        // its clicks.

        // The press session ends when the button is up.
        if self.pointer.button_down.is_none() {
            self.press_sel = None;
            self.drag_ended = false;
        }

        // Prune: only widgets reported this frame stay selectable; their
        // selections drop with them.
        let fresh = std::mem::take(&mut self.reported);
        let gone: Vec<WidgetId> = self
            .selections
            .iter()
            .map(|(w, _)| w.clone())
            .filter(|w| !fresh.contains_key(w))
            .collect();
        if !gone.is_empty() {
            for w in &gone {
                fx.push(InputEffect::InvalidateField {
                    win,
                    rect: self.coord.widget_rect(w),
                });
                self.sel_remove(w);
            }
            if let Some((w, _)) = &self.escalation {
                if gone.contains(w) {
                    self.escalation = None;
                }
            }
            changed = true;
        }
        self.selectables = fresh.0;
        self.sel_alias = fresh.1;

        changed
    }

    /// Ctrl+A with no focused text field: select all, escalating widget →
    /// panel → window across repeated presses. `Some(changed)` = consumed;
    /// `None` = no selectable context (the key routes on).
    fn ctrl_a(&mut self, win: WindowId, fx: &mut InputEffects) -> Option<bool> {
        if let Some((w, level)) = self.escalation.clone() {
            let next = match level {
                EscLevel::Widget => match self.nearest_panel_rect(&w) {
                    Some(rect) => {
                        self.select_in_rect(win, &rect, fx);
                        EscLevel::Panel
                    }
                    None => {
                        self.select_everything(win, fx);
                        EscLevel::Window
                    }
                },
                EscLevel::Panel => {
                    self.select_everything(win, fx);
                    EscLevel::Window
                }
                EscLevel::Window => return Some(false),
            };
            self.escalation = Some((w, next));
            return Some(true);
        }
        // First press: the hovered selectable, else the single selection.
        let start = self
            .hover
            .clone()
            .filter(|h| self.selectables.contains_key(h))
            .or_else(|| (self.selections.len() == 1).then(|| self.selections[0].0.clone()));
        let w = start?;
        let st = self.selectables.get(&w)?;
        let sel = TextSelection::all(&st.text);
        let changed = self.set_selection(win, &w, sel, fx);
        self.escalation = Some((w, EscLevel::Widget));
        Some(changed)
    }

    // -- frame ----------------------------------------------------------------

    fn begin_frame(&mut self, now: Seconds) -> bool {
        let mut state = InputState::new();
        state.pointer.pos = self.pointer.pos;
        state.pointer.prev_pos = self.pointer.prev_pos;
        state.pointer.button_down = self.pointer.button_down;
        state.pointer.clicked = self.pointer.clicked.take();
        state.modifiers = self.pointer.mods;
        state.scroll_delta = std::mem::take(&mut self.pointer.scroll);
        self.pointer.scroll_precise = false;
        self.pointer.scroll_touch = false;
        self.pointer.context = None;
        state.time = now.get();
        self.pointer.prev_pos = self.pointer.pos;
        self.coord.begin_frame(state);
        let had_clicks = !self.clicked.is_empty();
        self.clicked.clear();
        had_clicks
    }

    fn end_frame(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
        let mut hover = None;
        let mut clicked = SmallVec::new();
        for (id, r) in self.coord.end_frame() {
            if r.hovered {
                hover = Some(id.clone());
            }
            if r.clicked {
                let count = if r.triple_clicked {
                    3
                } else if r.double_clicked {
                    2
                } else {
                    1
                };
                clicked.push((id, count));
            }
        }
        for w in self.key_clicks.drain(..) {
            if !clicked.iter().any(|(c, _)| *c == w) {
                clicked.push((w, 1));
            }
        }
        let mut changed = hover != self.hover || clicked != self.clicked;
        self.hover = hover;
        self.clicked = clicked.clone();
        // A click on a focusable widget inside the active scope focuses
        // it (design §4.3, routing step 6); text fields reconcile below.
        let clicked_focus = clicked
            .iter()
            .map(|(id, _)| id.clone())
            .find(|id| self.allowed(id) && self.coord.widget_sense(id).is_some_and(|s| s.focus));
        if let Some(id) = clicked_focus {
            if self.focused_id() != Some(&id) {
                self.focus_raw(id);
                changed = true;
            }
        }
        changed |= self.selection_frame(win, fx);
        changed |= self.reconcile_focus();
        changed
    }

    // -- text -----------------------------------------------------------------

    /// The focused text field, when the store and the record agree.
    fn text_focus(&self) -> Option<WidgetId> {
        let f = self.focus.as_ref().filter(|f| f.field)?;
        self.coord
            .text_fields()
            .is_focused(&f.id)
            .then(|| f.id.clone())
    }

    fn key(
        &mut self,
        win: WindowId,
        input: KeyInput,
        next_ticket: &mut u64,
        fx: &mut InputEffects,
    ) -> bool {
        let m = input.mods;
        if input.code == KeyCode::Space && input.state == KeyState::Up {
            if let Some(w) = self.space_armed.take() {
                if self.focused_id() == Some(&w) {
                    self.key_clicks.push(w);
                    return true;
                }
            }
        }
        if input.state == KeyState::Up {
            fx.push(InputEffect::KeyPassed { win, key: input });
            return false;
        }
        if input.code != KeyCode::Unknown {
            self.focus_visible = true;
        }
        // Enter / Space on a focused control (not a text field) activate it.
        if matches!(input.code, KeyCode::Enter | KeyCode::Space) && !(m.ctrl || m.alt || m.meta) {
            if let Some(f) = self.focus.as_ref().filter(|f| !f.field).map(|f| f.id.clone()) {
                if self.coord.widget_sense(&f).is_some_and(|s| s.click) {
                    let (enter, space) = activation(self.coord.widget_kind(&f));
                    if input.code == KeyCode::Enter && enter {
                        self.key_clicks.push(f);
                        return true;
                    }
                    if input.code == KeyCode::Space && space {
                        self.space_armed = Some(f);
                        return false;
                    }
                }
            }
        }
        if input.code == KeyCode::Tab && !(m.ctrl || m.alt || m.meta) {
            return match self.cycle(!m.shift) {
                Some(changed) => changed,
                None => {
                    fx.push(InputEffect::KeyPassed { win, key: input });
                    false
                }
            };
        }
        let field = self.text_focus();
        let mut edit = editing_chord(&input);
        // A multiline field with laid lines moves its caret between them.
        if edit.is_none() && matches!(input.code, KeyCode::ArrowUp | KeyCode::ArrowDown) && !(m.ctrl || m.alt || m.meta) {
            if field.as_ref().is_some_and(|f| self.coord.text_fields().has_lines(f)) {
                edit = Some(Edit::Key(if input.code == KeyCode::ArrowUp { KeyPress::ArrowUp } else { KeyPress::ArrowDown }));
            }
        }
        let (field, edit) = match (field, edit) {
            (Some(f), Some(e)) => (f, e),
            // No focused text field: a plain-text selection takes the copy
            // / select-all chords; with nothing selected they route on.
            (None, Some(Edit::Copy)) => {
                if let Some(text) = self.selected_text_concat() {
                    fx.push(InputEffect::CopyText { win, text });
                } else {
                    // The focused custom widget's offer answers the copy;
                    // the key still reaches it.
                    if let Some(text) = self.offer.clone() {
                        fx.push(InputEffect::CopyText { win, text });
                    }
                    fx.push(InputEffect::KeyPassed { win, key: input });
                }
                return false;
            }
            (None, Some(Edit::Cut)) => {
                if let Some(text) = self.offer.clone() {
                    fx.push(InputEffect::CopyText { win, text });
                }
                fx.push(InputEffect::KeyPassed { win, key: input });
                return false;
            }
            (None, Some(Edit::Paste)) => {
                // No text field: the clipboard text goes to the app
                // (`UnhandledInput::Paste`). A web host answers with the DOM
                // paste event instead of a read.
                let ticket = Ticket(INPUT_TICKET_BASE.saturating_add(*next_ticket));
                *next_ticket = next_ticket.saturating_add(1);
                self.pending_paste = Some((ticket, None));
                fx.push(InputEffect::NeedPaste { win, ticket });
                return false;
            }
            (None, Some(Edit::Key(KeyPress::SelectAll)))
                if self.focus.as_ref().is_some_and(|f| !f.field && self.coord.widget_kind(&f.id).is_some_and(|k| k.is_blackbox())) =>
            {
                // A focused blackbox (terminal, remote view) owns its Ctrl+A.
                fx.push(InputEffect::KeyPassed { win, key: input });
                return false;
            }
            (None, Some(Edit::Key(KeyPress::SelectAll))) => {
                // `None` = no selectable context: the key routes on.
                return match self.ctrl_a(win, fx) {
                    Some(changed) => changed,
                    None => {
                        fx.push(InputEffect::KeyPassed { win, key: input });
                        false
                    }
                };
            }
            _ => {
                fx.push(InputEffect::KeyPassed { win, key: input });
                return false;
            }
        };
        let text_before = self.coord.text_fields().text(&field).to_owned();
        let changed_text = |action: &TextAction| matches!(action, TextAction::TextChanged(_));
        let mut changed = false;
        let multiline = self.coord.text_fields().field_state(&field).is_some_and(|s| s.config.multiline);
        let edit = match edit {
            Edit::Newline if multiline => Edit::Key(KeyPress::Paste("\n".into())),
            Edit::Newline => Edit::Submit,
            e => e,
        };
        match edit {
            Edit::Newline => {}
            Edit::Key(kp) => changed = changed_text(&self.coord.on_key(kp)),
            Edit::Char(c) => changed = changed_text(&self.coord.on_char(c)),
            Edit::Text(s) => {
                for c in s.chars() {
                    changed |= changed_text(&self.coord.on_char(c));
                }
            }
            Edit::Submit => {
                if let TextAction::Commit(_) = self.coord.on_char('\r') {
                    fx.push(InputEffect::Text(TextIntent::Submitted {
                        win,
                        field: field.clone(),
                    }));
                }
            }
            Edit::Copy => {
                // A field with no selection of its own (it kept focus while the user
                // selected page text): the page selection is what the user means.
                let own = if self.masked(&field) { None } else { self.coord.text_fields().copy_selection().filter(|t| !t.is_empty()) };
                if let Some(text) = own.or_else(|| self.selected_text_concat()) {
                    fx.push(InputEffect::CopyText { win, text });
                }
            }
            Edit::Cut => {
                if !self.masked(&field) {
                    if let Some(text) = self.coord.text_fields_mut().cut_selection(&field) {
                        fx.push(InputEffect::CopyText { win, text });
                    }
                }
            }
            Edit::Paste => {
                let ticket = Ticket(INPUT_TICKET_BASE.saturating_add(*next_ticket));
                *next_ticket = next_ticket.saturating_add(1);
                self.pending_paste = Some((ticket, Some(field.clone())));
                fx.push(InputEffect::NeedPaste { win, ticket });
            }
        }
        if changed || self.coord.text_fields().text(&field) != text_before {
            fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
        }
        // Text and caret changes are revisioned by `settle`.
        false
    }

    fn masked(&self, field: &WidgetId) -> bool {
        self.coord
            .text_fields()
            .field_state(field)
            .is_some_and(|s| s.config.masked)
    }

    fn ime(&mut self, win: WindowId, input: ImeInput, fx: &mut InputEffects) {
        let Some(field) = self.text_focus() else {
            return;
        };
        match input {
            ImeInput::Enabled => {}
            ImeInput::Preedit { text, cursor } => {
                let chars = |b: usize| text.get(..b).map(|s| s.chars().count());
                let at = cursor
                    .and_then(|(b, _)| chars(b))
                    .unwrap_or_else(|| text.chars().count());
                self.coord.text_fields_mut().preedit_set(&field, text, at);
            }
            ImeInput::Commit(text) => {
                let action = self.coord.text_fields_mut().ime_commit(&field, text);
                if let TextAction::TextChanged(_) = action {
                    fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
                }
            }
            ImeInput::Disabled => {
                self.coord
                    .text_fields_mut()
                    .preedit_set(&field, String::new(), 0);
            }
        }
    }

    fn clipboard(&mut self, win: WindowId, result: ClipboardResult, fx: &mut InputEffects) {
        let Some((ticket, field)) = self.pending_paste.clone() else {
            return;
        };
        if ticket != result.ticket {
            return;
        }
        self.pending_paste = None;
        let Some(text) = result.text.filter(|t| !t.is_empty()) else {
            return;
        };
        let Some(field) = field else {
            fx.push(InputEffect::Pasted { win, text });
            return;
        };
        let Some(focused) = self.text_focus() else {
            return;
        };
        if focused != field {
            return;
        }
        if let TextAction::TextChanged(_) = self.coord.on_key(KeyPress::Paste(text)) {
            fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
        }
    }

    /// The platform paste gesture's text: into the focused text field,
    /// else to the app. Settles an engine read still waiting for it (the
    /// web answers Ctrl/Cmd+V this way), so the text lands once.
    fn paste(&mut self, win: WindowId, text: String, fx: &mut InputEffects) {
        self.pending_paste = None;
        if text.is_empty() {
            return;
        }
        match self.text_focus() {
            Some(field) => {
                if let TextAction::TextChanged(_) = self.coord.on_key(KeyPress::Paste(text)) {
                    fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
                }
            }
            None => fx.push(InputEffect::Pasted { win, text }),
        }
    }

    // -- caret ----------------------------------------------------------------

    fn caret_key(&self) -> Option<CaretKey> {
        let store = self.coord.text_fields();
        let field = store.focused()?;
        let s = store.field_state(field)?;
        Some(CaretKey {
            field: field.clone(),
            engaged: s.engaged,
            text: s.text.clone(),
            cursor: s.cursor,
            selection: s.selection_start,
            preedit: s.preedit.clone(),
            preedit_cursor: s.preedit_cursor,
        })
    }

    fn field_rect(&self, field: &WidgetId) -> Option<Rect> {
        let (x, y, w, h) = self.coord.text_fields().field_state(field)?.last_rect?;
        Some(Rect::new(x, y, w, h))
    }

    /// The caret's rect: the char boundary at the cursor, full field height.
    fn caret_rect(&self, field: &WidgetId) -> Option<Rect> {
        let s = self.coord.text_fields().field_state(field)?;
        let (x, y, _, h) = s.last_rect?;
        let cx = s.last_char_positions.get(s.cursor).copied().unwrap_or(x);
        Some(Rect::new(cx, y, 1.0, h))
    }

    /// Re-derive caret blink, repaint, IME area and IME-allowed state after
    /// any op. Returns whether observable state changed.
    fn settle(&mut self, win: WindowId, now: Seconds, fx: &mut InputEffects) -> bool {
        let now_ms = millis(now);
        let key = self.caret_key();
        let key_changed = key != self.caret;
        if key_changed {
            if let Some(old) = &self.caret {
                if key.as_ref().map(|k| &k.field) != Some(&old.field) {
                    fx.push(InputEffect::InvalidateField {
                        win,
                        rect: self.field_rect(&old.field),
                    });
                }
            }
            self.caret = key;
            self.blink_anchor_ms = now_ms;
        }
        self.coord
            .text_fields_mut()
            .set_blink_time(self.blink_anchor_ms);
        let active = self.os_focused && self.caret.as_ref().is_some_and(|k| k.engaged);
        let visible = active && self.coord.text_fields().cursor_visible(now_ms);
        let visible_changed = visible != self.caret_visible;
        self.caret_visible = visible;
        if key_changed || visible_changed {
            if let Some(k) = &self.caret {
                fx.push(InputEffect::InvalidateField {
                    win,
                    rect: self.field_rect(&k.field),
                });
            }
        }
        let at = active.then(|| next_blink_edge(self.blink_anchor_ms, now_ms));
        if at != self.armed {
            self.armed = at;
            fx.push(InputEffect::CaretDeadline { win, at });
        }
        let field = self.caret.as_ref().map(|k| k.field.clone());
        let allowed = field.is_some();
        if allowed != self.ime_allowed {
            self.ime_allowed = allowed;
            fx.push(InputEffect::ImeAllowed { win, allowed });
        }
        let area = field.and_then(|f| self.caret_rect(&f));
        if area != self.ime_area {
            self.ime_area = area;
            if let Some(rect) = area {
                fx.push(InputEffect::ImeArea { win, rect });
            }
        }
        key_changed || visible_changed
    }
}

/// Host clock in whole milliseconds (the store's blink unit); negative and
/// NaN instants count as 0.
fn millis(t: Seconds) -> u64 {
    // `as` saturates: NaN -> 0, beyond u64::MAX -> u64::MAX.
    (t.get() * 1000.0).round().max(0.0) as u64
}

/// The first blink edge strictly after `now_ms` for a phase anchored at
/// `anchor_ms`.
fn next_blink_edge(anchor_ms: u64, now_ms: u64) -> Seconds {
    let phases = now_ms.saturating_sub(anchor_ms) / CARET_BLINK_MS + 1;
    let edge = anchor_ms.saturating_add(phases.saturating_mul(CARET_BLINK_MS));
    Seconds(edge as f64 / 1000.0)
}

/// What a key does to a focused text field.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Edit {
    Key(KeyPress),
    Char(char),
    Text(String),
    Submit,
    /// Shift+Enter: a newline in a multiline field, else a submit.
    Newline,
    Copy,
    Cut,
    Paste,
}

/// The editing chord a key press is for a focused text field, or `None`
/// when the field does not take it (it routes on to overlays and keymap).
fn editing_chord(input: &KeyInput) -> Option<Edit> {
    let m = input.mods;
    let cmd = m.ctrl || m.meta;
    let edit = match input.code {
        KeyCode::A if cmd => Edit::Key(KeyPress::SelectAll),
        KeyCode::Z if cmd && m.shift => Edit::Key(KeyPress::Redo),
        KeyCode::Z if cmd => Edit::Key(KeyPress::Undo),
        KeyCode::Y if m.ctrl && !m.alt => Edit::Key(KeyPress::Redo),
        KeyCode::C if cmd => Edit::Copy,
        KeyCode::X if cmd => Edit::Cut,
        KeyCode::V if cmd => Edit::Paste,
        KeyCode::ArrowLeft if cmd => Edit::Key(KeyPress::WordLeft),
        KeyCode::ArrowRight if cmd => Edit::Key(KeyPress::WordRight),
        KeyCode::Backspace if cmd => Edit::Key(KeyPress::DeleteWordBack),
        KeyCode::Delete if cmd => Edit::Key(KeyPress::DeleteWordForward),
        KeyCode::ArrowLeft if m.shift => Edit::Key(KeyPress::ShiftLeft),
        KeyCode::ArrowRight if m.shift => Edit::Key(KeyPress::ShiftRight),
        KeyCode::Home if m.shift => Edit::Key(KeyPress::ShiftHome),
        KeyCode::End if m.shift => Edit::Key(KeyPress::ShiftEnd),
        KeyCode::ArrowLeft => Edit::Key(KeyPress::ArrowLeft),
        KeyCode::ArrowRight => Edit::Key(KeyPress::ArrowRight),
        KeyCode::Home => Edit::Key(KeyPress::Home),
        KeyCode::End => Edit::Key(KeyPress::End),
        KeyCode::Backspace => Edit::Char('\x08'),
        KeyCode::Delete => Edit::Key(KeyPress::Delete),
        KeyCode::Enter if m.shift => Edit::Newline,
        KeyCode::Enter => Edit::Submit,
        // Other Ctrl / Cmd chords belong to the keymap; Ctrl+Alt is AltGr
        // on some layouts and does produce text.
        _ if cmd && !(m.ctrl && m.alt) => return None,
        _ => {
            let text: String = input
                .text
                .as_deref()?
                .chars()
                .filter(|c| !c.is_control())
                .collect();
            if text.is_empty() {
                return None;
            }
            match text.chars().count() {
                1 => Edit::Char(text.chars().next()?),
                _ => Edit::Text(text),
            }
        }
    };
    Some(edit)
}

// ---------------------------------------------------------------------------
// InputEngine
// ---------------------------------------------------------------------------

/// The InputEngine: see the module docs.
#[derive(Default)]
pub struct InputEngine {
    windows: VecMap<WindowId, PerWindowInput>,
    next_scope: u64,
    next_ticket: u64,
    rev: Revision,
}

impl fmt::Debug for InputEngine {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InputEngine")
            .field("windows", &self.windows.keys().collect::<Vec<_>>())
            .field("rev", &self.rev)
            .finish()
    }
}

impl InputEngine {
    /// An engine with no windows.
    pub fn new() -> Self {
        Self::default()
    }

    /// The only mutation door. Bumps the revision iff observable state
    /// changed (see the module docs).
    pub fn apply(&mut self, op: InputOp) -> InputEffects {
        let mut fx = InputEffects::new();
        let Self {
            windows,
            next_scope,
            next_ticket,
            rev,
        } = self;
        let changed = match op {
            InputOp::Open(win) => match windows.entry(win) {
                crate::types::vecmap::Entry::Occupied(_) => false,
                crate::types::vecmap::Entry::Vacant(slot) => {
                    slot.insert(PerWindowInput::new());
                    true
                }
            },
            InputOp::Close(win) => windows.remove(&win).is_some(),
            InputOp::WindowFocus { win, focused, now } => match windows.get_mut(&win) {
                Some(w) => {
                    w.os_focused = focused;
                    w.settle(win, now, &mut fx)
                }
                None => false,
            },
            InputOp::Pointer { win, now, input } => match windows.get_mut(&win) {
                Some(w) => {
                    let (changed, cooked) = w.cook(win, now, input);
                    fx.push(InputEffect::Pointer(cooked));
                    changed
                }
                None => false,
            },
            InputOp::Deliver { win, input } => match windows.get_mut(&win) {
                Some(w) => {
                    let (changed, target) = w.deliver(win, input, &mut fx);
                    fx.push(InputEffect::Content { win, target, changed });
                    changed
                }
                None => false,
            },
            InputOp::Wheel { win, input, touch } => {
                if let Some(w) = windows.get_mut(&win) {
                    w.pointer.scroll_touch |= touch;
                    let target = w.wheel(input);
                    let changed = target.is_some();
                    fx.push(InputEffect::Content { win, target, changed });
                }
                false
            }
            InputOp::Key { win, now, input } => match windows.get_mut(&win) {
                Some(w) => {
                    let changed = w.key(win, input, next_ticket, &mut fx);
                    w.settle(win, now, &mut fx) | changed
                }
                None => false,
            },
            InputOp::Ime { win, now, input } => match windows.get_mut(&win) {
                Some(w) => {
                    w.ime(win, input, &mut fx);
                    w.settle(win, now, &mut fx)
                }
                None => false,
            },
            InputOp::Context { win, pos } => match windows.get_mut(&win) {
                Some(w) => {
                    w.pointer.context = Some((pos.x, pos.y));
                    true
                }
                None => false,
            },
            InputOp::Paste { win, now, text } => match windows.get_mut(&win) {
                Some(w) => {
                    w.paste(win, text, &mut fx);
                    w.settle(win, now, &mut fx)
                }
                None => false,
            },
            InputOp::Offer { win, text } => {
                if let Some(w) = windows.get_mut(&win) {
                    w.offer = text;
                }
                false
            }
            InputOp::Clipboard { win, now, result } => match windows.get_mut(&win) {
                Some(w) => {
                    w.clipboard(win, result, &mut fx);
                    w.settle(win, now, &mut fx)
                }
                None => false,
            },
            InputOp::Focus { win, now, op } => match windows.get_mut(&win) {
                Some(w) => {
                    let changed = w.focus_op(win, op, next_scope, &mut fx);
                    w.settle(win, now, &mut fx) | changed
                }
                None => false,
            },
            InputOp::SetCapture { win, capture } => windows
                .get_mut(&win)
                .is_some_and(|w| w.set_capture(capture)),
            InputOp::BeginFrame { win, now } => {
                windows.get_mut(&win).is_some_and(|w| w.begin_frame(now))
            }
            InputOp::EndFrame { win, now } => match windows.get_mut(&win) {
                Some(w) => {
                    let changed = w.end_frame(win, &mut fx);
                    w.settle(win, now, &mut fx) | changed
                }
                None => false,
            },
        };
        if changed {
            rev.bump();
        }
        fx
    }

    /// Caret blink edges: every window whose armed edge is due at `now`
    /// flips its caret, asks for a repaint of that field and re-arms the
    /// next edge. The kernel calls it when `TimerOwner::CaretBlink` fires
    /// (calling it at any other time is harmless).
    pub fn tick(&mut self, now: Seconds) -> InputEffects {
        let mut fx = InputEffects::new();
        let mut changed = false;
        for (win, w) in &mut self.windows {
            if w.armed.is_some_and(|at| at.get() <= now.get()) {
                changed |= w.settle(*win, now, &mut fx);
            }
        }
        if changed {
            self.rev.bump();
        }
        fx
    }

    /// The compose-phase door for widget registration (`register*`,
    /// `register_text_field`, `update_field`, `mark_seen`, `unregister`,
    /// layers). Not revisioned: what registration changes is evaluated by
    /// the following [`InputOp::EndFrame`]. Lib brief L6 narrows what this
    /// reference can reach (see the module docs).
    // Read doors for the native/web host briefs (F8+) - unused in-crate until then.
    #[allow(dead_code)]
    pub fn registrar(&mut self, win: WindowId) -> Option<&mut InputCoordinator> {
        self.windows.get_mut(&win).map(|w| &mut w.coord)
    }

    /// The compose-phase door for the per-widget typed state store (the
    /// `Widgets` face of the app hook contexts). Not revisioned: the store
    /// holds no on-screen truth of its own.
    // Read doors for the native/web host briefs (F8+) - unused in-crate until then.
    #[allow(dead_code)]
    pub fn states_mut(&mut self, win: WindowId) -> Option<&mut uzor::app_context::StateRegistry> {
        self.windows.get_mut(&win).map(|w| &mut w.states)
    }

    /// The compose-phase `Widgets` pair, borrow-split: a hook holds both
    /// halves at once, so the two single doors cannot produce them
    /// together. Same revision rules as the single doors.
    pub fn compose_parts(
        &mut self,
        win: WindowId,
    ) -> Option<(&mut InputCoordinator, &mut uzor::app_context::StateRegistry, &mut Selectables)> {
        self.windows
            .get_mut(&win)
            .map(|w| (&mut w.coord, &mut w.states, &mut w.reported))
    }

    /// Compose-phase door (T2): report one selectable plain-text widget's
    /// content and line geometry for this frame — the input the selection
    /// owner resolves presses / drags against, mirroring
    /// `TextFieldStore::update_field`. A widget not reported in a frame
    /// stops being selectable and loses its selection. Not revisioned: the
    /// change is evaluated by the following [`InputOp::EndFrame`].
    // Read doors for the native/web host briefs (F8+) - unused in-crate until then.
    #[allow(dead_code)]
    pub fn update_selectable(
        &mut self,
        win: WindowId,
        widget: WidgetId,
        text: impl Into<String>,
        lines: Vec<SelectionLine>,
    ) {
        if let Some(w) = self.windows.get_mut(&win) {
            w.reported.report(widget, text, lines);
        }
    }

    /// Route presses on the hit region `member` to the selectable `owner` for
    /// this frame (see `Selectables::alias`).
    #[allow(dead_code)]
    pub fn alias_selectable(&mut self, win: WindowId, member: WidgetId, owner: WidgetId) {
        if let Some(w) = self.windows.get_mut(&win) {
            w.reported.alias(member, owner);
        }
    }

    /// Bumped on every observable state change.
    pub fn revision(&self) -> Revision {
        self.rev
    }

    /// Read-only projection.
    pub fn view(&self) -> InputEngineView<'_> {
        InputEngineView { e: self }
    }
}

/// Read-only projection of the [`InputEngine`].
#[derive(Clone, Copy, Debug)]
pub struct InputEngineView<'a> {
    e: &'a InputEngine,
}

// Read doors for the native/web host briefs (F8+) - unused in-crate until then.
#[allow(dead_code)]
impl<'a> InputEngineView<'a> {
    fn w(&self, win: WindowId) -> Option<&'a PerWindowInput> {
        self.e.windows.get(&win)
    }

    /// Tracked windows, ascending.
    pub fn ids(&self) -> impl Iterator<Item = WindowId> + 'a {
        self.e.windows.keys().copied()
    }

    /// The published input state of one window.
    pub fn window(&self, win: WindowId) -> Option<InputView> {
        self.w(win).map(|w| InputView {
            hovered: w.hover.clone(),
            pressed: w.pressed.clone(),
            focused: w.focused_id().cloned(),
            focus_visible: w.focus_visible,
            captured: w.capture.is_some(),
            scope_depth: w.scopes.len(),
        })
    }

    /// The widget with keyboard focus.
    pub fn focused(&self, win: WindowId) -> Option<&'a WidgetId> {
        self.w(win)?.focused_id()
    }

    /// The owner of the active (innermost) focus scope.
    pub fn active_scope(&self, win: WindowId) -> Option<&'a ScopeOwner> {
        self.w(win)?.scopes.last().map(|s| &s.owner)
    }

    /// The pointer capture.
    pub fn capture(&self, win: WindowId) -> Option<&'a Capture> {
        self.w(win)?.capture.as_ref()
    }

    /// The event-level cook state (click count, drag arm).
    pub fn cook(&self, win: WindowId) -> Option<&'a CookState> {
        self.w(win).map(|w| &w.cook)
    }

    /// Widgets clicked in the last evaluated frame, with their click count
    /// (1 single, 2 double, 3 triple).
    pub fn clicked(&self, win: WindowId) -> &'a [(WidgetId, u8)] {
        self.w(win).map_or(&[], |w| w.clicked.as_slice())
    }

    /// The caret of the focused field is in its visible phase (and blinking
    /// is active).
    pub fn caret_visible(&self, win: WindowId) -> bool {
        self.w(win).is_some_and(|w| w.caret_visible)
    }

    /// The armed caret blink edge.
    pub fn caret_deadline(&self, win: WindowId) -> Option<Seconds> {
        self.w(win)?.armed
    }

    /// The window's text fields (text, cursor, selection, preedit).
    pub fn text_fields(&self, win: WindowId) -> Option<&'a TextFieldStore> {
        self.w(win).map(|w| w.coord.text_fields())
    }

    /// The window's plain-text selections (widget → selection), the T2
    /// per-window owner state. The app reads this at compose time to draw
    /// highlights through the lib's `draw_text_with_selection`.
    pub fn selections(&self, win: WindowId) -> Option<&'a [(WidgetId, TextSelection)]> {
        self.w(win).map(|w| w.selections.as_slice())
    }

    /// The window's coordinator, read-only (hit tests, widget state).
    pub fn coordinator(&self, win: WindowId) -> Option<&'a InputCoordinator> {
        self.w(win).map(|w| &w.coord)
    }

    /// Scroll accumulated since the last `BeginFrame`, in lines. The
    /// compose phase reads it into the hook view before `BeginFrame`
    /// moves it into the coordinator's frame input.
    pub fn pending_scroll(&self, win: WindowId) -> (f64, f64) {
        self.w(win).map_or((0.0, 0.0), |w| w.pointer.scroll)
    }

    /// Whether [`Self::pending_scroll`] came from pixel deltas (trackpad,
    /// smooth wheel): scroll containers then follow 1:1 and fling on release.
    pub fn pending_scroll_precise(&self, win: WindowId) -> bool {
        self.w(win).is_some_and(|w| w.pointer.scroll_precise)
    }

    /// The pending scroll came from a touch pan or fling.
    pub fn pending_scroll_touch(&self, win: WindowId) -> bool {
        self.w(win).is_some_and(|w| w.pointer.scroll_touch)
    }

    /// Last pointer position in window coordinates and whether a button is
    /// held (embedded surfaces that forward raw pointer events need both).
    /// Secondary-button release position since the last `BeginFrame`.
    pub fn context_click(&self, win: WindowId) -> Option<(f64, f64)> {
        self.w(win).and_then(|w| w.pointer.context)
    }

    pub fn pointer(&self, win: WindowId) -> (Option<(f64, f64)>, bool) {
        self.w(win).map_or((None, false), |w| (w.pointer.pos, w.pointer.button_down.is_some()))
    }

    /// Where the held press went down (window coords), while a button is held. A drag
    /// measures from here, not from the first pointer position a frame saw: the pointer
    /// may have moved several pixels between the press and that frame.
    pub fn press_origin(&self, win: WindowId) -> Option<(f64, f64)> {
        let w = self.w(win)?;
        w.pointer.button_down?;
        w.cook.press_origin.map(|o| (o.x, o.y))
    }
}

#[cfg(test)]
mod tests;