From 66b2ccf380e05932d29cc388552a1568bb82121e Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 23:51:18 +0800 Subject: [PATCH] Rebuild paged documents that defer bottom floats --- crates/texrra-tex-core/src/lib.rs | 48 +++++++++++++++++++++++++++++++ docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 8 +++--- 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 46538cf..f5e31d2 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -2434,6 +2434,15 @@ impl Engine { let Some((nodes, owners, node_items)) = document_nodes(document) else { return false; }; + if nodes + .iter() + .any(|node| matches!(node, VerticalNode::BottomFloat { .. })) + { + // A bottom float that did not fit is carried on the fragment, and a + // suffix rebuild starting from a page boundary cannot recover that + // queue. Rebuild the whole paged document instead of misplacing it. + return false; + } let Some(mut first_node) = owners.iter().position(|owner| *owner >= unit_index) else { return false; }; @@ -6520,6 +6529,45 @@ mod tests { ); } + #[test] + fn paged_edit_with_bottom_floats_rebuilds_with_the_float_queue() { + let style = ParagraphStyle { + line_width: 100 * 65_536, + line_height: 12 * 65_536, + ..ParagraphStyle::default() + }; + let paragraph = |id, text: &str| { + Unit::paragraph_with_style_and_face(id, text, style.clone(), ParagraphFont::Roman) + }; + let mut document = Document::new( + 40 * 65_536, + vec![ + paragraph(1, "alpha"), + paragraph(2, "beta"), + Unit::float(3, FloatPlacement::Bottom, 100, 20 * 65_536), + paragraph(4, "gamma"), + ], + ); + document.text_float_sep = 0; + let mut engine = Engine::layout_paged(&document).expect("bottom floats are page-buildable"); + let total = engine.pages().len(); + assert_eq!(total, 2, "the float should be deferred to the second page"); + + let mut edited = document.clone(); + edited.units[3] = paragraph(4, "delta"); + engine.edit(&edited, 4, "delta"); + assert_eq!( + engine.recomputed_pages(), + total, + "the queue must force a full rebuild" + ); + + let fresh = Engine::layout_paged(&edited).expect("paged"); + let hashes: Vec<_> = engine.pages().iter().map(|page| page.hash).collect(); + let fresh_hashes: Vec<_> = fresh.pages().iter().map(|page| page.hash).collect(); + assert_eq!(hashes, fresh_hashes); + } + #[test] fn paged_layout_places_top_floats() { let document = Document::new( diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index a9f22d2..d1f08ed 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -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`). 462 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 463 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index e8c0f33..034e5fe 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -128,7 +128,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`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders, `\prevgraf` in the output routine, and vertical-glue fixtures | -| 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 (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; 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 and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets later pages when the document has no insertions or floats), `\ht255` and `\dp255` expose the page box height and depth to the routine, insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments for the duration of the routine, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine | +| 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 (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions, bottom floats or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets later pages when the document has no insertions or floats), `\ht255` and `\dp255` expose the page box height and depth to the routine, insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments for the duration of the routine, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine | | 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 | @@ -327,7 +327,7 @@ for a later overlaid slash. | --- | --- | --- | | M0 checkpoint engine | done | page list, page hashes, snapshot/restore, edit replay | | M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing with default and custom `\sfcode`/`\frenchspacing`, explicit `\spaceskip`/`\xspaceskip`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfTeX oracle matrix 90-240pt plus register, geometry and vertical-glue fixtures | -| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`; `Engine::layout_paged` builds pages through it for documents made of box/glue/penalty/mark vertical material (a unit may span pages), while in-text floats flow inline through the page builder; paged layouts replay edits from the edited page (insertions and interpreted `\output` force a full rebuild), and insertions are placed through the builder too; `\output` interpreted for a `\shipout`/`\ifdim`/`\ifnum` register subset over page globals and `\outputpenalty`/`\pageno`/`\deadcycles` | +| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`; `Engine::layout_paged` builds pages through it for documents made of box/glue/penalty/mark vertical material (a unit may span pages), while in-text floats flow inline through the page builder; paged layouts replay edits from the edited page (insertions, bottom floats and interpreted `\output` force a full rebuild), and insertions are placed through the builder too; `\output` interpreted for a `\shipout`/`\ifdim`/`\ifnum` register subset over page globals and `\outputpenalty`/`\pageno`/`\deadcycles` | | M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter | | M4 math | partial | atoms, scripts, fractions, roots, delimiters, accents, operators, classes, braces, boxed, negated; no math painter/shrink wrapping | | M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style | @@ -358,7 +358,7 @@ M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` be M2 (partial): `Page::display_list_with_goal(page_goal)` places insertion material at `page_goal - insertion_height`, adds a 0.4pt separator above footnotes, splits oversized insertions at item boundaries, and paints top/bottom floats from their vertical `content` at the page edges; empty floats keep a dimension rectangle. Floats also size themselves from content, respect `text_fraction_percent`, respect `top_fraction_percent` (TeX `\topfraction`, default 70%) and `bottom_fraction_percent` (TeX `\bottomfraction`, default 30%), and can take a dedicated float page. The incremental edit path applies the same float fractions, float number limits, insertion-class limits and per-class `skip` rules as full layout. `Document::float_sep` (TeX `\floatsep`, default 12pt) reserves a gap between stacked floats of the same placement in both paths. `Document::text_float_sep` (TeX `\textfloatsep`, default 20pt) reserves exactly one gap between the float block and the body text on a page that has both, again in both paths; `Page::display_list_with_layout(page_goal, text_float_sep)` applies the same gap when rendering, while `display_list_with_goal` stays gap-free for callers that do not know the document settings. Float material at the top of a page starts at the top margin: `\topskip` is consumed only by body text, matching TeX float pages. A `[t]` float seen while a page is already being filled is installed at the top of that same page, exactly as TeX's `\@toplist` does: the page height gains the float plus one `\textfloatsep` (or `\floatsep` between stacked floats), so the body stops earlier instead of the float waiting for the next page; only a break before the float moves it forward. `FloatPlacement::Here` models `[h]` floats: they keep their place in the body flow with `Document::in_text_sep` (TeX `\intextsep`, default 12pt) above and below, move to the next page when they do not fit, and count against `\totalnumber`. The page stores the float's `gap_after` so the display list advances the flow by the same amount the builder reserved. A standalone `page::PageBuilder` implements TeX's candidate-breakpoint cost model (page badness from accumulated glue stretch/shrink plus break penalties, `\topskip` for the first box, `\maxdepth` depth shifting) with unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties, marks and insertion classes, including per-class limits and held-over material; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item, and `Document::split_max_depth` (TeX `\splitmaxdepth`, `\maxdimen` by default) clamps the first held box's depth while moving the excess into its height); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the candidate closest to the page goal wins, so an overfull page takes the least overfull break. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. Paragraph boxes carry TeX depth: each node reports its last line's descent, so `\pagedepth` sees it, and the builder adds every box descent beyond `\maxdepth` to the page height while keeping the rest as page depth (TeX's per-box rule); route-D sources default `\maxdepth` to LaTeX's 5pt (0.5\topskip), and the page fixtures set it explicitly. A standalone `\smallskip`, `\medskip`, `\bigskip` or `\vskip` line between paragraphs becomes the following unit's `space_before` glue, carrying TeX's width plus its `plus`/`minus` parts (`\smallskip` is 3pt plus 1pt minus 1pt, and so on). Both page builders reserve it, the paged builder gets a real breakpoint with the glue's stretch and shrink, and edits preserve all three components; the command no longer leaks into the paragraph text. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and preview pages apply the same offsets to their display list so the editor and -PDF agree. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them, and the same pass reads `\parindent`, `\parskip`, `\baselineskip`, `\leftskip`, `\rightskip`, `\emergencystretch`, `\tolerance`, `\pretolerance`, `\hangindent`/`\hangafter`, `\spaceskip`/`\xspaceskip` and `\frenchspacing` into the paragraph styles; body paragraphs are measured with CMR10/per-face TFM advances rather than fixed cells; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty`, `\deadcycles` and `\maxdeadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\advance`, `\multiply` and `\divide` adjust those registers in place (`\advance\pageno by 2`, `\divide\deadcycles by 2`, `\advance\dimen2 by 5pt`), and an arithmetic `\vsize` change retargets later pages exactly like an assignment; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; Route-D sources map a standalone `\newpage` or `\clearpage` onto `Document::page_breaks`, so the next paragraph starts on a fresh page (the paged builder turns each break into a `-10000` penalty node); for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: ten page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, a 30pt `\topskip`, a forced `\newpage`, stretchy `\vskip` glue between paragraphs, footnotes raised with `\footnotetext`, and a `[t]` float that reserves its height plus `\textfloatsep` on the page it appears, and `[b]` floats that fit or defer to the next page) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`. +PDF agree. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them, and the same pass reads `\parindent`, `\parskip`, `\baselineskip`, `\leftskip`, `\rightskip`, `\emergencystretch`, `\tolerance`, `\pretolerance`, `\hangindent`/`\hangafter`, `\spaceskip`/`\xspaceskip` and `\frenchspacing` into the paragraph styles; body paragraphs are measured with CMR10/per-face TFM advances rather than fixed cells; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty`, `\deadcycles` and `\maxdeadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\advance`, `\multiply` and `\divide` adjust those registers in place (`\advance\pageno by 2`, `\divide\deadcycles by 2`, `\advance\dimen2 by 5pt`), and an arithmetic `\vsize` change retargets later pages exactly like an assignment; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; Route-D sources map a standalone `\newpage` or `\clearpage` onto `Document::page_breaks`, so the next paragraph starts on a fresh page (the paged builder turns each break into a `-10000` penalty node); for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. A document that contains a bottom float likewise rebuilds in full: a deferred float is carried on the page fragment, and a suffix replay starting at a page boundary cannot recover that queue. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: ten page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, a 30pt `\topskip`, a forced `\newpage`, stretchy `\vskip` glue between paragraphs, footnotes raised with `\footnotetext`, and a `[t]` float that reserves its height plus `\textfloatsep` on the page it appears, and `[b]` floats that fit or defer to the next page) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`. M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row heights and cell text widths to scaled points; the painter uses 10pt glyphs in 12pt rows. Rules and spans are painted; tall tables split at row boundaries (`Halign::split_for_height`) with column widths preserved. @@ -366,7 +366,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 306 unit tests plus seven route-D integration tests and thirty-four oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 462 tests (306 route-D unit, 7 route-D integration, 34 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path. +The crate currently has 307 unit tests plus seven route-D integration tests and thirty-four oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 463 tests (307 route-D unit, 7 route-D integration, 34 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo