Skip to main content

text_typeset/layout/
block.rs

1use crate::font::registry::FontRegistry;
2use crate::font::resolve::{ResolvedFont, resolve_font};
3use crate::layout::line::LayoutLine;
4use crate::layout::paragraph::{Alignment, Hyphenator, break_into_lines};
5use crate::shaping::run::{ShapedGlyph, ShapedRun};
6use crate::shaping::shaper::{
7    FontMetricsPx, TextDirection, font_metrics_px, shape_text, shape_text_with_fallback,
8    to_harfrust_features,
9};
10
11/// Computed layout for a single block (paragraph).
12#[derive(Clone)]
13pub struct BlockLayout {
14    pub block_id: usize,
15    /// Document character position of the block start.
16    pub position: usize,
17    /// Laid out lines within the block.
18    pub lines: Vec<LayoutLine>,
19    /// Top edge relative to document start (set by flow layout).
20    pub y: f32,
21    /// Total height: top_margin + sum(line heights) + bottom_margin.
22    pub height: f32,
23    pub top_margin: f32,
24    pub bottom_margin: f32,
25    pub left_margin: f32,
26    pub right_margin: f32,
27    /// Shaped list marker (positioned to the left of the content area).
28    /// None if the block is not a list item.
29    pub list_marker: Option<ShapedListMarker>,
30    /// Block background color (RGBA). None means transparent.
31    pub background_color: Option<[f32; 4]>,
32}
33
34/// A shaped list marker ready for rendering.
35#[derive(Clone)]
36pub struct ShapedListMarker {
37    pub run: ShapedRun,
38    /// X position of the marker (relative to block left edge, before content indent).
39    pub x: f32,
40}
41
42/// Parameters extracted from text-document's BlockFormat / TextFormat.
43/// This is a plain struct so block layout doesn't depend on text-document types.
44#[derive(Clone)]
45pub struct BlockLayoutParams {
46    pub block_id: usize,
47    pub position: usize,
48    pub text: String,
49    pub fragments: Vec<FragmentParams>,
50    pub alignment: Alignment,
51    pub top_margin: f32,
52    pub bottom_margin: f32,
53    pub left_margin: f32,
54    pub right_margin: f32,
55    pub text_indent: f32,
56    /// List marker text (e.g., "1.", "•", "a)"). Empty if not a list item.
57    pub list_marker: String,
58    /// Additional left indent for list items (in pixels).
59    pub list_indent: f32,
60    /// Tab stop positions in pixels from the left margin.
61    pub tab_positions: Vec<f32>,
62    /// Line height multiplier. 1.0 = normal (from font metrics), 1.5 = 150%, 2.0 = double.
63    /// None means use font metrics (ascent + descent + leading).
64    pub line_height_multiplier: Option<f32>,
65    /// If true, prevent line wrapping. The entire block is one long line.
66    pub non_breakable_lines: bool,
67    /// Hyphenation during line wrapping (`None` = off). See
68    /// [`crate::types::Hyphenation`].
69    pub hyphenation: Option<crate::types::Hyphenation>,
70    /// Checkbox marker: None = no checkbox, Some(false) = unchecked, Some(true) = checked.
71    pub checkbox: Option<bool>,
72    /// Block background color (RGBA). None means transparent.
73    pub background_color: Option<[f32; 4]>,
74}
75
76/// A text fragment with its formatting parameters.
77#[derive(Clone)]
78pub struct FragmentParams {
79    pub text: String,
80    /// **Byte** offset of this fragment's first character inside the
81    /// owning block's text. Lifted into glyph clusters by
82    /// `paragraph::flatten_runs` so glyph clusters
83    /// can be compared directly against `unicode-linebreak` break
84    /// positions (also bytes) and against the block-level text used
85    /// for `byte_offset_to_char_offset` conversion. Hosts threading
86    /// text-document `FragmentContent` through the bridge must
87    /// translate the char-based `FragmentContent::offset` into bytes
88    /// before assigning here.
89    pub offset: usize,
90    pub length: usize,
91    pub font_family: Option<String>,
92    pub font_weight: Option<u32>,
93    pub font_bold: Option<bool>,
94    pub font_italic: Option<bool>,
95    pub font_point_size: Option<u32>,
96    pub underline_style: crate::types::UnderlineStyle,
97    pub overline: bool,
98    pub strikeout: bool,
99    pub is_link: bool,
100    /// Extra space added after each glyph (in pixels). From TextFormat::letter_spacing.
101    pub letter_spacing: f32,
102    /// Extra space added after space glyphs (in pixels). From TextFormat::word_spacing.
103    pub word_spacing: f32,
104    /// Text foreground color (RGBA). None means default (black).
105    pub foreground_color: Option<[f32; 4]>,
106    /// Underline color (RGBA). None means use foreground_color.
107    pub underline_color: Option<[f32; 4]>,
108    /// Text-level background highlight color (RGBA). None means transparent.
109    pub background_color: Option<[f32; 4]>,
110    /// Hyperlink destination URL.
111    pub anchor_href: Option<String>,
112    /// Tooltip text.
113    pub tooltip: Option<String>,
114    /// Vertical alignment (normal, superscript, subscript).
115    pub vertical_alignment: crate::types::VerticalAlignment,
116    /// If Some, this fragment represents an inline image placeholder.
117    pub image_name: Option<String>,
118    /// Image width in pixels. Only meaningful when image_name is Some.
119    pub image_width: f32,
120    /// Image height in pixels. Only meaningful when image_name is Some.
121    pub image_height: f32,
122    /// Discretionary OpenType features to toggle during shaping. Empty =
123    /// font defaults. See [`crate::types::FontFeature`].
124    pub features: Vec<crate::types::FontFeature>,
125}
126
127/// Lay out a single block: resolve fonts, shape fragments, break into lines.
128///
129/// `scale_factor` is the device pixel ratio. Layout output is always in
130/// logical pixels; the scale factor affects shaping/rasterization precision.
131pub fn layout_block(
132    registry: &FontRegistry,
133    params: &BlockLayoutParams,
134    available_width: f32,
135    scale_factor: f32,
136) -> BlockLayout {
137    let effective_left_margin = params.left_margin + params.list_indent;
138    let content_width = (available_width - effective_left_margin - params.right_margin).max(0.0);
139
140    // Resolve fonts and shape each fragment
141    let mut shaped_runs = Vec::new();
142    let mut default_metrics: Option<FontMetricsPx> = None;
143
144    for frag in &params.fragments {
145        // Inline image: create a synthetic run with one placeholder glyph
146        if let Some(ref image_name) = frag.image_name {
147            let image_glyph = ShapedGlyph {
148                glyph_id: 0,
149                cluster: 0,
150                x_advance: frag.image_width,
151                y_advance: 0.0,
152                x_offset: 0.0,
153                y_offset: 0.0,
154                font_face_id: crate::types::FontFaceId(0),
155            };
156            let run = ShapedRun {
157                font_face_id: crate::types::FontFaceId(0),
158                size_px: 0.0,
159                weight: 400,
160                glyphs: vec![image_glyph],
161                advance_width: frag.image_width,
162                text_range: frag.offset..frag.offset + frag.text.len(),
163                direction: TextDirection::LeftToRight,
164                underline_style: frag.underline_style,
165                overline: false,
166                strikeout: false,
167                is_link: frag.is_link,
168                foreground_color: None,
169                underline_color: None,
170                background_color: None,
171                anchor_href: frag.anchor_href.clone(),
172                tooltip: frag.tooltip.clone(),
173                vertical_alignment: crate::types::VerticalAlignment::Normal,
174                image_name: Some(image_name.clone()),
175                image_height: frag.image_height,
176            };
177            shaped_runs.push(run);
178            continue;
179        }
180
181        // Scale font size for superscript/subscript
182        let font_point_size = match frag.vertical_alignment {
183            crate::types::VerticalAlignment::SuperScript
184            | crate::types::VerticalAlignment::SubScript => frag
185                .font_point_size
186                .map(|s| ((s as f32 * 0.65) as u32).max(1)),
187            crate::types::VerticalAlignment::Normal => frag.font_point_size,
188        };
189
190        let resolved = resolve_font(
191            registry,
192            frag.font_family.as_deref(),
193            frag.font_weight,
194            frag.font_bold,
195            frag.font_italic,
196            font_point_size,
197            scale_factor,
198        );
199
200        if let Some(resolved) = resolved {
201            // Capture default metrics from the first resolved font
202            if default_metrics.is_none() {
203                default_metrics = font_metrics_px(registry, &resolved);
204            }
205
206            let features = to_harfrust_features(&frag.features);
207            if let Some(mut run) = shape_text_with_fallback(
208                registry,
209                &resolved,
210                &frag.text,
211                frag.offset,
212                TextDirection::Auto,
213                &features,
214            ) {
215                run.underline_style = frag.underline_style;
216                run.overline = frag.overline;
217                run.strikeout = frag.strikeout;
218                run.is_link = frag.is_link;
219                run.foreground_color = frag.foreground_color;
220                run.underline_color = frag.underline_color;
221                run.background_color = frag.background_color;
222                run.anchor_href = frag.anchor_href.clone();
223                run.tooltip = frag.tooltip.clone();
224                run.vertical_alignment = frag.vertical_alignment;
225
226                // Apply letter_spacing and word_spacing post-shaping
227                if frag.letter_spacing != 0.0 || frag.word_spacing != 0.0 {
228                    apply_spacing(&mut run, &frag.text, frag.letter_spacing, frag.word_spacing);
229                }
230
231                // Apply tab stops
232                if !params.tab_positions.is_empty() {
233                    apply_tab_stops(&mut run, &frag.text, &params.tab_positions);
234                }
235
236                shaped_runs.push(run);
237            }
238        }
239    }
240
241    // Fallback metrics if no fragments resolved
242    let metrics = default_metrics.unwrap_or_else(|| get_default_metrics(registry, scale_factor));
243
244    // Non-breakable lines: use infinite width to prevent wrapping
245    let wrap_width = if params.non_breakable_lines {
246        f32::INFINITY
247    } else {
248        content_width
249    };
250
251    // Hyphenation: a hyphen glyph shaped in the default font, supplied only
252    // when enabled and wrapping is in effect.
253    let hyphenator = params
254        .hyphenation
255        .filter(|_| !params.non_breakable_lines)
256        .and_then(|h| {
257            shape_hyphen(registry, scale_factor).map(|glyph| Hyphenator {
258                glyph,
259                language: h.language,
260            })
261        });
262
263    // Break shaped runs into lines
264    let mut lines = break_into_lines(
265        shaped_runs,
266        &params.text,
267        wrap_width,
268        params.alignment,
269        params.text_indent,
270        &metrics,
271        hyphenator,
272    );
273
274    // Apply line height multiplier
275    let line_height_mul = params.line_height_multiplier.unwrap_or(1.0).max(0.1);
276
277    // Compute y positions for each line (relative to block content top)
278    let mut y = 0.0f32;
279    for line in &mut lines {
280        if line_height_mul != 1.0 {
281            line.line_height *= line_height_mul;
282        }
283        line.y = y + line.ascent; // y is the baseline position
284        y += line.line_height;
285    }
286
287    let content_height = y;
288    let total_height = params.top_margin + content_height + params.bottom_margin;
289
290    // Shape list marker or checkbox marker
291    let list_marker = if params.checkbox.is_some() {
292        shape_checkbox_marker(registry, &metrics, params, scale_factor)
293    } else if !params.list_marker.is_empty() {
294        shape_list_marker(registry, &metrics, params, scale_factor)
295    } else {
296        None
297    };
298
299    BlockLayout {
300        block_id: params.block_id,
301        position: params.position,
302        lines,
303        y: 0.0, // set by flow layout
304        height: total_height,
305        top_margin: params.top_margin,
306        bottom_margin: params.bottom_margin,
307        left_margin: effective_left_margin,
308        right_margin: params.right_margin,
309        list_marker,
310        background_color: params.background_color,
311    }
312}
313
314/// A resolved paint-only color overlay span for one character range of a block.
315///
316/// `char_start`/`char_end` are **block-relative character offsets** — the same
317/// space as the post-layout `ShapedGlyph::cluster` values (see
318/// `break_into_lines`, which converts clusters to char offsets). Each field is
319/// `None` when the overlay does not override it (the base run's value is kept).
320/// Applying paint spans never changes glyph geometry, advances, or line breaks
321/// — only color / decoration attributes — so the layout does not reflow.
322#[derive(Clone, Debug, Default, PartialEq)]
323pub struct PaintSpan {
324    pub char_start: usize,
325    pub char_end: usize,
326    pub foreground_color: Option<[f32; 4]>,
327    pub underline_color: Option<[f32; 4]>,
328    pub background_color: Option<[f32; 4]>,
329    pub underline_style: Option<crate::types::UnderlineStyle>,
330    pub overline: Option<bool>,
331    pub strikeout: Option<bool>,
332}
333
334/// The effective set of overrides for one glyph, used to group consecutive
335/// glyphs that share the same paint result into a single output run.
336#[derive(Clone, Default, PartialEq)]
337struct PaintOverride {
338    foreground_color: Option<[f32; 4]>,
339    underline_color: Option<[f32; 4]>,
340    background_color: Option<[f32; 4]>,
341    underline_style: Option<crate::types::UnderlineStyle>,
342    overline: Option<bool>,
343    strikeout: Option<bool>,
344}
345
346impl PaintOverride {
347    fn is_noop(&self) -> bool {
348        *self == PaintOverride::default()
349    }
350
351    /// Merge the overlapping spans covering `char_off` (last span wins per
352    /// field). Overlay spans from `extract_paint_spans` are already disjoint,
353    /// but last-wins keeps this correct for arbitrary inputs.
354    fn for_char(char_off: usize, spans: &[PaintSpan]) -> Self {
355        let mut o = PaintOverride::default();
356        for s in spans {
357            if s.char_start <= char_off && char_off < s.char_end {
358                if s.foreground_color.is_some() {
359                    o.foreground_color = s.foreground_color;
360                }
361                if s.underline_color.is_some() {
362                    o.underline_color = s.underline_color;
363                }
364                if s.background_color.is_some() {
365                    o.background_color = s.background_color;
366                }
367                if s.underline_style.is_some() {
368                    o.underline_style = s.underline_style;
369                }
370                if s.overline.is_some() {
371                    o.overline = s.overline;
372                }
373                if s.strikeout.is_some() {
374                    o.strikeout = s.strikeout;
375                }
376            }
377        }
378        o
379    }
380
381    /// Apply this override onto a positioned run segment, writing color /
382    /// decoration fields on BOTH the shaped run and its duplicated
383    /// `RunDecorations` (the renderer reads glyph color from the former and
384    /// decoration rects from the latter). `None` fields keep the base value.
385    fn apply(&self, run: &mut crate::layout::line::PositionedRun) {
386        if let Some(c) = self.foreground_color {
387            run.shaped_run.foreground_color = Some(c);
388            run.decorations.foreground_color = Some(c);
389        }
390        if let Some(c) = self.underline_color {
391            run.shaped_run.underline_color = Some(c);
392            run.decorations.underline_color = Some(c);
393        }
394        if let Some(c) = self.background_color {
395            run.shaped_run.background_color = Some(c);
396            run.decorations.background_color = Some(c);
397        }
398        if let Some(s) = self.underline_style {
399            run.shaped_run.underline_style = s;
400            run.decorations.underline_style = s;
401        }
402        if let Some(b) = self.overline {
403            run.shaped_run.overline = b;
404            run.decorations.overline = b;
405        }
406        if let Some(b) = self.strikeout {
407            run.shaped_run.strikeout = b;
408            run.decorations.strikeout = b;
409        }
410    }
411}
412
413/// Apply paint-only color spans to a base [`BlockLayout`], returning a recolored
414/// clone. The base is left untouched.
415///
416/// The result has byte-identical glyph positions, advances, line breaks, line
417/// widths, and block height to `base` — only color / decoration attributes
418/// differ. This is the "recolor without reshape/reflow" fast path: a run is
419/// split into segments at paint-span boundaries (snapped to glyph/cluster
420/// boundaries, never mid-cluster) and each segment's color fields are set.
421/// Splitting a run never alters any glyph advance, so line widths are preserved.
422///
423/// Empty `spans` returns an exact (color-preserving) clone of `base`.
424pub fn apply_paint_spans(base: &BlockLayout, spans: &[PaintSpan]) -> BlockLayout {
425    let mut out = base.clone();
426    if spans.is_empty() {
427        return out;
428    }
429    for line in &mut out.lines {
430        let mut new_runs: Vec<crate::layout::line::PositionedRun> =
431            Vec::with_capacity(line.runs.len());
432        for run in line.runs.drain(..) {
433            recolor_run_into(run, spans, &mut new_runs);
434        }
435        line.runs = new_runs;
436    }
437    out
438}
439
440/// Split `run` at paint-span boundaries and push the recolored segment(s) onto
441/// `out`. Image / glyph-less runs are passed through unchanged (paint overlays
442/// never recolor images).
443fn recolor_run_into(
444    run: crate::layout::line::PositionedRun,
445    spans: &[PaintSpan],
446    out: &mut Vec<crate::layout::line::PositionedRun>,
447) {
448    if run.shaped_run.glyphs.is_empty() || run.shaped_run.image_name.is_some() {
449        out.push(run);
450        return;
451    }
452
453    // Per-glyph effective override, in glyph (visual) order. Works for LTR and
454    // RTL alike: we group by adjacency in the glyph array, not by char order.
455    let overrides: Vec<PaintOverride> = run
456        .shaped_run
457        .glyphs
458        .iter()
459        .map(|g| PaintOverride::for_char(g.cluster as usize, spans))
460        .collect();
461
462    // Fast path: the whole run shares one override (the common case, and the
463    // only case when `spans` doesn't touch this run — then it's a no-op). Keep
464    // the base `advance_width` exactly so a cleared/uncovered run is identical.
465    if overrides.iter().all(|o| *o == overrides[0]) {
466        let mut seg = run;
467        overrides[0].apply(&mut seg);
468        out.push(seg);
469        return;
470    }
471
472    // Split into maximal runs of equal override.
473    let glyphs = run.shaped_run.glyphs.clone();
474    let mut seg_x = run.x;
475    let mut start = 0usize;
476    while start < glyphs.len() {
477        let ov = &overrides[start];
478        let mut end = start + 1;
479        while end < glyphs.len() && overrides[end] == *ov {
480            end += 1;
481        }
482        let seg_glyphs: Vec<crate::shaping::run::ShapedGlyph> = glyphs[start..end].to_vec();
483        let seg_advance: f32 = seg_glyphs.iter().map(|g| g.x_advance).sum();
484        let mut shaped = run.shaped_run.clone();
485        shaped.glyphs = seg_glyphs;
486        shaped.advance_width = seg_advance;
487        let mut seg = crate::layout::line::PositionedRun {
488            shaped_run: shaped,
489            x: seg_x,
490            decorations: run.decorations.clone(),
491        };
492        if !ov.is_noop() {
493            ov.apply(&mut seg);
494        }
495        out.push(seg);
496        seg_x += seg_advance;
497        start = end;
498    }
499}
500
501/// Add letter_spacing (to all glyphs) and word_spacing (to space glyphs).
502fn apply_spacing(run: &mut ShapedRun, text: &str, letter_spacing: f32, word_spacing: f32) {
503    let mut extra_advance = 0.0f32;
504    for glyph in &mut run.glyphs {
505        glyph.x_advance += letter_spacing;
506        extra_advance += letter_spacing;
507
508        // Add word_spacing to space characters.
509        // Detect spaces by mapping cluster back to the text.
510        if word_spacing != 0.0 {
511            let byte_offset = glyph.cluster as usize;
512            if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
513                && ch == ' '
514            {
515                glyph.x_advance += word_spacing;
516                extra_advance += word_spacing;
517            }
518        }
519    }
520    run.advance_width += extra_advance;
521}
522
523/// Shape a hyphen glyph (`-`) in the default font, for appending at
524/// hyphenated line breaks. Returns `None` if no default font resolves.
525pub(crate) fn shape_hyphen(registry: &FontRegistry, scale_factor: f32) -> Option<ShapedGlyph> {
526    let resolved = resolve_font(registry, None, None, None, None, None, scale_factor)?;
527    let run = shape_text(registry, &resolved, "-", 0)?;
528    run.glyphs.into_iter().next()
529}
530
531/// Shape the list marker text and position it in the indent area.
532fn shape_list_marker(
533    registry: &FontRegistry,
534    _metrics: &FontMetricsPx,
535    params: &BlockLayoutParams,
536    scale_factor: f32,
537) -> Option<ShapedListMarker> {
538    // Use the default font for the marker
539    let resolved = resolve_font(registry, None, None, None, None, None, scale_factor)?;
540    let run = shape_text(registry, &resolved, &params.list_marker, 0)?;
541
542    // Position the marker: right-aligned within the indent area, with a small gap
543    let gap = 4.0; // pixels between marker and content
544    let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
545    let marker_x = marker_x.max(params.left_margin);
546
547    Some(ShapedListMarker { run, x: marker_x })
548}
549
550/// Expand tab character advances to reach the next tab stop position.
551fn apply_tab_stops(run: &mut ShapedRun, text: &str, tab_positions: &[f32]) {
552    let default_tab = 48.0; // default tab width if no stops defined
553    let mut pen_x = 0.0f32;
554
555    for glyph in &mut run.glyphs {
556        let byte_offset = glyph.cluster as usize;
557        if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
558            && ch == '\t'
559        {
560            // Find the next tab stop after the current pen position
561            let next_stop = tab_positions
562                .iter()
563                .find(|&&stop| stop > pen_x + 1.0)
564                .copied()
565                .unwrap_or_else(|| {
566                    // Past all defined stops: use default tab increments
567                    let last = tab_positions.last().copied().unwrap_or(0.0);
568                    let increment = if tab_positions.len() >= 2 {
569                        tab_positions[1] - tab_positions[0]
570                    } else {
571                        default_tab
572                    };
573                    let mut stop = last + increment;
574                    while stop <= pen_x + 1.0 {
575                        stop += increment;
576                    }
577                    stop
578                });
579
580            let tab_advance = next_stop - pen_x;
581            let delta = tab_advance - glyph.x_advance;
582            glyph.x_advance = tab_advance;
583            run.advance_width += delta;
584        }
585        pen_x += glyph.x_advance;
586    }
587}
588
589/// Shape a checkbox marker (unchecked or checked) for rendering in the margin.
590fn shape_checkbox_marker(
591    registry: &FontRegistry,
592    _metrics: &FontMetricsPx,
593    params: &BlockLayoutParams,
594    scale_factor: f32,
595) -> Option<ShapedListMarker> {
596    let checked = params.checkbox?;
597    let marker_text = if checked { "\u{2611}" } else { "\u{2610}" }; // ballot box with/without check
598
599    let resolved = resolve_font(registry, None, None, None, None, None, scale_factor)?;
600    let run = shape_text(registry, &resolved, marker_text, 0)?;
601
602    // If the font doesn't have the ballot box characters, use ASCII fallback
603    let run = if run.glyphs.iter().any(|g| g.glyph_id == 0) {
604        let fallback_text = if checked { "[x]" } else { "[ ]" };
605        shape_text(registry, &resolved, fallback_text, 0)?
606    } else {
607        run
608    };
609
610    let gap = 4.0;
611    let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
612    let marker_x = marker_x.max(params.left_margin);
613
614    Some(ShapedListMarker { run, x: marker_x })
615}
616
617fn get_default_metrics(registry: &FontRegistry, scale_factor: f32) -> FontMetricsPx {
618    if let Some(default_id) = registry.default_font() {
619        let resolved = ResolvedFont {
620            font_face_id: default_id,
621            size_px: registry.default_size_px(),
622            face_index: registry.get(default_id).map(|e| e.face_index).unwrap_or(0),
623            swash_cache_key: registry
624                .get(default_id)
625                .map(|e| e.swash_cache_key)
626                .unwrap_or_default(),
627            scale_factor,
628            weight: 400,
629        };
630        if let Some(m) = font_metrics_px(registry, &resolved) {
631            return m;
632        }
633    }
634    // Absolute fallback: synthetic metrics for 16px
635    FontMetricsPx {
636        ascent: 14.0,
637        descent: 4.0,
638        leading: 0.0,
639        underline_offset: -2.0,
640        strikeout_offset: 5.0,
641        stroke_size: 1.0,
642    }
643}