1mod background;
32mod build;
33mod cap;
34mod exclusion;
35mod float;
36mod flow;
37mod fragment;
38mod furniture;
39mod image;
40mod inline;
41mod list;
42mod navigation;
43mod note;
44mod reference;
45mod sheet;
46mod table;
47mod text;
48
49#[cfg(test)]
50mod testing;
51
52pub use build::Reflow;
53pub use fragment::{
54 BreakPoint, Decoration, Decorations, DropCap, Floated, Fragment, Marker, Marks, Piece, TableRow,
55};
56pub use furniture::margin_band;
57pub use note::Note;
58
59use background::Backdrop;
60
61pub(crate) use exclusion::AnchoredBoxes;
62pub(crate) use flow::{PageInfo, Paged};
63pub(crate) use navigation::{navigation, run_area};
64pub(crate) use note::{Numbering, UNSETTLED};
65pub(crate) use reference::{Named, References, landed, moved};
66
67use std::borrow::Cow;
68use std::cell::{Cell, OnceCell, RefCell};
69use std::collections::{BTreeSet, HashSet};
70
71use crate::content::{Book, Metadata, origin};
72use crate::fonts::{FeatureSetting, FontRegistry};
73use crate::images::{Assets, Contours};
74use crate::lines::{LineLayout, ParagraphStyle, Patterns};
75use crate::pages::{DrawItem, Page, Side};
76use crate::session::Session;
77use crate::style::{Background, Float, PageGeometry, PageStyle, Position, StyleTree};
78use crate::{LayoutOutput, Warning};
79
80use flow::{Flow, PageSlot};
81
82pub(crate) const NOTE_PASSES: u32 = 4;
87
88pub fn layout_book(
98 book: &Book,
99 styles: &StyleTree,
100 registry: &FontRegistry,
101 assets: &Assets,
102) -> LayoutOutput {
103 Session::once(book, styles, registry, assets).into_output()
104}
105
106pub(crate) fn no_assets() -> &'static Assets {
108 static EMPTY: std::sync::OnceLock<Assets> = std::sync::OnceLock::new();
109 EMPTY.get_or_init(Assets::none)
110}
111
112pub(crate) fn no_contours() -> &'static Contours {
114 static EMPTY: std::sync::OnceLock<Contours> = std::sync::OnceLock::new();
115 EMPTY.get_or_init(Contours::none)
116}
117
118pub(crate) fn font_table(registry: &FontRegistry) -> Vec<crate::fonts::FontRefEntry> {
120 (0..registry.len() as u16)
121 .filter_map(|id| registry.font_ref(id).cloned())
122 .collect()
123}
124
125pub struct Paginator<'a> {
132 registry: &'a FontRegistry,
133 styles: &'a StyleTree,
134 assets: &'a Assets,
135 contours: &'a Contours,
138 lines: LineLayout<'a>,
139 patterns: Cell<Patterns>,
141 unknown: RefCell<Option<String>>,
144 warnings: RefCell<Vec<Warning>>,
148 uncovered: RefCell<Vec<UncoveredWarning>>,
152 wraps: OnceCell<bool>,
155 floats: OnceCell<bool>,
157 rebreaks: Cell<u32>,
159 references: RefCell<References>,
161 notes: RefCell<Numbering>,
163 settles: Cell<u32>,
166}
167
168#[derive(Debug, Clone, PartialEq)]
174pub(crate) struct UncoveredWarning {
175 pub(crate) character: char,
176 pub(crate) source: Option<String>,
178 pub(crate) warning: Warning,
179}
180
181impl UncoveredWarning {
182 pub(crate) fn warnings<'f>(
185 found: impl IntoIterator<Item = &'f UncoveredWarning>,
186 ) -> Vec<Warning> {
187 let mut seen = HashSet::new();
188 found
189 .into_iter()
190 .filter(|found| seen.insert((found.source.as_deref(), found.character)))
191 .map(|found| found.warning.clone())
192 .collect()
193 }
194}
195
196impl<'a> Paginator<'a> {
197 pub fn new(registry: &'a FontRegistry, styles: &'a StyleTree) -> Self {
200 Paginator::with_assets(registry, styles, no_assets())
201 }
202
203 pub fn with_assets(
208 registry: &'a FontRegistry,
209 styles: &'a StyleTree,
210 assets: &'a Assets,
211 ) -> Self {
212 Paginator::with_contours(registry, styles, assets, no_contours())
213 }
214
215 pub fn with_contours(
217 registry: &'a FontRegistry,
218 styles: &'a StyleTree,
219 assets: &'a Assets,
220 contours: &'a Contours,
221 ) -> Self {
222 Paginator {
223 registry,
224 styles,
225 assets,
226 contours,
227 lines: LineLayout::new(registry),
228 patterns: Cell::new(Patterns::default()),
229 unknown: RefCell::new(None),
230 warnings: RefCell::new(Vec::new()),
231 uncovered: RefCell::new(Vec::new()),
232 wraps: OnceCell::new(),
233 floats: OnceCell::new(),
234 rebreaks: Cell::new(0),
235 references: RefCell::new(References::default()),
236 notes: RefCell::new(Numbering::default()),
237 settles: Cell::new(0),
238 }
239 }
240}
241
242impl Paginator<'_> {
243 pub fn language(&self, metadata: &Metadata) {
252 let patterns = Patterns::of(metadata);
253 self.patterns.set(patterns);
254 *self.unknown.borrow_mut() = metadata
255 .language()
256 .filter(|_| patterns == Patterns::NONE)
257 .map(str::to_string);
258 }
259
260 fn patterns(&self) -> Patterns {
264 if let Some(tag) = self.unknown.borrow().as_deref() {
265 self.warn(
266 format!(
267 "No hyphenation patterns for `{tag}`. Hyphenation is skipped for that \
268 language."
269 ),
270 None,
271 );
272 }
273 self.patterns.get()
274 }
275
276 pub fn warnings(&self) -> Vec<Warning> {
278 let mut warnings = self.flow_warnings();
279 let uncovered = self.uncovered.borrow();
280 warnings.extend(uncovered.iter().map(|found| found.warning.clone()));
281 warnings
282 }
283
284 pub(crate) fn flow_warnings(&self) -> Vec<Warning> {
286 self.warnings.borrow().clone()
287 }
288
289 pub(crate) fn uncovered(&self) -> Vec<UncoveredWarning> {
292 self.uncovered.borrow().clone()
293 }
294
295 fn uncover(&self, source: Option<&str>) {
298 let mut uncovered = self.uncovered.borrow_mut();
299 for found in self.lines.take_uncovered() {
300 let seen = uncovered
301 .iter()
302 .any(|seen| seen.character == found.character && seen.source.as_deref() == source);
303 if seen {
304 continue;
305 }
306 let face = self
307 .registry
308 .font_ref(found.font_id)
309 .map(|entry| entry.name.clone())
310 .unwrap_or_default();
311 let at = origin(source, found.position);
312 uncovered.push(UncoveredWarning {
313 character: found.character,
314 source: source.map(str::to_string),
315 warning: Warning {
316 message: format!(
317 "{face} has no glyph for `{}` (U+{:04X}).",
318 found.character, found.character as u32,
319 ),
320 origin: (!at.is_empty()).then_some(at),
321 },
322 });
323 }
324 }
325
326 pub fn rebreaks(&self) -> u32 {
329 self.rebreaks.get()
330 }
331
332 pub fn settles(&self) -> u32 {
336 self.settles.get()
337 }
338
339 pub(crate) fn refer(&self, references: References) {
343 *self.references.borrow_mut() = references;
344 }
345
346 fn wraps(&self) -> bool {
352 *self.wraps.get_or_init(|| {
353 self.floats()
354 || self
355 .styles
356 .styles()
357 .iter()
358 .any(|style| style.position == Position::Absolute)
359 })
360 }
361
362 pub(super) fn floats(&self) -> bool {
364 *self.floats.get_or_init(|| {
365 self.styles
366 .styles()
367 .iter()
368 .any(|style| style.float != Float::None)
369 })
370 }
371
372 fn warn(&self, message: String, origin: Option<String>) {
375 let mut warnings = self.warnings.borrow_mut();
376 if !warnings.iter().any(|seen| seen.message == message) {
377 warnings.push(Warning { message, origin });
378 }
379 }
380
381 fn superior(&self, mut style: ParagraphStyle) -> ParagraphStyle {
390 const SUPS: [u8; 4] = *b"sups";
391 if self.registry.has_feature(style.font_id, SUPS) {
392 style.features.push(FeatureSetting::new(SUPS, 1));
393 return style;
394 }
395 let family = self
396 .registry
397 .font_ref(style.font_id)
398 .map(|entry| entry.family.clone())
399 .unwrap_or_default();
400 self.warn(
401 format!(
402 "{family} has no superior figures. The reference of a note stands on the \
403 baseline."
404 ),
405 None,
406 );
407 style
408 }
409
410 fn backdrop(&self, background: &Background) -> Backdrop {
416 let found = background.image.as_ref().and_then(|url| {
417 let found = self.assets.lookup(&url.value);
418 if found.is_none() {
419 self.missing(&url.value, url.origin.clone().unwrap_or_default());
420 }
421 found
422 });
423 Backdrop::of(background, found)
424 }
425
426 fn missing(&self, url: &str, origin: String) {
427 if !self.assets.probed(url) {
428 self.warn(
429 format!("No image was supplied for {url}. The image is skipped."),
430 (!origin.is_empty()).then_some(origin),
431 );
432 }
433 }
434
435 pub fn paginate(&self, book: &Book) -> Vec<Page> {
444 self.paginated(book).pages
445 }
446
447 pub(crate) fn paginated(&self, book: &Book) -> Paged {
449 self.language(&book.metadata);
450 if self.styles.refers() {
451 self.refer(References::of(book));
452 }
453 self.number(Numbering::of(book, self.styles));
454 let mut paged = self.pass(book);
455 if self.styles.numbers_notes_per_page() {
456 paged = self.settle_notes(book, paged);
457 }
458 if self.styles.counts_pages() {
459 let found = landed(&paged);
460 let resolved = self.references.borrow().landed(found.clone());
461 self.refer(resolved);
462 self.settles.set(self.settles.get() + 1);
463 paged = self.pass(book);
464 let references = self.references.borrow();
465 let printed: BTreeSet<_> = book
466 .sections
467 .iter()
468 .flat_map(|section| Named::in_section(section, self.styles, &references).pages)
469 .collect();
470 for warning in moved(&found, &landed(&paged), &printed, &references) {
471 self.warn(warning.message, warning.origin);
472 }
473 }
474 self.paint(&mut paged.pages, &paged.infos);
475 paged
476 }
477
478 fn settle_notes(&self, book: &Book, mut paged: Paged) -> Paged {
486 let start = self.styles.first_note_number();
487 for _ in 0..NOTE_PASSES {
488 let numbered = self.notes.borrow().on_pages(&paged.notes, start);
489 if numbered == *self.notes.borrow() {
490 return paged;
491 }
492 self.number(numbered);
493 self.settles.set(self.settles.get() + 1);
494 paged = self.pass(book);
495 }
496 self.warn(note::UNSETTLED.to_string(), None);
497 paged
498 }
499
500 fn pass(&self, book: &Book) -> Paged {
502 let anchored = self.anchored(book, |index| {
503 Cow::Owned(self.section_fragments(&book.sections[index]))
504 });
505 let mut flow = Flow::new(self, anchored);
506 for section in &book.sections {
507 let fragments = self.section_fragments(section);
508 flow.section(section, &fragments);
509 }
510 flow.finish()
511 }
512
513 fn anchored<'f>(
521 &self,
522 book: &Book,
523 mut fragments: impl FnMut(usize) -> Cow<'f, [Fragment]>,
524 ) -> AnchoredBoxes {
525 let boxes = self.anchored_boxes(book, &[]);
526 if boxes.is_empty() {
527 return AnchoredBoxes::default();
528 }
529 let mut settled = self.settle(book, boxes, &mut fragments);
530 if let Some(within) = settled.narrowed() {
531 let boxes = self.anchored_boxes(book, &within);
532 settled.relaid(boxes, within);
533 }
534 settled
535 }
536
537 pub fn flow(&self, book: &Book, sections: &[Vec<Fragment>]) -> Vec<Page> {
541 let mut paged = self.fragment(book, sections.iter().map(Vec::as_slice));
542 self.paint(&mut paged.pages, &paged.infos);
543 paged.pages
544 }
545
546 pub(crate) fn fragment<'f>(
549 &self,
550 book: &Book,
551 sections: impl IntoIterator<Item = &'f [Fragment]>,
552 ) -> Paged {
553 let sections: Vec<&[Fragment]> = sections.into_iter().collect();
554 let anchored = self.anchored(book, |index| Cow::Borrowed(sections[index]));
555 let mut flow = Flow::new(self, anchored);
556 for (section, fragments) in book.sections.iter().zip(§ions) {
557 flow.section(section, fragments);
558 }
559 flow.finish()
560 }
561
562 fn master(&self, index: usize, slot: &PageSlot) -> &PageStyle {
564 self.styles
565 .page(slot.query(Side::of_number(index as u32 + 1)))
566 }
567
568 fn blank_page(&self, slot: &PageSlot) -> Page {
571 let geometry = self.sheet(slot);
572 Page {
573 number: 0,
574 side: Side::Verso,
575 width: geometry.width,
576 height: geometry.height,
577 bleed: geometry.bleed(),
578 slug: geometry.slug(),
579 sections: Vec::new(),
580 items: Vec::new(),
581 links: Vec::new(),
582 }
583 }
584
585 fn marks(&self, slot: &PageSlot) -> Vec<DrawItem> {
587 sheet::marks(self.sheet(slot))
588 }
589
590 fn sheet(&self, slot: &PageSlot) -> PageGeometry {
592 self.styles.page(slot.query(Side::Verso)).geometry
593 }
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599 use crate::layout::testing::{book_of, heading, long_prose, registry, section};
600
601 #[test]
605 fn the_stages_compose_into_what_paginate_does() {
606 let book = book_of(vec![
607 section(long_prose(30)),
608 section([vec![heading("Two")], long_prose(24)].concat()),
609 ]);
610 let styles = crate::style::defaults(&book, registry());
611 let paginator = Paginator::new(registry(), &styles);
612
613 let staged: Vec<Vec<Fragment>> = book
614 .sections
615 .iter()
616 .map(|section| paginator.section_fragments(section))
617 .collect();
618 let by_stage = paginator.flow(&book, &staged);
619 let in_one = paginator.paginate(&book);
620
621 assert!(in_one.len() > 2, "a book worth splitting");
622 assert_eq!(by_stage.len(), in_one.len());
623 for (staged, whole) in by_stage.iter().zip(&in_one) {
624 assert_eq!(staged.number, whole.number);
625 assert_eq!(staged.side, whole.side);
626 assert_eq!(format!("{:?}", staged.items), format!("{:?}", whole.items));
627 }
628 }
629}