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
//! Line breaking and per-message layout.
//!
//! Produces a [`LayoutCache`] for one message at one width: its total
//! pixel height and the line boxes needed for hit-testing. This is where
//! both layouts live: two columns, with the timestamp and nick gutter on
//! the left and the body indented past it, and one, with the nick at the
//! start of the body's first line.
//!
//! Measurement goes through [`TextMeasure`], one call per *run*, never
//! per character. xtext's `find_next_wrap` (xtext.c:3685) measured
//! character by character through a full Pango layout round trip each
//! time; that is the single hottest thing in its append path and the
//! reason a resize of a large buffer visibly hitches.

use crate::measure::TextMeasure;
use crate::message::{Block, Message, MessageFlags};
use crate::span::{ParsedText, Span, Style};
use std::ops::Range;

/// Identifies the conditions a [`LayoutCache`] was computed under.
///
/// A cache is valid only for the generation it was built at; anything
/// that changes rendered geometry bumps a field. Critically, bumping a
/// generation does **not** trigger recomputation — caches are rebuilt
/// lazily when a row is next laid out, so a resize costs O(visible).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct LayoutGeneration {
    /// Content width in pixels.
    pub width: u32,
    /// Bumped on font change.
    pub font: u32,
    /// Bumped on theme change (palette resolution can alter nothing
    /// geometric, but a theme may carry a font).
    pub theme: u32,
    /// Zoom level in per-mille, so the generation stays `Eq`-comparable.
    /// See docs/design.md "Layout, the height index, and scroll anchoring".
    pub zoom_permille: u32,
}

/// What a [`LineBox`] draws text from.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum LineSource {
    /// The left column — the pre-rendered gutter, or the speaker's nick.
    /// Always the message's first line box when present.
    Gutter,
    /// Body block `n`.
    Block(usize),
}

/// One visual line within a message.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct LineBox {
    /// Y offset from the top of the message.
    pub y: u32,
    pub height: u32,
    /// Byte range within the owning source's text.
    pub range: Range<usize>,
    /// Where this line's text comes from.
    pub source: LineSource,
    /// X offset — the indent column, or 0 for full-width content.
    pub x: u32,
    /// Measured width of the line's text, in px.
    ///
    /// Recorded here rather than re-measured by the view because the
    /// wrap pass already knows it — it is the number the break decision
    /// was made on. Anything that wants to draw a box around laid-out
    /// text (a fenced code block, today) gets the same extent the
    /// wrapper used, so the box cannot disagree with the wrap.
    pub width: u32,
}

/// What a laid-out message knows about itself.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct LayoutCache {
    pub generation: LayoutGeneration,
    pub height: u32,
    pub lines: Vec<LineBox>,
    /// Width the gutter/nick column actually needed, before clamping to
    /// [`LayoutParams::max_indent`].
    pub natural_indent: u32,
    /// Where to paint the speaker's avatar, when there is one to paint.
    ///
    /// Only ever set on a *group head* — a continuation row shows
    /// neither the nick nor the icon, which is the whole point of
    /// grouping. The view resolves the actual image from the key at
    /// draw time, because avatars animate and a cached frame would
    /// freeze.
    pub avatar: Option<AvatarBox>,
}

/// A square avatar slot in the gutter, in row-local coordinates.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct AvatarBox {
    pub x: u32,
    pub y: u32,
    pub size: u32,
    pub key: u64,
}

/// Geometry knobs, supplied by the view.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct LayoutParams {
    /// Total content width available.
    pub width: u32,
    /// Two-column mode: body indented past a nick/timestamp gutter.
    pub indent: bool,
    /// Cap on the gutter width. Below it the gutter grows to fit the
    /// widest nick seen, which is what `gtk_xtext_fix_indent` did.
    pub max_indent: u32,
    /// Current gutter width, shared across the buffer so columns line
    /// up between rows.
    pub indent_width: u32,
    /// Width reserved at the left of the gutter for the timestamp
    /// column, or 0 when timestamps are off.
    ///
    /// The layout engine never formats a timestamp — it can't, having no
    /// locale or time formatting — it only reserves the space the view
    /// says it needs, so the gutter is wide enough for stamp + nick.
    pub stamp_width: u32,
    /// Gap between the right edge of the gutter and the body column.
    pub gutter_gap: u32,
    /// Left padding inside a quote block, per nesting level.
    pub quote_indent: u32,
    /// Vertical padding above and below an image or code block.
    pub block_padding: u32,
    pub word_wrap: bool,
    /// Edge length of the avatar slot in the gutter, or 0 for no
    /// avatars. Driven by the Settings toggle.
    pub avatar_size: u32,
}

impl Default for LayoutParams {
    fn default() -> Self {
        LayoutParams {
            width: 640,
            indent: true,
            max_indent: 256,
            indent_width: 0,
            stamp_width: 0,
            gutter_gap: 6,
            quote_indent: 12,
            block_padding: 2,
            word_wrap: true,
            avatar_size: 0,
        }
    }
}

/// Lay one message out.
pub fn layout_message(
    msg: &Message,
    params: &LayoutParams,
    generation: LayoutGeneration,
    measure: &dyn TextMeasure,
) -> LayoutCache {
    let metrics = measure.metrics();
    let line_h = metrics.line_height.max(1);
    let mut lines = Vec::new();
    let mut y = 0u32;

    // The gutter is only as wide as this message needs; the buffer
    // reconciles the maximum across rows and re-lays out when it grows.
    //
    // A pre-rendered gutter (see Message::gutter) wins over the speaker's
    // bare nick, because it carries the styling the application chose.
    // A grouped row is a continuation of the one above: same speaker,
    // close in time. Its gutter is suppressed so a burst of messages
    // reads as one block under one name instead of repeating the nick
    // (and, once avatars land, the icon) on every line. The body keeps
    // its indent, so the column stays straight.
    //
    // The flag is set by ChatBuffer, which is the only thing that can
    // see a message's neighbours. It still contributes its *natural*
    // gutter width below, so hiding a nick never narrows the shared
    // column and shifts every other row sideways.
    let grouped = msg.flags.contains(crate::message::MessageFlags::GROUPED);

    // An avatar is only drawn on a group head, but *every* row with a
    // speaker reserves its width — otherwise the shared gutter narrows
    // the moment a run forms and every column in the buffer jumps.
    let avatar_slot = if params.indent && params.avatar_size > 0 {
        match &msg.speaker {
            Some(s) if s.key != 0 => params.avatar_size + params.gutter_gap,
            _ => 0,
        }
    } else {
        0
    };

    let natural_indent = if params.indent {
        let gutter_text = match (&msg.gutter, &msg.speaker) {
            (Some(g), _) if !g.text.is_empty() => {
                measure_styled(g, 0..g.text.len(), measure) + metrics.space_width
            }
            (_, Some(s)) => measure.run_width(&s.nick, Style::default()) + metrics.space_width * 2,
            _ => 0,
        };
        // The gutter holds the timestamp *and* the nick, side by side,
        // so it has to be wide enough for both — reserving only the nick
        // width is what makes a stamp overlap it.
        params.stamp_width + avatar_slot + gutter_text
    } else {
        0
    };

    let body_x = if params.indent {
        params.indent_width
    } else {
        0
    };
    let body_width = params.width.saturating_sub(body_x).max(line_h);

    // The gutter is one unwrapped line, always first, carrying the x it
    // is actually drawn at.
    //
    // Right-aligned against the body column, the way xtext aligns its
    // left text (`ent->indent = buf->indent - left_width - space_width`,
    // xtext.c). Computing it *here* rather than in the view matters: the
    // view previously derived it from `params().indent_width`, which is
    // only ever set on a local copy inside `ensure_layout` and so read
    // back as 0 — the gutter drew hard left while bodies moved right as
    // the column grew, and hit-testing used the same wrong x, which is
    // why nicks could not be selected. One source of truth removes both
    // bugs at once.
    // The avatar sits at the left of the gutter, just past the stamp,
    // with the nick to its right. Group heads only.
    let avatar = if avatar_slot > 0 && !grouped {
        msg.speaker.as_ref().map(|s| AvatarBox {
            x: params.stamp_width,
            y: 0,
            size: params.avatar_size,
            key: s.key,
        })
    } else {
        None
    };

    // Where the first body line starts, in single-column mode: past the
    // timestamp and the gutter, which share its line instead of having a
    // column of their own. Zero in two-column mode, where both live in
    // the gutter column.
    let mut lead = 0u32;
    let gutter = msg
        .gutter
        .as_ref()
        .filter(|g| !g.text.is_empty() && !grouped);
    if let Some(g) = gutter {
        let gw = measure_styled(g, 0..g.text.len(), measure);
        let gx = if params.indent {
            params
                .indent_width
                .saturating_sub(gw + params.gutter_gap)
                .max(params.stamp_width)
        } else {
            params.stamp_width
        };
        lines.push(LineBox {
            y: 0,
            height: line_h,
            range: 0..g.text.len(),
            source: LineSource::Gutter,
            x: gx,
            width: gw,
        });
        if !params.indent {
            lead = gx + gw + metrics.space_width;
        }
    } else if !params.indent {
        lead = params.stamp_width;
    }
    // Only a text body can start beside the gutter. Anything else — a
    // code block, a quote, an image — starts on the line below it, since
    // it has a box or an indent of its own that the lead would break. So
    // does a body with less than half the width left beside a long nick:
    // one word per line down the right edge is worse than a line break.
    //
    // Either way the first line is left to the stamp and the gutter, which
    // the view draws there; a lead is only ever nonzero because one of
    // them is.
    if lead > 0 && (!matches!(msg.blocks.first(), Some(Block::Text(_))) || lead > body_width / 2) {
        y = line_h;
        lead = 0;
    }

    for (bi, block) in msg.blocks.iter().enumerate() {
        match block {
            Block::Text(p) => {
                let first = if bi == 0 { lead } else { 0 };
                let n = wrap_text(
                    p,
                    body_width,
                    first,
                    params.word_wrap,
                    measure,
                    |range, lw, dx| {
                        lines.push(LineBox {
                            y,
                            height: line_h,
                            range,
                            source: LineSource::Block(bi),
                            x: body_x + dx,
                            width: lw,
                        });
                        y += line_h;
                    },
                );
                // An empty block still occupies a line, so a blank
                // message doesn't collapse to zero height and become
                // unclickable.
                if n == 0 {
                    lines.push(LineBox {
                        y,
                        height: line_h,
                        range: 0..0,
                        source: LineSource::Block(bi),
                        x: body_x + first,
                        width: 0,
                    });
                    y += line_h;
                }
            }
            Block::Code { text, .. } => {
                y += params.block_padding;
                // Code never wraps on words — breaking a token would
                // change what it says. Overflow clips.
                let mut start = 0usize;
                // Code blocks carry no spans, so they draw — and so must
                // measure — in the default style.
                let plain = Style::default();
                for (i, _) in text.match_indices('\n') {
                    lines.push(LineBox {
                        y,
                        height: line_h,
                        range: start..i,
                        source: LineSource::Block(bi),
                        x: body_x,
                        width: measure.run_width(&text[start..i], plain),
                    });
                    y += line_h;
                    start = i + 1;
                }
                lines.push(LineBox {
                    y,
                    height: line_h,
                    range: start..text.len(),
                    source: LineSource::Block(bi),
                    x: body_x,
                    width: measure.run_width(&text[start..], plain),
                });
                y += line_h + params.block_padding;
            }
            Block::Quote { content, depth } => {
                let qx = body_x + params.quote_indent * u32::from(*depth).max(1);
                let qw = params.width.saturating_sub(qx).max(line_h);
                let n = wrap_text(content, qw, 0, params.word_wrap, measure, |range, lw, _| {
                    lines.push(LineBox {
                        y,
                        height: line_h,
                        range,
                        source: LineSource::Block(bi),
                        x: qx,
                        width: lw,
                    });
                    y += line_h;
                });
                // An empty quote still gets a line box, for the same
                // reason an empty text block does: a row with no line
                // boxes occupies vertical space that nothing can hit-test
                // or select, which reads as a dead patch in the buffer.
                if n == 0 {
                    lines.push(LineBox {
                        y,
                        height: line_h,
                        range: 0..0,
                        source: LineSource::Block(bi),
                        x: qx,
                        width: 0,
                    });
                    y += line_h;
                }
            }
            Block::Image { size, alt, .. } => match size {
                // The decode has landed: a real pixel height, not
                // `ceil(h / fontsize)` blank text rows with a texture
                // painted across them (xtext.c:4345). Selection,
                // hit-testing and the marker line all just work.
                Some(sz) => {
                    y += params.block_padding;
                    let (iw, h) = measure.image_size((sz.width, sz.height), body_width);
                    lines.push(LineBox {
                        y,
                        height: h,
                        range: 0..alt.len(),
                        source: LineSource::Block(bi),
                        x: body_x,
                        width: iw,
                    });
                    y += h + params.block_padding;
                }
                // Not decoded yet — measure as the placeholder text, so
                // the row doesn't jump when the bytes arrive any more
                // than it has to.
                None => {
                    let p = ParsedText::plain(alt.clone());
                    let n = wrap_text(
                        &p,
                        body_width,
                        0,
                        params.word_wrap,
                        measure,
                        |range, lw, _| {
                            lines.push(LineBox {
                                y,
                                height: line_h,
                                range,
                                source: LineSource::Block(bi),
                                x: body_x,
                                width: lw,
                            });
                            y += line_h;
                        },
                    );
                    // Same rule: an image whose alt text is empty must
                    // still be clickable — that is how the user opens
                    // the media dialog before the decode lands.
                    if n == 0 {
                        lines.push(LineBox {
                            y,
                            height: line_h,
                            range: 0..0,
                            source: LineSource::Block(bi),
                            x: body_x,
                            width: 0,
                        });
                        y += line_h;
                    }
                }
            },
        }
    }

    if lines.is_empty() {
        y = line_h;
    }

    // Centre the text against the icon when the icon is the taller of
    // the two.
    //
    // Without this the text sits on the icon's top edge, which reads as
    // misalignment rather than as a design: the eye pairs a 32px icon
    // with the line beside it, and "beside" means centred. Shifting
    // every line box (rather than only the first) keeps a two-line
    // message centred as a block, which is what looks right when the
    // message is still shorter than the icon.
    //
    // Done here, on the finished line boxes, so hit-testing and painting
    // move together — the alternative, offsetting only at draw time, is
    // the class of bug where you can see text you cannot select.
    let text_h = y.max(line_h);
    let row_h = text_h.max(avatar.map(|a| a.size).unwrap_or(0));
    if row_h > text_h {
        let shift = (row_h - text_h) / 2;
        for l in &mut lines {
            l.y += shift;
        }
    }

    LayoutCache {
        generation,
        // A head row must be at least as tall as its avatar, or the
        // icon overflows into the row below. This is the case the
        // "re-estimate on regroup" fix in ChatBuffer exists for: a head
        // and its continuations now genuinely differ in height.
        height: row_h,
        lines,
        natural_indent: natural_indent.min(params.max_indent),
        avatar,
    }
}

/// Break `p` into visual lines, calling `emit` per line with the line's
/// range, its width, and how far right of the block's x it starts.
/// Returns the count.
///
/// The first line starts `first_indent` in and is that much narrower;
/// every later line has the full width. That is how a single-column row
/// puts its body beside the nick rather than under it.
fn wrap_text(
    p: &ParsedText,
    width: u32,
    first_indent: u32,
    word_wrap: bool,
    measure: &dyn TextMeasure,
    mut emit: impl FnMut(Range<usize>, u32, u32),
) -> usize {
    if p.text.is_empty() {
        return 0;
    }
    let mut count = 0usize;
    let mut line_start = 0usize;
    let first_width = width.saturating_sub(first_indent).max(1);
    let avail = |count: usize| if count == 0 { first_width } else { width };
    let dx = |count: usize| if count == 0 { first_indent } else { 0 };

    while line_start < p.text.len() {
        // A hard newline always breaks.
        let hard = p.text[line_start..]
            .find('\n')
            .map(|i| line_start + i)
            .unwrap_or(p.text.len());
        let segment = &p.text[line_start..hard];

        if segment.is_empty() {
            emit(line_start..line_start, 0, dx(count));
            count += 1;
            line_start = hard + 1;
            continue;
        }

        let mut seg_start = line_start;
        loop {
            let rest = &p.text[seg_start..hard];
            if rest.is_empty() {
                break;
            }
            let w = measure_styled(p, seg_start..hard, measure);
            let width = avail(count);
            if w <= width {
                emit(seg_start..hard, w, dx(count));
                count += 1;
                break;
            }
            // Doesn't fit: find the break point, honouring every style
            // change between here and the boundary.
            let (fit_abs, fit_w) = fit_styled_prefix(p, seg_start..hard, width, measure);
            let mut brk = fit_abs.max(seg_start + 1);
            if word_wrap {
                if let Some(sp) = p.text[seg_start..brk].rfind([' ', '\t']) {
                    if sp > 0 {
                        brk = seg_start + sp;
                    }
                }
            }
            while brk < p.text.len() && !p.text.is_char_boundary(brk) {
                brk += 1;
            }
            if brk <= seg_start {
                brk = next_boundary(&p.text, seg_start);
            }
            // Reuse the prefix measurement when word-wrap didn't move
            // the break; re-measure only the shorter line we actually
            // emit. The common case costs nothing extra.
            let lw = if brk == fit_abs {
                fit_w
            } else {
                measure_styled(p, seg_start..brk, measure)
            };
            emit(seg_start..brk, lw, dx(count));
            count += 1;
            // Swallow the space we broke on.
            seg_start = brk;
            while seg_start < hard && p.text.as_bytes()[seg_start] == b' ' {
                seg_start += 1;
            }
        }
        line_start = hard + 1;
    }
    count
}

/// Walk `range` as maximal runs of uniform style, without allocating.
///
/// Gaps between spans are default-styled. This is the one place that
/// knows how to walk a `ParsedText`'s style structure, so measuring and
/// break-point search can't drift apart.
///
/// Callback rather than a returned `Vec` because both callers sit on the
/// wrapping hot path — `measure_styled` runs per candidate line and
/// `fit_styled_prefix` per overflowing line, so an allocation each would
/// be a per-line malloc during layout. `f` returning `Some` stops the
/// walk early, which is what lets the prefix search bail at the run that
/// straddles the width boundary.
fn walk_style_runs<R>(
    p: &ParsedText,
    range: Range<usize>,
    mut f: impl FnMut(Range<usize>, Style) -> Option<R>,
) -> Option<R> {
    let mut cursor = range.start;
    for s in &p.spans {
        if s.range.end <= cursor || s.range.start >= range.end {
            continue;
        }
        if s.range.start > cursor {
            if let Some(r) = f(cursor..s.range.start, Style::default()) {
                return Some(r);
            }
            cursor = s.range.start;
        }
        let end = s.range.end.min(range.end);
        if end > cursor {
            if let Some(r) = f(cursor..end, s.style) {
                return Some(r);
            }
            cursor = end;
        }
    }
    if cursor < range.end {
        return f(cursor..range.end, Style::default());
    }
    None
}

/// Total width of a byte range, measured one style run at a time.
///
/// The per-run granularity is the point: a 200-character message with
/// two bold words costs three measure calls, not two hundred.
fn measure_styled(p: &ParsedText, range: Range<usize>, measure: &dyn TextMeasure) -> u32 {
    let mut total = 0u32;
    walk_style_runs::<()>(p, range, |r, style| {
        total += measure.run_width(&p.text[r], style);
        None
    });
    total
}

/// Largest prefix of `range` fitting in `max_width`, honouring every
/// style change inside it.
///
/// The naive version — measure the whole rest with the style in effect
/// at its *start* — is wrong as soon as a run changes style partway
/// through, which `**bold**` and `` `code` `` both do. Bold and
/// monospace are wider than the base font, so a break point chosen from
/// the start style under-measures and the drawn line overflows its box.
/// Walking runs and only calling the measurer's own prefix search on the
/// single run that straddles the boundary is both correct and no more
/// expensive.
fn fit_styled_prefix(
    p: &ParsedText,
    range: Range<usize>,
    max_width: u32,
    measure: &dyn TextMeasure,
) -> (usize, u32) {
    let mut total = 0u32;
    let mut cursor = range.start;
    let straddled = walk_style_runs(p, range, |r, style| {
        let seg = &p.text[r.clone()];
        let w = measure.run_width(seg, style);
        if total + w <= max_width {
            total += w;
            cursor = r.end;
            return None;
        }
        // This run crosses the boundary — only it needs the measurer's
        // own prefix search.
        let (fit, fw) = measure.fit_prefix(seg, style, max_width.saturating_sub(total));
        Some((r.start + fit, total + fw))
    });
    straddled.unwrap_or((cursor, total))
}

fn next_boundary(s: &str, from: usize) -> usize {
    let mut i = from + 1;
    while i < s.len() && !s.is_char_boundary(i) {
        i += 1;
    }
    i.min(s.len())
}

/// Rough height for a row that has never been laid out.
///
/// Feeds the estimated heights in [`crate::index`]. Deliberately crude —
/// it only has to keep the scrollbar plausible until the row is actually
/// measured, and being fast matters more than being close, since it runs
/// for every row in the buffer on a resize.
///
/// Crude, but not *low*. The distinction matters because while the view
/// is following the bottom its scroll offset is `total - viewport`, and
/// the total is this estimate for every row that has not been laid out
/// yet — which always includes the row that was just appended. An
/// under-estimate therefore puts "the bottom" above the real bottom and
/// clips the newest message off the bottom edge. Over-estimating costs a
/// slightly wrong scrollbar thumb until the row is measured, which is
/// the tradeoff [`crate::index`] already documents.
///
/// Three things it has to get right for that, all of which it once got
/// wrong: a body's *hard newlines* (dividing the byte length by the
/// column count answers "how far would this wrap", not "how many lines
/// does it have", so a five-line message estimated as one); the width
/// the body actually wraps against, which in indent mode is the content
/// width less the gutter; and the vertical padding a code or image block
/// adds. The avatar floor is the same rule `layout_message` applies at
/// the end.
pub fn estimate_height(msg: &Message, params: &LayoutParams, measure: &dyn TextMeasure) -> u32 {
    let metrics = measure.metrics();
    let line_h = metrics.line_height.max(1);
    let body_x = if params.indent {
        params.indent_width
    } else {
        0
    };
    let body_width = params.width.saturating_sub(body_x).max(line_h);
    let cols = (body_width / metrics.space_width.max(1)).max(1) as usize;
    // Hard newlines break unconditionally; each resulting segment then
    // wraps on its own.
    let wrapped = |s: &str| {
        s.split('\n')
            .map(|seg| seg.len().div_ceil(cols).max(1))
            .sum::<usize>()
            .max(1)
    };
    let mut lines = 0usize;
    let mut extra = 0u32;

    // Single-column mode: the stamp and the gutter share the first body
    // line, so that line has that many fewer columns. Counted in bytes,
    // like everything else here, which over-counts a multibyte nick — on
    // the safe side.
    let gutter_cols = msg
        .gutter
        .as_ref()
        .filter(|g| !g.text.is_empty() && !msg.flags.contains(MessageFlags::GROUPED))
        .map(|g| g.text.len() + 1);
    let mut lead_cols = if params.indent {
        0
    } else {
        (params.stamp_width / metrics.space_width.max(1)) as usize + gutter_cols.unwrap_or(0)
    };
    // The same rule `layout_message` applies: a body that cannot start
    // beside the gutter starts on the line below it.
    let beside = matches!(msg.blocks.first(), Some(Block::Text(_))) && lead_cols <= cols / 2;
    if lead_cols > 0 && !beside {
        lines += 1;
        lead_cols = 0;
    }

    for (bi, b) in msg.blocks.iter().enumerate() {
        match b {
            Block::Text(p) if bi == 0 && lead_cols > 0 => {
                // Pad the first segment by the lead, then wrap as usual.
                let (first, rest) = p.text.split_once('\n').unwrap_or((&p.text, ""));
                lines += (first.len() + lead_cols).div_ceil(cols).max(1);
                if p.text.contains('\n') {
                    lines += wrapped(rest);
                }
            }
            Block::Text(p) => lines += wrapped(&p.text),
            Block::Code { text, .. } => {
                // Code never wraps, so it is exactly its own line count —
                // but it is boxed, and the box has padding above and
                // below.
                lines += text.split('\n').count().max(1);
                extra += params.block_padding * 2;
            }
            Block::Quote { content, depth } => {
                let qx = body_x + params.quote_indent * u32::from(*depth).max(1);
                let qw = params.width.saturating_sub(qx).max(line_h);
                let qcols = (qw / metrics.space_width.max(1)).max(1) as usize;
                lines += content
                    .text
                    .split('\n')
                    .map(|seg| seg.len().div_ceil(qcols).max(1))
                    .sum::<usize>()
                    .max(1);
            }
            Block::Image { size, alt, .. } => match size {
                Some(sz) => {
                    let (_, h) = measure.image_size((sz.width, sz.height), body_width);
                    extra += h + params.block_padding * 2;
                }
                None => lines += wrapped(alt),
            },
        }
    }
    let text_h = (lines.max(1) as u32) * line_h + extra;
    // A group head is at least as tall as the icon it draws.
    let avatar_h = if params.indent
        && params.avatar_size > 0
        && !msg.flags.contains(MessageFlags::GROUPED)
        && msg.speaker.as_ref().is_some_and(|s| s.key != 0)
    {
        params.avatar_size
    } else {
        0
    };
    text_h.max(avatar_h)
}

/// Whether a message draws in the muted secondary colour.
pub fn is_muted(msg: &Message) -> bool {
    msg.flags.contains(MessageFlags::MUTED) || msg.flags.contains(MessageFlags::DELETED)
}

/// Spans of `p` clipped to `range`, for the view's snapshot pass.
pub fn spans_in(p: &ParsedText, range: Range<usize>) -> Vec<Span> {
    p.spans
        .iter()
        .filter(|s| s.range.start < range.end && s.range.end > range.start)
        .map(|s| Span {
            range: s.range.start.max(range.start)..s.range.end.min(range.end),
            style: s.style,
        })
        .collect()
}