Skip to main content

text_typeset/layout/
block.rs

1use crate::font::registry::FontRegistry;
2use crate::font::resolve::{ResolvedFont, resolve_font};
3use crate::font::script_fallback::ScriptContext;
4use crate::layout::line::LayoutLine;
5use crate::layout::paragraph::{Alignment, Hyphenator, RunOrder, break_into_lines};
6use crate::shaping::run::{ShapedGlyph, ShapedRun};
7use crate::shaping::shaper::{
8    BidiParagraph, FontMetricsPx, TextDirection, analyze_paragraph_with_neutral, font_metrics_px,
9    shape_text, shape_text_in_paragraph, shape_text_with_fallback, to_harfrust_features,
10};
11
12/// Computed layout for a single block (paragraph).
13#[derive(Clone)]
14#[non_exhaustive]
15pub struct BlockLayout {
16    pub block_id: usize,
17    /// Document character position of the block start.
18    pub position: usize,
19    /// Laid out lines within the block.
20    pub lines: Vec<LayoutLine>,
21    /// Top edge relative to document start (set by flow layout).
22    pub y: f32,
23    /// Total height: top_margin + sum(line heights) + bottom_margin.
24    pub height: f32,
25    pub top_margin: f32,
26    pub bottom_margin: f32,
27    pub left_margin: f32,
28    pub right_margin: f32,
29    /// Shaped list marker (positioned to the left of the content area).
30    /// None if the block is not a list item.
31    pub list_marker: Option<ShapedListMarker>,
32    /// The paragraph's *resolved* base direction — never `Auto`.
33    ///
34    /// `BlockLayoutParams::base_direction` may ask for auto-detection;
35    /// this is what the bidi analysis actually settled on. Selection
36    /// painting and caret motion need the answer, not the question.
37    pub base_direction: TextDirection,
38    /// Block background color (RGBA). None means transparent.
39    pub background_color: Option<[f32; 4]>,
40}
41
42/// A shaped list marker ready for rendering.
43#[derive(Clone)]
44#[non_exhaustive]
45pub struct ShapedListMarker {
46    pub run: ShapedRun,
47    /// X position of the marker (relative to block left edge, before content indent).
48    pub x: f32,
49}
50
51/// Parameters extracted from text-document's BlockFormat / TextFormat.
52/// This is a plain struct so block layout doesn't depend on text-document types.
53#[derive(Clone)]
54pub struct BlockLayoutParams {
55    pub block_id: usize,
56    pub position: usize,
57    pub text: String,
58    pub fragments: Vec<FragmentParams>,
59    pub alignment: Alignment,
60    pub top_margin: f32,
61    pub bottom_margin: f32,
62    pub left_margin: f32,
63    pub right_margin: f32,
64    pub text_indent: f32,
65    /// List marker text (e.g., "1.", "•", "a)"). Empty if not a list item.
66    pub list_marker: String,
67    /// Additional left indent for list items (in pixels).
68    pub list_indent: f32,
69    /// Tab stop positions in pixels from the left margin.
70    pub tab_positions: Vec<f32>,
71    /// The paragraph's base reading direction.
72    ///
73    /// `Auto` applies UAX #9 rules P2/P3 (first strong character wins).
74    /// An explicit direction overrides that, which is what a stored
75    /// per-block direction is for: auto-detection reads an Arabic
76    /// paragraph opening with a Latin acronym as left-to-right.
77    ///
78    /// Drives three things: which direction each bidi run shapes with,
79    /// the visual order of a line's runs, and — when `alignment` is
80    /// `Start`/`End` — which edge the text sits against.
81    pub base_direction: TextDirection,
82    /// The direction an `Auto` paragraph takes when its text has no strongly
83    /// directional character: an empty paragraph, or one of digits, spaces
84    /// and punctuation. UAX #9 says left to right, which `LeftToRight` and
85    /// `Auto` both give; a host whose block is for a right-to-left language
86    /// (an empty field for Arabic) says `RightToLeft`. Ignored when
87    /// `base_direction` is explicit. See
88    /// [`resolve_paragraph_direction`](crate::resolve_paragraph_direction).
89    pub neutral_direction: TextDirection,
90    /// The language the block's text is written in, a BCP 47 tag (`ja`,
91    /// `sr-Cyrl`, `zh-Hant`). `None` when the host did not say.
92    ///
93    /// The shaper is told it, so a font's language-specific forms are used
94    /// (OpenType `locl`), and it decides how Han characters are drawn:
95    /// Japanese, Korean, Simplified or Traditional Chinese forms. Separate from
96    /// [`hyphenation`](Self::hyphenation), which may be off for a block whose
97    /// language is known.
98    pub language: Option<String>,
99    /// Line height multiplier. 1.0 = normal (from font metrics), 1.5 = 150%, 2.0 = double.
100    /// None means use font metrics (ascent + descent + leading).
101    pub line_height_multiplier: Option<f32>,
102    /// If true, prevent line wrapping. The entire block is one long line.
103    pub non_breakable_lines: bool,
104    /// Hyphenation during line wrapping (`None` = off). See
105    /// [`crate::types::Hyphenation`].
106    pub hyphenation: Option<crate::types::Hyphenation>,
107    /// Checkbox marker: None = no checkbox, Some(false) = unchecked, Some(true) = checked.
108    pub checkbox: Option<bool>,
109    /// Block background color (RGBA). None means transparent.
110    pub background_color: Option<[f32; 4]>,
111}
112
113/// A text fragment with its formatting parameters.
114#[derive(Clone)]
115pub struct FragmentParams {
116    pub text: String,
117    /// **Byte** offset of this fragment's first character inside the
118    /// owning block's text. Lifted into glyph clusters by
119    /// `paragraph::flatten_runs` so glyph clusters
120    /// can be compared directly against `unicode-linebreak` break
121    /// positions (also bytes) and against the block-level text used
122    /// for `byte_offset_to_char_offset` conversion. Hosts threading
123    /// text-document `FragmentContent` through the bridge must
124    /// translate the char-based `FragmentContent::offset` into bytes
125    /// before assigning here.
126    pub offset: usize,
127    pub length: usize,
128    pub font_family: Option<String>,
129    pub font_weight: Option<u32>,
130    pub font_bold: Option<bool>,
131    pub font_italic: Option<bool>,
132    pub font_point_size: Option<u32>,
133    /// Multiplies the fragment's size: `font_point_size` when it is set, the
134    /// default size the host gave [`set_default_font`] (the body size) when it
135    /// is not. The product is cut to whole pixels. `1.0` for body text; the
136    /// bridge gives a heading its level's ratio (2.0 for a level 1 heading),
137    /// so headings keep their proportion to whatever body size the host sets.
138    ///
139    /// [`set_default_font`]: crate::TextFontService::set_default_font
140    pub size_scale: f32,
141    pub underline_style: crate::types::UnderlineStyle,
142    pub overline: bool,
143    pub strikeout: bool,
144    pub is_link: bool,
145    /// Extra space added after each glyph (in pixels). From TextFormat::letter_spacing.
146    pub letter_spacing: f32,
147    /// Extra space added after space glyphs (in pixels). From TextFormat::word_spacing.
148    pub word_spacing: f32,
149    /// Text foreground color (RGBA). None means default (black).
150    pub foreground_color: Option<[f32; 4]>,
151    /// Underline color (RGBA). None means use foreground_color.
152    pub underline_color: Option<[f32; 4]>,
153    /// Text-level background highlight color (RGBA). None means transparent.
154    pub background_color: Option<[f32; 4]>,
155    /// Hyperlink destination URL.
156    pub anchor_href: Option<String>,
157    /// Tooltip text.
158    pub tooltip: Option<String>,
159    /// Vertical alignment (normal, superscript, subscript).
160    pub vertical_alignment: crate::types::VerticalAlignment,
161    /// If Some, this fragment represents an inline image placeholder.
162    pub image_name: Option<String>,
163    /// Image width in pixels. Only meaningful when image_name is Some.
164    pub image_width: f32,
165    /// Image height in pixels. Only meaningful when image_name is Some.
166    pub image_height: f32,
167    /// If Some, this fragment is a footnote reference and this is the marker
168    /// to draw at its position — a number, usually, but the host decides.
169    ///
170    /// The fragment still occupies exactly the **one** `U+FFFC` character its
171    /// `text` holds, however many glyphs the marker shapes to. That mismatch is
172    /// the whole point and the whole hazard: the marker is *presentation*, and
173    /// the document must not grow a character because a footnote reached two
174    /// digits. So the marker is shaped on its own and every resulting glyph is
175    /// pinned to the sentinel's cluster, which is what stops the caret landing
176    /// between the `1` and the `2` of note twelve.
177    ///
178    /// Distinct from [`Self::image_name`] rather than folded in with it: an
179    /// image reserves a box of a size the host measured, a marker reserves
180    /// whatever its own glyphs advance to, and only the latter needs a font.
181    pub footnote_marker: Option<String>,
182    /// Discretionary OpenType features to toggle during shaping. Empty =
183    /// font defaults. See [`crate::types::FontFeature`].
184    pub features: Vec<crate::types::FontFeature>,
185}
186
187/// The directional slices of one fragment, in logical order.
188///
189/// Intersects the fragment's byte span with the paragraph's bidi runs and
190/// yields `(span, direction, level)` for each overlap. A fragment lying
191/// wholly inside one bidi run — the overwhelmingly common case — yields a
192/// single slice covering it, so uniform text costs nothing extra.
193///
194/// Falls back to one `Auto` slice when the analysis produced no runs
195/// (empty block text), which preserves the pre-bidi behaviour.
196fn fragment_bidi_slices(
197    bidi: &BidiParagraph,
198    frag: &FragmentParams,
199) -> Vec<(std::ops::Range<usize>, TextDirection, u8)> {
200    let frag_end = frag.offset + frag.text.len();
201
202    if bidi.runs.is_empty() {
203        return vec![(frag.offset..frag_end, TextDirection::Auto, 0)];
204    }
205
206    let mut slices = Vec::new();
207    for run in &bidi.runs {
208        let start = run.byte_range.start.max(frag.offset);
209        let end = run.byte_range.end.min(frag_end);
210        if start < end {
211            slices.push((start..end, run.direction, run.level));
212        }
213    }
214
215    // A fragment outside the analysed text (a host bug, or a zero-length
216    // fragment) still deserves a shot at shaping rather than vanishing.
217    if slices.is_empty() {
218        slices.push((frag.offset..frag_end, TextDirection::Auto, 0));
219    }
220    slices
221}
222
223/// Lay out a single block: resolve fonts, shape fragments, break into lines.
224///
225/// `scale_factor` is the device pixel ratio. Layout output is always in
226/// logical pixels; the scale factor affects shaping/rasterization precision.
227pub fn layout_block(
228    registry: &FontRegistry,
229    params: &BlockLayoutParams,
230    available_width: f32,
231    scale_factor: f32,
232    font_scale: f32,
233) -> BlockLayout {
234    let effective_left_margin = params.left_margin + params.list_indent;
235    let content_width = (available_width - effective_left_margin - params.right_margin).max(0.0);
236
237    // Resolve the paragraph's bidi structure once, over the whole block
238    // text. It has to be the whole text: the algorithm's resolution of a
239    // neutral character (a space, a comma) depends on the strong
240    // characters on *both* sides of it, which a per-fragment analysis
241    // cannot see.
242    let bidi = analyze_paragraph_with_neutral(
243        &params.text,
244        params.base_direction,
245        params.neutral_direction,
246    );
247    // The paragraph and the language the block is in decide the faces glyph
248    // fallback prefers for Han, and the language the shaper is told. A block
249    // whose host set no language but asked for hyphenation is taken to be in
250    // the hyphenation's language.
251    let hyphenation_language = params
252        .hyphenation
253        .and_then(|h| std::str::from_utf8(&h.language).ok().map(str::to_owned));
254    let script_context = ScriptContext::in_language(
255        &params.text,
256        params
257            .language
258            .as_deref()
259            .or(hyphenation_language.as_deref()),
260    );
261    let base_direction = bidi.base_direction();
262
263    // Resolve fonts and shape each fragment
264    let mut shaped_runs = Vec::new();
265    let mut default_metrics: Option<FontMetricsPx> = None;
266
267    for frag in &params.fragments {
268        // Inline image: create a synthetic run with one placeholder glyph
269        if let Some(ref image_name) = frag.image_name {
270            // An image is a neutral character in the bidi algorithm, so
271            // it takes the level of whatever run covers its offset.
272            // Hardcoding 0 left it at paragraph level inside RTL prose,
273            // where it broke the contiguous run rule L2 reverses and so
274            // stayed on the wrong side of the text around it.
275            let (image_direction, image_level) = fragment_bidi_slices(&bidi, frag)
276                .first()
277                .map(|(_, d, l)| (*d, *l))
278                .unwrap_or((TextDirection::LeftToRight, 0));
279            let image_glyph = ShapedGlyph {
280                glyph_id: 0,
281                cluster: 0,
282                x_advance: frag.image_width,
283                y_advance: 0.0,
284                x_offset: 0.0,
285                y_offset: 0.0,
286                font_face_id: crate::types::FontFaceId(0),
287            };
288            let run = ShapedRun {
289                font_face_id: crate::types::FontFaceId(0),
290                size_px: 0.0,
291                weight: 400,
292                italic: false,
293                glyphs: vec![image_glyph],
294                advance_width: frag.image_width,
295                text_range: frag.offset..frag.offset + frag.text.len(),
296                direction: image_direction,
297                bidi_level: image_level,
298                underline_style: frag.underline_style,
299                overline: false,
300                strikeout: false,
301                is_link: frag.is_link,
302                foreground_color: None,
303                underline_color: None,
304                background_color: None,
305                anchor_href: frag.anchor_href.clone(),
306                tooltip: frag.tooltip.clone(),
307                vertical_alignment: crate::types::VerticalAlignment::Normal,
308                image_name: Some(image_name.clone()),
309                image_height: frag.image_height,
310            };
311            shaped_runs.push(run);
312            continue;
313        }
314
315        // A heading's size is a ratio of the body size: the run's own size
316        // when it has one, the default size otherwise.
317        let point_size = if frag.size_scale != 1.0 {
318            let base = frag
319                .font_point_size
320                .map(|s| s as f32)
321                .unwrap_or(registry.default_size_px());
322            Some((base * frag.size_scale) as u32)
323        } else {
324            frag.font_point_size
325        };
326        // Scale font size for superscript/subscript
327        let font_point_size = match frag.vertical_alignment {
328            crate::types::VerticalAlignment::SuperScript
329            | crate::types::VerticalAlignment::SubScript => {
330                point_size.map(|s| ((s as f32 * 0.65) as u32).max(1))
331            }
332            crate::types::VerticalAlignment::Normal => point_size,
333        };
334
335        let resolved = resolve_font(
336            registry,
337            frag.font_family.as_deref(),
338            frag.font_weight,
339            frag.font_bold,
340            frag.font_italic,
341            font_point_size,
342            scale_factor,
343            font_scale,
344        );
345
346        if let Some(resolved) = resolved {
347            // Capture default metrics from the first resolved font
348            if default_metrics.is_none() {
349                default_metrics = font_metrics_px(registry, &resolved);
350            }
351
352            let features = to_harfrust_features(&frag.features);
353
354            // A footnote reference: shape the *marker* and pin it to the
355            // sentinel.
356            //
357            // The fragment's own text is one `U+FFFC`, three bytes wide and one
358            // character long; the marker is whatever the host wants drawn there.
359            // Shaping the marker through the ordinary path below is not an
360            // option — that path slices `frag.text` by byte range, so a marker
361            // longer than the sentinel would read past it, and a marker shorter
362            // than it would leave a coverage gap. Shaping it standalone and
363            // then overwriting the run's own coordinates is the same graft
364            // `append_hyphen` performs for a hyphen that is likewise not in the
365            // text.
366            //
367            // Every glyph is collapsed onto the sentinel's cluster. Clusters are
368            // what hit-testing, caret movement and line breaking all read, so
369            // one shared value makes the marker atomic in all three at once: a
370            // click anywhere in it resolves to the sentinel, the caret cannot
371            // stop inside it, and a line cannot break within it.
372            //
373            // Deliberately no `image_height`: that field is what makes
374            // `break_into_lines` inflate a line to fit, and an inflated line is
375            // then excluded from the interline multiplier. A marker is smaller
376            // than the text it rides on and must stay an ordinary line, or a
377            // footnote would quietly change the leading of the paragraph
378            // holding it.
379            if let Some(marker) = frag.footnote_marker.as_deref() {
380                let (direction, level) = fragment_bidi_slices(&bidi, frag)
381                    .first()
382                    .map(|(_, d, l)| (*d, *l))
383                    .unwrap_or((TextDirection::LeftToRight, 0));
384
385                if let Some(mut run) =
386                    shape_text_with_fallback(registry, &resolved, marker, 0, direction, &features)
387                {
388                    // Cluster 0, not `frag.offset`: clusters are **run-local**
389                    // here and `flatten_runs` lifts them by `text_range.start`
390                    // on the way out. Pinning them to the absolute offset
391                    // instead double-counts it, which puts every stop past the
392                    // end of the run — the caret after a footnote then lands
393                    // wherever the *next* run happens to start, and a marker of
394                    // two digits measures the same as one of one. The image
395                    // branch above uses the same `cluster: 0` for the same
396                    // reason.
397                    for glyph in &mut run.glyphs {
398                        glyph.cluster = 0;
399                    }
400                    run.text_range = frag.offset..frag.offset + frag.text.len();
401                    run.bidi_level = level;
402                    run.underline_style = frag.underline_style;
403                    run.overline = frag.overline;
404                    run.strikeout = frag.strikeout;
405                    run.is_link = frag.is_link;
406                    run.foreground_color = frag.foreground_color;
407                    run.underline_color = frag.underline_color;
408                    run.background_color = frag.background_color;
409                    run.anchor_href = frag.anchor_href.clone();
410                    run.tooltip = frag.tooltip.clone();
411                    run.vertical_alignment = frag.vertical_alignment;
412                    shaped_runs.push(run);
413                }
414                continue;
415            }
416
417            // Shape each directional slice of the fragment separately. A
418            // fragment is a *formatting* span (one bold/italic/font run),
419            // which has nothing to do with where the text changes
420            // direction — so shaping a fragment as a single unit is what
421            // left mixed Arabic/Latin prose in raw logical order. Cutting
422            // it at the bidi boundaries gives every run one uniform
423            // direction, and `break_into_lines` reorders them per line.
424            for (span, direction, level) in fragment_bidi_slices(&bidi, frag) {
425                let local = (span.start - frag.offset)..(span.end - frag.offset);
426                let Some(piece) = frag.text.get(local) else {
427                    // The host's fragment offsets disagree with the block
428                    // text it also supplied. Nothing good can come of
429                    // guessing which is right; skip the slice rather than
430                    // panic on a bad byte index.
431                    continue;
432                };
433                if piece.is_empty() {
434                    continue;
435                }
436
437                if let Some(mut run) = shape_text_in_paragraph(
438                    registry,
439                    &resolved,
440                    piece,
441                    span.start,
442                    direction,
443                    &features,
444                    &script_context,
445                    span.start,
446                ) {
447                    run.bidi_level = level;
448                    run.underline_style = frag.underline_style;
449                    run.overline = frag.overline;
450                    run.strikeout = frag.strikeout;
451                    run.is_link = frag.is_link;
452                    run.foreground_color = frag.foreground_color;
453                    run.underline_color = frag.underline_color;
454                    run.background_color = frag.background_color;
455                    run.anchor_href = frag.anchor_href.clone();
456                    run.tooltip = frag.tooltip.clone();
457                    run.vertical_alignment = frag.vertical_alignment;
458
459                    // Both of these map `glyph.cluster` back into the text
460                    // they were shaped from, so they get the slice — not
461                    // the whole fragment.
462                    if frag.letter_spacing != 0.0 || frag.word_spacing != 0.0 {
463                        apply_spacing(&mut run, piece, frag.letter_spacing, frag.word_spacing);
464                    }
465                    if !params.tab_positions.is_empty() {
466                        apply_tab_stops(&mut run, piece, &params.tab_positions);
467                    }
468
469                    shaped_runs.push(run);
470                }
471            }
472        }
473    }
474
475    // Fallback metrics if no fragments resolved
476    let metrics =
477        default_metrics.unwrap_or_else(|| get_default_metrics(registry, scale_factor, font_scale));
478
479    // Non-breakable lines: use infinite width to prevent wrapping
480    let wrap_width = if params.non_breakable_lines {
481        f32::INFINITY
482    } else {
483        content_width
484    };
485
486    // Hyphenation: a hyphen glyph shaped in the default font, supplied only
487    // when enabled and wrapping is in effect.
488    let hyphenator = params
489        .hyphenation
490        .filter(|_| !params.non_breakable_lines)
491        .and_then(|h| {
492            shape_hyphen(registry, scale_factor, font_scale).map(|glyph| Hyphenator {
493                glyph,
494                language: h.language,
495            })
496        });
497
498    // Break shaped runs into lines
499    let mut lines = break_into_lines(
500        shaped_runs,
501        &params.text,
502        wrap_width,
503        params.alignment,
504        params.text_indent,
505        &metrics,
506        hyphenator,
507        RunOrder::Logical(base_direction),
508    );
509
510    // Apply line height multiplier.
511    //
512    // The multiplier expresses "N times the font's own line box", so it must
513    // stretch only that font-driven space. A line holding an inline image
514    // taller than the font's ascent already reports `line_height` inflated to
515    // fit the picture (`break_into_lines`, paragraph.rs), and multiplying THAT
516    // adds a fraction of the *image's* height as blank space below it — a 1.5×
517    // interline setting turned a 200px image into ~100px of dead space before
518    // the next block, which is the "huge gap under an image" report.
519    //
520    // So the multiplier is applied only to lines that were not image-inflated,
521    // which leaves it working in both directions. Comparing against a *scaled*
522    // natural height instead would silently cancel any multiplier below 1.0 for
523    // every line in the block, image or not — and sub-1.0 line heights arrive
524    // unclamped from imported HTML (`line-height: 0.8`) and from djot's
525    // `{line_height=800}`.
526    let line_height_mul = params.line_height_multiplier.unwrap_or(1.0).max(0.1);
527    let natural_line_height = metrics.ascent + metrics.descent + metrics.leading;
528
529    // Compute y positions for each line (relative to block content top)
530    let mut y = 0.0f32;
531    for line in &mut lines {
532        if line_height_mul != 1.0 && line.line_height <= natural_line_height + f32::EPSILON {
533            line.line_height *= line_height_mul;
534        }
535        line.y = y + line.ascent; // y is the baseline position
536        y += line.line_height;
537    }
538
539    let content_height = y;
540    let total_height = params.top_margin + content_height + params.bottom_margin;
541
542    // Shape list marker or checkbox marker
543    let list_marker = if params.checkbox.is_some() {
544        shape_checkbox_marker(registry, &metrics, params, scale_factor, font_scale)
545    } else if !params.list_marker.is_empty() {
546        shape_list_marker(registry, &metrics, params, scale_factor, font_scale)
547    } else {
548        None
549    };
550
551    BlockLayout {
552        block_id: params.block_id,
553        position: params.position,
554        base_direction,
555        lines,
556        y: 0.0, // set by flow layout
557        height: total_height,
558        top_margin: params.top_margin,
559        bottom_margin: params.bottom_margin,
560        left_margin: effective_left_margin,
561        right_margin: params.right_margin,
562        list_marker,
563        background_color: params.background_color,
564    }
565}
566
567/// A resolved paint-only color overlay span for one character range of a block.
568///
569/// `char_start`/`char_end` are **block-relative character offsets** — the same
570/// space as the post-layout `ShapedGlyph::cluster` values (see
571/// `break_into_lines`, which converts clusters to char offsets). Each field is
572/// `None` when the overlay does not override it (the base run's value is kept).
573/// Applying paint spans never changes glyph geometry, advances, or line breaks
574/// — only color / decoration attributes — so the layout does not reflow.
575#[derive(Clone, Debug, Default, PartialEq)]
576pub struct PaintSpan {
577    pub char_start: usize,
578    pub char_end: usize,
579    pub foreground_color: Option<[f32; 4]>,
580    pub underline_color: Option<[f32; 4]>,
581    pub background_color: Option<[f32; 4]>,
582    pub underline_style: Option<crate::types::UnderlineStyle>,
583    pub overline: Option<bool>,
584    pub strikeout: Option<bool>,
585}
586
587/// The effective set of overrides for one glyph, used to group consecutive
588/// glyphs that share the same paint result into a single output run.
589#[derive(Clone, Default, PartialEq)]
590struct PaintOverride {
591    foreground_color: Option<[f32; 4]>,
592    underline_color: Option<[f32; 4]>,
593    background_color: Option<[f32; 4]>,
594    underline_style: Option<crate::types::UnderlineStyle>,
595    overline: Option<bool>,
596    strikeout: Option<bool>,
597}
598
599impl PaintOverride {
600    fn is_noop(&self) -> bool {
601        *self == PaintOverride::default()
602    }
603
604    /// Merge the overlapping spans covering `char_off` (last span wins per
605    /// field). Overlay spans from `extract_paint_spans` are already disjoint,
606    /// but last-wins keeps this correct for arbitrary inputs.
607    fn for_char(char_off: usize, spans: &[PaintSpan]) -> Self {
608        let mut o = PaintOverride::default();
609        for s in spans {
610            if s.char_start <= char_off && char_off < s.char_end {
611                if s.foreground_color.is_some() {
612                    o.foreground_color = s.foreground_color;
613                }
614                if s.underline_color.is_some() {
615                    o.underline_color = s.underline_color;
616                }
617                if s.background_color.is_some() {
618                    o.background_color = s.background_color;
619                }
620                if s.underline_style.is_some() {
621                    o.underline_style = s.underline_style;
622                }
623                if s.overline.is_some() {
624                    o.overline = s.overline;
625                }
626                if s.strikeout.is_some() {
627                    o.strikeout = s.strikeout;
628                }
629            }
630        }
631        o
632    }
633
634    /// Apply this override onto a positioned run segment, writing color /
635    /// decoration fields on BOTH the shaped run and its duplicated
636    /// `RunDecorations` (the renderer reads glyph color from the former and
637    /// decoration rects from the latter). `None` fields keep the base value.
638    fn apply(&self, run: &mut crate::layout::line::PositionedRun) {
639        if let Some(c) = self.foreground_color {
640            run.shaped_run.foreground_color = Some(c);
641            run.decorations.foreground_color = Some(c);
642        }
643        if let Some(c) = self.underline_color {
644            run.shaped_run.underline_color = Some(c);
645            run.decorations.underline_color = Some(c);
646        }
647        if let Some(c) = self.background_color {
648            run.shaped_run.background_color = Some(c);
649            run.decorations.background_color = Some(c);
650        }
651        if let Some(s) = self.underline_style {
652            run.shaped_run.underline_style = s;
653            run.decorations.underline_style = s;
654        }
655        if let Some(b) = self.overline {
656            run.shaped_run.overline = b;
657            run.decorations.overline = b;
658        }
659        if let Some(b) = self.strikeout {
660            run.shaped_run.strikeout = b;
661            run.decorations.strikeout = b;
662        }
663    }
664}
665
666/// Apply paint-only color spans to a base [`BlockLayout`], returning a recolored
667/// clone. The base is left untouched.
668///
669/// The result has byte-identical glyph positions, advances, line breaks, line
670/// widths, and block height to `base` — only color / decoration attributes
671/// differ. This is the "recolor without reshape/reflow" fast path: a run is
672/// split into segments at paint-span boundaries (snapped to glyph/cluster
673/// boundaries, never mid-cluster) and each segment's color fields are set.
674/// Splitting a run never alters any glyph advance, so line widths are preserved.
675///
676/// Empty `spans` returns an exact (color-preserving) clone of `base`.
677pub fn apply_paint_spans(base: &BlockLayout, spans: &[PaintSpan]) -> BlockLayout {
678    let mut out = base.clone();
679    if spans.is_empty() {
680        return out;
681    }
682    for line in &mut out.lines {
683        let mut new_runs: Vec<crate::layout::line::PositionedRun> =
684            Vec::with_capacity(line.runs.len());
685        for run in line.runs.drain(..) {
686            recolor_run_into(run, spans, &mut new_runs);
687        }
688        line.runs = new_runs;
689    }
690    out
691}
692
693/// Split `run` at paint-span boundaries and push the recolored segment(s) onto
694/// `out`. Image / glyph-less runs are passed through unchanged (paint overlays
695/// never recolor images).
696fn recolor_run_into(
697    run: crate::layout::line::PositionedRun,
698    spans: &[PaintSpan],
699    out: &mut Vec<crate::layout::line::PositionedRun>,
700) {
701    if run.shaped_run.glyphs.is_empty() || run.shaped_run.image_name.is_some() {
702        out.push(run);
703        return;
704    }
705
706    // Per-glyph effective override, in glyph (visual) order. Works for LTR and
707    // RTL alike: we group by adjacency in the glyph array, not by char order.
708    let overrides: Vec<PaintOverride> = run
709        .shaped_run
710        .glyphs
711        .iter()
712        .map(|g| PaintOverride::for_char(g.cluster as usize, spans))
713        .collect();
714
715    // Fast path: the whole run shares one override (the common case, and the
716    // only case when `spans` doesn't touch this run — then it's a no-op). Keep
717    // the base `advance_width` exactly so a cleared/uncovered run is identical.
718    if overrides.iter().all(|o| *o == overrides[0]) {
719        let mut seg = run;
720        overrides[0].apply(&mut seg);
721        out.push(seg);
722        return;
723    }
724
725    // Split into maximal runs of equal override.
726    let glyphs = run.shaped_run.glyphs.clone();
727    let mut seg_x = run.x;
728    let mut start = 0usize;
729    while start < glyphs.len() {
730        let ov = &overrides[start];
731        let mut end = start + 1;
732        while end < glyphs.len() && overrides[end] == *ov {
733            end += 1;
734        }
735        let seg_glyphs: Vec<crate::shaping::run::ShapedGlyph> = glyphs[start..end].to_vec();
736        let seg_advance: f32 = seg_glyphs.iter().map(|g| g.x_advance).sum();
737        let mut shaped = run.shaped_run.clone();
738        shaped.glyphs = seg_glyphs;
739        shaped.advance_width = seg_advance;
740        let mut seg = crate::layout::line::PositionedRun {
741            shaped_run: shaped,
742            x: seg_x,
743            decorations: run.decorations.clone(),
744        };
745        if !ov.is_noop() {
746            ov.apply(&mut seg);
747        }
748        out.push(seg);
749        seg_x += seg_advance;
750        start = end;
751    }
752}
753
754/// Add letter_spacing (to all glyphs) and word_spacing (to space glyphs).
755fn apply_spacing(run: &mut ShapedRun, text: &str, letter_spacing: f32, word_spacing: f32) {
756    let mut extra_advance = 0.0f32;
757    for glyph in &mut run.glyphs {
758        // A hard break takes no space, tracked or not: spaced, it pushed a right-aligned
759        // or centred line ending in one off its place by the tracking.
760        let is_break = text
761            .get(glyph.cluster as usize..)
762            .and_then(|rest| rest.chars().next())
763            .is_some_and(crate::types::is_hard_break);
764        if is_break {
765            continue;
766        }
767        glyph.x_advance += letter_spacing;
768        extra_advance += letter_spacing;
769
770        // Add word_spacing to space characters.
771        // Detect spaces by mapping cluster back to the text.
772        if word_spacing != 0.0 {
773            let byte_offset = glyph.cluster as usize;
774            if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
775                && ch == ' '
776            {
777                glyph.x_advance += word_spacing;
778                extra_advance += word_spacing;
779            }
780        }
781    }
782    run.advance_width += extra_advance;
783}
784
785/// Shape a hyphen glyph (`-`) in the default font, for appending at
786/// hyphenated line breaks. Returns `None` if no default font resolves.
787pub(crate) fn shape_hyphen(
788    registry: &FontRegistry,
789    scale_factor: f32,
790    font_scale: f32,
791) -> Option<ShapedGlyph> {
792    let resolved = resolve_font(
793        registry,
794        None,
795        None,
796        None,
797        None,
798        None,
799        scale_factor,
800        font_scale,
801    )?;
802    let run = shape_text(registry, &resolved, "-", 0)?;
803    run.glyphs.into_iter().next()
804}
805
806/// Shape the list marker text and position it in the indent area.
807fn shape_list_marker(
808    registry: &FontRegistry,
809    _metrics: &FontMetricsPx,
810    params: &BlockLayoutParams,
811    scale_factor: f32,
812    font_scale: f32,
813) -> Option<ShapedListMarker> {
814    // Use the default font for the marker
815    let resolved = resolve_font(
816        registry,
817        None,
818        None,
819        None,
820        None,
821        None,
822        scale_factor,
823        font_scale,
824    )?;
825    let run = shape_text(registry, &resolved, &params.list_marker, 0)?;
826
827    // Position the marker: right-aligned within the indent area, with a small gap
828    let gap = 4.0; // pixels between marker and content
829    let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
830    let marker_x = marker_x.max(params.left_margin);
831
832    Some(ShapedListMarker { run, x: marker_x })
833}
834
835/// Expand tab character advances to reach the next tab stop position.
836fn apply_tab_stops(run: &mut ShapedRun, text: &str, tab_positions: &[f32]) {
837    let default_tab = 48.0; // default tab width if no stops defined
838    let mut pen_x = 0.0f32;
839
840    for glyph in &mut run.glyphs {
841        let byte_offset = glyph.cluster as usize;
842        if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
843            && ch == '\t'
844        {
845            // Find the next tab stop after the current pen position
846            let next_stop = tab_positions
847                .iter()
848                .find(|&&stop| stop > pen_x + 1.0)
849                .copied()
850                .unwrap_or_else(|| {
851                    // Past all defined stops: use default tab increments
852                    let last = tab_positions.last().copied().unwrap_or(0.0);
853                    let increment = if tab_positions.len() >= 2 {
854                        tab_positions[1] - tab_positions[0]
855                    } else {
856                        default_tab
857                    };
858                    let mut stop = last + increment;
859                    while stop <= pen_x + 1.0 {
860                        stop += increment;
861                    }
862                    stop
863                });
864
865            let tab_advance = next_stop - pen_x;
866            let delta = tab_advance - glyph.x_advance;
867            glyph.x_advance = tab_advance;
868            run.advance_width += delta;
869        }
870        pen_x += glyph.x_advance;
871    }
872}
873
874/// Shape a checkbox marker (unchecked or checked) for rendering in the margin.
875fn shape_checkbox_marker(
876    registry: &FontRegistry,
877    _metrics: &FontMetricsPx,
878    params: &BlockLayoutParams,
879    scale_factor: f32,
880    font_scale: f32,
881) -> Option<ShapedListMarker> {
882    let checked = params.checkbox?;
883    let marker_text = if checked { "\u{2611}" } else { "\u{2610}" }; // ballot box with/without check
884
885    let resolved = resolve_font(
886        registry,
887        None,
888        None,
889        None,
890        None,
891        None,
892        scale_factor,
893        font_scale,
894    )?;
895    let run = shape_text(registry, &resolved, marker_text, 0)?;
896
897    // If the font doesn't have the ballot box characters, use ASCII fallback
898    let run = if run.glyphs.iter().any(|g| g.glyph_id == 0) {
899        let fallback_text = if checked { "[x]" } else { "[ ]" };
900        shape_text(registry, &resolved, fallback_text, 0)?
901    } else {
902        run
903    };
904
905    let gap = 4.0;
906    let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
907    let marker_x = marker_x.max(params.left_margin);
908
909    Some(ShapedListMarker { run, x: marker_x })
910}
911
912fn get_default_metrics(
913    registry: &FontRegistry,
914    scale_factor: f32,
915    font_scale: f32,
916) -> FontMetricsPx {
917    if let Some(default_id) = registry.default_font() {
918        let resolved = ResolvedFont {
919            font_face_id: default_id,
920            size_px: registry.default_size_px() * font_scale,
921            face_index: registry.get(default_id).map(|e| e.face_index).unwrap_or(0),
922            swash_cache_key: registry
923                .get(default_id)
924                .map(|e| e.swash_cache_key)
925                .unwrap_or_default(),
926            scale_factor,
927            weight: 400,
928            italic: false,
929        };
930        if let Some(m) = font_metrics_px(registry, &resolved) {
931            return m;
932        }
933    }
934    // Absolute fallback: synthetic metrics for 16px
935    FontMetricsPx {
936        ascent: 14.0,
937        descent: 4.0,
938        leading: 0.0,
939        underline_offset: -2.0,
940        strikeout_offset: 5.0,
941        stroke_size: 1.0,
942    }
943}