nsh-core 0.5.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
//! A selection across the texts of a selectable view (a `View` with
//! `selectable`, a selectable `TextView`): one range from a point in one text
//! to a point in another, in document order, as a browser selects across
//! the elements of a page.
//!
//! The model is platform-independent and runs where the gestures are: on
//! each platform's main thread, which knows the texts' layouts. A backend
//! lists the texts of an area in document order ([`SelectionTexts`]: their
//! content, frames and hit-testing), feeds the model its gestures (pointer
//! presses and drags with their click count, a long press, the handles'
//! drags, select all) and draws what [`SelectionModel::ranges`] says, with
//! its own highlight, handles and menus; copying takes
//! [`SelectionModel::text`].
//!
//! Offsets are UTF-16 code units, as everywhere text crosses to the
//! platforms (`TextLine::start`); the model never puts one inside a
//! surrogate pair.
//!
//! A point is hit-tested across the texts as a browser does, in reading
//! order: a point inside a text's frame is in that text; otherwise, among
//! the texts whose rows (vertical extent) contain the point, the
//! horizontally nearest one; above every text, the first text's start;
//! below every text, the last text's end; between rows, the end of the last
//! text above (in document order) or the start of the first text below,
//! whichever is vertically nearer (the text above on a tie). A point is
//! clamped into the chosen text's frame before
//! [`SelectionTexts::offset_at`].
//!
//! Words are runs of letters, digits, `_` and combining marks, runs of
//! spaces, or single other characters: punctuation, an emoji, each CJK
//! ideograph or kana (scripts written without spaces between words).

use std::ops::Range;

use crate::geometry::{Bounds, Point, Points};

/// A place in the texts of an area: a text (its index in document order)
/// and a UTF-16 offset in it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct TextPosition {
    /// The text, in document order.
    pub text: usize,
    /// The UTF-16 offset in the text (0 ..= its length).
    pub offset: u32,
}

impl TextPosition {
    /// Offset `offset` of text `text`.
    pub const fn new(text: usize, offset: u32) -> Self {
        Self { text, offset }
    }
}

/// What a backend knows of the texts of one selectable view, in document
/// order (the area's subtree, depth first): their content, where they are
/// and which character is where. Coordinates are the area's (its top left
/// is the origin, y down), scroll offsets of the views between applied.
pub trait SelectionTexts {
    /// How many texts take part.
    fn len(&self) -> usize;

    /// Whether none takes part.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Text `i`'s content (attachments are U+FFFC, left out of copies).
    fn content(&self, i: usize) -> &str;

    /// The UTF-16 range `range` of text `i` as a copy gives it. By default
    /// its content's characters without attachments' placeholders; a
    /// backend that has the texts' runs gives
    /// [`crate::AttributedText::copied_text`], which also leaves hidden
    /// runs out (`visibility: "hidden"` on a span).
    fn copied(&self, i: usize, range: Range<u32>) -> String {
        let content = self.content(i);
        content[byte_offset(content, range.start)..byte_offset(content, range.end)]
            .chars()
            .filter(|&c| c != OBJECT_REPLACEMENT)
            .collect()
    }

    /// Text `i`'s content box.
    fn frame(&self, i: usize) -> Bounds<Points>;

    /// The UTF-16 offset of text `i` nearest `point` (inside its content
    /// box; the model clamps points into it first): the caret position a
    /// click there puts, as the text engine hit-tests its lines.
    fn offset_at(&self, i: usize, point: Point<Points>) -> u32;

    /// A stable identity of text `i` (its view's node), so that a
    /// selection follows its texts when others come or go before them
    /// ([`SelectionModel::texts_changed`]). By default its index: texts
    /// are then only clamped.
    fn key(&self, i: usize) -> u64 {
        i as u64
    }

    /// Whether text `i` continues text `i - 1`: the next part of a long
    /// line drawn as several texts, one per wrapped part (the view's
    /// [`ViewProps::continues_text`](crate::ViewProps::continues_text)).
    /// A copy joins the two with nothing between them, and a word or a
    /// paragraph (a double or triple click) runs on across them. By
    /// default none does; the first text never does.
    fn continues(&self, i: usize) -> bool {
        let _ = i;
        false
    }

    /// The box around what the characters `range` of text `i` cover, in
    /// the coordinates of the content boxes ([`Self::frame`]): what
    /// [`SelectionModel::selected_bounds`] unites. `None` by default: the
    /// platform's text engine places characters, the model does not.
    fn range_bounds(&self, i: usize, range: Range<u32>) -> Option<Bounds<Points>> {
        let _ = (i, range);
        None
    }
}

/// What a press, drag or extension selects by.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Granularity {
    /// Characters (a press and drag).
    #[default]
    Character,
    /// Words (a double click, a long press, then drags by words).
    Word,
    /// Paragraphs: a whole text (a triple click).
    Paragraph,
}

/// One of the two ends of a selection, for touch handles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Handle {
    /// The start (in document order).
    Start,
    /// The end.
    End,
}

/// The selection of one area: an anchor where it started and a focus
/// where it goes, extended by words or paragraphs after a double or triple
/// click. Methods that change it return whether it changed, so the backend
/// redraws only then.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SelectionModel {
    anchor: Option<TextPosition>,
    focus: Option<TextPosition>,
    granularity: Granularity,
    /// The unit (word, paragraph) around the anchor that a drag by words
    /// or paragraphs keeps selected.
    anchor_unit: Option<(TextPosition, TextPosition)>,
    /// The keys of the texts of the anchor, the focus and the anchor unit's
    /// ends ([`SelectionTexts::key`]), as of the last change.
    keys: [Option<u64>; 4],
}

impl SelectionModel {
    /// No selection.
    pub fn new() -> Self {
        Self::default()
    }

    /// Nothing is selected (no range, or an empty one).
    pub fn is_empty(&self) -> bool {
        self.bounds().is_none_or(|(start, end)| start == end)
    }

    /// A pointer press at `point`: one click puts the anchor there (nothing
    /// selected until a drag), two select the word, three the paragraph
    /// (the whole text); `extend` (Shift) extends the selection from its
    /// anchor to `point` instead, by the current granularity.
    pub fn press(
        &mut self,
        texts: &impl SelectionTexts,
        point: Point<Points>,
        clicks: u32,
        extend: bool,
    ) -> bool {
        let before = self.bounds();
        let Some(pos) = hit(texts, point) else {
            return self.clear();
        };
        if extend && self.anchor.is_some() {
            self.extend_to(texts, pos);
            self.remember(texts);
            return self.bounds() != before;
        }
        let granularity = match clicks {
            0 | 1 => Granularity::Character,
            2 => Granularity::Word,
            _ => Granularity::Paragraph,
        };
        self.select_unit(texts, pos, granularity);
        self.remember(texts);
        self.bounds() != before
    }

    /// The pointer moved to `point` while pressed: the focus follows, by
    /// the press's granularity (from text to text: above the first text is
    /// its start, below the last its end, between two the nearer edge).
    pub fn drag(&mut self, texts: &impl SelectionTexts, point: Point<Points>) -> bool {
        if self.anchor.is_none() {
            return false;
        }
        let Some(pos) = hit(texts, point) else {
            return false;
        };
        let before = self.bounds();
        self.extend_to(texts, pos);
        self.remember(texts);
        self.bounds() != before
    }

    /// Selects the word at `point` (a long press on a touch screen).
    pub fn select_word_at(&mut self, texts: &impl SelectionTexts, point: Point<Points>) -> bool {
        let before = self.bounds();
        let Some(pos) = hit(texts, point) else {
            return self.clear();
        };
        self.select_unit(texts, pos, Granularity::Word);
        self.remember(texts);
        self.bounds() != before
    }

    /// Handle `handle` dragged to `point`: that end moves, the other stays
    /// (they swap when one passes the other).
    pub fn move_handle(
        &mut self,
        texts: &impl SelectionTexts,
        handle: Handle,
        point: Point<Points>,
    ) -> bool {
        let Some((start, end)) = self.bounds() else {
            return false;
        };
        let Some(pos) = hit(texts, point) else {
            return false;
        };
        // The end that stays becomes the anchor: from here on the selection
        // is by characters, as handles move.
        let fixed = match handle {
            Handle::Start => end,
            Handle::End => start,
        };
        self.anchor = Some(fixed);
        self.focus = Some(pos);
        self.granularity = Granularity::Character;
        self.anchor_unit = None;
        self.remember(texts);
        self.bounds() != Some((start, end))
    }

    /// Selects every text of the area.
    pub fn select_all(&mut self, texts: &impl SelectionTexts) -> bool {
        if texts.is_empty() {
            return self.clear();
        }
        let before = self.bounds();
        let last = texts.len() - 1;
        self.anchor = Some(TextPosition::new(0, 0));
        self.focus = Some(TextPosition::new(last, utf16_len(texts.content(last))));
        self.granularity = Granularity::Character;
        self.anchor_unit = None;
        self.remember(texts);
        self.bounds() != before
    }

    /// Clears the selection.
    pub fn clear(&mut self) -> bool {
        let had = self.anchor.is_some();
        *self = Self::default();
        had
    }

    /// The texts changed (new content, texts added or gone): positions are
    /// clamped to what is there, and a selection whose texts are gone is
    /// cleared. `texts` is the new list.
    pub fn texts_changed(&mut self, texts: &impl SelectionTexts) -> bool {
        let (Some(mut anchor), Some(mut focus)) = (self.anchor, self.focus) else {
            return false;
        };
        // Each end follows its text by key: texts that came or went before
        // it move its index; a text that is gone clears the selection.
        let find = |key: Option<u64>, at: usize| -> Option<usize> {
            let key = key?;
            if at < texts.len() && texts.key(at) == key {
                return Some(at);
            }
            (0..texts.len()).find(|&i| texts.key(i) == key)
        };
        let (Some(a), Some(f)) = (
            find(self.keys[0], anchor.text),
            find(self.keys[1], focus.text),
        ) else {
            return self.clear();
        };
        let moved = a != anchor.text || f != focus.text;
        anchor.text = a;
        focus.text = f;
        self.anchor = Some(anchor);
        self.focus = Some(focus);
        if let Some((u0, u1)) = self.anchor_unit {
            self.anchor_unit = match (find(self.keys[2], u0.text), find(self.keys[3], u1.text)) {
                (Some(i), Some(j)) => Some((
                    TextPosition::new(i, u0.offset),
                    TextPosition::new(j, u1.offset),
                )),
                _ => None,
            };
        }
        let before = self.bounds();
        self.anchor = Some(clamp_position(texts, anchor));
        self.focus = Some(clamp_position(texts, focus));
        self.anchor_unit = self.anchor_unit.and_then(|(a, b)| {
            (a.text < texts.len() && b.text < texts.len())
                .then(|| (clamp_position(texts, a), clamp_position(texts, b)))
        });
        if self.anchor_unit.is_none() {
            self.granularity = Granularity::Character;
        }
        self.remember(texts);
        moved || self.bounds() != before
    }

    /// Records the keys of the texts the selection is in.
    fn remember(&mut self, texts: &impl SelectionTexts) {
        let key = |p: Option<TextPosition>| {
            p.filter(|p| p.text < texts.len())
                .map(|p| texts.key(p.text))
        };
        self.keys = [
            key(self.anchor),
            key(self.focus),
            key(self.anchor_unit.map(|u| u.0)),
            key(self.anchor_unit.map(|u| u.1)),
        ];
    }

    /// The start and the end, in document order (`None` without a
    /// selection).
    pub fn bounds(&self) -> Option<(TextPosition, TextPosition)> {
        let (anchor, focus) = (self.anchor?, self.focus?);
        Some((anchor.min(focus), anchor.max(focus)))
    }

    /// What each text has selected: its index and UTF-16 range, in order,
    /// only non-empty ranges (what the backend highlights).
    pub fn ranges(&self, texts: &impl SelectionTexts) -> Vec<(usize, Range<u32>)> {
        let Some((start, end)) = self.bounds() else {
            return Vec::new();
        };
        if texts.is_empty() || start == end {
            return Vec::new();
        }
        let last = end.text.min(texts.len() - 1);
        (start.text..=last)
            .filter_map(|i| {
                let len = utf16_len(texts.content(i));
                let from = if i == start.text {
                    start.offset.min(len)
                } else {
                    0
                };
                let to = if i == end.text {
                    end.offset.min(len)
                } else {
                    len
                };
                (from < to).then_some((i, from..to))
            })
            .collect()
    }

    /// The selected text, as a copy gives it: each text's selected part,
    /// attachments and hidden runs left out ([`SelectionTexts::copied`]),
    /// a text that continues the one before it
    /// ([`SelectionTexts::continues`]) joined to it with nothing between,
    /// other texts on one row (their frames overlap vertically) joined by a
    /// tab, the others by a line break; an empty text inside the selection
    /// counts as a text, so a blank line stays in the copy.
    pub fn text(&self, texts: &impl SelectionTexts) -> String {
        let mut out = String::new();
        let mut previous: Option<(usize, Bounds<Points>)> = None;
        let ranges = self.ranges(texts);
        let (Some(&(first, _)), Some(&(last, _))) = (ranges.first(), ranges.last()) else {
            return out;
        };
        let mut ranges = ranges.into_iter().peekable();
        for i in first..=last {
            // An empty text between the ends (a blank line of code) has
            // nothing to highlight but still takes its line in a copy.
            let range = match ranges.next_if(|&(at, _)| at == i) {
                Some((_, range)) => range,
                None if texts.content(i).is_empty() => 0..0,
                None => continue,
            };
            let frame = texts.frame(i);
            if let Some((before, previous)) = previous
                && (before + 1 != i || !continues(texts, i))
            {
                let same_row = previous.top() < frame.bottom() && frame.top() < previous.bottom();
                out.push(if same_row { '\t' } else { '\n' });
            }
            previous = Some((i, frame));
            out.push_str(&texts.copied(i, range));
        }
        out
    }

    /// The box around what is selected in `texts`, in their coordinates:
    /// each text's part of the selection ([`SelectionTexts::range_bounds`])
    /// united. `None` while nothing is selected, or where the texts cannot
    /// place their characters.
    pub fn selected_bounds(&self, texts: &impl SelectionTexts) -> Option<Bounds<Points>> {
        self.ranges(texts)
            .into_iter()
            .filter_map(|(i, range)| texts.range_bounds(i, range))
            .reduce(|a, b| a.union(&b))
    }

    /// Where the selection starts in the copy of all of `texts` (what
    /// [`Self::text`] gives once everything is selected), in UTF-16 code
    /// units: what maps it back to the document the texts show.
    pub fn start_offset(&self, texts: &impl SelectionTexts) -> u32 {
        let Some((start, _)) = self.bounds() else {
            return 0;
        };
        if texts.is_empty() || (start.text == 0 && start.offset == 0) {
            return 0;
        }
        let before = Self {
            anchor: Some(TextPosition { text: 0, offset: 0 }),
            focus: Some(start),
            ..Self::default()
        };
        let mut len = utf16_len(&before.text(texts));
        // A selection from the start of a text: the break before it.
        if start.offset == 0 && len > 0 {
            len += 1;
        }
        len
    }

    /// Puts the anchor at `pos` and selects the unit of `granularity`
    /// around it (nothing for characters).
    fn select_unit(
        &mut self,
        texts: &impl SelectionTexts,
        pos: TextPosition,
        granularity: Granularity,
    ) {
        self.granularity = granularity;
        if granularity == Granularity::Character {
            self.anchor = Some(pos);
            self.focus = Some(pos);
            self.anchor_unit = None;
        } else {
            let unit = unit_at(texts, pos, granularity);
            self.anchor = Some(unit.0);
            self.focus = Some(unit.1);
            self.anchor_unit = Some(unit);
        }
    }

    /// Moves the focus to `pos` by the current granularity: by words or
    /// paragraphs, the anchor's unit stays selected and the focus goes to
    /// the edge of the unit at `pos` that is farther from it.
    fn extend_to(&mut self, texts: &impl SelectionTexts, pos: TextPosition) {
        let Some((unit_start, unit_end)) = self.anchor_unit else {
            self.focus = Some(pos);
            return;
        };
        let (start, end) = unit_at(texts, pos, self.granularity);
        if pos < unit_start {
            self.anchor = Some(unit_end);
            self.focus = Some(start.min(unit_start));
        } else {
            self.anchor = Some(unit_start);
            self.focus = Some(end.max(unit_end));
        }
    }
}

/// U+FFFC, which stands for an attachment in a text's content.
const OBJECT_REPLACEMENT: char = '\u{FFFC}';

/// The order of the texts a backend listed child by child, in mount order:
/// `runs` are the children's frames (in their parent) and the ranges of
/// texts each added. The children with texts go by their tops when they
/// stack (no two share a row): a virtual list's cells, which recycling
/// leaves in mount order rather than their items'. Otherwise (a row, an
/// overlay) mount order stands. Children without texts never count: a
/// spare cell left where it was may overlap the shown ones. `None` when
/// the order stays; else the texts' indices in their new order, from the
/// first run's start.
pub fn reading_order(runs: &[(Bounds<Points>, Range<usize>)]) -> Option<Vec<usize>> {
    let runs: Vec<_> = runs.iter().filter(|(_, r)| !r.is_empty()).collect();
    let stacked = runs.iter().enumerate().all(|(i, (a, _))| {
        runs[i + 1..]
            .iter()
            .all(|(b, _)| a.bottom() <= b.top() || b.bottom() <= a.top())
    });
    let mut order: Vec<usize> = (0..runs.len()).collect();
    if stacked {
        order.sort_by(|&a, &b| {
            runs[a]
                .0
                .top()
                .partial_cmp(&runs[b].0.top())
                .unwrap_or(std::cmp::Ordering::Equal)
        });
    }
    if order.iter().enumerate().all(|(i, &o)| i == o) {
        return None;
    }
    Some(order.into_iter().flat_map(|i| runs[i].1.clone()).collect())
}

/// Puts `items[start..]` in `order` ([`reading_order`]'s indices).
pub fn reorder<T>(items: &mut Vec<T>, start: usize, order: &[usize]) {
    let mut taken: Vec<Option<T>> = items.drain(start..).map(Some).collect();
    items.extend(order.iter().filter_map(|&i| taken[i - start].take()));
}

/// The virtual list rows a selection keeps rendered: the nodes of the
/// texts at its ends, which the backend hands the engine
/// (`EngineControl::keep_rendered`) so that scrolling away does not
/// recycle them. Tracks what was last handed over.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct KeptRows(Vec<u64>);

impl KeptRows {
    /// The nodes to keep when they changed since the last call (none: the
    /// selection is gone), else `None`.
    pub fn changed(&mut self, model: &SelectionModel) -> Option<Vec<u64>> {
        let mut keys: Vec<u64> = if model.anchor.is_some() {
            model.keys.iter().flatten().copied().collect()
        } else {
            Vec::new()
        };
        keys.sort_unstable();
        keys.dedup();
        (keys != self.0).then(|| {
            self.0 = keys.clone();
            keys
        })
    }
    /// Lets go of every row (the selection's area is gone): an empty list
    /// when some were kept, else `None`.
    pub fn release(&mut self) -> Option<Vec<u64>> {
        (!self.0.is_empty()).then(|| {
            self.0.clear();
            Vec::new()
        })
    }
}

/// How far a selection drag scrolls a scroll view per 16 ms tick (points,
/// negative toward its start) with the pointer `at` along the view's axis
/// (its coordinates; `extent` long), 0 away from the edges. It starts
/// [`AUTOSCROLL_INSIDE`] inside an edge, as a maximized window leaves the
/// pointer little room past it, and speeds up linearly from
/// [`AUTOSCROLL_MIN`] to [`AUTOSCROLL_MAX`] over [`AUTOSCROLL_RAMP`] from
/// there outward.
pub fn autoscroll_step(at: Points, extent: Points) -> Points {
    let into = if at < AUTOSCROLL_INSIDE {
        at - AUTOSCROLL_INSIDE
    } else if at > extent - AUTOSCROLL_INSIDE {
        at - (extent - AUTOSCROLL_INSIDE)
    } else {
        return Points(0.0);
    };
    let t = (into.0.abs() / AUTOSCROLL_RAMP.0).min(1.0);
    Points(into.0.signum() * (AUTOSCROLL_MIN.0 + t * (AUTOSCROLL_MAX.0 - AUTOSCROLL_MIN.0)))
}

/// How far inside an edge a selection drag starts scrolling ([`autoscroll_step`]).
pub const AUTOSCROLL_INSIDE: Points = Points(16.0);
/// Its step per tick where it starts.
pub const AUTOSCROLL_MIN: Points = Points(12.0);
/// Its largest step per tick, [`AUTOSCROLL_RAMP`] from where it starts on.
pub const AUTOSCROLL_MAX: Points = Points(64.0);
/// How far from where it starts it reaches [`AUTOSCROLL_MAX`].
pub const AUTOSCROLL_RAMP: Points = Points(96.0);

/// The position under `point` ([module docs](self): the hit-testing rule),
/// `None` without texts.
fn hit(texts: &impl SelectionTexts, point: Point<Points>) -> Option<TextPosition> {
    let count = texts.len();
    if count == 0 {
        return None;
    }
    let at = |i: usize| {
        let frame = texts.frame(i);
        let clamped = Point::new(
            point.x.clamp(frame.left(), frame.right().max(frame.left())),
            point.y.clamp(frame.top(), frame.bottom().max(frame.top())),
        );
        clamp_position(texts, TextPosition::new(i, texts.offset_at(i, clamped)))
    };
    if let Some(i) = (0..count).find(|&i| texts.frame(i).contains(&point)) {
        return Some(at(i));
    }
    // The texts on the point's row: the horizontally nearest.
    let mut nearest: Option<(usize, Points)> = None;
    for i in 0..count {
        let frame = texts.frame(i);
        if point.y >= frame.top() && point.y < frame.bottom() {
            let distance = if point.x < frame.left() {
                frame.left() - point.x
            } else {
                (point.x - frame.right()).max(Points::ZERO)
            };
            if nearest.is_none_or(|(_, best)| distance < best) {
                nearest = Some((i, distance));
            }
        }
    }
    if let Some((i, _)) = nearest {
        return Some(at(i));
    }
    // Between rows: the end of the last text above or the start of the
    // first text below, whichever is nearer.
    let above = (0..count)
        .rev()
        .find(|&i| texts.frame(i).bottom() <= point.y);
    let below = (0..count).find(|&i| texts.frame(i).top() > point.y);
    let end_of = |i: usize| TextPosition::new(i, utf16_len(texts.content(i)));
    let start_of = |i: usize| TextPosition::new(i, 0);
    Some(match (above, below) {
        (Some(a), Some(b)) => {
            let to_above = point.y - texts.frame(a).bottom();
            let to_below = texts.frame(b).top() - point.y;
            if to_above <= to_below {
                end_of(a)
            } else {
                start_of(b)
            }
        }
        (Some(a), None) => end_of(a),
        (None, Some(b)) => start_of(b),
        // Only frames of no height, which no row contains.
        (None, None) => end_of(count - 1),
    })
}

/// The unit of `granularity` around `pos`: its word or its whole text.
fn unit_at(
    texts: &impl SelectionTexts,
    pos: TextPosition,
    granularity: Granularity,
) -> (TextPosition, TextPosition) {
    let content = texts.content(pos.text);
    match granularity {
        Granularity::Character => (pos, pos),
        Granularity::Word => {
            let range = word_range(content, pos.offset);
            let mut start = TextPosition::new(pos.text, range.start);
            let mut end = TextPosition::new(pos.text, range.end);
            // A word a wrap cut runs on into the parts around it: while the
            // word reaches its text's start and the text continues one
            // whose last character is of the same kind, it goes on there
            // (and the same forward).
            while start.offset == 0
                && continues(texts, start.text)
                && joins_word(texts, start.text - 1, start.text)
            {
                let before = texts.content(start.text - 1);
                let range = word_range(before, utf16_len(before));
                start = TextPosition::new(start.text - 1, range.start);
            }
            while end.offset == utf16_len(texts.content(end.text))
                && end.text + 1 < texts.len()
                && continues(texts, end.text + 1)
                && joins_word(texts, end.text, end.text + 1)
            {
                let after = texts.content(end.text + 1);
                let range = word_range(after, 0);
                end = TextPosition::new(end.text + 1, range.end);
            }
            (start, end)
        }
        // The whole line: the text and the texts it continues and that
        // continue it.
        Granularity::Paragraph => {
            let mut first = pos.text;
            while continues(texts, first) {
                first -= 1;
            }
            let mut last = pos.text;
            while last + 1 < texts.len() && continues(texts, last + 1) {
                last += 1;
            }
            (
                TextPosition::new(first, 0),
                TextPosition::new(last, utf16_len(texts.content(last))),
            )
        }
    }
}

/// Whether text `i` continues the text before it (never the first).
fn continues(texts: &impl SelectionTexts, i: usize) -> bool {
    i > 0 && i < texts.len() && texts.continues(i)
}

/// Whether the characters on both sides of the join of texts `a` and `b`
/// (`b` continuing `a`) are of one kind that makes words longer than a
/// character (letters and digits, or spaces): a word a wrap cut there is
/// one word.
fn joins_word(texts: &impl SelectionTexts, a: usize, b: usize) -> bool {
    let (Some(last), Some(first)) = (
        texts.content(a).chars().next_back(),
        texts.content(b).chars().next(),
    ) else {
        return false;
    };
    let kind = CharKind::of(last);
    kind != CharKind::Single && kind == CharKind::of(first)
}

/// What kind of character `c` is, for word boundaries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CharKind {
    /// Letters, digits, `_`, combining marks: runs of them are words.
    Word,
    /// Spaces and tabs: a run is one unit.
    Space,
    /// A line break, punctuation, an emoji, a CJK ideograph or kana: each
    /// is a unit of its own.
    Single,
}

impl CharKind {
    fn of(c: char) -> Self {
        if c == '\n' || c == '\r' || c == '\u{2028}' || c == '\u{2029}' {
            CharKind::Single
        } else if c.is_whitespace() {
            CharKind::Space
        } else if is_spaceless_script(c) {
            CharKind::Single
        } else if c.is_alphanumeric() || c == '_' || is_combining_mark(c) {
            CharKind::Word
        } else {
            CharKind::Single
        }
    }
}

/// Characters of scripts written without spaces between words (CJK
/// ideographs, kana): each one is a word.
fn is_spaceless_script(c: char) -> bool {
    matches!(c,
        '\u{3040}'..='\u{30FF}'     // Hiragana, Katakana
        | '\u{31F0}'..='\u{31FF}'   // Katakana phonetic extensions
        | '\u{3400}'..='\u{4DBF}'   // CJK extension A
        | '\u{4E00}'..='\u{9FFF}'   // CJK unified ideographs
        | '\u{F900}'..='\u{FAFF}'   // CJK compatibility ideographs
        | '\u{FF66}'..='\u{FF9F}'   // Half-width Katakana
        | '\u{20000}'..='\u{3FFFF}' // CJK extensions B and on
    )
}

/// Combining marks that belong to the word before them (accents written
/// apart, as Vietnamese is).
fn is_combining_mark(c: char) -> bool {
    matches!(c,
        '\u{0300}'..='\u{036F}'
        | '\u{1AB0}'..='\u{1AFF}'
        | '\u{1DC0}'..='\u{1DFF}'
        | '\u{20D0}'..='\u{20FF}'
        | '\u{FE20}'..='\u{FE2F}'
        | '\u{200D}' // zero-width joiner
        | '\u{FE0F}' // emoji presentation
    )
}

/// The UTF-16 range of the word at UTF-16 offset `offset` of `text`: the
/// word of the character after the offset, or of the one before at a line's
/// or the text's end. Empty on an empty line or text.
fn word_range(text: &str, offset: u32) -> Range<u32> {
    // UTF-16 starts of each character, with the characters.
    let chars: Vec<(u32, char)> = text
        .chars()
        .scan(0u32, |at, c| {
            let start = *at;
            *at += c.len_utf16() as u32;
            Some((start, c))
        })
        .collect();
    let len = utf16_len(text);
    let offset = snap(text, offset.min(len));
    let after = chars.partition_point(|&(start, _)| start < offset);
    let is_break = |i: usize| matches!(chars.get(i), Some((_, '\n' | '\r')) | None);
    let index = if is_break(after) {
        // At a line's or the text's end: the character before, unless the
        // line is empty.
        match after.checked_sub(1) {
            Some(before) if !is_break(before) => before,
            _ => return offset..offset,
        }
    } else {
        after
    };
    let kind = CharKind::of(chars[index].1);
    let (mut first, mut last) = (index, index);
    if kind != CharKind::Single {
        while first > 0 && CharKind::of(chars[first - 1].1) == kind {
            first -= 1;
        }
        while last + 1 < chars.len() && CharKind::of(chars[last + 1].1) == kind {
            last += 1;
        }
    }
    let end = chars[last].0 + chars[last].1.len_utf16() as u32;
    chars[first].0..end
}

/// `text`'s length in UTF-16 code units.
fn utf16_len(text: &str) -> u32 {
    text.chars().map(|c| c.len_utf16() as u32).sum()
}

/// The UTF-8 index of UTF-16 offset `offset` of `text` (rounded down to a
/// character, clamped to the end).
fn byte_offset(text: &str, offset: u32) -> usize {
    let mut at = 0u32;
    for (byte, c) in text.char_indices() {
        let next = at + c.len_utf16() as u32;
        if next > offset {
            return byte;
        }
        at = next;
    }
    text.len()
}

/// `offset` clamped to `text` and moved out of a surrogate pair (to the
/// pair's start).
fn snap(text: &str, offset: u32) -> u32 {
    let mut at = 0u32;
    for c in text.chars() {
        let next = at + c.len_utf16() as u32;
        if next > offset {
            return at;
        }
        at = next;
    }
    at
}

/// `pos` with its offset clamped into its text and out of a surrogate pair.
fn clamp_position(texts: &impl SelectionTexts, pos: TextPosition) -> TextPosition {
    TextPosition::new(pos.text, snap(texts.content(pos.text), pos.offset))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::{bounds, point, px, size};

    /// Texts set in a monospace font: each character is 8pt wide, lines
    /// break at '\n' and are 20pt high.
    struct Fake(Vec<(String, Bounds<Points>)>);

    /// A frame's x, y, width and height.
    type Frame = (f32, f32, f32, f32);

    impl Fake {
        fn new(texts: &[(&str, Frame)]) -> Self {
            Fake(
                texts
                    .iter()
                    .map(|&(text, (x, y, w, h))| {
                        (
                            text.to_string(),
                            bounds(point(px(x), px(y)), size(px(w), px(h))),
                        )
                    })
                    .collect(),
            )
        }
    }

    impl SelectionTexts for Fake {
        fn len(&self) -> usize {
            self.0.len()
        }

        fn content(&self, i: usize) -> &str {
            &self.0[i].0
        }

        fn frame(&self, i: usize) -> Bounds<Points> {
            self.0[i].1
        }

        fn offset_at(&self, i: usize, point: Point<Points>) -> u32 {
            let (text, frame) = &self.0[i];
            let lines: Vec<&str> = text.split('\n').collect();
            let line =
                (((point.y - frame.top()).0 / 20.0).floor().max(0.0) as usize).min(lines.len() - 1);
            let column = ((point.x - frame.left()).0 / 8.0).round().max(0.0) as usize;
            let before: u32 = lines[..line].iter().map(|l| utf16_len(l) + 1).sum();
            let within: u32 = lines[line]
                .chars()
                .take(column)
                .map(|c| c.len_utf16() as u32)
                .sum();
            before + within
        }

        // ASCII only: a character is a UTF-16 unit.
        fn range_bounds(&self, i: usize, range: Range<u32>) -> Option<Bounds<Points>> {
            let (text, frame) = &self.0[i];
            let place = |offset: u32| {
                let before = &text[..offset as usize];
                let line = before.matches('\n').count();
                let column = before.len() - before.rfind('\n').map_or(0, |n| n + 1);
                (line as f32, column as f32)
            };
            let ((l0, c0), (l1, c1)) = (place(range.start), place(range.end));
            let (left, width) = if l0 == l1 {
                (c0 * 8.0, (c1 - c0) * 8.0)
            } else {
                (0.0, frame.size.width.0)
            };
            Some(bounds(
                point(frame.left() + px(left), frame.top() + px(l0 * 20.0)),
                size(px(width), px((l1 - l0 + 1.0) * 20.0)),
            ))
        }
    }

    /// Three texts in a column: one line, two lines, one line, with gaps.
    fn column() -> Fake {
        Fake::new(&[
            ("Hello world", (0.0, 0.0, 200.0, 20.0)),
            ("Second line\nmore text", (0.0, 40.0, 200.0, 40.0)),
            ("Last", (0.0, 100.0, 200.0, 20.0)),
        ])
    }

    fn at(x: f32, y: f32) -> Point<Points> {
        point(px(x), px(y))
    }

    fn pos(text: usize, offset: u32) -> TextPosition {
        TextPosition::new(text, offset)
    }

    #[test]
    fn one_click_puts_the_anchor() {
        let texts = column();
        let mut model = SelectionModel::new();
        assert!(model.is_empty());
        assert!(model.press(&texts, at(17.0, 5.0), 1, false));
        assert!(model.is_empty());
        assert_eq!(model.bounds(), Some((pos(0, 2), pos(0, 2))));
        assert!(model.ranges(&texts).is_empty());
        assert_eq!(model.text(&texts), "");
    }

    #[test]
    fn drags_forward_and_backward_across_texts() {
        let texts = column();
        let mut model = SelectionModel::new();
        model.press(&texts, at(16.0, 5.0), 1, false);
        assert!(model.drag(&texts, at(24.0, 105.0)));
        assert_eq!(model.bounds(), Some((pos(0, 2), pos(2, 3))));
        assert_eq!(
            model.ranges(&texts),
            vec![(0, 2..11), (1, 0..21), (2, 0..3)]
        );
        assert_eq!(model.text(&texts), "llo world\nSecond line\nmore text\nLas");
        assert!(
            !model.drag(&texts, at(24.0, 105.0)),
            "the same point changes nothing"
        );

        let mut model = SelectionModel::new();
        model.press(&texts, at(24.0, 105.0), 1, false);
        model.drag(&texts, at(16.0, 5.0));
        assert_eq!(model.bounds(), Some((pos(0, 2), pos(2, 3))));
        assert_eq!(
            model.ranges(&texts),
            vec![(0, 2..11), (1, 0..21), (2, 0..3)]
        );
    }

    /// The selected part of each text, united: on one line, then across
    /// the texts of the column; nothing for nothing selected.
    #[test]
    fn the_selected_bounds_unite_each_texts_part() {
        let texts = column();
        let mut model = SelectionModel::new();
        assert_eq!(model.selected_bounds(&texts), None);
        model.press(&texts, at(16.0, 5.0), 1, false);
        assert_eq!(model.selected_bounds(&texts), None);
        model.drag(&texts, at(40.0, 5.0));
        assert_eq!(
            model.selected_bounds(&texts),
            Some(bounds(point(px(16.0), px(0.0)), size(px(24.0), px(20.0))))
        );
        model.drag(&texts, at(24.0, 105.0));
        assert_eq!(
            model.selected_bounds(&texts),
            Some(bounds(point(px(0.0), px(0.0)), size(px(200.0), px(120.0))))
        );
    }

    #[test]
    fn drag_without_a_press_does_nothing() {
        let texts = column();
        let mut model = SelectionModel::new();
        assert!(!model.drag(&texts, at(10.0, 10.0)));
        assert_eq!(model.bounds(), None);
    }

    #[test]
    fn between_rows_goes_to_the_nearer_edge() {
        let texts = column();
        let mut model = SelectionModel::new();
        model.press(&texts, at(0.0, 5.0), 1, false);
        model.drag(&texts, at(50.0, 25.0));
        assert_eq!(model.bounds(), Some((pos(0, 0), pos(0, 11))));
        model.drag(&texts, at(50.0, 35.0));
        assert_eq!(model.bounds(), Some((pos(0, 0), pos(1, 0))));
        // A tie goes to the text above.
        model.drag(&texts, at(50.0, 30.0));
        assert_eq!(model.bounds(), Some((pos(0, 0), pos(0, 11))));
    }

    #[test]
    fn above_and_below_all_texts() {
        let texts = column();
        let mut model = SelectionModel::new();
        model.press(&texts, at(40.0, 105.0), 1, false);
        model.drag(&texts, at(50.0, -10.0));
        assert_eq!(model.bounds(), Some((pos(0, 0), pos(2, 4))));

        model.press(&texts, at(0.0, 5.0), 1, false);
        model.drag(&texts, at(10.0, 500.0));
        assert_eq!(model.bounds(), Some((pos(0, 0), pos(2, 4))));
        assert_eq!(
            model.text(&texts),
            "Hello world\nSecond line\nmore text\nLast"
        );
    }

    #[test]
    fn beside_a_text_on_its_row() {
        let texts = Fake::new(&[
            ("left", (0.0, 0.0, 32.0, 20.0)),
            ("right", (100.0, 0.0, 40.0, 20.0)),
        ]);
        let mut model = SelectionModel::new();
        model.press(&texts, at(8.0, 5.0), 1, false);
        // Nearer the left text: its end.
        model.drag(&texts, at(50.0, 5.0));
        assert_eq!(model.bounds(), Some((pos(0, 1), pos(0, 4))));
        // Nearer the right text: its start.
        model.drag(&texts, at(90.0, 5.0));
        assert_eq!(model.bounds(), Some((pos(0, 1), pos(1, 0))));
        // Past the right text: its end.
        model.drag(&texts, at(300.0, 5.0));
        assert_eq!(model.bounds(), Some((pos(0, 1), pos(1, 5))));
        assert_eq!(model.text(&texts), "eft\tright");
    }

    #[test]
    fn double_click_selects_and_drags_by_words() {
        let texts = column();
        let mut model = SelectionModel::new();
        assert!(model.press(&texts, at(56.0, 5.0), 2, false));
        assert_eq!(model.bounds(), Some((pos(0, 6), pos(0, 11))));
        assert_eq!(model.text(&texts), "world");

        // Forward into the next text: to the end of the word there.
        model.drag(&texts, at(9.0, 45.0));
        assert_eq!(model.bounds(), Some((pos(0, 6), pos(1, 6))));
        // Back before the anchor's word: from the start of the word there to
        // the end of the anchor's.
        model.drag(&texts, at(8.0, 5.0));
        assert_eq!(model.bounds(), Some((pos(0, 0), pos(0, 11))));
        assert_eq!(model.text(&texts), "Hello world");
        // Back inside the anchor's word: just it.
        model.drag(&texts, at(64.0, 5.0));
        assert_eq!(model.bounds(), Some((pos(0, 6), pos(0, 11))));
    }

    #[test]
    fn double_click_at_a_line_end_selects_the_word_before() {
        let texts = column();
        let mut model = SelectionModel::new();
        model.press(&texts, at(150.0, 45.0), 2, false);
        assert_eq!(model.text(&texts), "line");
        model.press(&texts, at(150.0, 5.0), 2, false);
        assert_eq!(model.text(&texts), "world");
    }

    #[test]
    fn triple_click_selects_and_drags_by_paragraphs() {
        let texts = column();
        let mut model = SelectionModel::new();
        model.press(&texts, at(20.0, 65.0), 3, false);
        assert_eq!(model.bounds(), Some((pos(1, 0), pos(1, 21))));
        model.drag(&texts, at(8.0, 105.0));
        assert_eq!(model.bounds(), Some((pos(1, 0), pos(2, 4))));
        assert_eq!(model.text(&texts), "Second line\nmore text\nLast");
        model.drag(&texts, at(8.0, 5.0));
        assert_eq!(model.bounds(), Some((pos(0, 0), pos(1, 21))));
    }

    #[test]
    fn shift_click_extends_from_the_anchor() {
        let texts = column();
        let mut model = SelectionModel::new();
        model.press(&texts, at(16.0, 5.0), 1, false);
        assert!(model.press(&texts, at(24.0, 105.0), 1, true));
        assert_eq!(model.bounds(), Some((pos(0, 2), pos(2, 3))));
        // Again, before the anchor.
        model.press(&texts, at(8.0, 5.0), 1, true);
        assert_eq!(model.bounds(), Some((pos(0, 1), pos(0, 2))));

        // By words after a double click.
        model.press(&texts, at(56.0, 5.0), 2, false);
        model.press(&texts, at(8.0, 105.0), 1, true);
        assert_eq!(model.bounds(), Some((pos(0, 6), pos(2, 4))));

        // Without a selection, a Shift-click is a click.
        let mut model = SelectionModel::new();
        model.press(&texts, at(16.0, 5.0), 1, true);
        assert_eq!(model.bounds(), Some((pos(0, 2), pos(0, 2))));
    }

    #[test]
    fn long_press_selects_a_word() {
        let texts = column();
        let mut model = SelectionModel::new();
        assert!(model.select_word_at(&texts, at(10.0, 65.0)));
        assert_eq!(model.text(&texts), "more");
    }

    #[test]
    fn handles_move_their_end_and_swap_when_crossing() {
        let texts = column();
        let mut model = SelectionModel::new();
        assert!(!model.move_handle(&texts, Handle::End, at(0.0, 0.0)));
        assert!(model.select_all(&texts));
        assert_eq!(model.bounds(), Some((pos(0, 0), pos(2, 4))));
        assert!(model.move_handle(&texts, Handle::End, at(16.0, 5.0)));
        assert_eq!(model.bounds(), Some((pos(0, 0), pos(0, 2))));
        assert!(model.move_handle(&texts, Handle::Start, at(8.0, 45.0)));
        assert_eq!(model.bounds(), Some((pos(0, 2), pos(1, 1))));
        assert_eq!(model.text(&texts), "llo world\nS");
        // The start handle passed the end: it is the end now.
        assert!(model.move_handle(&texts, Handle::End, at(24.0, 5.0)));
        assert_eq!(model.bounds(), Some((pos(0, 2), pos(0, 3))));
    }

    #[test]
    fn select_all_and_clear() {
        let texts = column();
        let mut model = SelectionModel::new();
        assert!(model.select_all(&texts));
        assert!(!model.select_all(&texts));
        assert_eq!(
            model.ranges(&texts),
            vec![(0, 0..11), (1, 0..21), (2, 0..4)]
        );
        assert!(model.clear());
        assert!(!model.clear());
        assert_eq!(model.bounds(), None);

        let none = Fake(Vec::new());
        assert!(!model.select_all(&none));
        assert!(!model.press(&none, at(0.0, 0.0), 1, false));
    }

    #[test]
    fn copies_rows_with_tabs_and_leaves_attachments_out() {
        let texts = Fake::new(&[
            ("ab\u{FFFC}c", (0.0, 0.0, 80.0, 20.0)),
            ("de", (100.0, 5.0, 80.0, 20.0)),
            ("fg", (0.0, 40.0, 80.0, 20.0)),
            ("", (0.0, 60.0, 80.0, 20.0)),
            ("h", (0.0, 80.0, 80.0, 20.0)),
        ]);
        let mut model = SelectionModel::new();
        model.select_all(&texts);
        // The empty text is a blank line inside the selection: it keeps its
        // line in the copy, though it has nothing to highlight.
        assert_eq!(model.text(&texts), "abc\tde\nfg\n\nh");
        assert_eq!(model.ranges(&texts).len(), 4, "the empty text has no range");
    }

    #[test]
    fn never_splits_surrogate_pairs() {
        let texts = Fake::new(&[("a😀b c", (0.0, 0.0, 200.0, 20.0))]);
        let mut model = SelectionModel::new();
        model.press(&texts, at(9.0, 5.0), 2, false);
        assert_eq!(model.bounds(), Some((pos(0, 1), pos(0, 3))));
        assert_eq!(model.text(&texts), "😀");
        model.press(&texts, at(0.0, 5.0), 1, false);
        model.drag(&texts, at(16.0, 5.0));
        assert_eq!(model.text(&texts), "a😀");

        assert_eq!(snap("a😀b", 2), 1);
        assert_eq!(snap("a😀b", 3), 3);
        assert_eq!(snap("a😀b", 9), 4);
        assert_eq!(byte_offset("a😀b", 3), 5);
        assert_eq!(word_range("a😀b", 2), 1..3);
    }

    #[test]
    fn words_in_latin_and_cjk() {
        let text = "中文abc 测试, café_1  x\n\nend";
        let word = |offset| {
            let range = word_range(text, offset);
            let (from, to) = (byte_offset(text, range.start), byte_offset(text, range.end));
            text[from..to].to_string()
        };
        assert_eq!(word(0), "中");
        assert_eq!(word(1), "æ–‡");
        assert_eq!(word(2), "abc");
        assert_eq!(word(4), "abc");
        assert_eq!(word(5), " ");
        assert_eq!(word(6), "测");
        assert_eq!(word(8), ",");
        assert_eq!(word(10), "café_1");
        assert_eq!(word(16), "  ");
        // At the end of a line: the word before; on an empty line: nothing.
        assert_eq!(word(19), "x");
        assert_eq!(word(20), "");
        assert_eq!(word(24), "end");
        assert_eq!(word_range("", 0), 0..0);
    }

    #[test]
    fn texts_changed_clamps_and_clears() {
        let texts = column();
        let mut model = SelectionModel::new();
        model.press(&texts, at(16.0, 5.0), 1, false);
        model.drag(&texts, at(24.0, 105.0));

        let shorter = Fake::new(&[
            ("Hello world", (0.0, 0.0, 200.0, 20.0)),
            ("Second", (0.0, 40.0, 200.0, 20.0)),
            ("L", (0.0, 100.0, 200.0, 20.0)),
        ]);
        assert!(model.texts_changed(&shorter));
        assert_eq!(model.bounds(), Some((pos(0, 2), pos(2, 1))));
        assert!(!model.texts_changed(&shorter));

        let fewer = Fake::new(&[("Hello world", (0.0, 0.0, 200.0, 20.0))]);
        assert!(model.texts_changed(&fewer));
        assert_eq!(model.bounds(), None);
        assert!(!model.texts_changed(&fewer));
    }

    /// Texts with keys of their own, as backends give them (their nodes).
    struct Keyed(Fake, Vec<u64>);

    impl SelectionTexts for Keyed {
        fn len(&self) -> usize {
            self.0.len()
        }

        fn content(&self, i: usize) -> &str {
            self.0.content(i)
        }

        fn frame(&self, i: usize) -> Bounds<Points> {
            self.0.frame(i)
        }

        fn offset_at(&self, i: usize, point: Point<Points>) -> u32 {
            self.0.offset_at(i, point)
        }

        fn key(&self, i: usize) -> u64 {
            self.1[i]
        }
    }

    #[test]
    fn a_selection_follows_its_texts_by_key() {
        let texts = Keyed(column(), vec![10, 20, 30]);
        let mut model = SelectionModel::new();
        model.press(&texts, at(0.0, 45.0), 1, false);
        model.drag(&texts, at(16.0, 105.0));
        assert_eq!(model.bounds(), Some((pos(1, 0), pos(2, 2))));
        // A text comes before them: the selection moves with its texts.
        let more = Keyed(
            Fake::new(&[
                ("New", (0.0, 0.0, 200.0, 20.0)),
                ("Hello world", (0.0, 30.0, 200.0, 20.0)),
                ("Second line\nmore text", (0.0, 70.0, 200.0, 40.0)),
                ("Last", (0.0, 130.0, 200.0, 20.0)),
            ]),
            vec![5, 10, 20, 30],
        );
        assert!(model.texts_changed(&more));
        assert_eq!(model.bounds(), Some((pos(2, 0), pos(3, 2))));
        assert_eq!(model.text(&more), "Second line\nmore text\nLa");
        // The text of an end goes: the selection goes too.
        let gone = Keyed(
            Fake::new(&[
                ("New", (0.0, 0.0, 200.0, 20.0)),
                ("Second line\nmore text", (0.0, 70.0, 200.0, 40.0)),
            ]),
            vec![5, 20],
        );
        assert!(model.texts_changed(&gone));
        assert!(model.bounds().is_none());
    }

    #[test]
    fn stacked_children_go_by_their_tops_and_rows_stay_in_mount_order() {
        let frame = |x: f32, y: f32, h: f32| bounds(point(px(x), px(y)), size(px(100.0), px(h)));
        // Recycled cells: mounted showing rows 2, 0, 1 (two texts in the
        // first), and an empty spare cell overlapping them.
        let runs = [
            (frame(0.0, 200.0, 100.0), 0..2),
            (frame(0.0, 0.0, 300.0), 2..2),
            (frame(0.0, 0.0, 100.0), 2..3),
            (frame(0.0, 100.0, 100.0), 3..4),
        ];
        let order = reading_order(&runs).unwrap();
        assert_eq!(order, [2, 3, 0, 1]);
        let mut items = vec!["x", "c1", "c2", "a", "b"];
        let shifted: Vec<usize> = order.iter().map(|i| i + 1).collect();
        reorder(&mut items, 1, &shifted);
        assert_eq!(items, ["x", "a", "b", "c1", "c2"]);
        // Already in order, a row, an overlay: mount order.
        let in_order = [
            (frame(0.0, 0.0, 10.0), 0..1),
            (frame(0.0, 10.0, 10.0), 1..2),
        ];
        assert_eq!(reading_order(&in_order), None);
        let row = [
            (frame(200.0, 0.0, 20.0), 0..1),
            (frame(0.0, 0.0, 20.0), 1..2),
        ];
        assert_eq!(reading_order(&row), None);
        let overlay = [
            (frame(0.0, 50.0, 100.0), 0..1),
            (frame(0.0, 0.0, 100.0), 1..2),
        ];
        assert_eq!(reading_order(&overlay), None);
    }

    #[test]
    fn kept_rows_follow_the_ends_texts() {
        let texts = column();
        let mut model = SelectionModel::new();
        let mut kept = KeptRows::default();
        assert_eq!(kept.changed(&model), None);
        model.press(&texts, at(4.0, 4.0), 1, false);
        model.drag(&texts, at(4.0, 64.0));
        assert!(!kept.changed(&model).unwrap().is_empty());
        assert_eq!(kept.changed(&model), None);
        model.clear();
        assert_eq!(kept.changed(&model), Some(Vec::new()));
    }

    #[test]
    fn autoscroll_starts_inside_the_edge_and_speeds_up_outward() {
        let step = |at: f32| autoscroll_step(Points(at), Points(400.0));
        assert_eq!(step(200.0), Points(0.0));
        assert_eq!(step(17.0), Points(0.0));
        assert!(step(15.0) < Points(0.0));
        assert!(step(385.0) > Points(0.0));
        assert_eq!(step(400.0 - 16.0 + 96.0), AUTOSCROLL_MAX);
        assert_eq!(step(-500.0), Points(-AUTOSCROLL_MAX.0));
        assert!(step(420.0) > step(390.0));
    }

    /// Texts of which some continue the one before them (a long line's
    /// wrapped parts).
    struct Wrapped(Fake, Vec<bool>);

    impl SelectionTexts for Wrapped {
        fn len(&self) -> usize {
            self.0.len()
        }

        fn content(&self, i: usize) -> &str {
            self.0.content(i)
        }

        fn frame(&self, i: usize) -> Bounds<Points> {
            self.0.frame(i)
        }

        fn offset_at(&self, i: usize, point: Point<Points>) -> u32 {
            self.0.offset_at(i, point)
        }

        fn continues(&self, i: usize) -> bool {
            self.1[i]
        }
    }

    /// `first line` alone, then `a long li` + `ne wrapped` (one line in two
    /// parts, the second continuing the first), then `last`.
    #[test]
    fn a_copy_keeps_the_blank_lines_inside_the_selection() {
        let texts = Fake::new(&[
            ("}", (0.0, 0.0, 200.0, 20.0)),
            ("", (0.0, 20.0, 0.0, 20.0)),
            ("next", (0.0, 40.0, 200.0, 20.0)),
        ]);
        let mut model = SelectionModel::new();
        model.select_all(&texts);
        assert_eq!(model.text(&texts), "}\n\nnext");
    }

    fn wrapped() -> Wrapped {
        Wrapped(
            Fake::new(&[
                ("first line", (0.0, 0.0, 200.0, 20.0)),
                ("a long li", (0.0, 20.0, 200.0, 20.0)),
                ("ne wrapped", (0.0, 40.0, 200.0, 20.0)),
                ("last", (0.0, 60.0, 200.0, 20.0)),
            ]),
            vec![false, false, true, false],
        )
    }

    #[test]
    fn a_copy_joins_a_wrapped_lines_parts_with_nothing_between() {
        let texts = wrapped();
        let mut model = SelectionModel::new();
        model.select_all(&texts);
        assert_eq!(model.text(&texts), "first line\na long line wrapped\nlast");
        // From inside the first part into the second.
        model.press(&texts, at(16.0, 25.0), 1, false);
        model.drag(&texts, at(16.0, 45.0));
        assert_eq!(model.text(&texts), "long line");
    }

    #[test]
    fn a_continued_text_whose_part_before_is_not_selected_starts_the_copy() {
        let texts = wrapped();
        let mut model = SelectionModel::new();
        // From the second part to the last line: no break before the part,
        // one after it.
        model.press(&texts, at(0.0, 45.0), 1, false);
        model.drag(&texts, at(32.0, 65.0));
        assert_eq!(model.text(&texts), "ne wrapped\nlast");
    }

    #[test]
    fn a_triple_click_selects_a_wrapped_line_whole() {
        let texts = wrapped();
        let mut model = SelectionModel::new();
        model.press(&texts, at(16.0, 45.0), 3, false);
        assert_eq!(model.bounds(), Some((pos(1, 0), pos(2, 10))));
        assert_eq!(model.text(&texts), "a long line wrapped");
        // A text that continues none and that none continues: itself.
        model.press(&texts, at(8.0, 5.0), 3, false);
        assert_eq!(model.text(&texts), "first line");
    }

    #[test]
    fn a_double_click_selects_a_word_a_wrap_cut_across_its_parts() {
        let texts = wrapped();
        let mut model = SelectionModel::new();
        // On `li` at the first part's end, and on `ne` at the second's
        // start: the word `line` both times.
        model.press(&texts, at(60.0, 25.0), 2, false);
        assert_eq!(model.text(&texts), "line");
        model.press(&texts, at(8.0, 45.0), 2, false);
        assert_eq!(model.text(&texts), "line");
        // A word that ends where its text does, the next text not
        // continuing it, stays its own.
        model.press(&texts, at(60.0, 5.0), 2, false);
        assert_eq!(model.text(&texts), "line");
        assert_eq!(model.bounds(), Some((pos(0, 6), pos(0, 10))));
    }
}