Skip to main content

fleuron/
linebox.rs

1//! The line box model: how tall a line is and where its baseline sits.
2//!
3//! Half-leading over font metrics: a face's box is its ascent and
4//! descent, each widened by half the leading, where leading is what
5//! `line_height` adds over the face's natural height (ascent +
6//! descent + line gap). The line gap splits across the two halves so
7//! a single-face line always measures exactly `line_height × size`.
8//!
9//! The strut is the paragraph's own box — the line's minimum
10//! geometry, independent of the runs on it. Runs larger than
11//! the strut grow the line around the shared baseline; runs smaller
12//! never shrink it below the strut.
13//!
14//! Units: points throughout — runs of different sizes share one
15//! baseline, and font units don't commute across sizes.
16
17use crate::fonts::FontMetricsTable;
18
19/// Vertical extents around a baseline, in points: a face's box when
20/// computed for one font and size, the paragraph's strut when
21/// computed for the paragraph's own style.
22#[derive(Debug, Clone, Copy, PartialEq, Default)]
23pub struct Strut {
24    /// Distance from baseline to the top of the box.
25    pub above: f32,
26    /// Distance from baseline to the bottom of the box.
27    pub below: f32,
28}
29
30impl Strut {
31    /// The box a face makes at `size` under a unitless `line_height`.
32    pub fn from_metrics(metrics: FontMetricsTable, size: f32, line_height: f32) -> Strut {
33        let upem = metrics.units_per_em as f32;
34        let ascent = metrics.ascender as f32 / upem * size;
35        let descent = -metrics.descender as f32 / upem * size;
36        let gap = metrics.line_gap as f32 / upem * size;
37        let half_leading = (line_height * size - (ascent + descent + gap)) / 2.0;
38        Strut {
39            above: ascent + half_leading + gap / 2.0,
40            below: descent + half_leading + gap / 2.0,
41        }
42    }
43
44    /// The content area a face makes at `size`: its ascent and its
45    /// descent alone. This is the box an inline element's padding and
46    /// border are measured from, so what a chip encloses is the
47    /// letters rather than the space the line height opened around
48    /// them.
49    pub fn content(metrics: FontMetricsTable, size: f32) -> Strut {
50        let upem = metrics.units_per_em as f32;
51        Strut {
52            above: metrics.ascender as f32 / upem * size,
53            below: -metrics.descender as f32 / upem * size,
54        }
55    }
56
57    /// Total height: `above + below`.
58    pub fn height(self) -> f32 {
59        self.above + self.below
60    }
61}
62
63/// One line's vertical geometry, in points.
64#[derive(Debug, Clone, Copy, PartialEq)]
65pub struct LineBox {
66    /// Total height of the line.
67    pub height: f32,
68    /// Baseline offset from the top of the line. One baseline serves
69    /// the whole line; every run paints here, whatever its size.
70    pub baseline: f32,
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76    use crate::fonts::{FontRegistry, bundled_registry};
77    use crate::lines::{LineLayout, ParagraphStyle, ShapedRun};
78    use crate::style::BlendMode;
79
80    fn layout() -> LineLayout<'static> {
81        static REGISTRY: std::sync::OnceLock<FontRegistry> = std::sync::OnceLock::new();
82        let registry = REGISTRY.get_or_init(|| bundled_registry().expect("bundled font parses"));
83        LineLayout::new(registry)
84    }
85
86    /// The body style the built-in sheet computes: 11pt over the
87    /// bundled serif, at a line height of 1.4.
88    fn body() -> ParagraphStyle {
89        static REGISTRY: std::sync::OnceLock<FontRegistry> = std::sync::OnceLock::new();
90        let registry = REGISTRY.get_or_init(|| bundled_registry().expect("bundled font parses"));
91        crate::style::defaults(&crate::content::Book::default(), registry)
92            .root()
93            .paragraph()
94    }
95
96    fn run(size: f32) -> ShapedRun {
97        ShapedRun {
98            font_id: 0,
99            size,
100            text: String::new(),
101            source: String::new(),
102            source_map: Vec::new(),
103            text_start: 0,
104            origin: None,
105            pseudo_element: None,
106            inline: None,
107            lead: 0.0,
108            trail: 0.0,
109            features: crate::fonts::Features::NONE,
110            color: crate::style::Color::BLACK,
111            decoration: crate::style::TextDecoration::NONE,
112            glyphs: Vec::new(),
113            advance: 0,
114            blend: BlendMode::Normal,
115        }
116    }
117
118    fn assert_close(got: f32, want: f32, what: &str) {
119        assert!((got - want).abs() < 1e-3, "{what}: got {got}, want {want}");
120    }
121
122    /// EB Garamond: upem 1000, ascent 1007, descent −298, gap 0.
123    /// Body (11pt, line-height 1.4): natural 14.355pt, leading 1.045,
124    /// half 0.5225 — ascent 11.077 + 0.5225 above, 3.278 + 0.5225
125    /// below.
126    #[test]
127    fn strut_splits_the_leading_in_half() {
128        let strut = layout().strut(&body());
129        assert_close(strut.above, 11.5995, "above");
130        assert_close(strut.below, 3.8005, "below");
131        assert_close(strut.height(), 15.4, "height");
132    }
133
134    /// Above + below totals `line_height × size` whatever the knob —
135    /// including below the natural height, where the distribution is
136    /// symmetric negative leading.
137    #[test]
138    fn box_totals_line_height_at_any_knob() {
139        let metrics = bundled_registry().unwrap().metrics(0).unwrap();
140        for size in [6.0, 11.0, 24.0] {
141            for line_height in [0.9, 1.305, 1.4, 2.0] {
142                let strut = Strut::from_metrics(metrics, size, line_height);
143                assert_close(
144                    strut.height(),
145                    line_height * size,
146                    &format!("{size}pt at {line_height}"),
147                );
148            }
149        }
150    }
151
152    /// A line of runs smaller than the strut stays strut-tall — the
153    /// minimum height is independent of content.
154    #[test]
155    fn strut_is_the_minimum_independent_of_content() {
156        let strut = layout().strut(&body());
157        let line_box = layout().line_box(&[run(6.0)], &body());
158        assert_close(line_box.baseline, strut.above, "baseline");
159        assert_close(line_box.height, strut.height(), "height");
160    }
161
162    /// A line mixing 12pt and 24pt: both sit on one baseline, set by
163    /// the larger run. 24pt at 1.4: ascent 25.308 above, 8.292 below,
164    /// height 33.6 = 24 × 1.4; the 12pt run changes nothing.
165    #[test]
166    fn mixed_sizes_share_one_baseline() {
167        let line_box = layout().line_box(&[run(12.0), run(24.0)], &body());
168        assert_close(line_box.baseline, 25.308, "baseline");
169        assert_close(line_box.height, 33.6, "height");
170        let alone = layout().line_box(&[run(24.0)], &body());
171        assert_eq!(alone, line_box, "the 12pt run moved the line");
172    }
173
174    /// No runs at all: the strut alone defines the line.
175    #[test]
176    fn empty_line_is_the_strut() {
177        let strut = layout().strut(&body());
178        let line_box = layout().line_box(&[], &body());
179        assert_close(line_box.baseline, strut.above, "baseline");
180        assert_close(line_box.height, strut.height(), "height");
181    }
182}