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