Place top floats through the paged builder

This commit is contained in:
gloamxun committed 2026-10-23 03:30:15 +08:00
1 parent bc0d29ace4
commit aa081e3dc6
5 files changed
+136 -13

No files matched your search

+1 -1
View File
@@ -594,7 +594,7 @@ page body through `pdf::PageOrigin`, leaving the sheet size unchanged; the
route-D PDF endpoint reads leading `\hoffset`/`\voffset` 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. 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 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
+79 -1
View File
@@ -829,6 +829,12 @@ 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 {
height: float.height,
}
}
// Bottom and in-text floats still need the scrolling builder.
VerticalItem::Float(_) => return None,
};
nodes.push(node);
@@ -1665,6 +1671,7 @@ impl Engine {
height: document.insertion_class_limit(class.number),
})
.collect(),
text_float_sep: document.text_float_sep.max(0),
};
let mut pages = Vec::new();
let mut page_penalties = Vec::new();
@@ -1675,6 +1682,7 @@ impl Engine {
for fragment in builder.build(&nodes) {
let mut items = Vec::new();
let mut marks = Vec::new();
let mut floats = Vec::new();
let mut sources = Vec::new();
let mut insertions: BTreeMap<u8, Insertion> = BTreeMap::new();
let mut used: BTreeMap<u8, i64> = BTreeMap::new();
@@ -1716,6 +1724,7 @@ impl Engine {
held.entry(class).or_default().extend(remainder);
}
}
VerticalItem::Float(float) => floats.push(float.clone()),
other => items.push(other.clone()),
}
}
@@ -1723,6 +1732,7 @@ impl Engine {
let mut page = Page::empty();
page.items = items;
page.marks = marks;
page.floats = floats;
page.insertions = insertions.into_values().collect();
page.sources = sources;
page.seal_in_place();
@@ -5124,7 +5134,7 @@ mod tests {
#[test]
fn paged_layout_refuses_floats_but_places_insertions() {
let floated = Document::new(100, vec![Unit::float(1, FloatPlacement::Top, 100, 20)]);
let floated = Document::new(100, vec![Unit::float(1, FloatPlacement::Bottom, 100, 20)]);
assert!(Engine::layout_paged(&floated).is_none());
let insertion = Document::new(
@@ -5149,6 +5159,74 @@ mod tests {
assert_eq!(layout.pages()[0].insertions[0].items.len(), 1);
}
#[test]
fn paged_layout_places_top_floats() {
let document = Document::new(
100,
vec![
Unit::float(1, FloatPlacement::Top, 100, 20),
Unit::rule(2, 100, 60),
],
);
let layout = Engine::layout_paged(&document).expect("top floats are page-buildable");
assert_eq!(layout.pages().len(), 1);
assert_eq!(layout.pages()[0].floats.len(), 1);
assert_eq!(layout.pages()[0].items.len(), 1);
assert_eq!(
layout.pages()[0].items[0],
VerticalItem::Rule {
width: 100,
height: 60
}
);
}
#[test]
fn paged_layout_defers_a_late_top_float() {
let mut document = Document::new(
100,
vec![
Unit::rule(1, 100, 60),
Unit::float(2, FloatPlacement::Top, 100, 20),
Unit::rule(3, 100, 20),
],
);
document.text_float_sep = 0;
let layout = Engine::layout_paged(&document).expect("a late float still builds");
assert_eq!(layout.pages().len(), 2);
assert!(layout.pages()[0].floats.is_empty());
assert_eq!(layout.pages()[1].floats.len(), 1);
assert_eq!(layout.pages()[1].items.len(), 1);
}
#[test]
fn text_float_sep_reserves_space_after_floats() {
let units = || {
vec![
Unit::float(1, FloatPlacement::Top, 100, 20),
Unit::rule(2, 100, 40),
Unit::vskip(3, 0),
Unit::rule(4, 100, 40),
]
};
let mut packed = Document::new(100, units());
packed.text_float_sep = 0;
assert_eq!(
Engine::layout_paged(&packed)
.expect("packed floats build")
.pages()
.len(),
1
);
let mut spaced = Document::new(100, units());
spaced.text_float_sep = 20;
let layout = Engine::layout_paged(&spaced).expect("spaced floats build");
assert_eq!(layout.pages().len(), 2);
assert_eq!(layout.pages()[0].floats.len(), 1);
assert_eq!(layout.pages()[0].items.len(), 1);
}
#[test]
fn paged_layout_holds_over_insertion_material() {
let mut document = Document::new(
+43
View File
@@ -50,6 +50,11 @@ pub enum VerticalNode {
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,
},
Glue(VerticalGlue),
Penalty(i64),
Mark(Mark),
@@ -110,6 +115,8 @@ pub struct PageBuilder {
pub top_skip: i64,
pub max_depth: i64,
pub insertion_limits: Vec<InsertionLimit>,
/// TeX `\textfloatsep`: space between top floats and the body.
pub text_float_sep: i64,
}
impl PageBuilder {
@@ -119,6 +126,7 @@ impl PageBuilder {
top_skip: 0,
max_depth: 0,
insertion_limits: Vec::new(),
text_float_sep: 0,
}
}
@@ -168,6 +176,7 @@ impl PageBuilder {
let mut shrink = 0_i64;
let mut depth = 0_i64;
let mut first_box = true;
let mut has_float = false;
let mut usage: BTreeMap<u8, i64> = held.clone();
let mut reserved: i64 = usage.values().sum();
let mut candidates: Vec<Candidate> = Vec::new();
@@ -180,6 +189,11 @@ impl PageBuilder {
} => {
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
};
@@ -187,6 +201,35 @@ impl PageBuilder {
depth = *box_depth;
first_box = false;
}
VerticalNode::Float {
height: float_height,
} => {
if height > 0 {
// TeX never places a top float below body material:
// the float starts the next page instead.
let end = index.max(start);
let badness = self.badness(height, reserved, stretch, shrink);
let fragment = self.fragment(
start,
end,
height,
depth,
stretch,
shrink,
badness,
badness,
0,
self.insertion_space(nodes, start, end, held),
);
return Some((
fragment,
index,
self.insertion_overflow(nodes, start, end, held),
));
}
height += (*float_height).max(0);
has_float = true;
}
VerticalNode::Glue(glue) => {
if index > start {
candidates.push(
+8 -6
View File
@@ -66,9 +66,10 @@ yet generic `fil`/`fill` glue
policies, now with line-level paragraph splits; `page::PageBuilder`
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 and insertion classes
(per-class limits with held-over material), but floats and incremental
checkpoint replay still use the scrolling builder, and the interpreted
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
`\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
@@ -270,9 +271,10 @@ goal, so overfull pages take the least overfull break. `Document::h_offset` and
body without moving the sheet; a route-D integration fixture checks the shift
with `pdftotext -bbox`, and the PDF endpoint reads leading `\hoffset`/`\voffset`
dimension assignments from the source. Insertion classes are placed by the
paged builder with their limits and held-over material; floats and checkpoint
replay still fall back to the scrolling builder, which stays the default until
it has a paged equivalent. Next: port those paths and paper margins, then extend the `\output`
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 and checkpoint replay still fall back to the scrolling
builder, which stays the default until it has a paged equivalent. Next: port those paths and paper margins, then extend the `\output`
interpreter past the shipout/ifdim/ifnum/ifodd/ifcase subset.
Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks);
+5 -5
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, while the scrolling builder remains the default; `\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 floats and insertion classes on that path, while the scrolling builder remains the default for bottom/in-text floats and edit replay; `\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 |
@@ -247,9 +247,9 @@ oracle fixture is ignored.
paged builder, `Document::par_skip` is inserted as vertical glue between
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. Top `Float`
material is deferred to the next page when it arrives late; bottom
floats reserve height on the current page and must satisfy
change page goals. The paged builder places top `Float` material at the top
of a page and defers a late float to the next page; 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.
- No macro state, output routine, math, fonts or PDF output in the new core yet.
@@ -338,7 +338,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 240 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 358 tests (240 route-D unit, 7 route-D integration, 13 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
The crate currently has 243 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 361 tests (243 route-D unit, 7 route-D integration, 13 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
### M0 incremental demo