rotulus-layout 0.1.0

The layout engine behind the Rotulus chat view: message model, wrapping, height index, scroll anchoring
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
//! The buffer: rows, marks, lazy layout, trim.
//!
//! Owns the message list, the [`HeightIndex`] that shadows it, and the
//! [`ScrollAnchor`]. This is the object the view drives.
//!
//! The API mirrors what `rotulus.h` exposes to C — append,
//! insert-before-a-mark, replace, remove-a-mark, clear, trim — so the
//! widget's FFI layer is a translation rather than a redesign. A mark is
//! a [`MessageId`], not a pointer into a linked list, so a stale one is
//! inert rather than dangling.

use crate::anchor::{AnchorResolver, Gravity, ScrollAnchor};
use crate::index::HeightIndex;
use crate::measure::TextMeasure;
use crate::message::{Block, Message, MessageFlags, MessageId};
use crate::select::{Caret, RowSelection, Selection};
use crate::span::Style;
use crate::wrap::LineSource;
use crate::wrap::{estimate_height, layout_message, LayoutCache, LayoutGeneration, LayoutParams};
use std::collections::HashMap;
use std::collections::VecDeque;

/// Floor for a hand-dragged gutter, so it can't be collapsed to
/// nothing and become impossible to grab again.
pub const MIN_INDENT: u32 = 16;

/// Default gap that breaks a run of messages from one speaker.
///
/// Five minutes. Short enough that "hai / hai / hai" collapses to one
/// block with one nick, long enough that returning to a room after a
/// break shows who is talking again rather than silently attaching your
/// message to something you said an hour ago.
pub const DEFAULT_GROUP_GAP_SECS: i64 = 300;

#[derive(Debug)]
struct Row {
    id: MessageId,
    msg: Message,
    /// Boxed, because only the rows that have been drawn have one: inline,
    /// every row in the scrollback would reserve room for a layout it will
    /// most likely never get.
    layout: Option<Box<LayoutCache>>,
}

/// A scrollable list of laid-out messages.
#[derive(Debug)]
pub struct ChatBuffer {
    rows: VecDeque<Row>,
    index: HeightIndex,
    next_id: u64,

    /// `MessageId` → row position.
    ///
    /// Rebuilt lazily: any structural change that shifts positions sets
    /// `pos_dirty`, and the next lookup pays one O(n) rebuild and then
    /// serves O(1) until the next change. A history batch is one
    /// rebuild for the batch rather than one per row, which is the case
    /// that actually matters. (xtext did a full linear scan *per*
    /// lookup — `gtk_xtext_find_media_entry_by_token`, xtext.c:6386 —
    /// so even the unamortised path is no worse.)
    ///
    /// Trimming is the exception. It only ever removes rows from the front,
    /// which shifts every surviving position down by the same amount, so
    /// instead of rebuilding it drops the trimmed ids and raises
    /// `pos_base`. A stored value is the row position plus `pos_base`. At
    /// the scrollback cap every append trims, and a rebuild there would
    /// make each new message cost O(scrollback).
    pos: HashMap<MessageId, usize>,
    pos_base: usize,
    pos_dirty: bool,
    /// The rows most recently looked up by id while `pos` was dirty, kept
    /// in step through inserts, removals and trims.
    ///
    /// A Load-older page inserts row after row above one anchor, and each
    /// insert dirties `pos`; finding the insert anchor, and then the
    /// reading position for the scrollbar, rebuilt the whole map for every
    /// row of the page, which made the page quadratic in the scrollback.
    /// Those are the only two rows asked for, so they are remembered. Each
    /// is checked against its row before use, so a change these don't
    /// follow just falls back to the rebuild.
    hints: [Option<(MessageId, usize)>; 2],

    params: LayoutParams,
    generation: LayoutGeneration,
    anchor: ScrollAnchor,

    /// Scrollback cap on live rows. 0 disables trimming. History rows
    /// (see [`MessageKind::is_history`]) don't count against it.
    max_rows: usize,
    /// How many rows are history, so the live count is `rows.len()` minus
    /// this without a scan.
    history_rows: usize,
    /// Widest gutter any row has asked for, so columns align.
    indent_width: u32,
    /// How long a gap breaks a run of messages from one speaker, in
    /// seconds. 0 disables grouping entirely.
    group_gap_secs: i64,

    /// Set once the user drags the separator, which freezes the gutter.
    ///
    /// xtext left auto-growth on after a drag, so a long nick could
    /// silently undo a narrowing the user had just made by hand (and a
    /// widening only stuck because it happened to exceed
    /// `max_auto_indent`, which switched the auto path off as a side
    /// effect). An explicit pin is the behaviour that was being
    /// approximated.
    indent_pinned: bool,
}

impl ChatBuffer {
    pub fn new(params: LayoutParams) -> ChatBuffer {
        let generation = LayoutGeneration {
            width: params.width,
            font: 0,
            theme: 0,
            zoom_permille: 1000,
        };
        ChatBuffer {
            rows: VecDeque::new(),
            index: HeightIndex::new(),
            next_id: 1,
            pos: HashMap::new(),
            pos_base: 0,
            pos_dirty: false,
            hints: [None; 2],
            params,
            generation,
            anchor: ScrollAnchor::bottom(),
            max_rows: 0,
            history_rows: 0,
            group_gap_secs: DEFAULT_GROUP_GAP_SECS,
            indent_width: 0,
            indent_pinned: false,
        }
    }

    pub fn len(&self) -> usize {
        self.rows.len()
    }

    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    pub fn anchor(&self) -> ScrollAnchor {
        self.anchor
    }

    pub fn set_anchor(&mut self, a: ScrollAnchor) {
        self.anchor = a;
    }

    pub fn params(&self) -> &LayoutParams {
        &self.params
    }

    pub fn generation(&self) -> LayoutGeneration {
        self.generation
    }

    /// The scrollback cap on live rows; 0 is no limit.
    pub fn max_rows(&self) -> usize {
        self.max_rows
    }

    /// Scrollback cap on live rows. Matches `rotulus_view_set_max_lines`.
    pub fn set_max_rows(&mut self, n: usize, measure: &dyn TextMeasure) {
        self.max_rows = n;
        self.trim(measure);
    }

    pub fn message(&self, id: MessageId) -> Option<&Message> {
        self.row_of(id)
            .and_then(|r| self.rows.get(r))
            .map(|r| &r.msg)
    }

    pub fn message_at(&self, row: usize) -> Option<&Message> {
        self.rows.get(row).map(|r| &r.msg)
    }

    pub fn id_at(&self, row: usize) -> Option<MessageId> {
        self.rows.get(row).map(|r| r.id)
    }

    /// Row position of `id`, or `None` if it has been trimmed/cleared.
    pub fn row_of(&self, id: MessageId) -> Option<usize> {
        if self.pos_dirty {
            // Cold path: the caller holds `&self`, so rebuild by scan
            // rather than mutating. Callers that do this in a loop
            // should take `&mut self` and call `reindex` first.
            return self.rows.iter().position(|r| r.id == id);
        }
        self.pos.get(&id).map(|p| p - self.pos_base)
    }

    /// The layout params as the estimator should see them, with the
    /// settled gutter width filled in. `ensure_layout` builds the same
    /// thing; sharing it keeps an estimate and its eventual real layout
    /// measuring the same shape.
    fn layout_params(&self) -> LayoutParams {
        let mut p = self.params;
        p.indent_width = self.indent_width;
        p
    }

    /// Rebuild the id → position map if stale.
    pub fn reindex(&mut self) {
        if !self.pos_dirty {
            return;
        }
        self.pos.clear();
        self.pos_base = 0;
        for (i, r) in self.rows.iter().enumerate() {
            self.pos.insert(r.id, i);
        }
        self.pos_dirty = false;
    }

    // ---- mutation --------------------------------------------------

    /// Append a message; returns its mark.
    pub fn append(&mut self, mut msg: Message, measure: &dyn TextMeasure) -> MessageId {
        msg.compact();
        let id = self.alloc_id();
        if self.groups_with_previous(&msg, self.rows.len()) {
            msg.flags = msg.flags.union(MessageFlags::GROUPED);
        }
        let h = estimate_height(&msg, &self.layout_params(), measure);
        if msg.kind.is_history() {
            self.history_rows += 1;
        }
        self.rows.push_back(Row {
            id,
            msg,
            layout: None,
        });
        self.index.push_back(h, false);
        if !self.pos_dirty {
            self.pos.insert(id, self.pos_base + self.rows.len() - 1);
        }
        self.trim(measure);
        id
    }

    /// Insert immediately before `anchor`, or at the front if `anchor`
    /// is `None` or stale. Returns the new mark.
    ///
    /// This is the chat-history Load-Older path. Nothing here needs to
    /// compensate the scroll position: the anchor names a row, that row
    /// did not move, so the viewport does not move. xtext had to bump
    /// `pagetop_line` / `pagetop_subline` / `last_pixel_pos` /
    /// `old_value` by the inserted row's subline count to approximate
    /// the same effect (xtext.c:5720).
    pub fn insert_before(
        &mut self,
        anchor: Option<MessageId>,
        mut msg: Message,
        measure: &dyn TextMeasure,
    ) -> MessageId {
        msg.compact();
        let at = match anchor {
            Some(a) => self.locate(a).unwrap_or(0),
            None => 0,
        };
        let id = self.alloc_id();
        let h = estimate_height(&msg, &self.layout_params(), measure);
        if msg.kind.is_history() {
            self.history_rows += 1;
        }
        self.rows.insert(
            at,
            Row {
                id,
                msg,
                layout: None,
            },
        );
        self.index.insert(at, h, false);
        self.pos_dirty = true;
        self.shift_hints(at, 1);
        // An insert splits whatever run spanned this point: the new row
        // may continue the one above, and the row below may no longer
        // continue what is now two rows up. Nothing further down moves
        // relative to its predecessor.
        self.regroup_rows(at..at + 2, measure);
        id
    }

    /// Remove the row `id` names. `false` if the mark was already stale,
    /// which is not an error — it is how a caller learns the row was
    /// trimmed.
    pub fn remove(&mut self, id: MessageId, measure: &dyn TextMeasure) -> bool {
        let Some(row) = self.locate(id) else {
            return false;
        };
        self.remove_row(row, measure);
        true
    }

    /// Remove the row at `row`, which the caller has already found.
    fn remove_row(&mut self, row: usize, measure: &dyn TextMeasure) {
        let id = self.rows[row].id;
        if self.rows[row].msg.kind.is_history() {
            self.history_rows -= 1;
        }
        self.rows.remove(row);
        self.index.remove(row);
        self.pos_dirty = true;
        self.forget_hint(row);
        self.shift_hints(row + 1, -1);
        // The row that moved up has a new predecessor. Removing a run's
        // head would otherwise leave the next row suppressing a nick that
        // nothing above it shows.
        self.regroup_rows(row..row + 1, measure);
        if self.anchor.message == Some(id) {
            // Re-anchor to the row that took its place, so removing the
            // "Load older" sentinel from under the viewport doesn't
            // snap the view to the bottom.
            self.anchor.message = self.rows.get(row).map(|r| r.id);
            if self.anchor.message.is_none() {
                self.anchor = ScrollAnchor::bottom();
            }
        }
    }

    /// Replace a message in place, e.g. to attach a decoded image size.
    pub fn replace(&mut self, id: MessageId, mut msg: Message, measure: &dyn TextMeasure) -> bool {
        msg.compact();
        self.reindex();
        let Some(row) = self.row_of(id) else {
            return false;
        };
        let h = estimate_height(&msg, &self.layout_params(), measure);
        let was = self.rows[row].msg.kind.is_history();
        let now = msg.kind.is_history();
        self.rows[row].msg = msg;
        self.rows[row].layout = None;
        match (was, now) {
            (false, true) => self.history_rows += 1,
            (true, false) => self.history_rows -= 1,
            _ => {}
        }
        self.index.set_height(row, h, false);
        if was && !now {
            self.trim(measure);
        }
        true
    }

    /// Attach a decoded size to an image block, growing the row.
    ///
    /// The single operation the old design was worst at: xtext had to
    /// recompute the entry's subline list, diff the count, and patch the
    /// buffer's `num_lines` plus the scroll anchors. Here it is a height
    /// change, and the anchor absorbs it.
    /// Attach (or with `None`, clear) the decoded size of an image
    /// block.
    ///
    /// `None` is the decode-failed path: the row must shrink back to its
    /// placeholder height, or the alt text ends up floating inside a
    /// tall empty box the size of an image that never arrived.
    pub fn set_image_size(
        &mut self,
        id: MessageId,
        token: u32,
        size: Option<crate::message::ImageSize>,
        measure: &dyn TextMeasure,
    ) -> bool {
        self.reindex();
        let Some(row) = self.row_of(id) else {
            return false;
        };
        let mut hit = false;
        for b in &mut self.rows[row].msg.blocks {
            if let Block::Image {
                token: t, size: s, ..
            } = b
            {
                if *t == token {
                    *s = size;
                    hit = true;
                }
            }
        }
        if !hit {
            return false;
        }
        self.rows[row].layout = None;
        let params = self.layout_params();
        let h = estimate_height(&self.rows[row].msg, &params, measure);
        self.index.set_height(row, h, false);
        true
    }

    /// Find the row carrying an image block with `token`.
    pub fn find_image(&self, token: u32) -> Option<MessageId> {
        self.rows
            .iter()
            .find(|r| {
                r.msg
                    .blocks
                    .iter()
                    .any(|b| matches!(b, Block::Image { token: t, .. } if *t == token))
            })
            .map(|r| r.id)
    }

    pub fn clear(&mut self) {
        self.rows.clear();
        self.index = HeightIndex::new();
        self.pos.clear();
        self.pos_base = 0;
        self.pos_dirty = false;
        self.hints = [None; 2];
        self.history_rows = 0;
        self.anchor = ScrollAnchor::bottom();
        self.reset_indent();
    }

    /// Bring the live rows back under the cap by dropping the oldest of
    /// them.
    ///
    /// History rows don't count and are never dropped here: the replay on
    /// join, a reconnect's catch-up and "Load older" pages. A page the user
    /// asked for, inserted above a full scrollback, used to be trimmed
    /// away, whole, by the next live message. History is bounded instead by
    /// the server and the replay preference, and cleared on reconnect.
    fn trim(&mut self, measure: &dyn TextMeasure) {
        let live = self.rows.len() - self.history_rows;
        if self.max_rows == 0 || live <= self.max_rows {
            return;
        }
        let mut excess = live - self.max_rows;

        // Live rows at the very front go the cheap way.
        let front = self
            .rows
            .iter()
            .take(excess)
            .take_while(|r| !r.msg.kind.is_history())
            .count();
        if front > 0 {
            for _ in 0..front {
                if let Some(row) = self.rows.pop_front() {
                    // A dirty map is rebuilt from `rows` on the next
                    // lookup, so it has nothing to keep in step.
                    if !self.pos_dirty {
                        self.pos.remove(&row.id);
                    }
                }
            }
            self.index.drain_front(front);
            if !self.pos_dirty {
                self.pos_base += front;
            }
            for r in 0..front {
                self.forget_hint(r);
            }
            self.shift_hints(front, -(front as isize));
            // The trimmed rows may have included a run's head. Whatever
            // is at the front now cannot be a continuation of anything;
            // every other row keeps the predecessor it had.
            self.regroup_rows(0..1, measure);
            excess -= front;
        }

        // The rest are below a history block at the top: the oldest live
        // rows after it.
        while excess > 0 {
            let Some(row) = self.rows.iter().position(|r| !r.msg.kind.is_history()) else {
                break;
            };
            // By position: the row is in hand, and looking it up by id
            // would rebuild the whole map for every message at the cap.
            self.remove_row(row, measure);
            excess -= 1;
        }
    }

    /// Grouping controls. 0 disables it; rows already in the buffer are
    /// re-evaluated, since the flag describes neighbours rather than the
    /// message itself.
    pub fn set_group_gap_secs(&mut self, secs: i64, measure: &dyn TextMeasure) {
        if secs == self.group_gap_secs {
            return;
        }
        self.group_gap_secs = secs.max(0);
        self.regroup_rows(0..self.rows.len(), measure);
    }

    pub fn group_gap_secs(&self) -> i64 {
        self.group_gap_secs
    }

    /// Would `msg` continue the run ending at `before` (an index into
    /// `rows`, so `rows.len()` means "appending at the end")?
    fn groups_with_previous(&self, msg: &Message, before: usize) -> bool {
        if self.group_gap_secs == 0 || before == 0 {
            return false;
        }
        let Some(prev) = self.rows.get(before - 1) else {
            return false;
        };
        // Direction breaks a run before identity does.
        //
        // In a private-message window both halves of a conversation with
        // yourself have you as the sender, so identity cannot separate
        // them and grouping collapses "you said / they said / you said"
        // into one block — losing the alternation, which is the content.
        // Direction can separate them: it is a property of which path
        // produced the row, not of who is named on it.
        if prev.msg.flags.contains(MessageFlags::OUTGOING)
            != msg.flags.contains(MessageFlags::OUTGOING)
        {
            return false;
        }
        let (Some(a), Some(b)) = (prev.msg.group_key(), msg.group_key()) else {
            return false;
        };
        if a != b {
            return false;
        }
        // Timestamps are seconds; a message that predates the one above
        // it (history interleaving, clock skew) is not a continuation.
        let dt = msg.timestamp - prev.msg.timestamp;
        (0..=self.group_gap_secs).contains(&dt)
    }

    /// Recompute the GROUPED flag for `rows` (clamped to the buffer).
    ///
    /// Needed because the flag is a property of a message's *neighbours*.
    /// Trimming can delete a run's head, leaving rows that suppress their
    /// nick with nothing above them to have shown it — a speaker's
    /// messages appearing anonymously. Inserting can split a run the same
    /// way.
    ///
    /// The flag depends only on the row directly above
    /// (`groups_with_previous`), so a change touches at most the rows whose
    /// predecessor changed. Callers pass exactly those; walking to the end
    /// made every trim and every history insert cost O(scrollback).
    fn regroup_rows(&mut self, rows: std::ops::Range<usize>, measure: &dyn TextMeasure) {
        for i in rows.start..rows.end.min(self.rows.len()) {
            let want = {
                let msg = &self.rows[i].msg;
                self.groups_with_previous(msg, i)
            };
            let had = self.rows[i].msg.flags.contains(MessageFlags::GROUPED);
            if want == had {
                continue;
            }
            let f = &mut self.rows[i].msg.flags;
            *f = if want {
                f.union(MessageFlags::GROUPED)
            } else {
                MessageFlags(f.0 & !MessageFlags::GROUPED.0)
            };
            // The gutter appears or disappears, so the row's height and
            // layout are both stale.
            //
            // Re-*estimate* rather than keeping the old height as the new
            // estimate. Ungrouping adds a gutter line, so the stale value
            // is too small; carrying it forward under-reports
            // total_height and leaves the scrollbar's upper bound short
            // until enough rows happen to be laid out for real. That is
            // the kind of bug that looks like "scrolling stops early
            // sometimes" and is miserable to trace back here.
            self.rows[i].layout = None;
            let params = self.layout_params();
            let h = estimate_height(&self.rows[i].msg, &params, measure);
            self.index.set_height(i, h, false);
        }
    }

    fn alloc_id(&mut self) -> MessageId {
        let id = MessageId(self.next_id);
        self.next_id += 1;
        id
    }

    // ---- geometry ---------------------------------------------------

    /// Change the content width. Invalidates layout without recomputing
    /// it — the whole point of the lazy cache.
    pub fn set_width(&mut self, width: u32) {
        if width == self.params.width {
            return;
        }
        self.params.width = width;
        self.generation.width = width;
        self.index.invalidate_all_measurements();
    }

    pub fn set_font_generation(&mut self, font: u32) {
        if font == self.generation.font {
            return;
        }
        self.generation.font = font;
        self.index.invalidate_all_measurements();
    }

    /// Zoom, in per-mille (1000 = 100%).
    pub fn set_zoom_permille(&mut self, zoom: u32) {
        if zoom == self.generation.zoom_permille {
            return;
        }
        self.generation.zoom_permille = zoom;
        self.index.invalidate_all_measurements();
    }

    pub fn set_word_wrap(&mut self, on: bool) {
        if on == self.params.word_wrap {
            return;
        }
        self.params.word_wrap = on;
        self.invalidate_layout();
    }

    /// Edge length of the avatar slot in the gutter; 0 turns avatars
    /// off. Invalidates every layout, since it changes the gutter width
    /// and the height of every group head.
    pub fn set_avatar_size(&mut self, px: u32) {
        if px == self.params.avatar_size {
            return;
        }
        self.params.avatar_size = px;
        // The gutter has to be re-reconciled: the avatar contributes to
        // its width, so turning avatars off should let it shrink back
        // rather than stay padded out for icons that are gone.
        self.reset_indent();
        self.invalidate_layout();
    }

    /// Two-column mode.
    pub fn set_indent(&mut self, on: bool) {
        if on == self.params.indent {
            return;
        }
        self.params.indent = on;
        self.reset_indent();
        self.invalidate_layout();
    }

    /// Width to reserve for the timestamp column; 0 turns it off.
    pub fn set_stamp_width(&mut self, px: u32) {
        if px == self.params.stamp_width {
            return;
        }
        self.params.stamp_width = px;
        // The gutter has to be re-reconciled from scratch: it may need to
        // grow for a wider stamp, and when the stamp goes away it should
        // shrink back rather than stay padded out.
        self.reset_indent();
        self.invalidate_layout();
    }

    pub fn stamp_width(&self) -> u32 {
        self.params.stamp_width
    }

    /// Cap on the gutter width.
    pub fn set_max_indent(&mut self, px: u32) {
        if px == self.params.max_indent {
            return;
        }
        self.params.max_indent = px;
        self.indent_width = self.indent_width.min(px);
        self.invalidate_layout();
    }

    /// Drop every cached layout, keeping heights as estimates.
    ///
    /// The generation key can't express "the params changed" — it tracks
    /// width, font, theme and zoom, and a geometry knob like indent mode
    /// is none of those. Rather than widen the key for two setters that
    /// fire once at construction, clear the caches directly. Heights
    /// survive as estimates, so this is still O(1) work now and
    /// O(visible) on the next draw.
    fn invalidate_layout(&mut self) {
        for r in &mut self.rows {
            r.layout = None;
        }
        self.index.invalidate_all_measurements();
    }

    /// Ensure row `row` has a current layout, computing it if not.
    /// Returns its height.
    pub fn ensure_layout(&mut self, row: usize, measure: &dyn TextMeasure) -> u32 {
        let gen = self.generation;
        let mut params = self.params;
        params.indent_width = self.indent_width;

        let Some(r) = self.rows.get(row) else {
            return 0;
        };
        if let Some(l) = &r.layout {
            if l.generation == gen {
                return l.height;
            }
        }
        let layout = layout_message(&self.rows[row].msg, &params, gen, measure);

        // A wider nick than any seen so far widens the shared gutter, so
        // every *other* row's layout is stale. Rare — it settles within
        // the first few messages — and lazily repaired.
        //
        // The row we just laid out has to be redone rather than merely
        // invalidated: it was measured against the old, narrower gutter,
        // and dropping it would leave `layout_at(row)` returning None
        // immediately after an `ensure_layout(row)` call, which is a
        // contract violation the caller has no way to recover from.
        if layout.natural_indent > self.indent_width && !self.indent_pinned {
            self.indent_width = layout.natural_indent;
            for r in &mut self.rows {
                r.layout = None;
            }
            self.index.invalidate_all_measurements();
            params.indent_width = self.indent_width;
            let layout = layout_message(&self.rows[row].msg, &params, gen, measure);
            let height = layout.height;
            self.rows[row].layout = Some(Box::new(layout));
            self.index.set_height(row, height, true);
            return height;
        }

        let height = layout.height;
        // Reuse the allocation when the row is being relaid out.
        match &mut self.rows[row].layout {
            Some(b) => **b = layout,
            slot => *slot = Some(Box::new(layout)),
        }
        self.index.set_height(row, height, true);
        height
    }

    /// Lay out every row intersecting `[y, y + height)` and return their
    /// positions.
    ///
    /// **Every returned row is guaranteed to have a current layout.**
    /// That guarantee needs defending, because laying a row out can
    /// invalidate the rows already done: meeting a wider nick widens the
    /// shared gutter, which makes every other row's cached layout stale.
    /// Without the retry below, the rows laid out earlier in the pass
    /// come back with `layout_at(row) == None`, the view skips them, and
    /// the first paint of a fresh buffer is visibly shredded — while the
    /// next message, by which time the gutter has settled, looks fine.
    ///
    /// The gutter only ever grows and is capped by `max_indent`, so this
    /// converges fast; the bound is belt-and-braces.
    pub fn ensure_visible(
        &mut self,
        y: u64,
        viewport_height: u32,
        measure: &dyn TextMeasure,
    ) -> Vec<usize> {
        const MAX_SETTLE_PASSES: usize = 4;
        for _ in 0..MAX_SETTLE_PASSES {
            let indent_before = self.indent_width;
            let rows = self.layout_visible_once(y, viewport_height, measure);
            if self.indent_width == indent_before {
                return rows;
            }
        }
        // Didn't settle (shouldn't happen: the gutter is monotonic and
        // capped). Do one final pass so the caller still gets laid-out
        // rows rather than holes.
        self.layout_visible_once(y, viewport_height, measure)
    }

    fn layout_visible_once(
        &mut self,
        y: u64,
        viewport_height: u32,
        measure: &dyn TextMeasure,
    ) -> Vec<usize> {
        let mut out = Vec::new();
        let Some(first) = self.index.locate(y) else {
            return out;
        };
        let mut row = first.row;
        let mut consumed = u64::from(self.index.height_at(row)) - u64::from(first.offset);
        self.ensure_layout(row, measure);
        out.push(row);
        while consumed < u64::from(viewport_height) && row + 1 < self.rows.len() {
            row += 1;
            self.ensure_layout(row, measure);
            out.push(row);
            consumed += u64::from(self.index.height_at(row));
        }
        out
    }

    /// Text of one of a message's sources, for hit-testing and copying.
    pub fn source_text(&self, row: usize, source: LineSource) -> Option<&str> {
        self.source_text_for(&self.rows.get(row)?.msg, source)
    }

    fn source_text_for<'a>(&self, msg: &'a Message, source: LineSource) -> Option<&'a str> {
        match source {
            LineSource::Gutter => msg.gutter.as_ref().map(|g| g.text.as_str()),
            LineSource::Block(bi) => match msg.blocks.get(bi)? {
                Block::Text(p) => Some(p.text.as_str()),
                Block::Quote { content, .. } => Some(content.text.as_str()),
                Block::Code { text, .. } => Some(text.as_str()),
                // An image contributes its alt text, so a selection
                // dragged across a picture copies something meaningful
                // instead of nothing.
                Block::Image { alt, .. } => Some(alt.as_str()),
            },
        }
    }

    /// The link under a caret, as (href, visible text).
    ///
    /// Returned by value rather than by reference because the caller is
    /// the widget, which needs to hold it across a popup.
    /// The byte range of the link under `caret`, in its source's text.
    ///
    /// Split from `link_at` because the hover underline needs the extent
    /// and not the target — and deriving the extent a second way is how
    /// the underline and the click end up disagreeing about where a link
    /// stops.
    pub fn link_range_at(&self, caret: &Caret) -> Option<std::ops::Range<usize>> {
        let row = self.row_of(caret.message)?;
        let msg = &self.rows.get(row)?.msg;
        let parsed = match caret.source {
            LineSource::Gutter => msg.gutter.as_ref()?,
            LineSource::Block(bi) => match msg.blocks.get(bi)? {
                Block::Text(p) => p,
                Block::Quote { content, .. } => content,
                _ => return None,
            },
        };
        parsed.link_at(caret.offset).map(|l| l.range.clone())
    }

    /// Byte extent of a row's gutter text, for the nick hover underline.
    pub fn gutter_range(&self, id: MessageId) -> Option<std::ops::Range<usize>> {
        let row = self.row_of(id)?;
        let g = self.rows.get(row)?.msg.gutter.as_ref()?;
        (!g.text.is_empty()).then_some(0..g.text.len())
    }

    /// The speaker of a row, if it has one.
    pub fn speaker_of(&self, id: MessageId) -> Option<&crate::message::Speaker> {
        let row = self.row_of(id)?;
        self.rows.get(row)?.msg.speaker.as_ref()
    }

    pub fn link_at(&self, caret: &Caret) -> Option<(String, String)> {
        let row = self.row_of(caret.message)?;
        let msg = &self.rows.get(row)?.msg;
        let parsed = match caret.source {
            LineSource::Gutter => msg.gutter.as_ref()?,
            LineSource::Block(bi) => match msg.blocks.get(bi)? {
                Block::Text(p) => p,
                Block::Quote { content, .. } => content,
                _ => return None,
            },
        };
        let link = parsed.link_at(caret.offset)?;
        let label = parsed
            .text
            .get(link.range.clone())
            .unwrap_or_default()
            .to_string();
        Some((link.href.clone(), label))
    }

    /// The whitespace-delimited word around a caret.
    ///
    /// Tokenised like xtext's `is_del` macro: space, newline, `<`, `>`
    /// and NUL. The angle brackets are what let `<nick>` split into a
    /// bare nick when it is double-clicked.
    pub fn word_at(&self, caret: &Caret) -> Option<String> {
        let (start, end) = self.word_bounds(caret)?;
        let row = self.row_of(caret.message)?;
        let text = self.source_text(row, caret.source)?;
        Some(text[start..end].to_string())
    }

    /// Byte bounds of the word around a caret, in its own source.
    ///
    /// Shared by `word_at` (which the `word-click` emission needs as a
    /// string) and double-click word-select, so the two can never
    /// disagree about where a word begins.
    pub fn word_bounds(&self, caret: &Caret) -> Option<(usize, usize)> {
        let row = self.row_of(caret.message)?;
        let text = self.source_text(row, caret.source)?;
        if text.is_empty() {
            return None;
        }
        let is_del = |c: char| c == ' ' || c == '\n' || c == '<' || c == '>' || c == '\0';
        // Clamp to a char boundary before slicing. Carets from
        // `hit_test` are already aligned, but this is reachable from the
        // FFI with an arbitrary offset, and `&text[at..]` off a boundary
        // panics — which unwinds into GTK and aborts.
        let mut at = caret.offset.min(text.len());
        while at > 0 && !text.is_char_boundary(at) {
            at -= 1;
        }

        // A click *on* a delimiter yields no word, which is what xtext
        // does: both its scan loops (xtext.c:2095, 2114) test `is_del`
        // before stepping, so they collapse to an empty span. Returning
        // the preceding word instead would make clicking the gap after a
        // link activate it.
        match text[at..].chars().next() {
            Some(c) if !is_del(c) => {}
            _ => return None,
        }

        let start = text[..at]
            .rfind(is_del)
            .map(|i| i + text[i..].chars().next().map_or(1, |c| c.len_utf8()))
            .unwrap_or(0);
        let end = text[at..]
            .find(is_del)
            .map(|i| at + i)
            .unwrap_or(text.len());
        if start >= end {
            return None;
        }
        Some((start, end))
    }

    /// Double-click: select the word under the caret.
    pub fn select_word(&self, caret: &Caret) -> Option<Selection> {
        let (start, end) = self.word_bounds(caret)?;
        Some(Selection::new(
            Caret {
                message: caret.message,
                source: caret.source,
                offset: start,
            },
            Caret {
                message: caret.message,
                source: caret.source,
                offset: end,
            },
        ))
    }

    /// Triple-click: select the whole row, gutter included.
    ///
    /// The gutter is part of what the user sees on that line, so it is
    /// part of what a "select this line" gesture should give them —
    /// consistent with a whole-row selection dragged from above.
    pub fn select_row(&self, row: usize) -> Option<Selection> {
        let id = self.id_at(row)?;
        let first = self.sources_of(row).first().copied()?;
        let last = self.sources_of(row).last().copied()?;
        let end_len = self.source_text(row, last).map_or(0, |t| t.len());
        Some(Selection::new(
            Caret {
                message: id,
                source: first,
                offset: 0,
            },
            Caret {
                message: id,
                source: last,
                offset: end_len,
            },
        ))
    }

    /// Every occurrence of `needle`, in reading order.
    ///
    /// Reading order means row by row, and within a row by
    /// [`source_rank`](crate::select::source_rank) — the same order
    /// `selected_rows` walks and the same order the eye does, so
    /// stepping through matches never jumps backwards on screen.
    ///
    /// Searches the *model*, not the layout, so matches in rows that
    /// have never been laid out are found too. That matters: the whole
    /// point of search is to reach the part of the scrollback you
    /// haven't scrolled to.
    pub fn search(&self, needle: &str, case_sensitive: bool) -> Vec<crate::search::Match> {
        let mut out = Vec::new();
        if needle.is_empty() {
            return out;
        }
        for row in 0..self.rows.len() {
            let Some(id) = self.id_at(row) else { continue };
            for source in self.sources_of(row) {
                let Some(text) = self.source_text(row, source) else {
                    continue;
                };
                for (start, end) in crate::search::find_all(text, needle, case_sensitive) {
                    out.push(crate::search::Match {
                        message: id,
                        source,
                        start,
                        end,
                    });
                }
            }
        }
        out
    }

    /// The speaker whose avatar covers content point `(x, y)`, if any.
    ///
    /// The avatar is painted from `LayoutCache::avatar`, not from a line
    /// box, so the ordinary caret hit-test cannot see it — clicking an
    /// icon found nothing at all. Asking the layout directly keeps the
    /// clickable area and the painted area the same rectangle by
    /// construction.
    pub fn avatar_at(&mut self, x: i32, y: u64) -> Option<(MessageId, u64)> {
        let hit = self.index.locate(y)?;
        let top = self.index.offset_of(hit.row);
        let row = self.rows.get(hit.row)?;
        let av = row.layout.as_ref()?.avatar?;
        let id = row.id;
        let local_y = y.checked_sub(top)? as i64;
        let (ax, ay, size) = (av.x as i64, av.y as i64, av.size as i64);
        if (x as i64) >= ax && (x as i64) < ax + size && local_y >= ay && local_y < ay + size {
            // The id comes back with the key because the caller needs
            // both and this has already found the row. Making it look
            // the row up again meant a second borrow of the buffer while
            // this one was still live — an instant RefCell panic on the
            // first avatar hover.
            Some((id, av.key))
        } else {
            None
        }
    }

    /// A selection covering the whole buffer, or `None` when empty.
    ///
    /// The model owns what "everything" means, because the view kept
    /// getting it wrong: it hard-coded `Block(0)` at both ends, which
    /// skipped the first row's *gutter* and — once markdown started
    /// splitting a body into several blocks — stopped at the end of the
    /// first block of the last row, dropping any code block or quote
    /// after it.
    pub fn select_all(&self) -> Option<Selection> {
        if self.rows.is_empty() {
            return None;
        }
        let last_row = self.rows.len() - 1;
        let first_src = *self.sources_of(0).first()?;
        let last_src = *self.sources_of(last_row).last()?;
        let end = self.source_text(last_row, last_src).map_or(0, |t| t.len());
        Some(Selection::new(
            Caret {
                message: self.id_at(0)?,
                source: first_src,
                offset: 0,
            },
            Caret {
                message: self.id_at(last_row)?,
                source: last_src,
                offset: end,
            },
        ))
    }

    /// Matches falling inside one row's one source, for the renderer.
    ///
    /// The renderer asks per source per row while drawing, so this is a
    /// filter over the result set rather than a fresh search.
    pub fn matches_in(
        all: &[crate::search::Match],
        id: MessageId,
        source: LineSource,
    ) -> Vec<crate::search::Match> {
        all.iter()
            .filter(|m| m.message == id && m.source == source)
            .copied()
            .collect()
    }

    /// Scroll so `id` is on screen, centred if it isn't already visible.
    ///
    /// Leaves an already-visible row where it is. Yanking the viewport
    /// on every step would make walking a cluster of matches in one
    /// screenful feel like the view was fighting you.
    pub fn reveal(&mut self, id: MessageId, viewport_height: u32, measure: &dyn TextMeasure) {
        self.reindex();
        let Some(row) = self.row_of(id) else { return };
        // The offset is only meaningful once the row has a real height
        // rather than an estimate, so measure it first.
        self.ensure_layout(row, measure);
        let top = self.index.offset_of(row);
        let h = self.index.height_at(row) as u64;
        let cur = self.scroll_offset(viewport_height);
        let vh = viewport_height as u64;
        if top >= cur && top + h <= cur + vh {
            return;
        }
        let target = if h >= vh {
            top
        } else {
            top.saturating_sub((vh - h) / 2)
        };
        self.scroll_to(target, viewport_height, 0);
    }

    /// The settled gutter width. 0 when not in indent mode.
    pub fn indent_width(&self) -> u32 {
        self.indent_width
    }

    /// Whether the gutter has been pinned by a separator drag.
    pub fn indent_pinned(&self) -> bool {
        self.indent_pinned
    }

    /// Pin the gutter to `px`, as a separator drag does.
    ///
    /// Deliberately not clamped to `max_indent`: that cap governs how
    /// far the gutter may grow *on its own*, and a user dragging the
    /// separator is saying something the cap has no business overruling.
    /// The caller clamps to the viewport instead. Returns whether
    /// anything moved.
    pub fn set_indent_width(&mut self, px: u32) -> bool {
        let px = px.max(MIN_INDENT);
        self.indent_pinned = true;
        if px == self.indent_width {
            return false;
        }
        self.indent_width = px;
        self.invalidate_layout();
        true
    }

    /// Drop the auto-sized gutter so it re-reconciles from scratch.
    ///
    /// A no-op once pinned: every caller of this is some *other* knob
    /// changing (buffer cleared, stamp width changed, indent toggled),
    /// and none of them is a reason to discard a width the user set by
    /// hand.
    fn reset_indent(&mut self) {
        if !self.indent_pinned {
            self.indent_width = 0;
        }
    }

    /// Release the pin and let the gutter auto-size again.
    pub fn unpin_indent(&mut self) {
        if !self.indent_pinned {
            return;
        }
        self.indent_pinned = false;
        self.indent_width = 0;
        self.invalidate_layout();
    }

    /// Map a content-space pixel to a document position.
    ///
    /// `x` / `y` are in content coordinates (the view subtracts its own
    /// padding first). `y` is absolute within the buffer, not
    /// viewport-relative.
    ///
    /// Returns `None` only for an empty buffer; a point past the end
    /// clamps to the last row, because a drag that runs off the bottom
    /// should select to the end rather than stop tracking.
    pub fn hit_test(&mut self, x: i32, y: u64, measure: &dyn TextMeasure) -> Option<Caret> {
        let hit = self.index.locate(y)?;
        let row = hit.row;
        self.ensure_layout(row, measure);
        let id = self.id_at(row)?;
        let layout = self.layout_at(row)?;

        // The line whose band contains the point.
        //
        // Several boxes can share a y band — the gutter and the first
        // body line always do — so x has to break the tie, otherwise
        // every click on row 0 resolves to whichever was pushed first
        // and the other becomes unselectable.
        let in_band: Vec<&crate::wrap::LineBox> = layout
            .lines
            .iter()
            .filter(|l| hit.offset >= l.y && hit.offset < l.y + l.height)
            .collect();
        let line = in_band
            .iter()
            .copied()
            .find(|l| {
                let w = self
                    .source_text_for(&self.rows[row].msg, l.source)
                    .and_then(|t| t.get(l.range.clone()))
                    .map(|slice| measure.run_width(slice, Style::default()))
                    .unwrap_or(0);
                x >= l.x as i32 && x < (l.x + w) as i32
            })
            // No box owns the x: fall back to the nearest by distance,
            // so a click in the gap between gutter and body still picks
            // something sensible rather than nothing.
            .or_else(|| {
                in_band
                    .iter()
                    .copied()
                    .min_by_key(|l| (x - l.x as i32).abs())
            })
            .or_else(|| {
                if hit.offset < layout.lines.first().map_or(0, |l| l.y) {
                    layout.lines.first()
                } else {
                    layout.lines.last()
                }
            })?;

        let source = line.source;
        let range = line.range.clone();
        let line_x = line.x as i32;
        let text = self.source_text(row, source)?;
        let slice = text.get(range.clone()).unwrap_or("");

        // Within the line, find the byte the x lands on. Left of the
        // line start selects from its beginning; right of the end
        // selects through it, which is what makes dragging past the end
        // of a short line feel right.
        let rel = x - line_x;
        let offset = if rel <= 0 {
            range.start
        } else {
            let (fit, _) = measure.fit_prefix(slice, Style::default(), rel as u32);
            (range.start + fit).min(range.end)
        };

        Some(Caret {
            message: id,
            source,
            offset,
        })
    }

    /// How much of `row` a selection covers.
    pub fn row_selection(&self, row: usize, sel: &Selection) -> RowSelection {
        if sel.is_empty() {
            return RowSelection::None;
        }
        let (start, end) = sel.ordered(|id| self.row_of(id));
        let (Some(sr), Some(er)) = (self.row_of(start.message), self.row_of(end.message)) else {
            return RowSelection::None;
        };
        if row < sr || row > er {
            return RowSelection::None;
        }
        if row > sr && row < er {
            return RowSelection::All;
        }
        // A boundary row. The covered span can begin in one source and
        // end in another (gutter → body), so both endpoints are carried
        // and the caller resolves per source.
        let last = self.last_source(row);
        let (from, to) = if sr == er {
            ((start.source, start.offset), (end.source, end.offset))
        } else if row == sr {
            // Starts here, runs to the end of the row.
            (
                (start.source, start.offset),
                (last, self.source_text(row, last).map_or(0, |t| t.len())),
            )
        } else {
            // Ends here, having begun above.
            ((self.first_source(row), 0), (end.source, end.offset))
        };
        RowSelection::Partial {
            start: from,
            end: to,
        }
    }

    /// The row's sources in visual order: gutter first, then blocks.
    pub fn sources_of(&self, row: usize) -> Vec<LineSource> {
        let mut out = Vec::new();
        let Some(msg) = self.message_at(row) else {
            return out;
        };
        if msg.gutter.as_ref().is_some_and(|g| !g.text.is_empty()) {
            out.push(LineSource::Gutter);
        }
        for i in 0..msg.blocks.len() {
            out.push(LineSource::Block(i));
        }
        out
    }

    fn first_source(&self, row: usize) -> LineSource {
        self.sources_of(row)
            .first()
            .copied()
            .unwrap_or(LineSource::Block(0))
    }

    fn last_source(&self, row: usize) -> LineSource {
        self.sources_of(row)
            .last()
            .copied()
            .unwrap_or(LineSource::Block(0))
    }

    /// The byte range of `source` covered by a row selection, if any.
    ///
    /// The one place that resolves a possibly-cross-source `Partial`
    /// against a single text, so the view and `selected_text` cannot
    /// disagree about what is highlighted versus what gets copied.
    pub fn covered_range(
        &self,
        row: usize,
        source: LineSource,
        sel: &RowSelection,
    ) -> Option<std::ops::Range<usize>> {
        let len = self.source_text(row, source).map_or(0, |t| t.len());
        match sel {
            RowSelection::None => None,
            RowSelection::All => Some(0..len),
            RowSelection::Partial { start, end } => {
                let rank = crate::select::source_rank(source);
                let (sr, so) = *start;
                let (er, eo) = *end;
                let (sr, er) = (
                    crate::select::source_rank(sr),
                    crate::select::source_rank(er),
                );
                if rank < sr || rank > er {
                    return None;
                }
                let from = if rank == sr { so.min(len) } else { 0 };
                let to = if rank == er { eo.min(len) } else { len };
                if from < to {
                    Some(from..to)
                } else {
                    None
                }
            }
        }
    }

    /// The selected text of each covered row, as `(row, text)`.
    ///
    /// Exposed per row because a row's own text may contain hard
    /// newlines — the wrap engine supports them — so a caller cannot
    /// recover row boundaries by splitting the joined string. The
    /// autocopy-timestamp path needs exactly that: it prefixes each
    /// *row* with that row's stamp, and iterating `lines()` over the
    /// joined output drifts onto the wrong rows the moment any selected
    /// message spans more than one line.
    pub fn selected_rows(&self, sel: &Selection) -> Vec<(usize, String)> {
        if sel.is_empty() {
            return Vec::new();
        }
        let (start, end) = sel.ordered(|id| self.row_of(id));
        let (Some(sr), Some(er)) = (self.row_of(start.message), self.row_of(end.message)) else {
            return Vec::new();
        };
        let mut out = Vec::new();
        for row in sr..=er {
            // Walk the row's sources in visual order and take whatever
            // each contributes. One path for every case, so the gutter
            // is copied when it is selected and only then.
            let rsel = self.row_selection(row, sel);
            let mut text = String::new();
            let mut prev: Option<LineSource> = None;
            // A row can be *covered* and still contribute nothing — the
            // first and last rows of a selection that starts at the end
            // of one row and ends at the start of another. Those must
            // not be reported: they become blank lines in the copied
            // text, and AUTOCOPY_STAMP would prefix a timestamp to a row
            // with no content. A row that is genuinely empty is a
            // different thing and does belong in the output as a blank
            // line, so the test is "had text and none of it was
            // selected", not "produced no text".
            let mut had_text = false;
            for source in self.sources_of(row) {
                // Note the order: `had_text` has to be established
                // before any early-continue, or a row whose coverage is
                // empty everywhere looks indistinguishable from a row
                // that is empty.
                let Some(t) = self.source_text(row, source) else {
                    continue;
                };
                had_text |= !t.is_empty();
                let Some(range) = self.covered_range(row, source, &rsel) else {
                    continue;
                };
                let Some(slice) = t.get(range) else { continue };
                if slice.is_empty() {
                    continue;
                }
                // Separator matches Message::to_plain_text, which is
                // what whole-row copying used before this path existed:
                // a space between the gutter and the body (they read as
                // one line), a newline between body blocks (they are
                // distinct blocks and collapsing them to spaces would
                // run a code block into the paragraph after it).
                match prev {
                    None => {}
                    Some(LineSource::Gutter) => text.push(' '),
                    Some(LineSource::Block(_)) => text.push('\n'),
                }
                text.push_str(slice);
                prev = Some(source);
            }
            if text.is_empty() && had_text {
                continue;
            }
            out.push((row, text));
        }
        out
    }

    /// The selected text, rows joined by newlines.
    pub fn selected_text(&self, sel: &Selection) -> String {
        self.selected_rows(sel)
            .into_iter()
            .map(|(_, t)| t)
            .collect::<Vec<_>>()
            .join("\n")
    }

    pub fn layout_at(&self, row: usize) -> Option<&LayoutCache> {
        self.rows.get(row).and_then(|r| r.layout.as_deref())
    }

    pub fn total_height(&mut self) -> u64 {
        self.index.total_height()
    }

    pub fn index_mut(&mut self) -> &mut HeightIndex {
        &mut self.index
    }

    /// The scroll adjustment value the current anchor implies.
    pub fn scroll_offset(&mut self, viewport_height: u32) -> u64 {
        // Only the anchored row is ever asked for.
        let row = self.anchor.message.and_then(|id| self.locate(id));
        AnchorResolver::to_pixels(&self.anchor, &mut self.index, viewport_height, |_| row)
    }

    /// The row `id` names, from a remembered row when `pos` is dirty and
    /// the id was asked for recently, else by rebuilding `pos`.
    fn locate(&mut self, id: MessageId) -> Option<usize> {
        if !self.pos_dirty {
            return self.row_of(id);
        }
        let known = self
            .hints
            .iter()
            .flatten()
            .find(|&&(h, r)| h == id && self.rows.get(r).is_some_and(|row| row.id == id))
            .map(|&(_, r)| r);
        if known.is_some() {
            return known;
        }
        self.reindex();
        let row = self.row_of(id)?;
        self.hints = [Some((id, row)), self.hints[0].filter(|&(h, _)| h != id)];
        Some(row)
    }

    /// Rows at `from` and below moved by `delta`: move the hints with them.
    fn shift_hints(&mut self, from: usize, delta: isize) {
        for (_, r) in self.hints.iter_mut().flatten() {
            if *r >= from {
                *r = r.saturating_add_signed(delta);
            }
        }
    }

    /// Row `row` is gone: drop a hint that named it.
    fn forget_hint(&mut self, row: usize) {
        for h in &mut self.hints {
            if h.is_some_and(|(_, r)| r == row) {
                *h = None;
            }
        }
    }

    /// Re-anchor from a pixel position — a scrollbar drag.
    pub fn scroll_to(&mut self, y: u64, viewport_height: u32, follow_slop: u32) {
        // Borrow the rows rather than collecting their ids: a copy here
        // made every scroll cost O(scrollback).
        let rows = &self.rows;
        self.anchor =
            AnchorResolver::from_pixels(y, &mut self.index, viewport_height, follow_slop, |row| {
                rows.get(row).map(|r| r.id)
            });
    }

    /// Pin to the bottom and resume following.
    pub fn scroll_to_bottom(&mut self) {
        self.anchor = ScrollAnchor::bottom();
    }

    pub fn is_following(&self) -> bool {
        self.anchor.gravity == Gravity::Bottom
    }
}