uzor 1.5.8

Core UI engine — geometry, interaction, input state
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
//! Text field store — owns text/cursor/selection state for all registered fields.

use std::collections::HashMap;

use crate::types::WidgetId;
use crate::input::keyboard::keyboard::KeyPress;
use super::selection::{char_from_x as cursor_from_x, char_index_at_x, word_left, word_right, TextSelection};

// =============================================================================
// InputCapability
// =============================================================================

/// Which input sources a field accepts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InputCapability {
    /// Accepts both keyboard and mouse input.
    Both,
    /// Accepts keyboard input only (ignores mouse drag/click).
    Keyboard,
    /// Accepts mouse input only (ignores char/key events).
    Mouse,
    /// Raw PTY mode — bytes forwarded directly without text editing logic.
    Raw,
}

// =============================================================================
// TextFieldConfig
// =============================================================================

/// Configuration for a single text field.
#[derive(Clone)]
pub struct TextFieldConfig {
    /// Which input sources this field accepts.
    pub capability: InputCapability,
    /// Whether this field is read-only (accepts SelectAll/Copy but not editing).
    pub read_only: bool,
    /// Optional character filter — returns `true` if the character is allowed.
    pub char_filter: Option<fn(char) -> bool>,
    /// Maximum number of characters allowed (None = unlimited).
    pub max_len: Option<usize>,
    /// Whether to mask input display (password field).
    /// The store still holds the real text — masking is a renderer concern.
    pub masked: bool,
    /// Shift+Enter inserts a newline instead of submitting (chat composers).
    pub multiline: bool,
}

impl TextFieldConfig {
    /// This config with Shift+Enter inserting a newline.
    pub fn multiline(mut self) -> Self {
        self.multiline = true;
        self
    }

    /// Plain editable text field.
    pub fn text() -> Self {
        Self {
            capability: InputCapability::Both,
            read_only: false,
            char_filter: None,
            max_len: None,
            masked: false,
            multiline: false,
        }
    }

    /// Password field (editable, both input sources, no display filter needed here).
    pub fn password() -> Self {
        Self {
            capability: InputCapability::Both,
            read_only: false,
            char_filter: None,
            max_len: None,
            masked: true,
            multiline: false,
        }
    }

    /// Search field (same as text for now).
    pub fn search() -> Self {
        Self::text()
    }

    /// Read-only display field (Copy and SelectAll still work).
    pub fn read_only() -> Self {
        Self {
            capability: InputCapability::Both,
            read_only: true,
            char_filter: None,
            max_len: None,
            masked: false,
            multiline: false,
        }
    }

    /// Keyboard-only field (ignores mouse drag/click).
    pub fn keyboard_only() -> Self {
        Self {
            capability: InputCapability::Keyboard,
            read_only: false,
            char_filter: None,
            max_len: None,
            masked: false,
            multiline: false,
        }
    }

    /// Raw PTY field — bytes forwarded directly.
    pub fn raw() -> Self {
        Self {
            capability: InputCapability::Raw,
            read_only: false,
            char_filter: None,
            max_len: None,
            masked: false,
            multiline: false,
        }
    }

    /// Builder: set a character filter.
    pub fn with_filter(mut self, filter: fn(char) -> bool) -> Self {
        self.char_filter = Some(filter);
        self
    }

    /// Builder: set a maximum character length.
    pub fn with_max_len(mut self, max: usize) -> Self {
        self.max_len = Some(max);
        self
    }

    /// Builder: set masked mode (for password display).
    pub fn with_masked(mut self, masked: bool) -> Self {
        self.masked = masked;
        self
    }
}

// =============================================================================
// TextAction
// =============================================================================

/// Result of processing a character or key press.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TextAction {
    /// No action taken.
    None,
    /// User pressed Enter — contains the committed text.
    Commit(String),
    /// User pressed Escape — text reverted to `original_text`.
    Cancel,
    /// Text was modified — contains the new text.
    TextChanged(String),
    /// Raw PTY bytes (for Raw-capability fields).
    RawInput(Vec<u8>),
}

// =============================================================================
// TextFieldState
// =============================================================================

/// Mutable state for a single text field.
pub struct TextFieldState {
    /// Current text content.
    pub text: String,
    /// Snapshot of text at `begin_edit` time, used to revert on Cancel.
    pub original_text: String,
    /// Cursor position in char units (not bytes).
    pub cursor: usize,
    /// Selection anchor in char units. When `Some(anchor)`, the selection
    /// spans `min(anchor, cursor)..max(anchor, cursor)`.
    pub selection_start: Option<usize>,
    /// Last rendered bounding rect `(x, y, width, height)`.
    pub last_rect: Option<(f64, f64, f64, f64)>,
    /// X positions of char boundaries (length = char_count + 1).
    pub last_char_positions: Vec<f64>,
    /// Frame counter at last `update_field` call.
    pub last_frame: u64,
    /// Whether the user has TOUCHED this field — clicked into it or typed.
    ///
    /// Distinct from focus on purpose. A dialog arms its field on open so the
    /// first keystroke lands without a click, but arming is not an invitation:
    /// a caret blinking in a box nobody asked for reads as noise. Focus says
    /// "keystrokes come here"; this says "the user is in it", and only the
    /// second one should be visible.
    pub engaged: bool,
    /// IME composition in progress, shown over the text at `cursor` and
    /// never part of `text` until committed.
    pub preedit: String,
    /// Cursor inside `preedit`, in chars.
    pub preedit_cursor: usize,
    /// Field configuration (immutable after registration).
    pub config: TextFieldConfig,
    /// Undo history: `(text, cursor)` before each edit step, oldest first.
    pub undo: Vec<(String, usize)>,
    /// Redo history, filled by undo and cleared by a new edit.
    pub redo: Vec<(String, usize)>,
    /// The last edit was a typed (non-space) char: the next one joins its
    /// undo step, the way a browser undoes typing a word at a time.
    typing: bool,
}

/// Undo steps kept per field.
const UNDO_DEPTH: usize = 100;

impl TextFieldState {
    /// Create a new state for the given config.
    pub fn new(config: TextFieldConfig) -> Self {
        Self {
            text: String::new(),
            original_text: String::new(),
            cursor: 0,
            selection_start: None,
            last_rect: None,
            last_char_positions: Vec::new(),
            last_frame: 0,
            engaged: false,
            preedit: String::new(),
            preedit_cursor: 0,
            config,
            undo: Vec::new(),
            redo: Vec::new(),
            typing: false,
        }
    }

    /// Record an edit that turned `before` into the current text. `typed`
    /// marks a single typed char, which joins the previous typed char's step.
    /// No-op when the text did not change (a caret move ends the typing run).
    pub fn note_edit(&mut self, before: (String, usize), typed: bool) {
        if self.text == before.0 {
            self.typing = false;
            return;
        }
        if !(typed && self.typing) {
            if self.undo.len() == UNDO_DEPTH {
                self.undo.remove(0);
            }
            self.undo.push(before);
        }
        self.redo.clear();
        self.typing = typed;
    }

    /// Step back one edit. `false` when there is nothing to undo.
    pub fn undo(&mut self) -> bool {
        let Some((text, cursor)) = self.undo.pop() else { return false };
        let now = (std::mem::replace(&mut self.text, text), self.cursor);
        self.redo.push(now);
        self.restore_caret(cursor);
        true
    }

    /// Re-apply the last undone edit. `false` when there is nothing to redo.
    pub fn redo(&mut self) -> bool {
        let Some((text, cursor)) = self.redo.pop() else { return false };
        let now = (std::mem::replace(&mut self.text, text), self.cursor);
        self.undo.push(now);
        self.restore_caret(cursor);
        true
    }

    fn restore_caret(&mut self, cursor: usize) {
        self.cursor = cursor.min(self.char_count());
        self.selection_start = None;
        self.typing = false;
    }

    /// What a painter shows: the text with any IME preedit spliced in at the
    /// cursor, the caret (inside the preedit while composing) and the
    /// preedit's char range, to underline like the DOM's composition text.
    pub fn display(&self) -> (String, usize, Option<(usize, usize)>) {
        if self.preedit.is_empty() {
            return (self.text.clone(), self.cursor, None);
        }
        let at = self.text.char_indices().nth(self.cursor).map_or(self.text.len(), |(b, _)| b);
        let n = self.preedit.chars().count();
        let shown = format!("{}{}{}", &self.text[..at], self.preedit, &self.text[at..]);
        (shown, self.cursor + self.preedit_cursor.min(n), Some((self.cursor, self.cursor + n)))
    }

    /// Map char-boundary x positions measured on [`Self::display`] back to the
    /// buffer (the preedit's inner boundaries dropped, its end kept).
    pub fn buffer_positions(&self, mut shown: Vec<f64>) -> Vec<f64> {
        let n = self.preedit.chars().count();
        if n > 0 && self.cursor < shown.len() {
            let end = (self.cursor + n).min(shown.len() - 1);
            shown.drain(self.cursor..end);
        }
        shown
    }

    /// Return `(lo, hi)` if there is a non-empty selection, else `None`.
    pub fn selection_range(&self) -> Option<(usize, usize)> {
        let anchor = self.selection_start?;
        if anchor == self.cursor {
            return None;
        }
        let lo = anchor.min(self.cursor);
        let hi = anchor.max(self.cursor);
        Some((lo, hi))
    }

    /// Delete the current selection and position the cursor at `lo`.
    /// No-op if there is no selection.
    pub fn delete_selection(&mut self) {
        let (lo, hi) = match self.selection_range() {
            Some(range) => range,
            None => return,
        };
        let byte_lo = self.char_to_byte(lo);
        let byte_hi = self.char_to_byte(hi);
        self.text.drain(byte_lo..byte_hi);
        self.cursor = lo;
        self.selection_start = None;
    }

    /// Convert a char index to a byte index in `self.text`.
    pub fn char_to_byte(&self, char_idx: usize) -> usize {
        self.text
            .char_indices()
            .nth(char_idx)
            .map(|(b, _)| b)
            .unwrap_or(self.text.len())
    }

    /// Return the number of chars in `self.text`.
    pub fn char_count(&self) -> usize {
        self.text.chars().count()
    }
}

// =============================================================================
// TextFieldStore
// =============================================================================

/// Central store that owns text/cursor/selection for all registered fields.
///
/// # Focus model
/// Only one field is focused at a time. Focusing a new field clears the
/// selection anchor on the previously focused field but does NOT clear its
/// text.
pub struct TextFieldStore {
    fields: HashMap<WidgetId, TextFieldState>,
    focused: Option<WidgetId>,
    drag_field: Option<WidgetId>,
    current_frame: u64,
    blink_reset_time: u64,
}

impl TextFieldStore {
    /// Frame-staleness tolerance for [`Self::focused_is_stale`], in
    /// frame-counter ticks. A host's `prepare_frame`/`render_to_scene` pair
    /// can advance the frame counter twice per real rendered frame (calling
    /// `begin_frame()` once each, so their own `update_field` calls land on
    /// the second of the two) — this tolerates one full extra tick of lag
    /// on top of that before a non-updating field counts as gone, so an
    /// ordinary render-to-render gap is never mistaken for staleness.
    const FOCUS_STALE_FRAME_LAG: u64 = 3;

    // =========================================================================
    // Lifecycle
    // =========================================================================

    /// Create an empty store.
    pub fn new() -> Self {
        Self {
            fields: HashMap::new(),
            focused: None,
            drag_field: None,
            current_frame: 0,
            blink_reset_time: 0,
        }
    }

    /// Advance the frame counter. Call at the start of every render frame.
    pub fn begin_frame(&mut self) {
        self.current_frame = self.current_frame.wrapping_add(1);
    }

    // =========================================================================
    // Registration
    // =========================================================================

    /// Register a field. If the field is already registered its config is
    /// updated but existing text/cursor state is preserved.
    pub fn register(&mut self, id: impl Into<WidgetId>, config: TextFieldConfig) {
        let id = id.into();
        let state = self.fields
            .entry(id)
            .or_insert_with(|| TextFieldState::new(config.clone()));
        state.config = config;
    }

    /// Remove a field. Clears focus/drag if it was pointing at this field.
    pub fn unregister(&mut self, id: &WidgetId) {
        self.fields.remove(id);
        if self.focused.as_ref() == Some(id) {
            self.focused = None;
        }
        if self.drag_field.as_ref() == Some(id) {
            self.drag_field = None;
        }
    }

    /// Refresh the screen geometry for a field. Call after rendering the field.
    ///
    /// `char_positions` is the list of char boundary X positions (length = char_count + 1).
    pub fn update_field(
        &mut self,
        id: &WidgetId,
        rect: (f64, f64, f64, f64),
        char_positions: Vec<f64>,
    ) {
        if let Some(state) = self.fields.get_mut(id) {
            state.last_rect = Some(rect);
            state.last_char_positions = char_positions;
            state.last_frame = self.current_frame;
        }
    }

    /// Stamp a field as "on screen this frame" WITHOUT touching its
    /// click-to-cursor geometry — the light-weight sibling of
    /// [`Self::update_field`] for a field whose on-screen model does not
    /// fit a real rect + char-boundary list (a whole-button pseudo-field
    /// with no per-char caret, a raw terminal grid with its own selection
    /// state, ...). Sets only the frame-liveness signal
    /// [`Self::focused_is_stale`] and [`Self::focused_was_never_stamped`]
    /// read; leaves `last_rect`/`last_char_positions` untouched, so calling
    /// this can never make [`Self::on_drag_start`]'s hit-test start
    /// matching a field whose host never drew a real, clickable text box
    /// for it. Every field that can hold focus must be stamped by EITHER
    /// this or `update_field` each frame its host draws it — one of the two
    /// is the whole contract `focused_is_stale` relies on.
    pub fn mark_seen(&mut self, id: &WidgetId) {
        if let Some(state) = self.fields.get_mut(id) {
            state.last_frame = self.current_frame;
        }
    }

    // =========================================================================
    // Query
    // =========================================================================

    /// Current text of a field.
    pub fn text(&self, id: &WidgetId) -> &str {
        self.fields.get(id).map(|s| s.text.as_str()).unwrap_or("")
    }

    /// Cursor position (in chars) of a field.
    pub fn cursor(&self, id: &WidgetId) -> usize {
        self.fields.get(id).map(|s| s.cursor).unwrap_or(0)
    }

    /// Selection range `(lo, hi)` if a non-empty selection exists.
    pub fn selection_range(&self, id: &WidgetId) -> Option<(usize, usize)> {
        self.fields.get(id)?.selection_range()
    }

    /// Whether the given field is currently focused.
    /// Whether the user has touched this field — see [`TextFieldState::engaged`].
    /// Draw the caret and the focus ring from THIS, not from focus.
    pub fn is_engaged(&self, id: &WidgetId) -> bool {
        self.fields.get(id).map(|s| s.engaged).unwrap_or(false)
    }

    /// Mark a field as touched, for a host that routes its own clicks.
    pub fn engage(&mut self, id: &WidgetId) {
        if let Some(state) = self.fields.get_mut(id) {
            state.engaged = true;
        }
    }

    pub fn is_focused(&self, id: &WidgetId) -> bool {
        self.focused.as_ref() == Some(id)
    }

    /// Currently focused field id.
    pub fn focused(&self) -> Option<&WidgetId> {
        self.focused.as_ref()
    }

    /// Whether the currently focused field's screen geometry has gone
    /// stale: it has not been stamped (`update_field` or [`Self::mark_seen`])
    /// for more than [`Self::FOCUS_STALE_FRAME_LAG`] frame-counter ticks.
    /// This is the shape a modal or inline editor leaves behind when it
    /// stops being drawn without first calling [`Self::blur`] on its own
    /// field — a caller can use this to detect and clear that leftover
    /// focus instead of trusting it forever.
    ///
    /// A field that has NEVER once been stamped (`last_frame == 0` since
    /// registration) is treated the same as one whose stamps stopped: it
    /// goes stale as soon as more than `FOCUS_STALE_FRAME_LAG` frames have
    /// elapsed since it was focused. Every field that can hold focus is
    /// expected to be stamped by its host on every frame it draws it — a
    /// caller that focuses a field and never stamps it has a real bug, and
    /// [`Self::focused_was_never_stamped`] is the sharper, immediate signal
    /// for that specific case (a caller can `debug_assert!` on it instead
    /// of waiting out the frame lag). `false` (not stale) is always the
    /// safe default when nothing is focused.
    pub fn focused_is_stale(&self) -> bool {
        let Some(id) = self.focused.as_ref() else { return false };
        let Some(state) = self.fields.get(id) else { return false };
        self.current_frame.wrapping_sub(state.last_frame) > Self::FOCUS_STALE_FRAME_LAG
    }

    /// Whether the currently focused field has NEVER once been stamped via
    /// `update_field` or [`Self::mark_seen`] — a regression tripwire.
    ///
    /// `focused_is_stale` alone eventually self-heals this shape (see its
    /// own doc), but only after `FOCUS_STALE_FRAME_LAG` frames of silently
    /// swallowed keystrokes. A caller that dispatches keys should check
    /// this FIRST and `debug_assert!`/`log::warn!` under
    /// `cfg(debug_assertions)` — it means a focusable field's draw site is
    /// missing its stamp call entirely, a coding-time bug that should be
    /// caught in development rather than shipped. `false` when nothing is
    /// focused.
    pub fn focused_was_never_stamped(&self) -> bool {
        let Some(id) = self.focused.as_ref() else { return false };
        self.fields.get(id).map(|s| s.last_frame == 0).unwrap_or(false)
    }

    /// Whether the cursor should be visible right now (500 ms blink).
    pub fn cursor_visible(&self, now_ms: u64) -> bool {
        let elapsed = now_ms.wrapping_sub(self.blink_reset_time);
        (elapsed / 500) % 2 == 0
    }

    /// Shared read access to a field's full state.
    pub fn field_state(&self, id: &WidgetId) -> Option<&TextFieldState> {
        self.fields.get(id)
    }

    /// Exclusive access to a field's full state.
    pub fn field_state_mut(&mut self, id: &WidgetId) -> Option<&mut TextFieldState> {
        self.fields.get_mut(id)
    }

    /// Whether a field is registered.
    pub fn has_field(&self, id: &WidgetId) -> bool {
        self.fields.contains_key(id)
    }

    // =========================================================================
    // Focus
    // =========================================================================

    /// Focus a field. Returns `true` if focus changed.
    pub fn focus(&mut self, id: impl Into<WidgetId>) -> bool {
        let id = id.into();
        if self.focused.as_ref() == Some(&id) {
            // Already focused, so focus does not change — but this is still an
            // ARMING call, and arming is silent. A dialog that closes without
            // blurring and opens again would otherwise inherit the engagement
            // of its previous life.
            if let Some(state) = self.fields.get_mut(&id) {
                state.engaged = false;
            }
            return false;
        }
        if let Some(prev) = self.focused.take() {
            if let Some(state) = self.fields.get_mut(&prev) {
                state.selection_start = None;
                state.preedit.clear();
                state.preedit_cursor = 0;
            }
        }
        if let Some(state) = self.fields.get_mut(&id) {
            // Arming is silent. Whoever focused this field did not necessarily
            // ask for it to look focused; typing or clicking is what does.
            state.engaged = false;
        }
        self.focused = Some(id);
        self.reset_blink();
        true
    }

    /// Remove focus from the currently focused field.
    pub fn blur(&mut self) {
        if let Some(id) = self.focused.take() {
            if let Some(state) = self.fields.get_mut(&id) {
                state.selection_start = None;
                state.preedit.clear();
                state.preedit_cursor = 0;
            }
        }
        self.drag_field = None;
    }

    /// Set text programmatically. Positions cursor at end. Does not require focus.
    pub fn set_text(&mut self, id: &WidgetId, text: &str) {
        if let Some(state) = self.fields.get_mut(id) {
            if state.text != text {
                // A programmatic value drops the undo history, as `input.value = ..` does.
                state.undo.clear();
                state.redo.clear();
                state.typing = false;
            }
            state.text = text.to_string();
            state.cursor = state.char_count();
            state.selection_start = None;
        }
    }

    /// Clear text and reset cursor/selection. Does not require focus.
    pub fn clear(&mut self, id: &WidgetId) {
        if let Some(state) = self.fields.get_mut(id) {
            state.text.clear();
            state.undo.clear();
            state.redo.clear();
            state.typing = false;
            state.cursor = 0;
            state.selection_start = None;
        }
    }

    /// Snapshot current text as `original_text` so Cancel can revert to it.
    pub fn begin_edit(&mut self, id: &WidgetId) {
        if let Some(state) = self.fields.get_mut(id) {
            state.original_text = state.text.clone();
        }
    }

    /// Override the blink reset timestamp from the platform clock.
    pub fn set_blink_time(&mut self, now_ms: u64) {
        self.blink_reset_time = now_ms;
    }

    // =========================================================================
    // Input dispatch
    // =========================================================================

    /// Handle a printable character.
    pub fn on_char(&mut self, ch: char) -> TextAction {
        let before = self.snapshot();
        let action = self.on_char_inner(ch);
        let typed = !ch.is_control() && !ch.is_whitespace();
        self.note(before, typed);
        action
    }

    /// Handle a named key press.
    pub fn on_key(&mut self, key: KeyPress) -> TextAction {
        if matches!(key, KeyPress::Undo | KeyPress::Redo) {
            return self.undo_redo(matches!(key, KeyPress::Redo));
        }
        let before = self.snapshot();
        let action = self.on_key_inner(key);
        self.note(before, false);
        action
    }

    /// The focused field's text and caret, before an edit.
    fn snapshot(&self) -> Option<(WidgetId, (String, usize))> {
        let id = self.focused.clone()?;
        let s = self.fields.get(&id)?;
        Some((id, (s.text.clone(), s.cursor)))
    }

    fn note(&mut self, before: Option<(WidgetId, (String, usize))>, typed: bool) {
        if let Some((id, before)) = before {
            if let Some(s) = self.fields.get_mut(&id) {
                s.note_edit(before, typed);
            }
        }
    }

    fn undo_redo(&mut self, redo: bool) -> TextAction {
        let Some(id) = self.focused.clone() else { return TextAction::None };
        let Some(s) = self.fields.get_mut(&id) else { return TextAction::None };
        if s.config.read_only || matches!(s.config.capability, InputCapability::Mouse | InputCapability::Raw) {
            return TextAction::None;
        }
        let done = if redo { s.redo() } else { s.undo() };
        if !done {
            return TextAction::None;
        }
        s.engaged = true;
        let text = s.text.clone();
        self.reset_blink();
        TextAction::TextChanged(text)
    }

    fn on_char_inner(&mut self, ch: char) -> TextAction {
        let id = match self.focused.clone() {
            Some(id) => id,
            None => return TextAction::None,
        };

        // Raw fields bypass all text-editing logic.
        if self.fields.get(&id).map(|s| s.config.capability == InputCapability::Raw).unwrap_or(false) {
            return TextAction::RawInput(raw_char_to_bytes(ch));
        }

        let state = match self.fields.get_mut(&id) {
            Some(s) => s,
            None => return TextAction::None,
        };
        // Typing is engagement: the field becomes visibly focused the
        // moment it receives a keystroke, not when it was armed.
        state.engaged = true;

        // Mouse-only or read-only fields reject char input.
        if state.config.capability == InputCapability::Mouse || state.config.read_only {
            return TextAction::None;
        }

        match ch {
            '\r' | '\n' => {
                let text = state.text.clone();
                TextAction::Commit(text)
            }
            '\x1b' => {
                let original = state.original_text.clone();
                state.text = original;
                state.cursor = state.char_count();
                state.selection_start = None;
                self.reset_blink();
                TextAction::Cancel
            }
            '\x08' => {
                if state.selection_range().is_some() {
                    state.delete_selection();
                } else if state.cursor > 0 {
                    let byte_pos = state.char_to_byte(state.cursor - 1);
                    let byte_end = state.char_to_byte(state.cursor);
                    state.text.drain(byte_pos..byte_end);
                    state.cursor -= 1;
                }
                // Same collapse rule as typing: backspace ends at a caret.
                state.selection_start = None;
                self.reset_blink();
                let text = self.fields[&id].text.clone();
                TextAction::TextChanged(text)
            }
            c if c.is_control() => TextAction::None,
            c => {
                if let Some(filter) = state.config.char_filter {
                    if !filter(c) {
                        return TextAction::None;
                    }
                }
                let text_len_after_delete = if state.selection_range().is_some() {
                    let (lo, hi) = state.selection_range().unwrap();
                    state.char_count() - (hi - lo)
                } else {
                    state.char_count()
                };
                if let Some(max) = state.config.max_len {
                    if text_len_after_delete >= max {
                        return TextAction::None;
                    }
                }
                if state.selection_range().is_some() {
                    state.delete_selection();
                }
                let byte_pos = state.char_to_byte(state.cursor);
                state.text.insert(byte_pos, c);
                state.cursor += 1;
                // A collapsed anchor survives `delete_selection` (its range
                // is empty); left armed, it would silently select the just
                // typed char. Typing always collapses to the caret.
                state.selection_start = None;
                self.reset_blink();
                let text = self.fields[&id].text.clone();
                TextAction::TextChanged(text)
            }
        }
    }

    fn on_key_inner(&mut self, key: KeyPress) -> TextAction {
        let id = match self.focused.clone() {
            Some(id) => id,
            None => return TextAction::None,
        };

        // Raw fields bypass all text-editing logic.
        if self.fields.get(&id).map(|s| s.config.capability == InputCapability::Raw).unwrap_or(false) {
            if let Some(bytes) = key_to_pty_bytes(&key) {
                return TextAction::RawInput(bytes);
            }
            return TextAction::None;
        }

        let state = match self.fields.get_mut(&id) {
            Some(s) => s,
            None => return TextAction::None,
        };
        // Typing is engagement: the field becomes visibly focused the
        // moment it receives a keystroke, not when it was armed.
        state.engaged = true;

        let restricted = state.config.capability == InputCapability::Mouse || state.config.read_only;
        if restricted {
            match &key {
                KeyPress::Copy | KeyPress::SelectAll => {}
                _ => return TextAction::None,
            }
        }

        let text_before = state.text.clone();
        let consumed = apply_key(state, key);
        if consumed {
            self.reset_blink();
        }
        let text_after = &self.fields[&id].text;
        if text_after != &text_before {
            TextAction::TextChanged(text_after.clone())
        } else {
            TextAction::None
        }
    }

    /// Begin a mouse drag on the field whose rect contains `(x, y)`.
    ///
    /// Geometrically hit-tests every registered field's last-drawn rect
    /// (`TextFieldState::last_rect`) and, if one is hit, delegates to
    /// [`Self::begin_drag_at`]. Use this when the caller does NOT already
    /// know which field was hit (e.g. a raw platform mousedown handler with
    /// no z-order-aware coordinator of its own). When the caller already
    /// knows the hit field — e.g. `InputCoordinator::end_frame`, which just
    /// ran its own z-order-aware hit test — call [`Self::begin_drag_at`]
    /// directly instead; it skips this geometric re-search entirely, so it
    /// works even on the very first frame a field is registered, before any
    /// draw call has stamped a `last_rect` for it via [`Self::update_field`].
    pub fn on_drag_start(&mut self, x: f64, y: f64) {
        let hit_id = self.hit_test_field_rect(x, y);
        match hit_id {
            Some(id) => self.begin_drag_at(id, x),
            None => {
                // A press that landed on nothing editable ENDS engagement. The
                // field stays armed for the keyboard, but it stops looking
                // live: clicking a dialog's header, or anywhere else outside
                // the box, must take the caret and the ring away. Without this
                // the ring survived every click that was not a close.
                for state in self.fields.values_mut() {
                    state.engaged = false;
                }
            }
        }
    }

    /// Geometric hit-test against every registered field's last-drawn rect,
    /// skipping mouse-incapable fields and fields whose geometry has gone
    /// stale (not stamped via [`Self::update_field`] this frame or the
    /// previous one).
    fn hit_test_field_rect(&self, x: f64, y: f64) -> Option<WidgetId> {
        for (id, state) in &self.fields {
            if state.config.capability == InputCapability::Keyboard {
                continue;
            }
            let frame_lag = self.current_frame.wrapping_sub(state.last_frame);
            if frame_lag > 1 {
                continue;
            }
            if let Some((rx, ry, rw, rh)) = state.last_rect {
                if x >= rx && x <= rx + rw && y >= ry && y <= ry + rh {
                    return Some(id.clone());
                }
            }
        }
        None
    }

    /// Focus `id` and place the caret at the character nearest `x`, arming a
    /// drag-select session on it — the same effect [`Self::on_drag_start`]
    /// has once it has resolved which field was hit, but for a field the
    /// caller already knows (skips the geometric `last_rect` search).
    ///
    /// This is the caret-placement half of a click/press on a text-sense
    /// widget: focusing alone arms the field for the keyboard but leaves the
    /// caret wherever it happened to be from a previous session (or at 0 on
    /// first focus) — calling this instead moves it under the pointer, the
    /// way every native text field behaves on click.
    pub fn begin_drag_at(&mut self, id: impl Into<WidgetId>, x: f64) {
        let id = id.into();
        self.focus(id.clone());

        let state = match self.fields.get_mut(&id) {
            Some(s) => s,
            None => return,
        };
        // A click INTO the field is engagement — `focus` above cleared the
        // flag, which is right for an arming focus and wrong for this one.
        state.engaged = true;

        let cursor = cursor_from_x(&state.last_char_positions, x);
        state.cursor = cursor;
        state.selection_start = Some(cursor);
        self.drag_field = Some(id);
        self.reset_blink();
    }

    /// Update the drag-selection cursor as the mouse moves.
    pub fn on_drag_move(&mut self, x: f64) {
        let id = match self.drag_field.clone() {
            Some(id) => id,
            None => return,
        };

        let state = match self.fields.get_mut(&id) {
            Some(s) => s,
            None => return,
        };

        state.cursor = cursor_from_x(&state.last_char_positions, x);
    }

    /// Returns `true` if a text-select drag is currently in progress.
    pub fn drag_active(&self) -> bool {
        self.drag_field.is_some()
    }

    /// End the drag-selection. Clears degenerate (zero-width) selections.
    pub fn on_drag_end(&mut self) {
        if let Some(id) = self.drag_field.clone() {
            if let Some(state) = self.fields.get_mut(&id) {
                if state.selection_start == Some(state.cursor) {
                    state.selection_start = None;
                }
            }
        }
        self.drag_field = None;
    }

    /// The selection of field `id`: anchor = the selection anchor (or the
    /// cursor when there is none), focus = the cursor. `None` for an
    /// unknown field.
    pub fn selection(&self, id: &WidgetId) -> Option<TextSelection> {
        let state = self.fields.get(id)?;
        Some(TextSelection::new(state.selection_start.unwrap_or(state.cursor), state.cursor))
    }

    /// Focus and engage `id` and set its selection to `sel` (clamped to the
    /// text), ending any drag-select session. An empty `sel` is a caret
    /// with no selection.
    pub fn set_selection(&mut self, id: impl Into<WidgetId>, sel: TextSelection) {
        let id = id.into();
        self.focus(id.clone());
        let Some(state) = self.fields.get_mut(&id) else { return };
        state.engaged = true;
        let sel = sel.clamped(state.char_count());
        state.cursor = sel.focus;
        state.selection_start = if sel.is_empty() { None } else { Some(sel.anchor) };
        self.drag_field = None;
        self.reset_blink();
    }

    /// The end state of a drag-select on `id`: select from the char
    /// boundary nearest `anchor_x` (the press) to the one nearest `focus_x`
    /// (the release), either direction. A drag that ends on its start
    /// char leaves a caret there.
    pub fn select_drag(&mut self, id: impl Into<WidgetId>, anchor_x: f64, focus_x: f64) {
        let id = id.into();
        let Some(state) = self.fields.get(&id) else { return };
        let anchor = cursor_from_x(&state.last_char_positions, anchor_x);
        let focus = cursor_from_x(&state.last_char_positions, focus_x);
        self.set_selection(id, TextSelection::new(anchor, focus));
    }

    /// A press on `id` at `x` with `click_count`: 1 places the caret and
    /// arms a drag ([`Self::begin_drag_at`]); 2 selects the word under `x`;
    /// 3 selects the line under `x` (the whole text for a single-line
    /// field). Word and line use the
    /// [`selection`](super::selection) helpers, so they agree with
    /// Ctrl+Arrow.
    pub fn select_at_click_count(&mut self, id: impl Into<WidgetId>, x: f64, click_count: u8) {
        let id = id.into();
        if click_count <= 1 {
            self.begin_drag_at(id, x);
            return;
        }
        let Some(state) = self.fields.get(&id) else {
            self.focus(id);
            return;
        };
        // A masked field shows no words, so a multi-click selects it all
        // (as native password fields do) instead of leaking word breaks.
        let sel = if state.config.masked {
            TextSelection::all(&state.text)
        } else {
            let under = char_index_at_x(&state.last_char_positions, x);
            TextSelection::for_click_count(&state.text, under, click_count)
        };
        self.set_selection(id, sel);
    }

    /// Select all of field `id`'s text (focuses and engages it).
    pub fn select_all(&mut self, id: impl Into<WidgetId>) {
        let id = id.into();
        let Some(state) = self.fields.get(&id) else { return };
        let sel = TextSelection::all(&state.text);
        self.set_selection(id, sel);
    }

    /// Return the selected text of the focused (or drag) field for the clipboard.
    pub fn copy_selection(&self) -> Option<String> {
        let id = self.focused.as_ref().or(self.drag_field.as_ref())?;
        let state = self.fields.get(id)?;
        let (lo, hi) = state.selection_range()?;
        let byte_lo = state.char_to_byte(lo);
        let byte_hi = state.char_to_byte(hi);
        Some(state.text[byte_lo..byte_hi].to_string())
    }

    /// Cut the selection of field `id` for the clipboard: returns the
    /// selected text and deletes it. A read-only field returns the text and
    /// keeps it (a copy). `None` when there is no selection.
    pub fn cut_selection(&mut self, id: &WidgetId) -> Option<String> {
        let state = self.fields.get_mut(id)?;
        let (lo, hi) = state.selection_range()?;
        let byte_lo = state.char_to_byte(lo);
        let byte_hi = state.char_to_byte(hi);
        let selected = state.text[byte_lo..byte_hi].to_string();
        if !state.config.read_only && state.config.capability != InputCapability::Mouse {
            let before = (state.text.clone(), state.cursor);
            state.delete_selection();
            state.note_edit(before, false);
            self.reset_blink();
        }
        Some(selected)
    }

    /// Set the IME composition of field `id`: `text` with the cursor at
    /// `cursor` chars into it. An empty `text` ends the composition. The
    /// field's `text` is untouched until [`Self::ime_commit`].
    pub fn preedit_set(&mut self, id: &WidgetId, text: String, cursor: usize) {
        if let Some(state) = self.fields.get_mut(id) {
            state.preedit_cursor = cursor.min(text.chars().count());
            state.preedit = text;
        }
    }

    /// Commit IME text into field `id` at the cursor (replacing the
    /// selection), with the same filter / max-length / read-only rules as a
    /// paste, and end the composition.
    pub fn ime_commit(&mut self, id: &WidgetId, committed: String) -> TextAction {
        let state = match self.fields.get_mut(id) {
            Some(s) => s,
            None => return TextAction::None,
        };
        state.preedit.clear();
        state.preedit_cursor = 0;
        if state.config.capability == InputCapability::Mouse || state.config.read_only {
            return TextAction::None;
        }
        state.engaged = true;
        let before = state.text.clone();
        let caret = state.cursor;
        apply_key(state, KeyPress::Paste(committed));
        state.note_edit((before.clone(), caret), false);
        self.reset_blink();
        let after = &self.fields[id].text;
        if after != &before {
            TextAction::TextChanged(after.clone())
        } else {
            TextAction::None
        }
    }

    // =========================================================================
    // Private
    // =========================================================================

    fn reset_blink(&mut self) {
        self.blink_reset_time = 0;
    }
}

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

// =============================================================================
// Free helpers (private)
// =============================================================================

/// Apply a key event to a `TextFieldState`. Returns `true` if consumed.
fn apply_key(state: &mut TextFieldState, key: KeyPress) -> bool {
    let char_count = state.char_count();

    match key {
        KeyPress::Delete => {
            if state.selection_range().is_some() {
                state.delete_selection();
            } else if state.cursor < char_count {
                let byte_idx = state.char_to_byte(state.cursor);
                state.text.remove(byte_idx);
            }
            true
        }
        KeyPress::ArrowLeft => {
            if state.selection_range().is_some() {
                let (lo, _) = state.selection_range().unwrap();
                state.cursor = lo;
                state.selection_start = None;
            } else {
                state.cursor = state.cursor.saturating_sub(1);
            }
            true
        }
        KeyPress::ArrowRight => {
            if state.selection_range().is_some() {
                let (_, hi) = state.selection_range().unwrap();
                state.cursor = hi;
                state.selection_start = None;
            } else if state.cursor < char_count {
                state.cursor += 1;
            }
            true
        }
        KeyPress::Home => {
            state.cursor = 0;
            state.selection_start = None;
            true
        }
        KeyPress::End => {
            state.cursor = char_count;
            state.selection_start = None;
            true
        }
        KeyPress::SelectAll => {
            state.selection_start = Some(0);
            state.cursor = char_count;
            true
        }
        KeyPress::ShiftLeft => {
            if state.selection_start.is_none() {
                state.selection_start = Some(state.cursor);
            }
            state.cursor = state.cursor.saturating_sub(1);
            if state.selection_start == Some(state.cursor) {
                state.selection_start = None;
            }
            true
        }
        KeyPress::ShiftRight => {
            if state.selection_start.is_none() {
                state.selection_start = Some(state.cursor);
            }
            if state.cursor < char_count {
                state.cursor += 1;
            }
            if state.selection_start == Some(state.cursor) {
                state.selection_start = None;
            }
            true
        }
        KeyPress::ShiftHome => {
            if state.selection_start.is_none() {
                state.selection_start = Some(state.cursor);
            }
            state.cursor = 0;
            if state.selection_start == Some(state.cursor) {
                state.selection_start = None;
            }
            true
        }
        KeyPress::ShiftEnd => {
            if state.selection_start.is_none() {
                state.selection_start = Some(state.cursor);
            }
            state.cursor = char_count;
            if state.selection_start == Some(state.cursor) {
                state.selection_start = None;
            }
            true
        }
        KeyPress::Copy => false,
        KeyPress::Paste(ref text) => {
            if state.config.read_only {
                return false;
            }
            if state.selection_range().is_some() {
                state.delete_selection();
            }
            for ch in text.chars() {
                if ch.is_control() && !(ch == '\n' && state.config.multiline) {
                    continue;
                }
                if let Some(filter) = state.config.char_filter {
                    if !filter(ch) {
                        continue;
                    }
                }
                if let Some(max) = state.config.max_len {
                    if state.char_count() >= max {
                        break;
                    }
                }
                let byte_pos = state.char_to_byte(state.cursor);
                state.text.insert(byte_pos, ch);
                state.cursor += 1;
            }
            // Same collapse rule as typing (see `on_char`): a paste ends
            // with a caret, never with a selection over the pasted text.
            state.selection_start = None;
            true
        }
        KeyPress::WordLeft => {
            state.cursor = word_left(&state.text, state.cursor);
            state.selection_start = None;
            true
        }
        KeyPress::WordRight => {
            state.cursor = word_right(&state.text, state.cursor);
            state.selection_start = None;
            true
        }
        KeyPress::DeleteWordBack => {
            if state.selection_range().is_some() {
                state.delete_selection();
            } else {
                let start = word_left(&state.text, state.cursor);
                if start < state.cursor {
                    let byte_lo = state.char_to_byte(start);
                    let byte_hi = state.char_to_byte(state.cursor);
                    state.text.drain(byte_lo..byte_hi);
                    state.cursor = start;
                }
            }
            state.selection_start = None;
            true
        }
        KeyPress::DeleteWordForward => {
            if state.selection_range().is_some() {
                state.delete_selection();
            } else {
                let end = word_right(&state.text, state.cursor);
                if end > state.cursor {
                    let byte_lo = state.char_to_byte(state.cursor);
                    let byte_hi = state.char_to_byte(end);
                    state.text.drain(byte_lo..byte_hi);
                }
            }
            state.selection_start = None;
            true
        }
        KeyPress::Undo | KeyPress::Redo => false,
        KeyPress::ArrowUp
        | KeyPress::ArrowDown
        | KeyPress::Enter
        | KeyPress::Escape
        | KeyPress::Tab
        | KeyPress::Backspace
        | KeyPress::CtrlC
        | KeyPress::PageUp
        | KeyPress::PageDown => false,
    }
}

/// Encode a printable character as PTY bytes.
fn raw_char_to_bytes(ch: char) -> Vec<u8> {
    if ch == '\r' || ch == '\n' {
        return vec![b'\r'];
    }
    if ch == '\x08' {
        return vec![0x7f];
    }
    if ch == '\x1b' {
        return vec![0x1b];
    }
    if (ch as u32) < 0x20 {
        return vec![ch as u8];
    }
    let mut buf = [0u8; 4];
    let s = ch.encode_utf8(&mut buf);
    s.as_bytes().to_vec()
}

/// Map named key presses to ANSI escape sequences for PTY forwarding.
fn key_to_pty_bytes(key: &KeyPress) -> Option<Vec<u8>> {
    match key {
        KeyPress::ArrowLeft  => Some(b"\x1b[D".to_vec()),
        KeyPress::ArrowRight => Some(b"\x1b[C".to_vec()),
        KeyPress::ArrowUp    => Some(b"\x1b[A".to_vec()),
        KeyPress::ArrowDown  => Some(b"\x1b[B".to_vec()),
        KeyPress::Home       => Some(b"\x1b[H".to_vec()),
        KeyPress::End        => Some(b"\x1b[F".to_vec()),
        KeyPress::Delete     => Some(b"\x1b[3~".to_vec()),
        KeyPress::PageUp     => Some(b"\x1b[5~".to_vec()),
        KeyPress::PageDown   => Some(b"\x1b[6~".to_vec()),
        KeyPress::Enter      => Some(b"\r".to_vec()),
        KeyPress::Escape     => Some(b"\x1b".to_vec()),
        KeyPress::Tab        => Some(b"\t".to_vec()),
        KeyPress::Backspace  => Some(b"\x7f".to_vec()),
        KeyPress::CtrlC      => Some(b"\x03".to_vec()),
        KeyPress::ShiftLeft  => Some(b"\x1b[1;2D".to_vec()),
        KeyPress::ShiftRight => Some(b"\x1b[1;2C".to_vec()),
        _ => None,
    }
}

// =============================================================================
// Unit tests
// =============================================================================

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

    fn store() -> TextFieldStore {
        TextFieldStore::new()
    }

    fn id(s: &str) -> WidgetId {
        WidgetId::new(s)
    }

    fn focused_with(text: &str, cursor: usize) -> TextFieldStore {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        s.set_text(&id("f"), text);
        s.field_state_mut(&id("f")).unwrap().cursor = cursor;
        s
    }

    // H2 §7 scenario 8 — word movement over "hello world foo".
    #[test]
    fn word_right_and_left_land_on_each_word_boundary() {
        let mut s = focused_with("hello world foo", 0);
        let mut stops = Vec::new();
        for _ in 0..4 {
            s.on_key(KeyPress::WordRight);
            stops.push(s.cursor(&id("f")));
        }
        assert_eq!(stops, vec![6, 12, 15, 15]);
        let mut stops = Vec::new();
        for _ in 0..4 {
            s.on_key(KeyPress::WordLeft);
            stops.push(s.cursor(&id("f")));
        }
        assert_eq!(stops, vec![12, 6, 0, 0]);
    }

    #[test]
    fn word_movement_clears_the_selection() {
        let mut s = focused_with("hello world", 0);
        s.on_key(KeyPress::SelectAll);
        s.on_key(KeyPress::WordLeft);
        assert_eq!(s.selection_range(&id("f")), None);
    }

    #[test]
    fn delete_word_back_removes_the_previous_word() {
        let mut s = focused_with("hello world foo", 11);
        let action = s.on_key(KeyPress::DeleteWordBack);
        assert_eq!(action, TextAction::TextChanged("hello  foo".into()));
        assert_eq!(s.cursor(&id("f")), 6);
        // at the start: nothing to delete
        let mut s = focused_with("hello", 0);
        assert_eq!(s.on_key(KeyPress::DeleteWordBack), TextAction::None);
    }

    #[test]
    fn delete_word_forward_removes_the_next_word_and_keeps_the_cursor() {
        let mut s = focused_with("hello world foo", 6);
        s.on_key(KeyPress::DeleteWordForward);
        assert_eq!(s.text(&id("f")), "hello foo");
        assert_eq!(s.cursor(&id("f")), 6);
    }

    #[test]
    fn word_deletion_with_a_selection_deletes_only_the_selection() {
        let mut s = focused_with("hello world foo", 0);
        let st = s.field_state_mut(&id("f")).unwrap();
        st.selection_start = Some(6);
        st.cursor = 8; // "wo"
        s.on_key(KeyPress::DeleteWordBack);
        assert_eq!(s.text(&id("f")), "hello rld foo");
        assert_eq!(s.cursor(&id("f")), 6);
        let st = s.field_state_mut(&id("f")).unwrap();
        st.selection_start = Some(6);
        st.cursor = 9; // "rld"
        s.on_key(KeyPress::DeleteWordForward);
        assert_eq!(s.text(&id("f")), "hello  foo");
    }

    #[test]
    fn word_movement_counts_chars_not_bytes() {
        let mut s = focused_with("привет мир", 0);
        s.on_key(KeyPress::WordRight);
        assert_eq!(s.cursor(&id("f")), 7);
        s.on_key(KeyPress::DeleteWordForward);
        assert_eq!(s.text(&id("f")), "привет ");
    }

    // H2 §7 scenario 6, store level — preedit is an overlay, commit inserts.
    #[test]
    fn display_splices_the_preedit_at_the_caret() {
        let mut st = TextFieldState::new(TextFieldConfig::text());
        st.text = "ab".into();
        st.cursor = 1;
        assert_eq!(st.display(), ("ab".to_string(), 1, None));
        st.preedit = "日本".into();
        st.preedit_cursor = 1;
        assert_eq!(st.display(), ("a日本b".to_string(), 2, Some((1, 3))));
        // Boundaries of "a日本b" (5) map back to those of "ab" (3).
        assert_eq!(st.buffer_positions(vec![0.0, 1.0, 2.0, 3.0, 4.0]), vec![0.0, 3.0, 4.0]);
    }

    #[test]
    fn preedit_stays_out_of_the_text_until_commit() {
        let mut s = focused_with("x", 1);
        s.preedit_set(&id("f"), "ab".into(), 2);
        let st = s.field_state(&id("f")).unwrap();
        assert_eq!(st.preedit, "ab");
        assert_eq!(st.preedit_cursor, 2);
        assert_eq!(st.text, "x");
        let action = s.ime_commit(&id("f"), "ab".into());
        assert_eq!(action, TextAction::TextChanged("xab".into()));
        let st = s.field_state(&id("f")).unwrap();
        assert!(st.preedit.is_empty());
        assert_eq!(st.cursor, 3);
    }

    #[test]
    fn ime_commit_obeys_read_only_filter_and_max_len() {
        let mut s = store();
        s.register("ro", TextFieldConfig::read_only());
        s.focus("ro");
        s.preedit_set(&id("ro"), "zz".into(), 0);
        assert_eq!(s.ime_commit(&id("ro"), "zz".into()), TextAction::None);
        assert!(s.field_state(&id("ro")).unwrap().preedit.is_empty());

        let mut s = store();
        s.register("n", TextFieldConfig::text().with_filter(|c| c.is_ascii_digit()).with_max_len(3));
        s.focus("n");
        s.ime_commit(&id("n"), "1a2b34".into());
        assert_eq!(s.text(&id("n")), "123");
    }

    #[test]
    fn preedit_cursor_is_clamped_and_blur_drops_the_composition() {
        let mut s = focused_with("", 0);
        s.preedit_set(&id("f"), "日本".into(), 10);
        assert_eq!(s.field_state(&id("f")).unwrap().preedit_cursor, 2);
        s.blur();
        assert!(s.field_state(&id("f")).unwrap().preedit.is_empty());
    }

    #[test]
    fn cut_selection_returns_and_removes_the_selected_text() {
        let mut s = focused_with("hello world", 0);
        let st = s.field_state_mut(&id("f")).unwrap();
        st.selection_start = Some(0);
        st.cursor = 6;
        assert_eq!(s.cut_selection(&id("f")), Some("hello ".into()));
        assert_eq!(s.text(&id("f")), "world");
        assert_eq!(s.cursor(&id("f")), 0);
        assert_eq!(s.cut_selection(&id("f")), None, "no selection left");
    }

    #[test]
    fn cut_on_a_read_only_field_is_a_copy() {
        let mut s = store();
        s.register("ro", TextFieldConfig::read_only());
        s.set_text(&id("ro"), "keep");
        let st = s.field_state_mut(&id("ro")).unwrap();
        st.selection_start = Some(0);
        st.cursor = 4;
        assert_eq!(s.cut_selection(&id("ro")), Some("keep".into()));
        assert_eq!(s.text(&id("ro")), "keep");
    }

    #[test]
    fn register_and_focus() {
        let mut s = store();
        s.register("a", TextFieldConfig::text());
        assert!(s.has_field(&id("a")));
        assert!(!s.is_focused(&id("a")));
        s.focus("a");
        assert!(s.is_focused(&id("a")));
    }

    #[test]
    fn char_input() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        let action = s.on_char('x');
        assert_eq!(action, TextAction::TextChanged("x".into()));
        assert_eq!(s.text(&id("f")), "x");
        assert_eq!(s.cursor(&id("f")), 1);
    }

    #[test]
    fn char_filter() {
        let mut s = store();
        s.register("f", TextFieldConfig::text().with_filter(|c| c.is_ascii_digit()));
        s.focus("f");
        let _ = s.on_char('5');
        let _ = s.on_char('Z'); // rejected
        assert_eq!(s.text(&id("f")), "5");
    }

    #[test]
    fn undo_groups_typed_words_and_redo_replays() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        for c in "hi yo".chars() {
            s.on_char(c);
        }
        s.on_char('\x08');
        assert_eq!(s.text(&id("f")), "hi y");
        assert_eq!(s.on_key(KeyPress::Undo), TextAction::TextChanged("hi yo".into()));
        s.on_key(KeyPress::Undo);
        assert_eq!(s.text(&id("f")), "hi ");
        s.on_key(KeyPress::Undo);
        assert_eq!(s.text(&id("f")), "hi");
        s.on_key(KeyPress::Undo);
        assert_eq!(s.text(&id("f")), "");
        assert_eq!(s.on_key(KeyPress::Undo), TextAction::None);
        s.on_key(KeyPress::Redo);
        assert_eq!(s.text(&id("f")), "hi");
        assert_eq!(s.cursor(&id("f")), 2);
        s.on_char('!');
        assert_eq!(s.on_key(KeyPress::Redo), TextAction::None, "a new edit drops the redo branch");
    }

    #[test]
    fn caret_moves_split_undo_steps_and_set_text_drops_history() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        s.on_char('a');
        s.on_key(KeyPress::ArrowLeft);
        s.on_char('b');
        assert_eq!(s.text(&id("f")), "ba");
        s.on_key(KeyPress::Undo);
        assert_eq!(s.text(&id("f")), "a");
        s.set_text(&id("f"), "new");
        assert_eq!(s.on_key(KeyPress::Undo), TextAction::None);
        s.on_key(KeyPress::SelectAll);
        s.cut_selection(&id("f"));
        s.ime_commit(&id("f"), "日本".into());
        s.on_key(KeyPress::Undo);
        assert_eq!(s.text(&id("f")), "");
        s.on_key(KeyPress::Undo);
        assert_eq!(s.text(&id("f")), "new");
    }

    #[test]
    fn commit_cancel() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        s.set_text(&id("f"), "hello");
        s.begin_edit(&id("f"));
        s.on_char('X');
        assert_eq!(s.text(&id("f")), "helloX");
        let action = s.on_char('\x1b');
        assert_eq!(action, TextAction::Cancel);
        assert_eq!(s.text(&id("f")), "hello");

        s.set_text(&id("f"), "hi");
        s.begin_edit(&id("f"));
        let action = s.on_char('\r');
        assert_eq!(action, TextAction::Commit("hi".into()));
    }

    #[test]
    fn blink() {
        let mut s = store();
        // blink_reset_time = 0, now = 0 → elapsed = 0 → visible
        assert!(s.cursor_visible(0));
        // elapsed = 600 → phase 1 → hidden
        assert!(!s.cursor_visible(600));
        // elapsed = 1100 → phase 2 → visible
        assert!(s.cursor_visible(1100));
        s.set_blink_time(1000);
        // now = 1000 → elapsed = 0 → visible
        assert!(s.cursor_visible(1000));
    }

    #[test]
    fn selection_and_delete() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        s.set_text(&id("f"), "hello");
        // SelectAll
        s.on_key(KeyPress::SelectAll);
        assert_eq!(s.selection_range(&id("f")), Some((0, 5)));
        // Delete selection
        s.on_key(KeyPress::Delete);
        assert_eq!(s.text(&id("f")), "");
        assert_eq!(s.cursor(&id("f")), 0);
    }

    #[test]
    fn raw_mode() {
        let mut s = store();
        s.register("pty", TextFieldConfig::raw());
        s.focus("pty");
        let action = s.on_char('a');
        assert_eq!(action, TextAction::RawInput(vec![b'a']));
        let action = s.on_key(KeyPress::ArrowUp);
        assert_eq!(action, TextAction::RawInput(b"\x1b[A".to_vec()));
    }

    #[test]
    fn read_only() {
        let mut s = store();
        s.register("ro", TextFieldConfig::read_only());
        s.focus("ro");
        s.set_text(&id("ro"), "fixed");
        let action = s.on_char('X');
        assert_eq!(action, TextAction::None);
        assert_eq!(s.text(&id("ro")), "fixed");
        // SelectAll still works
        let action = s.on_key(KeyPress::SelectAll);
        assert_eq!(action, TextAction::None);
        assert_eq!(s.selection_range(&id("ro")), Some((0, 5)));
    }

    #[test]
    fn focused_is_stale_eventually_catches_a_never_stamped_field() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        // A field whose host never calls update_field/mark_seen at all
        // goes stale the same way one whose stamps stopped does — a
        // focusable field with no stamp call anywhere is a bug, not a
        // safe default to trust forever.
        for _ in 0..10 {
            s.begin_frame();
        }
        assert!(s.focused_is_stale());
    }

    #[test]
    fn mark_seen_keeps_a_button_style_field_fresh_without_touching_geometry() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        for _ in 0..10 {
            s.begin_frame();
            s.mark_seen(&id("f"));
        }
        assert!(!s.focused_is_stale());
        // mark_seen never sets rect/char_positions — a field stamped only
        // this way must never become hit-testable by on_drag_start.
        assert!(s.field_state(&id("f")).unwrap().last_rect.is_none());
        assert!(s.field_state(&id("f")).unwrap().last_char_positions.is_empty());
    }

    #[test]
    fn mark_seen_clears_the_never_stamped_flag() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        assert!(s.focused_was_never_stamped());
        // current_frame must have advanced past 0 for the stamp to be
        // distinguishable from "never stamped" (both read as last_frame == 0
        // at the very first tick) — an ordinary host has rendered many
        // frames before the first keystroke ever reaches dispatch.
        s.begin_frame();
        s.mark_seen(&id("f"));
        assert!(!s.focused_was_never_stamped());
    }

    #[test]
    fn focused_was_never_stamped_true_immediately_after_focus() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        assert!(!s.focused_was_never_stamped(), "nothing focused yet");
        s.focus("f");
        assert!(s.focused_was_never_stamped());
    }

    #[test]
    fn focused_was_never_stamped_false_once_update_field_lands() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        s.begin_frame();
        s.update_field(&id("f"), (0.0, 0.0, 10.0, 10.0), vec![0.0, 10.0]);
        assert!(!s.focused_was_never_stamped());
    }

    #[test]
    fn focused_was_never_stamped_false_when_nothing_focused() {
        let s = store();
        assert!(!s.focused_was_never_stamped());
    }

    #[test]
    fn focused_is_stale_false_when_nothing_focused() {
        let s = store();
        assert!(!s.focused_is_stale());
    }

    #[test]
    fn focused_is_stale_detects_field_that_stopped_rendering() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        s.begin_frame();
        s.update_field(&id("f"), (0.0, 0.0, 10.0, 10.0), vec![0.0, 10.0]);
        // Freshly drawn — not stale.
        assert!(!s.focused_is_stale());

        // A couple of frames within the tolerance (the double begin_frame
        // per render pass a real host does) — still not stale.
        s.begin_frame();
        s.begin_frame();
        assert!(!s.focused_is_stale());

        // The field's owner stops being drawn (e.g. its modal closed)
        // while focus lingers — eventually detected as stale.
        for _ in 0..5 {
            s.begin_frame();
        }
        assert!(s.focused_is_stale());
    }

    #[test]
    fn unregister() {
        let mut s = store();
        s.register("a", TextFieldConfig::text());
        s.focus("a");
        s.unregister(&id("a"));
        assert!(!s.has_field(&id("a")));
        assert!(s.focused().is_none());
    }

    #[test]
    fn drag_select() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        s.set_text(&id("f"), "hello");
        s.begin_frame();
        // positions: 0..5 chars, each 10px wide
        let positions: Vec<f64> = (0..=5).map(|i| i as f64 * 10.0).collect();
        s.update_field(&id("f"), (0.0, 0.0, 50.0, 20.0), positions);
        // drag_start at x=5 → char 0 (mid of char 0 is 5, x < 5 → char 0, x==5 → char 1)
        s.on_drag_start(3.0, 5.0);
        let anchor = s.field_state(&id("f")).unwrap().selection_start;
        assert!(anchor.is_some());
        // drag_move to x=35 → char 3 (mid of char 3 is 35, x<35 → 3)
        s.on_drag_move(25.0);
        let cursor_after = s.cursor(&id("f"));
        assert_ne!(cursor_after, anchor.unwrap());
        s.on_drag_end();
        assert!(s.selection_range(&id("f")).is_some());
    }

    #[test]
    fn begin_drag_at_places_caret_without_geometric_search() {
        // A caller that already knows which field was hit (e.g. a z-order-
        // aware coordinator) can go straight through `begin_drag_at` — this
        // must work even before the field has ever been drawn (no
        // `update_field` call yet, so `last_rect` is `None` and the
        // geometric search `on_drag_start` relies on would find nothing).
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.set_text(&id("f"), "hello");
        assert_eq!(s.cursor(&id("f")), 5);

        // No update_field call — last_char_positions is empty, so
        // cursor_from_x degrades to 0 rather than panicking.
        s.begin_drag_at("f", 12.0);
        assert!(s.is_focused(&id("f")));
        assert_eq!(s.cursor(&id("f")), 0);
        assert!(s.is_engaged(&id("f")));

        // Once geometry is known, the caret lands on the character nearest x.
        let positions: Vec<f64> = (0..=5).map(|i| i as f64 * 10.0).collect();
        s.update_field(&id("f"), (0.0, 0.0, 50.0, 20.0), positions);
        s.begin_drag_at("f", 25.0);
        assert_eq!(s.cursor(&id("f")), 3);
        // A fresh press collapses any prior selection to a point at the hit char.
        assert_eq!(s.field_state(&id("f")).unwrap().selection_start, Some(3));
    }

    #[test]
    fn max_len_enforced() {
        let mut s = store();
        s.register("f", TextFieldConfig::text().with_max_len(3));
        s.focus("f");
        s.on_char('a');
        s.on_char('b');
        s.on_char('c');
        let action = s.on_char('d');
        assert_eq!(action, TextAction::None);
        assert_eq!(s.text(&id("f")), "abc");
    }

    #[test]
    fn utf8_cursor_arithmetic() {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.focus("f");
        s.on_char('А'); // Cyrillic, 2-byte UTF-8
        s.on_char('Б');
        s.on_char('В');
        assert_eq!(s.text(&id("f")).chars().count(), 3);
        assert_eq!(s.cursor(&id("f")), 3);
        // Backspace
        s.on_char('\x08');
        assert_eq!(s.text(&id("f")).chars().count(), 2);
        assert_eq!(s.cursor(&id("f")), 2);
    }

    fn laid_out(text: &str) -> TextFieldStore {
        let mut s = store();
        s.register("f", TextFieldConfig::text());
        s.set_text(&id("f"), text);
        let n = text.chars().count();
        let positions: Vec<f64> = (0..=n).map(|i| i as f64 * 10.0).collect();
        s.update_field(&id("f"), (0.0, 0.0, n as f64 * 10.0, 20.0), positions);
        s
    }

    #[test]
    fn select_drag_selects_press_to_release_in_both_directions() {
        let mut s = laid_out("hello world");
        s.select_drag("f", 12.0, 48.0);
        assert!(s.is_focused(&id("f")) && s.is_engaged(&id("f")));
        assert_eq!(s.selection_range(&id("f")), Some((1, 5)));
        assert_eq!(s.copy_selection().as_deref(), Some("ello"));
        s.select_drag("f", 48.0, 12.0);
        assert_eq!(s.selection_range(&id("f")), Some((1, 5)));
        assert_eq!(s.cursor(&id("f")), 1, "the focus follows the release");
        assert!(!s.drag_active());
        // a drag back onto its start char leaves a caret
        s.select_drag("f", 12.0, 13.0);
        assert_eq!(s.selection_range(&id("f")), None);
        assert_eq!(s.cursor(&id("f")), 1);
    }

    #[test]
    fn click_count_selects_caret_word_or_line() {
        let mut s = laid_out("привет мир");
        // x=83 is inside char 8 ('и'); nearest boundary would be 8 too, but
        // x=88 (right half of 'и') must still select "мир", not the end.
        s.select_at_click_count("f", 88.0, 2);
        assert_eq!(s.selection_range(&id("f")), Some((7, 10)));
        assert_eq!(s.copy_selection().as_deref(), Some("мир"));
        s.select_at_click_count("f", 25.0, 3);
        assert_eq!(s.selection_range(&id("f")), Some((0, 10)));
        s.select_at_click_count("f", 25.0, 1);
        assert_eq!(s.selection_range(&id("f")), None);
        assert_eq!(s.cursor(&id("f")), 3);
    }

    #[test]
    fn multi_click_on_a_masked_field_selects_everything() {
        let mut s = store();
        s.register("p", TextFieldConfig::password());
        s.set_text(&id("p"), "two words");
        let positions: Vec<f64> = (0..=9).map(|i| i as f64 * 10.0).collect();
        s.update_field(&id("p"), (0.0, 0.0, 90.0, 20.0), positions);
        s.select_at_click_count("p", 5.0, 2);
        assert_eq!(s.selection_range(&id("p")), Some((0, 9)));
    }

    #[test]
    fn selection_accessor_and_select_all() {
        let mut s = laid_out("你好 世界");
        assert_eq!(s.selection(&id("f")), Some(TextSelection::caret(5)));
        s.select_all("f");
        assert_eq!(s.selection(&id("f")).unwrap().range(), (0, 5));
        assert_eq!(s.copy_selection().as_deref(), Some("你好 世界"));
        s.set_selection("f", TextSelection::new(4, 1));
        assert_eq!(s.copy_selection().as_deref(), Some("好 世"));
        assert_eq!(s.selection(&id("f")), Some(TextSelection::new(4, 1)));
        assert!(s.selection(&id("missing")).is_none());
    }
}