Place bottom floats through the paged builder

This commit is contained in:
gloamxun committed 2026-10-23 03:57:44 +08:00
1 parent 7b9d543e49
commit 14ca3b91d9
5 files changed
+198 -34

No files matched your search

+1 -1
View File
@@ -596,7 +596,7 @@ Letter) set the MediaBox and the preview page box; the route-D endpoints read
leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight` dimension
assignments from the submitted source. Page marks collected by `\mark` are exposed through
`Engine::top_mark`, `first_mark` and `bot_mark` with TeX's carry-forward rules.
`Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page (the paged builder applies the same limits and carries overflow onto dedicated pages), and `InsertionClass::multiplier` applies TeX's `\count<number>` reserve factor; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. `Engine::layout_paged` feeds the same material through `page::PageBuilder`, which places top floats at the head of a page, defers a late float, reserves `Document::text_float_sep` above the body and applies the insertion class limits; bottom and in-text floats still run through the scrolling builder. The v1 `/preview` and project APIs are unchanged and remain the default.
`Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page (the paged builder applies the same limits and carries overflow onto dedicated pages), and `InsertionClass::multiplier` applies TeX's `\count<number>` reserve factor; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. `Engine::layout_paged` feeds the same material through `page::PageBuilder`, which places top floats at the head of a page, defers a late float, reserves `Document::text_float_sep` above the body and applies the insertion class limits; bottom floats sit at the page bottom with `Document::float_sep` between them and a `Document::bottom_fraction_percent` cap, and in-text floats still run through the scrolling builder. The v1 `/preview` and project APIs are unchanged and remain the default.
Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline. The web client exposes this as the `引擎: v1` / `引擎: Route-D` toggle in the preview toolbar; the choice is stored in `localStorage` and switches both the preview request and `POST /api/projects/{id}/pdf`, since the PDF handler honors the same `engine=route-d` query. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages; text edits and structural edits with an unchanged paragraph prefix rebuild from the first difference through `Engine::relayout_from`, reusing the sealed pages before it, while edits without a reusable prefix fall back to a full layout. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D
document and returns the same page list plus `changedPages` and
+53 -7
View File
@@ -845,13 +845,16 @@ fn document_nodes(
class: insertion.class,
height: document.insertion_reserve(insertion.class, insertion.height),
},
VerticalItem::Float(float) if matches!(float.placement, FloatPlacement::Top) => {
VerticalNode::Float {
VerticalItem::Float(float) => match float.placement {
FloatPlacement::Top => VerticalNode::Float {
height: float.height,
}
}
// Bottom and in-text floats still need the scrolling builder.
VerticalItem::Float(_) => return None,
},
FloatPlacement::Bottom => VerticalNode::BottomFloat {
height: float.height,
},
// In-text floats are body material, not page-builder floats.
FloatPlacement::Here => return None,
},
};
nodes.push(node);
owners.push(index);
@@ -1854,6 +1857,8 @@ impl Engine {
})
.collect(),
text_float_sep: document.text_float_sep.max(0),
float_sep: document.float_sep.max(0),
bottom_fraction_percent: document.bottom_fraction_percent,
}
}
@@ -5272,7 +5277,7 @@ mod tests {
#[test]
fn paged_layout_refuses_floats_but_places_insertions() {
let floated = Document::new(100, vec![Unit::float(1, FloatPlacement::Bottom, 100, 20)]);
let floated = Document::new(100, vec![Unit::float(1, FloatPlacement::Here, 100, 20)]);
assert!(Engine::layout_paged(&floated).is_none());
let insertion = Document::new(
@@ -5297,6 +5302,47 @@ mod tests {
assert_eq!(layout.pages()[0].insertions[0].items.len(), 1);
}
#[test]
fn paged_layout_places_bottom_floats_at_the_page_end() {
let mut document = Document::new(
100,
vec![
Unit::rule(1, 100, 60),
Unit::float(2, FloatPlacement::Bottom, 100, 30),
],
);
document.text_float_sep = 0;
let layout = Engine::layout_paged(&document).expect("bottom floats are page-buildable");
assert_eq!(layout.pages().len(), 1);
assert_eq!(layout.pages()[0].floats.len(), 1);
assert_eq!(
layout.pages()[0].floats[0].placement,
FloatPlacement::Bottom
);
}
#[test]
fn paged_layout_defers_a_bottom_float_that_cannot_fit() {
let mut document = Document::new(
100,
vec![
Unit::rule(1, 100, 80),
Unit::float(2, FloatPlacement::Bottom, 100, 30),
Unit::rule(3, 100, 10),
],
);
document.text_float_sep = 0;
let layout = Engine::layout_paged(&document).expect("bottom floats are page-buildable");
assert_eq!(layout.pages().len(), 2);
assert_eq!(layout.pages()[0].floats.len(), 0);
assert_eq!(layout.pages()[0].items.len(), 1);
assert_eq!(layout.pages()[1].floats.len(), 1);
assert_eq!(
layout.pages()[1].floats[0].placement,
FloatPlacement::Bottom
);
}
#[test]
fn paged_layout_places_top_floats() {
let document = Document::new(
+124 -10
View File
@@ -55,6 +55,11 @@ pub enum VerticalNode {
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),
@@ -82,6 +87,8 @@ pub struct PageFragment {
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.
@@ -102,6 +109,7 @@ struct Candidate {
stretch: i64,
shrink: i64,
reserved: i64,
bottom: i64,
penalty: i64,
end: usize,
next: usize,
@@ -117,6 +125,10 @@ pub struct PageBuilder {
pub insertion_limits: Vec<InsertionLimit>,
/// 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,
}
impl PageBuilder {
@@ -127,6 +139,8 @@ impl PageBuilder {
max_depth: 0,
insertion_limits: Vec::new(),
text_float_sep: 0,
float_sep: 0,
bottom_fraction_percent: 100,
}
}
@@ -197,6 +211,8 @@ impl PageBuilder {
let mut depth = 0_i64;
let mut first_box = true;
let mut has_float = false;
let mut bottom = 0_i64;
let mut bottom_count = 0_usize;
let mut usage: BTreeMap<u8, i64> = held.clone();
let mut reserved: i64 = usage.values().sum();
let mut candidates: Vec<Candidate> = Vec::new();
@@ -239,6 +255,7 @@ impl PageBuilder {
badness,
badness,
0,
bottom,
self.insertion_space(nodes, start, end, held),
);
return Some((
@@ -250,10 +267,50 @@ impl PageBuilder {
height += (*float_height).max(0);
has_float = true;
}
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;
if height > 0
&& (height + reserved + bottom + needed > self.page_goal
|| bottom + needed > allowed)
{
let end = index.max(start);
let badness = self.badness(height, reserved + bottom, stretch, shrink);
let fragment = self.fragment(
start,
end,
height,
depth,
stretch,
shrink,
badness,
badness,
0,
bottom,
self.insertion_space(nodes, start, end, held),
);
return Some((
fragment,
index,
self.insertion_overflow(nodes, start, end, held),
));
}
bottom += needed;
bottom_count += 1;
}
VerticalNode::Glue(glue) => {
if index > start {
candidates.push(
self.candidate(height, depth, stretch, shrink, reserved, 0, index),
self.candidate(
height, depth, stretch, shrink, reserved, bottom, 0, index,
),
);
}
height += glue.width;
@@ -274,6 +331,7 @@ impl PageBuilder {
badness,
badness + *penalty,
*penalty,
bottom,
self.insertion_space(nodes, start, end, held),
);
return Some((
@@ -283,11 +341,9 @@ impl PageBuilder {
));
}
if index > start {
candidates.push(
self.candidate(
height, depth, stretch, shrink, reserved, *penalty, index,
),
);
candidates.push(self.candidate(
height, depth, stretch, shrink, reserved, bottom, *penalty, index,
));
}
}
VerticalNode::Insertion {
@@ -305,7 +361,16 @@ impl PageBuilder {
}
}
candidates.push(self.candidate(height, depth, stretch, shrink, reserved, 0, nodes.len()));
candidates.push(self.candidate(
height,
depth,
stretch,
shrink,
reserved,
bottom,
0,
nodes.len(),
));
let best = self.select(candidates)?;
let fragment = self.fragment(
start,
@@ -317,6 +382,7 @@ impl PageBuilder {
best.badness,
best.cost,
best.penalty,
best.bottom,
self.insertion_space(nodes, start, best.end, held),
);
Some((
@@ -377,6 +443,7 @@ impl PageBuilder {
stretch: i64,
shrink: i64,
reserved: i64,
bottom: i64,
penalty: i64,
end: usize,
) -> Candidate {
@@ -386,7 +453,7 @@ impl PageBuilder {
} else {
(height, depth)
};
let badness = self.badness(height, reserved, stretch, shrink);
let badness = self.badness(height, reserved + bottom, stretch, shrink);
Candidate {
cost: badness + penalty,
penalty,
@@ -396,6 +463,7 @@ impl PageBuilder {
stretch,
shrink,
reserved,
bottom,
end,
next: end + 1,
}
@@ -435,6 +503,7 @@ impl PageBuilder {
badness: i64,
cost: i64,
penalty: i64,
bottom: i64,
insertions: Vec<InsertionSpace>,
) -> PageFragment {
PageFragment {
@@ -444,6 +513,7 @@ impl PageBuilder {
penalty,
badness,
height,
bottom,
depth,
stretch,
shrink,
@@ -455,7 +525,7 @@ impl PageBuilder {
let feasible: Vec<Candidate> = candidates
.iter()
.filter(|candidate| {
let page = candidate.height + candidate.reserved;
let page = candidate.height + candidate.reserved + candidate.bottom;
page <= self.page_goal || page - self.page_goal <= candidate.shrink
})
.cloned()
@@ -468,7 +538,7 @@ impl PageBuilder {
pool.into_iter().min_by_key(|candidate| {
(
candidate.cost,
(candidate.height + candidate.reserved - self.page_goal).abs(),
(candidate.height + candidate.reserved + candidate.bottom - self.page_goal).abs(),
)
})
}
@@ -701,4 +771,48 @@ mod tests {
"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,
..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 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);
}
}
+10 -9
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`). 370 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 375 workspace tests are green and no oracle
fixture is ignored.
Known gaps, in dependency order:
@@ -67,9 +67,10 @@ yet generic `fil`/`fill` glue
implements the candidate-breakpoint cost model (badness + penalty, glue
setting, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it for
documents made of box/glue/penalty/mark units, insertion classes
(per-class limits with held-over material) and top floats (with
`\textfloatsep` reserved above the body); bottom/in-text floats and
incremental checkpoint replay still use the scrolling builder, and the interpreted
(per-class limits with held-over material) and top and bottom floats
(`\textfloatsep` above the body, `\floatsep` between stacked bottom
floats, `\bottomfraction` cap); in-text floats still use the scrolling
builder, and the interpreted
`\output` subset handles `\shipout`, `\ifdim` and `\ifnum` over page
registers such as `\pageno`, `\outputpenalty` and `\deadcycles`;
3. `\insert` classes model `\count`/`\dimen`/`\skip` but are not TeX
@@ -275,13 +276,13 @@ with `pdftotext -bbox`. `Document::paper_width`/`paper_height`
page box, and the endpoints read leading
`\hoffset`/`\voffset`/`\paperwidth`/`\paperheight` dimension assignments from
the source. Insertion classes are placed by the
paged builder with their limits and held-over material, and top floats are
placed at the head of a fragment with `\textfloatsep` reserved above the body;
bottom/in-text floats still fall back to the scrolling builder, which stays
the default until it has a paged equivalent. Paged layouts also record the
paged builder with their limits and held-over material, top floats are placed
at the head of a fragment with `\textfloatsep` reserved above the body, and
bottom floats sit at the page bottom with `\floatsep` between them and a
`\bottomfraction` cap; in-text floats still fall back to the scrolling builder. Paged layouts also record the
node index starting each page, so `Engine::edit` reuses the sealed prefix and
rebuilds only the pages from the edited unit onward; insertions and interpreted
`\output` keep the full-rebuild fallback. Next: port bottom/in-text floats and
`\output` keep the full-rebuild fallback. Next: port in-text floats and
paper margins, then extend the `\output` interpreter past the
shipout/ifdim/ifnum/ifodd/ifcase subset.
+10 -7
View File
@@ -116,7 +116,7 @@ and justification.
| --- | --- | --- |
| M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 |
| M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode` and vertical-glue fixtures; generic fil glue and `\prevgraf` next |
| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top floats and insertion classes on that path, while the scrolling builder remains the default for bottom/in-text floats; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable registers and `PageFragment::penalty` carries the break penalty |
| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep` and a `\bottomfraction` cap) and insertion classes on that path, while the scrolling builder remains the default for in-text floats; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable registers and `PageFragment::penalty` carries the break penalty |
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; no booktabs/longtable parity yet |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, accents and a display-list painter; no CMEX size variants or TeX math spacing classes yet |
| M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference |
@@ -248,11 +248,14 @@ oracle fixture is ignored.
consecutive paragraph units and is discarded when it would start a page,
matching TeX's paragraph spacing in vertical lists. The routine cannot yet
change page goals. The paged builder places top `Float` material at the top
of a page, defers a late float to the next page, and route-D preview/PDF
draw pages through `display_list_with_layout` so the body clears
`\textfloatsep`; bottom floats reserve height on the current page and must satisfy
`Document.text_fraction_percent` (default 50%); a page holding only floats
is sealed once it leaves less than that fraction for text.
of a page and bottom `Float` material at the page bottom: a late top float
starts the next page, a bottom float that cannot fit the remaining body
space is deferred, stacked bottom floats reserve `\floatsep`, and
`\bottomfraction` caps the bottom float share. Route-D preview/PDF draw
pages through `display_list_with_layout` so the body clears
`\textfloatsep` / the bottom float area; the scrolling builder still
reserves height for bottom floats against `Document.text_fraction_percent`
(default 50%) and seals float-only pages.
- No macro state, output routine, math, fonts or PDF output in the new core yet.
- The v1 server and project API still use `src/rust_typeset` and are unchanged.
@@ -339,7 +342,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 247 unit tests plus seven route-D integration tests and sixteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 370 tests (247 route-D unit, 7 route-D integration, 16 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
The crate currently has 252 unit tests plus seven route-D integration tests and sixteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 375 tests (252 route-D unit, 7 route-D integration, 16 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
### M0 incremental demo