Skip to main content

fleuron/
pages.rs

1//! Page output: the display structure.
2//!
3//! The engine's only product. Painters (SVG preview, PDF export) consume
4//! this and never re-derive layout. Coordinates are page units (points),
5//! origin top-left.
6
7use std::ops::Range;
8
9use serde::{Deserialize, Serialize};
10
11use crate::content::{NodeId, SourceRange};
12use crate::fonts::Features;
13use crate::style::{BlendMode, Color, Edges};
14
15/// Which side of the spread a page falls on.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18pub enum Side {
19    /// A right-hand page.
20    Recto,
21    /// A left-hand page.
22    Verso,
23}
24
25impl Side {
26    /// Books open on a right-hand page: odd numbers are recto.
27    pub fn of_number(number: u32) -> Side {
28        if number % 2 == 1 {
29            Side::Recto
30        } else {
31            Side::Verso
32        }
33    }
34}
35
36/// One typeset page: a number, a side, a trim size, and what to
37/// paint on it.
38///
39/// Coordinates are measured from the top left corner of the trim, so
40/// a page with a bleed has items at negative coordinates and past its
41/// width and height. The sheet a printer gets is the trim grown by
42/// `bleed + slug` on every edge.
43#[derive(Debug, PartialEq, Serialize, Deserialize)]
44pub struct Page {
45    /// Folio, counting from 1.
46    pub number: u32,
47    /// Which side of the spread this page falls on.
48    pub side: Side,
49    /// Trimmed page width in points.
50    pub width: f32,
51    /// Trimmed page height in points.
52    pub height: f32,
53    /// How far past the trim the page background reaches, in points,
54    /// on every edge. Art that runs to the edge of the finished page
55    /// runs this far past it, so a cut that drifts still leaves no
56    /// white edge. Zero on a page with no bleed.
57    pub bleed: f32,
58    /// How far past the bleed the sheet reaches, in points, on every
59    /// edge: the room crop marks and registration marks are painted
60    /// in. Zero on a page with no marks.
61    pub slug: f32,
62    /// The sections whose content appears on this page, in the order their
63    /// content appears on it. A chapter that ends mid-page is followed
64    /// there by the next one opening, so the page names both. A blank
65    /// leaf names none.
66    pub sections: Vec<NodeId>,
67    /// What to paint, in paint order: by layer, and inside one layer
68    /// in the order the blocks are written.
69    pub items: Vec<DrawItem>,
70    /// The links set on this page, in the order their text is painted.
71    /// Empty on a page with no link.
72    pub links: Vec<Link>,
73}
74
75impl Page {
76    /// How far the sheet reaches past the trim on every edge: the
77    /// bleed and the slug together.
78    pub fn outset(&self) -> f32 {
79        self.bleed + self.slug
80    }
81
82    /// Puts the page's items in paint order. The sort is stable, so
83    /// one layer keeps the order the flow produced it in.
84    pub(crate) fn sort_by_layer(&mut self) {
85        self.items.sort_by_key(DrawItem::layer);
86    }
87}
88
89/// Where one node's content is set: the folios it runs between, and
90/// the pages of the book those folios are.
91///
92/// `first` and `last` are what a page has printed on it, which is
93/// what a host puts on screen. They are read in reading order rather
94/// than compared, so a book whose page counter restarts still opens
95/// at `first` and a node that fits on one page answers with the same
96/// folio twice.
97///
98/// `at` and `count` are where those pages fall in the book, counting
99/// from 0. A page counter that restarts makes them differ from the
100/// folios, so they are answered rather than left to arithmetic, and
101/// they are the numbers a host fetches the pages by.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
103pub struct Folios {
104    /// The folio the node's content begins on.
105    pub first: u32,
106    /// The folio it ends on.
107    pub last: u32,
108    /// Which page of the book that first folio is, counting from 0.
109    pub at: u32,
110    /// How many pages the node's content runs across, so `at` and
111    /// `count` are every page it is on.
112    pub count: u32,
113}
114
115/// One box on one page, in points, origin top-left.
116#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
117pub struct PageBox {
118    /// Which page of the book the box is on, counting from 0.
119    pub page: u32,
120    /// Left edge.
121    pub x: f32,
122    /// Top edge.
123    pub y: f32,
124    /// Width in points.
125    pub width: f32,
126    /// Height in points.
127    pub height: f32,
128}
129
130impl PageBox {
131    /// Whether a point on the box's page falls inside it.
132    pub fn contains(&self, x: f32, y: f32) -> bool {
133        (self.x..=self.x + self.width).contains(&x) && (self.y..=self.y + self.height).contains(&y)
134    }
135}
136
137/// A single paint operation. Deliberately tiny: text, rules, images,
138/// and the rounded boxes a border radius draws.
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
140pub enum DrawItem {
141    /// A run of shaped glyphs sharing a font, size, and baseline.
142    Text {
143        /// Left edge of the run.
144        x: f32,
145        /// The run's baseline.
146        y: f32,
147        /// Index into `LayoutOutput::fonts`.
148        font_id: u16,
149        /// Em size in points.
150        size: f32,
151        /// How far the run's glyphs advance, in points: the run ends
152        /// at `x + width`.
153        width: f32,
154        /// The text the glyphs were shaped from, which the glyphs'
155        /// ranges index. A painter that draws characters rather than
156        /// glyphs draws these.
157        text: String,
158        /// What the author wrote, where `text-transform` or small
159        /// capitals made that differ from what was shaped, and empty
160        /// where the two are the same. Text extraction and copy and
161        /// paste return this rather than `text`: a title set in
162        /// capitals is read back in the case it was written in.
163        source: String,
164        /// The offset in `source` of every byte boundary of `text`,
165        /// so `source_map[range.start]..source_map[range.end]` is the
166        /// source a glyph stands for. Empty alongside `source`.
167        source_map: Vec<u32>,
168        /// Where the run was written: the content node it was shaped
169        /// from and the bytes of that node's own text it stands for.
170        /// The runs that name one node tile it, so a cursor in the
171        /// manuscript lands on a run and a run lands back on the
172        /// manuscript. The text of `::before` and `::after` names the
173        /// id of that pseudo-element. Absent on text the engine adds
174        /// to the book: a folio, a running head, a scene break's
175        /// ornament, and a table's header row set again on a later
176        /// page.
177        origin: Option<SourceRange>,
178        /// The pseudo-element the run was cut from: a drop cap, the
179        /// line a paragraph opens on, or the text of `::before` or
180        /// `::after`. `origin` still names the text it stands for.
181        pseudo_element: Option<NodeId>,
182        /// The features the run was shaped with. A painter that draws
183        /// characters asks the face for these; one that draws glyphs
184        /// has the answer already.
185        features: Features,
186        /// What the glyphs are painted in.
187        color: Color,
188        /// The glyphs, in visual order.
189        glyphs: Vec<Glyph>,
190        /// Which layer the run paints in.
191        layer: i32,
192        /// How the run is mixed with what is already painted
193        /// under it.
194        blend: BlendMode,
195    },
196    /// Filled rectangle: rules, borders, backgrounds.
197    Rect {
198        /// Left edge.
199        x: f32,
200        /// Top edge.
201        y: f32,
202        /// Width in points.
203        w: f32,
204        /// Height in points.
205        h: f32,
206        /// What the rectangle is filled with.
207        color: Color,
208        /// Which layer the rectangle paints in.
209        layer: i32,
210        /// How the rectangle is mixed with what is already painted
211        /// under it.
212        blend: BlendMode,
213    },
214    /// Placed image; `asset` indexes the asset table.
215    Image {
216        /// Left edge.
217        x: f32,
218        /// Top edge.
219        y: f32,
220        /// Width in points.
221        w: f32,
222        /// Height in points.
223        h: f32,
224        /// Index into the asset table.
225        asset: u32,
226        /// How much of the image shows, from 0 to 255, where 255 is
227        /// all of it: `opacity` on the image and the blocks around it.
228        alpha: u8,
229        /// Which layer the image paints in.
230        layer: i32,
231        /// How the image is mixed with what is already painted
232        /// under it.
233        blend: BlendMode,
234    },
235    /// An image painted behind a box: the page's own, or a block's
236    /// border box.
237    ///
238    /// The box is what the image is clipped to, and the tile is
239    /// where one copy of it is drawn, which may reach outside the
240    /// box. A painter clips to the box, draws the tile, and repeats
241    /// the tile across and down the box where `repeat` asks for it.
242    Background {
243        /// Left edge of the box the image is painted behind.
244        x: f32,
245        /// Its top edge.
246        y: f32,
247        /// Its width in points.
248        w: f32,
249        /// Its height in points.
250        h: f32,
251        /// How far each corner of the box is rounded. The image is
252        /// clipped to the rounded box.
253        radii: Corners,
254        /// Left edge of the first tile.
255        tile_x: f32,
256        /// Its top edge.
257        tile_y: f32,
258        /// The width one copy of the image is drawn at.
259        tile_w: f32,
260        /// The height one copy is drawn at.
261        tile_h: f32,
262        /// Whether the tile repeats to cover the box.
263        repeat: bool,
264        /// Index into the asset table.
265        asset: u32,
266        /// How much of the image shows, from 0 to 255, where 255 is
267        /// all of it: `opacity` on the blocks the box belongs to.
268        alpha: u8,
269        /// Which layer the image paints in.
270        layer: i32,
271        /// How the image is mixed with what is already painted
272        /// under it.
273        blend: BlendMode,
274    },
275    /// A filled box with rounded corners: a background, or a border
276    /// drawn as a ring.
277    ///
278    /// The outer shape is the box with its corners rounded by `radii`.
279    /// Where `ring` is zero on all four edges, the whole shape is
280    /// filled. Otherwise the fill is the band between the outer shape
281    /// and an inner one: the box `ring` in from each edge, with the
282    /// corners [`Corners::inside`] gives.
283    Rounded {
284        /// Left edge.
285        x: f32,
286        /// Top edge.
287        y: f32,
288        /// Width in points.
289        w: f32,
290        /// Height in points.
291        h: f32,
292        /// How far each corner is rounded.
293        radii: Corners,
294        /// How far in from each edge the fill reaches, in points. Zero
295        /// on all four fills the whole shape.
296        ring: Edges,
297        /// What the shape is filled with.
298        color: Color,
299        /// Which layer the shape paints in.
300        layer: i32,
301        /// How the shape is mixed with what is already painted
302        /// under it.
303        blend: BlendMode,
304    },
305}
306
307/// How far one corner of a box is rounded: the two radii of the
308/// quarter ellipse the corner follows, in points.
309#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
310pub struct Radius {
311    /// Along the top or bottom edge.
312    pub x: f32,
313    /// Along the left or right edge.
314    pub y: f32,
315}
316
317impl Radius {
318    /// A corner that is not rounded.
319    pub const SQUARE: Radius = Radius { x: 0.0, y: 0.0 };
320
321    /// Whether the corner is rounded at all. A radius of zero on
322    /// either axis leaves it square.
323    pub fn is_square(self) -> bool {
324        self.x <= 0.0 || self.y <= 0.0
325    }
326}
327
328/// The four corners of a box, each rounded by its own radius.
329///
330/// The radii of two corners on one edge never add up to more than the
331/// edge is long: layout scales all four down together until they fit.
332#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
333pub struct Corners {
334    /// The top left corner.
335    pub top_left: Radius,
336    /// The top right corner.
337    pub top_right: Radius,
338    /// The bottom right corner.
339    pub bottom_right: Radius,
340    /// The bottom left corner.
341    pub bottom_left: Radius,
342}
343
344impl Corners {
345    /// Four square corners.
346    pub const SQUARE: Corners = Corners {
347        top_left: Radius::SQUARE,
348        top_right: Radius::SQUARE,
349        bottom_right: Radius::SQUARE,
350        bottom_left: Radius::SQUARE,
351    };
352
353    /// Whether no corner is rounded.
354    pub fn is_square(&self) -> bool {
355        [
356            self.top_left,
357            self.top_right,
358            self.bottom_right,
359            self.bottom_left,
360        ]
361        .iter()
362        .all(|radius| radius.is_square())
363    }
364
365    /// The corners of the box `ring` in from this one. Each radius
366    /// loses the width of the edge it runs along, and none goes below
367    /// zero, so a ring wider than a radius leaves that inner corner
368    /// square.
369    pub fn inside(&self, ring: Edges) -> Corners {
370        let less = |radius: Radius, across: f32, down: f32| Radius {
371            x: (radius.x - across).max(0.0),
372            y: (radius.y - down).max(0.0),
373        };
374        Corners {
375            top_left: less(self.top_left, ring.left, ring.top),
376            top_right: less(self.top_right, ring.right, ring.top),
377            bottom_right: less(self.bottom_right, ring.right, ring.bottom),
378            bottom_left: less(self.bottom_left, ring.left, ring.bottom),
379        }
380    }
381}
382
383impl DrawItem {
384    /// The layer a page's own background paints in: under every layer
385    /// a stylesheet can name. Where a stylesheet names no `z-index`,
386    /// the text of a page still covers the background. A stylesheet
387    /// that names this number paints over the background as well. The
388    /// page puts its own background in first, and one layer keeps the
389    /// order it arrived in.
390    pub const PAGE_BACKGROUND: i32 = i32::MIN;
391
392    /// The layer a page's margin boxes paint in: over every layer a
393    /// stylesheet can name. A page number and a running head stay
394    /// visible whatever layer the blocks of the book are raised to.
395    pub const PAGE_FURNITURE: i32 = i32::MAX;
396
397    /// Which layer this item paints in. Higher paints later, over
398    /// what a lower layer put down.
399    pub fn layer(&self) -> i32 {
400        match self {
401            DrawItem::Text { layer, .. }
402            | DrawItem::Rect { layer, .. }
403            | DrawItem::Image { layer, .. }
404            | DrawItem::Background { layer, .. }
405            | DrawItem::Rounded { layer, .. } => *layer,
406        }
407    }
408
409    /// How this item is mixed with what is already painted under it.
410    pub fn blend(&self) -> BlendMode {
411        match self {
412            DrawItem::Text { blend, .. }
413            | DrawItem::Rect { blend, .. }
414            | DrawItem::Image { blend, .. }
415            | DrawItem::Background { blend, .. }
416            | DrawItem::Rounded { blend, .. } => *blend,
417        }
418    }
419}
420
421/// An eight-bit alpha scaled by `opacity`, from 0 to 1.
422pub(crate) fn fade(alpha: u8, opacity: f32) -> u8 {
423    (alpha as f32 * opacity.clamp(0.0, 1.0)).round() as u8
424}
425
426/// One glyph: an id in its font and an absolute x. Kerning and
427/// justification mean no two glyphs are uniformly spaced — the glyph is
428/// the atom of layout, so positions are per-glyph.
429#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
430pub struct Glyph {
431    /// Glyph id in the run's font.
432    pub id: u32,
433    /// Absolute x of the glyph's origin.
434    pub x: f32,
435    /// Byte range in the run's `text` this glyph stands for. A
436    /// ligature spans several characters, a decomposed cluster puts
437    /// several glyphs on one range.
438    pub range: Range<u32>,
439}
440
441/// What a reader of the book on a screen follows beyond the links on
442/// its pages: the outline of its headings.
443///
444/// A painter that can express an outline reads this. One that cannot
445/// paints the pages alone, and loses nothing a printed page shows.
446#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
447pub struct Navigation {
448    /// The book's headings, nested by level. Empty for a book with no
449    /// heading.
450    pub outline: Vec<OutlineEntry>,
451}
452
453impl Navigation {
454    /// Whether the book has no heading.
455    pub fn is_empty(&self) -> bool {
456        self.outline.is_empty()
457    }
458}
459
460/// One link on one page: the area its text covers on each line, and
461/// where it goes.
462#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
463pub struct Link {
464    /// One area for each line the link is set on in this page, in the
465    /// order the lines are painted. Each runs across the link's glyphs
466    /// on that line, the text of its `::before` and `::after` included,
467    /// and down from the ascent to the descent of the face.
468    pub areas: Vec<PageBox>,
469    /// Where the link goes.
470    pub to: LinkTo,
471}
472
473impl Link {
474    /// Whether a point on the link's page falls inside one of its areas.
475    pub fn contains(&self, x: f32, y: f32) -> bool {
476        self.areas.iter().any(|area| area.contains(x, y))
477    }
478}
479
480/// Where a link goes.
481#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
482pub enum LinkTo {
483    /// A place in the book.
484    Place {
485        /// The element the link names.
486        node: NodeId,
487        /// The box of that element on the page it opens on. `page` is
488        /// that page's place in the book, counting from 0, which is
489        /// the number a host fetches the page by.
490        place: PageBox,
491    },
492    /// Something outside the book, by its url.
493    Uri(String),
494}
495
496/// One heading in the outline.
497#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
498pub struct OutlineEntry {
499    /// The heading's words, markup discarded and a line break as a
500    /// space.
501    pub title: String,
502    /// The heading's level, from 1 to 6.
503    pub level: u8,
504    /// The box of the heading, on the page it is set on.
505    pub place: PageBox,
506    /// The headings after this one and deeper than it, up to the next
507    /// heading at its level or above.
508    pub children: Vec<OutlineEntry>,
509}