Skip to main content

text_typeset/layout/
paragraph.rs

1use std::collections::{HashMap, HashSet};
2use std::ops::Range;
3use std::sync::OnceLock;
4
5use icu_segmenter::LineSegmenter;
6use icu_segmenter::options::LineBreakOptions;
7
8use crate::layout::line::{LayoutLine, PositionedRun, RunDecorations};
9use crate::shaping::run::{ShapedGlyph, ShapedRun};
10use crate::shaping::shaper::{FontMetricsPx, TextDirection};
11
12/// How [`break_into_lines`] should treat the order of the runs it is given.
13///
14/// The two layout paths differ here and getting it wrong reverses text
15/// twice. The single-line path runs the bidi algorithm itself and shapes
16/// in display order, so its runs must be left alone; the block path hands
17/// over logical-order runs tagged with embedding levels and needs each
18/// line reordered once the breaks are known.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum RunOrder {
21    /// Runs already arrive in visual order — do not reorder them.
22    AlreadyVisual,
23    /// Runs are in logical order; reorder each line per UAX #9 rule L2,
24    /// and resolve `Start`/`End` alignment against this base direction.
25    Logical(TextDirection),
26}
27
28/// Whether a break opportunity *must* be taken (LB4/LB5 hard line
29/// break) or *may* be taken (regular UAX #14 break opportunity).
30///
31/// `icu_segmenter::LineSegmenter` doesn't distinguish the two — it just
32/// emits byte offsets — so we classify each emitted offset ourselves by
33/// looking at the line-break property of the preceding code point.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35enum BreakOpportunity {
36    Allowed,
37    Mandatory,
38}
39
40/// Shared compiled-data line segmenter. `LineSegmenter::new_auto`
41/// returns a `LineSegmenterBorrowed<'static>` (Copy, statically-baked
42/// CLDR data), but constructing it still touches the option-parsing
43/// path — cache once to keep `break_into_lines` allocation-free.
44fn line_segmenter() -> icu_segmenter::LineSegmenterBorrowed<'static> {
45    static CELL: OnceLock<icu_segmenter::LineSegmenterBorrowed<'static>> = OnceLock::new();
46    *CELL.get_or_init(|| LineSegmenter::new_auto(LineBreakOptions::default()))
47}
48
49/// UAX #14 LB4/LB5: a break at `byte_offset` is mandatory iff the
50/// immediately-preceding code point is one of the hard line break
51/// characters (LF, CR, NEL, VT, FF, LS, PS). The CR+LF sequence is
52/// handled implicitly: the segmenter emits a single break after the
53/// LF, and the char before that offset is `\n` — mandatory.
54fn is_mandatory_break_at(text: &str, byte_offset: usize) -> bool {
55    if byte_offset == 0 {
56        return false;
57    }
58    let preceding = &text[..byte_offset];
59    preceding
60        .chars()
61        .next_back()
62        .is_some_and(crate::types::is_hard_break)
63}
64
65/// Enumerate UAX #14 break opportunities in `text` and classify each
66/// as `Allowed` or `Mandatory`. Replaces the previous
67/// `unicode_linebreak::linebreaks(text)` call site one-to-one.
68fn enumerate_breaks(text: &str) -> Vec<(usize, BreakOpportunity)> {
69    line_segmenter()
70        .segment_str(text)
71        .map(|byte_offset| {
72            let kind = if is_mandatory_break_at(text, byte_offset) {
73                BreakOpportunity::Mandatory
74            } else {
75                BreakOpportunity::Allowed
76            };
77            (byte_offset, kind)
78        })
79        .collect()
80}
81
82/// Byte offsets in `text` where a hyphenated line break may occur and a
83/// hyphen glyph should be rendered: Knuth-Liang dictionary points inside
84/// words (in `lang_code`, an ISO 639-1 code) plus soft-hyphen (U+00AD)
85/// positions.
86///
87/// Returned offsets are "break before this byte" positions, matching the
88/// UAX #14 offsets from [`enumerate_breaks`]. Soft hyphens are honored
89/// regardless of language; dictionary breaks apply only when the
90/// language's patterns are compiled in (`hypher::Lang::from_iso` resolves
91/// it) — otherwise it gracefully degrades to soft-hyphen-only.
92fn hyphenation_breaks(text: &str, lang_code: [u8; 2]) -> Vec<usize> {
93    use hypher::hyphenate;
94
95    let mut offsets = Vec::new();
96
97    // Soft hyphens: break after the U+00AD so the hyphen renders at line end.
98    for (idx, ch) in text.char_indices() {
99        if ch == '\u{00AD}' {
100            offsets.push(idx + ch.len_utf8());
101        }
102    }
103
104    // Dictionary hyphenation, word by word — only if the language resolves.
105    if let Some(lang) = hypher::Lang::from_iso(lang_code) {
106        let mut word_start: Option<usize> = None;
107        let flush = |start: usize, end: usize, offsets: &mut Vec<usize>| {
108            let word = &text[start..end];
109            // Skip trivially short words; `hyphenate` would yield no interior
110            // breaks anyway, and this avoids the call overhead.
111            if word.chars().count() < 5 {
112                return;
113            }
114            let mut pos = start;
115            let mut syllables = hyphenate(word, lang).peekable();
116            while let Some(syl) = syllables.next() {
117                pos += syl.len();
118                // A break sits between syllables, not after the last one.
119                if syllables.peek().is_some() {
120                    offsets.push(pos);
121                }
122            }
123        };
124        for (idx, ch) in text.char_indices() {
125            if ch.is_alphabetic() {
126                word_start.get_or_insert(idx);
127            } else if let Some(start) = word_start.take() {
128                flush(start, idx, &mut offsets);
129            }
130        }
131        if let Some(start) = word_start.take() {
132            flush(start, text.len(), &mut offsets);
133        }
134    }
135
136    offsets.sort_unstable();
137    offsets.dedup();
138    offsets
139}
140
141/// Map hyphenation byte offsets to glyph indices (first glyph whose
142/// cluster is `>=` the offset), mirroring [`map_breaks_to_glyph_indices`].
143fn map_offsets_to_glyph_indices(flat: &[FlatGlyph], offsets: &[usize]) -> HashSet<usize> {
144    let mut set = HashSet::new();
145    let mut cursor = 0usize;
146    for &byte_offset in offsets {
147        while cursor < flat.len() && (flat[cursor].cluster as usize) < byte_offset {
148            cursor += 1;
149        }
150        set.insert(cursor.min(flat.len()));
151    }
152    set
153}
154
155/// Append a rendered hyphen glyph to the end of a line that broke at a
156/// hyphenation point, accounting for its advance in the run and line
157/// widths. The hyphen inherits the last glyph's cluster so caret/hit
158/// math treats it as part of the final character.
159fn append_hyphen(line: &mut LayoutLine, hyphen: &ShapedGlyph) {
160    if let Some(run) = line.runs.last_mut() {
161        let mut g = hyphen.clone();
162        g.cluster = run
163            .shaped_run
164            .glyphs
165            .last()
166            .map(|gl| gl.cluster)
167            .unwrap_or(0);
168        run.shaped_run.glyphs.push(g);
169        run.shaped_run.advance_width += hyphen.x_advance;
170        line.width += hyphen.x_advance;
171    }
172}
173
174/// Convert a byte offset within a UTF-8 string to a char offset.
175///
176/// Clamps to `text.len()` and rounds down to the nearest char boundary
177/// if `byte_offset` lands inside a multi-byte character. HarfBuzz can
178/// emit cluster values that don't coincide with UTF-8 char boundaries
179/// (ligature splits, fallback shaping), so callers must never assume
180/// cluster values are well-aligned.
181fn byte_offset_to_char_offset(text: &str, byte_offset: usize) -> usize {
182    let mut off = byte_offset.min(text.len());
183    while off > 0 && !text.is_char_boundary(off) {
184        off -= 1;
185    }
186    text[..off].chars().count()
187}
188
189/// Everything line wrapping needs to hyphenate: the pre-shaped hyphen
190/// glyph to append at a break and the ISO 639-1 language for the
191/// dictionary. Passed as `Some` only when hyphenation is enabled.
192pub struct Hyphenator {
193    /// Hyphen (`-`) glyph in the run's font, appended at hyphenated breaks.
194    pub glyph: ShapedGlyph,
195    /// ISO 639-1 language code for the Knuth-Liang dictionary.
196    pub language: [u8; 2],
197}
198
199/// Text alignment within a line.
200///
201/// `Left`/`Right` are absolute; `Start`/`End` are relative to the
202/// paragraph's base direction and are what an *unset* alignment should
203/// use. Keeping both lets a writer who explicitly chose "flush left" keep
204/// that in an RTL paragraph, while a paragraph nobody has aligned simply
205/// follows its own direction.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
207pub enum Alignment {
208    /// Leading edge: left in an LTR paragraph, right in an RTL one.
209    #[default]
210    Start,
211    /// Trailing edge: right in an LTR paragraph, left in an RTL one.
212    End,
213    Left,
214    Right,
215    Center,
216    Justify,
217}
218
219impl Alignment {
220    /// Resolve the direction-relative variants against a base direction.
221    ///
222    /// Always returns an absolute alignment, so line layout never has to
223    /// think about direction again.
224    pub fn resolve_for(self, base: TextDirection) -> Alignment {
225        let rtl = base == TextDirection::RightToLeft;
226        match self {
227            Alignment::Start if rtl => Alignment::Right,
228            Alignment::Start => Alignment::Left,
229            Alignment::End if rtl => Alignment::Left,
230            Alignment::End => Alignment::Right,
231            absolute => absolute,
232        }
233    }
234}
235
236/// Put a line's runs into visual order per UAX #9 rule L2, then re-lay
237/// their x positions left to right.
238///
239/// Line breaking is a logical operation and runs arrive in logical order,
240/// so this is where a mixed-direction line finally becomes visual. It has
241/// to run per line rather than per paragraph: reordering a paragraph
242/// before breaking it would let a wrap point fall in the middle of an
243/// already-reversed span and scramble every line after it.
244///
245/// The runs keep their glyphs untouched — harfrust already emitted those
246/// in visual order within each run. Only the runs' relative order and
247/// their x origins change.
248fn reorder_line_visually(line: &mut LayoutLine) {
249    if line.runs.len() < 2 {
250        return;
251    }
252    // Cheap scan before any allocation: with nothing right-to-left on
253    // the line there is nothing for rule L2 to reverse, and that is
254    // every line of an ordinary Latin document. Building the level and
255    // permutation vectors first would allocate twice per line on every
256    // relayout just to conclude the same thing.
257    if line.runs.iter().all(|r| r.shaped_run.bidi_level % 2 == 0) {
258        return;
259    }
260
261    let levels: Vec<u8> = line.runs.iter().map(|r| r.shaped_run.bidi_level).collect();
262
263    let order = crate::shaping::shaper::visual_order(&levels);
264    if order.iter().copied().eq(0..order.len()) {
265        return; // already visual — the common all-LTR case
266    }
267
268    // The line's left edge, which `build_line` set to the first-line
269    // indent. Re-laying from here keeps the indent intact.
270    let origin = line.runs.iter().map(|r| r.x).fold(f32::INFINITY, f32::min);
271
272    let mut reordered: Vec<crate::layout::line::PositionedRun> = Vec::with_capacity(order.len());
273    let mut taken: Vec<Option<crate::layout::line::PositionedRun>> =
274        line.runs.drain(..).map(Some).collect();
275    for logical_idx in order {
276        if let Some(run) = taken[logical_idx].take() {
277            reordered.push(run);
278        }
279    }
280
281    let mut x = origin;
282    for run in &mut reordered {
283        run.x = x;
284        x += run.shaped_run.advance_width;
285    }
286    line.runs = reordered;
287}
288
289/// Break shaped runs into lines that fit within `available_width`.
290///
291/// Strategy: shape-first-then-break.
292/// 1. The caller has already shaped the full paragraph into one or more ShapedRuns.
293/// 2. We use unicode-linebreak to find break opportunities in the original text.
294/// 3. We map break positions to glyph boundaries via cluster values.
295/// 4. Greedy line wrapping: accumulate glyph advances, break at the last
296///    allowed opportunity before exceeding the width.
297/// 5. Apply alignment per line.
298#[allow(clippy::too_many_arguments)]
299pub fn break_into_lines(
300    runs: Vec<ShapedRun>,
301    text: &str,
302    available_width: f32,
303    alignment: Alignment,
304    first_line_indent: f32,
305    metrics: &FontMetricsPx,
306    hyphenator: Option<Hyphenator>,
307    run_order: RunOrder,
308) -> Vec<LayoutLine> {
309    // A line with no right edge, in an unbounded width (a single-line field
310    // that scrolls rather than wraps), cannot be aligned against one: Right,
311    // Center and Justify would move its text, or an empty line's caret, to
312    // infinity. It starts at the left; a right-to-left paragraph aligns to
313    // the right by default, so without this its text was never seen.
314    let alignment = if available_width.is_finite() {
315        alignment
316    } else {
317        Alignment::Left
318    };
319    // Where a glyph-less line puts the caret. The alignment pass below only
320    // moves runs, so an empty line must carry this explicitly.
321    let empty_caret_x = {
322        let base = match run_order {
323            RunOrder::Logical(base) => base,
324            RunOrder::AlreadyVisual => TextDirection::LeftToRight,
325        };
326        empty_line_caret_x(alignment, base, first_line_indent, available_width)
327    };
328
329    if runs.is_empty() || text.is_empty() {
330        // Empty paragraph: produce one empty line for the block to have height
331        return vec![make_empty_line(metrics, 0..0, empty_caret_x)];
332    }
333
334    // Flatten all glyphs into a single sequence with their run association, in
335    // logical order when the runs come in logical order (see `flatten_runs`).
336    let flat = flatten_runs(&runs, matches!(run_order, RunOrder::Logical(_)));
337    if flat.is_empty() {
338        return vec![make_empty_line(metrics, 0..0, empty_caret_x)];
339    }
340
341    // Get UAX #14 break opportunities (byte offsets in text), each
342    // classified as Allowed or Mandatory.
343    let breaks: Vec<(usize, BreakOpportunity)> = enumerate_breaks(text);
344
345    // Build sets of allowed and mandatory break positions (glyph indices)
346    let (break_points, mandatory_breaks) = map_breaks_to_glyph_indices(&flat, &breaks);
347
348    // Hyphenation break candidates (glyph indices). A break here needs a
349    // trailing hyphen glyph and must reserve its advance in the fit check.
350    let hyphen_points = if let Some(h) = &hyphenator {
351        map_offsets_to_glyph_indices(&flat, &hyphenation_breaks(text, h.language))
352    } else {
353        HashSet::new()
354    };
355    let hyphen_adv = hyphenator
356        .as_ref()
357        .map(|h| h.glyph.x_advance)
358        .unwrap_or(0.0);
359
360    // Greedy line wrapping
361    let mut lines = Vec::new();
362    // Whether each line ends at a hard break, which justification leaves alone.
363    let mut hard_ends: Vec<bool> = Vec::new();
364    let mut line_start_glyph = 0usize;
365    let mut line_width = 0.0f32;
366    // Last break opportunity within the current line: (glyph index, whether
367    // breaking there renders a hyphen).
368    let mut last_break: Option<(usize, bool)> = None;
369    // First line may be indented; subsequent lines use full width
370    let mut effective_width = available_width - first_line_indent;
371
372    for i in 0..flat.len() {
373        let glyph_advance = flat[i].x_advance;
374        line_width += glyph_advance;
375
376        // Check for mandatory break — O(1) lookup — and where it falls in the text.
377        let mandatory_at = mandatory_breaks.get(&(i + 1)).copied();
378        let is_mandatory = mandatory_at.is_some();
379
380        let exceeds_width = line_width > effective_width && line_start_glyph < i;
381
382        if is_mandatory || exceeds_width {
383            let (break_at, needs_hyphen) = if is_mandatory {
384                (i + 1, false)
385            } else if let Some((bp, hy)) = last_break {
386                if bp > line_start_glyph {
387                    (bp, hy)
388                } else {
389                    (i + 1, false) // emergency break -no opportunity found
390                }
391            } else {
392                (i + 1, false) // emergency break -no break opportunities at all
393            };
394
395            let indent = if lines.is_empty() {
396                first_line_indent
397            } else {
398                0.0
399            };
400            let mut line = build_line(
401                &runs,
402                &flat,
403                line_start_glyph,
404                break_at,
405                metrics,
406                indent,
407                text,
408                if is_mandatory { mandatory_at } else { None },
409            );
410            if needs_hyphen && let Some(h) = &hyphenator {
411                append_hyphen(&mut line, &h.glyph);
412            }
413            lines.push(line);
414            hard_ends.push(is_mandatory);
415
416            line_start_glyph = break_at;
417            // Subsequent lines use full available width
418            effective_width = available_width;
419            // Re-accumulate width for glyphs already scanned past the break
420            line_width = 0.0;
421            for j in break_at..=i {
422                if j < flat.len() {
423                    line_width += flat[j].x_advance;
424                }
425            }
426            last_break = None;
427        }
428
429        // Update the break opportunity AFTER the width check so that a break
430        // discovered at this glyph does not clobber the previous one when the
431        // width is already exceeded. Hyphenation points are checked first so
432        // a soft hyphen (which is also a UAX #14 opportunity) renders its
433        // hyphen; they only count when the hyphen itself still fits.
434        let at = i + 1;
435        if hyphen_points.contains(&at) && line_width + hyphen_adv <= effective_width {
436            last_break = Some((at, true));
437        } else if break_points.contains(&at) {
438            last_break = Some((at, false));
439        }
440    }
441
442    // Remaining glyphs form the last line
443    if line_start_glyph < flat.len() {
444        let line = build_line(
445            &runs,
446            &flat,
447            line_start_glyph,
448            flat.len(),
449            metrics,
450            if lines.is_empty() {
451                first_line_indent
452            } else {
453                0.0
454            },
455            text,
456            None,
457        );
458        lines.push(line);
459        hard_ends.push(false);
460    }
461
462    // A hard break at the very end starts a line of its own, empty, where the
463    // caret goes after Shift+Enter at the end of a paragraph: without it the
464    // caret stayed at the end of the line it had just left, and the paragraph
465    // a line short.
466    if text
467        .chars()
468        .next_back()
469        .is_some_and(crate::types::is_hard_break)
470    {
471        let end = byte_offset_to_char_offset(text, text.len());
472        let base = match run_order {
473            RunOrder::Logical(base) => base,
474            RunOrder::AlreadyVisual => TextDirection::LeftToRight,
475        };
476        let caret_x = empty_line_caret_x(alignment, base, 0.0, available_width);
477        lines.push(make_empty_line(metrics, end..end, caret_x));
478        hard_ends.push(false);
479    }
480
481    // Put each line's runs into visual order before anything reads their
482    // x positions. Alignment shifts every run by the same amount so it
483    // does not care about order, but `justify_line` re-lays runs
484    // sequentially from the vector and would otherwise justify a
485    // mixed-direction line in logical order.
486    let base_direction = match run_order {
487        RunOrder::Logical(base) => {
488            for line in &mut lines {
489                reorder_line_visually(line);
490            }
491            base
492        }
493        // Already visual: reordering here would reverse the caller's work.
494        RunOrder::AlreadyVisual => TextDirection::LeftToRight,
495    };
496
497    // Apply alignment. An unset alignment follows the paragraph's base
498    // direction, so an RTL paragraph right-aligns without the host having
499    // to translate direction into alignment itself.
500    let alignment = alignment.resolve_for(base_direction);
501    let rtl_paragraph = base_direction == TextDirection::RightToLeft;
502    let effective_width = available_width;
503    let last_idx = lines.len().saturating_sub(1);
504    for (i, line) in lines.iter_mut().enumerate() {
505        let indent = if i == 0 { first_line_indent } else { 0.0 };
506        // A first-line indent insets from the paragraph's *leading* edge,
507        // which in an RTL paragraph is the right one. `build_line` always
508        // insets from the left, so undo that here and let the narrowed
509        // `line_avail` below carry the inset over to the right instead.
510        if rtl_paragraph && indent != 0.0 {
511            for run in &mut line.runs {
512                run.x -= indent;
513            }
514        }
515        let line_avail = effective_width - indent;
516        match alignment {
517            // `resolve_for` maps these onto Left/Right, so they cannot
518            // reach here — but fail soft rather than panicking in a
519            // layout pass that runs on every keystroke.
520            Alignment::Start | Alignment::End | Alignment::Left => {
521                // Runs already sit at the indent, except in an RTL
522                // paragraph where the block above moved them to 0 so the
523                // inset could go to the trailing edge. An explicit Left
524                // means the writer wants flush-left text, and the indent
525                // still belongs on the paragraph's leading edge, so put
526                // it back.
527                if rtl_paragraph && indent != 0.0 {
528                    for run in &mut line.runs {
529                        run.x += indent;
530                    }
531                }
532            }
533            Alignment::Right => {
534                let shift = (line_avail - line.width).max(0.0);
535                for run in &mut line.runs {
536                    run.x += shift;
537                }
538            }
539            Alignment::Center => {
540                let shift = ((line_avail - line.width) / 2.0).max(0.0);
541                for run in &mut line.runs {
542                    run.x += shift;
543                }
544            }
545            Alignment::Justify => {
546                // Don't justify the last line, nor one a hard break ends: a
547                // line of verse or of a letter set apart by Shift+Enter keeps
548                // its words where they are, as a browser and Typst set it.
549                if i < last_idx && !hard_ends[i] && line.width > 0.0 {
550                    justify_line(line, line_avail, text);
551                }
552            }
553        }
554    }
555
556    if lines.is_empty() {
557        lines.push(make_empty_line(metrics, 0..0, empty_caret_x));
558    }
559
560    // Convert glyph cluster values from byte offsets to char offsets.
561    // This must happen AFTER alignment because justify_line needs byte
562    // offsets to find space characters in the original text.
563    for line in &mut lines {
564        for run in &mut line.runs {
565            for glyph in &mut run.shaped_run.glyphs {
566                glyph.cluster = byte_offset_to_char_offset(text, glyph.cluster as usize) as u32;
567            }
568        }
569    }
570
571    lines
572}
573
574/// A flattened glyph with enough info to map back to runs.
575struct FlatGlyph {
576    x_advance: f32,
577    cluster: u32,
578    run_index: usize,
579    glyph_index_in_run: usize,
580}
581
582/// The glyphs of `runs` as one sequence, each with its run and its index in it.
583///
584/// With `logical`, the runs arrive in logical order and so does the sequence: a
585/// right-to-left run's glyphs, which shaping stores in visual order (its last
586/// character first), are walked from its end. Line breaking reads the sequence as the
587/// text runs, so walked visually such a run was broken from its logical end: a wrapped
588/// right-to-left paragraph set its last words on its first line, and a break inside
589/// one (a line separator, which stays in the run it sits in) mapped to its first
590/// glyph and was never taken. A line still takes a contiguous slice of each run's
591/// glyphs, since the logical stretch of a run is a contiguous stretch of it visually.
592fn flatten_runs(runs: &[ShapedRun], logical: bool) -> Vec<FlatGlyph> {
593    let mut flat = Vec::new();
594    for (run_idx, run) in runs.iter().enumerate() {
595        // Offset cluster values from fragment-text space to block-text space.
596        // rustybuzz assigns clusters as byte offsets within the fragment text (0-based),
597        // but unicode-linebreak returns byte offsets in the full block text.
598        let cluster_offset = run.text_range.start as u32;
599        let push = |flat: &mut Vec<FlatGlyph>, glyph_idx: usize| {
600            flat.push(FlatGlyph {
601                x_advance: run.glyphs[glyph_idx].x_advance,
602                cluster: run.glyphs[glyph_idx].cluster + cluster_offset,
603                run_index: run_idx,
604                glyph_index_in_run: glyph_idx,
605            });
606        };
607        if logical && run.direction == TextDirection::RightToLeft {
608            for glyph_idx in (0..run.glyphs.len()).rev() {
609                push(&mut flat, glyph_idx);
610            }
611        } else {
612            for glyph_idx in 0..run.glyphs.len() {
613                push(&mut flat, glyph_idx);
614            }
615        }
616    }
617    flat
618}
619
620/// Map unicode-linebreak byte offsets to glyph indices using a merged walk.
621/// Both `flat` (by cluster) and `breaks` (by byte offset) are sorted,
622/// so a single O(b + m) pass replaces the previous O(b × m) approach.
623///
624/// Returns (break_points: HashSet<glyph_idx>, mandatory_breaks: glyph_idx → the byte
625/// offset of the break in the text).
626fn map_breaks_to_glyph_indices(
627    flat: &[FlatGlyph],
628    breaks: &[(usize, BreakOpportunity)],
629) -> (HashSet<usize>, HashMap<usize, usize>) {
630    let mut break_points = HashSet::new();
631    let mut mandatory_breaks = HashMap::new();
632    let mut glyph_cursor = 0usize;
633
634    for &(byte_offset, opportunity) in breaks {
635        // Advance glyph cursor to the first glyph whose cluster >= byte_offset
636        while glyph_cursor < flat.len() && (flat[glyph_cursor].cluster as usize) < byte_offset {
637            glyph_cursor += 1;
638        }
639        let glyph_idx = if glyph_cursor < flat.len() {
640            glyph_cursor
641        } else {
642            flat.len()
643        };
644        break_points.insert(glyph_idx);
645        if opportunity == BreakOpportunity::Mandatory {
646            mandatory_breaks.insert(glyph_idx, byte_offset);
647        }
648    }
649
650    (break_points, mandatory_breaks)
651}
652
653/// Build a LayoutLine from a glyph range within the flat sequence.
654///
655/// `hard_end` is where a hard break the line ends at falls in the text, the byte
656/// after the break: the line's text ends there. Read from the next glyph instead, it
657/// overshot into the next line when that one opens with a right-to-left run, whose
658/// first glyph carries its *last* cluster, and the break was lost.
659#[allow(clippy::too_many_arguments)]
660fn build_line(
661    runs: &[ShapedRun],
662    flat: &[FlatGlyph],
663    start: usize,
664    end: usize,
665    metrics: &FontMetricsPx,
666    indent: f32,
667    text: &str,
668    hard_end: Option<usize>,
669) -> LayoutLine {
670    // Group consecutive glyphs by run_index to reconstruct PositionedRuns. A group is
671    // a contiguous slice of its run's glyphs, walked forwards, or backwards for a
672    // right-to-left run laid out in logical order (see `flatten_runs`), so its slice is
673    // the span of the indices it holds.
674    let mut positioned_runs = Vec::new();
675    let mut x = indent;
676    let mut i = start;
677    while i < end {
678        let run_idx = flat[i].run_index;
679        let (mut lo, mut hi) = (flat[i].glyph_index_in_run, flat[i].glyph_index_in_run);
680        let mut j = i + 1;
681        while j < end && flat[j].run_index == run_idx {
682            lo = lo.min(flat[j].glyph_index_in_run);
683            hi = hi.max(flat[j].glyph_index_in_run);
684            j += 1;
685        }
686        if let Some((pr, advance)) = extract_sub_run(runs, run_idx, lo, hi + 1) {
687            positioned_runs.push(PositionedRun {
688                decorations: RunDecorations {
689                    underline_style: pr.underline_style,
690                    overline: pr.overline,
691                    strikeout: pr.strikeout,
692                    is_link: pr.is_link,
693                    foreground_color: pr.foreground_color,
694                    underline_color: pr.underline_color,
695                    background_color: pr.background_color,
696                    anchor_href: pr.anchor_href.clone(),
697                    tooltip: pr.tooltip.clone(),
698                    vertical_alignment: pr.vertical_alignment,
699                },
700                shaped_run: pr,
701                x,
702            });
703            x += advance;
704        }
705        i = j;
706    }
707
708    let width = x - indent;
709
710    // Compute char range from cluster values.
711    // Clusters from rustybuzz are byte offsets — convert to char offsets
712    // so that positions match text-document's character-based coordinates.
713    //
714    // Glyphs are in *visual* order, so for an RTL run `flat[start]` holds
715    // the largest cluster and `flat[end-1]` the smallest. Take the min/max
716    // over the line's glyphs instead of trusting the array ends, so the
717    // logical range is correct for both directions.
718    let byte_start = flat[start..end.min(flat.len())]
719        .iter()
720        .map(|g| g.cluster as usize)
721        .min()
722        .unwrap_or(0);
723    let byte_end = if let Some(hard_end) = hard_end {
724        hard_end
725    } else if end >= flat.len() {
726        // Last glyph reaches the end of the input text. Always snap to the
727        // full length: a trailing ligature glyph may cover several source
728        // chars, so `max_cluster + 1` would be wrong.
729        text.len()
730    } else {
731        // Next visual glyph's cluster bounds an LTR line exactly; for a
732        // wrapped RTL line take whichever is larger so the logical end
733        // still covers the line's highest cluster.
734        let line_max = flat[start..end]
735            .iter()
736            .map(|g| g.cluster as usize)
737            .max()
738            .unwrap_or(0);
739        (flat[end].cluster as usize).max(line_max)
740    };
741    let char_start = byte_offset_to_char_offset(text, byte_start);
742    let char_end = byte_offset_to_char_offset(text, byte_end);
743    let hard_break_chars = match text
744        .get(byte_start..byte_end)
745        .and_then(crate::types::LineEnd::hard_break_ending)
746    {
747        Some(crate::types::LineEnd::HardBreak { chars, .. }) => chars as usize,
748        _ => 0,
749    };
750
751    // Expand line height for inline images taller than the font ascent
752    let mut ascent = metrics.ascent;
753    for run in &positioned_runs {
754        if run.shaped_run.image_name.is_some() && run.shaped_run.image_height > ascent {
755            ascent = run.shaped_run.image_height;
756        }
757    }
758    let line_height = ascent + metrics.descent + metrics.leading;
759
760    LayoutLine {
761        runs: positioned_runs,
762        y: 0.0, // will be set by the caller (block layout)
763        ascent,
764        descent: metrics.descent,
765        leading: metrics.leading,
766        width,
767        char_range: char_start..char_end,
768        line_height,
769        // Degenerate fallback only: a built line normally derives caret
770        // positions from its runs, but if every run came out glyph-less
771        // the caret still has the line's start to sit at.
772        empty_caret_x: indent,
773        hard_break_chars,
774    }
775}
776
777/// Extract a sub-run (slice of glyphs) from a ShapedRun.
778/// Cluster values are offset to block-text space (adding text_range.start).
779fn extract_sub_run(
780    runs: &[ShapedRun],
781    run_index: usize,
782    glyph_start: usize,
783    glyph_end: usize,
784) -> Option<(ShapedRun, f32)> {
785    let run = &runs[run_index];
786    let end = glyph_end.min(run.glyphs.len());
787    if glyph_start >= end {
788        return None;
789    }
790    let cluster_offset = run.text_range.start as u32;
791    let mut sub_glyphs = run.glyphs[glyph_start..end].to_vec();
792    // Offset cluster values from fragment-local to block-text space
793    for g in &mut sub_glyphs {
794        g.cluster += cluster_offset;
795    }
796    let advance: f32 = sub_glyphs.iter().map(|g| g.x_advance).sum();
797
798    let sub_run = ShapedRun {
799        font_face_id: run.font_face_id,
800        size_px: run.size_px,
801        weight: run.weight,
802        italic: run.italic,
803        glyphs: sub_glyphs,
804        advance_width: advance,
805        text_range: run.text_range.clone(),
806        direction: run.direction,
807        bidi_level: run.bidi_level,
808        underline_style: run.underline_style,
809        overline: run.overline,
810        strikeout: run.strikeout,
811        is_link: run.is_link,
812        foreground_color: run.foreground_color,
813        underline_color: run.underline_color,
814        background_color: run.background_color,
815        anchor_href: run.anchor_href.clone(),
816        tooltip: run.tooltip.clone(),
817        vertical_alignment: run.vertical_alignment,
818        image_name: run.image_name.clone(),
819        image_height: run.image_height,
820    };
821    Some((sub_run, advance))
822}
823
824fn make_empty_line(
825    metrics: &FontMetricsPx,
826    char_range: Range<usize>,
827    empty_caret_x: f32,
828) -> LayoutLine {
829    LayoutLine {
830        runs: Vec::new(),
831        y: 0.0,
832        ascent: metrics.ascent,
833        descent: metrics.descent,
834        leading: metrics.leading,
835        width: 0.0,
836        char_range,
837        line_height: metrics.ascent + metrics.descent + metrics.leading,
838        empty_caret_x,
839        hard_break_chars: 0,
840    }
841}
842
843/// The x where the caret sits on a line with no glyphs — i.e. where the
844/// first typed character's glyph would land. Mirrors the run-shifting
845/// arithmetic of `break_into_lines`' alignment pass with a line width of
846/// zero, so an empty paragraph's caret cannot disagree with where the
847/// first keystroke lays text out (the "caret jumps on the first
848/// character" bug).
849fn empty_line_caret_x(
850    alignment: Alignment,
851    base_direction: TextDirection,
852    first_line_indent: f32,
853    available_width: f32,
854) -> f32 {
855    let rtl = base_direction == TextDirection::RightToLeft;
856    let indent = first_line_indent;
857    let line_avail = (available_width - indent).max(0.0);
858    match alignment.resolve_for(base_direction) {
859        // In an RTL paragraph the alignment pass first moves runs to the
860        // left edge so the indent insets from the *right*; Right then
861        // shifts by the remaining width. Width zero leaves the caret at
862        // `line_avail` (RTL) or the full width (LTR).
863        Alignment::Right => {
864            if rtl {
865                line_avail
866            } else {
867                available_width
868            }
869        }
870        Alignment::Center => {
871            let shift = line_avail / 2.0;
872            if rtl { shift } else { indent + shift }
873        }
874        // Justify never justifies the last line, and a lone line is the
875        // last line, so runs keep their unshifted positions: the indent
876        // for LTR; the left edge for RTL, where the alignment pass moved
877        // them and Justify does not put the indent back.
878        Alignment::Justify => {
879            if rtl {
880                0.0
881            } else {
882                indent
883            }
884        }
885        // `resolve_for` maps Start/End onto Left/Right, so what remains is
886        // Left — which keeps runs at the indent in both directions.
887        _ => indent,
888    }
889}
890
891/// Distribute extra space among word gaps for justification.
892///
893/// Finds space glyphs (cluster mapping to ' ') across all runs and
894/// increases their x_advance proportionally. Then recomputes run x positions.
895fn justify_line(line: &mut LayoutLine, target_width: f32, text: &str) {
896    let extra = target_width - line.width;
897    if extra <= 0.0 {
898        return;
899    }
900
901    // Count space glyphs across all runs
902    let mut space_count = 0usize;
903    for run in &line.runs {
904        for glyph in &run.shaped_run.glyphs {
905            let byte_offset = glyph.cluster as usize;
906            if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
907                && ch == ' '
908            {
909                space_count += 1;
910            }
911        }
912    }
913
914    if space_count == 0 {
915        return;
916    }
917
918    let extra_per_space = extra / space_count as f32;
919
920    // Increase x_advance of space glyphs
921    for run in &mut line.runs {
922        for glyph in &mut run.shaped_run.glyphs {
923            let byte_offset = glyph.cluster as usize;
924            if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
925                && ch == ' '
926            {
927                glyph.x_advance += extra_per_space;
928            }
929        }
930        // Recompute run advance width
931        run.shaped_run.advance_width = run.shaped_run.glyphs.iter().map(|g| g.x_advance).sum();
932    }
933
934    // Recompute run x positions (runs follow each other)
935    let first_x = line.runs.first().map(|r| r.x).unwrap_or(0.0);
936    let mut x = first_x;
937    for run in &mut line.runs {
938        run.x = x;
939        x += run.shaped_run.advance_width;
940    }
941
942    line.width = target_width;
943}