Let the output routine retarget later pages with vsize

This commit is contained in:
gloamxun committed 2026-10-23 13:02:47 +08:00
1 parent 3b99f93ab8
commit c6ebbea58d
5 files changed
+188 -8

No files matched your search

+131
View File
@@ -1748,6 +1748,27 @@ impl Engine {
/// because their placement belongs to the incremental builder for now.
pub fn layout_paged(document: &Document) -> Option<Self> {
let (nodes, owners, node_items) = document_nodes(document)?;
if let Some(source) = &document.output_routine {
let program = output::OutputProgram::parse(source).ok()?;
let plain = document.insertion_classes.is_empty()
&& nodes.iter().all(|node| {
!matches!(
node,
VerticalNode::Insertion { .. }
| VerticalNode::Float { .. }
| VerticalNode::BottomFloat { .. }
)
});
if plain && program.assigns_vsize() {
return Self::layout_paged_variable_goal(
document,
&nodes,
&owners,
&node_items,
&program,
);
}
}
let builder = Self::paged_builder(document);
let mut pages = Vec::new();
let mut page_penalties = Vec::new();
@@ -2021,6 +2042,90 @@ impl Engine {
}
/// Materialize page fragments without insertion hold-over.
/// Build pages one at a time so an output routine that assigns `\vsize`
/// changes the goal of the pages it has not seen yet.
fn layout_paged_variable_goal(
document: &Document,
nodes: &[VerticalNode],
owners: &[usize],
node_items: &[VerticalItem],
program: &output::OutputProgram,
) -> Option<Self> {
let mut builder = Self::paged_builder(document);
let mut goal = document.page_goal.max(1);
let mut start = 0usize;
let mut pages = Vec::new();
let mut pageno = 1_i64;
let mut deadcycles = 0_i64;
while start < nodes.len() {
builder.set_page_goal(goal);
let fragment = builder.build_from(nodes, start).into_iter().next()?;
let mut items = Vec::new();
let mut marks = Vec::new();
let mut sources = Vec::new();
for index in fragment.start..fragment.end {
let item = &node_items[index];
let unit = &document.units[owners[index]];
if sources.last().map(|(id, _)| *id) != Some(unit.id) {
sources.push((unit.id, source_hash(&unit.source)));
}
match item {
VerticalItem::Mark(mark) => marks.push(mark.clone()),
other => items.push(other.clone()),
}
}
Self::set_page_glue(&mut items, &fragment);
let mut page = Page::empty();
page.items = items;
page.marks = marks;
page.sources = sources;
page.seal_in_place();
let page_total: i64 = page.items.iter().map(item_height).sum();
let mut context = output::OutputContext {
page_goal: goal,
page_total,
page_depth: fragment.depth,
page_stretch: fragment.stretch,
page_fil_stretch: fragment.stretches[1],
page_fill_stretch: fragment.stretches[2],
page_filll_stretch: fragment.stretches[3],
page_shrink: fragment.shrink,
vsize: goal,
top_skip: document.top_skip,
max_depth: document.max_depth,
output_penalty: fragment.penalty,
insertion_counts: [1000; 256],
insertion_dimens: [0; 256],
insertion_skips: [0; 256],
pageno,
deadcycles,
};
let shipped = program.shipout_count(&mut context).ok()?;
pageno = context.pageno.wrapping_add(1);
deadcycles = context.deadcycles;
if shipped > 0 {
pages.push(page);
deadcycles = 0;
} else {
deadcycles += 1;
}
if context.vsize != goal {
goal = context.vsize.max(1);
}
start = fragment.end.max(start + 1);
}
let count = pages.len();
Some(Self {
layout: Layout {
pages,
checkpoints: Vec::new(),
recomputed_pages: 0,
changed_pages: (0..count).collect(),
paged_page_nodes: Vec::new(),
},
})
}
fn paged_pages(
document: &Document,
owners: &[usize],
@@ -2711,6 +2816,32 @@ mod tests {
assert_eq!(result.layout.pages[1].insertions.len(), 0);
}
#[test]
fn output_routine_can_change_vsize_for_later_pages() {
let mut units = Vec::new();
for n in 0..7 {
units.push(Unit::rule(n * 2, 300, 300));
if n < 6 {
units.push(Unit::penalty(n * 2 + 1, 0));
}
}
let mut document = Document::new(1000, units);
document.top_skip = 0;
document.output_routine = Some(r"\ifnum\pageno=1\vsize=600\fi\shipout\box255".to_owned());
let engine = Engine::layout_paged(&document).expect("paged");
let counts = engine
.pages()
.iter()
.map(|page| {
page.items
.iter()
.filter(|item| matches!(item, VerticalItem::Rule { .. }))
.count()
})
.collect::<Vec<_>>();
assert_eq!(counts, vec![3, 2, 2], "pages: {counts:?}");
}
#[test]
fn output_routine_sees_page_goal_after_insertion_reservation() {
let scale = 65_536;
+43 -1
View File
@@ -92,6 +92,32 @@ impl OutputProgram {
Ok(Self { ops })
}
/// True when the routine assigns `\vsize`, so later page goals change.
pub fn assigns_vsize(&self) -> bool {
fn scan(ops: &[Op]) -> bool {
ops.iter().any(|op| match op {
Op::AssignDimension {
register: Register::Vsize,
..
} => true,
Op::IfDim {
then_ops, else_ops, ..
}
| Op::IfNum {
then_ops, else_ops, ..
}
| Op::IfOdd {
then_ops, else_ops, ..
} => scan(then_ops) || scan(else_ops),
Op::IfCase {
branches, else_ops, ..
} => branches.iter().any(|branch| scan(branch)) || scan(else_ops),
_ => false,
})
}
scan(&self.ops)
}
/// Execute the program for one page and return how many times it called
/// `\shipout`.
pub fn shipout_count(&self, context: &mut OutputContext) -> Result<usize, String> {
@@ -383,7 +409,8 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result<
}
ops.push(Op::Message(text));
}
"pageno" | "deadcycles" | "outputpenalty" | "count" | "dimen" | "skip" => {
"pageno" | "deadcycles" | "outputpenalty" | "count" | "dimen" | "skip"
| "vsize" => {
*index += 1;
let (integer_register, dimension_register) = match name.as_str() {
"pageno" => (Some(IntegerRegister::PageNo), None),
@@ -397,6 +424,7 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result<
let class = parse_insertion_class(tokens, index, "\\dimen", true)?;
(None, Some(Register::InsertionDimen(class)))
}
"vsize" => (None, Some(Register::Vsize)),
_ => {
let class = parse_insertion_class(tokens, index, "\\skip", true)?;
(None, Some(Register::InsertionSkip(class)))
@@ -727,6 +755,7 @@ fn execute(ops: &[Op], context: &mut OutputContext, shipped: &mut usize) -> Resu
Register::InsertionSkip(class) => {
context.insertion_skips[*class as usize] = value;
}
Register::Vsize => context.vsize = value,
other => {
return Err(format!("cannot assign to page register {other:?}"));
}
@@ -810,6 +839,19 @@ mod tests {
assert_eq!(program.shipout_count(&mut context(0)).unwrap(), 0);
}
#[test]
fn output_routine_can_assign_vsize() {
let mut context = context(0);
let program =
OutputProgram::parse(r"\vsize=300pt\ifdim\vsize>200pt\shipout\box255\fi").unwrap();
assert!(program.assigns_vsize());
assert_eq!(program.shipout_count(&mut context).unwrap(), 1);
assert_eq!(context.vsize, 300 * 65_536);
let plain = OutputProgram::parse(r"\shipout\box255").unwrap();
assert!(!plain.assigns_vsize());
}
#[test]
fn output_routine_can_assign_registers() {
let mut context = context(0);
+5
View File
@@ -192,6 +192,11 @@ impl PageBuilder {
.map_or(self.page_goal, |limit| limit.height.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<PageFragment> {
let mut pages = Vec::new();