text_typeset/layout/paragraph.rs
1use std::collections::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 matches!(
60 preceding.chars().next_back(),
61 Some('\n' | '\r' | '\u{0085}' | '\u{000B}' | '\u{000C}' | '\u{2028}' | '\u{2029}')
62 )
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 // Where a glyph-less line puts the caret. The alignment pass below only
310 // moves runs, so an empty line must carry this explicitly.
311 let empty_caret_x = {
312 let base = match run_order {
313 RunOrder::Logical(base) => base,
314 RunOrder::AlreadyVisual => TextDirection::LeftToRight,
315 };
316 empty_line_caret_x(alignment, base, first_line_indent, available_width)
317 };
318
319 if runs.is_empty() || text.is_empty() {
320 // Empty paragraph: produce one empty line for the block to have height
321 return vec![make_empty_line(metrics, 0..0, empty_caret_x)];
322 }
323
324 // Flatten all glyphs into a single sequence with their run association
325 let flat = flatten_runs(&runs);
326 if flat.is_empty() {
327 return vec![make_empty_line(metrics, 0..0, empty_caret_x)];
328 }
329
330 // Get UAX #14 break opportunities (byte offsets in text), each
331 // classified as Allowed or Mandatory.
332 let breaks: Vec<(usize, BreakOpportunity)> = enumerate_breaks(text);
333
334 // Build sets of allowed and mandatory break positions (glyph indices)
335 let (break_points, mandatory_breaks) = map_breaks_to_glyph_indices(&flat, &breaks);
336
337 // Hyphenation break candidates (glyph indices). A break here needs a
338 // trailing hyphen glyph and must reserve its advance in the fit check.
339 let hyphen_points = if let Some(h) = &hyphenator {
340 map_offsets_to_glyph_indices(&flat, &hyphenation_breaks(text, h.language))
341 } else {
342 HashSet::new()
343 };
344 let hyphen_adv = hyphenator
345 .as_ref()
346 .map(|h| h.glyph.x_advance)
347 .unwrap_or(0.0);
348
349 // Greedy line wrapping
350 let mut lines = Vec::new();
351 let mut line_start_glyph = 0usize;
352 let mut line_width = 0.0f32;
353 // Last break opportunity within the current line: (glyph index, whether
354 // breaking there renders a hyphen).
355 let mut last_break: Option<(usize, bool)> = None;
356 // First line may be indented; subsequent lines use full width
357 let mut effective_width = available_width - first_line_indent;
358
359 for i in 0..flat.len() {
360 let glyph_advance = flat[i].x_advance;
361 line_width += glyph_advance;
362
363 // Check for mandatory break — O(1) HashSet lookup
364 let is_mandatory = mandatory_breaks.contains(&(i + 1));
365
366 let exceeds_width = line_width > effective_width && line_start_glyph < i;
367
368 if is_mandatory || exceeds_width {
369 let (break_at, needs_hyphen) = if is_mandatory {
370 (i + 1, false)
371 } else if let Some((bp, hy)) = last_break {
372 if bp > line_start_glyph {
373 (bp, hy)
374 } else {
375 (i + 1, false) // emergency break -no opportunity found
376 }
377 } else {
378 (i + 1, false) // emergency break -no break opportunities at all
379 };
380
381 let indent = if lines.is_empty() {
382 first_line_indent
383 } else {
384 0.0
385 };
386 let mut line = build_line(
387 &runs,
388 &flat,
389 line_start_glyph,
390 break_at,
391 metrics,
392 indent,
393 text,
394 );
395 if needs_hyphen && let Some(h) = &hyphenator {
396 append_hyphen(&mut line, &h.glyph);
397 }
398 lines.push(line);
399
400 line_start_glyph = break_at;
401 // Subsequent lines use full available width
402 effective_width = available_width;
403 // Re-accumulate width for glyphs already scanned past the break
404 line_width = 0.0;
405 for j in break_at..=i {
406 if j < flat.len() {
407 line_width += flat[j].x_advance;
408 }
409 }
410 last_break = None;
411 }
412
413 // Update the break opportunity AFTER the width check so that a break
414 // discovered at this glyph does not clobber the previous one when the
415 // width is already exceeded. Hyphenation points are checked first so
416 // a soft hyphen (which is also a UAX #14 opportunity) renders its
417 // hyphen; they only count when the hyphen itself still fits.
418 let at = i + 1;
419 if hyphen_points.contains(&at) && line_width + hyphen_adv <= effective_width {
420 last_break = Some((at, true));
421 } else if break_points.contains(&at) {
422 last_break = Some((at, false));
423 }
424 }
425
426 // Remaining glyphs form the last line
427 if line_start_glyph < flat.len() {
428 let line = build_line(
429 &runs,
430 &flat,
431 line_start_glyph,
432 flat.len(),
433 metrics,
434 if lines.is_empty() {
435 first_line_indent
436 } else {
437 0.0
438 },
439 text,
440 );
441 lines.push(line);
442 }
443
444 // Put each line's runs into visual order before anything reads their
445 // x positions. Alignment shifts every run by the same amount so it
446 // does not care about order, but `justify_line` re-lays runs
447 // sequentially from the vector and would otherwise justify a
448 // mixed-direction line in logical order.
449 let base_direction = match run_order {
450 RunOrder::Logical(base) => {
451 for line in &mut lines {
452 reorder_line_visually(line);
453 }
454 base
455 }
456 // Already visual: reordering here would reverse the caller's work.
457 RunOrder::AlreadyVisual => TextDirection::LeftToRight,
458 };
459
460 // Apply alignment. An unset alignment follows the paragraph's base
461 // direction, so an RTL paragraph right-aligns without the host having
462 // to translate direction into alignment itself.
463 let alignment = alignment.resolve_for(base_direction);
464 let rtl_paragraph = base_direction == TextDirection::RightToLeft;
465 let effective_width = available_width;
466 let last_idx = lines.len().saturating_sub(1);
467 for (i, line) in lines.iter_mut().enumerate() {
468 let indent = if i == 0 { first_line_indent } else { 0.0 };
469 // A first-line indent insets from the paragraph's *leading* edge,
470 // which in an RTL paragraph is the right one. `build_line` always
471 // insets from the left, so undo that here and let the narrowed
472 // `line_avail` below carry the inset over to the right instead.
473 if rtl_paragraph && indent != 0.0 {
474 for run in &mut line.runs {
475 run.x -= indent;
476 }
477 }
478 let line_avail = effective_width - indent;
479 match alignment {
480 // `resolve_for` maps these onto Left/Right, so they cannot
481 // reach here — but fail soft rather than panicking in a
482 // layout pass that runs on every keystroke.
483 Alignment::Start | Alignment::End | Alignment::Left => {
484 // Runs already sit at the indent, except in an RTL
485 // paragraph where the block above moved them to 0 so the
486 // inset could go to the trailing edge. An explicit Left
487 // means the writer wants flush-left text, and the indent
488 // still belongs on the paragraph's leading edge, so put
489 // it back.
490 if rtl_paragraph && indent != 0.0 {
491 for run in &mut line.runs {
492 run.x += indent;
493 }
494 }
495 }
496 Alignment::Right => {
497 let shift = (line_avail - line.width).max(0.0);
498 for run in &mut line.runs {
499 run.x += shift;
500 }
501 }
502 Alignment::Center => {
503 let shift = ((line_avail - line.width) / 2.0).max(0.0);
504 for run in &mut line.runs {
505 run.x += shift;
506 }
507 }
508 Alignment::Justify => {
509 // Don't justify the last line
510 if i < last_idx && line.width > 0.0 {
511 justify_line(line, line_avail, text);
512 }
513 }
514 }
515 }
516
517 if lines.is_empty() {
518 lines.push(make_empty_line(metrics, 0..0, empty_caret_x));
519 }
520
521 // Convert glyph cluster values from byte offsets to char offsets.
522 // This must happen AFTER alignment because justify_line needs byte
523 // offsets to find space characters in the original text.
524 for line in &mut lines {
525 for run in &mut line.runs {
526 for glyph in &mut run.shaped_run.glyphs {
527 glyph.cluster = byte_offset_to_char_offset(text, glyph.cluster as usize) as u32;
528 }
529 }
530 }
531
532 lines
533}
534
535/// A flattened glyph with enough info to map back to runs.
536struct FlatGlyph {
537 x_advance: f32,
538 cluster: u32,
539 run_index: usize,
540 glyph_index_in_run: usize,
541}
542
543fn flatten_runs(runs: &[ShapedRun]) -> Vec<FlatGlyph> {
544 let mut flat = Vec::new();
545 for (run_idx, run) in runs.iter().enumerate() {
546 // Offset cluster values from fragment-text space to block-text space.
547 // rustybuzz assigns clusters as byte offsets within the fragment text (0-based),
548 // but unicode-linebreak returns byte offsets in the full block text.
549 let cluster_offset = run.text_range.start as u32;
550 for (glyph_idx, glyph) in run.glyphs.iter().enumerate() {
551 flat.push(FlatGlyph {
552 x_advance: glyph.x_advance,
553 cluster: glyph.cluster + cluster_offset,
554 run_index: run_idx,
555 glyph_index_in_run: glyph_idx,
556 });
557 }
558 }
559 flat
560}
561
562/// Map unicode-linebreak byte offsets to glyph indices using a merged walk.
563/// Both `flat` (by cluster) and `breaks` (by byte offset) are sorted,
564/// so a single O(b + m) pass replaces the previous O(b × m) approach.
565///
566/// Returns (break_points: HashSet<glyph_idx>, mandatory_breaks: HashSet<glyph_idx>).
567fn map_breaks_to_glyph_indices(
568 flat: &[FlatGlyph],
569 breaks: &[(usize, BreakOpportunity)],
570) -> (HashSet<usize>, HashSet<usize>) {
571 let mut break_points = HashSet::new();
572 let mut mandatory_breaks = HashSet::new();
573 let mut glyph_cursor = 0usize;
574
575 for &(byte_offset, opportunity) in breaks {
576 // Advance glyph cursor to the first glyph whose cluster >= byte_offset
577 while glyph_cursor < flat.len() && (flat[glyph_cursor].cluster as usize) < byte_offset {
578 glyph_cursor += 1;
579 }
580 let glyph_idx = if glyph_cursor < flat.len() {
581 glyph_cursor
582 } else {
583 flat.len()
584 };
585 break_points.insert(glyph_idx);
586 if opportunity == BreakOpportunity::Mandatory {
587 mandatory_breaks.insert(glyph_idx);
588 }
589 }
590
591 (break_points, mandatory_breaks)
592}
593
594/// Build a LayoutLine from a glyph range within the flat sequence.
595fn build_line(
596 runs: &[ShapedRun],
597 flat: &[FlatGlyph],
598 start: usize,
599 end: usize,
600 metrics: &FontMetricsPx,
601 indent: f32,
602 text: &str,
603) -> LayoutLine {
604 // Group consecutive glyphs by run_index to reconstruct PositionedRuns
605 let mut positioned_runs = Vec::new();
606 let mut x = indent;
607 let mut current_run_idx: Option<usize> = None;
608 let mut run_glyph_start = 0usize;
609
610 for i in start..end {
611 let fg = &flat[i];
612 if current_run_idx != Some(fg.run_index) {
613 // Emit previous run segment if any
614 if let Some(prev_run_idx) = current_run_idx {
615 // End of previous run: use the last glyph we saw from that run
616 let prev_end = if i > start {
617 flat[i - 1].glyph_index_in_run + 1
618 } else {
619 run_glyph_start
620 };
621 let sub_run = extract_sub_run(runs, prev_run_idx, run_glyph_start, prev_end);
622 if let Some((pr, advance)) = sub_run {
623 positioned_runs.push(PositionedRun {
624 decorations: RunDecorations {
625 underline_style: pr.underline_style,
626 overline: pr.overline,
627 strikeout: pr.strikeout,
628 is_link: pr.is_link,
629 foreground_color: pr.foreground_color,
630 underline_color: pr.underline_color,
631 background_color: pr.background_color,
632 anchor_href: pr.anchor_href.clone(),
633 tooltip: pr.tooltip.clone(),
634 vertical_alignment: pr.vertical_alignment,
635 },
636 shaped_run: pr,
637 x,
638 });
639 x += advance;
640 }
641 }
642 current_run_idx = Some(fg.run_index);
643 run_glyph_start = fg.glyph_index_in_run;
644 }
645 }
646
647 // Emit final run segment
648 if let Some(run_idx) = current_run_idx {
649 let end_in_run = if end < flat.len() && flat[end].run_index == run_idx {
650 flat[end].glyph_index_in_run
651 } else if end > start {
652 flat[end - 1].glyph_index_in_run + 1
653 } else {
654 run_glyph_start
655 };
656 let sub_run = extract_sub_run(runs, run_idx, run_glyph_start, end_in_run);
657 if let Some((pr, advance)) = sub_run {
658 positioned_runs.push(PositionedRun {
659 decorations: RunDecorations {
660 underline_style: pr.underline_style,
661 overline: pr.overline,
662 strikeout: pr.strikeout,
663 is_link: pr.is_link,
664 foreground_color: pr.foreground_color,
665 underline_color: pr.underline_color,
666 background_color: pr.background_color,
667 anchor_href: pr.anchor_href.clone(),
668 tooltip: pr.tooltip.clone(),
669 vertical_alignment: pr.vertical_alignment,
670 },
671 shaped_run: pr,
672 x,
673 });
674 x += advance;
675 }
676 }
677
678 let width = x - indent;
679
680 // Compute char range from cluster values.
681 // Clusters from rustybuzz are byte offsets — convert to char offsets
682 // so that positions match text-document's character-based coordinates.
683 //
684 // Glyphs are in *visual* order, so for an RTL run `flat[start]` holds
685 // the largest cluster and `flat[end-1]` the smallest. Take the min/max
686 // over the line's glyphs instead of trusting the array ends, so the
687 // logical range is correct for both directions.
688 let byte_start = flat[start..end.min(flat.len())]
689 .iter()
690 .map(|g| g.cluster as usize)
691 .min()
692 .unwrap_or(0);
693 let byte_end = if end >= flat.len() {
694 // Last glyph reaches the end of the input text. Always snap to the
695 // full length: a trailing ligature glyph may cover several source
696 // chars, so `max_cluster + 1` would be wrong.
697 text.len()
698 } else {
699 // Next visual glyph's cluster bounds an LTR line exactly; for a
700 // wrapped RTL line take whichever is larger so the logical end
701 // still covers the line's highest cluster.
702 let line_max = flat[start..end]
703 .iter()
704 .map(|g| g.cluster as usize)
705 .max()
706 .unwrap_or(0);
707 (flat[end].cluster as usize).max(line_max)
708 };
709 let char_start = byte_offset_to_char_offset(text, byte_start);
710 let char_end = byte_offset_to_char_offset(text, byte_end);
711
712 // Expand line height for inline images taller than the font ascent
713 let mut ascent = metrics.ascent;
714 for run in &positioned_runs {
715 if run.shaped_run.image_name.is_some() && run.shaped_run.image_height > ascent {
716 ascent = run.shaped_run.image_height;
717 }
718 }
719 let line_height = ascent + metrics.descent + metrics.leading;
720
721 LayoutLine {
722 runs: positioned_runs,
723 y: 0.0, // will be set by the caller (block layout)
724 ascent,
725 descent: metrics.descent,
726 leading: metrics.leading,
727 width,
728 char_range: char_start..char_end,
729 line_height,
730 // Degenerate fallback only: a built line normally derives caret
731 // positions from its runs, but if every run came out glyph-less
732 // the caret still has the line's start to sit at.
733 empty_caret_x: indent,
734 }
735}
736
737/// Extract a sub-run (slice of glyphs) from a ShapedRun.
738/// Cluster values are offset to block-text space (adding text_range.start).
739fn extract_sub_run(
740 runs: &[ShapedRun],
741 run_index: usize,
742 glyph_start: usize,
743 glyph_end: usize,
744) -> Option<(ShapedRun, f32)> {
745 let run = &runs[run_index];
746 let end = glyph_end.min(run.glyphs.len());
747 if glyph_start >= end {
748 return None;
749 }
750 let cluster_offset = run.text_range.start as u32;
751 let mut sub_glyphs = run.glyphs[glyph_start..end].to_vec();
752 // Offset cluster values from fragment-local to block-text space
753 for g in &mut sub_glyphs {
754 g.cluster += cluster_offset;
755 }
756 let advance: f32 = sub_glyphs.iter().map(|g| g.x_advance).sum();
757
758 let sub_run = ShapedRun {
759 font_face_id: run.font_face_id,
760 size_px: run.size_px,
761 weight: run.weight,
762 glyphs: sub_glyphs,
763 advance_width: advance,
764 text_range: run.text_range.clone(),
765 direction: run.direction,
766 bidi_level: run.bidi_level,
767 underline_style: run.underline_style,
768 overline: run.overline,
769 strikeout: run.strikeout,
770 is_link: run.is_link,
771 foreground_color: run.foreground_color,
772 underline_color: run.underline_color,
773 background_color: run.background_color,
774 anchor_href: run.anchor_href.clone(),
775 tooltip: run.tooltip.clone(),
776 vertical_alignment: run.vertical_alignment,
777 image_name: run.image_name.clone(),
778 image_height: run.image_height,
779 };
780 Some((sub_run, advance))
781}
782
783fn make_empty_line(
784 metrics: &FontMetricsPx,
785 char_range: Range<usize>,
786 empty_caret_x: f32,
787) -> LayoutLine {
788 LayoutLine {
789 runs: Vec::new(),
790 y: 0.0,
791 ascent: metrics.ascent,
792 descent: metrics.descent,
793 leading: metrics.leading,
794 width: 0.0,
795 char_range,
796 line_height: metrics.ascent + metrics.descent + metrics.leading,
797 empty_caret_x,
798 }
799}
800
801/// The x where the caret sits on a line with no glyphs — i.e. where the
802/// first typed character's glyph would land. Mirrors the run-shifting
803/// arithmetic of `break_into_lines`' alignment pass with a line width of
804/// zero, so an empty paragraph's caret cannot disagree with where the
805/// first keystroke lays text out (the "caret jumps on the first
806/// character" bug).
807fn empty_line_caret_x(
808 alignment: Alignment,
809 base_direction: TextDirection,
810 first_line_indent: f32,
811 available_width: f32,
812) -> f32 {
813 let rtl = base_direction == TextDirection::RightToLeft;
814 let indent = first_line_indent;
815 let line_avail = (available_width - indent).max(0.0);
816 match alignment.resolve_for(base_direction) {
817 // In an RTL paragraph the alignment pass first moves runs to the
818 // left edge so the indent insets from the *right*; Right then
819 // shifts by the remaining width. Width zero leaves the caret at
820 // `line_avail` (RTL) or the full width (LTR).
821 Alignment::Right => {
822 if rtl {
823 line_avail
824 } else {
825 available_width
826 }
827 }
828 Alignment::Center => {
829 let shift = line_avail / 2.0;
830 if rtl { shift } else { indent + shift }
831 }
832 // Justify never justifies the last line, and a lone line is the
833 // last line, so runs keep their unshifted positions: the indent
834 // for LTR; the left edge for RTL, where the alignment pass moved
835 // them and Justify does not put the indent back.
836 Alignment::Justify => {
837 if rtl {
838 0.0
839 } else {
840 indent
841 }
842 }
843 // `resolve_for` maps Start/End onto Left/Right, so what remains is
844 // Left — which keeps runs at the indent in both directions.
845 _ => indent,
846 }
847}
848
849/// Distribute extra space among word gaps for justification.
850///
851/// Finds space glyphs (cluster mapping to ' ') across all runs and
852/// increases their x_advance proportionally. Then recomputes run x positions.
853fn justify_line(line: &mut LayoutLine, target_width: f32, text: &str) {
854 let extra = target_width - line.width;
855 if extra <= 0.0 {
856 return;
857 }
858
859 // Count space glyphs across all runs
860 let mut space_count = 0usize;
861 for run in &line.runs {
862 for glyph in &run.shaped_run.glyphs {
863 let byte_offset = glyph.cluster as usize;
864 if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
865 && ch == ' '
866 {
867 space_count += 1;
868 }
869 }
870 }
871
872 if space_count == 0 {
873 return;
874 }
875
876 let extra_per_space = extra / space_count as f32;
877
878 // Increase x_advance of space glyphs
879 for run in &mut line.runs {
880 for glyph in &mut run.shaped_run.glyphs {
881 let byte_offset = glyph.cluster as usize;
882 if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
883 && ch == ' '
884 {
885 glyph.x_advance += extra_per_space;
886 }
887 }
888 // Recompute run advance width
889 run.shaped_run.advance_width = run.shaped_run.glyphs.iter().map(|g| g.x_advance).sum();
890 }
891
892 // Recompute run x positions (runs follow each other)
893 let first_x = line.runs.first().map(|r| r.x).unwrap_or(0.0);
894 let mut x = first_x;
895 for run in &mut line.runs {
896 run.x = x;
897 x += run.shaped_run.advance_width;
898 }
899
900 line.width = target_width;
901}