Skip to main content

fleuron/layout/
build.rs

1//! Blocks in, fragments out: margins folded together, breaks
2//! settled, lines broken, the initial letter set beside them.
3
4use std::borrow::Cow;
5use std::sync::Arc;
6
7use crate::content::{
8    Block, Inline, NodeId, PseudoElement, Section, SourcePos, block_attributes, block_id,
9    block_position, inline_attributes, inline_id, notes_in_inlines, origin, text,
10};
11use crate::lines::{Line, LineBreakOptions, Measure, Opening, Patterns, Shaped, Span};
12use crate::pages::{DrawItem, PageBox};
13use crate::style::{
14    Break, Clear, ColumnSpan, ComputedStyle, Content, Float, Hyphens, Position, StringPiece,
15    StyleTree, TextAlign, TextJustify,
16};
17
18use super::Paginator;
19use super::cap::Cap;
20use super::flow::Painted;
21use super::fragment::{
22    BreakPoint, Decoration, Decorations, DropCap, Floated, Fragment, Marks, Piece, decoration,
23};
24use super::image::ImageSize;
25use super::note::Note;
26use super::reference::Referring;
27
28impl Paginator<'_> {
29    /// One section's blocks as fragments, in document order:
30    /// everything measurement decides, and nothing pagination does.
31    ///
32    /// A block of the section that spans the columns breaks to the
33    /// whole content box, and one that does not breaks to a column. A
34    /// spanning block moves to the next page whole rather than split
35    /// under the columns above it.
36    pub fn section_fragments(&self, section: &Section) -> Vec<Fragment> {
37        // What was shaped outside a section was written in none.
38        self.lines.take_uncovered();
39        let geometry = self.styles.default_page().geometry;
40        let measure = geometry.measure();
41        let mut builder = Builder::new(self, section.source.as_deref());
42        let style = self.styles.style(section.id).clone();
43        builder.name(section.id);
44        let start = builder.open(section.id, &style, &[], 0.0, measure);
45        let column = style.content_box(0.0, measure);
46        let whole = style.content_box(0.0, geometry.content_size().0);
47        for child in children(self.styles, section.id, &section.blocks, section.position) {
48            builder.spanning = self.styles.style(child.id()).column_span == ColumnSpan::All;
49            let (x, measure) = if builder.spanning { whole } else { column };
50            let first = builder.fragments.len();
51            builder.blocks([child], x, measure);
52            if builder.spanning {
53                for fragment in builder.fragments[first..]
54                    .iter_mut()
55                    .filter(|fragment| !fragment.aside())
56                    .skip(1)
57                {
58                    fragment.break_before = BreakPoint::Forbidden;
59                }
60            }
61        }
62        builder.spanning = false;
63        builder.close(&style, start);
64        let fragments = builder.fragments;
65        self.uncover(section.source.as_deref());
66        fragments
67    }
68}
69
70/// Builds one section's fragments: blocks in, everything the flow
71/// needs to place them out.
72pub(super) struct Builder<'a, 'p> {
73    pub(super) paginator: &'p Paginator<'a>,
74    /// The file the section was read from, for diagnostics.
75    pub(super) source: Option<&'p str>,
76    pub(super) fragments: Vec<Fragment>,
77    /// What the cascade has asked for above the next fragment.
78    pub(super) pending: BreakPoint,
79    /// The floats the next fragment starts below.
80    clear: Clear,
81    /// The collapsible margin standing above the next fragment,
82    /// which is the larger of the margins that met there.
83    pub(super) margin: f32,
84    /// Space above the next fragment that no margin collapses
85    /// through: the borders and padding the blocks around it set.
86    pub(super) fixed: f32,
87    /// What the blocks opened so far have set, waiting for a fragment
88    /// to attach it to a page.
89    pub(super) pending_marks: Option<Box<Marks>>,
90    /// The blocks still open, outermost first.
91    open: Vec<Pending>,
92    /// Whether the block being built spans every column.
93    spanning: bool,
94    /// The layer the block being built paints in. Every block opens
95    /// before it emits anything, so opening one is where this is
96    /// settled.
97    pub(super) layer: i32,
98    /// The sum of the moves of every relative block still open around
99    /// the block being built.
100    offset: (f32, f32),
101    /// The value of `offset` before each open relative block added its
102    /// move, innermost last.
103    moved: Vec<(f32, f32)>,
104    /// How much shows of what the block being built paints, from 0 to
105    /// 1: the `opacity` of every block still open around it, its own
106    /// included, multiplied together.
107    pub(super) opacity: f32,
108    /// The value of `opacity` before each open block multiplied its
109    /// own into it, innermost last.
110    faded: Vec<f32>,
111    /// The block this builder lays out on its own, against the page.
112    /// Its own `position: absolute` does not anchor it a second time.
113    pub(super) lifted: Option<NodeId>,
114    /// How far down the fragments emitted so far reach, space above
115    /// each one included.
116    depth: f32,
117    /// The blocks still open that ask for a height, innermost last.
118    tall: Vec<Tall>,
119}
120
121impl<'a, 'p> Builder<'a, 'p> {
122    /// A builder with nothing built yet, over blocks read from
123    /// `source`.
124    pub(super) fn new(paginator: &'p Paginator<'a>, source: Option<&'p str>) -> Builder<'a, 'p> {
125        Builder {
126            paginator,
127            source,
128            fragments: Vec::new(),
129            pending: BreakPoint::Allowed,
130            clear: Clear::None,
131            margin: 0.0,
132            fixed: 0.0,
133            pending_marks: None,
134            open: Vec::new(),
135            spanning: false,
136            layer: 0,
137            offset: (0.0, 0.0),
138            moved: Vec::new(),
139            opacity: 1.0,
140            faded: Vec::new(),
141            lifted: None,
142            depth: 0.0,
143            tall: Vec::new(),
144        }
145    }
146}
147
148/// One box among the children of an element: a block the manuscript
149/// wrote, or a box that `::before` or `::after` generates.
150#[derive(Debug, Clone, Copy)]
151pub(super) enum Child<'b> {
152    Block(&'b Block),
153    /// A generated box, and where its element was written.
154    Generated(NodeId, Option<SourcePos>),
155}
156
157impl Child<'_> {
158    pub(super) fn id(self) -> NodeId {
159        match self {
160            Child::Block(block) => block_id(block),
161            Child::Generated(id, _) => id,
162        }
163    }
164}
165
166/// The children of the element `id`, written at `position`: the box
167/// `::before` generates, then `blocks`, then the box `::after`
168/// generates.
169pub(super) fn children<'b>(
170    styles: &StyleTree,
171    id: NodeId,
172    blocks: &'b [Block],
173    position: Option<SourcePos>,
174) -> impl Iterator<Item = Child<'b>> + use<'b> {
175    let generated = |which| {
176        styles
177            .pseudo_element(id, which)
178            .map(|id| Child::Generated(id, position))
179    };
180    generated(PseudoElement::Before)
181        .into_iter()
182        .chain(blocks.iter().map(Child::Block))
183        .chain(generated(PseudoElement::After))
184}
185
186/// A block that asks for a height, while its fragments are still being
187/// built.
188struct Tall {
189    /// Where its content box starts, as `depth` counts.
190    top: f32,
191    /// The height `height` gives its content box, which is what a
192    /// percentage inside it measures against. `None` for `auto`.
193    definite: Option<f32>,
194    /// The least height its content box takes.
195    least: f32,
196}
197
198/// A block while its fragments are still being built.
199struct Pending {
200    /// The fragment its first one will be.
201    start: usize,
202    /// What `fixed` stood at when the block's border box opened, and
203    /// what the distance down to its first fragment is measured from.
204    open_fixed: f32,
205    /// Whether anything has been committed above the block's first
206    /// fragment yet. Until something has, a margin committed inside
207    /// the block is one that collapsed through it, and sits above its
208    /// border box rather than inside it.
209    started: bool,
210    decoration: Decoration,
211}
212
213impl Builder<'_, '_> {
214    fn styles(&self) -> &StyleTree {
215        self.paginator.styles
216    }
217
218    /// Folds one `break-before` or `break-after` into what is already
219    /// asked above the next fragment. A forced break outranks an
220    /// avoided one, and either outranks `auto`. A page break outranks
221    /// a column break, being the same break carried further, and a
222    /// break to one side outranks both.
223    pub(super) fn ask(&mut self, wanted: Break) {
224        self.pending = match (self.pending, wanted) {
225            (BreakPoint::Forced(Break::Column), Break::Page)
226            | (BreakPoint::Forced(Break::Column | Break::Page), Break::Side(_)) => {
227                BreakPoint::Forced(wanted)
228            }
229            (BreakPoint::Forced(forced), _) => BreakPoint::Forced(forced),
230            (_, Break::Page) => BreakPoint::Forced(Break::Page),
231            (_, Break::Side(side)) => BreakPoint::Forced(Break::Side(side)),
232            (_, Break::Column) => BreakPoint::Forced(Break::Column),
233            (_, Break::Avoid) => BreakPoint::Forbidden,
234            (pending, Break::Auto) => pending,
235        };
236    }
237
238    /// Opens a block: what it asks for above itself, what it sets for
239    /// the page furniture, the space its top margin leaves, and the
240    /// decoration it paints across `x` and `measure`.
241    ///
242    /// Adjacent margins collapse to the larger. A top border or
243    /// padding is not a margin: it takes height of its own, and the
244    /// margins on either side of it no longer meet.
245    pub(super) fn open(
246        &mut self,
247        node: NodeId,
248        style: &ComputedStyle,
249        inlines: &[Inline],
250        x: f32,
251        measure: f32,
252    ) -> usize {
253        self.ask(style.break_before);
254        if style.clear != Clear::None {
255            self.clear = style.clear;
256        }
257        self.mark(style, inlines);
258        self.layer = style.z_index;
259        if style.position == Position::Relative {
260            // A percentage is a percentage of the page area that the
261            // lines of the section break to.
262            let area = self.styles().default_page().geometry.content_size();
263            let (dx, dy) = style.inset.offset(area);
264            self.moved.push(self.offset);
265            self.offset = (self.offset.0 + dx, self.offset.1 + dy);
266        }
267        self.faded.push(self.opacity);
268        self.opacity *= style.opacity;
269        self.margin = self.margin.max(style.margin.top);
270        let start = self.fragments.len();
271        let border = style.border.widths();
272        let backdrop = self.paginator.backdrop(&style.background);
273        self.open.push(Pending {
274            start,
275            open_fixed: self.fixed,
276            started: false,
277            decoration: decoration(
278                node,
279                style,
280                x,
281                measure,
282                backdrop,
283                (self.offset, self.opacity),
284            ),
285        });
286        if border.top + style.padding.top > 0.0 {
287            let margin = std::mem::take(&mut self.margin);
288            self.commit(margin);
289            self.fixed += border.top + style.padding.top;
290        }
291        if style.sized() {
292            let within = self.tall_within();
293            let definite = style.height.resolve(within);
294            let least = style
295                .min_height
296                .resolve(within)
297                .unwrap_or(0.0)
298                .max(definite.unwrap_or(0.0));
299            self.tall.push(Tall {
300                top: self.depth + self.fixed + self.margin,
301                definite,
302                least,
303            });
304        }
305        start
306    }
307
308    /// The height a percentage height measures against: the nearest
309    /// definite `height` around the block, or the page's content box.
310    fn tall_within(&self) -> f32 {
311        self.tall
312            .iter()
313            .rev()
314            .find_map(|tall| tall.definite)
315            .unwrap_or_else(|| self.styles().default_page().geometry.content_size().1)
316    }
317
318    /// Commits space no margin collapses through. The margin a
319    /// border or padding shuts off is outside every block that has
320    /// not opened a box of its own yet, and inside every block that
321    /// has.
322    fn commit(&mut self, amount: f32) {
323        for pending in self.open.iter_mut().rev() {
324            if pending.started {
325                break;
326            }
327            pending.started = true;
328            pending.open_fixed += amount;
329        }
330        self.fixed += amount;
331    }
332
333    /// Resolves what one element sets — its `string-set` values, the
334    /// folio its page takes — against its own text. It lands on the
335    /// first fragment the element emits, which is the fragment whose
336    /// page the element is on.
337    ///
338    /// An element that emits nothing hands what it set to whatever
339    /// comes next: a string set by an empty heading is still set.
340    fn mark(&mut self, style: &ComputedStyle, inlines: &[Inline]) {
341        if style.string_set.is_empty() && style.counter_reset.is_none() {
342            return;
343        }
344        let mut cached = None;
345        let marks = self.pending_marks.get_or_insert_with(Box::default);
346        for set in &style.string_set {
347            let mut value = String::new();
348            for piece in &set.value {
349                match piece {
350                    StringPiece::Content => {
351                        value.push_str(cached.get_or_insert_with(|| text(inlines)))
352                    }
353                    StringPiece::Text(literal) => value.push_str(literal),
354                }
355            }
356            marks.strings.push((set.name.clone(), value));
357        }
358        if let Some(folio) = style.counter_reset {
359            marks.page_number = Some(folio);
360        }
361    }
362
363    /// Records a node a link can reach. It lands on the first fragment
364    /// the node emits, the way a string it sets does, so the page that
365    /// fragment lands on is the page a reference to the node prints.
366    pub(super) fn name(&mut self, node: NodeId) {
367        let marks = self.pending_marks.get_or_insert_with(Box::default);
368        marks.targets.push(node);
369    }
370
371    /// The same for the inlines of one block: an inline that carries
372    /// an id is a target, and one that sets a string resolves it
373    /// against its own text. Both land on the block's first line.
374    fn name_inlines(&mut self, inlines: &[Inline]) {
375        for inline in inlines {
376            let node = inline_id(inline);
377            if inline_attributes(inline).id.is_some() {
378                self.name(node);
379            }
380            let style = self.styles().style(node);
381            if !style.string_set.is_empty() || style.counter_reset.is_some() {
382                let style = style.clone();
383                self.mark(&style, std::slice::from_ref(inline));
384            }
385            if let Inline::Emphasis { children, .. }
386            | Inline::Strong { children, .. }
387            | Inline::Link { children, .. } = inline
388            {
389                self.name_inlines(children);
390            }
391        }
392    }
393
394    /// Closes a block: `break-inside: avoid` glues everything it
395    /// emitted, its bottom border and padding take height of their
396    /// own, and its bottom margin becomes the next block's lead.
397    pub(super) fn close(&mut self, style: &ComputedStyle, start: usize) {
398        if style.sized() {
399            let tall = self.tall.pop().expect("the block opened a height");
400            let rest = tall.least - (self.depth + self.fixed + self.margin - tall.top);
401            if rest > 0.0 {
402                self.remainder(rest, start);
403            }
404        }
405        if style.break_inside == Break::Avoid {
406            for fragment in self.fragments.iter_mut().skip(start + 1) {
407                fragment.break_before = BreakPoint::Forbidden;
408            }
409        }
410        let border = style.border.widths();
411        if border.bottom + style.padding.bottom > 0.0 {
412            let margin = std::mem::take(&mut self.margin);
413            self.commit(margin);
414            self.fixed += border.bottom + style.padding.bottom;
415        }
416        let pending = self.open.pop().expect("the block opened a box");
417        self.seal(pending);
418        if style.position == Position::Relative
419            && let Some(offset) = self.moved.pop()
420        {
421            self.offset = offset;
422        }
423        if let Some(opacity) = self.faded.pop() {
424            self.opacity = opacity;
425        }
426        self.margin = self.margin.max(style.margin.bottom);
427        // A block that emitted nothing settles nothing: what was
428        // asked above it is still asked above whatever comes next. A
429        // forced break its last block asked for is asked after it too.
430        if self.fragments.len() > start && !matches!(self.pending, BreakPoint::Forced(_)) {
431            self.pending = BreakPoint::Allowed;
432        }
433        self.ask(style.break_after);
434    }
435
436    /// The space a block taller than its content leaves below that
437    /// content, as a fragment of the block. A page does not end
438    /// between the content and the space. A block that emitted nothing
439    /// else takes what was asked above it here.
440    fn remainder(&mut self, rest: f32, start: usize) {
441        let mut blank = Fragment::plain(0.0, rest, Piece::Blank);
442        let mut first = self.fragments[start..].iter().all(Fragment::aside);
443        if !first {
444            blank.break_before = BreakPoint::Forbidden;
445            blank.lead = std::mem::take(&mut self.margin);
446            blank.fixed = std::mem::take(&mut self.fixed);
447        }
448        self.emit(&mut first, blank);
449    }
450
451    /// Hands one block's decoration to the fragments at the ends of
452    /// its range, which is where the paginator reads it back. A block
453    /// that emitted nothing has no range and paints nothing. The
454    /// boxes it wrote against the page are not fragments of it, so
455    /// its range ends at the last fragment the flow places.
456    fn seal(&mut self, pending: Pending) {
457        let Some(last) = self.fragments[pending.start..]
458            .iter()
459            .rposition(|fragment| !fragment.aside())
460        else {
461            return;
462        };
463        let end = pending.start + last + 1;
464        let mut decoration = pending.decoration;
465        // Everything committed since the last fragment was emitted
466        // lies inside the block that fragment was in.
467        decoration.below = self.fixed;
468        // Outermost first, so the paginator's stack pops the
469        // innermost block that ends at a fragment.
470        Builder::decorations(&mut self.fragments[pending.start])
471            .opens
472            .insert(0, decoration);
473        Builder::decorations(&mut self.fragments[end - 1]).closes += 1;
474    }
475
476    fn decorations(fragment: &mut Fragment) -> &mut Decorations {
477        fragment.decorations.get_or_insert_with(Box::default)
478    }
479
480    /// Emits the one fragment a block is: everything the cascade asked
481    /// for above the block goes on it, there being no other fragment
482    /// for it.
483    fn emit_one(&mut self, x: f32, height: f32, piece: Piece) {
484        self.emit(&mut true, Fragment::plain(x, height, piece));
485    }
486
487    /// Emits one fragment. The first of a block gets the break the
488    /// cascade asked for above it and the space its margins left; the
489    /// rest keep what they arrived with, which is what the block says
490    /// about splitting itself.
491    pub(super) fn emit(&mut self, first: &mut bool, mut fragment: Fragment) {
492        // This fragment settles how far the border box of every
493        // block opening on it sits above it.
494        let (index, fixed) = (self.fragments.len(), self.fixed);
495        for pending in &mut self.open {
496            if pending.start == index {
497                pending.decoration.above = fixed - pending.open_fixed;
498            }
499        }
500        if *first {
501            *first = false;
502            fragment.break_before = std::mem::replace(&mut self.pending, BreakPoint::Allowed);
503            fragment.lead = std::mem::take(&mut self.margin);
504            fragment.fixed = std::mem::take(&mut self.fixed);
505            fragment.marks = self.pending_marks.take();
506            fragment.clear = std::mem::replace(&mut self.clear, Clear::None);
507        }
508        fragment.spanning = self.spanning;
509        fragment.layer = self.layer;
510        fragment.offset = self.offset;
511        fragment.opacity = self.opacity;
512        self.depth += fragment.lead + fragment.fixed + fragment.height;
513        self.fragments.push(fragment);
514    }
515
516    /// Marks where an image the sheet lifted out of the flow was
517    /// written. The fragment takes no space. The page the flow
518    /// reaches when it passes here is the page that carries the
519    /// image.
520    ///
521    /// A box against the page is no fragment of the block it was
522    /// written in. A block whose first fragment this would be starts
523    /// at the next fragment instead, so that its border box opens on
524    /// one the flow places.
525    pub(super) fn anchor(&mut self, id: NodeId) {
526        let index = self.fragments.len();
527        for pending in &mut self.open {
528            if pending.start == index {
529                pending.start = index + 1;
530            }
531        }
532        self.fragments
533            .push(Fragment::plain(0.0, 0.0, Piece::Anchor(id)));
534    }
535
536    /// An image floated to one side of the content box at `x` and
537    /// `measure`, sized as a block image is. It takes no height here,
538    /// and the margins that met around it still meet.
539    ///
540    /// A page does not end between the float and what follows it, so
541    /// a float that does not fit moves on with the text beside it.
542    fn float(
543        &mut self,
544        id: NodeId,
545        style: &ComputedStyle,
546        url: &str,
547        origin: String,
548        x: f32,
549        measure: f32,
550    ) {
551        let Some((asset, intrinsic)) = self.paginator.assets.lookup(url) else {
552            self.paginator.missing(url, origin);
553            return;
554        };
555        let within = (measure, self.tall_within());
556        let margin = style.margin;
557        let room = self.styles().default_page().geometry.content_size().1;
558        let ImageSize { width, height, .. } = self.paginator.image_size(
559            style,
560            url,
561            intrinsic.size(),
562            within,
563            (measure - margin.inline()).max(0.0),
564            (room - margin.top - margin.bottom).max(0.0),
565            (!origin.is_empty()).then_some(origin),
566        );
567        let outer = width + margin.inline();
568        let left = match style.float {
569            Float::Right => x + measure - outer,
570            _ => x,
571        };
572        let float = Floated {
573            node: id,
574            side: style.float,
575            asset,
576            x: margin.left,
577            y: margin.top,
578            width,
579            height,
580            outer,
581            blend: style.blend(),
582        };
583        let mut fragment = Fragment::plain(
584            left,
585            height + margin.top + margin.bottom,
586            Piece::Float(Box::new(float)),
587        );
588        self.ask(style.break_before);
589        fragment.break_before = std::mem::replace(&mut self.pending, BreakPoint::Forbidden);
590        self.ask(style.break_after);
591        let index = self.fragments.len();
592        for pending in &mut self.open {
593            if pending.start == index {
594                pending.start = index + 1;
595            }
596        }
597        fragment.spanning = self.spanning;
598        fragment.layer = style.z_index;
599        fragment.offset = self.offset;
600        fragment.opacity = self.opacity * style.opacity;
601        self.fragments.push(fragment);
602    }
603
604    /// Everything built so far, stacked in a box that no page break
605    /// splits. The result holds what the blocks paint, from the top
606    /// and the leading edge of that box, and the height of the box.
607    ///
608    /// A table cell is one of these, and so is a block anchored to
609    /// the page.
610    pub(super) fn stack(mut self) -> Stacked {
611        let mut marks = None;
612        let mut anchors = Vec::new();
613        let mut notes = Vec::new();
614        let mut placed = Vec::new();
615        let mut cursor = 0.0f32;
616        for fragment in &self.fragments {
617            if let Piece::Anchor(node) = fragment.piece {
618                anchors.push(node);
619                continue;
620            }
621            if let Some(held) = &fragment.notes {
622                notes.extend(held.iter().cloned());
623            }
624            gather(&mut marks, fragment.marks.clone());
625            let top = cursor + fragment.lead + fragment.fixed;
626            placed.push((top, fragment));
627            cursor = top + fragment.height;
628        }
629        gather(&mut marks, self.pending_marks.take());
630        let (mut items, boxes) = decorate(&placed);
631        for (top, fragment) in &placed {
632            items.append(&mut self.paginator.fragment_items(fragment, 0.0, *top));
633        }
634        Stacked {
635            items,
636            boxes,
637            height: cursor + self.margin + self.fixed,
638            anchors,
639            notes,
640            marks,
641        }
642    }
643
644    /// Every block of one nesting level, at `x` from the content
645    /// box's leading edge and breaking to `measure`.
646    pub(super) fn blocks<'b>(
647        &mut self,
648        boxes: impl IntoIterator<Item = Child<'b>>,
649        x: f32,
650        measure: f32,
651    ) {
652        for child in boxes {
653            let id = child.id();
654            if let Child::Block(block) = child
655                && (matches!(block, Block::Heading { .. }) || block_attributes(block).id.is_some())
656            {
657                self.name(id);
658            }
659            // A box against the page is not in the flow: it takes no
660            // space here, and the margins that met around it still
661            // meet.
662            if self.lifted != Some(id) && self.styles().style(id).position == Position::Absolute {
663                self.anchor(id);
664                continue;
665            }
666            let block = match child {
667                Child::Block(block) => block,
668                Child::Generated(id, position) => {
669                    self.generated(id, position, x, measure);
670                    continue;
671                }
672            };
673            let styles = self.paginator.styles;
674            let position = block_position(block);
675            match block {
676                Block::Heading { id, inlines, .. } | Block::Paragraph { id, inlines, .. } => {
677                    self.name_inlines(inlines);
678                    self.paragraph(*id, inlines, position, x, measure);
679                }
680                Block::Blockquote { id, blocks, .. } => {
681                    let style = styles.style(*id).clone();
682                    let start = self.open(*id, &style, &[], x, measure);
683                    let (inner, narrowed) = style.content_box(x, measure);
684                    self.blocks(children(styles, *id, blocks, position), inner, narrowed);
685                    self.close(&style, start);
686                }
687                Block::CodeBlock { id, text, .. } => {
688                    self.code_block(*id, text, position, x, measure)
689                }
690                Block::ThematicBreak { id, .. } => {
691                    let style = styles.style(*id).clone();
692                    let start = self.open(*id, &style, &[], x, measure);
693                    let (inner, narrowed) = style.content_box(x, measure);
694                    self.pseudo(*id, PseudoElement::Before, position, inner, narrowed);
695                    self.ornament(&style, x, measure);
696                    self.pseudo(*id, PseudoElement::After, position, inner, narrowed);
697                    self.close(&style, start);
698                }
699                // A break emits nothing of its own, so what it asks
700                // for lands on whatever comes next.
701                Block::PageBreak { id, .. } | Block::ColumnBreak { id, .. } => {
702                    let style = styles.style(*id).clone();
703                    let start = self.open(*id, &style, &[], x, measure);
704                    let (inner, narrowed) = style.content_box(x, measure);
705                    self.pseudo(*id, PseudoElement::Before, position, inner, narrowed);
706                    self.pseudo(*id, PseudoElement::After, position, inner, narrowed);
707                    self.close(&style, start);
708                }
709                Block::Image { id, url, .. } if styles.style(*id).float != Float::None => {
710                    let style = styles.style(*id).clone();
711                    self.float(*id, &style, url, origin(self.source, position), x, measure);
712                }
713                Block::Image { id, url, .. } => {
714                    let style = styles.style(*id).clone();
715                    // The image takes its `height` itself. A scaled
716                    // image would otherwise leave the rest below it.
717                    let boxed = ComputedStyle {
718                        height: crate::style::Width::Auto,
719                        ..style.clone()
720                    };
721                    let start = self.open(*id, &boxed, &[], x, measure);
722                    let (inner, narrowed) = style.content_box(x, measure);
723                    self.pseudo(*id, PseudoElement::Before, position, inner, narrowed);
724                    self.image(&style, url, origin(self.source, position), x, measure);
725                    self.pseudo(*id, PseudoElement::After, position, inner, narrowed);
726                    self.close(&boxed, start);
727                }
728                Block::List {
729                    id,
730                    start,
731                    items,
732                    position,
733                    ..
734                } => self.list(*id, *start, items, *position, x, measure),
735                Block::Table {
736                    id,
737                    head,
738                    body,
739                    position,
740                    ..
741                } => self.table(*id, head, body, *position, x, measure),
742            }
743        }
744    }
745
746    /// One paragraph's lines as fragments: alignment against each
747    /// band, the initial letter beside the first of them, and where a
748    /// page can end between them.
749    ///
750    /// `spec` is the profile the lines were broken to, and `gaps` the
751    /// space above a band the profile had to move past an image.
752    fn paragraph(
753        &mut self,
754        id: NodeId,
755        inlines: &[Inline],
756        position: Option<SourcePos>,
757        x: f32,
758        measure: f32,
759    ) {
760        let computed = self.styles().style(id).clone();
761        let start = self.open(id, &computed, inlines, x, measure);
762        let (x, measure) = computed.content_box(x, measure);
763        self.pseudo(id, PseudoElement::Before, position, x, measure);
764
765        let style = computed.paragraph();
766        let options = self.options(&computed);
767        let cap = self.paginator.drop_cap(id, &computed, inlines);
768        let full = Span::band(0.0, measure);
769        let spec = match &cap {
770            Some((cap, _)) => Measure::new(
771                vec![Span::ending(measure, measure - cap.reserved); cap.lines],
772                full,
773            ),
774            // An indent is a shorter first line. A cap outranks it:
775            // the first line is already displaced, and a book does
776            // not indent the paragraph a chapter opens with.
777            None if computed.text_indent != 0.0 => Measure::new(
778                vec![Span::ending(measure, measure - computed.text_indent)],
779                full,
780            ),
781            None => Measure::uniform(measure),
782        };
783        // The letter the cap holds is passed over below, so a drop
784        // cap and a first line over the same paragraph divide it:
785        // `::first-letter` has the cap, `::first-line` the rest of
786        // the line beside it.
787        let opening = Opening {
788            first_line: self.styles().opening_line(id),
789            taken: cap.as_ref().map_or(0, |(_, taken)| *taken),
790            node: id,
791        };
792        // The notes are built before the lines, because the number
793        // of each is what its reference prints in one of them.
794        let notes: Vec<Arc<Note>> = notes_in_inlines(inlines)
795            .into_iter()
796            .filter_map(|note| self.paginator.note(note, self.source))
797            .collect();
798        let referring = Referring {
799            paginator: self.paginator,
800            source: self.source,
801        };
802        let (broken, shaped) = self
803            .paginator
804            .lines
805            .layout_shaped(inlines, &style, &referring, &spec, options, opening);
806
807        let setting = Setting {
808            x,
809            align: computed.text_align,
810            orphans: computed.orphans as usize,
811            widows: computed.widows as usize,
812            cap: cap.map(|(cap, _)| cap),
813            cap_x: 0.0,
814            notes,
815        };
816        let fragments = set_lines(self.paginator, broken.lines, &spec, &[], &setting);
817        let reflow = shaped.filter(|_| self.paginator.wraps()).map(|shaped| {
818            Arc::new(Reflow {
819                leading: self.paginator.lines.strut(&style).height(),
820                shaped,
821                setting,
822                base: spec,
823                ends: broken.ends,
824            })
825        });
826        let mut first = true;
827        for mut fragment in fragments {
828            fragment.reflow = reflow.clone();
829            self.emit(&mut first, fragment);
830        }
831        self.pseudo(id, PseudoElement::After, position, x, measure);
832        self.close(&computed, start);
833    }
834
835    /// How the lines of a block in `style` break.
836    fn options(&self, style: &ComputedStyle) -> LineBreakOptions {
837        let hyphenate = style.hyphens == Hyphens::Auto;
838        LineBreakOptions {
839            hyphenate,
840            patterns: if hyphenate {
841                self.paginator.patterns()
842            } else {
843                Patterns::NONE
844            },
845            justify: style.text_align == TextAlign::Justify,
846            inter_character: style.text_justify == TextJustify::InterCharacter,
847            hanging: style.hanging_punctuation,
848            preformatted: false,
849        }
850    }
851
852    /// One code block's lines as fragments.
853    ///
854    /// The text breaks at its own newlines and nowhere else. Nothing
855    /// in it hyphenates, no line of it is justified, no mark of it
856    /// hangs past the measure, and its first line carries no indent,
857    /// whatever the cascade asked for around it. A character the
858    /// author did not put where the reader finds it changes what the
859    /// code says.
860    fn code_block(
861        &mut self,
862        id: NodeId,
863        text: &str,
864        position: Option<SourcePos>,
865        x: f32,
866        measure: f32,
867    ) {
868        let computed = self.styles().style(id).clone();
869        let start = self.open(id, &computed, &[], x, measure);
870        let (x, measure) = computed.content_box(x, measure);
871        self.pseudo(id, PseudoElement::Before, position, x, measure);
872
873        let style = computed.paragraph();
874        let options = LineBreakOptions {
875            preformatted: true,
876            ..LineBreakOptions::default()
877        };
878        let spec = Measure::uniform(measure);
879        let lines = self
880            .paginator
881            .lines
882            .layout_preformatted(text, id, position, &style, &spec, options);
883        let over = lines
884            .iter()
885            .any(|line| self.paginator.line_width(line) > measure);
886        if over {
887            let at = origin(self.source, position);
888            let message = concat!(
889                "A line of a code block is wider than the measure. It runs past it, ",
890                "because a code block breaks only where its own text does.",
891            );
892            self.paginator
893                .warn(message.to_string(), (!at.is_empty()).then_some(at));
894        }
895        let setting = Setting {
896            x,
897            align: computed.text_align,
898            orphans: computed.orphans as usize,
899            widows: computed.widows as usize,
900            cap: None,
901            cap_x: 0.0,
902            notes: Vec::new(),
903        };
904        if lines.is_empty() {
905            self.emit_one(x, 0.0, Piece::Blank);
906        }
907        let mut first = true;
908        for fragment in set_lines(self.paginator, lines, &spec, &[], &setting) {
909            self.emit(&mut first, fragment);
910        }
911        self.pseudo(id, PseudoElement::After, position, x, measure);
912        self.close(&computed, start);
913    }
914
915    /// The children of the block `element` that `::before` or
916    /// `::after` generates, at `x` and `measure`. `position` is where
917    /// the block was written.
918    pub(super) fn pseudo(
919        &mut self,
920        element: NodeId,
921        which: PseudoElement,
922        position: Option<SourcePos>,
923        x: f32,
924        measure: f32,
925    ) {
926        let child = self
927            .styles()
928            .pseudo_element(element, which)
929            .map(|id| Child::Generated(id, position));
930        self.blocks(child, x, measure);
931    }
932
933    /// The generated box `id` in the flow, across the content box at
934    /// `x` and `measure`. `position` is where its element was written.
935    /// It holds the text of its `content`, or nothing. A page does not
936    /// end between the box and the rest of its element.
937    fn generated(&mut self, id: NodeId, position: Option<SourcePos>, x: f32, measure: f32) {
938        let Some((_, which)) = id.pseudo_element() else {
939            return;
940        };
941        let mut style = self.styles().style(id).clone();
942        // A box with no layer of its own paints in the layer of its
943        // block.
944        let layer = self.layer;
945        if style.z_index == 0 {
946            style.z_index = layer;
947        }
948        if which == PseudoElement::After {
949            self.ask(Break::Avoid);
950        }
951        let start = self.open(id, &style, &[], x, measure);
952        let (x, measure) = style.content_box(x, measure);
953        let text = self
954            .paginator
955            .generate(&style.content, None, self.source, position)
956            .unwrap_or_default();
957        let spec = Measure::uniform(measure);
958        let lines = if text.is_empty() {
959            Vec::new()
960        } else {
961            let options = self.options(&style);
962            self.paginator
963                .lines
964                .layout_generated(&text, id, &style.paragraph(), &spec, options)
965        };
966        if lines.is_empty() {
967            self.emit_one(x, 0.0, Piece::Blank);
968        } else {
969            let setting = Setting {
970                x,
971                align: style.text_align,
972                orphans: style.orphans as usize,
973                widows: style.widows as usize,
974                cap: None,
975                cap_x: 0.0,
976                notes: Vec::new(),
977            };
978            let mut first = true;
979            for fragment in set_lines(self.paginator, lines, &spec, &[], &setting) {
980                self.emit(&mut first, fragment);
981            }
982        }
983        self.close(&style, start);
984        self.layer = layer;
985        if which == PseudoElement::Before {
986            self.ask(Break::Avoid);
987        }
988    }
989
990    /// A thematic break: the ornament the cascade named, or the space
991    /// it leaves when it names none.
992    fn ornament(&mut self, style: &ComputedStyle, x: f32, measure: f32) {
993        let (x, measure) = style.content_box(x, measure);
994        let paragraph = style.paragraph();
995        let ornament = match &style.content {
996            Content::Text(text) if !text.is_empty() => {
997                self.paginator.line_of(text, &paragraph).map(|line| {
998                    let offset =
999                        align_offset(style.text_align, self.paginator.line_width(&line), measure);
1000                    (offset, line.box_.height, Piece::Line { line, cap: None })
1001                })
1002            }
1003            _ => None,
1004        };
1005        let (offset, height, piece) = ornament.unwrap_or_else(|| {
1006            (
1007                0.0,
1008                self.paginator.lines.strut(&paragraph).height(),
1009                Piece::Blank,
1010            )
1011        });
1012        self.emit_one(x + offset, height, piece);
1013    }
1014
1015    /// A block image, at the size its style and its file ask for,
1016    /// scaled down when that does not fit the page. A percentage width
1017    /// measures against `measure`, the width the image is laid out in.
1018    fn image(&mut self, style: &ComputedStyle, url: &str, origin: String, x: f32, measure: f32) {
1019        let Some((asset, intrinsic)) = self.paginator.assets.lookup(url) else {
1020            self.paginator.missing(url, origin);
1021            return;
1022        };
1023        let within = (measure, self.tall_within());
1024        let (x, measure) = style.content_box(x, measure);
1025        let available = self
1026            .paginator
1027            .styles
1028            .default_page()
1029            .geometry
1030            .content_size()
1031            .1;
1032        let ImageSize { width, height, .. } = self.paginator.image_size(
1033            style,
1034            url,
1035            intrinsic.size_within(measure),
1036            within,
1037            measure,
1038            available,
1039            (!origin.is_empty()).then_some(origin),
1040        );
1041        let offset = align_offset(style.text_align, width, measure);
1042        self.emit_one(
1043            x + offset,
1044            height,
1045            Piece::Image {
1046                width,
1047                height,
1048                asset,
1049                blend: style.blend(),
1050            },
1051        );
1052    }
1053}
1054
1055/// One paragraph's lines as fragments: alignment against each band,
1056/// the initial letter beside the first of them, and where a page may
1057/// end between them.
1058///
1059/// `spec` is the profile the lines were broken to, and `gaps` the
1060/// space above a band the profile had to move past an image.
1061pub(super) fn set_lines(
1062    paginator: &Paginator,
1063    lines: Vec<Line>,
1064    spec: &Measure,
1065    gaps: &[f32],
1066    setting: &Setting,
1067) -> Vec<Fragment> {
1068    let count = lines.len();
1069    let sunk = setting
1070        .cap
1071        .as_ref()
1072        .map(|cap| cap.lines.min(count))
1073        .unwrap_or(0);
1074    // The cap's baseline is the last sunk line's, which is only
1075    // known once the lines are broken.
1076    let drop = if sunk > 0 {
1077        lines[..sunk - 1]
1078            .iter()
1079            .map(|line| line.box_.height)
1080            .sum::<f32>()
1081            + lines[sunk - 1].box_.baseline
1082            - lines[0].box_.baseline
1083    } else {
1084        0.0
1085    };
1086    let mut cap = setting.cap.as_ref().map(|cap| {
1087        Box::new(DropCap {
1088            line: cap.line.clone(),
1089            x: setting.x + setting.cap_x,
1090            drop,
1091        })
1092    });
1093
1094    let mut fragments = Vec::with_capacity(count);
1095    let mut slot = 0;
1096    for (index, mut line) in lines.into_iter().enumerate() {
1097        let last = line.spans.len() - 1;
1098        // A band's slack is at the end of its last span, so that
1099        // is where alignment moves the text.
1100        let offset = align_offset(
1101            setting.align,
1102            paginator.span_width(&line, last),
1103            spec.at(slot + last).width,
1104        );
1105        line.spans[last].offset += offset;
1106        let origin = spec.at(slot).origin;
1107        slot += line.spans.len();
1108        let height = line.box_.height;
1109        let protrusion = line.protrusion;
1110        let notes: Vec<Arc<Note>> = setting
1111            .notes
1112            .iter()
1113            .filter(|note| line.runs.iter().any(|run| run.inline == Some(note.node)))
1114            .cloned()
1115            .collect();
1116        let piece = Piece::Line {
1117            line,
1118            cap: (index == 0).then(|| cap.take()).flatten(),
1119        };
1120        let mut fragment = Fragment::plain(setting.x + origin - protrusion, height, piece);
1121        if !notes.is_empty() {
1122            fragment.notes = Some(Box::new(notes));
1123        }
1124        fragment.break_before =
1125            if index < setting.orphans || count - index < setting.widows || index < sunk {
1126                BreakPoint::Forbidden
1127            } else {
1128                BreakPoint::Allowed
1129            };
1130        fragment.fixed = gaps.get(index).copied().unwrap_or(0.0);
1131        fragments.push(fragment);
1132    }
1133    fragments
1134}
1135
1136/// Moves what the flow reads off the fragments a paragraph arrived as
1137/// onto the ones it was set again as: the paragraph they came out of,
1138/// the space and the break above the first of them, what it tells the
1139/// page furniture, and the decorations that open and close over the
1140/// paragraph.
1141///
1142/// `fixed` is the paragraph's own space above the first of them.
1143pub(super) fn carry_over(fresh: &mut [Fragment], old: &[Fragment], fixed: f32) {
1144    let (Some(head), Some(last)) = (old.first(), old.last()) else {
1145        return;
1146    };
1147    for fragment in fresh.iter_mut() {
1148        fragment.reflow.clone_from(&head.reflow);
1149        fragment.spanning = head.spanning;
1150        fragment.layer = head.layer;
1151        fragment.offset = head.offset;
1152        fragment.opacity = head.opacity;
1153    }
1154    let opens = head
1155        .decorations
1156        .as_ref()
1157        .map(|decorations| decorations.opens.clone())
1158        .unwrap_or_default();
1159    let closes = last
1160        .decorations
1161        .as_ref()
1162        .map(|decorations| decorations.closes)
1163        .unwrap_or(0);
1164    if let Some(first) = fresh.first_mut() {
1165        first.break_before = head.break_before;
1166        first.lead = head.lead;
1167        first.fixed += fixed;
1168        first.marks = head.marks.clone();
1169        first.markers = head.markers.clone();
1170        first.clear = head.clear;
1171        if !opens.is_empty() {
1172            first.decorations = Some(Box::new(Decorations {
1173                opens,
1174                ..Default::default()
1175            }));
1176        }
1177    }
1178    if let Some(end) = fresh.last_mut()
1179        && closes > 0
1180    {
1181        end.decorations.get_or_insert_with(Box::default).closes += closes;
1182    }
1183}
1184
1185/// What one paragraph's lines are set against once they are broken:
1186/// where they start, how they fill a band, and what must not be split
1187/// from what.
1188#[derive(Debug, Clone)]
1189pub(super) struct Setting {
1190    /// Leading edge, from the content box's own.
1191    pub(super) x: f32,
1192    align: TextAlign,
1193    orphans: usize,
1194    widows: usize,
1195    /// The initial letter beside the lines it is sunk over.
1196    pub(super) cap: Option<Cap>,
1197    /// Where the letter goes, from `x`. An image in the way of the
1198    /// bands it is sunk over moves it along with them.
1199    cap_x: f32,
1200    /// The notes written in the paragraph, in reading order. Each one
1201    /// lands on the line its reference was set on, and travels with
1202    /// that line.
1203    notes: Vec<Arc<Note>>,
1204}
1205
1206impl Setting {
1207    /// The same over the bands a profile left. An initial letter
1208    /// belongs to the line a paragraph opens on rather than to the
1209    /// line the rest of it opens on, and an image can move it.
1210    pub(super) fn wrapped(&self, opening: bool, letter: Option<f32>) -> Cow<'_, Setting> {
1211        if opening && letter.is_none() {
1212            return Cow::Borrowed(self);
1213        }
1214        Cow::Owned(Setting {
1215            cap: opening.then(|| self.cap.clone()).flatten(),
1216            cap_x: letter.unwrap_or(0.0),
1217            ..self.clone()
1218        })
1219    }
1220}
1221
1222/// A paragraph the flow can set again.
1223///
1224/// The lines a section is built with are broken against the measure
1225/// with nothing in the way. A paragraph that lands beside an image is
1226/// broken again against the bands the image leaves. This is what that
1227/// takes: the shaped runs, which the measure has no say in, and
1228/// everything settled around them.
1229#[derive(Debug)]
1230pub struct Reflow {
1231    pub(super) shaped: Shaped,
1232    pub(super) setting: Setting,
1233    /// The bands with nothing in the way. A first-line indent and a
1234    /// drop cap are already in them.
1235    pub(super) base: Measure,
1236    /// Height of one band, which is what an image is snapped to.
1237    pub(super) leading: f32,
1238    /// Where each line ended, so the rest of the paragraph can be set
1239    /// from any of them.
1240    pub(super) ends: Vec<usize>,
1241}
1242
1243/// What a stack of blocks comes to.
1244pub(super) struct Stacked {
1245    /// What they paint, from the top of their box.
1246    pub(super) items: Vec<DrawItem>,
1247    /// The border boxes of the blocks, from the top of their box.
1248    pub(super) boxes: Vec<(NodeId, PageBox)>,
1249    /// Their height, margins included.
1250    pub(super) height: f32,
1251    /// The boxes the sheet lifted out of the flow from inside them.
1252    pub(super) anchors: Vec<NodeId>,
1253    /// The notes written inside them, which are set at the foot of
1254    /// the page the stack lands on.
1255    pub(super) notes: Vec<Arc<Note>>,
1256    /// The strings, folios, and targets the blocks give the page
1257    /// furniture.
1258    pub(super) marks: Option<Box<Marks>>,
1259}
1260
1261/// The decorated blocks inside one stack, as the rects they paint. A
1262/// stack is never split, so no box inside it is cut.
1263pub(super) fn decorate(placed: &[(f32, &Fragment)]) -> (Vec<DrawItem>, Vec<(NodeId, PageBox)>) {
1264    let mut boxes: Vec<Painted> = Vec::new();
1265    let mut open: Vec<usize> = Vec::new();
1266    for (top, fragment) in placed {
1267        let Some(decorations) = &fragment.decorations else {
1268            continue;
1269        };
1270        for decoration in &decorations.opens {
1271            open.push(boxes.len());
1272            boxes.push(Painted {
1273                top: top - decoration.above,
1274                decoration: decoration.clone(),
1275                bottom: 0.0,
1276                cut_above: false,
1277                cut_below: false,
1278            });
1279        }
1280        for _ in 0..decorations.closes {
1281            let Some(index) = open.pop() else { continue };
1282            boxes[index].bottom = top + fragment.height + boxes[index].decoration.below;
1283        }
1284    }
1285    // A block the stack does not finish ends at the last fragment of
1286    // it that is here. A note split across two pages is one.
1287    let last = placed
1288        .last()
1289        .map(|(top, fragment)| top + fragment.height)
1290        .unwrap_or(0.0);
1291    for index in open {
1292        boxes[index].bottom = last;
1293        boxes[index].cut_below = true;
1294    }
1295    let mut items = Vec::new();
1296    let mut areas = Vec::new();
1297    for painted in &boxes {
1298        let (x, y, width, height) = painted.border_box((0.0, 0.0));
1299        if height > 0.0 {
1300            let area = PageBox {
1301                page: 0,
1302                x,
1303                y,
1304                width,
1305                height,
1306            };
1307            areas.push((painted.decoration.node, area));
1308        }
1309        items.extend(painted.items((0.0, 0.0)));
1310    }
1311    (items, areas)
1312}
1313
1314/// Adds the marks of one fragment to the marks gathered so far.
1315pub(super) fn gather(into: &mut Option<Box<Marks>>, from: Option<Box<Marks>>) {
1316    let Some(from) = from else {
1317        return;
1318    };
1319    let marks = into.get_or_insert_with(Box::default);
1320    marks.strings.extend(from.strings);
1321    marks.page_number = from.page_number.or(marks.page_number);
1322    marks.targets.extend(from.targets);
1323}
1324
1325/// Where a line of `width` starts inside a measure of `available`.
1326fn align_offset(align: TextAlign, width: f32, available: f32) -> f32 {
1327    match align {
1328        TextAlign::Left | TextAlign::Justify => 0.0,
1329        TextAlign::Right => (available - width).max(0.0),
1330        TextAlign::Center => ((available - width) / 2.0).max(0.0),
1331    }
1332}
1333
1334#[cfg(test)]
1335mod tests {
1336    use crate::content::{Attributes, Block, HeadingLevel, NodeId, Section, SourcePos};
1337    use crate::layout::testing::{
1338        assert_orphans_and_widows, book_of, broken_heading, chapter_size, content_lines,
1339        folio_size, heading, long_prose, master, origin_of, ornament, paginate, paginate_styled,
1340        paragraph, png, prose, quote, rects, registry, right_edge, scene_break, section,
1341        small_caps_lines, styled, tagged_prose, ua, under_h3,
1342    };
1343    use crate::layout::{BreakPoint, Fragment, Paginator, Piece, layout_book};
1344    use crate::pages::{DrawItem, Page, Side};
1345    use crate::style::{Color, Situation};
1346
1347    /// The baseline of the first line of the first page that opens
1348    /// with `token`.
1349    fn baseline_of(pages: &[Page], token: &str) -> f32 {
1350        content_lines(&pages[0])
1351            .into_iter()
1352            .find(|(_, runs)| runs[0].2.starts_with(token))
1353            .map(|(baseline, _)| baseline)
1354            .unwrap_or_else(|| panic!("no line opens with {token}"))
1355    }
1356
1357    /// Acceptance: `h1 { height: 3in }` leaves three inches before the
1358    /// block under it, whatever the heading's own height.
1359    #[test]
1360    fn a_heading_with_a_height_leaves_that_height_before_the_block_under_it() {
1361        let alone = paginate(vec![section(vec![paragraph("under the heading")])]);
1362        let wanted = baseline_of(&alone, "under") + 216.0;
1363        for css in [
1364            "h1 { height: 3in }",
1365            "h1 { height: 3in; font-size: 40pt }",
1366            "h1 { height: 3in; font-size: 9pt }",
1367        ] {
1368            let pages = paginate_styled(
1369                css,
1370                vec![section(vec![
1371                    heading("Tall"),
1372                    paragraph("under the heading"),
1373                ])],
1374            );
1375            let under = baseline_of(&pages, "under");
1376            assert!(
1377                (under - wanted).abs() < 1e-3,
1378                "{css}: the paragraph sits on {under}, not {wanted}"
1379            );
1380        }
1381    }
1382
1383    /// Acceptance: a percentage height resolves against the content box
1384    /// the block is in. For a block of the section that is the page's,
1385    /// and for a paragraph inside a quotation with a height it is the
1386    /// quotation's.
1387    #[test]
1388    fn a_percentage_height_resolves_against_the_content_box_the_block_is_in() {
1389        let (_, area) = ua().default_page().geometry.content_size();
1390        let alone = paginate(vec![section(vec![paragraph("after")])]);
1391        let top = baseline_of(&alone, "after");
1392        let near = |a: f32, b: f32| (a - b).abs() < 1e-3;
1393
1394        let half = paginate_styled(
1395            "h1 { height: 50% }",
1396            vec![section(vec![heading("Half"), paragraph("after")])],
1397        );
1398        assert!(near(baseline_of(&half, "after"), top + area / 2.0));
1399
1400        let nested = paginate_styled(
1401            "blockquote { height: 4in; margin: 0 } blockquote p { height: 50% }",
1402            vec![section(vec![
1403                quote(vec![paragraph("first"), paragraph("second")]),
1404                paragraph("after"),
1405            ])],
1406        );
1407        assert!(near(baseline_of(&nested, "first"), top));
1408        assert!(near(baseline_of(&nested, "second"), top + 144.0));
1409        assert!(near(baseline_of(&nested, "after"), top + 288.0));
1410    }
1411
1412    /// Part: a block taller than its content leaves the remainder below
1413    /// the content, inside its own box. `min-height` does the same for
1414    /// a block whose content is shorter. A block whose content is
1415    /// taller than its height grows to hold it.
1416    #[test]
1417    fn a_block_taller_than_its_content_leaves_the_remainder_below_it() {
1418        use crate::layout::testing::rects;
1419        let sections = || {
1420            vec![section(vec![
1421                quote(vec![paragraph("quoted")]),
1422                paragraph("after"),
1423            ])]
1424        };
1425        let near = |a: f32, b: f32| (a - b).abs() < 1e-3;
1426        let plain = paginate_styled("blockquote { margin: 0 }", sections());
1427        let quoted = baseline_of(&plain, "quoted");
1428
1429        let tall = paginate_styled(
1430            "blockquote { margin: 0; height: 2in; background-color: #eeeeee }",
1431            sections(),
1432        );
1433        assert!(near(baseline_of(&tall, "quoted"), quoted));
1434        assert!(near(baseline_of(&tall, "after"), quoted + 144.0));
1435        let tint = rects(&tall[0]);
1436        assert_eq!(tint.len(), 1, "one box, one tint: {tint:?}");
1437        assert!(near(tint[0].3, 144.0), "the box is {} tall", tint[0].3);
1438
1439        let least = paginate_styled("blockquote { margin: 0; min-height: 2in }", sections());
1440        assert!(near(baseline_of(&least, "after"), quoted + 144.0));
1441
1442        let short = paginate_styled("blockquote { margin: 0; height: 1pt }", sections());
1443        assert_eq!(
1444            baseline_of(&short, "after"),
1445            baseline_of(&plain, "after"),
1446            "a block shorter than its content cut into it"
1447        );
1448    }
1449
1450    /// A block that spans the columns breaks to the whole content
1451    /// box, and the prose around it breaks to one column. Past its
1452    /// first fragment it forbids every break, so it moves whole.
1453    #[test]
1454    fn a_spanning_block_breaks_to_the_content_box() {
1455        let css = "@page { column-count: 2; column-gap: 18pt } \
1456                   blockquote { column-span: all; margin: 0 }";
1457        let quoted = paragraph(&"a quiet sentence of prose ".repeat(18));
1458        let book = book_of(vec![section(vec![prose(), quote(vec![quoted]), prose()])]);
1459        let styles = styled(css, &book);
1460        let paginator = Paginator::new(registry(), &styles);
1461        let geometry = styles.default_page().geometry;
1462        let fragments = paginator.section_fragments(&book.sections[0]);
1463        let widest = |spanning: bool| {
1464            fragments
1465                .iter()
1466                .filter(|fragment| fragment.spanning == spanning)
1467                .filter_map(|fragment| match &fragment.piece {
1468                    Piece::Line { line, .. } => Some(fragment.x + paginator.line_width(line)),
1469                    _ => None,
1470                })
1471                .fold(0.0f32, f32::max)
1472        };
1473        assert!(widest(false) <= geometry.measure() + 1e-3);
1474        assert!(
1475            widest(true) > geometry.measure(),
1476            "the quotation broke to {} in a {} column",
1477            widest(true),
1478            geometry.measure(),
1479        );
1480        assert!(widest(true) <= geometry.content_size().0 + 1e-3);
1481
1482        let spanning: Vec<&Fragment> = fragments.iter().filter(|f| f.spanning).collect();
1483        assert!(
1484            spanning.len() > 2,
1485            "the quotation set {} lines",
1486            spanning.len()
1487        );
1488        assert!(
1489            spanning[1..]
1490                .iter()
1491                .all(|fragment| fragment.break_before == BreakPoint::Forbidden)
1492        );
1493    }
1494
1495    /// Acceptance: `h1 { position: relative; top: -12pt }` raises the
1496    /// heading and leaves the prose under it where it was.
1497    #[test]
1498    fn a_relative_heading_is_raised_and_the_prose_under_it_stays() {
1499        use crate::layout::testing::content_items;
1500        let sections = || vec![section([vec![heading("Raised")], long_prose(3)].concat())];
1501        let plain = paginate(sections());
1502        let raised = paginate_styled("h1 { position: relative; top: -12pt }", sections());
1503        assert_eq!(plain.len(), raised.len(), "the page count moved");
1504        let (plain, raised) = (content_items(&plain[0]), content_items(&raised[0]));
1505        assert_eq!(plain.len(), raised.len());
1506        let mut headings = 0;
1507        for (before, after) in plain.iter().zip(&raised) {
1508            assert_eq!(before.3, after.3, "the runs are painted in another order");
1509            assert_eq!(before.0, after.0, "{:?} moved across", after.3);
1510            if before.2 == chapter_size() {
1511                headings += 1;
1512                assert!(
1513                    (after.1 - (before.1 - 12.0)).abs() < 1e-3,
1514                    "the heading sits at {} rather than 12pt above {}",
1515                    after.1,
1516                    before.1,
1517                );
1518            } else {
1519                assert_eq!(before.1, after.1, "the prose {:?} moved", after.3);
1520            }
1521        }
1522        assert!(headings > 0, "no heading on the first page");
1523    }
1524
1525    /// Part: the engine moves a relative block and its box on every
1526    /// page the block runs over. A percentage is a percentage of the
1527    /// page area. Nothing around the block moves, and the page breaks
1528    /// do not change.
1529    #[test]
1530    fn a_relative_block_moves_its_box_and_its_lines_on_every_page() {
1531        use crate::layout::testing::{content_items, rects};
1532        let sections = || {
1533            vec![section(
1534                [
1535                    long_prose(1),
1536                    vec![quote(vec![paragraph(&"lilliputian ".repeat(500))])],
1537                    long_prose(1),
1538                ]
1539                .concat(),
1540            )]
1541        };
1542        let base = "blockquote { background-color: #eeeeee; box-decoration-break: clone }";
1543        let plain = paginate_styled(base, sections());
1544        let moved = paginate_styled(
1545            &format!("{base} blockquote {{ position: relative; left: 10%; bottom: 6pt }}"),
1546            sections(),
1547        );
1548        let (dx, dy) = (ua().default_page().geometry.content_size().0 * 0.1, -6.0);
1549        assert!(plain.len() > 1, "the quotation fits on one page");
1550        assert_eq!(plain.len(), moved.len(), "the page count moved");
1551        let near = |a: f32, b: f32| (a - b).abs() < 1e-3;
1552        let (mut boxes, mut quoted) = (0, 0);
1553        for (before, after) in plain.iter().zip(&moved) {
1554            let (was, now) = (rects(before), rects(after));
1555            assert_eq!(was.len(), now.len());
1556            for (was, now) in was.iter().zip(&now) {
1557                assert!(
1558                    near(now.0, was.0 + dx) && near(now.1, was.1 + dy),
1559                    "page {}: the box at {was:?} is painted at {now:?}",
1560                    after.number,
1561                );
1562                assert!(near(now.2, was.2) && near(now.3, was.3));
1563                boxes += 1;
1564            }
1565            for (was, now) in content_items(before).iter().zip(content_items(after)) {
1566                if was.3.contains("lilliputian") {
1567                    assert!(near(now.0, was.0 + dx) && near(now.1, was.1 + dy));
1568                    quoted += 1;
1569                } else {
1570                    assert_eq!((was.0, was.1), (now.0, now.1), "{:?} moved", now.3);
1571                }
1572            }
1573        }
1574        assert!(boxes > 1, "the box is painted on {boxes} page(s)");
1575        assert!(quoted > 0);
1576    }
1577
1578    /// Acceptance: no single line of a paragraph is stranded at a
1579    /// page boundary, either end — under the built-in sheet's two and
1580    /// two, and under an author's larger numbers.
1581    #[test]
1582    fn orphans_and_widows_hold_at_every_page_boundary() {
1583        assert_eq!((ua().root().orphans, ua().root().widows), (2, 2));
1584        assert_orphans_and_widows(&paginate(vec![section(tagged_prose(60))]), 2, 2);
1585        let pages = paginate_styled(
1586            "p { orphans: 4; widows: 3 }",
1587            vec![section(tagged_prose(60))],
1588        );
1589        assert_orphans_and_widows(&pages, 4, 3);
1590    }
1591
1592    /// The indent one level of quotation adds under the built-in
1593    /// sheet.
1594    fn quote_indent() -> f32 {
1595        let book = book_of(vec![section(vec![quote(vec![paragraph("quoted")])])]);
1596        let styles = crate::style::defaults(&book, registry());
1597        let node = styles
1598            .nodes()
1599            .iter()
1600            .find(|node| node.element == "blockquote")
1601            .expect("the sample book has a blockquote");
1602        styles.styles()[node.style as usize].margin.left
1603    }
1604
1605    /// Acceptance: a blockquote nested two deep indents twice, and
1606    /// splitting it across a page turn does not lose the indent.
1607    #[test]
1608    fn a_nested_blockquote_indents_twice_and_keeps_it_across_a_page() {
1609        let inner = vec!["inner"; 900].join(" ");
1610        let pages = paginate(vec![section(vec![
1611            paragraph(&"outside the quotation ".repeat(20)),
1612            quote(vec![
1613                paragraph(&"once removed ".repeat(20)),
1614                quote(vec![paragraph(&inner)]),
1615            ]),
1616        ])]);
1617        let indent = quote_indent();
1618        assert!(indent > 0.0, "the sheet indents nothing");
1619
1620        let mut spanned = 0;
1621        for page in &pages {
1622            let (left, _) = origin_of(page);
1623            let mut seen = false;
1624            for (_, runs) in content_lines(page) {
1625                let (x, _, text) = runs[0];
1626                if !text.starts_with("inner") {
1627                    continue;
1628                }
1629                seen = true;
1630                assert!(
1631                    (x - left - 2.0 * indent).abs() < 1e-3,
1632                    "page {}: the nested quote sits at {}, not {}",
1633                    page.number,
1634                    x - left,
1635                    2.0 * indent,
1636                );
1637            }
1638            spanned += seen as usize;
1639        }
1640        assert!(
1641            spanned >= 2,
1642            "the nested quote fitted on {spanned} page(s); nothing was split",
1643        );
1644
1645        // The measure narrows with the indent: every line of the
1646        // nested quote ends inside a box two indents narrower.
1647        let measure = master(Situation::Body(Side::Recto)).geometry.measure();
1648        for page in &pages {
1649            let (left, _) = origin_of(page);
1650            for item in &page.items {
1651                let DrawItem::Text { text, glyphs, .. } = item else {
1652                    continue;
1653                };
1654                if !text.starts_with("inner") {
1655                    continue;
1656                }
1657                for glyph in glyphs {
1658                    assert!(
1659                        glyph.x <= left + measure - indent,
1660                        "page {}: the nested quote runs past its measure",
1661                        page.number,
1662                    );
1663                }
1664            }
1665        }
1666    }
1667
1668    /// `text-indent` sinks the first line of a paragraph and leaves
1669    /// the rest of it at the full measure.
1670    #[test]
1671    fn text_indent_moves_the_first_line_and_nothing_else() {
1672        let indent = 18.0;
1673        let pages = paginate_styled(
1674            &format!("p {{ text-indent: {indent}pt; text-align: left }}"),
1675            vec![section(vec![paragraph(&"a word ".repeat(60))])],
1676        );
1677        let page = pages.first().expect("the paragraph set no pages");
1678        let (left, _) = origin_of(page);
1679        let lines = content_lines(page);
1680        assert!(
1681            lines.len() > 2,
1682            "the paragraph broke into {} line(s)",
1683            lines.len()
1684        );
1685
1686        let (_, first) = &lines[0];
1687        assert!(
1688            (first[0].0 - left - indent).abs() < 1e-3,
1689            "the first line starts at {}, not {indent} in",
1690            first[0].0 - left,
1691        );
1692        for (_, runs) in &lines[1..] {
1693            assert!(
1694                (runs[0].0 - left).abs() < 1e-3,
1695                "a later line starts at {}, not at the margin",
1696                runs[0].0 - left,
1697            );
1698        }
1699
1700        // The indent is taken out of the measure rather than hung
1701        // past it: the first line still ends inside the content box.
1702        let measure = master(Situation::Body(page.side)).geometry.measure();
1703        for item in &page.items {
1704            let DrawItem::Text { glyphs, size, .. } = item else {
1705                continue;
1706            };
1707            if *size == folio_size() {
1708                continue;
1709            }
1710            for glyph in glyphs {
1711                assert!(
1712                    glyph.x <= left + measure,
1713                    "a glyph at {} runs past the measure",
1714                    glyph.x - left,
1715                );
1716            }
1717        }
1718    }
1719
1720    /// The first-line indent the built-in sheet gives ordinary
1721    /// prose: a paragraph with another one above it.
1722    fn prose_indent() -> f32 {
1723        let book = book_of(vec![section(vec![
1724            paragraph("opening"),
1725            paragraph("following"),
1726        ])]);
1727        let styles = crate::style::defaults(&book, registry());
1728        let node = styles
1729            .nodes()
1730            .iter()
1731            .filter(|node| node.element == "p")
1732            .nth(1)
1733            .expect("the sample book has a second paragraph");
1734        styles.styles()[node.style as usize].text_indent
1735    }
1736
1737    /// The computed indent of the `nth` paragraph of a book styled by
1738    /// the built-in sheet alone.
1739    fn indent_of(sections: Vec<Section>, nth: usize) -> f32 {
1740        let book = book_of(sections);
1741        let styles = crate::style::defaults(&book, registry());
1742        let node = styles
1743            .nodes()
1744            .iter()
1745            .filter(|node| node.element == "p")
1746            .nth(nth)
1747            .expect("the book has that many paragraphs");
1748        styles.styles()[node.style as usize].text_indent
1749    }
1750
1751    /// Acceptance: the built-in sheet names the convention. A
1752    /// paragraph following another one indents; the paragraph a
1753    /// chapter opens with and the one a scene break starts again
1754    /// after do not.
1755    #[test]
1756    fn the_built_in_sheet_indents_prose_but_not_an_opening() {
1757        let indent = prose_indent();
1758        assert!(indent > 0.0, "the sheet indents nothing");
1759
1760        // Read off the tree first: an opening paragraph is flush
1761        // whether a heading or nothing at all stands above it.
1762        let words = "my father had a small estate in nottinghamshire ";
1763        let opening = vec![section(vec![
1764            heading("Chapter One"),
1765            paragraph(&words.repeat(4)),
1766            paragraph(&words.repeat(4)),
1767        ])];
1768        assert_eq!(indent_of(opening.clone(), 0), 0.0);
1769        assert_eq!(indent_of(opening, 1), indent);
1770        assert_eq!(
1771            indent_of(vec![section(vec![paragraph("alone")])], 0),
1772            0.0,
1773            "a section opening on prose indented its first paragraph",
1774        );
1775
1776        // And read it off the page: four paragraphs, the first under
1777        // a heading and the third after a scene break.
1778        let tagged = |tag: &str| paragraph(&format!("{tag} {}", words.repeat(3)));
1779        let pages = paginate(vec![section(vec![
1780            heading("Chapter One"),
1781            tagged("alpha"),
1782            tagged("bravo"),
1783            scene_break(),
1784            tagged("charlie"),
1785            tagged("delta"),
1786        ])]);
1787        let page = pages.first().expect("the chapter set no pages");
1788        let (left, _) = origin_of(page);
1789        for (tag, expected) in [
1790            ("alpha", 0.0),
1791            ("bravo", indent),
1792            ("charlie", 0.0),
1793            ("delta", indent),
1794        ] {
1795            let (_, runs) = content_lines(page)
1796                .into_iter()
1797                .find(|(_, runs)| runs[0].2.starts_with(tag))
1798                .unwrap_or_else(|| panic!("no line opens with {tag}"));
1799            assert!(
1800                (runs[0].0 - left - expected).abs() < 1e-3,
1801                "{tag} starts {}pt in, not {expected}pt",
1802                runs[0].0 - left,
1803            );
1804        }
1805    }
1806
1807    /// Acceptance: justification resolves against the shortened
1808    /// first-line measure, so an indented first line still ends
1809    /// flush on the measure's right edge.
1810    #[test]
1811    fn a_justified_first_line_still_ends_on_the_measure() {
1812        let indent = 24.0;
1813        let pages = paginate_styled(
1814            &format!("p {{ text-indent: {indent}pt; text-align: justify }}"),
1815            vec![section(vec![paragraph(
1816                &"my father had a small estate ".repeat(20),
1817            )])],
1818        );
1819        let page = pages.first().expect("the paragraph set no pages");
1820        let (left, _) = origin_of(page);
1821        let measure = master(Situation::Body(page.side)).geometry.measure();
1822        let lines = content_lines(page);
1823        assert!(lines.len() > 2, "not enough lines to justify");
1824
1825        // Every line but the last reaches the right edge, the
1826        // indented first one included: its own edge is the same edge.
1827        for (index, (baseline, _)) in lines.iter().enumerate().take(lines.len() - 1) {
1828            let right = right_edge(page, *baseline);
1829            assert!(
1830                (right - left - measure).abs() < 0.5,
1831                "line {index} ends {}pt in, not on the {measure}pt measure",
1832                right - left,
1833            );
1834        }
1835    }
1836
1837    /// Acceptance: a paragraph split over a page turn indents its
1838    /// first line and nothing else. The continuation opens flush at
1839    /// the top of the next page.
1840    #[test]
1841    fn a_paragraph_broken_across_a_page_indents_once() {
1842        let indent = 18.0;
1843        let pages = paginate_styled(
1844            &format!("p {{ text-indent: {indent}pt; text-align: left }}"),
1845            vec![section(vec![paragraph(
1846                &"my father had a small estate in nottinghamshire ".repeat(220),
1847            )])],
1848        );
1849        assert!(pages.len() > 1, "the paragraph fitted on one page");
1850        let mut indented = 0;
1851        for page in &pages {
1852            let (left, _) = origin_of(page);
1853            for (index, (_, runs)) in content_lines(page).iter().enumerate() {
1854                let start = runs[0].0 - left;
1855                if (start - indent).abs() < 1e-3 {
1856                    assert_eq!(
1857                        (page.number, index),
1858                        (pages[0].number, 0),
1859                        "page {} indented line {index}",
1860                        page.number,
1861                    );
1862                    indented += 1;
1863                } else {
1864                    assert!(
1865                        start.abs() < 1e-3,
1866                        "page {}: line {index} starts {start}pt in",
1867                        page.number,
1868                    );
1869                }
1870            }
1871        }
1872        assert_eq!(indented, 1, "the paragraph indented {indented} lines");
1873    }
1874
1875    /// Acceptance: a quotation indents from its own leading edge,
1876    /// not the page's.
1877    #[test]
1878    fn a_quotes_indent_starts_at_its_own_edge() {
1879        let indent = 9.0;
1880        let margin = quote_indent();
1881        let pages = paginate_styled(
1882            &format!("blockquote p {{ text-indent: {indent}pt; text-align: left }}"),
1883            vec![section(vec![quote(vec![paragraph(
1884                &"quoted prose runs on for a while ".repeat(12),
1885            )])])],
1886        );
1887        let page = pages.first().expect("the quote set no pages");
1888        let (left, _) = origin_of(page);
1889        let lines = content_lines(page);
1890        assert!(
1891            lines.len() > 2,
1892            "the quote broke into {} line(s)",
1893            lines.len()
1894        );
1895        assert!(
1896            (lines[0].1[0].0 - left - margin - indent).abs() < 1e-3,
1897            "the first line starts {}pt in, not {}pt",
1898            lines[0].1[0].0 - left,
1899            margin + indent,
1900        );
1901        for (_, runs) in &lines[1..] {
1902            assert!(
1903                (runs[0].0 - left - margin).abs() < 1e-3,
1904                "a later line starts {}pt in, not at the quote's edge",
1905                runs[0].0 - left,
1906            );
1907        }
1908    }
1909
1910    /// Acceptance: a scene break paints between the paragraphs it
1911    /// separates, centred in the measure, and never lands alone at a
1912    /// page boundary — neither closing a page nor opening one.
1913    #[test]
1914    fn a_scene_break_paints_between_paragraphs_and_never_lands_alone() {
1915        let mark = ornament();
1916        let words = "the drawer of knives was where it had always been and yet ";
1917        let mut blocks = Vec::new();
1918        for index in 0..24 {
1919            if index > 0 {
1920                blocks.push(scene_break());
1921            }
1922            blocks.push(paragraph(&words.repeat(3 + index % 4)));
1923        }
1924        let pages = paginate(vec![section(blocks)]);
1925
1926        let mut painted = 0;
1927        let measure = master(Situation::Body(Side::Recto)).geometry.measure();
1928        for page in &pages {
1929            let lines = content_lines(page);
1930            let marks: Vec<usize> = lines
1931                .iter()
1932                .enumerate()
1933                .filter(|(_, (_, runs))| runs[0].2 == mark)
1934                .map(|(index, _)| index)
1935                .collect();
1936            painted += marks.len();
1937            for index in marks {
1938                assert!(
1939                    index > 0,
1940                    "page {}: a scene break opened the page",
1941                    page.number,
1942                );
1943                assert!(
1944                    index + 1 < lines.len(),
1945                    "page {}: a scene break closed the page",
1946                    page.number,
1947                );
1948                let (left, _) = origin_of(page);
1949                let (x, size, text) = lines[index].1[0];
1950                let width = registry()
1951                    .shape(ua().root().font_id, text)
1952                    .unwrap_or_default()
1953                    .iter()
1954                    .map(|glyph| glyph.x_advance as f32)
1955                    .sum::<f32>()
1956                    / registry()
1957                        .metrics(ua().root().font_id)
1958                        .unwrap()
1959                        .units_per_em as f32
1960                    * size;
1961                assert!(
1962                    (x + width / 2.0 - left - measure / 2.0).abs() < 1e-3,
1963                    "page {}: the ornament is not centred in the measure",
1964                    page.number,
1965                );
1966            }
1967        }
1968        assert_eq!(painted, 23, "every scene break paints exactly once");
1969    }
1970
1971    /// Acceptance: `h1::first-line` styles the text before a hard
1972    /// break in a heading, and the text after the break takes the
1973    /// heading's own style.
1974    #[test]
1975    fn a_first_line_rule_styles_a_heading_as_far_as_its_break() {
1976        let pages = paginate_styled(
1977            "h1 { font-size: 14pt } h1::first-line { font-size: 24pt }",
1978            vec![section(vec![
1979                broken_heading("Chapter One", "The Voyage to Lilliput"),
1980                paragraph("It began."),
1981            ])],
1982        );
1983        let run = |words: &str| {
1984            pages[0]
1985                .items
1986                .iter()
1987                .find_map(|item| match item {
1988                    DrawItem::Text { text, size, y, .. }
1989                        if text.to_lowercase().contains(&words.to_lowercase()) =>
1990                    {
1991                        Some((*size, *y))
1992                    }
1993                    _ => None,
1994                })
1995                .unwrap_or_else(|| panic!("{words:?} is not drawn"))
1996        };
1997        let (opening, top) = run("Chapter One");
1998        let (rest, under) = run("The Voyage");
1999        assert_eq!(opening, 24.0, "the text before the break");
2000        assert_eq!(rest, 14.0, "the text after the break");
2001        assert!(
2002            under > top,
2003            "the text after the break is not on a line under it"
2004        );
2005    }
2006
2007    /// Acceptance: a heading with a hard break reads as one heading to
2008    /// `string-set`. The running head that prints it is one line, with
2009    /// a space where the break was.
2010    #[test]
2011    fn a_heading_with_a_break_sets_one_running_head() {
2012        let pages = paginate_styled(
2013            "h1 { string-set: chapter content() }
2014             @page :left { @top-left { content: string(chapter) } }
2015             @page :right { @top-right { content: string(chapter) } }",
2016            vec![section(vec![
2017                broken_heading("Chapter One", "The Voyage to Lilliput"),
2018                paragraph(&"my father had a small estate in nottinghamshire ".repeat(200)),
2019            ])],
2020        );
2021        assert!(pages.len() > 1, "the chapter fits on one page");
2022        let head: Vec<(String, f32)> = pages[1]
2023            .items
2024            .iter()
2025            .filter_map(|item| match item {
2026                DrawItem::Text { text, y, .. } => Some((text.to_lowercase(), *y)),
2027                _ => None,
2028            })
2029            .filter(|(text, _)| text.contains("chapter") || text.contains("voyage"))
2030            .collect();
2031        assert!(!head.is_empty(), "page 2 has no running head");
2032        assert!(
2033            head.iter().all(|(_, y)| *y == head[0].1),
2034            "the running head is not one line: {head:?}",
2035        );
2036        let printed: String = head.iter().map(|(text, _)| text.as_str()).collect();
2037        assert_eq!(printed, "chapter one the voyage to lilliput");
2038    }
2039
2040    /// Acceptance: `h3 + p::first-line { font-variant-caps:
2041    /// small-caps }` draws the opening line in small capitals and the
2042    /// rest of the paragraph in the letters the author wrote. The
2043    /// change stops at the break the paragraph came to: the last run
2044    /// of the first line is small capitals and the first run of the
2045    /// second is not.
2046    #[test]
2047    fn a_first_line_of_small_capitals_stops_where_the_line_does() {
2048        let prose = "my father had a small estate in nottinghamshire ".repeat(6);
2049        let pages = paginate_styled(
2050            "h3 + p::first-line { font-variant-caps: small-caps }",
2051            under_h3(&prose),
2052        );
2053        let lines = small_caps_lines(&pages[0]);
2054        assert!(lines.len() > 3, "not enough lines to break");
2055
2056        // The heading is the first baseline; the paragraph follows.
2057        let opening = &lines[1].1;
2058        let next = &lines[2].1;
2059        assert!(
2060            opening.iter().all(|(_, small)| *small),
2061            "the opening line is not all small capitals: {opening:?}",
2062        );
2063        assert!(
2064            next.iter().all(|(_, small)| !*small),
2065            "the small capitals ran past the first line: {next:?}",
2066        );
2067        assert!(
2068            lines[3..]
2069                .iter()
2070                .all(|(_, runs)| runs.iter().all(|(_, small)| !*small)),
2071            "the small capitals reached further down the page",
2072        );
2073
2074        // The letters are the ones the author wrote: the face draws
2075        // the capitals, the text does not spell them.
2076        // A break swallows the space it falls on, so the lines join
2077        // back with one between them.
2078        let set = lines[1..]
2079            .iter()
2080            .map(|(_, runs)| runs.iter().map(|(text, _)| *text).collect::<String>())
2081            .collect::<Vec<_>>()
2082            .join(" ");
2083        assert!(
2084            prose.starts_with(set.trim_end()),
2085            "the paragraph was not set as it was written: {set:?}",
2086        );
2087    }
2088
2089    /// Acceptance: an image warning names its url once, so the reader
2090    /// does not read the same name twice on one line.
2091    #[test]
2092    fn an_image_warning_names_its_url_once() {
2093        struct Tall;
2094        impl crate::images::ImageLoader for Tall {
2095            fn load(&self, url: &str) -> Option<Vec<u8>> {
2096                (url == "tall.png").then(|| png(768, 1536))
2097            }
2098        }
2099
2100        let book = book_of(vec![section(vec![Block::Image {
2101            id: NodeId::UNASSIGNED,
2102            url: "tall.png".into(),
2103            alt: "a drawer of knives".into(),
2104            attributes: Attributes::default(),
2105            position: Some(SourcePos { line: 9, column: 1 }),
2106            span: None,
2107        }])]);
2108        let styles = crate::style::defaults(&book, registry());
2109        let assets = crate::images::Assets::probe(&book, &styles, &Tall);
2110        let output = layout_book(&book, &styles, registry(), &assets);
2111
2112        let warning = output
2113            .warnings
2114            .iter()
2115            .find(|warning| warning.message.contains("tall.png"))
2116            .expect("scaling an image to fit is worth saying");
2117        assert_eq!(warning.message.matches("tall.png").count(), 1);
2118        assert!(warning.message.ends_with('.'), "{}", warning.message);
2119        assert!(!warning.message.contains(';'), "{}", warning.message);
2120    }
2121
2122    /// Acceptance: an image taller than the content box is scaled to
2123    /// fit it, keeping its ratio, and the run says so.
2124    #[test]
2125    fn an_image_taller_than_the_content_box_scales_and_warns() {
2126        struct Png;
2127        impl crate::images::ImageLoader for Png {
2128            fn load(&self, url: &str) -> Option<Vec<u8>> {
2129                match url {
2130                    // 8in by 16in at 96dpi: taller than the page.
2131                    "tall.png" => Some(png(768, 1536)),
2132                    // 2in square: it fits as it is.
2133                    "small.png" => Some(png(192, 192)),
2134                    _ => None,
2135                }
2136            }
2137        }
2138
2139        let image = |url: &str| Block::Image {
2140            id: NodeId::UNASSIGNED,
2141            url: url.into(),
2142            alt: "a drawer of knives".into(),
2143            attributes: Attributes::default(),
2144            position: Some(SourcePos { line: 9, column: 1 }),
2145            span: None,
2146        };
2147        let book = book_of(vec![section(vec![
2148            paragraph("before"),
2149            image("tall.png"),
2150            image("small.png"),
2151        ])]);
2152        let styles = crate::style::defaults(&book, registry());
2153        let assets = crate::images::Assets::probe(&book, &styles, &Png);
2154        let output = layout_book(&book, &styles, registry(), &assets);
2155
2156        let placed: Vec<(f32, f32, u32)> = output
2157            .pages
2158            .iter()
2159            .flat_map(|page| page.items.iter())
2160            .filter_map(|item| match item {
2161                DrawItem::Image { w, h, asset, .. } => Some((*w, *h, *asset)),
2162                _ => None,
2163            })
2164            .collect();
2165        assert_eq!(placed.len(), 2, "both images are placed");
2166
2167        let (_, height) = master(Situation::Body(Side::Recto)).geometry.content_size();
2168        let (width, tall, asset) = placed[0];
2169        assert_eq!(asset, 0, "the first image indexes the first asset");
2170        assert!(
2171            (tall - height).abs() < 1e-3,
2172            "the tall image is {tall}pt in a {height}pt box",
2173        );
2174        assert!(
2175            (width / tall - 0.5).abs() < 1e-3,
2176            "scaling did not keep the ratio: {width} by {tall}",
2177        );
2178        // The one that fits keeps its intrinsic size: 2in square.
2179        assert_eq!(placed[1], (144.0, 144.0, 1));
2180
2181        let warning = output
2182            .warnings
2183            .iter()
2184            .find(|warning| warning.message.contains("tall.png"))
2185            .expect("scaling an image to fit is worth saying");
2186        assert!(warning.message.contains("is taller than the page"));
2187        assert_eq!(warning.origin.as_deref(), Some("9:1"));
2188        assert!(
2189            !output
2190                .warnings
2191                .iter()
2192                .any(|w| w.message.contains("small.png")),
2193            "an image that fits is not worth a diagnostic",
2194        );
2195    }
2196
2197    /// `break-before` and `break-after` reach fragmentation from the
2198    /// cascade, and nothing in the paginator hardcodes them: a sheet
2199    /// that turns the page break off runs the chapters together, and
2200    /// one that asks for a side gets the blank page that takes.
2201    #[test]
2202    fn break_control_comes_from_the_cascade() {
2203        let chapters = || {
2204            vec![
2205                section(vec![heading("One"), paragraph("The first chapter.")]),
2206                section(vec![heading("Two"), paragraph("The second chapter.")]),
2207            ]
2208        };
2209        // The built-in sheet opens a chapter on the next page.
2210        assert_eq!(paginate(chapters()).len(), 2);
2211        // The author turns that off and the chapters run together.
2212        assert_eq!(
2213            paginate_styled("section { break-before: auto }", chapters()).len(),
2214            1,
2215        );
2216        // A recto open leaves a blank verso behind it.
2217        let pages = paginate_styled("section { break-before: recto }", chapters());
2218        assert_eq!(pages.len(), 3);
2219        assert!(pages[1].items.is_empty());
2220        // And a verso open leaves the blank recto behind it.
2221        let pages = paginate_styled("section { break-before: verso }", chapters());
2222        assert_eq!(pages.len(), 4);
2223        assert!(pages[0].items.is_empty() || pages[2].items.is_empty());
2224    }
2225
2226    /// `break-inside: avoid` moves a block whole rather than split
2227    /// it, and `break-after: avoid` keeps a heading with the prose
2228    /// under it.
2229    #[test]
2230    fn avoid_keeps_blocks_and_headings_with_what_follows_them() {
2231        // A page of single-line paragraphs, all but a few lines
2232        // full, and then a quotation too long for what is left.
2233        let quoted = "quoted words that would rather not be split across a page turn ";
2234        let filler: Vec<Block> = (0..30)
2235            .map(|index| paragraph(&format!("filler line {index}")))
2236            .collect();
2237        let blocks = [
2238            filler,
2239            vec![quote(vec![paragraph(&quoted.repeat(6))])],
2240            long_prose(2),
2241        ]
2242        .concat();
2243        // A quoted line is one set at the quotation's indent: only
2244        // its first begins with the words the quotation opens with.
2245        let indent = quote_indent();
2246        let split = |css: &str| {
2247            let pages = paginate_styled(css, vec![section(blocks.clone())]);
2248            pages
2249                .iter()
2250                .filter(|page| {
2251                    let (left, _) = origin_of(page);
2252                    content_lines(page)
2253                        .iter()
2254                        .any(|(_, runs)| (runs[0].0 - left - indent).abs() < 1e-3)
2255                })
2256                .count()
2257        };
2258        assert!(split("") >= 2, "the quotation should straddle a page");
2259        assert_eq!(
2260            split("blockquote { break-inside: avoid }"),
2261            1,
2262            "an avoided blockquote should move whole",
2263        );
2264
2265        // A heading is never the last thing on a page: the built-in
2266        // sheet gives it `break-after: avoid`.
2267        let pages = paginate(vec![
2268            section(long_prose(12)),
2269            section([vec![heading("Two")], long_prose(12)].concat()),
2270        ]);
2271        for page in &pages {
2272            let lines = content_lines(page);
2273            if let Some((_, runs)) = lines.last() {
2274                assert!(
2275                    runs[0].1 != chapter_size(),
2276                    "page {}: a heading closed the page",
2277                    page.number,
2278                );
2279            }
2280        }
2281    }
2282
2283    /// An `h4` with the words `value`.
2284    fn h4(value: &str) -> Block {
2285        let Block::Heading { inlines, .. } = heading(value) else {
2286            unreachable!("`heading` makes a heading");
2287        };
2288        Block::Heading {
2289            id: NodeId::UNASSIGNED,
2290            level: HeadingLevel::H4,
2291            inlines,
2292            attributes: Attributes::default(),
2293            position: None,
2294            span: None,
2295        }
2296    }
2297
2298    /// Each content line of a page as the text of its runs, with its
2299    /// baseline, its leading edge and its size.
2300    fn read_lines(page: &Page) -> Vec<(f32, f32, f32, String)> {
2301        content_lines(page)
2302            .into_iter()
2303            .map(|(baseline, runs)| {
2304                let text = runs.iter().map(|run| run.2).collect();
2305                (baseline, runs[0].0, runs[0].1, text)
2306            })
2307            .collect()
2308    }
2309
2310    /// The width of a line of text on the opening page of a chapter.
2311    fn opening_measure() -> f32 {
2312        master(Situation::First(Side::Recto)).geometry.measure()
2313    }
2314
2315    /// Part: a generated box holds the value of `content`, which is a
2316    /// string or nothing.
2317    #[test]
2318    fn a_generated_box_holds_its_string_or_nothing() {
2319        let blocks = || vec![section(vec![paragraph("the paragraph itself")])];
2320        let said = paginate_styled("p::before { content: \"Before it\" }", blocks());
2321        let texts: Vec<String> = read_lines(&said[0])
2322            .into_iter()
2323            .map(|line| line.3)
2324            .collect();
2325        assert_eq!(texts, ["Before it", "the paragraph itself"]);
2326
2327        let bare = paginate(blocks());
2328        let empty = paginate_styled("p::before { content: \"\" }", blocks());
2329        assert_eq!(read_lines(&empty[0]), read_lines(&bare[0]));
2330    }
2331
2332    /// Part: the generated box is a block in the flow, the first or
2333    /// the last child of its element, across the element's content box
2334    /// and in the element's style.
2335    #[test]
2336    fn a_generated_box_is_the_first_or_last_child_of_its_block() {
2337        let pages = paginate_styled(
2338            "blockquote { font-size: 10pt; margin: 0 20pt } \
2339             blockquote::before { content: \"first\" } \
2340             blockquote::after { content: \"last\" }",
2341            vec![section(vec![
2342                quote(vec![paragraph("inside one"), paragraph("inside two")]),
2343                paragraph("outside"),
2344            ])],
2345        );
2346        let lines = read_lines(&pages[0]);
2347        let texts: Vec<&str> = lines.iter().map(|line| line.3.as_str()).collect();
2348        assert_eq!(
2349            texts,
2350            ["first", "inside one", "inside two", "last", "outside"]
2351        );
2352        let (left, _) = origin_of(&pages[0]);
2353        for (_, x, size, text) in [&lines[0], &lines[3]] {
2354            assert!((x - (left + 20.0)).abs() < 1e-3, "{text} starts at {x}");
2355            assert_eq!(*size, 10.0, "{text} is not in the quotation's size");
2356        }
2357    }
2358
2359    /// Part: the generated box takes the box model. Its border box
2360    /// holds its border, its padding and its height, inside its own
2361    /// margins.
2362    #[test]
2363    fn a_generated_box_takes_the_box_model() {
2364        const TINT: Color = Color::rgb(0xee, 0xee, 0xee);
2365        const INK: Color = Color::rgb(0xd6, 0x07, 0x5e);
2366        let blocks = || vec![section(vec![heading("Title"), paragraph("after")])];
2367        let pages = paginate_styled(
2368            "h1::after { content: \"\"; height: 2pt; padding: 3pt 0; \
2369             border-top: 1pt solid #d6075e; margin: 0 12pt; background-color: #eeeeee }",
2370            blocks(),
2371        );
2372        let (left, _) = origin_of(&pages[0]);
2373        let measure = opening_measure();
2374        let boxes = rects(&pages[0]);
2375        let [(x, _, w, h, _)] = boxes
2376            .iter()
2377            .filter(|rect| rect.4 == TINT)
2378            .collect::<Vec<_>>()[..]
2379        else {
2380            panic!("one background: {boxes:?}");
2381        };
2382        assert!((x - (left + 12.0)).abs() < 1e-3, "the box starts at {x}");
2383        assert!((w - (measure - 24.0)).abs() < 1e-3, "the box is {w} wide");
2384        assert!((h - 9.0).abs() < 1e-3, "the box is {h} tall");
2385        assert!(
2386            boxes
2387                .iter()
2388                .any(|rect| rect.4 == INK && (rect.3 - 1.0).abs() < 1e-3),
2389            "no top border: {boxes:?}",
2390        );
2391        let moved = baseline_of(&pages, "after") - baseline_of(&paginate(blocks()), "after");
2392        assert!((moved - 9.0).abs() < 1e-3, "the prose moved {moved}");
2393    }
2394
2395    /// Acceptance: `h4::after { content: ""; height: 2pt;
2396    /// background-color: #d6075e }` draws a rule under every h4, at
2397    /// the width of the heading's content box.
2398    #[test]
2399    fn a_generated_rule_sits_under_every_h4_across_its_content_box() {
2400        const INK: Color = Color::rgb(0xd6, 0x07, 0x5e);
2401        let pages = paginate_styled(
2402            "h4 { margin: 0 20pt; padding: 0 10pt } \
2403             h4::after { content: \"\"; height: 2pt; background-color: #d6075e }",
2404            vec![section(vec![
2405                h4("First"),
2406                paragraph("one"),
2407                h4("Second"),
2408                paragraph("two"),
2409            ])],
2410        );
2411        let page = &pages[0];
2412        let (left, _) = origin_of(page);
2413        let measure = opening_measure();
2414        let lines = read_lines(page);
2415        let rules: Vec<_> = rects(page)
2416            .into_iter()
2417            .filter(|rect| rect.4 == INK)
2418            .collect();
2419        assert_eq!(rules.len(), 2, "{rules:?}");
2420        for ((x, y, w, h, _), title) in rules.iter().zip(["First", "Second"]) {
2421            assert!(
2422                (x - (left + 30.0)).abs() < 1e-3,
2423                "{title}: the rule starts at {x}"
2424            );
2425            assert!(
2426                (w - (measure - 60.0)).abs() < 1e-3,
2427                "{title}: the rule is {w} wide"
2428            );
2429            assert!((h - 2.0).abs() < 1e-3, "{title}: the rule is {h} tall");
2430            let at = lines
2431                .iter()
2432                .position(|line| line.3 == title)
2433                .expect("the heading is set");
2434            assert!(*y > lines[at].0, "{title}: the rule is above the baseline");
2435            assert!(
2436                y + h <= lines[at + 1].0,
2437                "{title}: the rule runs into the prose"
2438            );
2439        }
2440    }
2441
2442    /// Acceptance: `blockquote::before { content: "\201C" }` sets an
2443    /// opening quotation mark before the quote's first line.
2444    #[test]
2445    fn a_generated_quotation_mark_opens_the_quotation() {
2446        let pages = paginate_styled(
2447            "blockquote::before { content: \"\\201C\" }",
2448            vec![section(vec![quote(vec![paragraph("quoted words")])])],
2449        );
2450        let lines = read_lines(&pages[0]);
2451        let texts: Vec<&str> = lines.iter().map(|line| line.3.as_str()).collect();
2452        assert_eq!(texts, ["\u{201C}", "quoted words"]);
2453        let (left, _) = origin_of(&pages[0]);
2454        assert!(
2455            (lines[0].1 - (left + quote_indent())).abs() < 1e-3,
2456            "the mark starts at {}",
2457            lines[0].1,
2458        );
2459    }
2460
2461    /// Acceptance: a generated box takes height in the flow, and the
2462    /// block under it moves down by that height.
2463    #[test]
2464    fn the_block_under_a_generated_box_moves_down_by_its_height() {
2465        let blocks = || vec![section(vec![paragraph("one"), paragraph("two")])];
2466        let bare = paginate(blocks());
2467        let tall = paginate_styled("p::after { content: \"\"; height: 30pt }", blocks());
2468        let moved = baseline_of(&tall, "two") - baseline_of(&bare, "two");
2469        assert!((moved - 30.0).abs() < 1e-3, "the paragraph moved {moved}");
2470    }
2471
2472    /// Acceptance: a page break falling on a generated box keeps it
2473    /// with the element it belongs to. No page opens between a box and
2474    /// its element, so no page opens on a box that `::after` made.
2475    #[test]
2476    fn a_page_break_keeps_a_generated_box_with_its_element() {
2477        let book = book_of(vec![section(vec![paragraph(&"words ".repeat(60))])]);
2478        let fragments = |css: &str| {
2479            let styles = styled(css, &book);
2480            Paginator::new(registry(), &styles).section_fragments(&book.sections[0])
2481        };
2482        let lines = |fragments: &[Fragment]| -> Vec<usize> {
2483            fragments
2484                .iter()
2485                .enumerate()
2486                .filter(|(_, fragment)| matches!(fragment.piece, Piece::Line { .. }))
2487                .map(|(index, _)| index)
2488                .collect()
2489        };
2490        let bare = fragments("");
2491        assert_ne!(bare[lines(&bare)[0]].break_before, BreakPoint::Forbidden);
2492
2493        let boxed =
2494            fragments("p::before { content: \"x\" } p::after { content: \"\"; height: 20pt }");
2495        let at = lines(&boxed);
2496        assert_eq!(
2497            boxed[at[1]].break_before,
2498            BreakPoint::Forbidden,
2499            "the paragraph can leave the box before it",
2500        );
2501        let after = at.last().expect("the paragraph has lines") + 1;
2502        assert!(
2503            after < boxed.len(),
2504            "the box after the paragraph is missing"
2505        );
2506        for fragment in &boxed[after..] {
2507            assert_eq!(
2508                fragment.break_before,
2509                BreakPoint::Forbidden,
2510                "the box after the paragraph can leave it",
2511            );
2512        }
2513
2514        let pages = paginate_styled(
2515            "p { orphans: 1; widows: 1 } \
2516             p::after { content: \"\"; height: 24pt; background-color: #eeeeee }",
2517            vec![section(long_prose(40))],
2518        );
2519        assert!(pages.len() > 2, "the prose fills {} pages", pages.len());
2520        for page in &pages {
2521            let lines = content_lines(page);
2522            for (_, y, ..) in rects(page) {
2523                assert!(
2524                    lines.first().is_some_and(|(baseline, _)| *baseline < y),
2525                    "page {}: a generated box opens the page",
2526                    page.number,
2527                );
2528            }
2529        }
2530    }
2531}