use crate::{document::BlockBox, layout::LayoutError};
use std::{
cell::{Cell, RefCell},
rc::Rc,
};
const MARK_SHIFTS: [u32; 4] = [4, 3, 2, 1];
#[derive(Clone)]
pub(crate) struct Budget {
limit: usize,
remaining: Rc<Cell<Option<usize>>>,
declined: Rc<Cell<bool>>,
frontier: Rc<Cell<Frontier>>,
marks: Rc<RefCell<Vec<Frontier>>>,
next_mark: Rc<Cell<usize>>,
nested: bool,
}
type Frontier = Option<*const BlockBox>;
#[derive(Debug)]
pub(crate) struct Exhausted {
pub(crate) limit: usize,
}
impl From<Exhausted> for LayoutError {
fn from(Exhausted { limit }: Exhausted) -> Self {
Self::WorkLimit { limit }
}
}
impl Budget {
pub(crate) fn new(limit: usize) -> Self {
Self {
limit,
remaining: Rc::new(Cell::new(Some(limit))),
declined: Rc::new(Cell::new(false)),
frontier: Rc::default(),
marks: Rc::default(),
next_mark: Rc::new(Cell::new(limit >> MARK_SHIFTS[0])),
nested: false,
}
}
pub(crate) fn spend_optional(&self, units: usize) -> bool {
if let Some(left) = self
.remaining
.get()
.and_then(|left| left.checked_sub(units))
{
self.remaining.set(Some(left));
true
} else {
self.declined.set(true);
false
}
}
pub(crate) fn declined(&self) -> Option<usize> {
self.declined.get().then_some(self.limit)
}
pub(crate) fn exhausted(&self) -> Option<usize> {
self.remaining.get().is_none().then_some(self.limit)
}
pub(crate) fn spent(&self) -> usize {
self.limit - self.remaining.get().unwrap_or(0)
}
pub(crate) fn charge(&self, units: usize) {
self.remaining.set(
self.remaining
.get()
.and_then(|left| left.checked_sub(units)),
);
}
pub(crate) fn nested(&self) -> Self {
Self {
nested: true,
..self.clone()
}
}
pub(crate) fn start(&self, block: &BlockBox) {
if !self.nested {
self.frontier.set(Some(std::ptr::from_ref(block)));
}
}
pub(crate) fn frontier(&self) -> Frontier {
self.frontier.get()
}
pub(crate) fn marks(&self) -> Vec<Frontier> {
self.marks.borrow().clone()
}
pub(crate) fn spend(&self, units: usize) -> Result<(), Exhausted> {
let remaining = self
.remaining
.get()
.and_then(|left| left.checked_sub(units));
self.remaining.set(remaining);
let spent = self.spent();
if spent >= self.next_mark.get() {
let mut marks = self.marks.borrow_mut();
while let Some(shift) = MARK_SHIFTS.get(marks.len())
&& spent >= self.limit >> shift
{
marks.push(self.frontier.get());
}
self.next_mark.set(
MARK_SHIFTS
.get(marks.len())
.map_or(usize::MAX, |shift| self.limit >> shift),
);
}
remaining.map(|_| ()).ok_or(Exhausted { limit: self.limit })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::StyledDocument;
use crate::layout::{MAX_FAILED_LAYOUT_BUDGETS, MAX_LAYOUT_WORK, layout_with_work_limit};
use crate::resources::{FileResolver, ResourceBase};
#[test]
fn target_stabilization_charges_all_passes_to_one_budget() {
let resolver = crate::tests::common::fixture_resolver();
let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let mut document = StyledDocument::parse(
"<style>@font-face{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}body{font-family:Fixed}p::after{content:target-counter('#target',page)}h2{break-before:page}</style><p>See </p><h2 id=target>Destination</h2>",
&base, &[], &resolver,
).unwrap();
let measurement = Budget::new(MAX_LAYOUT_WORK);
crate::layout::layout_pass(&document, &resolver, measurement.clone()).unwrap();
let first_pass_work = MAX_LAYOUT_WORK - measurement.remaining.get().unwrap();
assert!(first_pass_work > 0);
let provisional = crate::layout::stabilize(
&mut document,
&resolver,
&Budget::new(first_pass_work),
Vec::new(),
)
.expect("a budget that only fits the provisional pass keeps that pass");
let text: Vec<_> = provisional
.pages
.iter()
.flatten()
.map(|line| line.text.as_str())
.collect();
assert_eq!(
text,
["See", "Destination"],
"the kept pass is the provisional one, whose target counter is not yet resolved"
);
let diagnostics = document.into_diagnostics();
assert_eq!(
diagnostics
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>(),
[crate::layout::LayoutDiagnostic::WorkLimit {
limit: first_pass_work,
kept: crate::layout::WorkFallback::LastPass,
}
.to_string()],
"the budget is shared by every pass and its exhaustion is reported once"
);
assert!(
crate::checked_diagnostics(diagnostics, crate::ContentLoss::Fail).is_ok(),
"keeping the last pass loses no content, so the default policy renders it"
);
}
#[test]
fn a_first_pass_out_of_work_omits_the_content_it_reached_late() {
const ITEMS: usize = 300;
let resolver = crate::tests::common::fixture_resolver();
let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let document = || {
StyledDocument::parse(
&format!(
"<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0;font:10pt/10pt Fixed}}</style><p>before</p><section>{}</section><p>after</p>",
"<div>item</div>".repeat(ITEMS)
),
&base,
&[],
&resolver,
)
.unwrap()
};
let limit = required_work(&document(), &resolver) / 2;
let (document, trace) = crate::layout::layout_within(
document(),
&resolver,
limit,
&Budget::new(limit * MAX_FAILED_LAYOUT_BUDGETS),
)
.expect("a document that exceeds its work budget keeps the content laid out within it");
let text: Vec<_> = trace
.pages
.iter()
.flatten()
.map(|line| line.text.as_str())
.collect();
let items = text.iter().filter(|line| **line == "item").count();
assert_eq!(text.first(), Some(&"before"), "the content before is kept");
assert!(
(1..ITEMS).contains(&items) && !text.contains(&"after"),
"the content from a box started late in the budget is omitted: \
{items} of {ITEMS} items kept, text ends {:?}",
text.last()
);
let diagnostics = document.into_diagnostics();
assert_eq!(
diagnostics
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>(),
[crate::layout::LayoutDiagnostic::WorkLimit {
limit,
kept: crate::layout::WorkFallback::Truncated,
}
.to_string()],
"the omission is reported once however many layouts it takes"
);
match crate::checked_diagnostics(diagnostics, crate::ContentLoss::Fail) {
Err(crate::Error::ContentLost { diagnostics }) => assert_eq!(
diagnostics.len(),
1,
"the default policy fails with the truncation: {diagnostics:?}"
),
other => panic!(
"the default policy must fail on the truncated content, got {:?}",
other.map(|_| ())
),
}
}
#[test]
fn failed_layouts_share_one_bounded_budget_before_all_content_is_omitted() {
const ITEMS: usize = 40;
const SECTIONS: usize = crate::layout::MAX_OMITTED_BOXES;
const FAILING_BOX: &str = "<div class=over></div>";
let resolver = crate::tests::common::fixture_resolver();
let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let parse = |failing: &str| {
StyledDocument::parse(
&format!(
"<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0;font:10pt/10pt Fixed}}.over{{padding:3e38pt 0}}</style>{}",
format!("<section>{}</section>{failing}", "<div>item</div>".repeat(ITEMS))
.repeat(SECTIONS)
),
&base,
&[],
&resolver,
)
.unwrap()
};
let omitted = |document: StyledDocument| {
document.into_diagnostics().into_iter().any(|diagnostic| {
matches!(
diagnostic,
crate::RenderDiagnostic::Layout(crate::LayoutDiagnostic::OmittedBox { .. })
)
})
};
let limit = required_work(&parse(""), &resolver);
let unbounded = Budget::new(usize::MAX);
let (document, trace) =
crate::layout::layout_within(parse(FAILING_BOX), &resolver, limit, &unbounded)
.expect("omitting each failing box completes the layout");
let unbounded_work = unbounded.spent();
assert!(
unbounded_work > limit && omitted(document),
"fixture: omitting the {SECTIONS} failing boxes one at a time spends {unbounded_work} \
units in failed layouts, more than one {limit}-unit layout budget"
);
assert!(
trace.pages.iter().flatten().any(|line| line.text == "item"),
"fixture: with work to spare for failed layouts the items stay"
);
let failed = Budget::new(limit);
let (document, trace) =
crate::layout::layout_within(parse(FAILING_BOX), &resolver, limit, &failed)
.expect("failed layouts past their shared budget omit all content, not fail");
assert!(
failed.exhausted().is_some(),
"the failed layouts stop once they spend the {limit} units they share"
);
let text: Vec<_> = trace
.pages
.iter()
.flatten()
.map(|line| line.text.as_str())
.collect();
assert!(
text.is_empty(),
"the layout after them omits all content: {text:?}"
);
assert!(omitted(document), "the omitted boxes are reported");
}
#[test]
fn exhaustion_is_inclusive_overflow_safe_and_sticky() {
let budget = Budget::new(8);
budget.spend(3).unwrap();
budget.spend(5).unwrap();
assert!(matches!(budget.spend(1), Err(Exhausted { limit: 8 })));
assert!(matches!(budget.spend(0), Err(Exhausted { limit: 8 })));
let budget = Budget::new(usize::MAX - 1);
assert!(matches!(budget.spend(usize::MAX), Err(Exhausted { .. })));
assert!(budget.spend(1).is_err());
}
#[test]
fn column_candidates_share_the_jobs_budget_without_poisoning_later_jobs() {
const LIMIT: usize = 8192;
let resolver = crate::tests::common::fixture_resolver();
let content = "<div class=item></div>".repeat(320);
let parse = |columns| {
StyledDocument::parse(
&format!(
"<!doctype html><style>@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0}}.item{{height:10pt}}section{{{columns}}}</style><section>{content}</section>"
),
&ResourceBase::default(),
&[],
&resolver,
).unwrap()
};
let ordinary = parse("");
let columns = parse("column-count:2;column-gap:10pt");
let expected = layout_with_work_limit(&ordinary, &resolver, LIMIT).unwrap();
match layout_with_work_limit(&columns, &resolver, LIMIT) {
Err(LayoutError::WorkLimit { limit }) => assert_eq!(limit, LIMIT),
Err(error) => panic!("unexpected column failure: {error}"),
Ok(trace) => panic!(
"column probes escaped the shared budget: {} pages",
trace.pages.len()
),
}
let completed = layout_with_work_limit(&columns, &resolver, MAX_LAYOUT_WORK).unwrap();
assert!(!completed.pages.is_empty());
let next = layout_with_work_limit(&ordinary, &resolver, LIMIT).unwrap();
assert_eq!(expected.pages.len(), next.pages.len());
}
#[test]
fn automatic_columns_resume_each_row_within_the_shared_work_budget() {
const LIMIT: usize = 16_384;
const BLOCKS: usize = 256;
const BLOCKS_PER_PAGE: usize = 8;
let resolver = crate::tests::common::fixture_resolver();
let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let content = (0..BLOCKS)
.map(|index| {
format!("<div id=item{index}><a href=\"#item{index}\">B{index:03}</a></div>")
})
.collect::<String>();
let document = StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 40pt;margin:0}}html,body{{margin:0;font:10pt/10pt Fixed;widows:1;orphans:1}}section{{column-count:2;column-gap:10pt;column-fill:auto}}div{{height:10pt;background:red}}</style><section>{content}</section>"),
&base, &[], &resolver,
).unwrap();
assert_eq!(
document.navigation().destinations,
BLOCKS,
"fixture must register each linked target"
);
let output = layout_with_work_limit(&document, &resolver, LIMIT).unwrap_or_else(|error| {
panic!("each physical row must resume its source checkpoint: {error}")
});
assert_eq!(output.pages.len(), BLOCKS / BLOCKS_PER_PAGE);
assert_eq!(
output.destinations.iter().flatten().count(),
BLOCKS,
"every source target must be placed exactly once"
);
let actual = output
.pages
.iter()
.flatten()
.map(|line| line.text.as_str())
.collect::<Vec<_>>();
let expected = (0..BLOCKS)
.map(|index| format!("B{index:03}"))
.collect::<Vec<_>>();
assert_eq!(
actual, expected,
"each visible source label must be preserved once"
);
for (index, destination) in output.destinations.iter().enumerate() {
let destination = destination.as_ref().expect("every block keeps its target");
assert_eq!(
destination.page,
index / BLOCKS_PER_PAGE,
"item{index} was replayed or placed on the wrong physical page"
);
}
}
#[test]
fn mixed_native_css_layout_and_raw_paint_share_a_bounded_measurement_cache() {
const SEGMENTS: usize = 8;
const LIMIT: usize = 1_000_000;
const SMALLER_LIMIT: usize = LIMIT / 1000;
let resolver = crate::tests::common::fixture_resolver();
let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let open = "<mrow><mtext><span style='display:block;writing-mode:vertical-rl'><math>";
let close = "</math></span></mtext></mrow>";
let parse = |segments| {
StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}math{{font:10pt Fixed}}</style><math>{}<mn>1</mn>{}</math>", open.repeat(segments), close.repeat(segments)),
&base, &[], &resolver,
).unwrap()
};
let document = parse(SEGMENTS);
let check = || {
let output = layout_with_work_limit(&document, &resolver, LIMIT)
.unwrap_or_else(|error| panic!("{SEGMENTS} auto-sized mixed native/CSS boundaries must reuse measurement dependencies through raw paint within {LIMIT} shared units: {error}"));
assert_eq!(
output
.pages
.iter()
.flatten()
.filter(|line| line.text == "1")
.count(),
1,
"the single retained token must survive every native/CSS transport exactly once"
);
};
check();
assert!(
matches!(
layout_with_work_limit(&document, &resolver, SMALLER_LIMIT),
Err(LayoutError::WorkLimit {
limit: SMALLER_LIMIT
})
),
"the same auto-sized orthogonal candidates must exhaust a smaller shared budget with the typed error"
);
check();
}
#[test]
fn wide_native_math_batches_siblings_under_one_linear_work_budget() {
const TOKENS: usize = 8192;
const WORK_PER_TOKEN: usize = 512;
const LIMIT: usize = TOKENS * WORK_PER_TOKEN;
let resolver = crate::tests::common::fixture_resolver();
let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let content = (0..TOKENS)
.map(|index| format!("<mn id=token{index}>1</mn>"))
.collect::<String>();
let document = StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:100000pt 100pt;margin:0}}html,body{{margin:0}}math{{font:10pt Fixed}}</style><math>{content}</math>"),
&base, &[], &resolver,
).unwrap();
assert_eq!(document.navigation().destinations, TOKENS);
for limit in [MAX_LAYOUT_WORK, LIMIT] {
let output = layout_with_work_limit(&document, &resolver, limit)
.unwrap_or_else(|error| panic!("{TOKENS} native siblings must batch within {limit} shared work units: {error}"));
assert_eq!(
output.pages.len(),
1,
"the wide physical page must hold one native row"
);
let lines = output.pages[0]
.iter()
.filter(|line| line.text == "1")
.collect::<Vec<_>>();
assert_eq!(
lines.len(),
TOKENS,
"every canonical token must paint exactly once"
);
assert!(
output.pages[0].iter().all(|line| line.text == "1"
|| line
.text
.chars()
.all(|ch| ch == crate::document::OBJECT_REPLACEMENT_CHARACTER)),
"the host atomic placeholder must not introduce additional visible text"
);
assert!(
lines
.windows(2)
.all(|pair| pair[0].paragraph < pair[1].paragraph)
&& lines.iter().all(|line| line.width > 0.0),
"batch replay must preserve canonical sibling order and positive glyph advances"
);
let mut paragraphs = lines.iter().map(|line| line.paragraph).collect::<Vec<_>>();
paragraphs.sort_unstable();
paragraphs.dedup();
assert_eq!(
paragraphs.len(),
TOKENS,
"native siblings must retain distinct canonical paragraph identities"
);
assert_eq!(
output.destinations.iter().flatten().count(),
TOKENS,
"each canonical target must retain one page location"
);
}
const EXHAUSTED_LIMIT: usize = TOKENS;
assert!(
matches!(
layout_with_work_limit(&document, &resolver, EXHAUSTED_LIMIT),
Err(LayoutError::WorkLimit {
limit: EXHAUSTED_LIMIT
})
),
"native frame requests must consume the shared job budget"
);
assert!(
layout_with_work_limit(&document, &resolver, LIMIT).is_ok(),
"a bounded failure must not poison the next render of the same retained source"
);
}
#[test]
fn balancing_stops_when_adjacent_heights_cannot_be_bisected() {
const LIMIT: usize = 4096;
let resolver = crate::tests::common::fixture_resolver();
let document = StyledDocument::parse(
"<!doctype html><style>@page{size:200pt 2000000pt;margin:0}html,body{margin:0}section{column-count:2;column-gap:0}div{height:1000000pt}</style><section><div></div><div></div></section>",
&ResourceBase::default(),
&[],
&resolver,
).unwrap();
let output = layout_with_work_limit(&document, &resolver, LIMIT)
.unwrap_or_else(|error| panic!("finite two-column balance failed: {error}"));
assert_eq!(output.pages.len(), 1);
}
#[test]
fn repeated_table_geometry_consumes_the_same_budget() {
const LIMIT: usize = 1024;
const ROWS: usize = 32;
let resolver = crate::tests::common::fixture_resolver();
let body = "<tr><td><div></div></td></tr>".repeat(ROWS);
let document = StyledDocument::parse(
&format!("<!doctype html><style>@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0}}table{{border-spacing:0}}td{{padding:0}}thead div{{height:40pt}}tbody div{{height:100pt}}</style><table><thead><tr><td><div></div></td></tr></thead><tbody>{body}</tbody></table>"),
&ResourceBase::default(), &[], &resolver,
).unwrap();
assert!(
matches!(
layout_with_work_limit(&document, &resolver, LIMIT),
Err(LayoutError::WorkLimit { limit: LIMIT })
),
"repeated table measurement escaped the job budget"
);
let output = layout_with_work_limit(&document, &resolver, MAX_LAYOUT_WORK).unwrap();
assert_eq!(
output.pages.len(),
ROWS,
"each page fits one body row and its repeated header"
);
}
#[test]
fn generated_margin_text_shares_the_body_budget() {
const LIMIT: usize = 4096;
const PAGES: usize = 8;
let resolver = crate::tests::common::fixture_resolver();
let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let body = "<div></div>".repeat(PAGES);
let margin = "A ".repeat(256);
let parse = |margin_rule| {
StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 200pt;margin:20pt;{margin_rule}}}html,body{{margin:0}}div{{height:160pt;background:#eee}}</style>{body}"),
&base, &[], &resolver,
).unwrap()
};
let ordinary = parse("");
assert_eq!(
layout_with_work_limit(&ordinary, &resolver, LIMIT)
.unwrap()
.pages
.len(),
PAGES
);
let margins = parse(&format!(
"@top-center{{font:1pt/1pt Fixed;content:'{margin}'}}"
));
assert!(
matches!(
layout_with_work_limit(&margins, &resolver, LIMIT),
Err(LayoutError::WorkLimit { limit: LIMIT })
),
"generated text escaped the job budget"
);
let output = layout_with_work_limit(&margins, &resolver, MAX_LAYOUT_WORK).unwrap();
assert_eq!(output.pages.len(), PAGES);
for (page, lines) in output.pages.iter().enumerate() {
let count = lines
.iter()
.flat_map(|line| line.text.split_whitespace())
.count();
assert_eq!(count, 256, "margin text lost on page {}", page + 1);
}
}
fn required_work(document: &StyledDocument, resolver: &FileResolver) -> usize {
const PRECISION: usize = 64;
let fits = |limit| match layout_with_work_limit(document, resolver, limit) {
Ok(_) => true,
Err(LayoutError::WorkLimit { .. }) => false,
Err(error) => panic!("layout failed with {error} instead of exhausting its budget"),
};
let (mut fails, mut fits_within) = (0, 1);
while !fits(fits_within) {
assert!(
fits_within < MAX_LAYOUT_WORK,
"the document must lay out within the layout budget"
);
fails = fits_within;
fits_within *= 2;
}
while (fits_within - fails) * PRECISION > fits_within {
let limit = fails + (fits_within - fails) / 2;
if fits(limit) {
fits_within = limit;
} else {
fails = limit;
}
}
fits_within
}
#[test]
fn footnote_parts_copy_only_the_lines_they_show() {
const FOOTNOTES: usize = 96;
let resolver = crate::tests::common::fixture_resolver();
let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let work = |count: usize| {
let calls = (0..count)
.map(|index| format!("w{index}<span class=fn>note {index}</span> "))
.collect::<String>();
let document = StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:120pt 120pt;margin:10pt}}html,body{{margin:0;font:10pt/10pt Fixed}}.fn{{float:footnote;footnote-display:inline}}</style><p>{calls}</p>"),
&base, &[], &resolver,
)
.unwrap();
required_work(&document, &resolver)
};
let (single, doubled) = (work(FOOTNOTES), work(2 * FOOTNOTES));
assert!(
doubled < 3 * single,
"doubling the footnotes doubles the pages and the body's lines, so copying each part \
whole would quadruple the charged work: {FOOTNOTES} footnotes need {single} units, \
{} need {doubled}",
2 * FOOTNOTES
);
}
const NO_ROOM_PAGE: &str = "@page{size:200pt 100pt;margin:50pt 0}";
fn page_text(trace: &crate::layout::LayoutTrace) -> Vec<Vec<&str>> {
trace
.pages
.iter()
.map(|lines| lines.iter().map(|line| line.text.as_str()).collect())
.collect()
}
#[test]
fn row_lanes_start_fragmentainers_without_room_instead_of_yielding_them_again() {
const LIMIT: usize = 65_536;
let resolver = crate::tests::common::fixture_resolver();
let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let document = StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}{NO_ROOM_PAGE}body{{margin:10pt 0 0;font:10pt/10pt Fixed}}</style><div style=\"display:flex\"><div>a1<br>a2<br>a3</div><div>b1<br>b2</div></div>"),
&base, &[], &resolver,
)
.unwrap();
let output = layout_with_work_limit(&document, &resolver, LIMIT).unwrap_or_else(|error| {
panic!(
"lanes yielding a fragmentainer that holds no content never progress, so they \
exhaust any budget: {error}"
)
});
let pages = page_text(&output);
let lines: Vec<_> = pages.iter().flatten().copied().collect();
for lane in [["a1", "a2", "a3"].as_slice(), &["b1", "b2"]] {
let placed: Vec<_> = lines
.iter()
.copied()
.filter(|text| lane.contains(text))
.collect();
assert_eq!(
placed, lane,
"each lane places its lines once, in order: {pages:?}"
);
}
}
#[test]
fn grid_lanes_in_a_shrink_to_fit_float_of_a_thousand_columns_progress() {
let resolver = crate::tests::common::fixture_resolver();
let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let document = StyledDocument::parse(
"<!doctype html><style>@font-face{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}body{font:10pt/10pt Fixed}</style><div style=\"float:left\">words <div style=\"column-count:1000\">column text <div style=\"display:grid\">grid text</div></div></div>",
&base, &[], &resolver,
)
.unwrap();
const LIMIT: usize = 65_536;
let output = layout_with_work_limit(&document, &resolver, LIMIT).unwrap_or_else(|error| {
panic!(
"lanes yielding columns that hold no content never progress, so they exhaust \
any budget: {error}"
)
});
let pages = page_text(&output);
let mut words: Vec<_> = pages
.iter()
.flatten()
.flat_map(|line| line.split_whitespace())
.collect();
words.sort_unstable();
assert_eq!(
words,
["column", "grid", "text", "text", "words"],
"every word is placed once: {pages:?}"
);
}
#[test]
fn floats_across_fragmentainers_measure_their_content_once_per_containing_block() {
const LINES: usize = 48;
let resolver = crate::tests::common::fixture_resolver();
let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let work = |lines: usize| {
let content = (0..lines)
.map(|index| format!("<div>line {index}</div>"))
.collect::<String>();
let document = StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 10pt;margin:0}}html,body{{margin:0;font:10pt/10pt Fixed}}</style><div style=\"float:left\">{content}</div>"),
&base, &[], &resolver,
)
.unwrap();
required_work(&document, &resolver)
};
let (single, doubled) = (work(LINES), work(2 * LINES));
assert!(
doubled < 3 * single,
"doubling the lines doubles the pages and the content, so measuring the content on \
each page would quadruple the charged work: {LINES} lines need {single} units, {} \
need {doubled}",
2 * LINES
);
}
#[test]
fn table_rows_progress_past_repeated_edges_that_fill_their_fragmentainers() {
const LIMIT: usize = 65_536;
let resolver = crate::tests::common::fixture_resolver();
let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let document = StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}{NO_ROOM_PAGE}body{{font:10pt/10pt Fixed}}td{{padding:10pt}}</style><table><tr><td>r1a</td><td>r1b</td></tr><tr><td>r2a</td><td>r2b</td></tr></table><p>after</p>"),
&base, &[], &resolver,
)
.unwrap();
let pass = crate::layout::layout_pass(&document, &resolver, Budget::new(LIMIT))
.unwrap_or_else(|error| panic!("rows on fragmentainers without room failed: {error}"));
assert_eq!(
pass.diagnostics,
[],
"the rows progress, so no content is omitted at the page limit"
);
let pages = page_text(&pass.trace);
let mut lines: Vec<_> = pages.iter().flatten().copied().collect();
lines.sort_unstable();
assert_eq!(
lines,
["after", "r1a", "r1b", "r2a", "r2b"],
"every cell and the paragraph after the table are placed once: {pages:?}"
);
}
#[test]
fn fixed_columns_without_room_for_cloned_edges_take_1px_of_content_each() {
const LIMIT: usize = 4096;
const CONTENT_HEIGHT: f32 = 100.0;
let resolver = crate::tests::common::fixture_resolver();
let document = StyledDocument::parse(
&format!("<!doctype html><style>@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0}}section{{column-count:2;column-gap:10pt;column-fill:auto;height:10pt}}div{{height:{CONTENT_HEIGHT}pt;padding:10pt;box-decoration-break:clone;background:blue}}</style><section><div></div></section>"),
&ResourceBase::default(), &[], &resolver,
).unwrap();
let pass = crate::layout::layout_pass(&document, &resolver, Budget::new(LIMIT))
.unwrap_or_else(|error| {
panic!("fixed columns without room past cloned edges must still progress: {error}")
});
assert_eq!(pass.diagnostics, [], "no content is omitted");
assert_eq!(
pass.trace.pages.len(),
1,
"the columns overflow inline, on one page"
);
let blue: Vec<_> = pass.trace.display_lists[0]
.iter()
.filter_map(|item| match item {
crate::graphics::DisplayItem::Box(paint)
if paint.decoration.background.rgb == [0, 0, 255] =>
{
Some(paint)
}
_ => None,
})
.collect();
let columns = (CONTENT_HEIGHT / crate::graphics::POINTS_PER_PIXEL).ceil() as usize;
assert!(
blue.len() >= columns,
"each column takes at most 1px of the {CONTENT_HEIGHT}pt content, so it needs \
{columns} columns, got {} fragments",
blue.len()
);
assert!(
blue.windows(2).all(|pair| pair[0].rect.x < pair[1].rect.x),
"each fragment lies in the next overflow column: {:?}",
blue.iter().map(|paint| paint.rect.x).collect::<Vec<_>>()
);
}
#[test]
fn paginating_a_table_takes_work_linear_in_its_rows() {
const ROWS: usize = 96;
let resolver = crate::tests::common::fixture_resolver();
let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let work = |collapse: &str, css: &str, rows: usize| {
let body = "<tr><td rowspan=2>span</td><td>first</td><td>x</td></tr><tr><td>second</td><td>y</td></tr><tr class=third><td>third</td><td>z</td><td>w</td></tr>"
.repeat(rows / 6);
let document = StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0;font:8pt/10pt Fixed}}table{{width:100%;border-collapse:{collapse}}}td,th{{border:1pt solid;padding:1pt}}{css}</style><table><thead><tr><th>head</th><th>a</th><th>b</th></tr></thead><tfoot><tr><td>foot</td><td>c</td><td>d</td></tr></tfoot><tbody>{body}</tbody><tbody>{body}</tbody></table>"),
&base, &[], &resolver,
)
.unwrap();
let budget = Budget::new(MAX_LAYOUT_WORK);
let trace = crate::layout::layout_pass(&document, &resolver, budget.clone())
.unwrap_or_else(|error| {
panic!("{collapse} table of {rows} rows with `{css}` failed: {error}")
})
.trace;
let heads = trace
.pages
.iter()
.filter(|page| page.iter().any(|line| line.text == "head"))
.count();
assert!(
trace.pages.len() > 1 && heads == trace.pages.len(),
"fixture: the {collapse} table of {rows} rows with `{css}` spans pages that \
each repeat its header, but {heads} of {} pages show it",
trace.pages.len()
);
budget.spent()
};
for (collapse, css) in [
("separate", ""),
("collapse", ""),
("separate", "td{height:12pt}"),
("collapse", ".third{visibility:collapse}"),
] {
crate::work::assert_linear(
&format!("rows of a {collapse} table with `{css}`"),
ROWS,
|rows| work(collapse, css, rows),
);
}
}
fn paged_document(body: &str, resolver: &FileResolver) -> StyledDocument {
let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0;font:8pt/10pt Fixed}}</style>{body}"),
&base, &[], resolver,
)
.unwrap()
}
fn paged_pass(
what: &str,
document: &StyledDocument,
resolver: &FileResolver,
budget: Budget,
) -> crate::layout::LayoutPass {
let pass = crate::layout::layout_pass(document, resolver, budget)
.unwrap_or_else(|error| panic!("{what} failed: {error}"));
assert!(
pass.trace.pages.len() > 1,
"fixture: {what} spans pages, but lays out on {} page",
pass.trace.pages.len()
);
pass
}
fn paged_work(what: &str, body: &str, work: crate::work::Work) -> usize {
let resolver = crate::tests::common::fixture_resolver();
let document = paged_document(body, &resolver);
let (_, units) = crate::work::measured(work, || {
paged_pass(what, &document, &resolver, Budget::new(MAX_LAYOUT_WORK))
});
units
}
#[test]
fn rows_of_a_row_spanning_band_take_work_linear_in_its_rows() {
const ROWS: usize = 240;
type Collapsed = fn(usize) -> bool;
let cases: [(&str, Collapsed); 2] = [
("every row kept", |_| false),
("two of every three rows collapsed", |row| row % 3 != 0),
];
for (rows_kept, gone) in cases {
crate::work::assert_linear(
&format!(
"fragmentainers visited to place the rows of a row-spanning band, {rows_kept}"
),
ROWS,
|rows| {
let body: String = (1..rows)
.map(|row| {
let class = if gone(row) { " class=gone" } else { "" };
format!("<tr{class}><td>r{row}</td></tr>")
})
.collect();
paged_work(
&format!("a band of {rows} rows, {rows_kept}"),
&format!(
"<style>td{{border:1pt solid}}.gone{{visibility:collapse}}</style><table><tr><td rowspan={rows}>span</td><td>r0</td></tr>{body}</table>"
),
crate::work::Work::BandPage,
)
},
);
}
}
#[test]
fn laying_out_flex_items_takes_work_linear_in_their_count() {
const ITEMS: usize = 240;
for (css, collapse) in [
("flex-wrap:wrap", ""),
("flex-direction:column", ""),
(
"flex-wrap:wrap",
".tags span:nth-child(3n){visibility:collapse}",
),
("flex-direction:column;flex-wrap:wrap;height:400pt", ""),
] {
let what = format!("flex items of a container with `{css}` and `{collapse}`");
crate::work::assert_linear(&what, ITEMS, |items| {
let tags: String = (0..items)
.map(|index| format!("<span>tag {index}</span>"))
.collect();
paged_work(
&format!("{what} holding {items} items"),
&format!(
"<style>.tags{{display:flex;gap:2pt;{css}}}.tags span{{border:1pt solid;padding:1pt}}{collapse}</style><div class=tags>{tags}</div>"
),
crate::work::Work::SiblingStep,
)
});
}
}
#[test]
fn laying_out_grid_items_takes_work_linear_in_their_count() {
const ITEMS: usize = 240;
for (steps, work) in [
("sibling", crate::work::Work::SiblingStep),
("single-span", crate::work::Work::SingleSpanStep),
] {
let what = format!("{steps} steps for the items of a four-column grid");
crate::work::assert_linear(&what, ITEMS, |items| {
let cards: String = (0..items)
.map(|index| format!("<div>card {index}</div>"))
.collect();
paged_work(
&format!("{what} holding {items} items"),
&format!(
"<style>.grid{{display:grid;grid-template-columns:repeat(4,auto);gap:2pt}}.grid div{{border:1pt solid}}</style><div class=grid>{cards}</div>"
),
work,
)
});
}
}
#[test]
fn paginating_a_shrink_to_fit_grid_takes_work_linear_in_its_items() {
const ITEMS: usize = 240;
for css in ["width:fit-content", "width:max-content", "float:left"] {
let what = format!("layout budget for the items of a four-column grid with `{css}`");
crate::work::assert_linear(&what, ITEMS, |items| {
let cards: String = (0..items)
.map(|index| format!("<div>card {index}</div>"))
.collect();
let resolver = crate::tests::common::fixture_resolver();
let document = paged_document(
&format!(
"<style>.grid{{display:grid;grid-template-columns:repeat(4,1fr);gap:2pt;{css}}}.grid div{{border:1pt solid}}</style><div class=grid>{cards}</div>"
),
&resolver,
);
let budget = Budget::new(MAX_LAYOUT_WORK);
let pass = paged_pass(
&format!("{what} holding {items} items"),
&document,
&resolver,
budget.clone(),
);
let last = (items - 1).to_string();
let pages = page_text(&pass.trace);
assert!(
pages
.last()
.is_some_and(|lines| lines.iter().any(|line| line.ends_with(&last))),
"{what}: the last page of {items} items shows card {last}: {:?}",
pages.last()
);
budget.spent()
});
}
}
#[test]
fn measuring_nested_flex_and_grid_items_takes_work_linear_in_their_nesting_and_count() {
const DEPTH: usize = 8;
const ITEMS: usize = 4;
const LEVELS: [&str; 3] = [
"display:flex;gap:2pt",
"display:grid;grid-template-columns:auto 1fr",
"display:flex;flex-direction:column",
];
let work = |depth: usize, items: usize, kind: crate::work::Work| {
let mut nested = "<span>innermost</span>".to_owned();
for level in 0..depth {
let siblings = |side: &str| -> String {
(0..items / 2)
.map(|item| format!("<span>{side}{level}.{item}</span>"))
.collect()
};
nested = format!(
"<div style='{}'>{}{nested}{}</div>",
LEVELS[level % LEVELS.len()],
siblings("before"),
siblings("after")
);
}
let resolver = crate::tests::common::fixture_resolver();
let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let document = StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}body{{font:8pt Fixed}}</style>{nested}"),
&base, &[], &resolver,
)
.unwrap();
let (pass, units) = crate::work::measured(kind, || {
crate::layout::layout_pass(&document, &resolver, Budget::new(MAX_LAYOUT_WORK))
.unwrap_or_else(|error| {
panic!("{depth} levels of {items} items failed: {error}")
})
});
let text = page_text(&pass.trace).concat().concat();
assert!(
text.contains("innermost") && text.contains(&format!("after{}.0", depth - 1)),
"fixture: {depth} levels of {items} items lay out every level: {text}"
);
units
};
for (what, kind) in [
("item measurements", crate::work::Work::ItemMeasurement),
(
"content width computations",
crate::work::Work::ContentSizes,
),
] {
crate::work::assert_linear(
&format!("{what} for flex and grid containers nested in each other"),
DEPTH,
|depth| work(depth, ITEMS, kind),
);
crate::work::assert_linear(
&format!("{what} for {DEPTH} levels of flex and grid containers"),
ITEMS,
|items| work(DEPTH, items, kind),
);
}
}
#[test]
fn multicolumn_layout_takes_work_linear_in_its_content() {
const TWO_COLUMN_PARAGRAPHS: usize = 144;
const THREE_COLUMN_PARAGRAPHS: usize = 96;
const BANNER_AFTER: usize = 8;
let resolver = crate::tests::common::fixture_resolver();
let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/oracle/fixtures")
.into();
let work = |css: &str, banner: bool, wrapper: bool, paragraphs: usize| {
let mut content = (0..paragraphs)
.map(|index| format!("<p>p{index:04} words</p>"))
.collect::<Vec<_>>();
if banner {
content.insert(BANNER_AFTER, "<h2>Banner</h2>".to_owned());
}
let content = content.concat();
let content = if wrapper {
format!("<div>{content}</div>")
} else {
content
};
let document = StyledDocument::parse(
&format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 40pt;margin:0}}html,body{{margin:0;font:10pt/10pt Fixed}}p{{margin:0}}h2{{column-span:all;margin:0;font-size:10pt}}{css}</style><section>{content}</section>"),
&base, &[], &resolver,
)
.unwrap();
let budget = Budget::new(MAX_LAYOUT_WORK);
let trace = crate::layout::layout_pass(&document, &resolver, budget.clone())
.unwrap_or_else(|error| {
panic!("{paragraphs} paragraphs in `{css}` failed: {error}")
})
.trace;
let labels: Vec<_> = trace
.pages
.iter()
.flatten()
.flat_map(|line| line.text.split_whitespace())
.filter(|word| word.starts_with('p') && word.len() == 5)
.collect();
let expected: Vec<_> = (0..paragraphs)
.map(|index| format!("p{index:04}"))
.collect();
assert_eq!(
labels, expected,
"fixture: every paragraph in `{css}` is placed once, in order"
);
let offsets = trace
.pages
.last()
.into_iter()
.flatten()
.map(|line| line.x.to_bits())
.collect::<std::collections::BTreeSet<_>>()
.len();
assert!(
trace.pages.len() > 2 && offsets > 1,
"fixture: {paragraphs} paragraphs in `{css}` fill pages of columns, but they \
take {} pages and the last holds lines at {offsets} offsets",
trace.pages.len()
);
budget.spent()
};
for (css, banner, wrapper, paragraphs) in [
(
"section{columns:2;column-gap:10pt}",
false,
false,
TWO_COLUMN_PARAGRAPHS,
),
(
"section{columns:2;column-gap:10pt}",
false,
true,
TWO_COLUMN_PARAGRAPHS,
),
(
"section{columns:3;column-gap:6pt}",
false,
false,
THREE_COLUMN_PARAGRAPHS,
),
(
"section{columns:2;column-gap:10pt}",
true,
false,
TWO_COLUMN_PARAGRAPHS,
),
(
"section{columns:2;column-gap:10pt;column-fill:auto;padding-bottom:20pt;border-bottom:1pt solid}",
false,
false,
TWO_COLUMN_PARAGRAPHS,
),
] {
crate::work::assert_linear(
&format!(
"columns `{css}`{}{}",
if banner {
" after a spanning banner"
} else {
""
},
if wrapper { " in one wrapper" } else { "" }
),
paragraphs,
|paragraphs| work(css, banner, wrapper, paragraphs),
);
}
}
}