Skip to main content

fleuron/lines/
mod.rs

1//! Line layout: text in, broken lines out.
2//!
3//! Knuth-Plass total fit. A paragraph is flattened into style runs,
4//! shaped, and modelled as boxes, glue and penalties; the breaker
5//! picks the set of breaks with the fewest demerits over the whole
6//! paragraph rather than the most text on each line. The break
7//! source is UAX #14 with word boundaries from UAX #29, plus
8//! optional hyphenation, which enters as a flagged penalty.
9//!
10//! Justified text has its glue stretched or shrunk to the measure
11//! here. The adjustment lands on the glyphs' own advances, so a
12//! painter positions what it is given and never re-derives spacing.
13//! A `Line` is shaped runs: measurement happened here.
14//!
15//! Units: advances come out of the shaper in font units; the measure
16//! arrives in points and converts once, via `units_per_em * size`.
17//!
18//! The stages have a file each: `flatten` makes one string of styled
19//! spans, `shape` turns spans into glyphs, `opportunity` says where a
20//! line may end, `breaker` picks the breaks, `justify` moves the glue
21//! on a line that was set to its measure, and `line` is what comes
22//! out.
23
24use std::cell::RefCell;
25use std::collections::HashSet;
26
27use crate::content::{Inline, SourcePos};
28use crate::fonts::FontRegistry;
29use crate::linebox::{LineBox, Strut};
30use icu_segmenter::{WordSegmenter, options::WordBreakInvariantOptions};
31
32mod breaker;
33mod flatten;
34mod inline;
35mod justify;
36mod line;
37mod measure;
38mod opportunity;
39mod paragraph;
40mod shape;
41
42#[cfg(test)]
43mod testing;
44
45pub use line::{InlineFragment, Line, LineSpan, ShapedRun, Spans};
46pub use measure::{Measure, Span};
47pub use paragraph::{
48    Face, FirstLine, Generated, HangEnd, HangingPunctuation, Inherited, InlineBox, InlineStyles,
49    LineBreakOptions, Opening, ParagraphStyle, Patterns,
50};
51
52use breaker::Breaker;
53use flatten::FlatParagraph;
54use justify::adjust;
55use line::{Widths, cut_runs, gather, tile};
56use paragraph::Lead;
57use shape::ShapedSpan;
58
59/// The layout pass: one paragraph → lines that fit the measure.
60pub struct LineLayout<'a> {
61    registry: &'a FontRegistry,
62    segmenter: WordSegmenterBorrowedStatic,
63    /// The characters shaping found no glyph for, since they were
64    /// last taken.
65    uncovered: RefCell<Found>,
66}
67
68/// A character the face it was set in has no glyph for, where it was
69/// first written.
70#[derive(Debug, Clone, PartialEq)]
71pub(crate) struct Uncovered {
72    pub(crate) character: char,
73    /// The face that has no glyph for it.
74    pub(crate) font_id: u16,
75    /// `None` where the manuscript does not hold the character.
76    pub(crate) position: Option<SourcePos>,
77}
78
79/// The characters with no glyph, each one once, in the order they
80/// were shaped.
81#[derive(Default)]
82struct Found {
83    seen: HashSet<char>,
84    list: Vec<Uncovered>,
85}
86
87/// The borrowed, 'static segmenter `WordSegmenter::new_auto` returns.
88type WordSegmenterBorrowedStatic = icu_segmenter::WordSegmenterBorrowed<'static>;
89
90impl<'a> LineLayout<'a> {
91    /// A layout pass over the faces in `registry`.
92    pub fn new(registry: &'a FontRegistry) -> Self {
93        LineLayout {
94            registry,
95            segmenter: WordSegmenter::new_auto(WordBreakInvariantOptions::default()),
96            uncovered: RefCell::new(Found::default()),
97        }
98    }
99
100    /// Hands over the characters shaping found no glyph for, each
101    /// one once, and starts over.
102    pub(crate) fn take_uncovered(&self) -> Vec<Uncovered> {
103        std::mem::take(&mut *self.uncovered.borrow_mut()).list
104    }
105}
106
107impl LineLayout<'_> {
108    /// The paragraph's strut: the minimum box every one of its lines
109    /// occupies, whatever the runs on it.
110    pub fn strut(&self, style: &ParagraphStyle) -> Strut {
111        self.registry
112            .metrics(style.font_id)
113            .map(|m| Strut::from_metrics(m, style.size, style.line_height))
114            .unwrap_or_default()
115    }
116
117    /// The strut of the line a paragraph opens on. A `line-height`
118    /// on `::first-line` is a multiple of that line's own size, so
119    /// the strut is the opening style's where the rule gave one, and
120    /// the paragraph's own where it did not.
121    pub fn opening_strut(&self, style: &ParagraphStyle, first_line: Option<FirstLine>) -> Strut {
122        match self.opening_style(style, first_line) {
123            Some(opening) => self.strut(&opening),
124            None => self.strut(style),
125        }
126    }
127
128    /// The style the opening line's box is measured in, where
129    /// `::first-line` gave the line a height of its own.
130    fn opening_style(
131        &self,
132        style: &ParagraphStyle,
133        first_line: Option<FirstLine>,
134    ) -> Option<ParagraphStyle> {
135        first_line
136            .filter(|first| first.line_height.is_some())
137            .map(|first| first.over(style, self.registry))
138    }
139
140    /// The box one line occupies: the strut, grown by any run taller
141    /// than it around the shared baseline.
142    pub fn line_box(&self, runs: &[ShapedRun], style: &ParagraphStyle) -> LineBox {
143        let strut = self.strut(style);
144        let mut above = strut.above;
145        let mut below = strut.below;
146        for run in runs {
147            let Some(metrics) = self.registry.metrics(run.font_id) else {
148                continue;
149            };
150            let run_strut = Strut::from_metrics(metrics, run.size, style.line_height);
151            above = above.max(run_strut.above);
152            below = below.max(run_strut.below);
153        }
154        LineBox {
155            baseline: above,
156            height: above + below,
157        }
158    }
159
160    /// Breaks one paragraph into lines of at most `measure_pt`
161    /// points, every inline taking the block's own style.
162    pub fn layout(
163        &self,
164        inlines: &[Inline],
165        style: &ParagraphStyle,
166        measure: impl Into<Measure>,
167        options: LineBreakOptions,
168    ) -> Vec<Line> {
169        self.layout_styled(
170            inlines,
171            style,
172            &Inherited,
173            &measure.into(),
174            options,
175            Opening::default(),
176        )
177    }
178
179    /// The same, with the style tree answering for each inline and
180    /// `opening` saying what sets the line the paragraph opens on
181    /// apart from the rest of it.
182    pub fn layout_styled(
183        &self,
184        inlines: &[Inline],
185        style: &ParagraphStyle,
186        styles: &dyn InlineStyles,
187        measure: &Measure,
188        options: LineBreakOptions,
189        opening: Opening,
190    ) -> Vec<Line> {
191        self.broken(inlines, style, styles, measure, options, opening)
192            .0
193    }
194
195    /// The same, handing back the shaped paragraph beside the lines.
196    ///
197    /// A caller that can break this paragraph again keeps it.
198    /// [`LineLayout::rebreak`] sets the same text to a different
199    /// profile without shaping it twice.
200    pub fn layout_shaped(
201        &self,
202        inlines: &[Inline],
203        style: &ParagraphStyle,
204        styles: &dyn InlineStyles,
205        measure: &Measure,
206        options: LineBreakOptions,
207        opening: Opening,
208    ) -> (Broken, Option<Shaped>) {
209        let (broken, _, shaped) =
210            self.broken_shaped(inlines, style, styles, measure, options, opening);
211        (broken, shaped)
212    }
213
214    /// Breaks a paragraph that was already shaped to `measure`,
215    /// starting from the end of the line `from`, which is `0` for the
216    /// whole of it.
217    ///
218    /// The style over the opening line is not held to the text it
219    /// covered before. The profile decides where the lines end. A
220    /// line pinned to a width it no longer has runs past that width.
221    pub fn rebreak(&self, shaped: &Shaped, measure: &Measure, from: usize) -> Broken {
222        self.break_shaped(shaped, measure, from, None)
223    }
224
225    /// Breaks one paragraph, and how many times the breaker ran.
226    ///
227    /// A first-line style takes two runs. What it sets changes the
228    /// width of the opening run, the width moves where the paragraph
229    /// breaks, and the break decides how much text the opening line
230    /// holds. The first run sets the paragraph's leading run in the
231    /// opening style to the end and breaks the whole of it. The
232    /// second sets as far as the extent that break gave and breaks
233    /// again with the opening line ending there, so the style covers
234    /// the text the line comes to hold. The count is fixed at two,
235    /// because a line count that depended on how long a paragraph
236    /// took to settle would not be deterministic.
237    fn broken(
238        &self,
239        inlines: &[Inline],
240        style: &ParagraphStyle,
241        styles: &dyn InlineStyles,
242        measure: &Measure,
243        options: LineBreakOptions,
244        opening: Opening,
245    ) -> (Vec<Line>, u8) {
246        let (broken, runs, _) =
247            self.broken_shaped(inlines, style, styles, measure, options, opening);
248        (broken.lines, runs)
249    }
250
251    /// The same, handing back what the paragraph was shaped from.
252    fn broken_shaped(
253        &self,
254        inlines: &[Inline],
255        style: &ParagraphStyle,
256        styles: &dyn InlineStyles,
257        measure: &Measure,
258        options: LineBreakOptions,
259        opening: Opening,
260    ) -> (Broken, u8, Option<Shaped>) {
261        let lead = Lead {
262            style: opening.first_line,
263            extent: None,
264            taken: opening.taken,
265            pseudo_element: (opening.first_line.is_some()
266                && opening.node != crate::content::NodeId::UNASSIGNED)
267                .then(|| {
268                    opening
269                        .node
270                        .pseudo(crate::content::PseudoElement::FirstLine)
271                }),
272        };
273        let once = |lead| {
274            let shaped = self.shaped(inlines, style, styles, options, lead);
275            let broken = shaped
276                .as_ref()
277                .map(|shaped| self.break_shaped(shaped, measure, 0, shaped.opening))
278                .unwrap_or_default();
279            (broken, shaped)
280        };
281        let (broken, shaped) = once(lead);
282        if lead.style.is_none() || broken.extent == 0 {
283            return (broken, 1, shaped);
284        }
285        let lead = Lead {
286            extent: Some(broken.extent),
287            ..lead
288        };
289        let (broken, shaped) = once(lead);
290        (broken, 2, shaped)
291    }
292
293    /// One paragraph flattened and shaped, which is everything about
294    /// it that the measure does not decide.
295    ///
296    /// `lead` is the style the paragraph opens in, how far it reaches
297    /// in bytes of that text, and what a drop cap took.
298    fn shaped(
299        &self,
300        inlines: &[Inline],
301        style: &ParagraphStyle,
302        styles: &dyn InlineStyles,
303        options: LineBreakOptions,
304        lead: Lead,
305    ) -> Option<Shaped> {
306        let flat = self.flatten(inlines, style, styles, lead);
307        let mut shaped = self.shape_flat(flat, style, options, lead.extent)?;
308        shaped.opening_style = self.opening_style(style, lead.style);
309        Some(shaped)
310    }
311
312    /// Breaks the text of the generated box `node` into lines of
313    /// `measure`: what `::before` and `::after` generate on a block.
314    pub(crate) fn layout_generated(
315        &self,
316        text: &str,
317        node: crate::content::NodeId,
318        style: &ParagraphStyle,
319        measure: &Measure,
320        options: LineBreakOptions,
321    ) -> Vec<Line> {
322        let flat = self.flatten_generated(text, node, style);
323        self.shape_flat(flat, style, options, None)
324            .map(|shaped| self.break_shaped(&shaped, measure, 0, None).lines)
325            .unwrap_or_default()
326    }
327
328    /// Breaks the preformatted text of `node` into lines: one line per
329    /// newline the author wrote, whatever the measure.
330    ///
331    /// A line wider than the measure runs past it, because there is
332    /// nowhere else for it to end.
333    pub(crate) fn layout_preformatted(
334        &self,
335        text: &str,
336        node: crate::content::NodeId,
337        position: Option<SourcePos>,
338        style: &ParagraphStyle,
339        measure: &Measure,
340        options: LineBreakOptions,
341    ) -> Vec<Line> {
342        let flat = self.flatten_preformatted(text, node, position, style);
343        self.shape_flat(flat, style, options, None)
344            .map(|shaped| self.break_shaped(&shaped, measure, 0, None).lines)
345            .unwrap_or_default()
346    }
347
348    /// One flattened paragraph shaped. `opening` is where the line the
349    /// paragraph opens on has to end.
350    fn shape_flat(
351        &self,
352        flat: flatten::FlatParagraph,
353        style: &ParagraphStyle,
354        options: LineBreakOptions,
355        opening: Option<usize>,
356    ) -> Option<Shaped> {
357        if flat.text.is_empty() {
358            return None;
359        }
360        let upem = self.registry.metrics(style.font_id)?.units_per_em as f32;
361        let spans = self.shape_spans(&flat, style, upem);
362        Some(Shaped {
363            flat,
364            spans,
365            style: style.clone(),
366            options,
367            upem,
368            opening,
369            opening_style: None,
370        })
371    }
372
373    /// Breaks a shaped paragraph to `measure`, starting from the
374    /// break `from`.
375    ///
376    /// `opening` is where the line the paragraph opens on has to end,
377    /// which is the extent of the style over it.
378    fn break_shaped(
379        &self,
380        shaped: &Shaped,
381        measure: &Measure,
382        from: usize,
383        opening: Option<usize>,
384    ) -> Broken {
385        let Shaped {
386            flat,
387            spans,
388            style,
389            options,
390            upem,
391            opening_style,
392            ..
393        } = shaped;
394        let (options, upem) = (*options, *upem);
395        // The line the paragraph opens on is the first one broken
396        // from its start.
397        let boxed = |opens: bool| opening_style.as_ref().filter(|_| opens).unwrap_or(style);
398        // Points → font units: measure / size gives ems, ems *
399        // units_per_em gives font units.
400        let to_points = |units: f32| units / upem * style.size;
401
402        // Points into the paragraph's own font units: what an
403        // inline box's edges are charged in.
404        let units = if style.size > 0.0 {
405            upem / style.size
406        } else {
407            0.0
408        };
409        let widths = Widths::build(flat, spans, units);
410        let hyphen = self.hyphen_advance(style) as f32;
411        let breaks = self.break_points(&flat.text, &widths, hyphen, options);
412        let breaker = Breaker {
413            breaks: &breaks,
414            widths: &widths,
415            measure,
416            rest: measure.at(measure.settled()),
417            settled: measure.settled(),
418            first_band: (0..).find(|slot| measure.at(*slot).ends_band).unwrap_or(0),
419            upem,
420            size: style.size,
421            hyphen,
422            options,
423            from,
424            opening: opening
425                .and_then(|extent| breaks.iter().position(|at| at.content_end == extent)),
426        };
427
428        let mut broken = Broken::default();
429        let mut start = breaks[from.min(breaks.len() - 1)].next;
430        // The band being filled, and where its first span was set:
431        // a span's offset is from there, so a painter handed the
432        // line's leading edge places the rest. One buffer gathers the
433        // spans of every band.
434        let mut band: Option<(Line, f32)> = None;
435        let mut spans = Vec::new();
436        for fit in breaker.run() {
437            let at = &breaks[fit.at];
438            let span = measure.at(fit.slot);
439            if at.content_end > start {
440                let (line, origin) = band.get_or_insert_with(|| {
441                    let mut line = Line::empty();
442                    line.protrusion = to_points(fit.protrusion);
443                    (line, span.origin)
444                });
445                let first = line.runs.len();
446                line.runs
447                    .extend(cut_runs(flat, &shaped.spans, start, at.content_end));
448                adjust(&mut line.runs[first..], &flat.text, fit.ratio, options);
449                if at.hyphen {
450                    self.hyphenate(&mut line.runs, style);
451                }
452                let mut boxes = self.inline_fragments(
453                    flat,
454                    &mut line.runs[first..],
455                    spans.len(),
456                    start..at.content_end,
457                );
458                line.boxes.append(&mut boxes);
459                let offset = span.origin - *origin;
460                let width = line.runs[first..].iter().map(|run| run.advance).sum();
461                spans.push(LineSpan {
462                    runs: first..line.runs.len(),
463                    offset,
464                    width,
465                });
466                line.width += width;
467            }
468            start = at.next;
469            let hard = at.forced && fit.at != breaker.end();
470            if !span.ends_band && !hard {
471                continue;
472            }
473            // A blank line of preformatted text takes a line of its
474            // own, so what the author wrote under it stays where it
475            // was written.
476            if band.is_none() && options.preformatted && hard {
477                spans.push(LineSpan {
478                    runs: 0..0,
479                    offset: 0.0,
480                    width: 0,
481                });
482                band = Some((Line::empty(), span.origin));
483            }
484            let Some((mut line, _)) = band.take() else {
485                continue;
486            };
487            line.overhang = to_points(fit.overhang);
488            let opens = from == 0 && broken.lines.is_empty();
489            line.box_ = self.line_box(&line.runs, boxed(opens));
490            line.spans = gather(&mut spans);
491            if broken.lines.is_empty() {
492                broken.extent = at.content_end;
493            }
494            broken.lines.push(line);
495            broken.ends.push(fit.at);
496        }
497        // A paragraph that ran out inside a band still sets what it
498        // reached.
499        if let Some((mut line, _)) = band.take() {
500            let opens = from == 0 && broken.lines.is_empty();
501            line.box_ = self.line_box(&line.runs, boxed(opens));
502            line.spans = gather(&mut spans);
503            broken.lines.push(line);
504            broken.ends.push(breaker.end());
505        }
506        tile(&mut broken.lines, flat);
507        broken
508    }
509}
510
511/// A paragraph shaped once, and everything about it the measure does
512/// not decide: the flattened text, the runs it shaped into, and the
513/// style and options it was set with.
514///
515/// Shaping is the expensive half of setting a paragraph, and it does
516/// not depend on where the lines end. A caller that can break the
517/// same paragraph again against a different profile keeps this. It
518/// breaks the paragraph through [`LineLayout::rebreak`].
519pub struct Shaped {
520    flat: FlatParagraph,
521    spans: Vec<ShapedSpan>,
522    style: ParagraphStyle,
523    options: LineBreakOptions,
524    upem: f32,
525    /// Where the line the paragraph opens on has to end, when an
526    /// opening style covers exactly that much of the text.
527    opening: Option<usize>,
528    /// The style the opening line's box is measured in, where
529    /// `::first-line` gave the line a height of its own.
530    opening_style: Option<ParagraphStyle>,
531}
532
533impl std::fmt::Debug for Shaped {
534    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
535        f.debug_struct("Shaped")
536            .field("text", &self.flat.text)
537            .finish_non_exhaustive()
538    }
539}
540
541impl Shaped {
542    /// The style the paragraph is set in.
543    pub fn style(&self) -> &ParagraphStyle {
544        &self.style
545    }
546}
547
548/// One paragraph broken into lines: the lines themselves, and where
549/// each of them ended.
550#[derive(Debug, Default)]
551pub struct Broken {
552    /// The lines, in reading order.
553    pub lines: Vec<Line>,
554    /// Where each line ended, as the paragraph counts the places it
555    /// can be broken. A break from the end of a line sets the text
556    /// that line left.
557    pub ends: Vec<usize>,
558    /// Where the first line ended in the shaped text.
559    extent: usize,
560}
561
562#[cfg(test)]
563mod tests {
564    use crate::content::NodeId;
565    use crate::fonts::FaceAttributes;
566    use crate::lines::flatten::SMALL_CAPS_RATIO;
567    use crate::lines::testing::{
568        DISPLAY, OPENING, body, divided_band, drawn, emphasis, layout_body, layout_first,
569        line_text, one_run, registry, two_families, units_per_em, with_breaks,
570    };
571    use crate::lines::{
572        Face, FirstLine, Inherited, InlineStyles, Line, LineBreakOptions, LineLayout, Measure,
573        Opening, ParagraphStyle,
574    };
575    use crate::style::{FontVariantCaps, TextTransform};
576
577    /// The opening line set in `face` and nothing else.
578    fn faced(face: Face) -> Option<FirstLine> {
579        Some(FirstLine {
580            face: Some(face),
581            ..FirstLine::default()
582        })
583    }
584
585    /// The opening line at `line_height`, set at `size` where one is
586    /// given.
587    fn leaded(line_height: f32, size: Option<f32>) -> Option<FirstLine> {
588        Some(FirstLine {
589            line_height: Some(line_height),
590            size,
591            ..FirstLine::default()
592        })
593    }
594
595    /// The cut of the bundled family at one slope and weight.
596    fn cut(italic: bool, weight: u16) -> u16 {
597        registry()
598            .select("eb garamond", FaceAttributes { italic, weight })
599            .expect("the bundled family has cuts")
600            .id
601    }
602
603    /// The face every run of `line` is shaped with, where they agree.
604    fn face_of(line: &Line) -> u16 {
605        let first = line.runs[0].font_id;
606        assert!(
607            line.runs.iter().all(|run| run.font_id == first),
608            "the line is set in more than one face: {:?}",
609            line.runs.iter().map(|run| run.font_id).collect::<Vec<_>>(),
610        );
611        first
612    }
613
614    /// A hard break ends the band it falls in. The text after a break
615    /// in the first span of a divided band opens the band under it,
616    /// not the span beside it.
617    #[test]
618    fn a_hard_break_in_a_divided_band_opens_the_next_band() {
619        let layout = LineLayout::new(registry());
620        let lines = layout.layout(
621            &with_breaks("one\ntwo"),
622            &body(),
623            divided_band(100.0, 20.0),
624            LineBreakOptions::default(),
625        );
626        assert_eq!(drawn(&lines), ["one", "two"]);
627        assert_eq!(lines[0].spans.len(), 1, "{:?}", lines[0].spans);
628        assert_eq!(lines[1].spans[0].offset, 0.0);
629    }
630
631    /// A paragraph shaped once breaks to the same lines as the same
632    /// text shaped and broken together. A break from the end of one
633    /// line sets the text that line left.
634    #[test]
635    fn a_shaped_paragraph_breaks_again_to_the_same_lines() {
636        let layout = LineLayout::new(registry());
637        let measure = Measure::uniform(120.0);
638        let (first, shaped) = layout.layout_shaped(
639            &one_run(OPENING),
640            &body(),
641            &Inherited,
642            &measure,
643            LineBreakOptions::default(),
644            Opening::default(),
645        );
646        let shaped = shaped.expect("the paragraph shaped");
647        let lines = first.lines;
648        assert!(lines.len() > 3, "{} lines is too few to cut", lines.len());
649
650        let again = layout.rebreak(&shaped, &measure, 0);
651        assert_eq!(drawn(&again.lines), drawn(&lines));
652        assert_eq!(again.ends.len(), again.lines.len());
653
654        let tail = layout.rebreak(&shaped, &measure, again.ends[1]);
655        assert_eq!(drawn(&tail.lines), drawn(&lines[2..]));
656    }
657
658    /// The same paragraph broken to a narrower measure holds the same
659    /// words in more lines. No line runs past the measure it was set
660    /// to.
661    #[test]
662    fn a_shaped_paragraph_breaks_again_to_a_narrower_measure() {
663        let layout = LineLayout::new(registry());
664        let (wide, shaped) = layout.layout_shaped(
665            &one_run(OPENING),
666            &body(),
667            &Inherited,
668            &Measure::uniform(200.0),
669            LineBreakOptions::default(),
670            Opening::default(),
671        );
672        let shaped = shaped.expect("the paragraph shaped");
673        let lines = wide.lines;
674        let narrow = Measure::uniform(100.0);
675        let again = layout.rebreak(&shaped, &narrow, 0);
676        assert!(again.lines.len() > lines.len());
677        assert_eq!(
678            drawn(&again.lines).join(" ").replace("  ", " "),
679            drawn(&lines).join(" ").replace("  ", " ")
680        );
681        let upem = units_per_em() as f32;
682        for line in &again.lines {
683            let width = line.width as f32 / upem * body().size;
684            assert!(width <= 100.0 + 0.5, "{width} runs past the measure");
685        }
686    }
687
688    /// Empty paragraph → no lines.
689    #[test]
690    fn empty_paragraph_yields_no_lines() {
691        assert!(layout_body("", 200.0).is_empty());
692    }
693
694    /// A word that fits stays on one line, and its width is the
695    /// shaped advance of exactly its glyphs.
696    #[test]
697    fn short_text_is_one_line() {
698        let lines = layout_body("hello", 200.0);
699        assert_eq!(lines.len(), 1);
700        assert_eq!(line_text(&lines[0]), "hello");
701        let glyph_count: usize = lines[0].runs.iter().map(|r| r.glyphs.len()).sum();
702        assert_eq!(glyph_count, 5);
703    }
704
705    /// Words flow to later lines once the measure overflows; nothing
706    /// is lost and nothing is reordered.
707    #[test]
708    fn text_wraps_and_preserves_every_word() {
709        let text = "one two three four five six seven eight";
710        let lines = layout_body(text, 60.0);
711        assert!(lines.len() >= 2, "expected wrapping, got {lines:?}");
712        let reconstructed: String = lines
713            .iter()
714            .map(|l| line_text(l).trim_end().to_string())
715            .collect::<Vec<_>>()
716            .join(" ");
717        assert_eq!(reconstructed, text);
718    }
719
720    /// A paragraph with only one sensible answer gets it: everything
721    /// that fits on one line stays on it.
722    #[test]
723    fn a_paragraph_with_one_answer_gets_it() {
724        let text = "aa bb cc";
725        let lines = layout_body(text, 100.0);
726        assert_eq!(lines.len(), 1, "everything fits: {lines:?}");
727        let lines = layout_body(text, 30.0);
728        assert_eq!(line_text(&lines[0]), "aa bb");
729    }
730
731    /// A first-line style takes two runs of the breaker and a
732    /// paragraph without one takes a single run, whether or not the
733    /// two runs agree on where the paragraph breaks.
734    #[test]
735    fn a_first_line_style_breaks_the_paragraph_twice() {
736        let layout = LineLayout::new(registry());
737        let inlines = one_run(OPENING);
738        let broken = |first_line| {
739            layout
740                .broken(
741                    &inlines,
742                    &body(),
743                    &Inherited,
744                    &Measure::uniform(160.0),
745                    LineBreakOptions::default(),
746                    Opening {
747                        first_line,
748                        ..Opening::default()
749                    },
750                )
751                .1
752        };
753        assert_eq!(broken(None), 1);
754        assert_eq!(
755            broken(Some(FirstLine {
756                caps: Some(FontVariantCaps::SmallCaps),
757                ..FirstLine::default()
758            })),
759            2,
760        );
761    }
762
763    /// Small capitals on the opening line stop at the break the
764    /// second run chose: the last word of the first line is set in
765    /// them throughout and the first word of the second line is none
766    /// of it. What the author wrote comes back off the runs either
767    /// way.
768    #[test]
769    fn a_first_line_is_small_capitals_as_far_as_the_break() {
770        // The face with no substitutions of its own synthesises its
771        // small capitals, which puts the boundary in the drawn text.
772        let bare = crate::fonts::registry_without_substitutions();
773        let layout = LineLayout::new(&bare);
774        let lines = layout_first(
775            &layout,
776            160.0,
777            Some(FirstLine {
778                caps: Some(FontVariantCaps::SmallCaps),
779                ..FirstLine::default()
780            }),
781        );
782        assert!(lines.len() > 2, "the paragraph did not break");
783
784        let opening = line_text(&lines[0]);
785        let next = line_text(&lines[1]);
786        let last_word = opening.split_whitespace().next_back().expect("a word");
787        let first_word = next.split_whitespace().next().expect("a word");
788        assert_eq!(
789            last_word,
790            last_word.to_uppercase(),
791            "the first line's last word is not small capitals throughout: {opening:?}",
792        );
793        assert_eq!(
794            first_word,
795            first_word.to_lowercase(),
796            "the small capitals ran past the first line: {next:?}",
797        );
798        assert_eq!(opening, opening.to_uppercase());
799        assert_eq!(next, next.to_lowercase());
800        assert!(
801            lines[0]
802                .runs
803                .iter()
804                .any(|run| run.size == body().size * SMALL_CAPS_RATIO),
805            "nothing on the opening line was set at the reduced size",
806        );
807        assert!(
808            lines[1].runs.iter().all(|run| run.size == body().size),
809            "the reduced size reached the second line",
810        );
811
812        // What the author wrote is on the runs beside what was drawn.
813        let written: String = lines[0]
814            .runs
815            .iter()
816            .map(|run| match run.source.is_empty() {
817                true => run.text.as_str(),
818                false => run.source.as_str(),
819            })
820            .collect();
821        assert!(
822            OPENING.starts_with(&written),
823            "the opening line lost the manuscript: {written:?}",
824        );
825    }
826
827    /// Tracking on the opening line is width like any other, so the
828    /// line the paragraph breaks at holds less than it does
829    /// untracked.
830    #[test]
831    fn a_tracked_first_line_breaks_earlier() {
832        let layout = LineLayout::new(registry());
833        let plain = layout_first(&layout, 160.0, None);
834        let tracked = layout_first(
835            &layout,
836            160.0,
837            Some(FirstLine {
838                letter_spacing: Some(0.12 * body().size),
839                ..FirstLine::default()
840            }),
841        );
842        assert!(
843            line_text(&tracked[0]).len() < line_text(&plain[0]).len(),
844            "the tracked line held as much: {:?} against {:?}",
845            line_text(&tracked[0]),
846            line_text(&plain[0]),
847        );
848    }
849
850    /// A first line set larger grows its own line box around the
851    /// baseline the paragraph shares, and leaves the lines under it
852    /// the size they were.
853    #[test]
854    fn a_first_line_set_larger_grows_its_line_box() {
855        let layout = LineLayout::new(registry());
856        let lines = layout_first(
857            &layout,
858            240.0,
859            Some(FirstLine {
860                size: Some(body().size * 1.6),
861                ..FirstLine::default()
862            }),
863        );
864        assert!(lines.len() > 1, "the paragraph did not break");
865        assert!(
866            lines[0].box_.height > lines[1].box_.height,
867            "the opening line did not grow: {:?} against {:?}",
868            lines[0].box_,
869            lines[1].box_,
870        );
871        assert!(
872            lines[0].box_.baseline > lines[1].box_.baseline,
873            "the opening line grew below the baseline alone",
874        );
875        assert_eq!(
876            lines[0].runs[0].size,
877            body().size * 1.6,
878            "the opening run was not set larger",
879        );
880        assert_eq!(lines[1].runs[0].size, body().size);
881    }
882
883    /// Acceptance: a larger line height on the opening line makes
884    /// that line taller around its own baseline, and leaves the lines
885    /// under it the height they were.
886    #[test]
887    fn a_first_line_line_height_makes_its_line_taller() {
888        let layout = LineLayout::new(registry());
889        let plain = layout_first(&layout, 240.0, None);
890        let lines = layout_first(&layout, 240.0, leaded(2.0, None));
891        assert!(lines.len() > 1, "the paragraph did not break");
892        assert!(
893            (lines[0].box_.height - 2.0 * body().size).abs() < 1e-3,
894            "the opening line is {}pt",
895            lines[0].box_.height,
896        );
897        assert!(lines[0].box_.baseline > plain[0].box_.baseline);
898        assert_eq!(
899            lines[1..].iter().map(|line| line.box_).collect::<Vec<_>>(),
900            plain[1..].iter().map(|line| line.box_).collect::<Vec<_>>(),
901            "a line under the opening one moved",
902        );
903    }
904
905    /// Acceptance: a smaller line height on the opening line makes
906    /// that line shorter than the paragraph's own lines.
907    #[test]
908    fn a_first_line_line_height_makes_its_line_shorter() {
909        let layout = LineLayout::new(registry());
910        let lines = layout_first(&layout, 240.0, leaded(1.0, None));
911        assert!(lines.len() > 1, "the paragraph did not break");
912        assert!(
913            (lines[0].box_.height - body().size).abs() < 1e-3,
914            "the opening line is {}pt",
915            lines[0].box_.height,
916        );
917        assert!(lines[0].box_.height < lines[1].box_.height);
918    }
919
920    /// Acceptance: the line height of the opening line multiplies
921    /// the size that line is set in, so a smaller first line under a
922    /// line height of its own is not held to the paragraph's strut.
923    #[test]
924    fn a_first_line_line_height_multiplies_its_own_size() {
925        let layout = LineLayout::new(registry());
926        let lines = layout_first(&layout, 240.0, leaded(2.5, Some(8.0)));
927        assert!(
928            (lines[0].box_.height - 20.0).abs() < 1e-3,
929            "the opening line is {}pt",
930            lines[0].box_.height,
931        );
932        assert_eq!(
933            layout
934                .opening_strut(&body(), leaded(2.5, Some(8.0)))
935                .height(),
936            lines[0].box_.height,
937        );
938    }
939
940    /// Acceptance: a line height on the opening line moves no break.
941    #[test]
942    fn a_first_line_line_height_moves_no_break() {
943        let layout = LineLayout::new(registry());
944        let plain = layout_first(&layout, 160.0, None);
945        let lines = layout_first(&layout, 160.0, leaded(3.0, None));
946        assert!(plain.len() > 2, "the paragraph did not break");
947        assert_eq!(
948            lines.iter().map(line_text).collect::<Vec<_>>(),
949            plain.iter().map(line_text).collect::<Vec<_>>(),
950        );
951    }
952
953    /// Acceptance: `font-style: italic` on the opening line sets it
954    /// in the italic of the family the paragraph is set in, and
955    /// leaves the lines under it upright.
956    #[test]
957    fn an_italic_first_line_is_set_in_the_italic_cut() {
958        let layout = LineLayout::new(registry());
959        let lines = layout_first(
960            &layout,
961            160.0,
962            faced(Face {
963                italic: Some(true),
964                ..Face::default()
965            }),
966        );
967        assert!(lines.len() > 1, "the paragraph did not break");
968        assert_eq!(face_of(&lines[0]), cut(true, 400));
969        assert_eq!(face_of(&lines[1]), body().font_id);
970    }
971
972    /// Acceptance: `font-family` on the opening line sets it in
973    /// another family, and the lines under it keep the paragraph's
974    /// own.
975    #[test]
976    fn a_first_line_takes_another_family() {
977        let registry = two_families();
978        let layout = LineLayout::new(registry);
979        let display = registry
980            .select(DISPLAY, FaceAttributes::REGULAR)
981            .expect("the second family is registered")
982            .id;
983        let lines = layout_first(
984            &layout,
985            160.0,
986            faced(Face {
987                family: Some(display),
988                ..Face::default()
989            }),
990        );
991        assert!(lines.len() > 1, "the paragraph did not break");
992        assert_eq!(face_of(&lines[0]), display);
993        assert_eq!(face_of(&lines[1]), body().font_id);
994    }
995
996    /// Acceptance: `font-weight` on the opening line picks another
997    /// cut of the same family.
998    #[test]
999    fn a_first_line_set_bold_picks_the_bold_cut() {
1000        let layout = LineLayout::new(registry());
1001        let lines = layout_first(
1002            &layout,
1003            160.0,
1004            faced(Face {
1005                weight: Some(700),
1006                ..Face::default()
1007            }),
1008        );
1009        assert!(lines.len() > 1, "the paragraph did not break");
1010        assert_eq!(face_of(&lines[0]), cut(false, 700));
1011        assert_eq!(face_of(&lines[1]), body().font_id);
1012    }
1013
1014    /// What the rule leaves alone an inline element keeps: an italic
1015    /// opening line over an inline element set bold is set in the
1016    /// bold italic, not in the regular one.
1017    #[test]
1018    fn a_face_on_the_first_line_keeps_the_cut_an_inline_element_brought() {
1019        /// A style tree that sets one node bold and everything else
1020        /// as the block is set.
1021        struct Bold(NodeId);
1022        impl InlineStyles for Bold {
1023            fn style(&self, id: NodeId, block: &ParagraphStyle) -> ParagraphStyle {
1024                let font_id = match id == self.0 {
1025                    true => cut(false, 700),
1026                    false => block.font_id,
1027                };
1028                ParagraphStyle {
1029                    font_id,
1030                    ..block.clone()
1031                }
1032            }
1033        }
1034
1035        let bold = NodeId::new(3);
1036        let mut inlines = one_run("she said ");
1037        inlines.push(emphasis(bold, one_run("never")));
1038        let layout = LineLayout::new(registry());
1039        let lines = layout.layout_styled(
1040            &inlines,
1041            &body(),
1042            &Bold(bold),
1043            &Measure::uniform(200.0),
1044            LineBreakOptions::default(),
1045            Opening {
1046                first_line: faced(Face {
1047                    italic: Some(true),
1048                    ..Face::default()
1049                }),
1050                ..Opening::default()
1051            },
1052        );
1053        let faces: Vec<u16> = lines[0].runs.iter().map(|run| run.font_id).collect();
1054        assert_eq!(
1055            faces,
1056            [cut(true, 400), cut(true, 700)],
1057            "{:?}",
1058            lines[0].runs
1059        );
1060    }
1061
1062    /// Acceptance: a face on the opening line re-breaks it. The bold
1063    /// cut is wider, so the line holds less, and the word it dropped
1064    /// opens the line under it.
1065    #[test]
1066    fn a_face_on_the_first_line_rebreaks_it() {
1067        let layout = LineLayout::new(registry());
1068        let plain = layout_first(&layout, 160.0, None);
1069        let bold = layout_first(
1070            &layout,
1071            160.0,
1072            faced(Face {
1073                weight: Some(700),
1074                ..Face::default()
1075            }),
1076        );
1077        assert!(
1078            line_text(&bold[0]).len() < line_text(&plain[0]).len(),
1079            "the bold line held as much: {:?} against {:?}",
1080            line_text(&bold[0]),
1081            line_text(&plain[0]),
1082        );
1083        let dropped = line_text(&plain[0])
1084            .split_whitespace()
1085            .next_back()
1086            .expect("a word")
1087            .to_string();
1088        assert!(
1089            line_text(&bold[1]).starts_with(&dropped),
1090            "the word the opening line dropped did not open the second: {:?}",
1091            line_text(&bold[1]),
1092        );
1093    }
1094
1095    /// `text-transform` on the opening line changes what is shaped
1096    /// and leaves what the author wrote on the run beside it, the way
1097    /// it does on a whole paragraph.
1098    #[test]
1099    fn a_transformed_first_line_keeps_the_manuscript() {
1100        let layout = LineLayout::new(registry());
1101        let lines = layout_first(
1102            &layout,
1103            160.0,
1104            Some(FirstLine {
1105                transform: Some(TextTransform::Uppercase),
1106                ..FirstLine::default()
1107            }),
1108        );
1109        let opening = line_text(&lines[0]);
1110        assert_eq!(opening, opening.to_uppercase());
1111        assert_eq!(line_text(&lines[1]), line_text(&lines[1]).to_lowercase());
1112        let written: String = lines[0]
1113            .runs
1114            .iter()
1115            .map(|run| run.source.as_str())
1116            .collect();
1117        assert!(
1118            OPENING.starts_with(&written) && written == written.to_lowercase(),
1119            "the opening line lost the manuscript: {written:?}",
1120        );
1121    }
1122}