//! TeX-style page building over an explicit vertical list. //! //! This module is the foundation for the TeX page builder described by P2 of //! `docs/ROUTE_D_PLAN.md`. Instead of stopping at the first box that does not //! fit, it scores every candidate breakpoint with TeX's page badness and //! penalty cost, so a fuller page can win over a much emptier one. Floats and //! insertion classes are still handled by the incremental builder in //! `Engine`; wiring this module into `Document` is the next P2 step. use std::collections::BTreeMap; use crate::Mark; /// Vertical glue with the stretch and shrink TeX uses to set a page. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct VerticalGlue { pub width: i64, pub stretch: i64, pub shrink: i64, /// TeX glue order: 0 is normal, 1 `\vfil`, 2 `\vfill`, 3 `\vfilll`. /// Page setting only uses glue of the highest order that has stretch. #[serde(default)] pub order: u8, } impl VerticalGlue { pub const fn new(width: i64, stretch: i64, shrink: i64) -> Self { Self { width, stretch, shrink, order: 0, } } /// Vertical glue with an explicit TeX order. pub const fn with_order(width: i64, stretch: i64, shrink: i64, order: u8) -> Self { Self { width, stretch, shrink, order, } } } /// Upper bound for one insertion class on a page (`\dimen` in TeX). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct InsertionLimit { pub class: u8, pub height: i64, } /// Space one insertion class occupies on a page. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct InsertionSpace { pub class: u8, pub height: i64, } /// Material that can appear in a vertical list handed to the page builder. #[derive(Clone, Debug, PartialEq, Eq)] pub enum VerticalNode { Box { height: i64, depth: i64, }, /// A top float: TeX puts it at the top of a page and never below body /// material, so a late float starts the next page. Float { height: i64, }, /// A bottom float: TeX reserves it at the bottom of the page, below the /// body material. BottomFloat { height: i64, }, Glue(VerticalGlue), Penalty(i64), Mark(Mark), /// `\insert` material: reserved at the page bottom, capped by the /// class limit; the remainder is held over to the next page. Insertion { class: u8, height: i64, }, } /// One page chosen by [`PageBuilder::build`]. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PageFragment { /// Index of the first node that belongs to this page. pub start: usize, /// Index one past the last node that belongs to this page. pub end: usize, /// TeX's page cost for the breakpoint: badness plus penalty. pub cost: i64, /// TeX `\outputpenalty` for this break: the penalty value when the page /// broke at a penalty, otherwise 10000 (glue break, goal overflow or the /// final page, exactly as TeX reports it). pub penalty: i64, /// Badness of the page height against the page goal. pub badness: i64, /// Height of the page box after glue setting. pub height: i64, /// Height reserved at the page bottom by bottom floats. pub bottom: i64, /// Depth of the page box, capped at `max_depth`. pub depth: i64, /// Total stretch of the vertical glue on the page (highest order only). pub stretch: i64, /// Highest glue order that contributes stretch: 0 normal, 1 `\vfil`, ... pub stretch_order: u8, /// Total shrink of the vertical glue on the page. pub shrink: i64, /// Stretch of each glue order: index 0 is normal, 1 is `\vfil`, 2 is /// `\vfill` and 3 is `\vfilll`. pub stretches: [i64; 4], /// Signed glue-setting amount applied to the page: positive stretch to /// fill the goal, negative shrink to fit it (zero when ragged). pub set: i64, /// Accepted insertion space per class, including material held over from /// the previous page. pub insertions: Vec, /// Bottom floats placed at this page's bottom, as heights in placement /// order, including floats carried over from the page before. pub bottom_floats: Vec, } #[derive(Clone, Debug)] struct Candidate { cost: i64, badness: i64, height: i64, depth: i64, stretch: i64, stretch_order: u8, shrink: i64, reserved: i64, bottom: i64, penalty: i64, end: usize, next: usize, } /// TeX page builder parameters (`\vsize`, `\topskip`, `\maxdepth`) plus one /// `\dimen` limit per insertion class. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PageBuilder { pub page_goal: i64, pub top_skip: i64, pub max_depth: i64, pub insertion_limits: Vec, /// TeX `\skip`: space above an insertion class on a page that /// carries it. Applied once per class, on top of the class limit. pub insertion_skips: Vec<(u8, i64)>, /// TeX `\textfloatsep`: space between top floats and the body. pub text_float_sep: i64, /// TeX floatsep: space between stacked bottom floats. pub float_sep: i64, /// TeX bottomfraction: percent of the page bottom floats may occupy. pub bottom_fraction_percent: u8, /// TeX `\topnumber`: maximum top floats on one page. pub top_number: usize, /// TeX `\bottomnumber`: maximum bottom floats on one page. pub bottom_number: usize, /// TeX `\totalnumber`: maximum floats, of any placement, on one page. pub total_number: usize, /// TeX `\floatpagefraction`: percent of the page floats must occupy /// before the body is pushed to the next page. pub float_page_fraction_percent: u8, /// TeX `\raggedbottom` (default) versus `\flushbottom`. pub ragged_bottom: bool, } impl PageBuilder { pub const fn new(page_goal: i64) -> Self { Self { page_goal, top_skip: 0, max_depth: 0, insertion_limits: Vec::new(), insertion_skips: Vec::new(), text_float_sep: 0, float_sep: 0, bottom_fraction_percent: 100, top_number: 2, bottom_number: 1, total_number: 12, float_page_fraction_percent: 50, ragged_bottom: true, } } /// Upper bound for `class` on one page; unlisted classes share the page. fn insertion_limit(&self, class: u8) -> i64 { self.insertion_limits .iter() .find(|limit| limit.class == class) .map_or(self.page_goal, |limit| limit.height.max(0)) } /// TeX's `\skip` for `class`. fn insertion_skip(&self, class: u8) -> i64 { self.insertion_skips .iter() .find(|(number, _)| *number == class) .map_or(0, |(_, skip)| (*skip).max(0)) } /// Replace the page goal used by later `build`/`build_from` calls. pub fn set_page_goal(&mut self, page_goal: i64) { self.page_goal = page_goal.max(1); } /// Split `nodes` into pages, choosing the cheapest legal break each time. pub fn build(&self, nodes: &[VerticalNode]) -> Vec { let mut pages = Vec::new(); let mut held = BTreeMap::new(); let mut start = self.skip_leading(nodes, 0); while start < nodes.len() { let Some((fragment, next, next_held, _, _)) = self.best_fragment(nodes, start, &held, &[], false) else { break; }; let next = next.max(start + 1); pages.push(fragment); held = next_held; start = self.skip_leading(nodes, next); } pages } /// Build pages starting at a node that begins a page. /// /// Insertion material is not carried over here: the incremental replay in /// `Engine` refuses documents that raise insertions, because held-over /// material can add pages that have no node start of their own. pub fn build_from(&self, nodes: &[VerticalNode], start: usize) -> Vec { let mut pages = Vec::new(); let mut next = self.skip_leading(nodes, start); while next < nodes.len() { let Some((fragment, after, _, _, _)) = self.best_fragment(nodes, next, &BTreeMap::new(), &[], false) else { break; }; let after = after.max(next + 1); pages.push(fragment); next = self.skip_leading(nodes, after); } pages } /// Split `nodes` into pages while deferring bottom floats that do not /// fit: the page keeps filling with body material and the float lands at /// the bottom of the following page (TeX's deferred float queue). pub fn build_with_deferred_bottom_floats(&self, nodes: &[VerticalNode]) -> Vec { let mut pages = Vec::new(); let mut carried: Vec = Vec::new(); let mut start = self.skip_leading(nodes, 0); while start < nodes.len() { let Some((fragment, next, _, _, deferred)) = self.best_fragment(nodes, start, &BTreeMap::new(), &carried, true) else { break; }; let next = next.max(start + 1); carried = deferred; pages.push(fragment); start = self.skip_leading(nodes, next); } if !carried.is_empty() { pages.push(self.float_page_fragment(nodes.len(), &carried)); } pages } fn float_page_fragment(&self, at: usize, floats: &[i64]) -> PageFragment { let mut bottom = 0_i64; for (index, height) in floats.iter().enumerate() { let gap = if index == 0 { self.text_float_sep.max(0) } else { self.float_sep.max(0) }; bottom += (*height).max(0) + gap; } PageFragment { start: at, end: at, cost: 0, penalty: 10_000, badness: 0, height: 0, bottom, depth: 0, stretch: 0, stretch_order: 0, shrink: 0, stretches: [0; 4], set: 0, insertions: Vec::new(), bottom_floats: floats.to_vec(), } } fn skip_leading(&self, nodes: &[VerticalNode], mut index: usize) -> usize { while index < nodes.len() { match nodes[index] { VerticalNode::Glue(_) | VerticalNode::Penalty(_) => index += 1, _ => break, } } index } fn best_fragment( &self, nodes: &[VerticalNode], start: usize, held: &BTreeMap, carried_floats: &[i64], defer_floats: bool, ) -> Option<(PageFragment, usize, BTreeMap, Vec, Vec)> { let mut height = 0_i64; let mut stretch_orders = [0_i64; 4]; let mut shrink = 0_i64; let mut depth = 0_i64; let mut first_box = true; let mut has_float = false; let mut has_body = false; let mut top_count = 0_usize; let mut float_total = 0_usize; let mut bottom = 0_i64; let mut bottom_count = 0_usize; let mut usage: BTreeMap = held.clone(); let mut reserved: i64 = usage.values().sum(); let mut candidates: Vec = Vec::new(); let mut bottom_floats: Vec = Vec::new(); let mut deferred_floats: Vec = Vec::new(); for height in carried_floats { let gap = if bottom_count == 0 { self.text_float_sep.max(0) } else { self.float_sep.max(0) }; bottom += (*height).max(0) + gap; bottom_count += 1; bottom_floats.push((*height).max(0)); float_total += 1; } let mut stopped_at_break = false; for index in start..nodes.len() { let (stretch, stretch_order) = effective_stretch(&stretch_orders); match &nodes[index] { VerticalNode::Box { height: box_height, depth: box_depth, } => { // TeX ships a page that is mostly floats on its own; the // body starts on the next page instead of sharing it. if has_float && !has_body && height * 100 >= i64::from(self.float_page_fraction_percent) * self.page_goal { let end = index.max(start); let badness = self.badness(height, reserved + bottom, stretch, shrink, stretch_order); let fragment = self.fragment( start, end, height, depth, stretch, shrink, stretch_order, badness, badness, 0, bottom, order_stretches(&nodes[start..end]), self.insertion_space(nodes, start, end, held), bottom_floats.clone(), ); return Some(( fragment, index, self.insertion_overflow(nodes, start, end, held), bottom_floats.clone(), deferred_floats.clone(), )); } let contribution = if first_box { (*box_height).max(self.top_skip) + if has_float { self.text_float_sep.max(0) } else { 0 } } else { *box_height }; // Consume the previous box's pending depth exactly once. // The current box leaves at most \maxdepth below the page. height += depth + contribution + (*box_depth - self.max_depth).max(0); depth = (*box_depth).min(self.max_depth); first_box = false; has_body = true; } VerticalNode::Float { height: float_height, } => { if height > 0 && (top_count >= self.top_number || float_total >= self.total_number) { // TeX never puts more top floats on one page than // `\topnumber`/`\totalnumber` allow: the float starts // the next page instead. let end = index.max(start); let badness = self.badness(height, reserved, stretch, shrink, stretch_order); let fragment = self.fragment( start, end, height, depth, stretch, shrink, stretch_order, badness, badness, 0, bottom, order_stretches(&nodes[start..end]), self.insertion_space(nodes, start, end, held), bottom_floats.clone(), ); return Some(( fragment, index, self.insertion_overflow(nodes, start, end, held), bottom_floats.clone(), deferred_floats.clone(), )); } // TeX installs a `[t]` float at the top of the page it is // seen on, pushing the body down by its height plus // `\textfloatsep` (or `\floatsep` between stacked // floats). Only a page that breaks before the float moves // it to the next page. if height > 0 { height += (*float_height).max(0) + if has_float { self.float_sep.max(0) } else { self.text_float_sep.max(0) }; } else { height += (*float_height).max(0); } has_float = true; top_count += 1; float_total += 1; } VerticalNode::BottomFloat { height: float_height, } => { let gap = if bottom_count == 0 { self.text_float_sep.max(0) } else { self.float_sep.max(0) }; let needed = (*float_height).max(0) + gap; let allowed = self.page_goal * i64::from(self.bottom_fraction_percent) / 100; // TeX defers a bottom float that does not fit and keeps // filling the page with body material; the float moves to // the next page's bottom area. if defer_floats && height > 0 && needed <= self.page_goal && needed <= allowed && (height + reserved + bottom + needed > self.page_goal || bottom + needed > allowed || bottom_count >= self.bottom_number || float_total >= self.total_number) { deferred_floats.push((*float_height).max(0)); continue; } if height > 0 && (height + reserved + bottom + needed > self.page_goal || bottom + needed > allowed || bottom_count >= self.bottom_number || float_total >= self.total_number) { let end = index.max(start); let badness = self.badness(height, reserved + bottom, stretch, shrink, stretch_order); let fragment = self.fragment( start, end, height, depth, stretch, shrink, stretch_order, badness, badness, 0, bottom, order_stretches(&nodes[start..end]), self.insertion_space(nodes, start, end, held), bottom_floats.clone(), ); return Some(( fragment, index, self.insertion_overflow(nodes, start, end, held), bottom_floats.clone(), deferred_floats.clone(), )); } bottom += needed; bottom_count += 1; float_total += 1; bottom_floats.push((*float_height).max(0)); } VerticalNode::Glue(glue) => { // TeX only allows a break at glue that follows a // non-discardable item: glue after glue is not a legal // breakpoint, and the glue at a break is discarded rather // than counted towards the page height. let legal_break = index > start && !matches!( nodes[index - 1], VerticalNode::Glue(_) | VerticalNode::Penalty(_) ); if legal_break { candidates.push(self.candidate( height, depth, stretch, shrink, stretch_order, reserved, bottom, 0, index, )); if candidates.last().unwrap().cost == 1_073_741_823 { stopped_at_break = true; break; } } height += depth + glue.width; depth = 0; let order = usize::from(glue.order.min(3)); stretch_orders[order] += glue.stretch.max(0); if order == 0 { shrink += glue.shrink.max(0); } } VerticalNode::Penalty(penalty) => { if *penalty <= -10_000 { candidates.push(self.candidate( height, depth, stretch, shrink, stretch_order, reserved, bottom, *penalty, index, )); // fire_up uses the best candidate seen so far. An // overfull forced point must not discard an earlier fit. stopped_at_break = true; break; } // TeX treats a penalty of 10000 or more as no break at // all; only the forced (<= -10000) case above is stronger. if index > start && *penalty < 10_000 { candidates.push(self.candidate( height, depth, stretch, shrink, stretch_order, reserved, bottom, *penalty, index, )); if candidates.last().unwrap().cost == 1_073_741_823 { stopped_at_break = true; break; } } } VerticalNode::Insertion { class, height: insert, } => { let limit = self.insertion_limit(*class); let first = !usage.contains_key(class); let skip = self.insertion_skip(*class); let used = usage.entry(*class).or_insert(0); if first { reserved += skip; } let capacity = (limit - *used).max(0); let taken = (*insert).min(capacity); *used += taken; reserved += taken; } VerticalNode::Mark(_) => {} } } let (stretch, stretch_order) = effective_stretch(&stretch_orders); let final_page_fits = !stopped_at_break && height + reserved + bottom <= self.page_goal; let mut final_break = self.candidate( height, depth, stretch, shrink, stretch_order, reserved, bottom, 0, nodes.len(), ); // TeX ends the job with infinite fill and a forced break. Without // that terminator a negative section penalty can split even a short // final page, and flushbottom stretches its body instead of the fill. if final_page_fits { final_break.cost = -10_000; final_break.badness = 0; } if !stopped_at_break { candidates.push(final_break); } let best = self.select(candidates)?; let mut fragment = self.fragment( start, best.end, best.height, best.depth, best.stretch, best.shrink, best.stretch_order, best.badness, best.cost, best.penalty, best.bottom, order_stretches(&nodes[start..best.end]), self.insertion_space(nodes, start, best.end, held), bottom_floats.clone(), ); if final_page_fits && best.end == nodes.len() { fragment.set = 0; } Some(( fragment, best.next, self.insertion_overflow(nodes, start, best.end, held), bottom_floats.clone(), deferred_floats.clone(), )) } fn insertion_space( &self, nodes: &[VerticalNode], start: usize, end: usize, held: &BTreeMap, ) -> Vec { let mut usage = held.clone(); for node in &nodes[start..end] { if let VerticalNode::Insertion { class, height } = node { let limit = self.insertion_limit(*class); let used = usage.entry(*class).or_insert(0); let capacity = (limit - *used).max(0); *used += (*height).min(capacity); } } usage .into_iter() .map(|(class, height)| InsertionSpace { class, height }) .collect() } fn insertion_overflow( &self, nodes: &[VerticalNode], start: usize, end: usize, held: &BTreeMap, ) -> BTreeMap { let mut requested = held.clone(); for node in &nodes[start..end] { if let VerticalNode::Insertion { class, height } = node { *requested.entry(*class).or_insert(0) += height; } } requested .into_iter() .filter_map(|(class, total)| { let overflow = total - self.insertion_limit(class); (overflow > 0).then_some((class, overflow)) }) .collect() } fn candidate( &self, height: i64, depth: i64, stretch: i64, shrink: i64, stretch_order: u8, reserved: i64, bottom: i64, penalty: i64, end: usize, ) -> Candidate { let depth = depth.max(0); let (height, depth) = if depth > self.max_depth { (height + depth - self.max_depth, self.max_depth) } else { (height, depth) }; let badness = self.badness(height, reserved + bottom, stretch, shrink, stretch_order); Candidate { // TeX build_page: saturated underfull badness has the fixed // deplorable cost; a finite penalty cannot distinguish such pages. cost: if height + reserved + bottom - self.page_goal > shrink { 1_073_741_823 // TeX awful_bad, which triggers fire_up. } else if penalty <= -10_000 { penalty } else if badness >= 10_000 { 100_000 } else { badness + penalty }, penalty, badness, height, depth, stretch, stretch_order, shrink, reserved, bottom, end, next: end + 1, } } fn badness( &self, height: i64, reserved: i64, stretch: i64, shrink: i64, stretch_order: u8, ) -> i64 { let goal = self.page_goal - reserved; if height == goal { return 0; } let (shortfall, slack) = if height < goal { // `\vfil` and higher orders stretch without bound: a page that // stops short of the goal is free when one of them is present. if stretch_order > 0 { return 0; } (goal - height, stretch) } else { (height - goal, shrink) }; if slack <= 0 { return 10_000; } let ratio = shortfall as f64 / slack as f64; let badness = 100.0 * ratio * ratio * ratio; if badness >= 10_000.0 { 10_000 } else { badness.round() as i64 } } #[allow(clippy::too_many_arguments)] fn fragment( &self, start: usize, end: usize, height: i64, depth: i64, stretch: i64, shrink: i64, stretch_order: u8, badness: i64, cost: i64, penalty: i64, bottom: i64, stretches: [i64; 4], insertions: Vec, bottom_floats: Vec, ) -> PageFragment { // The candidate already reserved each insertion class's \skip as // well as its material. Use the same reservation for glue setting; // otherwise footnote pages are stretched into their separator space. let reserved: i64 = insertions .iter() .map(|space| space.height + self.insertion_skip(space.class)) .sum(); let target = (self.page_goal - bottom - reserved).max(0); let set = if self.ragged_bottom { 0 } else if height < target { // TeX stretches glue past its nominal amount (the glue set ratio // is unbounded upward); only shrink is clamped. target - height } else if height > target { -(height - target).min(shrink) } else { 0 }; let penalty = if penalty == 0 { 10_000 } else { penalty }; PageFragment { start, end, cost, penalty, badness, height, bottom, depth, stretch, stretch_order, shrink, stretches, set, insertions, bottom_floats, } } fn select(&self, candidates: Vec) -> Option { let feasible: Vec = candidates .iter() .filter(|candidate| { let page = candidate.height + candidate.reserved + candidate.bottom; page <= self.page_goal || page - self.page_goal <= candidate.shrink }) .cloned() .collect(); if feasible.is_empty() { // Nothing fits: TeX ships an overfull page, and the least overfull // break keeps the damage minimal. return candidates.into_iter().min_by_key(|candidate| { ( candidate.cost, (candidate.height + candidate.reserved + candidate.bottom - self.page_goal) .abs(), ) }); } // TeX keeps the least-cost breakpoint and prefers the later one on a // tie (`<=` in the page builder's scan), so ties resolve by document // order rather than by distance to the page goal. feasible .into_iter() .min_by_key(|candidate| (candidate.cost, std::cmp::Reverse(candidate.end))) } } fn order_stretches(nodes: &[VerticalNode]) -> [i64; 4] { let mut stretches = [0_i64; 4]; for node in nodes { if let VerticalNode::Glue(glue) = node { let order = usize::from(glue.order.min(3)); stretches[order] += glue.stretch.max(0); } } stretches } fn effective_stretch(stretch_orders: &[i64; 4]) -> (i64, u8) { for (order, stretch) in stretch_orders.iter().enumerate().rev() { if *stretch > 0 { return (*stretch, order as u8); } } (0, 0) } #[cfg(test)] mod tests { use super::*; fn box_(height: i64, depth: i64) -> VerticalNode { VerticalNode::Box { height, depth } } fn glue(width: i64, stretch: i64, shrink: i64) -> VerticalNode { VerticalNode::Glue(VerticalGlue::new(width, stretch, shrink)) } #[test] fn deferred_bottom_float_continues_the_page() { let mut builder = PageBuilder::new(100); builder.text_float_sep = 0; let nodes = vec![ box_(30, 0), VerticalNode::BottomFloat { height: 80 }, glue(0, 0, 0), box_(30, 0), ]; let pages = builder.build_with_deferred_bottom_floats(&nodes); assert_eq!(pages.len(), 2); assert_eq!( pages[0].height, 60, "body continues past the deferred float" ); assert_eq!(pages[0].bottom, 0); assert_eq!(pages[1].bottom, 80, "float lands on the next page"); assert_eq!((pages[1].start, pages[1].end), (4, 4)); } #[test] fn fitting_bottom_float_stays_on_its_page() { let builder = PageBuilder::new(100); let nodes = vec![ box_(30, 0), VerticalNode::BottomFloat { height: 50 }, box_(10, 0), ]; let pages = builder.build_with_deferred_bottom_floats(&nodes); assert_eq!(pages.len(), 1); assert_eq!(pages[0].bottom, 50); } #[test] fn forced_penalty_breaks_record_the_penalty() { let builder = PageBuilder::new(100); let nodes = vec![box_(20, 0), VerticalNode::Penalty(-10_000), box_(20, 0)]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!(pages[0].penalty, -10_000); assert_eq!(pages[1].penalty, 10_000); } #[test] fn infinite_penalty_forbids_the_break() { let builder = PageBuilder::new(100); let nodes = vec![box_(60, 0), VerticalNode::Penalty(10_000), box_(60, 0)]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 1, "a 10000 penalty must not be a breakpoint"); } #[test] fn glue_breaks_report_a_ten_thousand_penalty() { let builder = PageBuilder::new(100); let nodes = vec![box_(80, 0), glue(0, 0, 0), box_(80, 0)]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!(pages[0].penalty, 10_000); assert_eq!(pages[1].penalty, 10_000); } #[test] fn breaks_before_the_page_overflows() { let builder = PageBuilder::new(100); let nodes = vec![ box_(40, 0), glue(0, 10, 0), box_(40, 0), glue(0, 10, 0), box_(40, 0), ]; let pages = builder.build(&nodes); assert_eq!( pages.iter().map(|page| page.height).collect::>(), vec![80, 40] ); assert_eq!(pages[0].badness, 800); } #[test] fn glue_stretch_can_fill_the_page_exactly() { let builder = PageBuilder::new(100); let nodes = vec![box_(50, 0), glue(0, 10, 0), box_(50, 0)]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 1); assert_eq!(pages[0].height, 100); assert_eq!(pages[0].badness, 0); } #[test] fn flush_bottom_stretches_glue_to_the_goal() { let nodes = vec![ box_(40, 0), glue(0, 10, 0), box_(40, 0), VerticalNode::Penalty(-10_000), ]; let mut builder = PageBuilder::new(120); assert_eq!( builder.build(&nodes)[0].set, 0, "ragged pages do not set glue" ); builder.ragged_bottom = false; let pages = builder.build(&nodes); assert_eq!(pages.len(), 1); assert_eq!(pages[0].set, 40); } #[test] fn insertion_separator_is_reserved_when_setting_page_glue() { let mut builder = PageBuilder::new(120); builder.ragged_bottom = false; builder.insertion_skips = vec![(0, 10)]; let pages = builder.build(&[ box_(40, 0), glue(0, 10, 0), VerticalNode::Insertion { class: 0, height: 10, }, box_(40, 0), VerticalNode::Penalty(-10_000), ]); assert_eq!(pages.len(), 1); assert_eq!( pages[0].set, 20, "120 - 80 body - 10 insertion - 10 separator" ); } #[test] fn short_final_page_uses_terminal_fill_instead_of_an_earlier_section_break() { let mut builder = PageBuilder::new(120); builder.ragged_bottom = false; let pages = builder.build(&[ box_(20, 0), VerticalNode::Penalty(-300), glue(0, 1, 0), box_(20, 0), ]); assert_eq!(pages.len(), 1); assert_eq!( pages[0].set, 0, "terminal fill must not stretch ordinary body glue" ); } #[test] fn glue_cannot_bypass_a_no_break_penalty() { let pages = PageBuilder::new(100).build(&[ box_(70, 0), VerticalNode::Penalty(10_000), glue(0, 0, 0), box_(70, 0), ]); assert_eq!(pages.len(), 1); assert_eq!(pages[0].height, 140); } #[test] fn fill_glue_makes_short_pages_free() { let nodes = vec![ box_(100, 0), VerticalNode::Glue(VerticalGlue::with_order(20, 1, 0, 1)), VerticalNode::Penalty(-10_000), ]; let mut builder = PageBuilder::new(200); builder.ragged_bottom = false; let pages = builder.build(&nodes); assert_eq!(pages.len(), 1); assert_eq!(pages[0].stretch_order, 1); assert_eq!(pages[0].stretch, 1); assert_eq!(pages[0].badness, 0); assert_eq!(pages[0].set, 80); } #[test] fn fragments_report_glue_stretch_and_shrink() { let builder = PageBuilder::new(100); let nodes = vec![box_(40, 0), glue(0, 20, 5), box_(40, 0)]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 1); assert_eq!(pages[0].height, 80); assert_eq!(pages[0].stretch, 20); assert_eq!(pages[0].shrink, 5); } #[test] fn fragments_record_stretch_by_glue_order() { let builder = PageBuilder::new(200); let nodes = vec![ box_(50, 0), VerticalNode::Glue(VerticalGlue::with_order(0, 20, 0, 0)), VerticalNode::Glue(VerticalGlue::with_order(0, 10, 0, 1)), VerticalNode::Glue(VerticalGlue::with_order(0, 5, 0, 2)), box_(50, 0), ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 1); assert_eq!(pages[0].stretches, [20, 10, 5, 0]); } #[test] fn forced_penalty_breaks_the_page() { let builder = PageBuilder::new(100); let nodes = vec![box_(30, 0), VerticalNode::Penalty(-10_000), box_(30, 0)]; let pages = builder.build(&nodes); assert_eq!( pages.iter().map(|page| page.height).collect::>(), vec![30, 30] ); } #[test] fn penalty_can_move_the_break_to_an_earlier_page() { let nodes = |penalty| { vec![ box_(40, 0), glue(0, 20, 0), box_(0, 0), VerticalNode::Penalty(0), box_(40, 0), VerticalNode::Penalty(penalty), box_(40, 0), ] }; let calm = PageBuilder::new(100).build(&nodes(0)); assert_eq!( calm.iter().map(|page| page.height).collect::>(), vec![80, 40] ); let penalized = PageBuilder::new(100).build(&nodes(9_500)); assert_eq!( penalized.iter().map(|page| page.height).collect::>(), vec![40, 80] ); } #[test] fn top_skip_sets_the_first_box_height() { let mut builder = PageBuilder::new(100); builder.top_skip = 10; let nodes = vec![box_(5, 0), glue(0, 0, 0), box_(5, 0)]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 1); assert_eq!(pages[0].height, 15); } #[test] fn max_depth_moves_excess_depth_into_the_height() { let mut builder = PageBuilder::new(100); builder.max_depth = 4; let pages = builder.build(&[box_(90, 10)]); assert_eq!(pages[0].height, 96); assert_eq!(pages[0].depth, 4); } #[test] fn equal_cost_breaks_prefer_the_later_candidate() { // Two legal breaks have cost zero: the earlier one is 5pt short of // the goal with 100pt of stretch, the later one overfills by 10pt // with 1000pt of shrink. TeX's page builder updates its best break // with `<=`, so the later candidate wins even though it is farther // from the goal. let builder = PageBuilder::new(200); let nodes = vec![ VerticalNode::Box { height: 90, depth: 0, }, VerticalNode::Glue(VerticalGlue::new(0, 100, 1000)), VerticalNode::Box { height: 105, depth: 0, }, VerticalNode::Glue(VerticalGlue::new(0, 0, 0)), VerticalNode::Box { height: 15, depth: 0, }, VerticalNode::Glue(VerticalGlue::new(0, 0, 0)), ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 1); assert_eq!(pages[0].height, 210); } #[test] fn overfull_pages_take_the_least_overfull_break() { let builder = PageBuilder::new(50); let nodes = [ VerticalNode::Box { height: 60, depth: 0, }, VerticalNode::Glue(VerticalGlue::new(0, 0, 0)), VerticalNode::Box { height: 40, depth: 0, }, ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!(pages[0].height, 60, "the shorter overfull page wins"); } #[test] fn marks_do_not_change_page_heights() { let builder = PageBuilder::new(100); let nodes = vec![ VerticalNode::Mark(Mark { class: 0, text: "intro".to_owned(), }), box_(30, 0), VerticalNode::Mark(Mark { class: 0, text: "next".to_owned(), }), glue(0, 0, 0), box_(30, 0), ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 1); assert_eq!(pages[0].height, 60); assert_eq!((pages[0].start, pages[0].end), (0, 5)); } fn limit(class: u8, height: i64) -> InsertionLimit { InsertionLimit { class, height } } #[test] fn insertion_skip_reserves_space_once_per_class() { let nodes = [ VerticalNode::Box { height: 30, depth: 0, }, VerticalNode::Glue(VerticalGlue { width: 0, stretch: 100, shrink: 0, order: 0, }), VerticalNode::Insertion { class: 1, height: 50, }, VerticalNode::Glue(VerticalGlue { width: 0, stretch: 100, shrink: 0, order: 0, }), VerticalNode::Box { height: 20, depth: 0, }, ]; let mut plain = PageBuilder::new(100); plain.insertion_limits = vec![InsertionLimit { class: 1, height: 100, }]; assert_eq!(plain.build(&nodes).len(), 1); let mut skipped = PageBuilder::new(100); skipped.insertion_limits = vec![InsertionLimit { class: 1, height: 100, }]; skipped.insertion_skips = vec![(1, 10)]; let pages = skipped.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!(pages[0].start, 0); assert_eq!(pages[0].end, 3); } #[test] fn insertion_reservation_pushes_the_break_earlier() { let mut builder = PageBuilder::new(100); builder.insertion_limits = vec![limit(1, 100)]; let nodes = vec![ box_(60, 0), VerticalNode::Insertion { class: 1, height: 30, }, glue(0, 10, 0), box_(40, 0), ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2, "the reservation must split the page"); assert_eq!(pages[0].height, 60); assert_eq!( pages[0].insertions, vec![InsertionSpace { class: 1, height: 30 }] ); assert_eq!(pages[1].height, 40); assert!(pages[1].insertions.is_empty()); } #[test] fn insertion_overflow_is_held_over_to_the_next_page() { let builder = PageBuilder { insertion_limits: vec![limit(1, 20)], ..PageBuilder::new(100) }; let nodes = vec![ box_(30, 0), VerticalNode::Insertion { class: 1, height: 20, }, glue(0, 40, 0), box_(30, 0), VerticalNode::Insertion { class: 1, height: 20, }, glue(0, 40, 0), box_(30, 0), ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!(pages[0].height, 60); assert_eq!( pages[0].insertions, vec![InsertionSpace { class: 1, height: 20 }] ); assert_eq!(pages[1].height, 30); assert_eq!( pages[1].insertions, vec![InsertionSpace { class: 1, height: 20 }], "the overflow material is held over to the next page" ); } #[test] fn bottom_floats_reserve_space_at_the_page_bottom() { let builder = PageBuilder::new(100); let nodes = vec![ box_(80, 0), glue(0, 0, 0), VerticalNode::BottomFloat { height: 30 }, ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!(pages[0].height, 80); assert_eq!(pages[0].bottom, 0); assert_eq!(pages[1].bottom, 30); } #[test] fn stacked_bottom_floats_add_float_separators() { let builder = PageBuilder { float_sep: 5, bottom_number: 2, ..PageBuilder::new(100) }; let nodes = vec![ box_(50, 0), VerticalNode::BottomFloat { height: 20 }, VerticalNode::BottomFloat { height: 20 }, ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 1); assert_eq!(pages[0].bottom, 45); } #[test] fn top_number_limits_stacked_top_floats() { let builder = PageBuilder { top_number: 1, ..PageBuilder::new(100) }; let nodes = vec![ VerticalNode::Float { height: 20 }, VerticalNode::Float { height: 20 }, box_(10, 0), ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!(pages[0].height, 20); assert_eq!(pages[1].height, 30); } #[test] fn bottom_number_limits_stacked_bottom_floats() { let builder = PageBuilder { bottom_number: 1, ..PageBuilder::new(100) }; let nodes = vec![ box_(50, 0), VerticalNode::BottomFloat { height: 20 }, VerticalNode::BottomFloat { height: 20 }, ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!(pages[0].bottom, 20); assert_eq!(pages[1].bottom, 20); } #[test] fn total_number_counts_every_float_placement() { let builder = PageBuilder { total_number: 1, ..PageBuilder::new(100) }; let nodes = vec![ VerticalNode::Float { height: 10 }, VerticalNode::BottomFloat { height: 10 }, box_(10, 0), ]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!(pages[0].bottom, 0); assert_eq!(pages[1].bottom, 10); } #[test] fn float_page_fraction_pushes_the_body_to_the_next_page() { let nodes = vec![ VerticalNode::Float { height: 60 }, VerticalNode::Box { height: 10, depth: 0, }, ]; let mut builder = PageBuilder::new(100); builder.float_page_fraction_percent = 50; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!((pages[0].start, pages[0].end), (0, 1)); assert_eq!(pages[1].start, 1); builder.float_page_fraction_percent = 90; assert_eq!(builder.build(&nodes).len(), 1); } #[test] fn bottom_fraction_caps_bottom_float_space() { let builder = PageBuilder { bottom_fraction_percent: 20, ..PageBuilder::new(100) }; let nodes = vec![box_(50, 0), VerticalNode::BottomFloat { height: 30 }]; let pages = builder.build(&nodes); assert_eq!(pages.len(), 2); assert_eq!(pages[0].bottom, 0); assert_eq!(pages[1].bottom, 30); } }