From b4ee4c13308e5359ac9a43fdae51e21f6cf1de74 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Mon, 19 Oct 2026 14:10:08 +0800 Subject: [PATCH] Remove the duplicate page-break planner and page-layout cache --- README.md | 6 +- docs/ROADMAP.md | 40 +- docs/STATUS.md | 9 +- src/rust_typeset.rs | 3 - src/rust_typeset/page_builder.rs | 340 +---------- src/rust_typeset/pdf.rs | 258 +------- src/rust_typeset/pdf/layout.rs | 970 +------------------------------ src/rust_typeset/pdf/preview.rs | 5 - 8 files changed, 40 insertions(+), 1591 deletions(-) diff --git a/README.md b/README.md index 50aec14..f92fdb9 100644 --- a/README.md +++ b/README.md @@ -374,7 +374,7 @@ binary operators, and punctuation. Fractions, scripts, roots, and delimiters remain indivisible math boxes. Rust paints ordinary paragraph lines at their measured baselines and applies the line breaker's adjusted word spaces. For 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 documents still use `genpdf` for page composition. This fixed-spacing subset is 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` | | 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 | -| 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 | -| 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 commands, break advisories, and document metadata; see the sections above. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index cb89341..8d997b7 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -9,32 +9,34 @@ family and true scaled small caps; inline box geometry (`\fbox`, `\makebox`, footnotes/`\thanks`; figure/table `[htbp]` placement approximations; page styles (plain/fancy, `\thispagestyle`, fancyhdr headers/footers, `\thepage`); geometry-aware `\textwidth`/`\textheight` named length registers; table of -contents and figure/table lists; and native PDF rectangles for rules and -frames (vendored genpdf `fill_rect`/`draw_rect`, no image XObjects). +contents and figure/table lists; native PDF rectangles; unified pagination +(`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 - (`build_positioned_pages`) vertical logic into one page builder returning an - ordered list of placed items, then use it for both page-break decisions and - final painting. This is the prerequisite for a true deferred float queue. +- Figures/tables currently place immediately from their source position. Add a + per-page float queue with `\textfraction`/`\topfraction` tuning so a later + float can move ahead of text while preserving source order numbers. -## 2. Base font size (implemented) +## 2. Paragraph alignment declarations (remaining) -- `DocumentModel.base_font_size` is set by the class option (default 11) - and threaded through both the page planner and the positioned renderer: - body lines, headings (`article_heading_font_size`), title material, lists, - tables, block boxes, footnotes, and the default `\parindent` (15pt for - 10/12pt, 17pt for 11pt). +- `\raggedright`/`\raggedleft` are parsed as no-ops. Thread a per-paragraph + alignment into `Block::Paragraph`, then select natural spaces rather than + justification in `boxworks_line_break`/`cached_paragraph_lines`. -## 3. Table of contents and lists (implemented) +## 3. True vertical boxes (remaining) -- Parser placeholders are expanded after parsing into headings plus entries - from numbered sections and captions; entry runs carry a `TocPage` reference - that is resolved by re-laying out once page numbers are known. Dotted - leaders are not implemented. +- `\vbox`/`\vtop` currently map to a full-width block `\parbox`. A real VBox + needs a vertical-material capture with its own natural width, baseline, and + nested line/box children in the positioned renderer. -## 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 block once the engine's title model can run box material. diff --git a/docs/STATUS.md b/docs/STATUS.md index 4e4eea3..11e1d81 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -43,8 +43,8 @@ the source changes; the SVG preview is refreshed per page. - Compatibility: spacing macros (quad/qquad/thin/en/med/thick, `\vspace*`, `\hspace*`, skips), text symbols/letters/punctuation, break advisories, metadata, citations/references, tables/lists/images. -- Live preview: paragraph and page-layout caches, page-hash diffing, warm - rebuilds in the low milliseconds for small edits. +- Live preview: paragraph cache, page-hash diffing, warm rebuilds in the low + milliseconds for small edits. ## 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 full-width block rather than true nested VBox material. - Pages: float placement is immediate rather than a deferred float queue - (no `\textfraction` tuning, no reordering around later text); planner and - renderer are still separate. + (no `\textfraction` tuning, no reordering around later text). Pagination is + performed by the positioned renderer; the separate page-break planner was + removed. - Notes: footnotes inside captions, floats, or arbitrary boxes are not collected; the insertion area currently follows the page where the paragraph ends rather than the exact reference line. diff --git a/src/rust_typeset.rs b/src/rust_typeset.rs index e937747..b380bfb 100644 --- a/src/rust_typeset.rs +++ b/src/rust_typeset.rs @@ -66,7 +66,6 @@ struct FrontendInputKey { #[derive(Default)] pub struct CompilerSession { paragraph_layout_cache: pdf::ParagraphLayoutCache, - page_layout_cache: pdf::PageLayoutCache, compilation_cache: VecDeque, expansion_cache: tex_expansion::ExpansionCache, math_parse_cache: frontend::MathParseCache, @@ -87,7 +86,6 @@ impl CompilerSession { model, source_dir, &mut self.paragraph_layout_cache, - &mut self.page_layout_cache, math_metrics, Rc::clone(&self.math_layout_cache), )?; @@ -125,7 +123,6 @@ impl CompilerSession { content_width, content_height, &mut self.paragraph_layout_cache, - &mut self.page_layout_cache, )?; let duration_ms = timing_start.elapsed().as_secs_f64() * 1000.0; log_timing("preview", timing_start); diff --git a/src/rust_typeset/page_builder.rs b/src/rust_typeset/page_builder.rs index bf701ad..ee79072 100644 --- a/src/rust_typeset/page_builder.rs +++ b/src/rust_typeset/page_builder.rs @@ -1,8 +1,6 @@ -// Rust reimplementation of the fixed-box, glue, and kern page-break slice from -// XeTeX's `xetex.web` (`vert_break` and `build_page`); TeX modes, inserts, and -// output routines remain outside this module. -use std::collections::HashSet; - +// Page anchors identify the first line of a block on a page. Pagination itself +// is performed by the positioned renderer in `pdf/layout.rs`; this module only +// keeps the shared anchor type. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(super) struct PageAnchor { pub(super) block: usize, @@ -10,7 +8,6 @@ pub(super) struct PageAnchor { } #[derive(Clone, Copy, Debug)] -#[allow(dead_code)] // Preserve TeX's full glue-order model as syntax support expands. pub(super) enum GlueOrder { Normal, Fil, @@ -18,17 +15,6 @@ pub(super) enum GlueOrder { Filll, } -impl GlueOrder { - const fn index(self) -> usize { - match self { - Self::Normal => 0, - Self::Fil => 1, - Self::Fill => 2, - Self::Filll => 3, - } - } -} - impl From for GlueOrder { fn from(order: super::engine::glue::TeXGlueOrder) -> Self { match order { @@ -39,323 +25,3 @@ impl From for GlueOrder { } } } - -#[derive(Clone, Copy, Debug)] -pub(super) enum VerticalNode { - Box { - height: i64, - depth: i64, - anchor: Option, - }, - 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, - pub(super) decisions: Vec, -} - -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 { - 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, 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(_) - ) -} diff --git a/src/rust_typeset/pdf.rs b/src/rust_typeset/pdf.rs index ffa6398..e806355 100644 --- a/src/rust_typeset/pdf.rs +++ b/src/rust_typeset/pdf.rs @@ -18,12 +18,11 @@ use genpdf::{ }; use rusttype::Font as RustFont; -use super::engine::glue::TeXGlue; -use super::page_builder::{self, GlueOrder, PageAnchor, VerticalNode}; +use super::page_builder::{GlueOrder, PageAnchor}; use super::{ - Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, MathExpr, - MathLayoutEnvironment, PAGE_NUMBER_MARKER, PDF_POINTS_PER_INCH, PageDecoration, - PageDecorationPosition, PageStyleKind, RuleBox, Run, + Block, ColumnAlignment, DocumentModel, ListBlock, MathExpr, MathLayoutEnvironment, + PAGE_NUMBER_MARKER, PDF_POINTS_PER_INCH, PageDecoration, PageDecorationPosition, PageStyleKind, + RuleBox, Run, box_font::{BoxFont, TeXHyphenator, scaled_points}, is_cjk, math_font, math_layout, parse_dimension, prohibits_cjk_line_break, text_layout, }; @@ -31,8 +30,7 @@ use super::{ mod layout; pub(super) mod preview; use self::layout::{ - cached_paragraph_lines, layout_document, page_break_dependencies, plan_all_page_breaks, - positioned_item_anchor, scaled_units_to_mm, text_line_metrics_scaled, + cached_paragraph_lines, layout_document, scaled_units_to_mm, text_line_metrics_scaled, }; // The local font renderer takes integer point sizes, so `\Large` is rounded @@ -61,85 +59,8 @@ pub(super) struct ParagraphLayoutCache { insertion_order: VecDeque, } -#[derive(Clone, PartialEq, Eq, Hash)] -enum PageBlockKey { - Paragraph(Vec), - Heading { - level: u8, - runs: Vec, - }, - List(ListBlock), - Table { - rows: Vec>>, - caption: Option>, - alignments: Vec, - rules: Vec, - }, - Image { - path: PathBuf, - options: String, - caption: Option>, - placement: String, - fingerprint: u64, - }, - Bibliography(Vec<(String, Vec)>), - FramedBox { - runs: Vec, - frame: bool, - width: Option, - }, - Centered(Vec), - HorizontalRule { - height: common::Scaled, - width: Option, - }, - Math { - expression: MathExpr, - equation_numbers: Vec>, - }, - 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, - page_starts: Vec, - block_first_pages: Vec, - page_dependencies: Vec>, - incremental_safe: bool, -} - -#[derive(Default)] -pub(super) struct PageLayoutCache { - snapshot: Option, -} - struct PageBreakPlan { breaks: HashSet, - dependencies: HashMap, - config: PageLayoutConfig, - blocks: Vec, -} - -struct PlannedBreaks { - anchors: HashSet, - dependencies: HashMap, } enum PositionedLineContent { @@ -340,6 +261,7 @@ impl PositionedTable { } } +#[allow(dead_code)] // anchors remain useful for diagnostics and future page queries enum PositionedPageItem { Line(PositionedLine), 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, - dependencies: HashMap, - positioned_pages: &[PositionedPage], - block_count: usize, - ) -> PageLayoutSnapshot { - let page_starts = positioned_pages - .iter() - .filter_map(|page| page.items.first().map(positioned_item_anchor)) - .collect::>(); - let page_dependencies = page_starts - .iter() - .map(|anchor| dependencies.get(anchor).copied()) - .collect::>(); - let incremental_safe = page_dependencies.iter().skip(1).all(Option::is_some); - let mut block_first_pages: Vec> = 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 { latin_fonts: BoxFontFamily, cjk_font: Option>>, @@ -2231,7 +1990,6 @@ pub(super) fn render_pdf( model: DocumentModel, source_dir: &Path, paragraph_layout_cache: &mut ParagraphLayoutCache, - page_layout_cache: &mut PageLayoutCache, math_metrics: math_font::MathFontMetrics, math_layout_cache: Rc>, ) -> Result, String> { @@ -2253,7 +2011,6 @@ pub(super) fn render_pdf( &resources.math_metrics, &resources.math_layout, paragraph_layout_cache, - page_layout_cache, ); super::log_timing("pdf.layout", timing_start); if let Some(pages) = page_layout.pages { @@ -2282,9 +2039,6 @@ pub(super) fn render_pdf( .render(&mut pdf) .map_err(|error| format!("Rust PDF layout failed: {error}"))?; super::log_timing("pdf.paint", timing_start); - if let Some(snapshot) = page_layout.snapshot { - page_layout_cache.snapshot = Some(snapshot); - } return Ok(pdf); } let RenderResources { diff --git a/src/rust_typeset/pdf/layout.rs b/src/rust_typeset/pdf/layout.rs index ba3f07e..e77f701 100644 --- a/src/rust_typeset/pdf/layout.rs +++ b/src/rust_typeset/pdf/layout.rs @@ -24,7 +24,6 @@ const ARTICLE_11PT_MAX_DEPTH_PT: f64 = 5.5; pub(super) struct DocumentLayout { pub(super) plan: Option, pub(super) pages: Option>, - pub(super) snapshot: Option, } pub(super) fn layout_document( @@ -40,31 +39,7 @@ pub(super) fn layout_document( math_metrics: &math_font::MathFontMetrics, math_layout: &MathLayoutEnvironment, paragraph_cache: &mut ParagraphLayoutCache, - _page_layout_cache: &PageLayoutCache, ) -> DocumentLayout { - let config = PageLayoutConfig { - content_width_bits: content_width_mm.to_bits(), - content_height_bits: content_height_mm.to_bits(), - top_skip: i64::from(scaled_points(ARTICLE_11PT_TOPSKIP_PT).0), - max_depth: i64::from(scaled_points(ARTICLE_11PT_MAX_DEPTH_PT).0), - text_font_fingerprint: metrics.fingerprint, - math_font_fingerprint: math_metrics.fingerprint, - math_layout_font_fingerprint: math_layout.font_fingerprint, - base_font_size: model.base_font_size, - page_style_fingerprint: { - let mut hasher = DefaultHasher::new(); - model.page_style.hash(&mut hasher); - model.page_style_overrides.hash(&mut hasher); - hasher.finish() - }, - }; - let Some(blocks) = page_block_keys(model, source_dir) else { - return DocumentLayout { - plan: None, - pages: None, - snapshot: None, - }; - }; // The positioned renderer is the single pagination authority: explicit // `\newpage`/float placement breaks are applied directly from the block // stream, and natural breaks come from the same vertical placement pass @@ -88,7 +63,6 @@ pub(super) fn layout_document( return DocumentLayout { plan: None, pages: None, - snapshot: None, }; }; let pages = match resolve_toc_page_numbers(model, &block_page_numbers(&first_pages)) { @@ -110,165 +84,9 @@ pub(super) fn layout_document( .unwrap_or(first_pages), None => first_pages, }; - let snapshot = (!model.show_title).then(|| { - PageLayoutCache::snapshot(config, blocks, HashMap::new(), &pages, model.blocks.len()) - }); DocumentLayout { plan: None, pages: Some(pages), - snapshot, - } -} - -pub(super) fn plan_all_page_breaks( - nodes: &[VerticalNode], - page_goal: i64, - top_skip: i64, - max_depth: i64, -) -> PlannedBreaks { - let result = - page_builder::plan_page_breaks_with_dependencies(nodes, 0, page_goal, top_skip, max_depth); - PlannedBreaks { - anchors: result.anchors, - dependencies: page_break_dependencies(nodes, &result.decisions), - } -} - -pub(super) fn page_break_dependencies( - nodes: &[VerticalNode], - decisions: &[page_builder::PageBreakDecision], -) -> HashMap { - let mut latest_block = None; - let latest_block_by_node = nodes - .iter() - .map(|node| { - if let VerticalNode::Box { - anchor: Some(anchor), - .. - } = node - { - latest_block = - Some(latest_block.map_or(anchor.block, |old: usize| old.max(anchor.block))); - } - latest_block - }) - .collect::>(); - decisions - .iter() - .map(|decision| { - let dependency_end_block = latest_block_by_node - .get(decision.dependency_end) - .copied() - .flatten() - .unwrap_or(decision.anchor.block); - (decision.anchor, dependency_end_block) - }) - .collect() -} - -pub(super) fn positioned_item_anchor(item: &PositionedPageItem) -> PageAnchor { - match item { - PositionedPageItem::Line(line) => line.anchor, - PositionedPageItem::DisplayMath { anchor, .. } => *anchor, - PositionedPageItem::Table { anchor, .. } => *anchor, - PositionedPageItem::Image { anchor, .. } => *anchor, - PositionedPageItem::FramedBox { anchor, .. } => *anchor, - PositionedPageItem::Centered { anchor, .. } => *anchor, - } -} - -fn page_block_keys(model: &DocumentModel, source_dir: &Path) -> Option> { - model - .blocks - .iter() - .map(|block| match block { - Block::Paragraph(runs) => Some(PageBlockKey::Paragraph(normalize_page_runs(runs))), - Block::Heading { level, runs } => Some(PageBlockKey::Heading { - level: *level, - runs: normalize_page_runs(runs), - }), - Block::List(list) => { - let mut list = list.clone(); - normalize_list_runs(&mut list); - Some(PageBlockKey::List(list)) - } - Block::Table { - rows, - caption, - alignments, - rules, - .. - } => Some(PageBlockKey::Table { - rows: rows - .iter() - .map(|row| row.iter().map(|cell| normalize_page_runs(cell)).collect()) - .collect(), - caption: caption.as_deref().map(normalize_page_runs), - alignments: alignments - .iter() - .map(|alignment| match alignment { - ColumnAlignment::Left => 0, - ColumnAlignment::Center => 1, - ColumnAlignment::Right => 2, - }) - .collect(), - rules: rules.clone(), - }), - Block::Image { - path, - options, - caption, - placement, - } => { - let image_path = resolved_image_path(source_dir, path); - let bytes = fs::read(&image_path).ok()?; - let mut hasher = DefaultHasher::new(); - bytes.hash(&mut hasher); - Some(PageBlockKey::Image { - path: image_path, - options: options.clone(), - caption: caption.as_deref().map(normalize_page_runs), - placement: placement.clone(), - fingerprint: hasher.finish(), - }) - } - Block::Bibliography(items) => Some(PageBlockKey::Bibliography( - items - .iter() - .map(|(key, runs)| (key.clone(), normalize_page_runs(runs))) - .collect(), - )), - Block::FramedBox { runs, frame, width } => Some(PageBlockKey::FramedBox { - runs: normalize_page_runs(runs), - frame: *frame, - width: *width, - }), - Block::Centered { runs } => Some(PageBlockKey::Centered(normalize_page_runs(runs))), - Block::HorizontalRule { height, width } => Some(PageBlockKey::HorizontalRule { - height: *height, - width: *width, - }), - Block::Math { - expression, - equation_numbers, - } => Some(PageBlockKey::Math { - expression: expression.without_source(), - equation_numbers: equation_numbers.clone(), - }), - Block::VerticalKern(width) => Some(PageBlockKey::VerticalKern(*width)), - Block::VerticalGlue(glue) => Some(PageBlockKey::VerticalGlue(*glue)), - Block::Penalty(penalty) => Some(PageBlockKey::Penalty(*penalty)), - Block::PageBreak => Some(PageBlockKey::PageBreak), - }) - .collect() -} - -fn normalize_list_runs(list: &mut ListBlock) { - for item in &mut list.items { - item.runs = normalize_page_runs(&item.runs); - for nested in &mut item.nested { - normalize_list_runs(nested); - } } } @@ -312,6 +130,7 @@ fn millimeters_to_scaled(value: f64) -> i64 { } #[derive(Clone, Copy)] +#[allow(dead_code)] // stretch/shrink are retained for future page-level glue setting struct DisplaySkipGlue { width: i64, stretch: i64, @@ -453,6 +272,7 @@ fn latex_nested_list_itemsep(depth: usize) -> ListGlue { } } +#[allow(dead_code)] // glue fields are retained for future page-level glue setting enum ListLayoutToken { Gap { width: i64, @@ -778,16 +598,6 @@ fn layout_figure( }) } -fn normalize_page_runs(runs: &[Run]) -> Vec { - runs.iter() - .cloned() - .map(|mut run| { - run.math = run.math.map(|math| math.without_source()); - run - }) - .collect() -} - pub(super) fn cached_paragraph_lines( runs: &[Run], width_mm: f64, @@ -1043,590 +853,6 @@ fn measure_centered( MeasuredCentered { lines, height } } -pub(super) fn build_page_break_plan( - model: &DocumentModel, - source_dir: &Path, - content_width_mm: f64, - content_height_mm: f64, - metrics: &BoxFontMetrics, - font_cache: &fonts::FontCache, - cjk_family: Option>, - mono_family: Option>, - sans_family: Option>, - math_metrics: &math_font::MathFontMetrics, - math_layout: &MathLayoutEnvironment, - paragraph_cache: &mut ParagraphLayoutCache, - page_layout_cache: &PageLayoutCache, -) -> Option { - let base_font_size = model.base_font_size; - let normal_line_height = font_line_height_scaled( - font_cache, - cjk_family, - mono_family, - sans_family, - base_font_size, - ); - let top_skip = i64::from(scaled_points(ARTICLE_11PT_TOPSKIP_PT).0); - let max_depth = i64::from(scaled_points(ARTICLE_11PT_MAX_DEPTH_PT).0); - let page_goal = scaled_points(content_height_mm * PDF_POINTS_PER_INCH / 25.4).0 as i64; - let mut nodes = Vec::new(); - let mut pre_display_size = None; - if model.show_title { - for (text, size, bold) in [ - (&model.title, base_font_size + 9, true), - (&model.author, base_font_size + 1, false), - (&model.date, base_font_size, false), - ] { - if text.is_empty() { - continue; - } - let mut run = Run::plain(text.clone()); - run.bold = bold; - let _ = append_vertical_text( - &mut nodes, - &[run], - Some(usize::MAX), - size, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - paragraph_cache, - ); - nodes.push(VerticalNode::Penalty(10_000)); - } - nodes.push(VerticalNode::fixed_glue(normal_line_height)); - nodes.push(VerticalNode::Penalty(0)); - pre_display_size = None; - } - - for (block_index, block) in model.blocks.iter().enumerate() { - match block { - Block::Paragraph(runs) => { - pre_display_size = if runs.iter().any(|run| run.math.is_some()) { - append_vertical_inline_math( - &mut nodes, - runs, - block_index, - base_font_size, - content_width_mm, - font_cache, - cjk_family, - mono_family, - sans_family, - math_metrics, - math_layout, - ) - } else { - append_vertical_text( - &mut nodes, - runs, - Some(block_index), - base_font_size, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - paragraph_cache, - ) - }; - let reserve = footnote_reserve( - model, - block_index, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - math_metrics, - math_layout, - paragraph_cache, - ); - if reserve > 0 { - nodes.push(VerticalNode::Kern(reserve)); - } - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.35).round() as i64, - )); - } - Block::FramedBox { runs, frame, width } => { - pre_display_size = None; - let Some(measured) = measure_framed_box( - runs, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - paragraph_cache, - *frame, - *width, - base_font_size, - ) else { - continue; - }; - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.35).round() as i64, - )); - nodes.push(VerticalNode::Box { - height: measured.height, - depth: 0, - anchor: Some(PageAnchor { - block: block_index, - line: 0, - }), - }); - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.35).round() as i64, - )); - } - Block::Centered { runs } => { - pre_display_size = None; - let measured = measure_centered( - runs, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - paragraph_cache, - base_font_size, - ); - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.35).round() as i64, - )); - nodes.push(VerticalNode::Box { - height: measured.height, - depth: 0, - anchor: Some(PageAnchor { - block: block_index, - line: 0, - }), - }); - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.35).round() as i64, - )); - } - Block::HorizontalRule { height, .. } => { - pre_display_size = None; - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.35).round() as i64, - )); - nodes.push(VerticalNode::Box { - height: i64::from(height.0), - depth: 0, - anchor: Some(PageAnchor { - block: block_index, - line: 0, - }), - }); - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.35).round() as i64, - )); - } - Block::Heading { level, runs } => { - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.65).round() as i64, - )); - let mut runs = runs.clone(); - for run in &mut runs { - run.bold = true; - } - let size = super::article_heading_font_size(*level, base_font_size); - pre_display_size = if runs.iter().any(|run| run.math.is_some()) { - append_vertical_inline_math( - &mut nodes, - &runs, - block_index, - size, - content_width_mm, - font_cache, - cjk_family, - mono_family, - sans_family, - math_metrics, - math_layout, - ) - } else { - append_vertical_text( - &mut nodes, - &runs, - Some(block_index), - size, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - paragraph_cache, - ) - }; - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.35).round() as i64, - )); - } - Block::Math { - expression, - equation_numbers, - } => { - append_vertical_math( - &mut nodes, - expression, - equation_numbers.clone(), - block_index, - pre_display_size, - content_width_mm, - font_cache, - math_metrics, - math_layout, - ); - pre_display_size = None; - } - Block::VerticalKern(width) => { - nodes.push(VerticalNode::Kern(i64::from(width.0))); - } - Block::VerticalGlue(glue) => { - nodes.push(VerticalNode::glue( - i64::from(glue.width.0), - i64::from(glue.stretch.0), - glue.stretch_order.into(), - i64::from(glue.shrink.0), - glue.shrink_order.into(), - )); - } - Block::Penalty(penalty) => nodes.push(VerticalNode::Penalty(*penalty)), - Block::List(list) => { - let mut tokens = Vec::new(); - let mut next_line = 0; - append_list_layout_tokens( - &mut tokens, - list, - 0, - 0.0, - true, - &mut next_line, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - math_metrics, - math_layout, - paragraph_cache, - base_font_size, - )?; - let mut list_pre_display_size = None; - for token in tokens { - match token { - ListLayoutToken::Gap { - width, - stretch, - stretch_order, - shrink, - shrink_order, - outer_topsep: true, - .. - } => { - if let Some(VerticalNode::Glue { - width: previous, - stretch: previous_stretch, - shrink: previous_shrink, - .. - }) = nodes.last_mut() - { - *previous = (*previous).max(width); - *previous_stretch = (*previous_stretch).max(stretch); - *previous_shrink = (*previous_shrink).max(shrink); - } else { - nodes.push(VerticalNode::glue( - width, - stretch, - stretch_order, - shrink, - shrink_order, - )); - } - } - ListLayoutToken::Gap { - width, - stretch, - stretch_order, - shrink, - shrink_order, - outer_topsep: false, - .. - } => { - nodes.push(VerticalNode::glue( - width, - stretch, - stretch_order, - shrink, - shrink_order, - )); - nodes.push(VerticalNode::Penalty(0)); - } - ListLayoutToken::Line { line, .. } => { - list_pre_display_size = line.pre_display_size; - push_vertical_line( - &mut nodes, - Some(PageAnchor { - block: block_index, - line: line.line_index, - }), - line.height, - line.ascent, - line.leading_before, - 0, - ); - } - } - } - pre_display_size = list_pre_display_size; - } - Block::Table { - rows, - caption, - alignments, - rules, - .. - } => { - pre_display_size = None; - let mut line_index = 0; - if let Some(caption) = caption { - for mut line in measure_positioned_lines( - caption, - 10, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - math_metrics, - math_layout, - paragraph_cache, - ) { - line.line_index = line_index; - push_vertical_line( - &mut nodes, - Some(PageAnchor { - block: block_index, - line: line_index, - }), - line.height, - line.ascent, - line.leading_before, - 0, - ); - line_index += 1; - } - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.25).round() as i64, - )); - } - if let Some(table) = layout_table( - rows, - alignments, - rules, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - math_metrics, - math_layout, - paragraph_cache, - base_font_size, - ) { - for row in table.rows { - if row.height > page_goal { - return None; - } - nodes.push(VerticalNode::Box { - height: row.height, - depth: 0, - anchor: Some(PageAnchor { - block: block_index, - line: line_index, - }), - }); - nodes.push(VerticalNode::Penalty(0)); - line_index += 1; - } - } - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.5).round() as i64, - )); - } - Block::Image { - path, - options, - caption, - .. - } => { - pre_display_size = None; - let Some(figure) = layout_figure( - source_dir, - path, - options, - caption.as_deref(), - content_width_mm, - content_height_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - math_metrics, - math_layout, - paragraph_cache, - ) else { - return None; - }; - if figure.height > page_goal { - return None; - } - nodes.push(VerticalNode::Box { - height: figure.height, - depth: 0, - anchor: Some(PageAnchor { - block: block_index, - line: 0, - }), - }); - nodes.push(VerticalNode::Penalty(0)); - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.5).round() as i64, - )); - } - Block::Bibliography(items) => { - pre_display_size = None; - let top_gap = (normal_line_height as f64 * 0.5).round() as i64; - if let Some(VerticalNode::Glue { width, .. }) = nodes.last_mut() { - *width = (*width).max(top_gap); - } else { - nodes.push(VerticalNode::fixed_glue(top_gap)); - } - - let mut heading = Run::plain("References".to_string()); - heading.bold = true; - let heading_lines = measure_positioned_lines( - &[heading], - 15, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - math_metrics, - math_layout, - paragraph_cache, - ); - let mut line_index = 0; - for (index, line) in heading_lines.iter().enumerate() { - push_vertical_line( - &mut nodes, - Some(PageAnchor { - block: block_index, - line: line_index, - }), - line.height, - line.ascent, - line.leading_before, - if index + 1 == heading_lines.len() { - 10_000 - } else { - 0 - }, - ); - line_index += 1; - } - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.25).round() as i64, - )); - - for (index, (_key, runs)) in items.iter().enumerate() { - let mut numbered = vec![Run::plain(format!("[{}] ", index + 1))]; - numbered.extend(runs.clone()); - for line in measure_positioned_lines( - &numbered, - 10, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - math_metrics, - math_layout, - paragraph_cache, - ) { - push_vertical_line( - &mut nodes, - Some(PageAnchor { - block: block_index, - line: line_index, - }), - line.height, - line.ascent, - line.leading_before, - 0, - ); - line_index += 1; - } - nodes.push(VerticalNode::fixed_glue( - (normal_line_height as f64 * 0.2).round() as i64, - )); - } - } - Block::PageBreak => { - pre_display_size = None; - nodes.push(VerticalNode::Penalty(-10_000)); - } - } - } - - let config = PageLayoutConfig { - content_width_bits: content_width_mm.to_bits(), - content_height_bits: content_height_mm.to_bits(), - top_skip, - max_depth, - text_font_fingerprint: metrics.fingerprint, - math_font_fingerprint: math_metrics.fingerprint, - math_layout_font_fingerprint: math_layout.font_fingerprint, - base_font_size: model.base_font_size, - page_style_fingerprint: { - let mut hasher = DefaultHasher::new(); - model.page_style.hash(&mut hasher); - model.page_style_overrides.hash(&mut hasher); - hasher.finish() - }, - }; - let blocks = page_block_keys(model, source_dir)?; - let breaks = if model.show_title { - plan_all_page_breaks(&nodes, page_goal, top_skip, max_depth) - } else { - page_layout_cache.plan(&config, &blocks, &nodes, page_goal, top_skip, max_depth) - }; - Some(PageBreakPlan { - breaks: breaks.anchors, - dependencies: breaks.dependencies, - config, - blocks, - }) -} - #[allow(clippy::too_many_arguments)] fn footnote_marker(number: u32) -> String { number @@ -1837,25 +1063,6 @@ fn assign_baseline_leading(lines: &mut [MeasuredLine], font_size: u8) { } } -fn push_vertical_line( - nodes: &mut Vec, - anchor: Option, - height: i64, - ascent: i64, - leading_before: i64, - penalty: i32, -) { - if leading_before > 0 { - nodes.push(VerticalNode::fixed_glue(leading_before)); - } - nodes.push(VerticalNode::Box { - height: ascent, - depth: height.saturating_sub(ascent), - anchor, - }); - nodes.push(VerticalNode::Penalty(penalty)); -} - #[allow(clippy::too_many_arguments)] fn append_page_footnotes( model: &DocumentModel, @@ -3141,179 +2348,6 @@ fn append_decoration( } } -#[allow(clippy::too_many_arguments)] -fn append_vertical_text( - nodes: &mut Vec, - runs: &[Run], - block_index: Option, - font_size: u8, - content_width_mm: f64, - metrics: &BoxFontMetrics, - font_cache: &fonts::FontCache, - cjk_family: Option>, - mono_family: Option>, - sans_family: Option>, - cache: &mut ParagraphLayoutCache, -) -> Option { - let lines = cached_paragraph_lines(runs, content_width_mm, metrics, font_size, cache); - let baseline_skip = baseline_skip_scaled(font_size); - let mut previous_depth = None; - let mut pre_display_size = None; - for (line_index, line) in lines.iter().enumerate() { - if line.items.is_empty() { - continue; - } - pre_display_size = line.pre_display_size.map(|size| i64::from(size.0)); - let (ascent, descent) = text_line_metrics_scaled( - font_cache, - line, - cjk_family, - mono_family, - sans_family, - font_size, - ); - let leading_before = - previous_depth.map_or(0, |depth| baseline_leading(depth, ascent, baseline_skip)); - push_vertical_line( - nodes, - block_index.map(|block| PageAnchor { - block, - line: line_index, - }), - ascent.saturating_add(descent), - ascent, - leading_before, - 0, - ); - previous_depth = Some(descent); - } - pre_display_size -} - -#[allow(clippy::too_many_arguments)] -fn append_vertical_inline_math( - nodes: &mut Vec, - runs: &[Run], - block_index: usize, - font_size: u8, - content_width_mm: f64, - font_cache: &fonts::FontCache, - cjk_family: Option>, - mono_family: Option>, - _sans_family: Option>, - metrics: &math_font::MathFontMetrics, - layout: &MathLayoutEnvironment, -) -> Option { - let paragraph = - inline_math_paragraph(runs, font_size, cjk_family, mono_family, metrics, layout); - let style = Style::new() - .with_font_size(font_size) - .with_line_spacing(1.22); - let baseline_skip = baseline_skip_scaled(font_size); - let mut previous_depth = None; - let mut pre_display_size = None; - for (line_index, (height_mm, element)) in paragraph - .positioned_lines(font_cache, Mm::from(content_width_mm), style) - .into_iter() - .enumerate() - { - pre_display_size = element - .pre_display_size() - .map(|size| millimeters_to_scaled(f64::from(size))); - let height = i64::from(scaled_points(f64::from(height_mm) * PDF_POINTS_PER_INCH / 25.4).0) - .saturating_add(1); - let ascent = millimeters_to_scaled(f64::from(element.baseline())).min(height); - let depth = height.saturating_sub(ascent); - let leading_before = - previous_depth.map_or(0, |depth| baseline_leading(depth, ascent, baseline_skip)); - push_vertical_line( - nodes, - Some(PageAnchor { - block: block_index, - line: line_index, - }), - height, - ascent, - leading_before, - 0, - ); - previous_depth = Some(depth); - } - pre_display_size -} - -fn append_vertical_math( - nodes: &mut Vec, - expression: &super::MathExpr, - equation_numbers: Vec>, - block_index: usize, - pre_display_size: Option, - content_width_mm: f64, - font_cache: &fonts::FontCache, - metrics: &math_font::MathFontMetrics, - layout: &MathLayoutEnvironment, -) { - let mut display = math_layout::MathDisplay::new( - expression.clone(), - metrics, - Rc::clone(&layout.cache), - layout.font_fingerprint, - ); - display = display.with_equation_numbers(equation_numbers); - display = display.with_display_width(Mm::from(content_width_mm)); - let height_mm = display.measure_height(font_cache, display_math_style()); - let (above, below) = display_skip_glues( - pre_display_size, - millimeters_to_scaled(f64::from(display.measure_width())), - millimeters_to_scaled(content_width_mm), - ); - if let Some(VerticalNode::Glue { - width, - stretch: previous_stretch, - stretch_order, - shrink: previous_shrink, - shrink_order, - }) = nodes.last_mut() - { - *width = above.width; - *previous_stretch = above.stretch; - *stretch_order = GlueOrder::Normal; - *previous_shrink = above.shrink; - *shrink_order = GlueOrder::Normal; - } else { - nodes.push(VerticalNode::glue( - above.width, - above.stretch, - GlueOrder::Normal, - above.shrink, - GlueOrder::Normal, - )); - } - let height = i64::from(scaled_points(f64::from(height_mm) * PDF_POINTS_PER_INCH / 25.4).0) - .saturating_add(1); - let ascent = display - .first_baseline() - .map(|baseline| millimeters_to_scaled(f64::from(baseline))) - .unwrap_or(0) - .min(height); - nodes.push(VerticalNode::Box { - height: ascent, - depth: height.saturating_sub(ascent), - anchor: Some(PageAnchor { - block: block_index, - line: 0, - }), - }); - nodes.push(VerticalNode::Penalty(0)); - nodes.push(VerticalNode::glue( - below.width, - below.stretch, - GlueOrder::Normal, - below.shrink, - GlueOrder::Normal, - )); -} - fn display_math_style() -> Style { Style::new().italic().with_font_size(12) } diff --git a/src/rust_typeset/pdf/preview.rs b/src/rust_typeset/pdf/preview.rs index 9f8698f..55b97f6 100644 --- a/src/rust_typeset/pdf/preview.rs +++ b/src/rust_typeset/pdf/preview.rs @@ -22,7 +22,6 @@ pub(in crate::rust_typeset) fn render_pages( content_width_mm: f64, content_height_mm: f64, paragraph_layout_cache: &mut ParagraphLayoutCache, - page_layout_cache: &mut PageLayoutCache, ) -> Result>, String> { let timing_start = std::time::Instant::now(); let page_layout = layout_document( @@ -38,14 +37,10 @@ pub(in crate::rust_typeset) fn render_pages( &resources.math_metrics, &resources.math_layout, paragraph_layout_cache, - page_layout_cache, ); let Some(mut pages) = page_layout.pages else { return Ok(None); }; - if let Some(snapshot) = page_layout.snapshot { - page_layout_cache.snapshot = Some(snapshot); - } super::super::log_timing("preview.layout", timing_start); let content_width = Mm::from(content_width_mm); let mut rendered = Vec::with_capacity(pages.len());