1use 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#[derive(Debug, thiserror::Error)]
43pub enum PdfError {
44 #[error("font {0} could not be embedded")]
46 Font(String),
47 #[error("image {0} could not be embedded")]
49 Image(String),
50 #[error("page {number} draws {kind} outside what PDF can express")]
52 Geometry {
53 number: u32,
55 kind: &'static str,
57 },
58 #[error("PDF serialization failed: {0}")]
60 Serialize(String),
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70pub enum PadTo {
71 Even,
73 MultipleOfFour,
75}
76
77impl PadTo {
78 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
89pub 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
96pub 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
114pub 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 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
190fn 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
210fn 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
221fn 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
232fn 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
241enum Embedded {
243 Raster(Image),
245 Vector(Box<svg::Vector>),
247}
248
249impl Embedded {
250 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
259fn 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
283fn 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
302fn 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
330fn 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
356fn 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
390fn 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 features: _,
432 origin: _,
433 pseudo_element: _,
434 width: _,
436 layer: _,
439 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 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 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 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 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
604const KAPPA: f32 = 0.552_284_8;
608
609fn 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
653fn 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
665const TILES: usize = 4096;
670
671fn 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 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
704fn 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
714fn 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
736fn opacity(alpha: u8) -> NormalizedF32 {
738 NormalizedF32::new(alpha as f32 / 255.0).unwrap_or(NormalizedF32::ONE)
739}
740
741fn 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 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
785struct Extracted<'a> {
788 text: &'a str,
789 ranges: Vec<std::ops::Range<usize>>,
790}
791
792fn 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
822fn 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 const MAP: &[u8] = include_bytes!("../../../fixtures/images/plate.jpg");
848
849 const ORNAMENT: &[u8] = include_bytes!("../../../fixtures/images/fleuron.png");
852 const ORNAMENT_WEBP: &[u8] = include_bytes!("../../../fixtures/images/fleuron.webp");
853 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 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 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 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 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 fn readable(output: &LayoutOutput, metadata: &Metadata) -> String {
969 with_images(output, &Assets::none(), metadata)
970 }
971
972 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 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 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 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 fn content(pdf: &str) -> String {
1052 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 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 #[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 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 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 #[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 #[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 #[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 assert_eq!(page_box(&pdf, "Rect"), Some([19.0, 184.0, 49.0, 189.0]));
1164 }
1165
1166 #[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 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 #[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 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 #[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 #[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 #[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 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 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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 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 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 #[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 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 #[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 #[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 #[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 #[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 #[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 assert!(
2189 pdf.contains("<006F>"),
2190 "the ToUnicode map does not send the capitals to the source:\n{pdf}",
2191 );
2192 }
2193
2194 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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}