Skip to main content

lievisual/text/
layout.rs

1use crate::geometry::{Color, Rect, Size};
2use crate::text::style::*;
3use std::sync::Arc;
4
5/// A single glyph (1:1 with parley's positioned glyph).
6#[derive(Debug, Clone, PartialEq)]
7pub struct Glyph {
8    /// Glyph ID.
9    pub id: u32,
10    /// X coordinate (offset relative to the origin of the owning [`TextLine::bounds`]).
11    pub x: f32,
12    /// Y coordinate (offset relative to the origin of the owning [`TextLine::bounds`]).
13    pub y: f32,
14    /// Advance width.
15    pub advance: f32,
16    /// Byte-cluster offset (relative to this run's own `text`, i.e. `text[cluster..]`).
17    pub cluster: u32,
18}
19
20/// A text Run — a contiguous sequence of glyphs sharing the same style (font, size, color).
21///
22/// The smallest unit of text rendering. A Run is self-contained: `text` is a local slice
23/// relative to the original `full_text`, and `glyphs[].cluster` is normalized to a local
24/// offset relative to `text`, so it can be drawn independently of the owning Line and the
25/// original string. The font is embedded as a self-contained `Vec<u8>` (`Arc`-shared, so
26/// the whole font file is not copied per run).
27///
28/// Extended attributes (`url` / `decoration` / `background_color` / `baseline_shift`) are
29/// mapped by lievisual from each [`RichSpan`]'s style ([`TextStyle`]) onto the run according
30/// to byte ranges, so downstream can consume them directly without re-annotating.
31#[derive(Debug, Clone)]
32pub struct TextRun {
33    /// The run's text content (self-contained, a local slice relative to the original
34    /// full_text).
35    pub text: String,
36    /// Raw font bytes (parsed from parley's FontData blob; self-contained, `Arc`-shared).
37    pub font_data: Arc<Vec<u8>>,
38    /// Index of the font within the font-collection file (ttc / otc). Always 0 for a
39    /// single-font file.
40    ///
41    /// Downstream (e.g. PDF font embedding) uses this to locate the specific font instance
42    /// inside `font_data`.
43    pub font_index: u32,
44    /// Font size.
45    pub font_size: f32,
46    /// Whether the font is bold (backends using system fonts, such as SVG, emit this as
47    /// `font-weight`).
48    pub font_weight_bold: bool,
49    /// Whether the font is italic (backends emit this as `font-style`).
50    pub font_style_italic: bool,
51    /// Text color.
52    pub color: Color,
53    /// Total advance width.
54    pub advance: f32,
55    /// Glyph list (coordinates offset relative to [`TextLine::bounds`] origin).
56    pub glyphs: Vec<Glyph>,
57    /// Whether the run is right-to-left.
58    pub is_rtl: bool,
59    /// Baseline X coordinate of the run's first character (relative to the layout origin).
60    pub baseline_x: f32,
61    /// Baseline Y coordinate of the line (offset from the line top; shared by all runs in
62    /// the same line).
63    pub baseline_y: f32,
64    /// Hyperlink URL, if any.
65    pub url: Option<String>,
66    /// Text decoration (underline / strikethrough).
67    pub decoration: TextDecoration,
68    /// Baseline shift (moves superscripts / subscripts up or down within the line).
69    pub baseline_shift: f32,
70    /// Inline background color (inline code / highlight; `None` means no background).
71    pub background_color: Option<Color>,
72}
73
74impl TextRun {
75    /// Split the run into multiple sub-runs at byte offsets (relative to `text`).
76    ///
77    /// - `offsets` 会被去重排序,并只保留位于 `(0, text.len())` 内、落在字符边界
78    ///   且与某字形 `cluster` 对齐的切点(不对齐的切点被忽略,字形不会丢失)。
79    /// - 子 run 的 `glyphs[].cluster` 重定基为相对各自 `text` 的局部偏移;
80    ///   `advance` 按子 run 字形重新求和;`baseline_x` 取子 run 首字形的 `x`
81    ///   (使背景矩形 / 链接热区等按 `baseline_x + advance` 定位的绘制属性
82    ///   在子 run 上依然正确)。
83    /// - 字体、颜色、粗斜体、修饰、背景、链接、基线偏移等属性**原样继承**;
84    ///   需要按 piece 区分扩展属性(如只给中段文本上背景色 / 链接)的调用方,
85    ///   在切分后按 piece 改写即可。
86    ///
87    /// 无有效切点时返回原 run 的克隆(原样)。
88    #[must_use]
89    pub fn split_at(&self, offsets: &[usize]) -> Vec<TextRun> {
90        let len = self.text.len();
91        let mut cuts: Vec<usize> = offsets.to_vec();
92        cuts.retain(|&o| {
93            o > 0
94                && o < len
95                && self.text.is_char_boundary(o)
96                && self.glyphs.iter().any(|g| g.cluster as usize == o)
97        });
98        cuts.sort_unstable();
99        cuts.dedup();
100        if cuts.is_empty() {
101            return vec![self.clone()];
102        }
103
104        let mut bounds = cuts;
105        bounds.insert(0, 0);
106        bounds.push(len);
107
108        let mut out = Vec::with_capacity(bounds.len() - 1);
109        for w in bounds.windows(2) {
110            let (start, end) = (w[0], w[1]);
111            let glyphs: Vec<Glyph> = self
112                .glyphs
113                .iter()
114                .filter(|g| {
115                    let c = g.cluster as usize;
116                    c >= start && c < end
117                })
118                .map(|g| Glyph {
119                    cluster: g.cluster - start as u32,
120                    ..g.clone()
121                })
122                .collect();
123            if glyphs.is_empty() {
124                continue;
125            }
126            let advance: f32 = glyphs.iter().map(|g| g.advance).sum();
127            let baseline_x = glyphs[0].x;
128            out.push(TextRun {
129                text: self.text[start..end].to_string(),
130                advance,
131                glyphs,
132                baseline_x,
133                ..self.clone()
134            });
135        }
136        out
137    }
138}
139
140/// Per-line font metrics — mirrors Parley 0.13's `LineMetrics` (block-axis coords)
141/// plus the font-level `cap_height` / `x_height` pulled from parley's `FontMetrics`.
142///
143/// All block-axis fields are **relative to the line's top edge** (i.e.
144/// `parley_line_metrics.baseline - row_top_rel`, etc.), so consumers don't need
145/// to know the line's position within the layout.
146///
147/// Parley 0.13 dropped `ascent` / `descent` from `LineMetrics`; they are now
148/// derivable as `baseline - content_block_min` and `content_block_max - baseline`.
149#[derive(Debug, Clone, Copy, PartialEq)]
150pub struct LineMetrics {
151    /// The absolute line height (`line_height`).
152    pub line_height: f32,
153
154    /// Block-axis coordinate of the line's baseline, relative to the line's top.
155    pub baseline: f32,
156
157    /// Top of the **line box** (half-leading included), relative to the line's top.
158    /// Comes from `block_min_coord`.
159    pub block_min: f32,
160
161    /// Bottom of the **line box**, relative to the line's top.
162    /// Comes from `block_max_coord`.
163    pub block_max: f32,
164
165    /// Top of the **typographic content** (ascender edge, no leading),
166    /// relative to the line's top. Comes from `content_block_min_coord`.
167    pub content_block_min: f32,
168
169    /// Bottom of the **typographic content** (descender edge, no leading),
170    /// relative to the line's top. Comes from `content_block_max_coord`.
171    pub content_block_max: f32,
172
173    /// Font-level cap height (baseline → top of uppercase). `0.0` when unknown.
174    /// Sourced from parley's `FontMetrics`, not `LineMetrics`.
175    pub cap_height: f32,
176
177    /// Font-level x-height (baseline → top of lowercase). `0.0` when unknown.
178    pub x_height: f32,
179}
180
181impl LineMetrics {
182    /// Typographic ascent (baseline → content top), derived.
183    pub fn ascent(&self) -> f32 {
184        self.baseline - self.content_block_min
185    }
186
187    /// Typographic descent (baseline → content bottom), derived.
188    pub fn descent(&self) -> f32 {
189        self.content_block_max - self.baseline
190    }
191}
192
193/// A text line — holds all [`TextRun`]s within one line.
194///
195/// Coordinate system (relative to the layout origin):
196/// - `bounds.origin`: the line's position in the layout.
197/// - `runs[].glyphs[].x/y`: offsets relative to `bounds.origin`.
198#[derive(Debug, Clone)]
199pub struct TextLine {
200    /// All runs in this line.
201    pub runs: Vec<TextRun>,
202    /// The line's bounding box (relative to the layout origin).
203    /// This is the **line box** (equivalent to `block_min/max`, kept for compat).
204    pub bounds: Rect,
205    /// Inline font metrics (block-axis coords + cap / x).
206    pub metrics: LineMetrics,
207}
208
209impl TextLine {
210    /// **Layout bounds** for this line: parley's default `line_height` box,
211    /// i.e. `row_top → row_top + line_height`.
212    pub fn layout_bounds(&self) -> Rect {
213        self.bounds
214    }
215
216    /// **Line box bounds** — `block_min` → `block_max` (half-leading included).
217    /// Identical to [`Self::layout_bounds`] in most cases; kept separate so the
218    /// two concepts stay distinct if parley changes its default.
219    pub fn line_box_bounds(&self) -> Rect {
220        let top = self.bounds.min_y();
221        Rect::new(
222            self.bounds.min_x(),
223            top + self.metrics.block_min as f64,
224            self.bounds.max_x(),
225            top + self.metrics.block_max as f64,
226        )
227    }
228
229    /// **Logical / content bounds** — `content_block_min` → `content_block_max`.
230    ///
231    /// This is the equivalent of Pango's `logical_rect`: typographic ascent +
232    /// descent, **without** leading. Stable across text changes, but for CJK
233    /// the font's ascent margin still makes it look top-heavy.
234    pub fn logical_bounds(&self) -> Rect {
235        let top = self.bounds.min_y();
236        Rect::new(
237            self.bounds.min_x(),
238            top + self.metrics.content_block_min as f64,
239            self.bounds.max_x(),
240            top + self.metrics.content_block_max as f64,
241        )
242    }
243
244    /// **Cap bounds** — `baseline - cap_height` → `baseline`.
245    ///
246    /// Equivalent to CSS `text-box-edge: cap alphabetic`. Recommended for
247    /// visual vertical centering of digits / uppercase / CJK. Because
248    /// `cap_height` is a font-level constant, this box does **not** change
249    /// when the line's text changes.
250    ///
251    /// Falls back to [`Self::logical_bounds`] when `cap_height` is unavailable.
252    pub fn cap_bounds(&self) -> Rect {
253        if self.metrics.cap_height > 0.0 {
254            let top = self.bounds.min_y();
255            let baseline_y = top + self.metrics.baseline as f64;
256            Rect::new(
257                self.bounds.min_x(),
258                baseline_y - self.metrics.cap_height as f64,
259                self.bounds.max_x(),
260                baseline_y,
261            )
262        } else {
263            self.logical_bounds()
264        }
265    }
266}
267
268/// Rich-text layout result — holds the laid-out set of lines.
269///
270/// All coordinates are relative to the layout origin (the paragraph's
271/// top-left corner); pagination and absolute positioning are the output
272/// backend's responsibility.
273#[derive(Debug, Clone)]
274pub struct TextLayout {
275    /// All laid-out lines.
276    pub lines: Vec<TextLine>,
277    /// Total layout width.
278    pub width: f64,
279    /// Total layout height (sum of `line_height`, = parley's `layout.height()`).
280    pub height: f64,
281}
282
283impl TextLayout {
284    /// Aggregate **layout bounds** over all lines (parley's default box).
285    pub fn layout_bounds(&self) -> Rect {
286        self.lines
287            .iter()
288            .map(TextLine::layout_bounds)
289            .fold(None, union_rect)
290            .unwrap_or_else(|| Rect::new(0.0, 0.0, self.width, self.height))
291    }
292
293    /// Aggregate **line box bounds** over all lines.
294    pub fn line_box_bounds(&self) -> Rect {
295        self.lines
296            .iter()
297            .map(TextLine::line_box_bounds)
298            .fold(None, union_rect)
299            .unwrap_or_else(|| Rect::new(0.0, 0.0, self.width, self.height))
300    }
301
302    /// Aggregate **logical / content bounds** over all lines.
303    pub fn logical_bounds(&self) -> Rect {
304        self.lines
305            .iter()
306            .map(TextLine::logical_bounds)
307            .fold(None, union_rect)
308            .unwrap_or_else(|| Rect::new(0.0, 0.0, self.width, self.height))
309    }
310
311    /// Aggregate **cap bounds** over all lines.
312    pub fn cap_bounds(&self) -> Rect {
313        self.lines
314            .iter()
315            .map(TextLine::cap_bounds)
316            .fold(None, union_rect)
317            .unwrap_or_else(|| Rect::new(0.0, 0.0, self.width, self.height))
318    }
319}
320
321fn union_rect(acc: Option<Rect>, r: Rect) -> Option<Rect> {
322    Some(match acc {
323        None => r,
324        Some(a) => a.union(r),
325    })
326}
327/// Text measurement result (the value returned by canvas `measureText()`).
328///
329/// Coordinate semantics (consistent with Canvas `TextMetrics`, where y-down quantities
330/// take positive values):
331/// - `*ascent` / `*descent` are relative to the **baseline** (positive upward / downward);
332/// - `*baseline` are relative to the **top of the text block** (positive downward);
333/// - `actual_bounding_box_*` are approximate (for multiline, derived from the first line's
334///   metrics).
335#[derive(Debug, Clone, Copy, PartialEq)]
336pub struct TextMetrics {
337    /// Text block width (canvas `width`).
338    pub width: f64,
339    /// Text block height (canvas has no direct field; equals `layout.height()`).
340    pub height: f64,
341    /// Distance from the anchor (left edge) to the leftmost glyph boundary, ≤ 0.
342    pub actual_bounding_box_left: f64,
343    /// Distance from the anchor (left edge) to the rightmost glyph boundary.
344    pub actual_bounding_box_right: f64,
345    /// Height from the font box top to the baseline (positive, upward).
346    pub font_bounding_box_ascent: f64,
347    /// Height from the baseline to the font box bottom (positive, downward).
348    pub font_bounding_box_descent: f64,
349    /// Actual glyph top to the baseline (≈ first line ascent).
350    pub actual_bounding_box_ascent: f64,
351    /// Baseline to the actual glyph bottom (≈ first line descent).
352    pub actual_bounding_box_descent: f64,
353    /// Em-box top to the baseline (≈ first line ascent).
354    pub em_height_ascent: f64,
355    /// Baseline to the em-box bottom (≈ first line descent).
356    pub em_height_descent: f64,
357    /// Distance from the top of the text block to the hanging baseline.
358    pub hanging_baseline: f64,
359    /// Distance from the top of the text block to the alphabetic baseline.
360    pub alphabetic_baseline: f64,
361    /// Distance from the top of the text block to the ideographic baseline.
362    pub ideographic_baseline: f64,
363    /// Single-line line height.
364    pub line_height: f64,
365}
366
367/// A measurement result: size + metrics + reusable layout (avoids re-layout when drawing).
368pub struct TextMeasure {
369    /// Text block size (`width` / `height`).
370    pub size: Size,
371    /// Detailed metrics (canvas `TextMetrics`).
372    pub metrics: TextMetrics,
373    /// Pre-computed layout, which can be fed to [`crate::scene::Element::Text::layout`] for
374    /// exact glyph drawing.
375    pub layout: Arc<TextLayout>,
376}