Remove the duplicate page-break planner and page-layout cache
This commit is contained in:
1 parent
dd3a20890d
commit
b4ee4c1330
8 files changed
+40
-1591
No files matched your search
@@ -374,7 +374,7 @@ binary operators, and punctuation. Fractions, scripts, roots, and delimiters
|
|||||||
remain indivisible math boxes. Rust paints ordinary paragraph lines at their
|
remain indivisible math boxes. Rust paints ordinary paragraph lines at their
|
||||||
measured baselines and applies the line breaker's adjusted word spaces. For
|
measured baselines and applies the line breaker's adjusted word spaces. For
|
||||||
documents with no title block and only plain paragraphs and headings, Rust
|
documents with no title block and only plain paragraphs and headings, Rust
|
||||||
builds the vertical list, chooses page breaks, and assigns line positions;
|
paginates and assigns line positions in one positioned-layout pass;
|
||||||
`genpdf` paints those line boxes at the planned coordinates. Mixed-content
|
`genpdf` paints those line boxes at the planned coordinates. Mixed-content
|
||||||
documents still use `genpdf` for page composition. This fixed-spacing subset is
|
documents still use `genpdf` for page composition. This fixed-spacing subset is
|
||||||
an initial page-building slice, not full TeX page building. Display math
|
an initial page-building slice, not full TeX page building. Display math
|
||||||
@@ -486,9 +486,9 @@ advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`,
|
|||||||
| Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, centering, `\parindent` (17pt default), `\hfill`/`\hfil` | `\raggedright`/`\raggedleft` |
|
| Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, centering, `\parindent` (17pt default), `\hfill`/`\hfil` | `\raggedright`/`\raggedleft` |
|
||||||
| Notes/floats | footnotes with page-bottom insertion area, title/author `\thanks`, figure/table `[htbp]` placement (top/bottom/page/here approximations) | deferred float queue, `\textfraction` |
|
| Notes/floats | footnotes with page-bottom insertion area, title/author `\thanks`, figure/table `[htbp]` placement (top/bottom/page/here approximations) | deferred float queue, `\textfraction` |
|
||||||
| Contents | `\tableofcontents`, `\listoffigures`, `\listoftables` generated from numbered headings and captions, page numbers resolved after pagination | dotted leaders, per-chapter book/report contents |
|
| Contents | `\tableofcontents`, `\listoffigures`, `\listoftables` generated from numbered headings and captions, page numbers resolved after pagination | dotted leaders, per-chapter book/report contents |
|
||||||
| Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak`, plain/fancy page styles, `\thispagestyle`, fancyhdr L/C/R headers and footers | unified planner/renderer |
|
| Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak`, plain/fancy page styles, `\thispagestyle`, fancyhdr L/C/R headers and footers | — |
|
||||||
| Classes/packages | built-in + local classes, option protocol, local package options, base font sizes 10/11/12pt | class-specific section formatting |
|
| Classes/packages | built-in + local classes, option protocol, local package options, base font sizes 10/11/12pt | class-specific section formatting |
|
||||||
| Live preview | incremental paragraph/page caches, page-hash diffing, SVG refresh | — |
|
| Live preview | incremental paragraph cache, page-hash diffing, SVG refresh | — |
|
||||||
|
|
||||||
The compatibility layer also covers spacing macros, text symbols/letters, style
|
The compatibility layer also covers spacing macros, text symbols/letters, style
|
||||||
commands, break advisories, and document metadata; see the sections above.
|
commands, break advisories, and document metadata; see the sections above.
|
||||||
+21
-19
@@ -9,32 +9,34 @@ family and true scaled small caps; inline box geometry (`\fbox`, `\makebox`,
|
|||||||
footnotes/`\thanks`; figure/table `[htbp]` placement approximations; page
|
footnotes/`\thanks`; figure/table `[htbp]` placement approximations; page
|
||||||
styles (plain/fancy, `\thispagestyle`, fancyhdr headers/footers, `\thepage`);
|
styles (plain/fancy, `\thispagestyle`, fancyhdr headers/footers, `\thepage`);
|
||||||
geometry-aware `\textwidth`/`\textheight` named length registers; table of
|
geometry-aware `\textwidth`/`\textheight` named length registers; table of
|
||||||
contents and figure/table lists; and native PDF rectangles for rules and
|
contents and figure/table lists; native PDF rectangles; unified pagination
|
||||||
frames (vendored genpdf `fill_rect`/`draw_rect`, no image XObjects).
|
(`build_positioned_pages` is the only page builder and no separate break
|
||||||
|
planner remains).
|
||||||
|
|
||||||
## 1. Unified pagination
|
## 1. Deferred float queue
|
||||||
|
|
||||||
- Extract the current duplicated planner (`build_page_break_plan`) and renderer
|
- Figures/tables currently place immediately from their source position. Add a
|
||||||
(`build_positioned_pages`) vertical logic into one page builder returning an
|
per-page float queue with `\textfraction`/`\topfraction` tuning so a later
|
||||||
ordered list of placed items, then use it for both page-break decisions and
|
float can move ahead of text while preserving source order numbers.
|
||||||
final painting. This is the prerequisite for a true deferred float queue.
|
|
||||||
|
|
||||||
## 2. Base font size (implemented)
|
## 2. Paragraph alignment declarations (remaining)
|
||||||
|
|
||||||
- `DocumentModel.base_font_size` is set by the class option (default 11)
|
- `\raggedright`/`\raggedleft` are parsed as no-ops. Thread a per-paragraph
|
||||||
and threaded through both the page planner and the positioned renderer:
|
alignment into `Block::Paragraph`, then select natural spaces rather than
|
||||||
body lines, headings (`article_heading_font_size`), title material, lists,
|
justification in `boxworks_line_break`/`cached_paragraph_lines`.
|
||||||
tables, block boxes, footnotes, and the default `\parindent` (15pt for
|
|
||||||
10/12pt, 17pt for 11pt).
|
|
||||||
|
|
||||||
## 3. Table of contents and lists (implemented)
|
## 3. True vertical boxes (remaining)
|
||||||
|
|
||||||
- Parser placeholders are expanded after parsing into headings plus entries
|
- `\vbox`/`\vtop` currently map to a full-width block `\parbox`. A real VBox
|
||||||
from numbered sections and captions; entry runs carry a `TocPage` reference
|
needs a vertical-material capture with its own natural width, baseline, and
|
||||||
that is resolved by re-laying out once page numbers are known. Dotted
|
nested line/box children in the positioned renderer.
|
||||||
leaders are not implemented.
|
|
||||||
|
|
||||||
## 4. PDF painting and title blocks (remaining)
|
## 4. Contents leaders (remaining)
|
||||||
|
|
||||||
|
- TOC/list entries use infinite glue for right-aligned page numbers. Dotted
|
||||||
|
leaders require a glue item that repeats a character across its stretch.
|
||||||
|
|
||||||
|
## 5. Custom title blocks (remaining)
|
||||||
|
|
||||||
- Let a document-level `\renewcommand{\maketitle}` contribute a real title
|
- Let a document-level `\renewcommand{\maketitle}` contribute a real title
|
||||||
block once the engine's title model can run box material.
|
block once the engine's title model can run box material.
|
||||||
+5
-4
@@ -43,8 +43,8 @@ the source changes; the SVG preview is refreshed per page.
|
|||||||
- Compatibility: spacing macros (quad/qquad/thin/en/med/thick, `\vspace*`,
|
- Compatibility: spacing macros (quad/qquad/thin/en/med/thick, `\vspace*`,
|
||||||
`\hspace*`, skips), text symbols/letters/punctuation, break advisories,
|
`\hspace*`, skips), text symbols/letters/punctuation, break advisories,
|
||||||
metadata, citations/references, tables/lists/images.
|
metadata, citations/references, tables/lists/images.
|
||||||
- Live preview: paragraph and page-layout caches, page-hash diffing, warm
|
- Live preview: paragraph cache, page-hash diffing, warm rebuilds in the low
|
||||||
rebuilds in the low milliseconds for small edits.
|
milliseconds for small edits.
|
||||||
|
|
||||||
## Remaining structural work
|
## Remaining structural work
|
||||||
|
|
||||||
@@ -55,8 +55,9 @@ See `docs/ROADMAP.md` for concrete implementation plans.
|
|||||||
- Boxes: `\parbox`/`\minipage` are block-level; `\vbox`/`\vtop` map to a
|
- Boxes: `\parbox`/`\minipage` are block-level; `\vbox`/`\vtop` map to a
|
||||||
full-width block rather than true nested VBox material.
|
full-width block rather than true nested VBox material.
|
||||||
- Pages: float placement is immediate rather than a deferred float queue
|
- Pages: float placement is immediate rather than a deferred float queue
|
||||||
(no `\textfraction` tuning, no reordering around later text); planner and
|
(no `\textfraction` tuning, no reordering around later text). Pagination is
|
||||||
renderer are still separate.
|
performed by the positioned renderer; the separate page-break planner was
|
||||||
|
removed.
|
||||||
- Notes: footnotes inside captions, floats, or arbitrary boxes are not
|
- Notes: footnotes inside captions, floats, or arbitrary boxes are not
|
||||||
collected; the insertion area currently follows the page where the paragraph
|
collected; the insertion area currently follows the page where the paragraph
|
||||||
ends rather than the exact reference line.
|
ends rather than the exact reference line.
|
||||||
|
|||||||
@@ -66,7 +66,6 @@ struct FrontendInputKey {
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct CompilerSession {
|
pub struct CompilerSession {
|
||||||
paragraph_layout_cache: pdf::ParagraphLayoutCache,
|
paragraph_layout_cache: pdf::ParagraphLayoutCache,
|
||||||
page_layout_cache: pdf::PageLayoutCache,
|
|
||||||
compilation_cache: VecDeque<CachedCompilation>,
|
compilation_cache: VecDeque<CachedCompilation>,
|
||||||
expansion_cache: tex_expansion::ExpansionCache,
|
expansion_cache: tex_expansion::ExpansionCache,
|
||||||
math_parse_cache: frontend::MathParseCache,
|
math_parse_cache: frontend::MathParseCache,
|
||||||
@@ -87,7 +86,6 @@ impl CompilerSession {
|
|||||||
model,
|
model,
|
||||||
source_dir,
|
source_dir,
|
||||||
&mut self.paragraph_layout_cache,
|
&mut self.paragraph_layout_cache,
|
||||||
&mut self.page_layout_cache,
|
|
||||||
math_metrics,
|
math_metrics,
|
||||||
Rc::clone(&self.math_layout_cache),
|
Rc::clone(&self.math_layout_cache),
|
||||||
)?;
|
)?;
|
||||||
@@ -125,7 +123,6 @@ impl CompilerSession {
|
|||||||
content_width,
|
content_width,
|
||||||
content_height,
|
content_height,
|
||||||
&mut self.paragraph_layout_cache,
|
&mut self.paragraph_layout_cache,
|
||||||
&mut self.page_layout_cache,
|
|
||||||
)?;
|
)?;
|
||||||
let duration_ms = timing_start.elapsed().as_secs_f64() * 1000.0;
|
let duration_ms = timing_start.elapsed().as_secs_f64() * 1000.0;
|
||||||
log_timing("preview", timing_start);
|
log_timing("preview", timing_start);
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
// Rust reimplementation of the fixed-box, glue, and kern page-break slice from
|
// Page anchors identify the first line of a block on a page. Pagination itself
|
||||||
// XeTeX's `xetex.web` (`vert_break` and `build_page`); TeX modes, inserts, and
|
// is performed by the positioned renderer in `pdf/layout.rs`; this module only
|
||||||
// output routines remain outside this module.
|
// keeps the shared anchor type.
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
pub(super) struct PageAnchor {
|
pub(super) struct PageAnchor {
|
||||||
pub(super) block: usize,
|
pub(super) block: usize,
|
||||||
@@ -10,7 +8,6 @@ pub(super) struct PageAnchor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
#[derive(Clone, Copy, Debug)]
|
||||||
#[allow(dead_code)] // Preserve TeX's full glue-order model as syntax support expands.
|
|
||||||
pub(super) enum GlueOrder {
|
pub(super) enum GlueOrder {
|
||||||
Normal,
|
Normal,
|
||||||
Fil,
|
Fil,
|
||||||
@@ -18,17 +15,6 @@ pub(super) enum GlueOrder {
|
|||||||
Filll,
|
Filll,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlueOrder {
|
|
||||||
const fn index(self) -> usize {
|
|
||||||
match self {
|
|
||||||
Self::Normal => 0,
|
|
||||||
Self::Fil => 1,
|
|
||||||
Self::Fill => 2,
|
|
||||||
Self::Filll => 3,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<super::engine::glue::TeXGlueOrder> for GlueOrder {
|
impl From<super::engine::glue::TeXGlueOrder> for GlueOrder {
|
||||||
fn from(order: super::engine::glue::TeXGlueOrder) -> Self {
|
fn from(order: super::engine::glue::TeXGlueOrder) -> Self {
|
||||||
match order {
|
match order {
|
||||||
@@ -39,323 +25,3 @@ impl From<super::engine::glue::TeXGlueOrder> for GlueOrder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub(super) enum VerticalNode {
|
|
||||||
Box {
|
|
||||||
height: i64,
|
|
||||||
depth: i64,
|
|
||||||
anchor: Option<PageAnchor>,
|
|
||||||
},
|
|
||||||
Glue {
|
|
||||||
width: i64,
|
|
||||||
stretch: i64,
|
|
||||||
stretch_order: GlueOrder,
|
|
||||||
shrink: i64,
|
|
||||||
// The page-break cost uses total shrink; retain its order for later
|
|
||||||
// page-level glue setting in the positioned renderer.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
shrink_order: GlueOrder,
|
|
||||||
},
|
|
||||||
Kern(i64),
|
|
||||||
Penalty(i32),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VerticalNode {
|
|
||||||
pub(super) fn fixed_glue(width: i64) -> Self {
|
|
||||||
Self::Glue {
|
|
||||||
width,
|
|
||||||
stretch: 0,
|
|
||||||
stretch_order: GlueOrder::Normal,
|
|
||||||
shrink: 0,
|
|
||||||
shrink_order: GlueOrder::Normal,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn glue(
|
|
||||||
width: i64,
|
|
||||||
stretch: i64,
|
|
||||||
stretch_order: GlueOrder,
|
|
||||||
shrink: i64,
|
|
||||||
shrink_order: GlueOrder,
|
|
||||||
) -> Self {
|
|
||||||
Self::Glue {
|
|
||||||
width,
|
|
||||||
stretch,
|
|
||||||
stretch_order,
|
|
||||||
shrink,
|
|
||||||
shrink_order,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default)]
|
|
||||||
struct PageDimensions {
|
|
||||||
// Mirrors TeX's page_total: the pending bottom depth is accounted for only
|
|
||||||
// when another box or vertical glue is added.
|
|
||||||
height: i64,
|
|
||||||
depth: i64,
|
|
||||||
stretch: [i64; 4],
|
|
||||||
shrink: i64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
struct BreakCandidate {
|
|
||||||
node: usize,
|
|
||||||
dependency_end: usize,
|
|
||||||
cost: i64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub(super) struct PageBreakDecision {
|
|
||||||
pub(super) anchor: PageAnchor,
|
|
||||||
pub(super) dependency_end: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(super) struct PlannedPageBreaks {
|
|
||||||
pub(super) anchors: HashSet<PageAnchor>,
|
|
||||||
pub(super) decisions: Vec<PageBreakDecision>,
|
|
||||||
}
|
|
||||||
|
|
||||||
const INFINITE_BADNESS: i64 = 10_000;
|
|
||||||
const AWFUL_BADNESS: i64 = 1_073_741_823;
|
|
||||||
const DEPLORABLE_COST: i64 = 100_000;
|
|
||||||
const INFINITE_PENALTY: i32 = 10_000;
|
|
||||||
const EJECT_PENALTY: i32 = -10_000;
|
|
||||||
|
|
||||||
pub(super) fn plan_page_breaks_with_dependencies(
|
|
||||||
nodes: &[VerticalNode],
|
|
||||||
start_node: usize,
|
|
||||||
page_goal: i64,
|
|
||||||
top_skip: i64,
|
|
||||||
max_depth: i64,
|
|
||||||
) -> PlannedPageBreaks {
|
|
||||||
let mut plan = PlannedPageBreaks::default();
|
|
||||||
let mut page_start = start_node.min(nodes.len());
|
|
||||||
|
|
||||||
while page_start < nodes.len() {
|
|
||||||
let Some(candidate) = find_page_break(nodes, page_start, page_goal, top_skip, max_depth)
|
|
||||||
else {
|
|
||||||
break;
|
|
||||||
};
|
|
||||||
let mut next_page_start = candidate.node + 1;
|
|
||||||
while next_page_start < nodes.len() && is_discardable(nodes[next_page_start]) {
|
|
||||||
next_page_start += 1;
|
|
||||||
}
|
|
||||||
if next_page_start <= page_start || next_page_start >= nodes.len() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if let Some(anchor) = nodes[next_page_start..].iter().find_map(|node| match node {
|
|
||||||
VerticalNode::Box { anchor, .. } => *anchor,
|
|
||||||
_ => None,
|
|
||||||
}) {
|
|
||||||
plan.anchors.insert(anchor);
|
|
||||||
plan.decisions.push(PageBreakDecision {
|
|
||||||
anchor,
|
|
||||||
dependency_end: candidate.dependency_end,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
page_start = next_page_start;
|
|
||||||
}
|
|
||||||
|
|
||||||
plan
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_page_break(
|
|
||||||
nodes: &[VerticalNode],
|
|
||||||
start: usize,
|
|
||||||
page_goal: i64,
|
|
||||||
top_skip: i64,
|
|
||||||
max_depth: i64,
|
|
||||||
) -> Option<BreakCandidate> {
|
|
||||||
let mut dimensions = PageDimensions::default();
|
|
||||||
let mut best = None;
|
|
||||||
let mut least_cost = AWFUL_BADNESS;
|
|
||||||
let mut has_box = false;
|
|
||||||
let mut last_node_was_box = false;
|
|
||||||
|
|
||||||
for (offset, node) in nodes.iter().copied().enumerate().skip(start) {
|
|
||||||
match node {
|
|
||||||
VerticalNode::Box { height, depth, .. } => {
|
|
||||||
if !has_box {
|
|
||||||
dimensions.height = dimensions
|
|
||||||
.height
|
|
||||||
.saturating_add(top_skip.saturating_sub(height).max(0));
|
|
||||||
dimensions.height = dimensions.height.saturating_add(height);
|
|
||||||
has_box = true;
|
|
||||||
} else {
|
|
||||||
dimensions.height = dimensions
|
|
||||||
.height
|
|
||||||
.saturating_add(dimensions.depth)
|
|
||||||
.saturating_add(height);
|
|
||||||
}
|
|
||||||
dimensions.depth = depth;
|
|
||||||
if dimensions.depth > max_depth {
|
|
||||||
dimensions.height = dimensions
|
|
||||||
.height
|
|
||||||
.saturating_add(dimensions.depth - max_depth);
|
|
||||||
dimensions.depth = max_depth;
|
|
||||||
}
|
|
||||||
last_node_was_box = true;
|
|
||||||
}
|
|
||||||
VerticalNode::Glue {
|
|
||||||
width,
|
|
||||||
stretch,
|
|
||||||
stretch_order,
|
|
||||||
shrink,
|
|
||||||
shrink_order: _,
|
|
||||||
} => {
|
|
||||||
if !has_box {
|
|
||||||
last_node_was_box = false;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if last_node_was_box {
|
|
||||||
let candidate = make_candidate(offset, 0, dimensions, page_goal);
|
|
||||||
update_best(candidate, &mut best, &mut least_cost);
|
|
||||||
if dimensions.height > page_goal
|
|
||||||
&& dimensions.height - page_goal > dimensions.shrink
|
|
||||||
{
|
|
||||||
let mut selected = best.unwrap_or(candidate);
|
|
||||||
selected.dependency_end = offset;
|
|
||||||
return Some(selected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
dimensions.height = dimensions
|
|
||||||
.height
|
|
||||||
.saturating_add(dimensions.depth)
|
|
||||||
.saturating_add(width);
|
|
||||||
dimensions.depth = 0;
|
|
||||||
let stretch_order = stretch_order.index();
|
|
||||||
dimensions.stretch[stretch_order] =
|
|
||||||
dimensions.stretch[stretch_order].saturating_add(stretch.max(0));
|
|
||||||
dimensions.shrink = dimensions.shrink.saturating_add(shrink.max(0));
|
|
||||||
last_node_was_box = false;
|
|
||||||
}
|
|
||||||
VerticalNode::Penalty(penalty) => {
|
|
||||||
if !has_box {
|
|
||||||
last_node_was_box = false;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if penalty <= EJECT_PENALTY {
|
|
||||||
return Some(make_candidate(offset, penalty, dimensions, page_goal));
|
|
||||||
}
|
|
||||||
if has_box && penalty < INFINITE_PENALTY {
|
|
||||||
let candidate = make_candidate(offset, penalty, dimensions, page_goal);
|
|
||||||
update_best(candidate, &mut best, &mut least_cost);
|
|
||||||
if page_badness(dimensions, page_goal) == AWFUL_BADNESS {
|
|
||||||
let mut selected = best.unwrap_or(candidate);
|
|
||||||
selected.dependency_end = offset;
|
|
||||||
return Some(selected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
last_node_was_box = false;
|
|
||||||
}
|
|
||||||
VerticalNode::Kern(width) => {
|
|
||||||
if has_box
|
|
||||||
&& (offset + 1 == nodes.len()
|
|
||||||
|| matches!(nodes[offset + 1], VerticalNode::Glue { .. }))
|
|
||||||
{
|
|
||||||
let candidate = make_candidate(offset, 0, dimensions, page_goal);
|
|
||||||
update_best(candidate, &mut best, &mut least_cost);
|
|
||||||
if page_badness(dimensions, page_goal) == AWFUL_BADNESS {
|
|
||||||
let mut selected = best.unwrap_or(candidate);
|
|
||||||
selected.dependency_end = offset;
|
|
||||||
return Some(selected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if has_box {
|
|
||||||
dimensions.height = dimensions
|
|
||||||
.height
|
|
||||||
.saturating_add(dimensions.depth)
|
|
||||||
.saturating_add(width);
|
|
||||||
dimensions.depth = 0;
|
|
||||||
}
|
|
||||||
last_node_was_box = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_candidate(
|
|
||||||
node: usize,
|
|
||||||
penalty: i32,
|
|
||||||
dimensions: PageDimensions,
|
|
||||||
page_goal: i64,
|
|
||||||
) -> BreakCandidate {
|
|
||||||
let badness = page_badness(dimensions, page_goal);
|
|
||||||
let cost = if penalty <= EJECT_PENALTY {
|
|
||||||
i64::from(penalty)
|
|
||||||
} else if badness < AWFUL_BADNESS && badness < INFINITE_BADNESS {
|
|
||||||
badness + i64::from(penalty)
|
|
||||||
} else if badness < AWFUL_BADNESS {
|
|
||||||
DEPLORABLE_COST
|
|
||||||
} else {
|
|
||||||
AWFUL_BADNESS
|
|
||||||
};
|
|
||||||
BreakCandidate {
|
|
||||||
node,
|
|
||||||
dependency_end: node,
|
|
||||||
cost,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn update_best(candidate: BreakCandidate, best: &mut Option<BreakCandidate>, least_cost: &mut i64) {
|
|
||||||
if candidate.cost <= *least_cost {
|
|
||||||
*best = Some(candidate);
|
|
||||||
*least_cost = candidate.cost;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn page_badness(dimensions: PageDimensions, page_goal: i64) -> i64 {
|
|
||||||
let difference = page_goal.saturating_sub(dimensions.height);
|
|
||||||
if difference == 0 {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if difference > 0 {
|
|
||||||
if dimensions.stretch[1..].iter().any(|stretch| *stretch > 0) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return ratio_badness(difference, dimensions.stretch[GlueOrder::Normal.index()]);
|
|
||||||
}
|
|
||||||
let excess = difference.saturating_neg();
|
|
||||||
if excess > dimensions.shrink {
|
|
||||||
AWFUL_BADNESS
|
|
||||||
} else {
|
|
||||||
ratio_badness(excess, dimensions.shrink)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ratio_badness(amount: i64, available: i64) -> i64 {
|
|
||||||
// TeX's `badness` routine in tex.web uses integer arithmetic so page-break
|
|
||||||
// choices do not depend on host floating-point behavior. The first branch
|
|
||||||
// keeps the multiply within the range used by TeX's scaled arithmetic.
|
|
||||||
if amount == 0 {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if available <= 0 {
|
|
||||||
return INFINITE_BADNESS;
|
|
||||||
}
|
|
||||||
|
|
||||||
let ratio = if amount <= 7_230_584 {
|
|
||||||
amount.saturating_mul(297) / available
|
|
||||||
} else if available >= 1_663_497 {
|
|
||||||
amount / (available / 297)
|
|
||||||
} else {
|
|
||||||
amount
|
|
||||||
};
|
|
||||||
if ratio > 1_290 {
|
|
||||||
return INFINITE_BADNESS;
|
|
||||||
}
|
|
||||||
|
|
||||||
(ratio * ratio * ratio + 0x4_0000) / 0x10_0000
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_discardable(node: VerticalNode) -> bool {
|
|
||||||
matches!(
|
|
||||||
node,
|
|
||||||
VerticalNode::Glue { .. } | VerticalNode::Penalty(_) | VerticalNode::Kern(_)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
+6
-252
@@ -18,12 +18,11 @@ use genpdf::{
|
|||||||
};
|
};
|
||||||
use rusttype::Font as RustFont;
|
use rusttype::Font as RustFont;
|
||||||
|
|
||||||
use super::engine::glue::TeXGlue;
|
use super::page_builder::{GlueOrder, PageAnchor};
|
||||||
use super::page_builder::{self, GlueOrder, PageAnchor, VerticalNode};
|
|
||||||
use super::{
|
use super::{
|
||||||
Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, MathExpr,
|
Block, ColumnAlignment, DocumentModel, ListBlock, MathExpr, MathLayoutEnvironment,
|
||||||
MathLayoutEnvironment, PAGE_NUMBER_MARKER, PDF_POINTS_PER_INCH, PageDecoration,
|
PAGE_NUMBER_MARKER, PDF_POINTS_PER_INCH, PageDecoration, PageDecorationPosition, PageStyleKind,
|
||||||
PageDecorationPosition, PageStyleKind, RuleBox, Run,
|
RuleBox, Run,
|
||||||
box_font::{BoxFont, TeXHyphenator, scaled_points},
|
box_font::{BoxFont, TeXHyphenator, scaled_points},
|
||||||
is_cjk, math_font, math_layout, parse_dimension, prohibits_cjk_line_break, text_layout,
|
is_cjk, math_font, math_layout, parse_dimension, prohibits_cjk_line_break, text_layout,
|
||||||
};
|
};
|
||||||
@@ -31,8 +30,7 @@ use super::{
|
|||||||
mod layout;
|
mod layout;
|
||||||
pub(super) mod preview;
|
pub(super) mod preview;
|
||||||
use self::layout::{
|
use self::layout::{
|
||||||
cached_paragraph_lines, layout_document, page_break_dependencies, plan_all_page_breaks,
|
cached_paragraph_lines, layout_document, scaled_units_to_mm, text_line_metrics_scaled,
|
||||||
positioned_item_anchor, scaled_units_to_mm, text_line_metrics_scaled,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// The local font renderer takes integer point sizes, so `\Large` is rounded
|
// The local font renderer takes integer point sizes, so `\Large` is rounded
|
||||||
@@ -61,85 +59,8 @@ pub(super) struct ParagraphLayoutCache {
|
|||||||
insertion_order: VecDeque<ParagraphLayoutKey>,
|
insertion_order: VecDeque<ParagraphLayoutKey>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
||||||
enum PageBlockKey {
|
|
||||||
Paragraph(Vec<Run>),
|
|
||||||
Heading {
|
|
||||||
level: u8,
|
|
||||||
runs: Vec<Run>,
|
|
||||||
},
|
|
||||||
List(ListBlock),
|
|
||||||
Table {
|
|
||||||
rows: Vec<Vec<Vec<Run>>>,
|
|
||||||
caption: Option<Vec<Run>>,
|
|
||||||
alignments: Vec<u8>,
|
|
||||||
rules: Vec<usize>,
|
|
||||||
},
|
|
||||||
Image {
|
|
||||||
path: PathBuf,
|
|
||||||
options: String,
|
|
||||||
caption: Option<Vec<Run>>,
|
|
||||||
placement: String,
|
|
||||||
fingerprint: u64,
|
|
||||||
},
|
|
||||||
Bibliography(Vec<(String, Vec<Run>)>),
|
|
||||||
FramedBox {
|
|
||||||
runs: Vec<Run>,
|
|
||||||
frame: bool,
|
|
||||||
width: Option<common::Scaled>,
|
|
||||||
},
|
|
||||||
Centered(Vec<Run>),
|
|
||||||
HorizontalRule {
|
|
||||||
height: common::Scaled,
|
|
||||||
width: Option<common::Scaled>,
|
|
||||||
},
|
|
||||||
Math {
|
|
||||||
expression: MathExpr,
|
|
||||||
equation_numbers: Vec<Option<EquationNumber>>,
|
|
||||||
},
|
|
||||||
VerticalKern(common::Scaled),
|
|
||||||
VerticalGlue(TeXGlue),
|
|
||||||
Penalty(i32),
|
|
||||||
PageBreak,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq)]
|
|
||||||
struct PageLayoutConfig {
|
|
||||||
content_width_bits: u64,
|
|
||||||
content_height_bits: u64,
|
|
||||||
top_skip: i64,
|
|
||||||
max_depth: i64,
|
|
||||||
text_font_fingerprint: u64,
|
|
||||||
math_font_fingerprint: u64,
|
|
||||||
math_layout_font_fingerprint: u64,
|
|
||||||
page_style_fingerprint: u64,
|
|
||||||
base_font_size: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct PageLayoutSnapshot {
|
|
||||||
config: PageLayoutConfig,
|
|
||||||
blocks: Vec<PageBlockKey>,
|
|
||||||
page_starts: Vec<PageAnchor>,
|
|
||||||
block_first_pages: Vec<usize>,
|
|
||||||
page_dependencies: Vec<Option<usize>>,
|
|
||||||
incremental_safe: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(super) struct PageLayoutCache {
|
|
||||||
snapshot: Option<PageLayoutSnapshot>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct PageBreakPlan {
|
struct PageBreakPlan {
|
||||||
breaks: HashSet<PageAnchor>,
|
breaks: HashSet<PageAnchor>,
|
||||||
dependencies: HashMap<PageAnchor, usize>,
|
|
||||||
config: PageLayoutConfig,
|
|
||||||
blocks: Vec<PageBlockKey>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct PlannedBreaks {
|
|
||||||
anchors: HashSet<PageAnchor>,
|
|
||||||
dependencies: HashMap<PageAnchor, usize>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum PositionedLineContent {
|
enum PositionedLineContent {
|
||||||
@@ -340,6 +261,7 @@ impl PositionedTable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)] // anchors remain useful for diagnostics and future page queries
|
||||||
enum PositionedPageItem {
|
enum PositionedPageItem {
|
||||||
Line(PositionedLine),
|
Line(PositionedLine),
|
||||||
DisplayMath {
|
DisplayMath {
|
||||||
@@ -698,169 +620,6 @@ impl ParagraphLayoutCache {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PageLayoutCache {
|
|
||||||
fn plan(
|
|
||||||
&self,
|
|
||||||
config: &PageLayoutConfig,
|
|
||||||
blocks: &[PageBlockKey],
|
|
||||||
nodes: &[VerticalNode],
|
|
||||||
page_goal: i64,
|
|
||||||
top_skip: i64,
|
|
||||||
max_depth: i64,
|
|
||||||
) -> PlannedBreaks {
|
|
||||||
let Some(previous) = self.snapshot.as_ref() else {
|
|
||||||
return plan_all_page_breaks(nodes, page_goal, top_skip, max_depth);
|
|
||||||
};
|
|
||||||
if previous.config != *config {
|
|
||||||
return plan_all_page_breaks(nodes, page_goal, top_skip, max_depth);
|
|
||||||
}
|
|
||||||
|
|
||||||
let common_prefix = previous
|
|
||||||
.blocks
|
|
||||||
.iter()
|
|
||||||
.zip(blocks)
|
|
||||||
.take_while(|(old, new)| old == new)
|
|
||||||
.count();
|
|
||||||
if common_prefix == previous.blocks.len() && common_prefix == blocks.len() {
|
|
||||||
return PlannedBreaks {
|
|
||||||
anchors: previous.page_starts.iter().copied().skip(1).collect(),
|
|
||||||
dependencies: previous
|
|
||||||
.page_starts
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.zip(&previous.page_dependencies)
|
|
||||||
.skip(1)
|
|
||||||
.filter_map(|(anchor, dependency)| {
|
|
||||||
dependency.map(|dependency| (anchor, dependency))
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
let prefix_only_change = common_prefix == previous.blocks.len().min(blocks.len());
|
|
||||||
if !previous.incremental_safe
|
|
||||||
|| (previous.blocks.len() != blocks.len() && !prefix_only_change)
|
|
||||||
{
|
|
||||||
return plan_all_page_breaks(nodes, page_goal, top_skip, max_depth);
|
|
||||||
}
|
|
||||||
|
|
||||||
let dirty_page = previous
|
|
||||||
.block_first_pages
|
|
||||||
.get(common_prefix)
|
|
||||||
.copied()
|
|
||||||
.unwrap_or_else(|| previous.page_starts.len().saturating_sub(1));
|
|
||||||
|
|
||||||
// A page-break decision may inspect nodes beyond its chosen break.
|
|
||||||
// Recompute from the earliest previous page whose look-ahead reaches
|
|
||||||
// the changed block. Appending can also extend a decision that reached
|
|
||||||
// the old final block.
|
|
||||||
let dependency_start = if blocks.len() > previous.blocks.len() {
|
|
||||||
common_prefix.saturating_sub(1)
|
|
||||||
} else {
|
|
||||||
common_prefix
|
|
||||||
};
|
|
||||||
let dependency_restart_page = previous
|
|
||||||
.page_dependencies
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.skip(1)
|
|
||||||
.find_map(|(page_index, dependency)| {
|
|
||||||
dependency
|
|
||||||
.is_some_and(|dependency| dependency >= dependency_start)
|
|
||||||
.then_some(page_index.saturating_sub(1))
|
|
||||||
})
|
|
||||||
.unwrap_or(dirty_page);
|
|
||||||
let restart_page = dirty_page.min(dependency_restart_page);
|
|
||||||
let start_node = if restart_page == 0 {
|
|
||||||
0
|
|
||||||
} else {
|
|
||||||
let Some(restart_anchor) = previous.page_starts.get(restart_page).copied() else {
|
|
||||||
return plan_all_page_breaks(nodes, page_goal, top_skip, max_depth);
|
|
||||||
};
|
|
||||||
let Some(start_node) = nodes.iter().position(|node| {
|
|
||||||
matches!(node, VerticalNode::Box { anchor: Some(anchor), .. } if *anchor == restart_anchor)
|
|
||||||
}) else {
|
|
||||||
return plan_all_page_breaks(nodes, page_goal, top_skip, max_depth);
|
|
||||||
};
|
|
||||||
start_node
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut plan = PlannedBreaks {
|
|
||||||
anchors: previous
|
|
||||||
.page_starts
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.skip(1)
|
|
||||||
.take(restart_page)
|
|
||||||
.collect(),
|
|
||||||
dependencies: previous
|
|
||||||
.page_starts
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.zip(&previous.page_dependencies)
|
|
||||||
.skip(1)
|
|
||||||
.take(restart_page)
|
|
||||||
.filter_map(|(anchor, dependency)| {
|
|
||||||
dependency.map(|dependency| (anchor, dependency))
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
};
|
|
||||||
let suffix = page_builder::plan_page_breaks_with_dependencies(
|
|
||||||
nodes, start_node, page_goal, top_skip, max_depth,
|
|
||||||
);
|
|
||||||
plan.anchors.extend(suffix.anchors);
|
|
||||||
plan.dependencies
|
|
||||||
.extend(page_break_dependencies(nodes, &suffix.decisions));
|
|
||||||
plan
|
|
||||||
}
|
|
||||||
|
|
||||||
fn snapshot(
|
|
||||||
config: PageLayoutConfig,
|
|
||||||
blocks: Vec<PageBlockKey>,
|
|
||||||
dependencies: HashMap<PageAnchor, usize>,
|
|
||||||
positioned_pages: &[PositionedPage],
|
|
||||||
block_count: usize,
|
|
||||||
) -> PageLayoutSnapshot {
|
|
||||||
let page_starts = positioned_pages
|
|
||||||
.iter()
|
|
||||||
.filter_map(|page| page.items.first().map(positioned_item_anchor))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let page_dependencies = page_starts
|
|
||||||
.iter()
|
|
||||||
.map(|anchor| dependencies.get(anchor).copied())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let incremental_safe = page_dependencies.iter().skip(1).all(Option::is_some);
|
|
||||||
let mut block_first_pages: Vec<Option<usize>> = vec![None; block_count];
|
|
||||||
for (page_index, page) in positioned_pages.iter().enumerate() {
|
|
||||||
for item in &page.items {
|
|
||||||
let block_index = positioned_item_anchor(item).block;
|
|
||||||
if let Some(first_page) = block_first_pages.get_mut(block_index) {
|
|
||||||
*first_page = Some((*first_page).map_or(page_index, |old| old.min(page_index)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut previous_page = 0;
|
|
||||||
let block_first_pages = block_first_pages
|
|
||||||
.into_iter()
|
|
||||||
.map(|page| {
|
|
||||||
if let Some(page) = page {
|
|
||||||
previous_page = page;
|
|
||||||
}
|
|
||||||
previous_page
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
PageLayoutSnapshot {
|
|
||||||
config,
|
|
||||||
blocks,
|
|
||||||
page_starts,
|
|
||||||
block_first_pages,
|
|
||||||
page_dependencies,
|
|
||||||
incremental_safe,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct BoxFontMetrics {
|
struct BoxFontMetrics {
|
||||||
latin_fonts: BoxFontFamily,
|
latin_fonts: BoxFontFamily,
|
||||||
cjk_font: Option<Rc<RustFont<'static>>>,
|
cjk_font: Option<Rc<RustFont<'static>>>,
|
||||||
@@ -2231,7 +1990,6 @@ pub(super) fn render_pdf(
|
|||||||
model: DocumentModel,
|
model: DocumentModel,
|
||||||
source_dir: &Path,
|
source_dir: &Path,
|
||||||
paragraph_layout_cache: &mut ParagraphLayoutCache,
|
paragraph_layout_cache: &mut ParagraphLayoutCache,
|
||||||
page_layout_cache: &mut PageLayoutCache,
|
|
||||||
math_metrics: math_font::MathFontMetrics,
|
math_metrics: math_font::MathFontMetrics,
|
||||||
math_layout_cache: Rc<RefCell<math_layout::MathLayoutCache>>,
|
math_layout_cache: Rc<RefCell<math_layout::MathLayoutCache>>,
|
||||||
) -> Result<Vec<u8>, String> {
|
) -> Result<Vec<u8>, String> {
|
||||||
@@ -2253,7 +2011,6 @@ pub(super) fn render_pdf(
|
|||||||
&resources.math_metrics,
|
&resources.math_metrics,
|
||||||
&resources.math_layout,
|
&resources.math_layout,
|
||||||
paragraph_layout_cache,
|
paragraph_layout_cache,
|
||||||
page_layout_cache,
|
|
||||||
);
|
);
|
||||||
super::log_timing("pdf.layout", timing_start);
|
super::log_timing("pdf.layout", timing_start);
|
||||||
if let Some(pages) = page_layout.pages {
|
if let Some(pages) = page_layout.pages {
|
||||||
@@ -2282,9 +2039,6 @@ pub(super) fn render_pdf(
|
|||||||
.render(&mut pdf)
|
.render(&mut pdf)
|
||||||
.map_err(|error| format!("Rust PDF layout failed: {error}"))?;
|
.map_err(|error| format!("Rust PDF layout failed: {error}"))?;
|
||||||
super::log_timing("pdf.paint", timing_start);
|
super::log_timing("pdf.paint", timing_start);
|
||||||
if let Some(snapshot) = page_layout.snapshot {
|
|
||||||
page_layout_cache.snapshot = Some(snapshot);
|
|
||||||
}
|
|
||||||
return Ok(pdf);
|
return Ok(pdf);
|
||||||
}
|
}
|
||||||
let RenderResources {
|
let RenderResources {
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -22,7 +22,6 @@ pub(in crate::rust_typeset) fn render_pages(
|
|||||||
content_width_mm: f64,
|
content_width_mm: f64,
|
||||||
content_height_mm: f64,
|
content_height_mm: f64,
|
||||||
paragraph_layout_cache: &mut ParagraphLayoutCache,
|
paragraph_layout_cache: &mut ParagraphLayoutCache,
|
||||||
page_layout_cache: &mut PageLayoutCache,
|
|
||||||
) -> Result<Option<Vec<PreviewPage>>, String> {
|
) -> Result<Option<Vec<PreviewPage>>, String> {
|
||||||
let timing_start = std::time::Instant::now();
|
let timing_start = std::time::Instant::now();
|
||||||
let page_layout = layout_document(
|
let page_layout = layout_document(
|
||||||
@@ -38,14 +37,10 @@ pub(in crate::rust_typeset) fn render_pages(
|
|||||||
&resources.math_metrics,
|
&resources.math_metrics,
|
||||||
&resources.math_layout,
|
&resources.math_layout,
|
||||||
paragraph_layout_cache,
|
paragraph_layout_cache,
|
||||||
page_layout_cache,
|
|
||||||
);
|
);
|
||||||
let Some(mut pages) = page_layout.pages else {
|
let Some(mut pages) = page_layout.pages else {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
};
|
};
|
||||||
if let Some(snapshot) = page_layout.snapshot {
|
|
||||||
page_layout_cache.snapshot = Some(snapshot);
|
|
||||||
}
|
|
||||||
super::super::log_timing("preview.layout", timing_start);
|
super::super::log_timing("preview.layout", timing_start);
|
||||||
let content_width = Mm::from(content_width_mm);
|
let content_width = Mm::from(content_width_mm);
|
||||||
let mut rendered = Vec::with_capacity(pages.len());
|
let mut rendered = Vec::with_capacity(pages.len());
|
||||||
|
|||||||
Reference in new issue
Block a user