Skip to main content

fleuron/lines/
line.rs

1//! A broken line: the runs on it, the spans it fills, and the
2//! widths that measure it.
3
4use std::ops::Range;
5
6use crate::content::{NodeId, SourceRange};
7use crate::fonts::{Features, ShapedGlyph};
8use crate::linebox::LineBox;
9use crate::style::{BlendMode, Color, TextDecoration};
10
11use super::flatten::FlatParagraph;
12use super::shape::ShapedSpan;
13
14/// A run of glyphs sharing one font and size — the paintable unit.
15#[derive(Debug, Clone, PartialEq)]
16pub struct ShapedRun {
17    /// Index into the registry that shaped the run.
18    pub font_id: u16,
19    /// Em size in points.
20    pub size: f32,
21    /// The text the run was shaped from. Glyph ids alone do not
22    /// spell anything, and the correspondence exists only in the
23    /// shaper's output.
24    pub text: String,
25    /// What the author wrote, where a transform made that differ
26    /// from what was shaped, and empty where the two are the same.
27    pub source: String,
28    /// The offset in `source` of every byte boundary of `text`.
29    /// Empty alongside `source`.
30    pub source_map: Vec<u32>,
31    /// Byte offset of `text` in the paragraph the glyphs' clusters
32    /// index.
33    pub text_start: u32,
34    /// Where the run was written: the node it was shaped from and
35    /// the bytes of that node's own text it stands for. `None` for
36    /// text no node was walked for: page furniture, an ornament.
37    pub origin: Option<SourceRange>,
38    /// The pseudo-element the run was cut from, where it was cut from
39    /// one.
40    pub pseudo_element: Option<NodeId>,
41    /// The innermost inline element the run came from: a link, an
42    /// emphasis, a strong, a code span. `None` on the text of the
43    /// paragraph itself.
44    pub inline: Option<NodeId>,
45    /// Points of space before the run's first glyph, from the leading
46    /// edges of the inline boxes that open on it.
47    pub lead: f32,
48    /// Points of space after its last glyph, from the trailing edges
49    /// of the ones that close on it.
50    pub trail: f32,
51    /// The features the run was shaped with.
52    pub features: Features,
53    /// What the run is painted in.
54    pub color: Color,
55    /// What is drawn across it: the rules `text-decoration` asks
56    /// for, each painted over the run's own advance.
57    pub decoration: TextDecoration,
58    /// How the run and its rules are mixed with what is under them.
59    pub blend: BlendMode,
60    /// The glyphs, in visual order.
61    pub glyphs: Vec<ShapedGlyph>,
62    /// Total advance of the run's glyphs, in font units. What an
63    /// inline box takes beside them is `lead` and `trail`, in points.
64    pub advance: u32,
65}
66
67impl ShapedRun {
68    /// The byte range in `text` each glyph stands for, in glyph
69    /// order. A glyph covers its cluster up to the next cluster that
70    /// starts later — which is how a ligature comes to span the
71    /// characters it swallowed.
72    pub fn glyph_ranges(&self) -> Vec<Range<u32>> {
73        let end = self.text.len() as u32;
74        let starts: Vec<u32> = self
75            .glyphs
76            .iter()
77            .map(|g| g.cluster.saturating_sub(self.text_start).min(end))
78            .collect();
79        starts
80            .iter()
81            .enumerate()
82            .map(|(i, start)| {
83                let next = starts[i + 1..]
84                    .iter()
85                    .find(|later| *later > start)
86                    .copied()
87                    .unwrap_or(end);
88                *start..next.max(*start)
89            })
90            .collect()
91    }
92}
93
94/// One span of a line: the runs set in it, and where they go.
95#[derive(Debug, Clone, PartialEq)]
96pub struct LineSpan {
97    /// The runs of `Line::runs` set here.
98    pub runs: Range<usize>,
99    /// Points from the line's own leading edge the span is set at.
100    pub offset: f32,
101    /// Advance of the span's glyphs, in font units.
102    pub width: u32,
103}
104
105/// The spans of one line, read as a slice either way. A band set
106/// undivided holds its span inline: the ordinary line of a book does
107/// not pay for an allocation.
108#[derive(Debug, Clone, PartialEq)]
109pub enum Spans {
110    /// The band was set in one span.
111    One(LineSpan),
112    /// It was divided, and these are its spans in reading order.
113    Many(Vec<LineSpan>),
114}
115
116impl std::ops::Deref for Spans {
117    type Target = [LineSpan];
118
119    fn deref(&self) -> &[LineSpan] {
120        match self {
121            Spans::One(span) => std::slice::from_ref(span),
122            Spans::Many(spans) => spans,
123        }
124    }
125}
126
127impl std::ops::DerefMut for Spans {
128    fn deref_mut(&mut self) -> &mut [LineSpan] {
129        match self {
130            Spans::One(span) => std::slice::from_mut(span),
131            Spans::Many(spans) => spans,
132        }
133    }
134}
135
136/// One inline element's box on one line: where it sits, and which of
137/// its edges it paints there.
138///
139/// An inline element covers as many lines as its runs reach, and one
140/// of these stands for what it takes on one of them. The edges the
141/// line break cut are open under `box-decoration-break: slice` and
142/// closed under `clone`.
143#[derive(Debug, Clone, Copy, PartialEq)]
144pub struct InlineFragment {
145    /// The inline element the box belongs to.
146    pub node: NodeId,
147    /// Which span of the line the box is set in, as an index into
148    /// `Line::spans`. An element covering two spans of one band has a
149    /// box in each of them.
150    pub span: usize,
151    /// Points from the leading edge of that span to the leading edge
152    /// of the border box. The span's own offset moves the box with
153    /// the text, which is what alignment moves.
154    pub x: f32,
155    /// Width of the border box, in points.
156    pub width: f32,
157    /// Points from the baseline up to the top of the border box.
158    pub above: f32,
159    /// Points from the baseline down to its bottom.
160    pub below: f32,
161    /// Whether the leading edge is painted here.
162    pub opens: bool,
163    /// Whether the trailing edge is.
164    pub closes: bool,
165}
166
167/// One typeset line: shaped runs plus its width in font units.
168///
169/// A line is a band of the page, which is set in one span or in
170/// several. The runs are in reading order across all of them.
171#[derive(Debug, Clone, PartialEq)]
172pub struct Line {
173    /// The line's runs, in visual order.
174    pub runs: Vec<ShapedRun>,
175    /// The spans the runs are divided between, in reading order.
176    pub spans: Spans,
177    /// The boxes the inline elements on the line paint there,
178    /// outermost first. Empty on the ordinary line of a book.
179    pub boxes: Vec<InlineFragment>,
180    /// Advance of the line's glyphs, trailing spaces excluded; a
181    /// hyphenated line's hyphen is charged here even though the glyph
182    /// joins the runs when the structured outpur paints it. What hangs
183    /// past the measure is charged here too, and taken off again by
184    /// `overhang` and `protrusion`.
185    pub width: u32,
186    /// Points the line's last glyph hangs past the measure.
187    pub overhang: f32,
188    /// Points the line's first glyph hangs before the line's origin.
189    pub protrusion: f32,
190    /// The line's vertical geometry — computed here, in points;
191    /// downstream stages position against it, never re-measure.
192    pub box_: LineBox,
193}
194
195impl Line {
196    /// Shaped runs as a line of one span: page furniture, an
197    /// ornament, an initial letter, and anything else set rather
198    /// than broken.
199    pub fn of(runs: Vec<ShapedRun>, box_: LineBox) -> Line {
200        let width = runs.iter().map(|run| run.advance).sum();
201        Line {
202            spans: Spans::One(LineSpan {
203                runs: 0..runs.len(),
204                offset: 0.0,
205                width,
206            }),
207            runs,
208            boxes: Vec::new(),
209            width,
210            overhang: 0.0,
211            protrusion: 0.0,
212            box_,
213        }
214    }
215
216    /// A band with nothing set in it yet.
217    pub(super) fn empty() -> Line {
218        Line {
219            runs: Vec::new(),
220            spans: Spans::Many(Vec::new()),
221            boxes: Vec::new(),
222            width: 0,
223            overhang: 0.0,
224            protrusion: 0.0,
225            box_: LineBox {
226                height: 0.0,
227                baseline: 0.0,
228            },
229        }
230    }
231}
232
233/// Prefix sums over the paragraph's shaped glyphs, in the
234/// paragraph's own font units: the width of any byte range is one
235/// subtraction.
236pub(super) struct Widths {
237    /// Advance of every glyph whose cluster starts before byte `i`.
238    text: Vec<f32>,
239    /// The same for space glyphs alone, which is where the glue is.
240    pub(super) spaces: Vec<f32>,
241    /// Whether a glyph's cluster starts at byte `i`. A break inside
242    /// a cluster would cut a ligature in half and lose it.
243    pub(super) starts: Vec<bool>,
244    /// Tracking charged to the last cluster starting before byte `i`.
245    /// Empty where nothing is tracked, which is most paragraphs.
246    trailing: Vec<f32>,
247    /// The inline boxes a break inside closes and opens again: their
248    /// byte range, their leading edge and their trailing edge, in
249    /// font units. Empty for every paragraph with no cloned box in
250    /// it, which is nearly all of them.
251    cloned: Vec<Cloned>,
252    /// Stretches set as they were written, which take no hyphen. An
253    /// inline code span is one.
254    literal: Vec<Range<usize>>,
255}
256
257/// One inline box that paints all four of its edges on every line it
258/// reaches, from `box-decoration-break: clone`.
259struct Cloned {
260    range: Range<usize>,
261    leading: f32,
262    trailing: f32,
263}
264
265impl Widths {
266    /// Whether a hyphen may be put at byte `at`: not inside a
267    /// cluster, whose glyph belongs to neither half of a break, and
268    /// not inside a stretch set as it was written.
269    pub(super) fn hyphenates(&self, at: usize) -> bool {
270        self.starts[at] && !self.literal.iter().any(|range| range.contains(&at))
271    }
272
273    /// The widths of one flattened paragraph, shaped. `units` takes a
274    /// length in points into the paragraph's own font units, which is
275    /// how an inline box's edges are charged beside the glyphs.
276    pub(super) fn build(flat: &FlatParagraph, shaped: &[ShapedSpan], units: f32) -> Widths {
277        let text = flat.text.as_str();
278        let tracked = shaped.iter().any(|span| span.tracking != 0.0);
279        let mut widths = Widths {
280            text: vec![0.0; text.len() + 1],
281            spaces: vec![0.0; text.len() + 1],
282            starts: vec![false; text.len() + 1],
283            trailing: if tracked {
284                vec![0.0; text.len() + 1]
285            } else {
286                Vec::new()
287            },
288            cloned: flat
289                .boxes
290                .iter()
291                .filter(|span| span.box_.cloned && !span.range.is_empty())
292                .map(|span| Cloned {
293                    range: span.range.clone(),
294                    leading: span.box_.leading() * units,
295                    trailing: span.box_.trailing() * units,
296                })
297                .collect(),
298            literal: flat.literal.clone(),
299        };
300        let bytes = text.as_bytes();
301        for span in shaped {
302            for glyph in &span.glyphs {
303                let at = (span.range.start + glyph.cluster as usize).min(text.len());
304                let advance = glyph.x_advance as f32 * span.scale;
305                widths.text[at] += advance;
306                if bytes.get(at) == Some(&b' ') {
307                    widths.spaces[at] += advance;
308                }
309                widths.starts[at] = true;
310                if tracked {
311                    widths.trailing[at] = span.tracking;
312                }
313            }
314        }
315        // An inline box is width like any other: its leading edge
316        // falls at its first byte and its trailing edge at its last,
317        // so a line that holds either end is charged for it and one
318        // that runs through the middle is charged for neither.
319        for span in &flat.boxes {
320            if span.range.is_empty() {
321                continue;
322            }
323            widths.text[span.range.start] += span.box_.leading() * units;
324            widths.text[span.range.end - 1] += span.box_.trailing() * units;
325        }
326        // Exclusive prefixes: entry `i` totals the glyphs that
327        // start before byte `i`, which is exactly the glyphs on a line
328        // ending there.
329        let (mut text_total, mut space_total, mut track) = (0.0, 0.0, 0.0);
330        for at in 0..widths.text.len() {
331            let (here, space) = (widths.text[at], widths.spaces[at]);
332            widths.text[at] = text_total;
333            widths.spaces[at] = space_total;
334            text_total += here;
335            space_total += space;
336            if tracked {
337                let charged = widths.trailing[at];
338                widths.trailing[at] = track;
339                if widths.starts[at] {
340                    track = charged;
341                }
342            }
343        }
344        widths
345    }
346
347    /// The advance of the glyphs in `[from, to)`, less the tracking
348    /// charged after the last of them: what runs between two letters
349    /// does not run past the last one.
350    pub(super) fn advance(&self, from: usize, to: usize) -> f32 {
351        if to <= from {
352            return 0.0;
353        }
354        self.text[to] - self.text[from] - self.trailing.get(to).copied().unwrap_or(0.0)
355    }
356
357    /// The same for a whole line, with the edges a cloned box closes
358    /// at the break and opens again after it.
359    ///
360    /// A box the line runs into the middle of paints its trailing
361    /// edge at the break, and one the line starts in the middle of
362    /// paints its leading edge at the line's own start. The edges at
363    /// the two true ends of the box are charged by `build`.
364    pub(super) fn line_advance(&self, from: usize, to: usize) -> f32 {
365        let mut width = self.advance(from, to);
366        for cloned in &self.cloned {
367            if from > cloned.range.start && from < cloned.range.end {
368                width += cloned.leading;
369            }
370            if to > cloned.range.start && to < cloned.range.end {
371                width += cloned.trailing;
372            }
373        }
374        width
375    }
376}
377
378/// One band's spans, leaving the buffer to the band after it.
379pub(super) fn gather(spans: &mut Vec<LineSpan>) -> Spans {
380    match spans.len() {
381        1 => Spans::One(spans.pop().expect("a span")),
382        _ => Spans::Many(std::mem::take(spans)),
383    }
384}
385
386/// Slices shaped spans into the runs of one line. `end` is where the
387/// line's paintable text stops: the spaces a break swallows are
388/// already off it.
389///
390/// A run records the text it was shaped from, which is what a
391/// painter that draws characters draws, and beside it what the
392/// author wrote, which is what extraction and copy and paste return.
393pub(super) fn cut_runs(
394    flat: &FlatParagraph,
395    shaped: &[ShapedSpan],
396    start: usize,
397    end: usize,
398) -> Vec<ShapedRun> {
399    let mut runs = Vec::new();
400    let mut trailing = 0i64;
401    for (span, spec) in shaped.iter().zip(flat.spans.iter()) {
402        if span.range.start >= end || span.range.end <= start {
403            continue;
404        }
405        let glyphs = span.glyphs_in(start, end);
406        if glyphs.is_empty() {
407            continue;
408        }
409        let advance = glyphs.iter().map(|g| g.x_advance).sum();
410        let text_start = span.range.start.max(start);
411        let text_end = span.range.end.min(end).max(text_start);
412        trailing = span.track;
413        let (source, source_map) = flat.source_of(text_start..text_end);
414        runs.push(ShapedRun {
415            font_id: spec.font_id,
416            size: spec.size,
417            text: flat.text[text_start..text_end].to_string(),
418            source,
419            source_map,
420            text_start: text_start as u32,
421            // Where the run was written is settled once the
422            // paragraph is broken, by `tile`.
423            origin: None,
424            pseudo_element: None,
425            inline: spec.inline,
426            lead: 0.0,
427            trail: 0.0,
428            features: spec.features.clone(),
429            color: spec.color,
430            decoration: spec.decoration,
431            blend: spec.blend,
432            glyphs,
433            advance,
434        });
435    }
436    // Tracking goes between letters: the line's last glyph keeps its
437    // own advance and nothing more.
438    if trailing != 0
439        && let Some(run) = runs.last_mut()
440    {
441        if let Some(glyph) = run.glyphs.last_mut() {
442            glyph.x_advance = (glyph.x_advance as i64 - trailing).max(0) as u32;
443        }
444        run.advance = run.glyphs.iter().map(|g| g.x_advance).sum();
445    }
446    runs
447}
448
449/// Says where each of a paragraph's runs was written, each range
450/// running on to where the next one starts, so the space a break
451/// swallowed belongs to a run rather than to nothing and the runs
452/// naming one node tile that node's text.
453pub(super) fn tile(lines: &mut [Line], flat: &FlatParagraph) {
454    let starts: Vec<usize> = lines
455        .iter()
456        .flat_map(|line| &line.runs)
457        .map(|run| run.text_start as usize)
458        .collect();
459    let mut ends = starts.iter().skip(1).copied().chain([flat.text.len()]);
460    let mut after = None;
461    for run in lines.iter_mut().flat_map(|line| &mut line.runs) {
462        let to = ends.next().unwrap_or(flat.text.len());
463        run.origin = flat.origin_of(after, run.text_start as usize, to);
464        run.pseudo_element = flat.pseudo_element_of(run.origin.as_ref(), run.text_start as usize);
465        after = run.origin.as_ref().map(|origin| origin.node);
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use crate::lines::testing::layout_body;
472
473    /// A run's glyphs map back to the characters they were shaped
474    /// from: the ffi ligature is one glyph spanning three bytes, and
475    /// the ranges tile the run's text without gaps.
476    #[test]
477    fn glyph_ranges_cover_the_run_text() {
478        let lines = layout_body("difficult", 200.0);
479        let run = &lines[0].runs[0];
480        assert_eq!(run.text, "difficult");
481        let ranges = run.glyph_ranges();
482        assert_eq!(
483            ranges.first().cloned(),
484            Some(0..1),
485            "the first glyph stands for the first byte"
486        );
487        assert!(
488            ranges.iter().any(|r| r.end - r.start == 3),
489            "no glyph spans the three characters of the ffi ligature: {ranges:?}"
490        );
491        assert_eq!(
492            ranges.last().map(|r| r.end),
493            Some(run.text.len() as u32),
494            "the last glyph runs to the end of the run's text"
495        );
496        for pair in ranges.windows(2) {
497            assert!(
498                pair[1].start == pair[0].end || pair[1].start == pair[0].start,
499                "ranges neither tile nor share a cluster: {pair:?}"
500            );
501        }
502    }
503}