1use 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
59pub struct LineLayout<'a> {
61 registry: &'a FontRegistry,
62 segmenter: WordSegmenterBorrowedStatic,
63 uncovered: RefCell<Found>,
66}
67
68#[derive(Debug, Clone, PartialEq)]
71pub(crate) struct Uncovered {
72 pub(crate) character: char,
73 pub(crate) font_id: u16,
75 pub(crate) position: Option<SourcePos>,
77}
78
79#[derive(Default)]
82struct Found {
83 seen: HashSet<char>,
84 list: Vec<Uncovered>,
85}
86
87type WordSegmenterBorrowedStatic = icu_segmenter::WordSegmenterBorrowed<'static>;
89
90impl<'a> LineLayout<'a> {
91 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 pub(crate) fn take_uncovered(&self) -> Vec<Uncovered> {
103 std::mem::take(&mut *self.uncovered.borrow_mut()).list
104 }
105}
106
107impl LineLayout<'_> {
108 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 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 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 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 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 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 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 pub fn rebreak(&self, shaped: &Shaped, measure: &Measure, from: usize) -> Broken {
222 self.break_shaped(shaped, measure, from, None)
223 }
224
225 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 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 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 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 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 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 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 let boxed = |opens: bool| opening_style.as_ref().filter(|_| opens).unwrap_or(style);
398 let to_points = |units: f32| units / upem * style.size;
401
402 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 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 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 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
511pub struct Shaped {
520 flat: FlatParagraph,
521 spans: Vec<ShapedSpan>,
522 style: ParagraphStyle,
523 options: LineBreakOptions,
524 upem: f32,
525 opening: Option<usize>,
528 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 pub fn style(&self) -> &ParagraphStyle {
544 &self.style
545 }
546}
547
548#[derive(Debug, Default)]
551pub struct Broken {
552 pub lines: Vec<Line>,
554 pub ends: Vec<usize>,
558 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 fn faced(face: Face) -> Option<FirstLine> {
579 Some(FirstLine {
580 face: Some(face),
581 ..FirstLine::default()
582 })
583 }
584
585 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 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 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 #[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 #[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 #[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 #[test]
690 fn empty_paragraph_yields_no_lines() {
691 assert!(layout_body("", 200.0).is_empty());
692 }
693
694 #[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 #[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 #[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 #[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 #[test]
769 fn a_first_line_is_small_capitals_as_far_as_the_break() {
770 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[test]
1018 fn a_face_on_the_first_line_keeps_the_cut_an_inline_element_brought() {
1019 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 #[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 #[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}