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 // An emergency break goes before the glyph that overflowed, at the last
383 // cluster boundary after the line's start: the line keeps at least one
384 // cluster and a cluster wider than the line is never split. With no such
385 // boundary the line goes on, and a later glyph asks again.
386 let decision = if is_mandatory {
387 Some((i + 1, false))
388 } else if exceeds_width {
389 match last_break {
390 Some((bp, hy)) if bp > line_start_glyph => Some((bp, hy)),
391 _ => (line_start_glyph + 1..=i)
392 .rev()
393 .find(|&k| flat[k].cluster != flat[k - 1].cluster)
394 .map(|k| (k, false)),
395 }
396 } else {
397 None
398 };
399
400 if let Some((break_at, needs_hyphen)) = decision {
401 let indent = if lines.is_empty() {
402 first_line_indent
403 } else {
404 0.0
405 };
406 let mut line = build_line(
407 &runs,
408 &flat,
409 line_start_glyph,
410 break_at,
411 metrics,
412 indent,
413 text,
414 if is_mandatory { mandatory_at } else { None },
415 );
416 if needs_hyphen && let Some(h) = &hyphenator {
417 append_hyphen(&mut line, &h.glyph);
418 }
419 lines.push(line);
420 hard_ends.push(is_mandatory);
421
422 line_start_glyph = break_at;
423 // Subsequent lines use full available width
424 effective_width = available_width;
425 // Re-accumulate width for glyphs already scanned past the break
426 line_width = 0.0;
427 for j in break_at..=i {
428 if j < flat.len() {
429 line_width += flat[j].x_advance;
430 }
431 }
432 last_break = None;
433 }
434
435 // Update the break opportunity AFTER the width check so that a break
436 // discovered at this glyph does not clobber the previous one when the
437 // width is already exceeded. Hyphenation points are checked first so
438 // a soft hyphen (which is also a UAX #14 opportunity) renders its
439 // hyphen; they only count when the hyphen itself still fits.
440 let at = i + 1;
441 if hyphen_points.contains(&at) && line_width + hyphen_adv <= effective_width {
442 last_break = Some((at, true));
443 } else if break_points.contains(&at) {
444 last_break = Some((at, false));
445 }
446 }
447
448 // Remaining glyphs form the last line
449 if line_start_glyph < flat.len() {
450 let line = build_line(
451 &runs,
452 &flat,
453 line_start_glyph,
454 flat.len(),
455 metrics,
456 if lines.is_empty() {
457 first_line_indent
458 } else {
459 0.0
460 },
461 text,
462 None,
463 );
464 lines.push(line);
465 hard_ends.push(false);
466 }
467
468 // A hard break at the very end starts a line of its own, empty, where the
469 // caret goes after Shift+Enter at the end of a paragraph: without it the
470 // caret stayed at the end of the line it had just left, and the paragraph
471 // a line short.
472 if text
473 .chars()
474 .next_back()
475 .is_some_and(crate::types::is_hard_break)
476 {
477 let end = byte_offset_to_char_offset(text, text.len());
478 let base = match run_order {
479 RunOrder::Logical(base) => base,
480 RunOrder::AlreadyVisual => TextDirection::LeftToRight,
481 };
482 let caret_x = empty_line_caret_x(alignment, base, 0.0, available_width);
483 lines.push(make_empty_line(metrics, end..end, caret_x));
484 hard_ends.push(false);
485 }
486
487 // Put each line's runs into visual order before anything reads their
488 // x positions. Alignment shifts every run by the same amount so it
489 // does not care about order, but `justify_line` re-lays runs
490 // sequentially from the vector and would otherwise justify a
491 // mixed-direction line in logical order.
492 let base_direction = match run_order {
493 RunOrder::Logical(base) => {
494 for line in &mut lines {
495 reorder_line_visually(line);
496 }
497 base
498 }
499 // Already visual: reordering here would reverse the caller's work.
500 RunOrder::AlreadyVisual => TextDirection::LeftToRight,
501 };
502
503 // Apply alignment. An unset alignment follows the paragraph's base
504 // direction, so an RTL paragraph right-aligns without the host having
505 // to translate direction into alignment itself.
506 let alignment = alignment.resolve_for(base_direction);
507 let rtl_paragraph = base_direction == TextDirection::RightToLeft;
508 let effective_width = available_width;
509 let last_idx = lines.len().saturating_sub(1);
510 for (i, line) in lines.iter_mut().enumerate() {
511 let indent = if i == 0 { first_line_indent } else { 0.0 };
512 // A first-line indent insets from the paragraph's *leading* edge,
513 // which in an RTL paragraph is the right one. `build_line` always
514 // insets from the left, so undo that here and let the narrowed
515 // `line_avail` below carry the inset over to the right instead.
516 if rtl_paragraph && indent != 0.0 {
517 for run in &mut line.runs {
518 run.x -= indent;
519 }
520 }
521 let line_avail = effective_width - indent;
522 match alignment {
523 // `resolve_for` maps these onto Left/Right, so they cannot
524 // reach here — but fail soft rather than panicking in a
525 // layout pass that runs on every keystroke.
526 Alignment::Start | Alignment::End | Alignment::Left => {
527 // Runs already sit at the indent, except in an RTL
528 // paragraph where the block above moved them to 0 so the
529 // inset could go to the trailing edge. An explicit Left
530 // means the writer wants flush-left text, and the indent
531 // still belongs on the paragraph's leading edge, so put
532 // it back.
533 if rtl_paragraph && indent != 0.0 {
534 for run in &mut line.runs {
535 run.x += indent;
536 }
537 }
538 }
539 Alignment::Right => {
540 let shift = (line_avail - line.width).max(0.0);
541 for run in &mut line.runs {
542 run.x += shift;
543 }
544 }
545 Alignment::Center => {
546 let shift = ((line_avail - line.width) / 2.0).max(0.0);
547 for run in &mut line.runs {
548 run.x += shift;
549 }
550 }
551 Alignment::Justify => {
552 // Don't justify the last line, nor one a hard break ends: a
553 // line of verse or of a letter set apart by Shift+Enter keeps
554 // its words where they are, as a browser and Typst set it.
555 if i < last_idx && !hard_ends[i] && line.width > 0.0 {
556 justify_line(line, line_avail, text);
557 }
558 }
559 }
560 }
561
562 if lines.is_empty() {
563 lines.push(make_empty_line(metrics, 0..0, empty_caret_x));
564 }
565
566 // Convert glyph cluster values from byte offsets to char offsets.
567 // This must happen AFTER alignment because justify_line needs byte
568 // offsets to find space characters in the original text.
569 for line in &mut lines {
570 for run in &mut line.runs {
571 for glyph in &mut run.shaped_run.glyphs {
572 glyph.cluster = byte_offset_to_char_offset(text, glyph.cluster as usize) as u32;
573 }
574 }
575 }
576
577 lines
578}
579
580/// A flattened glyph with enough info to map back to runs.
581struct FlatGlyph {
582 x_advance: f32,
583 cluster: u32,
584 run_index: usize,
585 glyph_index_in_run: usize,
586}
587
588/// The glyphs of `runs` as one sequence, each with its run and its index in it.
589///
590/// With `logical`, the runs arrive in logical order and so does the sequence: a
591/// right-to-left run's glyphs, which shaping stores in visual order (its last
592/// character first), are walked from its end. Line breaking reads the sequence as the
593/// text runs, so walked visually such a run was broken from its logical end: a wrapped
594/// right-to-left paragraph set its last words on its first line, and a break inside
595/// one (a line separator, which stays in the run it sits in) mapped to its first
596/// glyph and was never taken. A line still takes a contiguous slice of each run's
597/// glyphs, since the logical stretch of a run is a contiguous stretch of it visually.
598fn flatten_runs(runs: &[ShapedRun], logical: bool) -> Vec<FlatGlyph> {
599 let mut flat = Vec::new();
600 for (run_idx, run) in runs.iter().enumerate() {
601 // Offset cluster values from fragment-text space to block-text space.
602 // rustybuzz assigns clusters as byte offsets within the fragment text (0-based),
603 // but unicode-linebreak returns byte offsets in the full block text.
604 let cluster_offset = run.text_range.start as u32;
605 let push = |flat: &mut Vec<FlatGlyph>, glyph_idx: usize| {
606 flat.push(FlatGlyph {
607 x_advance: run.glyphs[glyph_idx].x_advance,
608 cluster: run.glyphs[glyph_idx].cluster + cluster_offset,
609 run_index: run_idx,
610 glyph_index_in_run: glyph_idx,
611 });
612 };
613 if logical && run.direction == TextDirection::RightToLeft {
614 for glyph_idx in (0..run.glyphs.len()).rev() {
615 push(&mut flat, glyph_idx);
616 }
617 } else {
618 for glyph_idx in 0..run.glyphs.len() {
619 push(&mut flat, glyph_idx);
620 }
621 }
622 }
623 flat
624}
625
626/// Map unicode-linebreak byte offsets to glyph indices using a merged walk.
627/// Both `flat` (by cluster) and `breaks` (by byte offset) are sorted,
628/// so a single O(b + m) pass replaces the previous O(b × m) approach.
629///
630/// Returns (break_points: HashSet<glyph_idx>, mandatory_breaks: glyph_idx → the byte
631/// offset of the break in the text).
632fn map_breaks_to_glyph_indices(
633 flat: &[FlatGlyph],
634 breaks: &[(usize, BreakOpportunity)],
635) -> (HashSet<usize>, HashMap<usize, usize>) {
636 let mut break_points = HashSet::new();
637 let mut mandatory_breaks = HashMap::new();
638 let mut glyph_cursor = 0usize;
639
640 for &(byte_offset, opportunity) in breaks {
641 // Advance glyph cursor to the first glyph whose cluster >= byte_offset
642 while glyph_cursor < flat.len() && (flat[glyph_cursor].cluster as usize) < byte_offset {
643 glyph_cursor += 1;
644 }
645 let glyph_idx = if glyph_cursor < flat.len() {
646 glyph_cursor
647 } else {
648 flat.len()
649 };
650 break_points.insert(glyph_idx);
651 if opportunity == BreakOpportunity::Mandatory {
652 mandatory_breaks.insert(glyph_idx, byte_offset);
653 }
654 }
655
656 (break_points, mandatory_breaks)
657}
658
659/// Build a LayoutLine from a glyph range within the flat sequence.
660///
661/// `hard_end` is where a hard break the line ends at falls in the text, the byte
662/// after the break: the line's text ends there. Read from the next glyph instead, it
663/// overshot into the next line when that one opens with a right-to-left run, whose
664/// first glyph carries its *last* cluster, and the break was lost.
665#[allow(clippy::too_many_arguments)]
666fn build_line(
667 runs: &[ShapedRun],
668 flat: &[FlatGlyph],
669 start: usize,
670 end: usize,
671 metrics: &FontMetricsPx,
672 indent: f32,
673 text: &str,
674 hard_end: Option<usize>,
675) -> LayoutLine {
676 // Group consecutive glyphs by run_index to reconstruct PositionedRuns. A group is
677 // a contiguous slice of its run's glyphs, walked forwards, or backwards for a
678 // right-to-left run laid out in logical order (see `flatten_runs`), so its slice is
679 // the span of the indices it holds.
680 let mut positioned_runs = Vec::new();
681 let mut x = indent;
682 let mut i = start;
683 while i < end {
684 let run_idx = flat[i].run_index;
685 let (mut lo, mut hi) = (flat[i].glyph_index_in_run, flat[i].glyph_index_in_run);
686 let mut j = i + 1;
687 while j < end && flat[j].run_index == run_idx {
688 lo = lo.min(flat[j].glyph_index_in_run);
689 hi = hi.max(flat[j].glyph_index_in_run);
690 j += 1;
691 }
692 if let Some((pr, advance)) = extract_sub_run(runs, run_idx, lo, hi + 1) {
693 positioned_runs.push(PositionedRun {
694 decorations: RunDecorations {
695 underline_style: pr.underline_style,
696 overline: pr.overline,
697 strikeout: pr.strikeout,
698 is_link: pr.is_link,
699 foreground_color: pr.foreground_color,
700 underline_color: pr.underline_color,
701 background_color: pr.background_color,
702 anchor_href: pr.anchor_href.clone(),
703 tooltip: pr.tooltip.clone(),
704 vertical_alignment: pr.vertical_alignment,
705 },
706 shaped_run: pr,
707 x,
708 });
709 x += advance;
710 }
711 i = j;
712 }
713
714 let width = x - indent;
715
716 // Compute char range from cluster values.
717 // Clusters from rustybuzz are byte offsets — convert to char offsets
718 // so that positions match text-document's character-based coordinates.
719 //
720 // Glyphs are in *visual* order, so for an RTL run `flat[start]` holds
721 // the largest cluster and `flat[end-1]` the smallest. Take the min/max
722 // over the line's glyphs instead of trusting the array ends, so the
723 // logical range is correct for both directions.
724 let byte_start = flat[start..end.min(flat.len())]
725 .iter()
726 .map(|g| g.cluster as usize)
727 .min()
728 .unwrap_or(0);
729 let byte_end = if let Some(hard_end) = hard_end {
730 hard_end
731 } else if end >= flat.len() {
732 // Last glyph reaches the end of the input text. Always snap to the
733 // full length: a trailing ligature glyph may cover several source
734 // chars, so `max_cluster + 1` would be wrong.
735 text.len()
736 } else {
737 // Next visual glyph's cluster bounds an LTR line exactly; for a
738 // wrapped RTL line take whichever is larger so the logical end
739 // still covers the line's highest cluster.
740 let line_max = flat[start..end]
741 .iter()
742 .map(|g| g.cluster as usize)
743 .max()
744 .unwrap_or(0);
745 (flat[end].cluster as usize).max(line_max)
746 };
747 let char_start = byte_offset_to_char_offset(text, byte_start);
748 let char_end = byte_offset_to_char_offset(text, byte_end);
749 let hard_break_chars = match text
750 .get(byte_start..byte_end)
751 .and_then(crate::types::LineEnd::hard_break_ending)
752 {
753 Some(crate::types::LineEnd::HardBreak { chars, .. }) => chars as usize,
754 _ => 0,
755 };
756
757 // Expand line height for inline images taller than the font ascent
758 let mut ascent = metrics.ascent;
759 for run in &positioned_runs {
760 if run.shaped_run.image_name.is_some() && run.shaped_run.image_height > ascent {
761 ascent = run.shaped_run.image_height;
762 }
763 }
764 let line_height = ascent + metrics.descent + metrics.leading;
765
766 LayoutLine {
767 runs: positioned_runs,
768 y: 0.0, // will be set by the caller (block layout)
769 ascent,
770 descent: metrics.descent,
771 leading: metrics.leading,
772 width,
773 char_range: char_start..char_end,
774 line_height,
775 // Degenerate fallback only: a built line normally derives caret
776 // positions from its runs, but if every run came out glyph-less
777 // the caret still has the line's start to sit at.
778 empty_caret_x: indent,
779 hard_break_chars,
780 }
781}
782
783/// Extract a sub-run (slice of glyphs) from a ShapedRun.
784/// Cluster values are offset to block-text space (adding text_range.start).
785fn extract_sub_run(
786 runs: &[ShapedRun],
787 run_index: usize,
788 glyph_start: usize,
789 glyph_end: usize,
790) -> Option<(ShapedRun, f32)> {
791 let run = &runs[run_index];
792 let end = glyph_end.min(run.glyphs.len());
793 if glyph_start >= end {
794 return None;
795 }
796 let cluster_offset = run.text_range.start as u32;
797 let mut sub_glyphs = run.glyphs[glyph_start..end].to_vec();
798 // Offset cluster values from fragment-local to block-text space
799 for g in &mut sub_glyphs {
800 g.cluster += cluster_offset;
801 }
802 let advance: f32 = sub_glyphs.iter().map(|g| g.x_advance).sum();
803
804 let sub_run = ShapedRun {
805 font_face_id: run.font_face_id,
806 size_px: run.size_px,
807 weight: run.weight,
808 italic: run.italic,
809 glyphs: sub_glyphs,
810 advance_width: advance,
811 text_range: run.text_range.clone(),
812 direction: run.direction,
813 bidi_level: run.bidi_level,
814 underline_style: run.underline_style,
815 overline: run.overline,
816 strikeout: run.strikeout,
817 is_link: run.is_link,
818 foreground_color: run.foreground_color,
819 underline_color: run.underline_color,
820 background_color: run.background_color,
821 anchor_href: run.anchor_href.clone(),
822 tooltip: run.tooltip.clone(),
823 vertical_alignment: run.vertical_alignment,
824 image_name: run.image_name.clone(),
825 image_height: run.image_height,
826 };
827 Some((sub_run, advance))
828}
829
830fn make_empty_line(
831 metrics: &FontMetricsPx,
832 char_range: Range<usize>,
833 empty_caret_x: f32,
834) -> LayoutLine {
835 LayoutLine {
836 runs: Vec::new(),
837 y: 0.0,
838 ascent: metrics.ascent,
839 descent: metrics.descent,
840 leading: metrics.leading,
841 width: 0.0,
842 char_range,
843 line_height: metrics.ascent + metrics.descent + metrics.leading,
844 empty_caret_x,
845 hard_break_chars: 0,
846 }
847}
848
849/// The x where the caret sits on a line with no glyphs — i.e. where the
850/// first typed character's glyph would land. Mirrors the run-shifting
851/// arithmetic of `break_into_lines`' alignment pass with a line width of
852/// zero, so an empty paragraph's caret cannot disagree with where the
853/// first keystroke lays text out (the "caret jumps on the first
854/// character" bug).
855fn empty_line_caret_x(
856 alignment: Alignment,
857 base_direction: TextDirection,
858 first_line_indent: f32,
859 available_width: f32,
860) -> f32 {
861 let rtl = base_direction == TextDirection::RightToLeft;
862 let indent = first_line_indent;
863 let line_avail = (available_width - indent).max(0.0);
864 match alignment.resolve_for(base_direction) {
865 // In an RTL paragraph the alignment pass first moves runs to the
866 // left edge so the indent insets from the *right*; Right then
867 // shifts by the remaining width. Width zero leaves the caret at
868 // `line_avail` (RTL) or the full width (LTR).
869 Alignment::Right => {
870 if rtl {
871 line_avail
872 } else {
873 available_width
874 }
875 }
876 Alignment::Center => {
877 let shift = line_avail / 2.0;
878 if rtl { shift } else { indent + shift }
879 }
880 // Justify never justifies the last line, and a lone line is the
881 // last line, so runs keep their unshifted positions: the indent
882 // for LTR; the left edge for RTL, where the alignment pass moved
883 // them and Justify does not put the indent back.
884 Alignment::Justify => {
885 if rtl {
886 0.0
887 } else {
888 indent
889 }
890 }
891 // `resolve_for` maps Start/End onto Left/Right, so what remains is
892 // Left — which keeps runs at the indent in both directions.
893 _ => indent,
894 }
895}
896
897/// Distribute extra space among word gaps for justification.
898///
899/// Finds space glyphs (cluster mapping to ' ') across all runs and
900/// increases their x_advance proportionally. Then recomputes run x positions.
901fn justify_line(line: &mut LayoutLine, target_width: f32, text: &str) {
902 let extra = target_width - line.width;
903 if extra <= 0.0 {
904 return;
905 }
906
907 // Count space glyphs across all runs
908 let mut space_count = 0usize;
909 for run in &line.runs {
910 for glyph in &run.shaped_run.glyphs {
911 let byte_offset = glyph.cluster as usize;
912 if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
913 && ch == ' '
914 {
915 space_count += 1;
916 }
917 }
918 }
919
920 if space_count == 0 {
921 return;
922 }
923
924 let extra_per_space = extra / space_count as f32;
925
926 // Increase x_advance of space glyphs
927 for run in &mut line.runs {
928 for glyph in &mut run.shaped_run.glyphs {
929 let byte_offset = glyph.cluster as usize;
930 if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
931 && ch == ' '
932 {
933 glyph.x_advance += extra_per_space;
934 }
935 }
936 // Recompute run advance width
937 run.shaped_run.advance_width = run.shaped_run.glyphs.iter().map(|g| g.x_advance).sum();
938 }
939
940 // Recompute run x positions (runs follow each other)
941 let first_x = line.runs.first().map(|r| r.x).unwrap_or(0.0);
942 let mut x = first_x;
943 for run in &mut line.runs {
944 run.x = x;
945 x += run.shaped_run.advance_width;
946 }
947
948 line.width = target_width;
949}