Skip to main content

fleuron/
pdf.rs

1//! PDF export: display structure in, PDF bytes out.
2//!
3//! The painter for print. Everything it needs already exists on the
4//! page — glyph ids, absolute positions, page trim — so this stage
5//! places what layout decided and decides nothing itself.
6//!
7//! Glyphs are shown at their own x, not at the font's: kerning and
8//! justification put them where they are, and a PDF that re-derived
9//! positions from advances would disagree with the preview. The text
10//! each run was shaped from travels with it, so the writer can build
11//! the glyph-to-character map that makes the text selectable.
12//!
13//! Links and the outline are layout's too: each link arrives on its
14//! page with the areas it covers and the place it goes, and each outline entry with
15//! the place of its heading.
16
17use krilla::action::LinkAction;
18use krilla::annotation::{Annotation, LinkAnnotation, Target};
19use krilla::color::rgb;
20use krilla::destination::XyzDestination;
21use krilla::geom::{PathBuilder, Point, Rect, Size, Transform};
22use krilla::image::Image;
23use krilla::metadata::{DateTime, Metadata as PdfMetadata};
24use krilla::num::NormalizedF32;
25use krilla::outline::{Outline, OutlineNode};
26use krilla::page::PageSettings;
27use krilla::paint::{Fill, FillRule};
28use krilla::surface::Surface;
29use krilla::text::{Font, GlyphId, KrillaGlyph, Tag};
30use krilla::{Document, SerializeSettings};
31
32use crate::LayoutOutput;
33use crate::content::Metadata;
34use crate::fonts::FontRegistry;
35use crate::images::Assets;
36use crate::pages::{Corners, DrawItem, Glyph, LinkTo, OutlineEntry, Page, PageBox};
37use crate::style::{BlendMode, Color};
38
39mod svg;
40
41/// What can go wrong turning the display structure into a PDF.
42#[derive(Debug, thiserror::Error)]
43pub enum PdfError {
44    /// The face named could not be embedded.
45    #[error("font {0} could not be embedded")]
46    Font(String),
47    /// The image named is in no format the writer can embed.
48    #[error("image {0} could not be embedded")]
49    Image(String),
50    /// A draw item falls outside what PDF can express.
51    #[error("page {number} draws {kind} outside what PDF can express")]
52    Geometry {
53        /// The folio the offending item is on.
54        number: u32,
55        /// What kind of item it was.
56        kind: &'static str,
57    },
58    /// The writer refused the document.
59    #[error("PDF serialization failed: {0}")]
60    Serialize(String),
61}
62
63/// The page count a print vendor asks a book to reach.
64///
65/// The writer adds blank pages after the last page of a book that
66/// falls short. A blank page has the size of that last page, with
67/// the same bleed and the same room for marks. It has no page
68/// number, no running head and no other margin box.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70pub enum PadTo {
71    /// An even count.
72    Even,
73    /// A multiple of four.
74    MultipleOfFour,
75}
76
77impl PadTo {
78    /// How many pages a book of `pages` holds once it is padded. A
79    /// book that already has the count, or has no page at all, is
80    /// left as it is.
81    pub fn count(self, pages: usize) -> usize {
82        pages.next_multiple_of(match self {
83            PadTo::Even => 2,
84            PadTo::MultipleOfFour => 4,
85        })
86    }
87}
88
89/// How many pages [`write_padded`] writes for this book: the pages
90/// laid out, and the blank pages `pad` adds after them.
91pub fn page_count(output: &LayoutOutput, pad: Option<PadTo>) -> usize {
92    let pages = output.pages.len();
93    pad.map_or(pages, |pad| pad.count(pages))
94}
95
96/// Writes one laid-out book as PDF bytes.
97///
98/// Fonts resolve through the registry that shaped the run and images
99/// through the table that sized them: the display structure names
100/// indexes, the tables own the files, and so the embedded subset has
101/// the outlines the shaper measured and the embedded image is the
102/// file the header was read from.
103///
104/// A book with no images passes [`Assets::none`].
105pub fn write(
106    output: &LayoutOutput,
107    registry: &FontRegistry,
108    assets: &Assets,
109    metadata: &Metadata,
110) -> Result<Vec<u8>, PdfError> {
111    write_padded(output, registry, assets, metadata, None)
112}
113
114/// The same, with blank pages after the last page until the book
115/// has the count `pad` names. [`page_count`] returns that count.
116///
117/// The blank pages are in the PDF only. The writer reads the display
118/// structure and does not change it, so nothing is laid out again.
119pub fn write_padded(
120    output: &LayoutOutput,
121    registry: &FontRegistry,
122    assets: &Assets,
123    metadata: &Metadata,
124    pad: Option<PadTo>,
125) -> Result<Vec<u8>, PdfError> {
126    write_with(
127        output,
128        registry,
129        assets,
130        metadata,
131        pad,
132        SerializeSettings::default(),
133    )
134}
135
136fn write_with(
137    output: &LayoutOutput,
138    registry: &FontRegistry,
139    assets: &Assets,
140    metadata: &Metadata,
141    pad: Option<PadTo>,
142    settings: SerializeSettings,
143) -> Result<Vec<u8>, PdfError> {
144    let fonts = embed_fonts(registry)?;
145    let images = embed_images(assets)?;
146    let mut document = Document::new_with(settings);
147    document.set_metadata(document_metadata(metadata));
148    for page in &output.pages {
149        let outset = page.outset();
150        let mut pdf_page = document.start_page_with(settings_of(page));
151        let mut surface = pdf_page.surface();
152        // Layout measures from the corner of the trim, and the sheet
153        // begins `outset` above and to the left of it.
154        if outset > 0.0 {
155            surface.push_transform(&Transform::from_translate(outset, outset));
156        }
157        for item in &page.items {
158            paint(&mut surface, item, page, &fonts, &images, registry)?;
159        }
160        if outset > 0.0 {
161            surface.pop();
162        }
163        surface.finish();
164        for link in &page.links {
165            for area in &link.areas {
166                if let Some(annotation) = annotation(area, &link.to, outset, &output.pages) {
167                    pdf_page.add_annotation(annotation);
168                }
169            }
170        }
171        pdf_page.finish();
172    }
173    if let Some(last) = output.pages.last() {
174        for _ in output.pages.len()..page_count(output, pad) {
175            document.start_page_with(settings_of(last)).finish();
176        }
177    }
178    if !output.navigation.outline.is_empty() {
179        let mut outline = Outline::new();
180        for entry in &output.navigation.outline {
181            outline.push_child(outline_node(entry, &output.pages));
182        }
183        document.set_outline(outline);
184    }
185    document
186        .finish()
187        .map_err(|e| PdfError::Serialize(format!("{e:?}")))
188}
189
190/// The sheet a page is printed on. A page with no bleed and no marks
191/// is its trim and nothing else. One with either grows by its outset
192/// on every edge and names its trim and its bleed inside that.
193fn settings_of(page: &Page) -> PageSettings {
194    let outset = page.outset();
195    let settings = PageSettings::new(page.width + 2.0 * outset, page.height + 2.0 * outset);
196    if outset <= 0.0 {
197        return settings;
198    }
199    let bleed = page.bleed;
200    let trim = Rect::from_xywh(outset, outset, page.width, page.height);
201    let bled = Rect::from_xywh(
202        outset - bleed,
203        outset - bleed,
204        page.width + 2.0 * bleed,
205        page.height + 2.0 * bleed,
206    );
207    settings.with_trim_box(trim).with_bleed_box(bled)
208}
209
210/// One line of a link as the annotation a viewer follows. An empty
211/// area is none.
212fn annotation(area: &PageBox, to: &LinkTo, outset: f32, pages: &[Page]) -> Option<Annotation> {
213    let rect = Rect::from_xywh(area.x + outset, area.y + outset, area.width, area.height)?;
214    let target = match to {
215        LinkTo::Place { place, .. } => Target::Destination(destination(place, pages).into()),
216        LinkTo::Uri(uri) => Target::Action(LinkAction::new(uri.clone()).into()),
217    };
218    Some(LinkAnnotation::new(rect, target).into())
219}
220
221/// The top left corner of a box, on its page.
222fn destination(place: &PageBox, pages: &[Page]) -> XyzDestination {
223    let outset = pages
224        .get(place.page as usize)
225        .map_or(0.0, |page| page.outset());
226    XyzDestination::new(
227        place.page as usize,
228        Point::from_xy(place.x + outset, place.y + outset),
229    )
230}
231
232/// One heading of the outline, and the headings under it.
233fn outline_node(entry: &OutlineEntry, pages: &[Page]) -> OutlineNode {
234    let mut node = OutlineNode::new(entry.title.clone(), destination(&entry.place, pages));
235    for child in &entry.children {
236        node.push_child(outline_node(child, pages));
237    }
238    node
239}
240
241/// One asset as the writer draws it.
242enum Embedded {
243    /// Pixels, as an image object.
244    Raster(Image),
245    /// An SVG, drawn as the paths it holds.
246    Vector(Box<svg::Vector>),
247}
248
249impl Embedded {
250    /// Draws the asset over a box of `size` at the surface's origin.
251    fn draw(&self, surface: &mut Surface, size: Size) {
252        match self {
253            Embedded::Raster(image) => surface.draw_image(image.clone(), size),
254            Embedded::Vector(vector) => vector.draw(surface, size),
255        }
256    }
257}
258
259/// Every asset as the writer draws it, indexed as the display
260/// structure indexes them.
261///
262/// The format is read off the bytes rather than off the url, since a
263/// url never has to name one: `/asset/8412` is a perfectly good
264/// one. PDF's `DCTDecode` is the JPEG stream
265/// itself, so a JPEG travels into the file as it arrived; the raster
266/// formats are decoded once, alpha channel and all. An SVG is parsed
267/// once and stays vector.
268fn embed_images(assets: &Assets) -> Result<Vec<Embedded>, PdfError> {
269    assets
270        .assets()
271        .iter()
272        .enumerate()
273        .map(|(index, asset)| {
274            let bytes = assets
275                .bytes(index as u32)
276                .ok_or_else(|| PdfError::Image(asset.url.clone()))?
277                .to_vec();
278            embed_image(bytes).ok_or_else(|| PdfError::Image(asset.url.clone()))
279        })
280        .collect()
281}
282
283/// One image, in whichever format its own header says it is.
284///
285/// Interpolation is off, because an image placed at the size its own
286/// header asked for is already at the resolution it was made for.
287fn embed_image(bytes: Vec<u8>) -> Option<Embedded> {
288    if crate::images::is_svg(&bytes) {
289        return svg::Vector::parse(&bytes).map(|vector| Embedded::Vector(Box::new(vector)));
290    }
291    let data = krilla::Data::from(bytes);
292    let image = match () {
293        _ if data.as_ref().starts_with(b"\x89PNG\r\n\x1a\n") => Image::from_png(data, false),
294        _ if data.as_ref().starts_with(&[0xFF, 0xD8]) => Image::from_jpeg(data, false),
295        _ if data.as_ref().starts_with(b"GIF8") => Image::from_gif(data, false),
296        _ if data.as_ref().starts_with(b"RIFF") => Image::from_webp(data, false),
297        _ => None,
298    };
299    image.map(Embedded::Raster)
300}
301
302/// Every registered face as a krilla font, indexed by `font_id`.
303/// krilla subsets on write, so a face nothing draws with costs
304/// nothing.
305///
306/// A face off its family's default location embeds as that instance:
307/// the outlines a reader gets are the ones the shaper measured, not
308/// the whole axis.
309fn embed_fonts(registry: &FontRegistry) -> Result<Vec<Font>, PdfError> {
310    (0..registry.len() as u16)
311        .map(|id| {
312            let name = || {
313                registry
314                    .font_ref(id)
315                    .map(|f| f.name.clone())
316                    .unwrap_or_else(|| id.to_string())
317            };
318            let bytes = registry.bytes(id).ok_or_else(|| PdfError::Font(name()))?;
319            let variations: Vec<(Tag, f32)> = registry
320                .variations(id)
321                .unwrap_or_default()
322                .iter()
323                .map(|axis| (Tag::new(&axis.tag), axis.value))
324                .collect();
325            Font::new_variable(bytes.into(), 0, &variations).ok_or_else(|| PdfError::Font(name()))
326        })
327        .collect()
328}
329
330/// Book metadata as document metadata. `fleuron` is both creator and
331/// producer: the engine laid the pages out and wrote the file.
332///
333/// The creation date is the book's own `date`, because the engine
334/// reads no clock: a run that stamped the hour would write different
335/// bytes every time it ran, and two runs over one book are meant to
336/// be one file.
337fn document_metadata(metadata: &Metadata) -> PdfMetadata {
338    let mut pdf = PdfMetadata::new()
339        .creator("fleuron".to_string())
340        .producer("fleuron".to_string());
341    if let Some(title) = &metadata.title {
342        pdf = pdf.title(title.clone());
343    }
344    if let Some(author) = &metadata.author {
345        pdf = pdf.authors(vec![author.clone()]);
346    }
347    if let Some(language) = metadata.language() {
348        pdf = pdf.language(language.to_string());
349    }
350    if let Some(date) = metadata.extra.get("date").and_then(|date| written(date)) {
351        pdf = pdf.creation_date(date);
352    }
353    pdf
354}
355
356/// A date as a book writes one: `2026-08-27`, and as much of
357/// `T14:30:00` after it as the book bothered with. Anything else is
358/// no date and no creation date.
359fn written(date: &str) -> Option<DateTime> {
360    let number = |field: Option<&str>, digits: usize| -> Option<u16> {
361        let field = field?;
362        (field.len() == digits && field.bytes().all(|b| b.is_ascii_digit()))
363            .then(|| field.parse().ok())?
364    };
365    let (day, clock) = match date.split_once(['T', ' ']) {
366        Some((day, clock)) => (day, Some(clock)),
367        None => (date, None),
368    };
369    let mut fields = day.split('-');
370    let mut stamp = DateTime::new(number(fields.next(), 4)?);
371    if let Some(month) = number(fields.next(), 2) {
372        stamp = stamp.month(month as u8);
373        if let Some(day) = number(fields.next(), 2) {
374            stamp = stamp.day(day as u8);
375        }
376    }
377    let mut fields = clock.unwrap_or_default().split(':');
378    if let Some(hour) = number(fields.next(), 2) {
379        stamp = stamp.hour(hour as u8);
380        if let Some(minute) = number(fields.next(), 2) {
381            stamp = stamp.minute(minute as u8);
382            if let Some(second) = number(fields.next(), 2) {
383                stamp = stamp.second(second as u8);
384            }
385        }
386    }
387    Some(stamp)
388}
389
390/// Paints one item, mixed with what the page already holds where the
391/// item names a mode.
392fn paint(
393    surface: &mut Surface,
394    item: &DrawItem,
395    page: &Page,
396    fonts: &[Font],
397    images: &[Embedded],
398    registry: &FontRegistry,
399) -> Result<(), PdfError> {
400    let mode = item.blend();
401    if mode.is_normal() {
402        return draw(surface, item, page, fonts, images, registry);
403    }
404    surface.push_blend_mode(blend_mode(mode));
405    let drawn = draw(surface, item, page, fonts, images, registry);
406    surface.pop();
407    drawn
408}
409
410fn draw(
411    surface: &mut Surface,
412    item: &DrawItem,
413    page: &Page,
414    fonts: &[Font],
415    images: &[Embedded],
416    registry: &FontRegistry,
417) -> Result<(), PdfError> {
418    match item {
419        DrawItem::Text {
420            x,
421            y,
422            font_id,
423            size,
424            text,
425            source,
426            source_map,
427            // The glyphs are here; the features that chose them are
428            // for a painter that has to choose its own. Where the run
429            // was written is for a preview that follows a cursor; a
430            // page of a PDF does not move.
431            features: _,
432            origin: _,
433            pseudo_element: _,
434            // Each glyph carries its own x.
435            width: _,
436            // The page's items arrived in paint order, so the layer
437            // that put them in it is spent.
438            layer: _,
439            // `paint` pushed the mode before it came here.
440            blend: _,
441            color,
442            glyphs,
443        } => {
444            ink(surface, *color);
445            let font = fonts
446                .get(*font_id as usize)
447                .ok_or_else(|| PdfError::Font(font_id.to_string()))?;
448            // What a reader selects and what a search matches is the
449            // manuscript, so a run that was transformed hands over
450            // what the author wrote rather than what was drawn.
451            let extracted = extracted(text, source, source_map, glyphs);
452            let placed = place(glyphs, &extracted, *x, *size, *font_id, registry);
453            surface.draw_glyphs(
454                Point::from_xy(*x, *y),
455                &placed,
456                font.clone(),
457                extracted.text,
458                *size,
459                false,
460            );
461        }
462        DrawItem::Rect {
463            x,
464            y,
465            w,
466            h,
467            color,
468            layer: _,
469            blend: _,
470        } => {
471            ink(surface, *color);
472            let rect = Rect::from_xywh(*x, *y, *w, *h).ok_or(PdfError::Geometry {
473                number: page.number,
474                kind: "a rectangle",
475            })?;
476            let mut builder = PathBuilder::new();
477            builder.push_rect(rect);
478            let path = builder.finish().ok_or(PdfError::Geometry {
479                number: page.number,
480                kind: "a rectangle",
481            })?;
482            surface.draw_path(&path);
483        }
484        // The transform is layout's decision, not the writer's: an
485        // image krilla draws into a unit square is translated to the
486        // corner layout put it at and scaled to the box layout sized
487        // for it.
488        DrawItem::Image {
489            x,
490            y,
491            w,
492            h,
493            asset,
494            alpha,
495            layer: _,
496            blend: _,
497        } => {
498            let image = images
499                .get(*asset as usize)
500                .ok_or_else(|| PdfError::Image(asset.to_string()))?;
501            let size = Size::from_wh(*w, *h).ok_or(PdfError::Geometry {
502                number: page.number,
503                kind: "an image",
504            })?;
505            faded(surface, *alpha, |surface| {
506                surface.push_transform(&Transform::from_translate(*x, *y));
507                image.draw(surface, size);
508                surface.pop();
509            });
510        }
511        // The box clips and the tile is drawn inside it, once or as
512        // many times as it takes to cover the box. Layout placed the
513        // first tile; the rest are that tile stepped by its own size.
514        DrawItem::Background {
515            x,
516            y,
517            w,
518            h,
519            radii,
520            tile_x,
521            tile_y,
522            tile_w,
523            tile_h,
524            repeat,
525            asset,
526            alpha,
527            layer: _,
528            blend: _,
529        } => {
530            let image = images
531                .get(*asset as usize)
532                .ok_or_else(|| PdfError::Image(asset.to_string()))?;
533            let size = Size::from_wh(*tile_w, *tile_h).ok_or(PdfError::Geometry {
534                number: page.number,
535                kind: "a background image",
536            })?;
537            let clip = Rect::from_xywh(*x, *y, *w, *h).ok_or(PdfError::Geometry {
538                number: page.number,
539                kind: "a background box",
540            })?;
541            let mut builder = PathBuilder::new();
542            if radii.is_square() {
543                builder.push_rect(clip);
544            } else {
545                outline(&mut builder, [*x, *y, *w, *h], *radii);
546            }
547            let path = builder.finish().ok_or(PdfError::Geometry {
548                number: page.number,
549                kind: "a background box",
550            })?;
551            faded(surface, *alpha, |surface| {
552                surface.push_clip_path(&path, &FillRule::NonZero);
553                for (left, top) in tiles(
554                    [*x, *y, *w, *h],
555                    [*tile_x, *tile_y, *tile_w, *tile_h],
556                    *repeat,
557                ) {
558                    surface.push_transform(&Transform::from_translate(left, top));
559                    image.draw(surface, size);
560                    surface.pop();
561                }
562                surface.pop();
563            });
564        }
565        // The even-odd rule is what leaves the inside of a ring empty.
566        DrawItem::Rounded {
567            x,
568            y,
569            w,
570            h,
571            radii,
572            ring,
573            color,
574            layer: _,
575            blend: _,
576        } => {
577            surface.set_fill(Some(Fill {
578                paint: rgb::Color::new(color.r, color.g, color.b).into(),
579                opacity: opacity(color.a),
580                rule: FillRule::EvenOdd,
581            }));
582            let mut builder = PathBuilder::new();
583            outline(&mut builder, [*x, *y, *w, *h], *radii);
584            let inner = [
585                x + ring.left,
586                y + ring.top,
587                w - ring.left - ring.right,
588                h - ring.top - ring.bottom,
589            ];
590            let hollow = ring.top > 0.0 || ring.right > 0.0 || ring.bottom > 0.0 || ring.left > 0.0;
591            if hollow && inner[2] > 0.0 && inner[3] > 0.0 {
592                outline(&mut builder, inner, radii.inside(*ring));
593            }
594            let path = builder.finish().ok_or(PdfError::Geometry {
595                number: page.number,
596                kind: "a rounded box",
597            })?;
598            surface.draw_path(&path);
599        }
600    }
601    Ok(())
602}
603
604/// How far along its tangent each control point of a cubic curve sits,
605/// as a fraction of the radius, for the curve to follow a quarter
606/// ellipse.
607const KAPPA: f32 = 0.552_284_8;
608
609/// A box `[left, top, width, height]` with rounded corners, clockwise
610/// from the top left. Each corner is one cubic curve.
611fn outline(builder: &mut PathBuilder, box_: [f32; 4], radii: Corners) {
612    let [x, y, w, h] = box_;
613    let Corners {
614        top_left: tl,
615        top_right: tr,
616        bottom_right: br,
617        bottom_left: bl,
618    } = radii;
619    let near = 1.0 - KAPPA;
620    builder.move_to(x + tl.x, y);
621    builder.line_to(x + w - tr.x, y);
622    builder.cubic_to(
623        x + w - tr.x * near,
624        y,
625        x + w,
626        y + tr.y * near,
627        x + w,
628        y + tr.y,
629    );
630    builder.line_to(x + w, y + h - br.y);
631    builder.cubic_to(
632        x + w,
633        y + h - br.y * near,
634        x + w - br.x * near,
635        y + h,
636        x + w - br.x,
637        y + h,
638    );
639    builder.line_to(x + bl.x, y + h);
640    builder.cubic_to(
641        x + bl.x * near,
642        y + h,
643        x,
644        y + h - bl.y * near,
645        x,
646        y + h - bl.y,
647    );
648    builder.line_to(x, y + tl.y);
649    builder.cubic_to(x, y + tl.y * near, x + tl.x * near, y, x + tl.x, y);
650    builder.close();
651}
652
653/// Draws what `draw` draws at an eight-bit alpha, and writes nothing
654/// around it where the alpha is opaque.
655fn faded(surface: &mut Surface, alpha: u8, draw: impl FnOnce(&mut Surface)) {
656    if alpha == 255 {
657        draw(surface);
658        return;
659    }
660    surface.push_opacity(opacity(alpha));
661    draw(surface);
662    surface.pop();
663}
664
665/// How many tiles one background is drawn as, whatever the arithmetic
666/// asks for. A tile a fraction of a point wide over a whole page
667/// would otherwise be drawn a million times, and nobody sees past the
668/// first few thousand.
669const TILES: usize = 4096;
670
671/// Where each copy of a repeated image is drawn, in paint order. One
672/// copy where the sheet asked for no repeat. Both boxes are
673/// `[left, top, width, height]`.
674fn tiles(box_: [f32; 4], tile: [f32; 4], repeat: bool) -> Vec<(f32, f32)> {
675    let [x, y, w, h] = box_;
676    let [tile_x, tile_y, tile_w, tile_h] = tile;
677    if !repeat {
678        return vec![(tile_x, tile_y)];
679    }
680    // How far back the tiling starts, and how many copies it takes to
681    // reach the far edge from there.
682    let steps = |start: f32, edge: f32, extent: f32, step: f32| {
683        let before = ((start - edge) / step).ceil().max(0.0) as usize;
684        let after = ((edge + extent - start) / step).ceil().max(1.0) as usize;
685        (start - before as f32 * step, (before + after).min(TILES))
686    };
687    let (first_x, across) = steps(tile_x, x, w, tile_w);
688    let (first_y, down) = steps(tile_y, y, h, tile_h);
689    let mut placed = Vec::with_capacity((across * down).min(TILES));
690    for row in 0..down {
691        for column in 0..across {
692            if placed.len() == TILES {
693                return placed;
694            }
695            placed.push((
696                first_x + column as f32 * tile_w,
697                first_y + row as f32 * tile_h,
698            ));
699        }
700    }
701    placed
702}
703
704/// What the next item is filled with. A page starts out filling in
705/// opaque black, so a run in opaque black writes no colour at all.
706fn ink(surface: &mut Surface, color: Color) {
707    surface.set_fill((color != Color::BLACK).then(|| Fill {
708        paint: rgb::Color::new(color.r, color.g, color.b).into(),
709        opacity: opacity(color.a),
710        ..Fill::default()
711    }));
712}
713
714/// A mode of `mix-blend-mode` as the one krilla takes.
715fn blend_mode(mode: BlendMode) -> krilla::blend::BlendMode {
716    match mode {
717        BlendMode::Normal => krilla::blend::BlendMode::Normal,
718        BlendMode::Multiply => krilla::blend::BlendMode::Multiply,
719        BlendMode::Screen => krilla::blend::BlendMode::Screen,
720        BlendMode::Overlay => krilla::blend::BlendMode::Overlay,
721        BlendMode::Darken => krilla::blend::BlendMode::Darken,
722        BlendMode::Lighten => krilla::blend::BlendMode::Lighten,
723        BlendMode::ColorDodge => krilla::blend::BlendMode::ColorDodge,
724        BlendMode::ColorBurn => krilla::blend::BlendMode::ColorBurn,
725        BlendMode::HardLight => krilla::blend::BlendMode::HardLight,
726        BlendMode::SoftLight => krilla::blend::BlendMode::SoftLight,
727        BlendMode::Difference => krilla::blend::BlendMode::Difference,
728        BlendMode::Exclusion => krilla::blend::BlendMode::Exclusion,
729        BlendMode::Hue => krilla::blend::BlendMode::Hue,
730        BlendMode::Saturation => krilla::blend::BlendMode::Saturation,
731        BlendMode::Color => krilla::blend::BlendMode::Color,
732        BlendMode::Luminosity => krilla::blend::BlendMode::Luminosity,
733    }
734}
735
736/// An eight-bit alpha as the opacity krilla takes.
737fn opacity(alpha: u8) -> NormalizedF32 {
738    NormalizedF32::new(alpha as f32 / 255.0).unwrap_or(NormalizedF32::ONE)
739}
740
741/// Display-structure glyphs as krilla glyphs.
742///
743/// krilla walks a run by advances from its origin, so an absolute x
744/// becomes the gap to the glyph after it. The last glyph has no
745/// successor and takes the advance its font gives it — anything else
746/// would leave a spurious adjustment at the end of every run.
747/// Advances are in ems, hence the division by size.
748fn place(
749    glyphs: &[Glyph],
750    extracted: &Extracted<'_>,
751    origin: f32,
752    size: f32,
753    font_id: u16,
754    registry: &FontRegistry,
755) -> Vec<KrillaGlyph> {
756    let upem = registry
757        .metrics(font_id)
758        .map(|m| m.units_per_em as f32)
759        .unwrap_or(1000.0);
760    // The run's origin need not be its first glyph's x; the gap
761    // shifts every glyph, since krilla measures the cursor from the
762    // origin.
763    let offset = glyphs.first().map(|g| g.x - origin).unwrap_or(0.0);
764    glyphs
765        .iter()
766        .enumerate()
767        .map(|(i, glyph)| {
768            let advance = match glyphs.get(i + 1) {
769                Some(next) => (next.x - glyph.x) / size,
770                None => registry.advance_width(font_id, glyph.id).unwrap_or(0) as f32 / upem,
771            };
772            KrillaGlyph {
773                glyph_id: GlyphId::new(glyph.id),
774                text_range: extracted.ranges[i].clone(),
775                x_advance: advance,
776                x_offset: offset / size,
777                y_offset: 0.0,
778                y_advance: 0.0,
779                location: None,
780            }
781        })
782        .collect()
783}
784
785/// What a run's glyphs are read back as: one string, and the stretch
786/// of it each glyph stands for.
787struct Extracted<'a> {
788    text: &'a str,
789    ranges: Vec<std::ops::Range<usize>>,
790}
791
792/// The run as a reader gets it back. A run nothing transformed is
793/// read back as it was shaped; one that was has what the author
794/// wrote, and every glyph's range is taken through the run's map
795/// into it.
796fn extracted<'a>(
797    text: &'a str,
798    source: &'a str,
799    source_map: &[u32],
800    glyphs: &[Glyph],
801) -> Extracted<'a> {
802    let transformed = !source_map.is_empty();
803    let read = if transformed { source } else { text };
804    let through = |at: u32| match source_map.get(at as usize) {
805        Some(offset) => *offset,
806        None => read.len() as u32,
807    };
808    let ranges = glyphs
809        .iter()
810        .map(|glyph| {
811            let range = if transformed {
812                through(glyph.range.start)..through(glyph.range.end)
813            } else {
814                glyph.range.start..glyph.range.end
815            };
816            clamp_range(range, read)
817        })
818        .collect();
819    Extracted { text: read, ranges }
820}
821
822/// A glyph's range, kept inside the string it indexes and on
823/// character boundaries: krilla slices the text with it to build the
824/// ToUnicode map, and a bad range there is a panic, not a wrong
825/// glyph.
826fn clamp_range(range: std::ops::Range<u32>, text: &str) -> std::ops::Range<usize> {
827    let floor = |at: u32| {
828        let mut at = (at as usize).min(text.len());
829        while !text.is_char_boundary(at) {
830            at -= 1;
831        }
832        at
833    };
834    let start = floor(range.start);
835    start..floor(range.end).max(start)
836}
837
838#[cfg(test)]
839mod tests {
840    use super::*;
841    use crate::content::{Attributes, Block, Book, HeadingLevel, Inline, Section};
842    use crate::fonts::{BUNDLED_FONT, Features, bundled_registry};
843    use crate::pages::{Glyph, Side};
844
845    /// The fixture map: a JPEG whose JFIF density is not 96dpi, so
846    /// its intrinsic size is not its pixel count.
847    const MAP: &[u8] = include_bytes!("../../../fixtures/images/plate.jpg");
848
849    /// The fixture ornament: a PNG whose ground is transparent, and
850    /// the same image as lossless WebP.
851    const ORNAMENT: &[u8] = include_bytes!("../../../fixtures/images/fleuron.png");
852    const ORNAMENT_WEBP: &[u8] = include_bytes!("../../../fixtures/images/fleuron.webp");
853    /// A swelled rule drawn as paths, 2in by 0.25in.
854    const TAILPIECE: &[u8] = include_bytes!("../../../fixtures/images/tailpiece.svg");
855
856    fn registry() -> &'static FontRegistry {
857        static REGISTRY: std::sync::OnceLock<FontRegistry> = std::sync::OnceLock::new();
858        REGISTRY.get_or_init(|| bundled_registry().expect("bundled font parses"))
859    }
860
861    /// A book of one paragraph, with title metadata.
862    fn book(text: &str) -> Book {
863        let mut book = Book {
864            metadata: Metadata {
865                title: Some("Gulliver\'s Travels".into()),
866                author: Some("Jonathan Swift".into()),
867                extra: [("date".to_string(), "1726-10-28".to_string())]
868                    .into_iter()
869                    .collect(),
870            },
871            sections: vec![Section {
872                attributes: Default::default(),
873                blocks: vec![Block::Paragraph {
874                    id: Default::default(),
875                    inlines: vec![Inline::Text {
876                        id: Default::default(),
877                        value: text.into(),
878                        attributes: Attributes::default(),
879                        position: None,
880                        span: None,
881                    }],
882                    attributes: Attributes::default(),
883                    position: None,
884                    span: None,
885                }],
886                ..Default::default()
887            }],
888        };
889        book.assign_node_ids();
890        book
891    }
892
893    /// A book that opens with a heading, for a sheet to colour.
894    fn chapter() -> Book {
895        let mut book = Book {
896            metadata: Metadata::default(),
897            sections: vec![Section {
898                attributes: Default::default(),
899                blocks: vec![
900                    Block::Heading {
901                        id: Default::default(),
902                        level: HeadingLevel::H1,
903                        inlines: vec![Inline::Text {
904                            id: Default::default(),
905                            value: "Chapter One".into(),
906                            attributes: Attributes::default(),
907                            position: None,
908                            span: None,
909                        }],
910                        attributes: Attributes::default(),
911                        position: None,
912                        span: None,
913                    },
914                    Block::Paragraph {
915                        id: Default::default(),
916                        inlines: vec![Inline::Text {
917                            id: Default::default(),
918                            value: "The wind came off the water.".into(),
919                            attributes: Attributes::default(),
920                            position: None,
921                            span: None,
922                        }],
923                        attributes: Attributes::default(),
924                        position: None,
925                        span: None,
926                    },
927                ],
928                ..Default::default()
929            }],
930        };
931        book.assign_node_ids();
932        book
933    }
934
935    /// One hand-built page: the display structure a painter sees, without
936    /// going through layout.
937    fn page_of(items: Vec<DrawItem>, width: f32, height: f32) -> LayoutOutput {
938        LayoutOutput {
939            pages: vec![Page {
940                number: 1,
941                side: Side::Recto,
942                width,
943                height,
944                bleed: 0.0,
945                slug: 0.0,
946                sections: Vec::new(),
947                items,
948                links: Vec::new(),
949            }],
950            fonts: registry().font_ref(0).cloned().into_iter().collect(),
951            assets: Vec::new(),
952            warnings: Vec::new(),
953            navigation: Default::default(),
954        }
955    }
956
957    /// An asset table over files a host handed over by name.
958    fn assets(files: &[(&str, &[u8])]) -> Assets {
959        let mut assets = Assets::none();
960        for (url, bytes) in files {
961            assets.add(url, bytes.to_vec());
962        }
963        assets
964    }
965
966    /// PDF bytes as inspectable text: content streams uncompressed,
967    /// bytes read as latin-1 so offsets survive.
968    fn readable(output: &LayoutOutput, metadata: &Metadata) -> String {
969        with_images(output, &Assets::none(), metadata)
970    }
971
972    /// The same, over images the host supplied.
973    fn with_images(output: &LayoutOutput, assets: &Assets, metadata: &Metadata) -> String {
974        latin1(&bytes_of(output, assets, metadata))
975    }
976
977    fn bytes_of(output: &LayoutOutput, assets: &Assets, metadata: &Metadata) -> Vec<u8> {
978        bytes_padded(output, assets, metadata, None)
979    }
980
981    fn bytes_padded(
982        output: &LayoutOutput,
983        assets: &Assets,
984        metadata: &Metadata,
985        pad: Option<PadTo>,
986    ) -> Vec<u8> {
987        write_with(
988            output,
989            registry(),
990            assets,
991            metadata,
992            pad,
993            SerializeSettings {
994                compress_content_streams: false,
995                ..Default::default()
996            },
997        )
998        .expect("the bundled face embeds")
999    }
1000
1001    /// The same as [`readable`], padded to a count.
1002    fn padded(output: &LayoutOutput, pad: Option<PadTo>) -> String {
1003        latin1(&bytes_padded(
1004            output,
1005            &Assets::none(),
1006            &Metadata::default(),
1007            pad,
1008        ))
1009    }
1010
1011    /// How many pages the page tree counts.
1012    fn counted(pdf: &str) -> usize {
1013        let (_, rest) = pdf
1014            .split_once("/Type /Pages\n  /Count ")
1015            .expect("a page tree");
1016        let (count, _) = rest.split_once('\n').expect("a count");
1017        count.parse().expect("a number")
1018    }
1019
1020    /// Each page of the file, in the order the file writes them: its
1021    /// object, and its content stream.
1022    fn written_pages(pdf: &str) -> Vec<(&str, &str)> {
1023        pdf.split("  /Type /Page\n")
1024            .skip(1)
1025            .map(|rest| {
1026                let (page, _) = rest.split_once("endobj").expect("the page object ends");
1027                let (_, contents) = page.split_once("/Contents ").expect("a content stream");
1028                let (id, _) = contents.split_once(' ').expect("an object number");
1029                let (_, object) = pdf
1030                    .split_once(&format!("\n{id} 0 obj\n"))
1031                    .expect("the stream is in the file");
1032                let (_, stream) = object.split_once("stream\n").expect("a stream");
1033                let (body, _) = stream.split_once("endstream").expect("the stream ends");
1034                (page, body)
1035            })
1036            .collect()
1037    }
1038
1039    fn latin1(bytes: &[u8]) -> String {
1040        bytes.iter().map(|b| *b as char).collect()
1041    }
1042
1043    fn laid_out(book: &Book) -> LayoutOutput {
1044        let styles = crate::style::defaults(book, registry());
1045        crate::layout::layout_book(book, &styles, registry(), &Assets::none())
1046    }
1047
1048    /// The page content streams, joined: where the operators are.
1049    /// The rest of a PDF is font and image bytes, and a byte pair
1050    /// inside a subset is not an operator.
1051    fn content(pdf: &str) -> String {
1052        // The split is on `\nstream\n` rather than `stream\n`, which
1053        // also matches the tail of `endstream` and takes the
1054        // terminator with it.
1055        let streams: Vec<&str> = pdf
1056            .split("\nstream\n")
1057            .skip(1)
1058            .filter_map(|rest| rest.split_once("\nendstream"))
1059            .map(|(body, _)| body)
1060            .filter(|body| body.is_ascii() && body.contains(" cm\n"))
1061            .collect();
1062        assert!(!streams.is_empty(), "no page content stream in:\n{pdf}");
1063        streams.join("\n")
1064    }
1065
1066    /// The one glyph-positioning offset inside a showing op, in
1067    /// 1000ths of an em: `[(…) 100 (…)] TJ`.
1068    fn showing_offset(pdf: &str) -> Option<f32> {
1069        let show = &pdf[pdf.find("[(")?..pdf.find("] TJ")?];
1070        show.rsplit_once(") ")?.1.split_once(" (")?.0.parse().ok()
1071    }
1072
1073    /// The page's trim size is the media box: krilla is told the size
1074    /// the display structure gives, not a default.
1075    #[test]
1076    fn page_trim_becomes_the_media_box() {
1077        let pdf = readable(&page_of(Vec::new(), 432.0, 648.0), &Metadata::default());
1078        assert!(
1079            pdf.contains("/MediaBox [0 0 432 648]"),
1080            "media box missing from:\n{pdf}"
1081        );
1082    }
1083
1084    /// The four numbers of one page box, where the file names it.
1085    fn page_box(pdf: &str, name: &str) -> Option<[f32; 4]> {
1086        let key = format!("/{name} [");
1087        let rest = &pdf[pdf.find(&key)? + key.len()..];
1088        let numbers: Vec<f32> = rest[..rest.find(']')?]
1089            .split_whitespace()
1090            .map(|number| number.parse().expect("a number"))
1091            .collect();
1092        numbers.try_into().ok()
1093    }
1094
1095    /// A book laid out under one author sheet.
1096    fn styled(book: &Book, css: &str) -> LayoutOutput {
1097        let styles =
1098            crate::style::Stylesheets::parse(&[crate::style::Source::author("author.css", css)])
1099                .compile(book, registry());
1100        crate::layout::layout_book(book, &styles, registry(), &Assets::none())
1101    }
1102
1103    /// Acceptance: `@page { bleed: 3mm; marks: crop }` writes a sheet
1104    /// whose MediaBox is larger than its TrimBox by the bleed plus the
1105    /// room for the marks, with the BleedBox between the two.
1106    #[test]
1107    fn a_bled_page_writes_media_trim_and_bleed_boxes() {
1108        let output = styled(
1109            &book("Some prose."),
1110            "@page { size: 432pt 648pt; bleed: 3mm; marks: crop }",
1111        );
1112        let page = &output.pages[0];
1113        let (bleed, outset) = (page.bleed, page.outset());
1114        assert!((bleed - 3.0 * 72.0 / 25.4).abs() < 1e-3);
1115        assert!(outset > bleed, "no room for the marks");
1116
1117        let pdf = readable(&output, &Metadata::default());
1118        let near = |a: [f32; 4], b: [f32; 4]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 0.01);
1119        let media = page_box(&pdf, "MediaBox").expect("a media box");
1120        let trim = page_box(&pdf, "TrimBox").expect("a trim box");
1121        let bled = page_box(&pdf, "BleedBox").expect("a bleed box");
1122        let (w, h) = (432.0 + 2.0 * outset, 648.0 + 2.0 * outset);
1123        assert!(near(media, [0.0, 0.0, w, h]), "{media:?}");
1124        assert!(
1125            near(trim, [outset, outset, w - outset, h - outset]),
1126            "{trim:?}"
1127        );
1128        let edge = outset - bleed;
1129        assert!(near(bled, [edge, edge, w - edge, h - edge]), "{bled:?}");
1130    }
1131
1132    /// Acceptance: a book naming no bleed writes the same single-box
1133    /// pages it writes today.
1134    #[test]
1135    fn a_book_naming_no_bleed_writes_one_box() {
1136        let output = styled(&book("Some prose."), "@page { size: 432pt 648pt }");
1137        let pdf = readable(&output, &Metadata::default());
1138        assert_eq!(page_box(&pdf, "MediaBox"), Some([0.0, 0.0, 432.0, 648.0]));
1139        assert!(page_box(&pdf, "TrimBox").is_none());
1140        assert!(page_box(&pdf, "BleedBox").is_none());
1141    }
1142
1143    /// A link on a bled page covers its text on the sheet, which sits
1144    /// the outset in from the sheet's corner.
1145    #[test]
1146    fn a_link_on_a_bled_page_moves_with_its_text() {
1147        let area = PageBox {
1148            page: 0,
1149            x: 10.0,
1150            y: 20.0,
1151            width: 30.0,
1152            height: 5.0,
1153        };
1154        let mut output = page_of(Vec::new(), 100.0, 200.0);
1155        let page = &mut output.pages[0];
1156        page.bleed = 9.0;
1157        page.links.push(crate::pages::Link {
1158            areas: vec![area],
1159            to: LinkTo::Uri("https://example.org".into()),
1160        });
1161        let pdf = readable(&output, &Metadata::default());
1162        // Up from the foot of a sheet 218pt tall: 218 - 9 - 20 - 5.
1163        assert_eq!(page_box(&pdf, "Rect"), Some([19.0, 184.0, 49.0, 189.0]));
1164    }
1165
1166    /// Glyphs show where layout put them. A run whose second glyph
1167    /// sits a hair off its font advance must come out as one showing
1168    /// op with that offset in it — 1000ths of an em, positive leftwards
1169    /// — not as two runs and not as font-advance spacing.
1170    #[test]
1171    fn glyphs_show_at_the_positions_layout_gave_them() {
1172        let d = registry().char_glyph(0, 'd').unwrap();
1173        let advance = registry().advance_width(0, d).unwrap() as f32 / 1000.0 * 10.0;
1174        let items = vec![DrawItem::Text {
1175            x: 0.0,
1176            y: 20.0,
1177            font_id: 0,
1178            size: 10.0,
1179            width: advance * 2.0 - 1.0,
1180            text: "dd".into(),
1181            source: String::new(),
1182            source_map: Vec::new(),
1183            origin: None,
1184            pseudo_element: None,
1185            features: Features::NONE,
1186            color: Color::BLACK,
1187            layer: 0,
1188            glyphs: vec![
1189                Glyph {
1190                    id: d,
1191                    x: 0.0,
1192                    range: 0..1,
1193                },
1194                Glyph {
1195                    id: d,
1196                    x: advance - 1.0,
1197                    range: 1..2,
1198                },
1199            ],
1200            blend: BlendMode::Normal,
1201        }];
1202        let pdf = readable(&page_of(items, 200.0, 200.0), &Metadata::default());
1203        // 1pt tighter than the font advance, at 10pt: 100/1000 em,
1204        // positive because PDF offsets pull the next glyph leftwards.
1205        let offset = showing_offset(&pdf).expect("no showing offset in:\n{pdf}");
1206        assert!(
1207            (offset - 100.0).abs() < 0.01,
1208            "pair shows {offset}/1000 em tight, layout asked for 100"
1209        );
1210    }
1211
1212    /// Acceptance: the writer paints a layered page in the order the
1213    /// list is in, which is the order the layers put it in. The
1214    /// preview painter walks the same list the same way, so the two
1215    /// agree on what covers what.
1216    #[test]
1217    fn a_layered_page_paints_in_the_order_the_list_is_in() {
1218        let under = Color::rgb(0, 51, 102);
1219        let over = Color::rgb(180, 30, 30);
1220        // What a lowered block and a raised one come out as: the
1221        // sort put the lower one first, and the writer keeps it
1222        // there.
1223        let items = vec![
1224            DrawItem::Rect {
1225                x: 0.0,
1226                y: 0.0,
1227                w: 100.0,
1228                h: 100.0,
1229                color: under,
1230                layer: -1,
1231                blend: BlendMode::Normal,
1232            },
1233            DrawItem::Rect {
1234                x: 20.0,
1235                y: 20.0,
1236                w: 60.0,
1237                h: 60.0,
1238                color: over,
1239                layer: 10,
1240                blend: BlendMode::Normal,
1241            },
1242        ];
1243        let painted = content(&readable(
1244            &page_of(items, 200.0, 200.0),
1245            &Metadata::default(),
1246        ));
1247        let lower = painted
1248            .find("0 0.2 0.4 rg")
1249            .expect("the lowered block filled with its own colour");
1250        let raised = painted
1251            .find("0.7058824 0.11764706 0.11764706 rg")
1252            .expect("the raised block filled with its own colour");
1253        assert!(
1254            lower < raised,
1255            "the writer painted the raised block first:\n{painted}"
1256        );
1257    }
1258
1259    /// Rules paint as filled paths at the coordinates layout gave them.
1260    #[test]
1261    fn rect_items_paint_as_filled_paths() {
1262        let items = vec![DrawItem::Rect {
1263            x: 54.0,
1264            y: 100.0,
1265            w: 324.0,
1266            h: 0.5,
1267            color: Color::BLACK,
1268            layer: 0,
1269            blend: BlendMode::Normal,
1270        }];
1271        let pdf = readable(&page_of(items, 432.0, 648.0), &Metadata::default());
1272        assert!(
1273            pdf.contains("54 100 m") && pdf.contains("378 100 l") && pdf.contains("\nf\n"),
1274            "rect did not paint as a filled path:\n{pdf}"
1275        );
1276    }
1277
1278    /// Acceptance: the preview and the export agree about a rule
1279    /// across a run. Both painters read the rects the display
1280    /// structure holds and neither derives one of its own, so the
1281    /// test is that the export paints a filled path at the
1282    /// coordinates layout wrote.
1283    #[test]
1284    fn a_rule_across_a_run_paints_where_layout_put_it() {
1285        let book = chapter();
1286        let styles = crate::style::Stylesheets::parse(&[crate::style::Source::author(
1287            "decoration.css",
1288            "h1 { text-decoration: underline }",
1289        )])
1290        .compile(&book, registry());
1291        let output = crate::layout::layout_book(&book, &styles, registry(), &Assets::none());
1292        let rules: Vec<(f32, f32, f32, f32)> = output.pages[0]
1293            .items
1294            .iter()
1295            .filter_map(|item| match item {
1296                DrawItem::Rect { x, y, w, h, .. } => Some((*x, *y, *w, *h)),
1297                _ => None,
1298            })
1299            .collect();
1300        assert_eq!(rules.len(), 1, "the heading did not take one rule");
1301        let (x, y, w, h) = rules[0];
1302        let painted = content(&readable(&output, &Metadata::default()));
1303        let corners = [
1304            format!("{x} {y} m"),
1305            format!("{} {y} l", x + w),
1306            format!("{} {} l", x + w, y + h),
1307        ];
1308        for corner in &corners {
1309            assert!(
1310                painted.contains(corner),
1311                "the export did not paint `{corner}`:\n{painted}",
1312            );
1313        }
1314    }
1315
1316    /// Colour reaches the page: a heading the sheet coloured fills
1317    /// with the colour its run carries, a rule fills with its own,
1318    /// and a page in black writes no colour at all.
1319    #[test]
1320    fn items_fill_with_the_colour_they_carry() {
1321        let book = chapter();
1322        let styles = crate::style::Stylesheets::parse(&[crate::style::Source::author(
1323            "colour.css",
1324            "h1 { color: #b41e1e }",
1325        )])
1326        .compile(&book, registry());
1327        let output = crate::layout::layout_book(&book, &styles, registry(), &Assets::none());
1328        let heading = output.pages[0]
1329            .items
1330            .iter()
1331            .find_map(|item| match item {
1332                DrawItem::Text { text, color, .. } if text.starts_with("Chapter") => Some(*color),
1333                _ => None,
1334            })
1335            .expect("the heading opens the first page");
1336        assert_eq!(heading, Color::rgb(180, 30, 30));
1337        let painted = content(&readable(&output, &Metadata::default()));
1338        // The channels the PDF writes, each over 255.
1339        let red = painted
1340            .find("0.7058824 0.11764706 0.11764706 rg")
1341            .unwrap_or_else(|| {
1342                panic!("the heading did not fill with the colour its run carries:\n{painted}")
1343            });
1344        // The fill is surface state, so the prose under the heading
1345        // has to set it back rather than inherit the red.
1346        assert!(
1347            painted[red..].contains("\n0 g\n"),
1348            "the heading's colour ran on into the prose under it:\n{painted}"
1349        );
1350
1351        let rule = page_of(
1352            vec![DrawItem::Rect {
1353                x: 10.0,
1354                y: 40.0,
1355                w: 100.0,
1356                h: 0.5,
1357                color: Color::rgb(0, 51, 102),
1358                layer: 0,
1359                blend: BlendMode::Normal,
1360            }],
1361            200.0,
1362            200.0,
1363        );
1364        let painted = content(&readable(&rule, &Metadata::default()));
1365        assert!(
1366            painted.contains("0 0.2 0.4 rg"),
1367            "the rule did not fill with the colour it carries:\n{painted}"
1368        );
1369
1370        let black = content(&readable(&laid_out(&book), &Metadata::default()));
1371        assert!(
1372            !black.contains(" rg"),
1373            "a page in black wrote a colour of its own:\n{black}"
1374        );
1375    }
1376
1377    /// Acceptance: an item that names a mode is drawn in it, text
1378    /// included, and a book that asks for none writes no blend mode.
1379    #[test]
1380    fn an_item_with_a_blend_mode_is_drawn_in_that_mode() {
1381        let rect = |x: f32, color: Color, blend: BlendMode| DrawItem::Rect {
1382            x,
1383            y: 40.0,
1384            w: 100.0,
1385            h: 100.0,
1386            color,
1387            layer: 0,
1388            blend,
1389        };
1390        let mixed = page_of(
1391            vec![
1392                rect(10.0, Color::rgb(255, 221, 0), BlendMode::Normal),
1393                rect(60.0, Color::rgb(0, 51, 102), BlendMode::Multiply),
1394            ],
1395            200.0,
1396            200.0,
1397        );
1398        let pdf = readable(&mixed, &Metadata::default());
1399        assert_eq!(
1400            pdf.matches("/BM /Multiply").count(),
1401            1,
1402            "one rectangle is multiplied in:\n{pdf}"
1403        );
1404
1405        let book = chapter();
1406        let sheet = crate::style::Source::author("blend.css", "h1 { mix-blend-mode: screen }");
1407        let styles = crate::style::Stylesheets::parse(&[sheet]).compile(&book, registry());
1408        let output = crate::layout::layout_book(&book, &styles, registry(), &Assets::none());
1409        let pdf = readable(&output, &Metadata::default());
1410        assert!(
1411            pdf.contains("/BM /Screen"),
1412            "the heading is not screened in:\n{pdf}"
1413        );
1414
1415        let plain = readable(&laid_out(&book), &Metadata::default());
1416        assert!(
1417            !plain.contains("/BM"),
1418            "a plain book wrote a blend mode:\n{plain}"
1419        );
1420    }
1421
1422    /// Acceptance: text set in a colour with alpha paints at that
1423    /// alpha. The fill carries the colour, and a graphics state carries
1424    /// the alpha as its fill opacity.
1425    #[test]
1426    fn a_run_in_a_colour_with_alpha_fills_at_that_alpha() {
1427        let book = chapter();
1428        let styles = crate::style::Stylesheets::parse(&[crate::style::Source::author(
1429            "alpha.css",
1430            "h1 { color: rgba(180, 30, 30, 0.25) }",
1431        )])
1432        .compile(&book, registry());
1433        let output = crate::layout::layout_book(&book, &styles, registry(), &Assets::none());
1434        let pdf = readable(&output, &Metadata::default());
1435        assert!(
1436            pdf.contains("/ca 0.2509804"),
1437            "no fill opacity of a quarter in:\n{pdf}"
1438        );
1439        let painted = content(&pdf);
1440        let red = painted
1441            .find("0.7058824 0.11764706 0.11764706 rg")
1442            .unwrap_or_else(|| panic!("the heading lost its colour:\n{painted}"));
1443        assert!(
1444            painted[..red].contains(" gs\n") || painted[red..].contains(" gs\n"),
1445            "the fill opacity is never set on the page:\n{painted}"
1446        );
1447    }
1448
1449    /// The face embeds as a subset: a tagged BaseFont, a FontFile2,
1450    /// and a stream far smaller than the face it came from.
1451    #[test]
1452    fn the_face_embeds_as_a_subset() {
1453        let pdf = readable(&laid_out(&book("difficult offices")), &Metadata::default());
1454        let tag = pdf
1455            .find("+EBGaramond-Regular")
1456            .expect("no subset-tagged BaseFont");
1457        assert!(
1458            pdf[tag - 6..tag].chars().all(|c| c.is_ascii_uppercase()),
1459            "BaseFont has no six-letter subset tag"
1460        );
1461        assert!(pdf.contains("/FontFile2"), "no embedded font program");
1462        assert!(
1463            pdf.len() < BUNDLED_FONT.len(),
1464            "the whole PDF ({} bytes) is no smaller than the full face ({} bytes)",
1465            pdf.len(),
1466            BUNDLED_FONT.len()
1467        );
1468    }
1469
1470    /// A JPEG is embedded as it arrived: PDF's `DCTDecode` is the
1471    /// JPEG stream itself, so re-encoding one would cost quality for
1472    /// nothing.
1473    #[test]
1474    fn a_jpeg_embeds_the_bytes_it_arrived_as() {
1475        let items = vec![DrawItem::Image {
1476            x: 40.0,
1477            y: 60.0,
1478            w: 115.2,
1479            h: 76.8,
1480            asset: 0,
1481            alpha: 255,
1482            layer: 0,
1483            blend: BlendMode::Normal,
1484        }];
1485        let table = assets(&[("plate.jpg", MAP)]);
1486        let bytes = bytes_of(&page_of(items, 432.0, 648.0), &table, &Metadata::default());
1487        let pdf = latin1(&bytes);
1488        assert!(pdf.contains("/DCTDecode"), "the map was re-encoded");
1489        assert!(
1490            bytes.windows(MAP.len()).any(|window| window == MAP),
1491            "the embedded stream is not the file that went in",
1492        );
1493    }
1494
1495    /// Part: the PDF export paints an SVG, and the art stays vector:
1496    /// the page fills curves in the colour the file names, scaled
1497    /// from the file's own units to the box layout gave it, and no
1498    /// image object is written.
1499    #[test]
1500    fn an_svg_goes_into_the_pdf_as_paths() {
1501        let items = vec![DrawItem::Image {
1502            x: 144.0,
1503            y: 300.0,
1504            w: 144.0,
1505            h: 18.0,
1506            asset: 0,
1507            alpha: 255,
1508            layer: 0,
1509            blend: BlendMode::Normal,
1510        }];
1511        let table = assets(&[("tailpiece.svg", TAILPIECE)]);
1512        let pdf = with_images(&page_of(items, 432.0, 648.0), &table, &Metadata::default());
1513        assert!(!pdf.contains("/Subtype /Image"), "the SVG was rasterized");
1514        let painted = content(&pdf);
1515        // 192 units across 144pt, with the corner at (144, 300) from
1516        // the top of a 648pt page.
1517        assert!(
1518            painted.contains("0.75 0 0 -0.75 144 348 cm"),
1519            "the art is not scaled into its box:\n{painted}",
1520        );
1521        assert!(
1522            painted.contains("0.36078432 0.2901961 0.18039216 rg"),
1523            "the rule is not filled in its own colour:\n{painted}",
1524        );
1525        assert!(
1526            painted.contains("40 10.5 70 10 84 12 c"),
1527            "the curve the file draws is not in the page:\n{painted}",
1528        );
1529    }
1530
1531    /// Acceptance: an SVG behind a box is drawn as paths as well, one
1532    /// copy to a tile, inside the clip of the box.
1533    #[test]
1534    fn an_svg_background_tiles_as_paths() {
1535        let items = vec![DrawItem::Background {
1536            x: 72.0,
1537            y: 72.0,
1538            w: 288.0,
1539            h: 18.0,
1540            radii: Corners::SQUARE,
1541            tile_x: 72.0,
1542            tile_y: 72.0,
1543            tile_w: 144.0,
1544            tile_h: 18.0,
1545            repeat: true,
1546            asset: 0,
1547            alpha: 255,
1548            layer: 0,
1549            blend: BlendMode::Normal,
1550        }];
1551        let table = assets(&[("tailpiece.svg", TAILPIECE)]);
1552        let pdf = with_images(&page_of(items, 432.0, 648.0), &table, &Metadata::default());
1553        assert!(!pdf.contains("/Subtype /Image"), "the SVG was rasterized");
1554        let painted = content(&pdf);
1555        assert_eq!(
1556            painted.matches("40 10.5 70 10 84 12 c").count(),
1557            2,
1558            "two tiles cover the box:\n{painted}",
1559        );
1560        assert!(
1561            painted.contains("W\nn"),
1562            "the box does not clip:\n{painted}"
1563        );
1564    }
1565
1566    /// What an SVG holds beyond flat fills reaches the PDF as the
1567    /// same kind of object: a gradient as a shading, a clip path as a
1568    /// clip, a stroke as a stroke, and group opacity as a graphics
1569    /// state.
1570    #[test]
1571    fn gradients_clips_and_strokes_stay_vector() {
1572        let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
1573            <defs>
1574              <linearGradient id="fade"><stop offset="0" stop-color="#800"/><stop offset="1" stop-color="#008"/></linearGradient>
1575              <clipPath id="disc"><circle cx="50" cy="50" r="40"/></clipPath>
1576            </defs>
1577            <rect width="100" height="100" fill="url(#fade)" clip-path="url(#disc)"/>
1578            <g opacity="0.5"><path d="M10 10 L90 90" fill="none" stroke="#123456" stroke-width="3"/></g>
1579            <text x="10" y="20">not outlined</text>
1580          </svg>"##;
1581        let items = vec![DrawItem::Image {
1582            x: 0.0,
1583            y: 0.0,
1584            w: 75.0,
1585            h: 75.0,
1586            asset: 0,
1587            alpha: 255,
1588            layer: 0,
1589            blend: BlendMode::Normal,
1590        }];
1591        let table = assets(&[("plate.svg", svg)]);
1592        let pdf = with_images(&page_of(items, 432.0, 648.0), &table, &Metadata::default());
1593        assert!(!pdf.contains("/Subtype /Image"), "the SVG was rasterized");
1594        assert!(pdf.contains("/ShadingType 2"), "no axial shading:\n{pdf}");
1595        assert!(pdf.contains("/ca 0.5"), "the group opacity is lost:\n{pdf}");
1596        assert!(pdf.contains("\n3 w\n"), "the stroke width is lost:\n{pdf}");
1597        assert!(
1598            pdf.contains("0.07058824 0.20392157 0.3372549 RG"),
1599            "the stroke colour is lost:\n{pdf}",
1600        );
1601        assert!(content(&pdf).contains("W\nn"), "nothing clips:\n{pdf}");
1602    }
1603
1604    /// The writer opens no file. An SVG that names an image by path
1605    /// is drawn without it, and one that carries the bytes is drawn
1606    /// with them.
1607    #[test]
1608    fn an_svg_reads_no_file_it_names() {
1609        let item = vec![DrawItem::Image {
1610            x: 0.0,
1611            y: 0.0,
1612            w: 72.0,
1613            h: 72.0,
1614            asset: 0,
1615            alpha: 255,
1616            layer: 0,
1617            blend: BlendMode::Normal,
1618        }];
1619        let path = concat!(
1620            env!("CARGO_MANIFEST_DIR"),
1621            "/../../fixtures/images/plate.jpg"
1622        );
1623        let named = format!(
1624            r#"<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96"><image width="96" height="96" href="{path}"/></svg>"#,
1625        );
1626        let table = assets(&[("named.svg", named.as_bytes())]);
1627        let pdf = with_images(&page_of(item, 432.0, 648.0), &table, &Metadata::default());
1628        assert!(!pdf.contains("/DCTDecode"), "the writer read {path}");
1629    }
1630
1631    /// An SVG the probe sized and the parser cannot read fails the
1632    /// export by name, as a raster file that does not decode does.
1633    #[test]
1634    fn an_svg_that_does_not_parse_is_named() {
1635        let broken = br#"<svg width="10" height="10"><g></svg>"#;
1636        let table = assets(&[("broken.svg", broken)]);
1637        let output = page_of(Vec::new(), 432.0, 648.0);
1638        let error = write(&output, registry(), &table, &Metadata::default())
1639            .expect_err("a broken SVG embedded");
1640        assert!(matches!(error, PdfError::Image(url) if url == "broken.svg"));
1641    }
1642
1643    /// The raster formats decode, and an alpha channel becomes the
1644    /// image's soft mask, which is what lets the paper, or a rule
1645    /// under it, show through.
1646    #[test]
1647    fn a_raster_image_with_alpha_embeds_a_soft_mask() {
1648        for (url, bytes) in [("fleuron.png", ORNAMENT), ("fleuron.webp", ORNAMENT_WEBP)] {
1649            let items = vec![
1650                DrawItem::Rect {
1651                    x: 0.0,
1652                    y: 0.0,
1653                    w: 432.0,
1654                    h: 648.0,
1655                    color: Color::BLACK,
1656                    layer: 0,
1657                    blend: BlendMode::Normal,
1658                },
1659                DrawItem::Image {
1660                    x: 200.0,
1661                    y: 300.0,
1662                    w: 30.72,
1663                    h: 30.72,
1664                    asset: 0,
1665                    alpha: 255,
1666                    layer: 0,
1667                    blend: BlendMode::Normal,
1668                },
1669            ];
1670            let table = assets(&[(url, bytes)]);
1671            let pdf = with_images(&page_of(items, 432.0, 648.0), &table, &Metadata::default());
1672            assert!(
1673                pdf.contains("/SMask"),
1674                "{url}: the ornament's transparency was flattened away",
1675            );
1676            assert!(
1677                pdf.contains("/ColorSpace /DeviceGray"),
1678                "{url}: no grayscale mask stream",
1679            );
1680            assert!(
1681                !pdf.contains("/DCTDecode"),
1682                "{url}: a raster image went in as a JPEG stream",
1683            );
1684        }
1685    }
1686
1687    /// Four corners of one radius.
1688    fn round(radius: f32) -> Corners {
1689        let radius = crate::pages::Radius {
1690            x: radius,
1691            y: radius,
1692        };
1693        Corners {
1694            top_left: radius,
1695            top_right: radius,
1696            bottom_right: radius,
1697            bottom_left: radius,
1698        }
1699    }
1700
1701    /// A rounded tint fills a path whose corners are curves, and a ring
1702    /// fills the band between two outlines by the even-odd rule.
1703    #[test]
1704    fn a_rounded_box_fills_a_curved_path() {
1705        let items = vec![
1706            DrawItem::Rounded {
1707                x: 20.0,
1708                y: 20.0,
1709                w: 100.0,
1710                h: 40.0,
1711                radii: round(3.0),
1712                ring: crate::style::Edges::all(0.0),
1713                color: Color::rgb(0xf4, 0xf1, 0xea),
1714                layer: 0,
1715                blend: BlendMode::Normal,
1716            },
1717            DrawItem::Rounded {
1718                x: 20.0,
1719                y: 80.0,
1720                w: 100.0,
1721                h: 40.0,
1722                radii: round(6.0),
1723                ring: crate::style::Edges::all(2.0),
1724                color: Color::rgb(0, 51, 102),
1725                layer: 0,
1726                blend: BlendMode::Normal,
1727            },
1728        ];
1729        let painted = content(&readable(
1730            &page_of(items, 200.0, 200.0),
1731            &Metadata::default(),
1732        ));
1733        let curves = painted.matches(" c\n").count();
1734        assert_eq!(
1735            curves, 12,
1736            "one curve per corner of three outlines:\n{painted}"
1737        );
1738        assert!(
1739            painted.contains("\nf*\n"),
1740            "the ring is not filled by the even-odd rule:\n{painted}"
1741        );
1742    }
1743
1744    /// Acceptance: a rounded chip on a run draws its corners in the
1745    /// export, the way a rounded block does. The chip reaches the
1746    /// painter as one rounded box, so the curves come out of the same
1747    /// path builder the preview reads the same box through.
1748    #[test]
1749    fn a_rounded_chip_draws_its_corners() {
1750        let mut book = book("roll for the modifier");
1751        let Some(Block::Paragraph { inlines, .. }) = book.sections[0].blocks.first_mut() else {
1752            panic!("the fixture opens with a paragraph");
1753        };
1754        inlines.push(Inline::Code {
1755            id: Default::default(),
1756            value: "2d6".into(),
1757            attributes: Attributes::default(),
1758            position: None,
1759            span: None,
1760        });
1761        book.assign_node_ids();
1762        let styles = crate::style::Stylesheets::parse(&[crate::style::Source::author(
1763            "chip.css",
1764            "code { background-color: #858585; padding: 2pt 4pt; border-radius: 3pt }",
1765        )])
1766        .compile(&book, registry());
1767        let output = crate::layout::layout_book(&book, &styles, registry(), &Assets::none());
1768        let chip = output.pages[0]
1769            .items
1770            .iter()
1771            .filter(|item| matches!(item, DrawItem::Rounded { .. }))
1772            .count();
1773        assert_eq!(chip, 1, "the chip is not one rounded box");
1774        let painted = content(&readable(&output, &Metadata::default()));
1775        assert_eq!(
1776            painted.matches(" c\n").count(),
1777            4,
1778            "one curve per corner of the chip:\n{painted}",
1779        );
1780    }
1781
1782    /// Acceptance: a rounded background image is clipped to the same
1783    /// curve as the tint under it.
1784    #[test]
1785    fn a_rounded_background_clips_to_a_curved_path() {
1786        let items = vec![DrawItem::Background {
1787            x: 40.0,
1788            y: 60.0,
1789            w: 120.0,
1790            h: 80.0,
1791            radii: round(3.0),
1792            tile_x: 40.0,
1793            tile_y: 60.0,
1794            tile_w: 120.0,
1795            tile_h: 80.0,
1796            repeat: false,
1797            asset: 0,
1798            alpha: 255,
1799            layer: 0,
1800            blend: BlendMode::Normal,
1801        }];
1802        let table = assets(&[("plate.jpg", MAP)]);
1803        let painted = content(&with_images(
1804            &page_of(items, 432.0, 648.0),
1805            &table,
1806            &Metadata::default(),
1807        ));
1808        let clip = painted
1809            .find("\nW\n")
1810            .unwrap_or_else(|| panic!("the image is not clipped:\n{painted}"));
1811        assert_eq!(
1812            painted[..clip].matches(" c\n").count(),
1813            4,
1814            "the clip does not follow four curved corners:\n{painted}"
1815        );
1816    }
1817
1818    /// Acceptance: a tint with an alpha over the image behind a page
1819    /// leaves the image showing through. The image is drawn first, and
1820    /// the tint over it fills at a quarter of full opacity.
1821    #[test]
1822    fn a_translucent_tint_over_a_page_image_fills_at_its_alpha() {
1823        let items = vec![
1824            DrawItem::Background {
1825                x: 0.0,
1826                y: 0.0,
1827                w: 432.0,
1828                h: 648.0,
1829                radii: Corners::SQUARE,
1830                tile_x: 0.0,
1831                tile_y: 0.0,
1832                tile_w: 432.0,
1833                tile_h: 648.0,
1834                repeat: false,
1835                asset: 0,
1836                alpha: 255,
1837                layer: DrawItem::PAGE_BACKGROUND,
1838                blend: BlendMode::Normal,
1839            },
1840            DrawItem::Rect {
1841                x: 54.0,
1842                y: 100.0,
1843                w: 324.0,
1844                h: 120.0,
1845                color: Color::rgba(0, 0, 0, 64),
1846                layer: 0,
1847                blend: BlendMode::Normal,
1848            },
1849        ];
1850        let table = assets(&[("plate.jpg", MAP)]);
1851        let pdf = with_images(&page_of(items, 432.0, 648.0), &table, &Metadata::default());
1852        assert!(
1853            pdf.contains("/ca 0.2509804"),
1854            "the tint fills opaque:\n{pdf}"
1855        );
1856        let painted = content(&pdf);
1857        let image = painted
1858            .find(" Do\n")
1859            .unwrap_or_else(|| panic!("the page image is not drawn:\n{painted}"));
1860        let tint = painted
1861            .find("0 0 0 rg")
1862            .unwrap_or_else(|| panic!("the tint is not filled:\n{painted}"));
1863        assert!(image < tint, "the tint is under the image:\n{painted}");
1864    }
1865
1866    /// An image with an alpha draws under a graphics state that
1867    /// carries the alpha as its opacity, and an opaque one sets none.
1868    #[test]
1869    fn an_image_with_alpha_draws_at_that_alpha() {
1870        let image = |alpha| {
1871            vec![DrawItem::Image {
1872                x: 54.0,
1873                y: 90.0,
1874                w: 72.0,
1875                h: 48.0,
1876                asset: 0,
1877                alpha,
1878                layer: 0,
1879                blend: BlendMode::Normal,
1880            }]
1881        };
1882        let table = assets(&[("plate.jpg", MAP)]);
1883        let faded = with_images(
1884            &page_of(image(128), 432.0, 648.0),
1885            &table,
1886            &Metadata::default(),
1887        );
1888        assert!(
1889            faded.contains("/ca 0.5019608") && faded.contains("/CA 0.5019608"),
1890            "no opacity of a half in:\n{faded}"
1891        );
1892        let opaque = with_images(
1893            &page_of(image(255), 432.0, 648.0),
1894            &table,
1895            &Metadata::default(),
1896        );
1897        assert!(!opaque.contains("/ca "), "an opaque image set an opacity");
1898    }
1899
1900    /// Painters scale; they do not re-derive. An image layout sized
1901    /// down draws at the size layout gave it, not at the one its
1902    /// header declares.
1903    #[test]
1904    fn an_image_draws_at_the_size_layout_gave_it() {
1905        let items = vec![DrawItem::Image {
1906            x: 54.0,
1907            y: 90.0,
1908            w: 72.0,
1909            h: 48.0,
1910            asset: 0,
1911            alpha: 255,
1912            layer: 0,
1913            blend: BlendMode::Normal,
1914        }];
1915        let table = assets(&[("plate.jpg", MAP)]);
1916        let (width, height) = table
1917            .lookup("plate.jpg")
1918            .expect("the map is an asset")
1919            .1
1920            .size();
1921        assert!(
1922            (width - 180.0).abs() < 0.01 && (height - 306.72).abs() < 0.01,
1923            "the header sizes the map at {width}x{height}pt",
1924        );
1925        let pdf = with_images(&page_of(items, 432.0, 648.0), &table, &Metadata::default());
1926        // krilla draws an image into the unit square, so the box is
1927        // the transform: the size layout asked for, and the corner it
1928        // asked for, measured up from the foot of the page.
1929        assert!(
1930            pdf.contains("72 0 0 48 54 510 cm"),
1931            "the image is not placed at 72x48pt at (54, 90):\n{pdf}",
1932        );
1933    }
1934
1935    /// Acceptance: the preview and the export of a wrapped page
1936    /// agree.
1937    ///
1938    /// Both painters read the same display structure. The question is
1939    /// whether the export puts each item where that structure says.
1940    /// The image lands at the box its item carries. The line beside
1941    /// it starts at the x and the baseline its own item carries.
1942    #[test]
1943    fn a_wrapped_page_exports_where_the_display_structure_put_it() {
1944        let mut book = book(
1945            "My father had a small estate in Nottinghamshire, and I was the third of \
1946             five sons. He sent me to Emanuel College in Cambridge at fourteen years \
1947             old, where I resided three years and applied myself close to my studies.",
1948        );
1949        book.sections[0].blocks.insert(
1950            0,
1951            Block::Image {
1952                id: Default::default(),
1953                url: "plate.jpg".into(),
1954                alt: "a map of Lilliput".into(),
1955                attributes: Attributes::default(),
1956                position: None,
1957                span: None,
1958            },
1959        );
1960        book.assign_node_ids();
1961        let styles = crate::style::Stylesheets::parse(&[crate::style::Source::author(
1962            "anchored.css",
1963            "img { position: absolute; top: 0; left: 0; margin-right: 12pt; wrap-flow: end }",
1964        )])
1965        .compile(&book, registry());
1966        let table = assets(&[("plate.jpg", MAP)]);
1967        let output = crate::layout::layout_book(&book, &styles, registry(), &table);
1968        let page = &output.pages[0];
1969
1970        let image = page
1971            .items
1972            .iter()
1973            .find_map(|item| match item {
1974                DrawItem::Image { x, y, w, h, .. } => Some((*x, *y, *w, *h)),
1975                _ => None,
1976            })
1977            .expect("the image is on the page");
1978        let (x, baseline) = page
1979            .items
1980            .iter()
1981            .find_map(|item| match item {
1982                DrawItem::Text { x, y, .. } if *x > image.0 + image.2 => Some((*x, *y)),
1983                _ => None,
1984            })
1985            .expect("a line is set beside the image");
1986        assert!(
1987            baseline > image.1 && baseline < image.1 + image.3,
1988            "the line at {baseline} is not beside the image at {image:?}",
1989        );
1990
1991        let pdf = content(&with_images(&output, &table, &Metadata::default()));
1992        // krilla draws an image into the unit square, so the box is
1993        // the transform. It carries the size and the corner of the
1994        // item, measured up from the foot of the page.
1995        let box_ = format!(
1996            "{} 0 0 {} {} {} cm",
1997            image.2,
1998            image.3,
1999            image.0,
2000            page.height - image.1 - image.3,
2001        );
2002        assert!(
2003            pdf.contains(&box_),
2004            "the image is not placed at {box_}:\n{pdf}",
2005        );
2006        // krilla writes text under a flip, so the line sits at the x
2007        // and the baseline the item carries.
2008        let text = format!("1 0 0 -1 {x} {baseline} Tm");
2009        assert!(
2010            pdf.contains(&text),
2011            "the line beside the image is not set at {text}:\n{pdf}",
2012        );
2013    }
2014
2015    /// Acceptance: the preview and the export of a page with a
2016    /// relative block and an absolute block on it agree.
2017    ///
2018    /// Both painters read the same display structure. The export must
2019    /// put the lines of both blocks at the x and the baseline that
2020    /// their items carry.
2021    #[test]
2022    fn a_page_of_positioned_blocks_exports_where_the_display_structure_put_them() {
2023        let text = |value: &str| Inline::Text {
2024            id: Default::default(),
2025            value: value.into(),
2026            attributes: Attributes::default(),
2027            position: None,
2028            span: None,
2029        };
2030        let mut book = book(
2031            "My father had a small estate in Nottinghamshire, and I was the third of \
2032             five sons. He sent me to Emanuel College in Cambridge at fourteen years old.",
2033        );
2034        let blocks = &mut book.sections[0].blocks;
2035        blocks.insert(
2036            0,
2037            Block::Heading {
2038                id: Default::default(),
2039                level: HeadingLevel::H1,
2040                inlines: vec![text("Raised")],
2041                attributes: Attributes::default(),
2042                position: None,
2043                span: None,
2044            },
2045        );
2046        blocks.push(Block::Blockquote {
2047            id: Default::default(),
2048            blocks: vec![Block::Paragraph {
2049                id: Default::default(),
2050                inlines: vec![text("Lifted against the page")],
2051                attributes: Attributes::default(),
2052                position: None,
2053                span: None,
2054            }],
2055            attributes: Attributes::default(),
2056            position: None,
2057            span: None,
2058        });
2059        book.assign_node_ids();
2060        let styles = crate::style::Stylesheets::parse(&[crate::style::Source::author(
2061            "positioned.css",
2062            "h1 { position: relative; top: -12pt } \
2063             blockquote { position: absolute; bottom: 1in; left: 0.5in; margin: 0 }",
2064        )])
2065        .compile(&book, registry());
2066        let output = crate::layout::layout_book(&book, &styles, registry(), &Assets::none());
2067        let page = &output.pages[0];
2068
2069        let pdf = content(&readable(&output, &Metadata::default()));
2070        for word in ["Raised", "Lifted"] {
2071            let (x, baseline) = page
2072                .items
2073                .iter()
2074                .find_map(|item| match item {
2075                    DrawItem::Text { x, y, text, .. } if text.contains(word) => Some((*x, *y)),
2076                    _ => None,
2077                })
2078                .unwrap_or_else(|| panic!("no run of {word} on the page"));
2079            // krilla writes text under a flip, so the line sits at the
2080            // x and the baseline the item carries.
2081            let placed = format!("1 0 0 -1 {x} {baseline} Tm");
2082            assert!(
2083                pdf.contains(&placed),
2084                "{word} is not set at {placed}:\n{pdf}",
2085            );
2086        }
2087    }
2088
2089    /// An image nothing supplied is no draw item, and one warning
2090    /// names the url.
2091    #[test]
2092    fn an_image_no_host_supplied_is_reported_and_skipped() {
2093        let mut book = Book {
2094            sections: vec![Section {
2095                attributes: Default::default(),
2096                blocks: vec![Block::Image {
2097                    id: Default::default(),
2098                    url: "missing.png".into(),
2099                    alt: "a map".into(),
2100                    attributes: Attributes::default(),
2101                    position: None,
2102                    span: None,
2103                }],
2104                ..Default::default()
2105            }],
2106            ..Default::default()
2107        };
2108        book.assign_node_ids();
2109        let output = laid_out(&book);
2110        assert!(
2111            !output.pages.iter().any(|page| page
2112                .items
2113                .iter()
2114                .any(|item| matches!(item, DrawItem::Image { .. }))),
2115            "an image with no bytes was placed anyway",
2116        );
2117        assert_eq!(output.warnings.len(), 1, "{:?}", output.warnings);
2118        assert!(output.warnings[0].message.contains("missing.png"));
2119    }
2120
2121    /// Book metadata reaches the document information dictionary.
2122    #[test]
2123    fn metadata_carries_the_book_title() {
2124        let book = book("Some prose.");
2125        let pdf = readable(&laid_out(&book), &book.metadata);
2126        assert!(pdf.contains("/Title (Gulliver's Travels)"), "no title");
2127        assert!(pdf.contains("/Author (Jonathan Swift)"), "no author");
2128        assert!(pdf.contains("/Producer (fleuron)"), "no producer");
2129        assert!(
2130            pdf.contains("/CreationDate (D:17261028"),
2131            "the book's own date is not the creation date:\n{pdf}",
2132        );
2133    }
2134
2135    /// A date the book does not write is no creation date, rather
2136    /// than the hour the run happened to start: the engine reads no
2137    /// clock, and two runs over one book are one file.
2138    #[test]
2139    fn a_book_with_no_date_is_stamped_with_none() {
2140        let mut book = book("Some prose.");
2141        book.metadata.extra.remove("date");
2142        let pdf = readable(&laid_out(&book), &book.metadata);
2143        assert!(!pdf.contains("/CreationDate"), "a clock was read");
2144    }
2145
2146    /// Text is selectable because every glyph maps back to the
2147    /// characters it was shaped from: the ffi ligature is one glyph
2148    /// and three code points in the ToUnicode map.
2149    #[test]
2150    fn glyphs_map_back_to_their_characters() {
2151        let pdf = readable(&laid_out(&book("difficult offices")), &Metadata::default());
2152        assert!(pdf.contains("/ToUnicode"), "no ToUnicode map");
2153        assert!(
2154            pdf.contains("<006600660069>"),
2155            "the ffi ligature does not map back to f, f, i:\n{pdf}"
2156        );
2157    }
2158
2159    /// A transformed run is drawn in the letters the transform asked
2160    /// for and read back in the ones the author wrote: the glyphs are
2161    /// the capitals, and the ToUnicode map sends them to the source.
2162    #[test]
2163    fn a_transformed_run_extracts_as_it_was_written() {
2164        let book = book("Some prose.");
2165        let styles = crate::style::Stylesheets::parse(&[crate::style::Source::author(
2166            "author.css",
2167            "p { text-transform: uppercase }",
2168        )])
2169        .compile(&book, registry());
2170        let output = crate::layout::layout_book(&book, &styles, registry(), &Assets::none());
2171        let (text, source) = output
2172            .pages
2173            .iter()
2174            .flat_map(|page| &page.items)
2175            .find_map(|item| match item {
2176                DrawItem::Text { text, source, .. } => Some((text.clone(), source.clone())),
2177                _ => None,
2178            })
2179            .expect("the book set a line");
2180        assert_eq!(
2181            (text.as_str(), source.as_str()),
2182            ("SOME PROSE.", "Some prose.")
2183        );
2184
2185        let pdf = readable(&output, &Metadata::default());
2186        // The drawn capitals map back to what was written: an `O`
2187        // that stands for an `o` is the whole of the difference.
2188        assert!(
2189            pdf.contains("<006F>"),
2190            "the ToUnicode map does not send the capitals to the source:\n{pdf}",
2191        );
2192    }
2193
2194    /// A first line transformed is drawn in the letters the transform
2195    /// asked for and read back in the ones the author wrote, and the
2196    /// rest of the paragraph is untouched.
2197    #[test]
2198    fn a_transformed_first_line_extracts_as_it_was_written() {
2199        let book = book(&"my father had a small estate in nottinghamshire ".repeat(6));
2200        let styles = crate::style::Stylesheets::parse(&[crate::style::Source::author(
2201            "author.css",
2202            "p::first-line { text-transform: uppercase }",
2203        )])
2204        .compile(&book, registry());
2205        let output = crate::layout::layout_book(&book, &styles, registry(), &Assets::none());
2206        let drawn: Vec<(String, String)> = output
2207            .pages
2208            .iter()
2209            .flat_map(|page| &page.items)
2210            .filter_map(|item| match item {
2211                DrawItem::Text { text, source, .. } => Some((text.clone(), source.clone())),
2212                _ => None,
2213            })
2214            .collect();
2215        let (opening, written) = drawn.first().expect("the book set a line");
2216        assert_eq!(opening, &opening.to_uppercase());
2217        assert_eq!(written, &written.to_lowercase());
2218        assert_eq!(opening, &written.to_uppercase());
2219        assert!(
2220            drawn[1..]
2221                .iter()
2222                .all(|(text, source)| text == &text.to_lowercase() && source.is_empty()),
2223            "the transform ran past the first line",
2224        );
2225
2226        let pdf = readable(&output, &Metadata::default());
2227        assert!(
2228            pdf.contains("<006D>"),
2229            "the ToUnicode map does not send the capitals to the source:\n{pdf}",
2230        );
2231    }
2232
2233    /// The file is structurally whole — header, page tree, cross
2234    /// reference, trailer — which is what `qpdf --check` reads.
2235    #[test]
2236    fn the_document_is_structurally_whole() {
2237        let book = book("Some prose.");
2238        let output = laid_out(&book);
2239        let pdf = readable(&output, &book.metadata);
2240        assert!(pdf.starts_with("%PDF-1.7"), "no PDF header");
2241        assert!(
2242            pdf.contains(&format!("/Type /Pages\n  /Count {}", output.pages.len())),
2243            "page tree does not count the display structure's pages"
2244        );
2245        assert!(pdf.contains("startxref"), "no cross-reference offset");
2246        assert!(pdf.trim_end().ends_with("%%EOF"), "no trailer");
2247    }
2248
2249    /// A book of this many pages, each with a line of text on it.
2250    fn pages_of(count: usize) -> LayoutOutput {
2251        let book = book("Some prose.");
2252        let mut output = laid_out(&book);
2253        output.pages = (0..count).flat_map(|_| laid_out(&book).pages).collect();
2254        output
2255    }
2256
2257    /// Acceptance: the writer takes a count to pad to, an even one or
2258    /// a multiple of four, and the book has the least such count that
2259    /// holds its pages.
2260    #[test]
2261    fn a_book_is_padded_to_an_even_count_or_a_multiple_of_four() {
2262        for pages in 1..=9 {
2263            let output = pages_of(pages);
2264            assert_eq!(counted(&padded(&output, None)), pages);
2265
2266            let even = counted(&padded(&output, Some(PadTo::Even)));
2267            assert_eq!(even % 2, 0, "{pages} pages padded to {even}");
2268            assert!((pages..pages + 2).contains(&even), "{pages} to {even}");
2269
2270            let fours = counted(&padded(&output, Some(PadTo::MultipleOfFour)));
2271            assert_eq!(fours % 4, 0, "{pages} pages padded to {fours}");
2272            assert!((pages..pages + 4).contains(&fours), "{pages} to {fours}");
2273        }
2274    }
2275
2276    /// A book with no page has no last page to size a leaf by, and
2277    /// the file is the one the writer makes of it unpadded.
2278    #[test]
2279    fn a_book_with_no_page_is_not_padded() {
2280        let output = pages_of(0);
2281        assert_eq!(page_count(&output, Some(PadTo::MultipleOfFour)), 0);
2282        assert_eq!(
2283            padded(&output, Some(PadTo::MultipleOfFour)),
2284            padded(&output, None)
2285        );
2286    }
2287
2288    /// Acceptance: a blank leaf has the size of the book's last page,
2289    /// sheet and trim and bleed, and carries no folio, no running
2290    /// head and no other margin box.
2291    #[test]
2292    fn a_blank_leaf_is_the_size_of_the_last_page_and_carries_nothing() {
2293        let book = book("Some prose.");
2294        let furniture = "bleed: 3mm; marks: crop;
2295             @top-center { content: 'Gulliver' }
2296             @bottom-center { content: counter(page) }";
2297        let mut output = styled(
2298            &book,
2299            &format!("@page {{ size: 300pt 400pt; {furniture} }}"),
2300        );
2301        output.pages.extend(
2302            styled(
2303                &book,
2304                &format!("@page {{ size: 432pt 648pt; {furniture} }}"),
2305            )
2306            .pages,
2307        );
2308        assert_eq!(output.pages.len(), 2);
2309
2310        let pdf = padded(&output, Some(PadTo::MultipleOfFour));
2311        let pages = written_pages(&pdf);
2312        assert_eq!(pages.len(), 4);
2313        let (last, painted) = pages[1];
2314        assert!(
2315            painted.contains("Tj") || painted.contains("TJ"),
2316            "the last page of the book shows no folio, so this proves nothing:\n{painted}"
2317        );
2318        for (leaf, stream) in &pages[2..] {
2319            for name in ["MediaBox", "TrimBox", "BleedBox"] {
2320                assert_eq!(page_box(leaf, name), page_box(last, name), "{name}");
2321            }
2322            assert_eq!(stream.trim(), "", "a blank leaf paints something");
2323            assert!(!leaf.contains("/Annots"), "a blank leaf carries a link");
2324            assert!(!leaf.contains("/Font"), "a blank leaf names a face");
2325        }
2326        assert_ne!(
2327            page_box(pages[0].0, "MediaBox"),
2328            page_box(last, "MediaBox"),
2329            "the two pages of the book are one size, so this proves nothing"
2330        );
2331    }
2332
2333    /// Acceptance: the count the writer answers with is the count the
2334    /// file holds.
2335    #[test]
2336    fn the_count_answered_is_the_count_written() {
2337        for pages in 1..=9 {
2338            let output = pages_of(pages);
2339            for pad in [None, Some(PadTo::Even), Some(PadTo::MultipleOfFour)] {
2340                assert_eq!(
2341                    page_count(&output, pad),
2342                    counted(&padded(&output, pad)),
2343                    "{pages} pages, {pad:?}"
2344                );
2345            }
2346        }
2347    }
2348
2349    /// Two runs over one book produce byte-identical PDFs: nothing in
2350    /// the writer reads a clock or a hash of an address.
2351    #[test]
2352    fn writing_is_deterministic() {
2353        let book = book("Some prose, twice over.");
2354        let output = laid_out(&book);
2355        let table = assets(&[("plate.jpg", MAP)]);
2356        let first = write(&output, registry(), &table, &book.metadata).unwrap();
2357        let second = write(&output, registry(), &table, &book.metadata).unwrap();
2358        assert_eq!(first, second);
2359    }
2360}