From ed1da06685b6a2af883069324dcb765523ceb4ee Mon Sep 17 00:00:00 2001 From: GloamXun Date: Mon, 19 Oct 2026 13:41:29 +0800 Subject: [PATCH] Add float placement and page headers/footers --- Cargo.lock | 1 + Cargo.toml | 1 + README.md | 16 +- crates/texrra-core/src/document.rs | 77 ++++++ crates/texrra-core/src/document_parser.rs | 157 +++++++++++- crates/texrra-core/src/expanded.rs | 11 + docs/ROADMAP.md | 44 ++-- docs/STATUS.md | 24 +- src/rust_typeset.rs | 4 +- src/rust_typeset/document.rs | 3 +- src/rust_typeset/frontend.rs | 18 +- src/rust_typeset/pdf.rs | 63 +++-- src/rust_typeset/pdf/layout.rs | 296 ++++++++++++++++++++-- src/rust_typeset/texlang_adapter.rs | 160 ++++++++++++ src/rust_typeset/text_layout.rs | 22 ++ tests/typeset.rs | 167 ++++++++++++ 16 files changed, 974 insertions(+), 90 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 615241d..fba6e1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -950,6 +950,7 @@ dependencies = [ "genpdf", "hyphenate", "image", + "printpdf", "rmp-serde", "rusttype", "serde", diff --git a/Cargo.toml b/Cargo.toml index 0d42be8..41b9422 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ texrra-core = { path = "crates/texrra-core", features = ["serde"] } flate2 = "1.1" hyphenate = { path = "vendor/hyphenate" } genpdf = { version = "0.2.0", features = ["images"] } +printpdf = "0.3.4" image = { version = "0.23.12", default-features = false, features = ["png", "jpeg", "bmp"] } common = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0", features = ["serde"] } boxworks = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" } diff --git a/README.md b/README.md index c6066b7..9b01fc8 100644 --- a/README.md +++ b/README.md @@ -165,13 +165,21 @@ options/`\geometry{...}` settings, including `paperwidth`, `paperheight`, `textheight` sizes it below the current top margin. The chosen page size drives the PDF pages, the positioned layout, and the SVG preview. +Page styles are painted in both the PDF and the SVG preview: +`\pagestyle{empty|plain|fancy}` sets the document default, +`\thispagestyle{...}` overrides one page, and fancyhdr's `\fancyhead`/ +`\fancyfoot` plus `\lhead`/`\chead`/`\rhead`/`\lfoot`/`\cfoot`/`\rfoot` +place runs in the left, center, or right slot. `\thepage` is resolved when the +page is painted, so the footer shows the real page number. The default style is +`plain` (a centered page number). + The following packages are accepted as built-ins: `geometry`, `graphicx`, `amsmath`, `amssymb`, `amsfonts`, `booktabs`, `hyperref`, `cite`, `natbib`, `inputenc`, `fontenc`, `url`, `nicefrac`, `microtype`, `cleveref`, `lipsum`, `doi`, `authblk`, and `fancyhdr`. Their commands are approximated where they affect text (`\url` becomes breakable monospace, `\nicefrac`, `\cref`, -`\doi`, `\lipsum`, `\verb`), and are no-ops where they only affect the PDF -back end (`\hypersetup`, `\fancyhf`, `\microtypesetup`). +`\doi`, `\lipsum`, `\verb`); `\hypersetup` and `\microtypesetup` remain +PDF-backend no-ops, while fancyhdr's page decorations are painted natively. Figure and table captions are numbered (`Figure 1: ...`, `Table 1: ...`), and `\ref` to a figure/table label resolves to that number. Display math that is @@ -464,8 +472,8 @@ advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`, | Boxes | `\rule`, inline framed `\fbox`, block `\parbox`/`\minipage`, `\vbox`/`\vtop` (as full-width block), inline `\mbox`/`\makebox`, `\raisebox`, `center`, `\hrule` | true nested VBox material | | Fonts | serif/sans/mono faces, bold/italic/mono/sans declarations, group scoping, true scaled small caps | — | | 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 floats | -| Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak` | headers/footers (`fancyhdr`), unified planner/renderer | +| Notes/floats | footnotes with page-bottom insertion area, title/author `\thanks`, figure/table `[htbp]` placement (top/bottom/page/here approximations) | deferred float queue, `\textfraction` | +| 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 | | Classes/packages | built-in + local classes, option protocol, local package options | base font-size options (10/11/12pt) | | Live preview | incremental paragraph/page caches, page-hash diffing, SVG refresh | — | diff --git a/crates/texrra-core/src/document.rs b/crates/texrra-core/src/document.rs index d0c3057..11e5868 100644 --- a/crates/texrra-core/src/document.rs +++ b/crates/texrra-core/src/document.rs @@ -75,6 +75,8 @@ pub struct DocumentModel { pub labels: HashMap, pub citations: HashMap, pub footnotes: Vec, + pub page_style: PageStyle, + pub page_style_overrides: Vec, } impl Default for DocumentModel { @@ -93,10 +95,81 @@ impl Default for DocumentModel { labels: HashMap::new(), citations: HashMap::new(), footnotes: Vec::new(), + page_style: PageStyle::default(), + page_style_overrides: Vec::new(), } } } +/// Page style selected by `\pagestyle`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum PageStyleKind { + Empty, + /// LaTeX's default: a centered page number in the footer. + #[default] + Plain, + /// fancyhdr-style header/footer declared with `\fancyhead`/`\fancyfoot`. + Fancy, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum PageDecorationPosition { + #[default] + Center, + Left, + Right, +} + +/// Header or footer runs for one edge of the page. +#[derive(Clone, Default, PartialEq, Eq, Hash)] +pub struct PageDecoration { + pub left: Vec, + pub center: Vec, + pub right: Vec, +} + +impl PageDecoration { + pub fn slot_mut(&mut self, position: PageDecorationPosition) -> &mut Vec { + match position { + PageDecorationPosition::Left => &mut self.left, + PageDecorationPosition::Center => &mut self.center, + PageDecorationPosition::Right => &mut self.right, + } + } + + pub fn is_empty(&self) -> bool { + self.left.is_empty() && self.center.is_empty() && self.right.is_empty() + } + + pub fn clear(&mut self) { + self.left.clear(); + self.center.clear(); + self.right.clear(); + } +} + +#[derive(Clone, Default, PartialEq, Eq, Hash)] +pub struct PageStyle { + pub kind: PageStyleKind, + pub header: PageDecoration, + pub footer: PageDecoration, +} + +/// A `\thispagestyle` override, anchored at the block it was issued before. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct PageStyleOverride { + pub anchor: usize, + pub kind: PageStyleKind, +} + +/// Marker character used by `\thepage` inside header/footer runs; the page +/// renderer substitutes the concrete page number before measuring and painting. +pub const PAGE_NUMBER_MARKER: char = '\u{F5000}'; + +pub fn page_number_marker_text() -> String { + PAGE_NUMBER_MARKER.to_string() +} + pub struct ParsedDocument(pub DocumentModel); #[derive(Clone)] @@ -137,11 +210,15 @@ pub enum Block { caption: Option>, alignments: Vec, rules: Vec, + /// Float placement hints from `[htbp]`. + placement: String, }, Image { path: String, options: String, caption: Option>, + /// Float placement hints from `[htbp]`. + placement: String, }, Bibliography(Vec<(String, Vec)>), /// A box such as `\fbox{...}` (framed) or `\parbox{width}{...}`. diff --git a/crates/texrra-core/src/document_parser.rs b/crates/texrra-core/src/document_parser.rs index ccced69..e715ab0 100644 --- a/crates/texrra-core/src/document_parser.rs +++ b/crates/texrra-core/src/document_parser.rs @@ -4,8 +4,8 @@ use crate::{ TeXGlue, document::{ Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign, - ListBlock, ListItem, PageMargins, PageSize, ParsedDocument, RuleBox, Run, - UnresolvedReference, + ListBlock, ListItem, PageMargins, PageSize, PageStyleOverride, ParsedDocument, RuleBox, + Run, UnresolvedReference, }, expanded, math_expr::*, @@ -300,7 +300,7 @@ fn consume_environment_preamble( expanded: &expanded::ExpandedTokenStream, start_index: usize, environment: &str, -) -> usize { +) -> (usize, Option) { use expanded::{ExpandedItemKind, ExpandedTokenValue, FrontendEventKind as Event}; let mut argument_start = start_index; @@ -320,7 +320,7 @@ fn consume_environment_preamble( let Some(ExpandedItemKind::Event(Event::GroupStart)) = expanded.items.get(argument_start).map(|item| &item.kind) else { - return start_index; + return (start_index, None); }; let mut depth = 0usize; for (index, item) in expanded.items.iter().enumerate().skip(argument_start) { @@ -329,13 +329,13 @@ fn consume_environment_preamble( ExpandedItemKind::Event(Event::GroupEnd) => { depth -= 1; if depth == 0 { - return index + 1; + return (index + 1, None); } } _ => {} } } - return start_index; + return (start_index, None); } if !matches!(environment, "figure" | "table") @@ -348,11 +348,12 @@ fn consume_environment_preamble( }) != Some('[') { - return start_index; + return (start_index, None); } let mut bracket_depth = 0usize; let mut group_depth = 0usize; + let mut placement = String::new(); for (index, item) in expanded.items.iter().enumerate().skip(argument_start) { match &item.kind { ExpandedItemKind::Event(Event::GroupStart) => group_depth += 1, @@ -364,15 +365,16 @@ fn consume_environment_preamble( Some(']') => { bracket_depth = bracket_depth.saturating_sub(1); if bracket_depth == 0 { - return index + 1; + return (index + 1, Some(placement)); } } + Some(character) if bracket_depth == 1 => placement.push(character), _ => {} }, _ => {} } } - start_index + (start_index, None) } struct MinipageBuilder { @@ -422,6 +424,19 @@ struct Parser { minipage: Option, footnote_capture: Option>, footnote_counter: u32, + page_decoration_capture: Option<( + bool, + crate::document::PageDecorationPosition, + Vec, + usize, + bool, + bool, + bool, + bool, + bool, + )>, + float_placement: String, + table_placement: String, centered: Option>, current_source: Option, paragraph_source: Option, @@ -465,6 +480,9 @@ impl Parser { minipage: None, footnote_capture: None, footnote_counter: 0, + page_decoration_capture: None, + float_placement: String::new(), + table_placement: String::new(), centered: None, current_source: None, paragraph_source: None, @@ -553,8 +571,16 @@ impl Parser { name: environment, .. } = kind { - item_index = + let (next_index, placement) = consume_environment_preamble(expanded, item_index, environment); + item_index = next_index; + if let Some(placement) = placement { + match environment.as_str() { + "figure" => self.float_placement = placement, + "table" => self.table_placement = placement, + _ => {} + } + } } if paragraph_break { @@ -835,6 +861,83 @@ impl Parser { self.begin_style(*style); self.style_declarations.push((self.group_depth, *style)); } + expanded::FrontendEventKind::PageStyle(kind) => { + self.document.page_style.kind = *kind; + } + expanded::FrontendEventKind::ThisPageStyle(kind) => { + self.document.page_style_overrides.push(PageStyleOverride { + anchor: self.document.blocks.len(), + kind: *kind, + }); + } + expanded::FrontendEventKind::PageDecorationStart { header, position } => { + self.page_decoration_capture = Some(( + *header, + *position, + Vec::new(), + self.group_depth, + self.bold, + self.italic, + self.monospace, + self.sans, + self.small_caps, + )); + self.group_depth += 1; + } + expanded::FrontendEventKind::PageDecorationEnd => { + if let Some(( + header, + position, + mut runs, + depth, + bold, + italic, + monospace, + sans, + small_caps, + )) = self.page_decoration_capture.take() + { + while self + .style_declarations + .last() + .is_some_and(|(declaration_depth, _)| *declaration_depth > depth) + { + if let Some((_, style)) = self.style_declarations.pop() { + self.end_style(style); + } + } + self.group_depth = depth; + self.bold = bold; + self.italic = italic; + self.monospace = monospace; + self.sans = sans; + self.small_caps = small_caps; + trim_run_end(&mut runs); + let decoration = if header { + &mut self.document.page_style.header + } else { + &mut self.document.page_style.footer + }; + *decoration.slot_mut(position) = runs; + } + } + expanded::FrontendEventKind::PageDecorationClear { header } => { + let decoration = if *header { + &mut self.document.page_style.header + } else { + &mut self.document.page_style.footer + }; + decoration.clear(); + } + expanded::FrontendEventKind::PageNumber => { + let mut run = Run::plain(crate::document::page_number_marker_text()); + run.bold = self.bold; + run.italic = self.italic; + run.monospace = self.monospace; + run.sans = self.sans; + run.small_caps = self.small_caps; + self.target_runs().push(run); + } expanded::FrontendEventKind::GroupStart => self.group_depth += 1, expanded::FrontendEventKind::GroupEnd => { let depth = self.group_depth; @@ -1342,6 +1445,13 @@ impl Parser { } fn target_runs(&mut self) -> &mut Vec { + if self.page_decoration_capture.is_some() { + return &mut self + .page_decoration_capture + .as_mut() + .expect("page decoration capture was checked") + .2; + } if self.footnote_capture.is_some() { return self .footnote_capture @@ -1357,6 +1467,7 @@ impl Parser { && self.centered.is_none() && self.framed_box.is_none() && self.metadata_capture.is_none() + && self.page_decoration_capture.is_none() && self.caption_capture.is_none() && self.heading.is_none() && self.table.is_none() @@ -1546,6 +1657,7 @@ impl Parser { (false, "tabular") => self.finish_table(), (true, "figure") => { self.flush_paragraph(); + self.float_placement = String::new(); self.figure_active = true; self.figure_image = None; self.figure_number += 1; @@ -1553,11 +1665,18 @@ impl Parser { } (false, "figure") => { self.flush_paragraph(); + if self.figure_active + && !self.float_placement.is_empty() + && self.float_placement.contains('p') + { + self.push_block(Block::PageBreak); + } self.figure_active = false; self.figure_image = None; } (true, "table") => { self.flush_paragraph(); + self.table_placement = String::new(); self.table_active = true; self.current_table_block = None; self.pending_table_caption = None; @@ -1620,11 +1739,19 @@ impl Parser { self.figure_number += 1; } self.current_reference = self.figure_number.to_string(); + if self.figure_active + && !self.float_placement.is_empty() + && !self.float_placement.contains('h') + && (self.float_placement.contains('t') || self.float_placement.contains('p')) + { + self.push_block(Block::PageBreak); + } let index = self.document.blocks.len(); self.push_block(Block::Image { path, options, caption: None, + placement: self.float_placement.clone(), }); if self.figure_active { self.figure_image = Some(index); @@ -1695,6 +1822,12 @@ impl Parser { if let Some(table) = self.table.take() && !table.rows.is_empty() { + if !self.table_placement.is_empty() + && !self.table_placement.contains('h') + && (self.table_placement.contains('t') || self.table_placement.contains('p')) + { + self.push_block(Block::PageBreak); + } let index = self.document.blocks.len(); let caption = table.caption.or_else(|| self.pending_table_caption.take()); self.push_block(Block::Table { @@ -1702,10 +1835,14 @@ impl Parser { caption, alignments: table.alignments, rules: table.rules, + placement: self.table_placement.clone(), }); if self.table_active { self.current_table_block = Some(index); } + if !self.table_placement.is_empty() && self.table_placement.contains('p') { + self.push_block(Block::PageBreak); + } } } diff --git a/crates/texrra-core/src/expanded.rs b/crates/texrra-core/src/expanded.rs index 30f5e48..23d8fcb 100644 --- a/crates/texrra-core/src/expanded.rs +++ b/crates/texrra-core/src/expanded.rs @@ -234,6 +234,17 @@ pub enum FrontendEventKind { Reference(String), Citation(String), BibliographyItem(String), + PageStyle(crate::document::PageStyleKind), + ThisPageStyle(crate::document::PageStyleKind), + PageDecorationStart { + header: bool, + position: crate::document::PageDecorationPosition, + }, + PageDecorationEnd, + PageDecorationClear { + header: bool, + }, + PageNumber, GroupStart, GroupEnd, } diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index b14f567..99e88cd 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -5,26 +5,34 @@ are still missing. Each item names the files/functions to touch. Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil`; sans family and true scaled small caps; inline box geometry (`\fbox`, `\makebox`, -`\raisebox`), `\minipage`, `\vbox`/`\vtop` block approximations, and -footnotes/`\thanks` (see `docs/STATUS.md`). +`\raisebox`), `\minipage`, `\vbox`/`\vtop` block approximations; +footnotes/`\thanks`; figure/table `[htbp]` placement approximations; and page +styles (plain/fancy, `\thispagestyle`, fancyhdr headers/footers, `\thepage`). -## 1. Floats - -- Classify figure/table blocks as floats with `[htbp]` placement hints. -- Planner: maintain pending floats and try top/bottom/page placements; keep - reading order for text and defer floats when they do not fit. -- Renderer: place deferred floats at the saved slots; page keys must include - float placement decisions. - -## 2. Page styles / headers-footers - -- `DocumentModel` fields for header/footer runs and `\pagestyle`/`\thispagestyle`. -- Paint headers/footers in the page margins in both PDF and SVG; page numbers - need a page index placeholder resolved at paint time. - -## 3. Unified pagination +## 1. Unified pagination - 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. + final painting. This is the prerequisite for a true deferred float queue. + +## 2. Lengths and base font size + +- Emit geometry changes into named length registers so `\textwidth`, + `\textheight`, `\linewidth`, and `\columnwidth` track `\geometry` and + paper-size options instead of fixed A4 defaults. +- Thread the `10pt`/`11pt`/`12pt` class option through the parser, line metrics, + headings, and the PDF so the base size changes consistently. + +## 3. Table of contents and lists + +- Record section/figure/table entries while parsing, then generate + `\tableofcontents`, `\listoffigures`, and `\listoftables` blocks with + resolved page numbers after pagination. + +## 4. PDF painting and title blocks + +- Paint rules and frames as native PDF rectangles (`printpdf` operators) + instead of 1x1 image XObjects. +- 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 ca16a46..e7af585 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -23,7 +23,12 @@ the source changes; the SVG preview is refreshed per page. centering, first-line `\parindent` (17pt default, group-scoped, `\setlength`/ `\addtolength`/`\noindent` aware), and `\hfill`/`\hfil` infinite glue. - Pages: A4/A5/B5/Letter/Legal/Executive, landscape, geometry margins and - text block, automatic pagination, `\newpage`/`\pagebreak`. + text block, automatic pagination, `\newpage`/`\pagebreak`; figures/tables + honor `[htbp]` hints with top/bottom/page/here approximations. Page styles: + default `plain` page numbers, `\pagestyle{empty|plain|fancy}`, + `\thispagestyle`, fancyhdr `\fancyhead`/`\fancyfoot` (L/C/R) and + `\lhead`/`\chead`/`\rhead`/`\lfoot`/`\cfoot`/`\rfoot`, with `\thepage` + resolved at paint time. - Notes: `\footnote{...}` page-bottom insertion area with separator rule, superscript markers, and title/author `\thanks`. - Classes/packages: built-in classes, local `.cls`/`.sty`, paper options, @@ -42,8 +47,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: no floats, no headers/footers (fancyhdr commands are accepted as - no-ops), planner and renderer are separate. +- 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. - 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. @@ -51,14 +57,16 @@ See `docs/ROADMAP.md` for concrete implementation plans. A4-content defaults, not geometry-aware. - Miscellaneous: `\tableofcontents`/list commands are no-ops; base font-size class options (10/11/12pt) are parsed but unused; rules are painted with 1x1 - images in PDF. + images in PDF; a document-level `\renewcommand{\maketitle}` is ignored in + favor of the engine title block. ## Verification - `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to one A4 page each; the arXiv template project compiles to 3 Letter pages. -- `cargo fmt --check` passes; `cargo test --workspace` (23 tests) covers the three - examples, the arXiv fixture, SVG/PDF output, project API, static frontend - assets, path traversal, the legacy `/texrra` endpoint, and page-hash cache - stability. +- `cargo fmt --check` passes; `cargo test --offline` (26 tests: 22 compiler + integration tests + 4 server tests) covers the three examples, the arXiv + fixture, floats/newpage, page styles and `\thispagestyle`, SVG/PDF output, + project API, static frontend assets, path traversal, the legacy + `/texrra` endpoint, and page-hash cache stability. - Warm preview: hello ~0.6ms, arXiv ~13ms (release server, page layout cached). diff --git a/src/rust_typeset.rs b/src/rust_typeset.rs index dbec076..e937747 100644 --- a/src/rust_typeset.rs +++ b/src/rust_typeset.rs @@ -33,7 +33,7 @@ use document::{ MathDelimiterSettings, MathExpr, MathFontFamilies, MathFontSelection, MathFontStyle, MathFractionDelimiters, MathFractionStyle, MathInfixFractionKind, MathLimitMode, MathLineBreakPenalties, MathMuGlue, MathPhantomKind, MathRowSpacing, MathSpacingSettings, - RuleBox, Run, + PAGE_NUMBER_MARKER, PageDecoration, PageDecorationPosition, PageStyleKind, RuleBox, Run, }; use parser::parse_dimension; @@ -444,6 +444,7 @@ fn render_html_document( caption, alignments, rules, + .. } => { html.push_str(&format!( "" @@ -482,6 +483,7 @@ fn render_html_document( path, options, caption, + .. } => { let image_path = PathBuf::from(&path); let image_path = if image_path.is_absolute() { diff --git a/src/rust_typeset/document.rs b/src/rust_typeset/document.rs index 0a8342d..816d5ec 100644 --- a/src/rust_typeset/document.rs +++ b/src/rust_typeset/document.rs @@ -1,4 +1,5 @@ pub(super) use texrra_core::document::{ - Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, RuleBox, Run, + Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, PAGE_NUMBER_MARKER, + PageDecoration, PageDecorationPosition, PageStyleKind, RuleBox, Run, }; pub(super) use texrra_core::math_expr::*; diff --git a/src/rust_typeset/frontend.rs b/src/rust_typeset/frontend.rs index 37fb83d..9af4f06 100644 --- a/src/rust_typeset/frontend.rs +++ b/src/rust_typeset/frontend.rs @@ -350,21 +350,15 @@ const PRELUDE: &str = r#" \def~{ } \def\AtBeginDocument#1{#1} \def\newgeometry#1{\texrrageometry{#1}} -\def\fancyhf{} \def\fancyheadoffset#1{} -\def\fancyhead#1{} -\def\fancyfoot#1{} -\def\lhead#1{} -\def\chead#1{} -\def\rhead#1{} -\def\lfoot#1{} -\def\cfoot#1{} -\def\rfoot#1{} +\def\lhead#1{\fancyhead[L]{#1}} +\def\chead#1{\fancyhead[C]{#1}} +\def\rhead#1{\fancyhead[R]{#1}} +\def\lfoot#1{\fancyfoot[L]{#1}} +\def\cfoot#1{\fancyfoot[C]{#1}} +\def\rfoot#1{\fancyfoot[R]{#1}} \def\headrulewidth{0.4pt} \def\footrulewidth{0pt} -\def\pagestyle#1{} -\def\thispagestyle#1{} -\def\thepage{1} \def\hypersetup#1{} \def\microtypesetup#1{} \def\urlstyle#1{} diff --git a/src/rust_typeset/pdf.rs b/src/rust_typeset/pdf.rs index 30b8806..8471187 100644 --- a/src/rust_typeset/pdf.rs +++ b/src/rust_typeset/pdf.rs @@ -22,7 +22,8 @@ use super::engine::glue::TeXGlue; use super::page_builder::{self, GlueOrder, PageAnchor, VerticalNode}; use super::{ Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, MathExpr, - MathLayoutEnvironment, PDF_POINTS_PER_INCH, RuleBox, Run, + 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, }; @@ -76,6 +77,7 @@ enum PageBlockKey { path: PathBuf, options: String, caption: Option>, + placement: String, fingerprint: u64, }, Bibliography(Vec<(String, Vec)>), @@ -108,6 +110,7 @@ struct PageLayoutConfig { text_font_fingerprint: u64, math_font_fingerprint: u64, math_layout_font_fingerprint: u64, + page_style_fingerprint: u64, } struct PageLayoutSnapshot { @@ -490,6 +493,8 @@ impl PositionedCentered { struct PositionedPages { pages: Vec, + content_margins: Margins, + left_margin_mm: f64, next_page: usize, cjk_family: Option>, mono_family: Option>, @@ -499,12 +504,16 @@ struct PositionedPages { impl PositionedPages { fn new( pages: Vec, + content_margins: Margins, + left_margin_mm: f64, cjk_family: Option>, mono_family: Option>, sans_family: Option>, ) -> Self { Self { pages, + content_margins, + left_margin_mm, next_page: 0, cjk_family, mono_family, @@ -526,6 +535,9 @@ impl Element for PositionedPages { let page_index = self.next_page; self.next_page += 1; let page = &mut self.pages[page_index]; + let mut body_area = area.clone(); + body_area.add_margins(self.content_margins); + let body_height = f64::from(body_area.size().height); let mut used_height = 0.0_f64; for item in &mut page.items { @@ -540,8 +552,20 @@ impl Element for PositionedPages { let (result, y) = match item { PositionedPageItem::Line(planned_line) => { let y = scaled_units_to_mm(planned_line.y); - let mut line_area = area.clone(); - line_area.add_offset(Position::new(scaled_units_to_mm(planned_line.x), y)); + let is_decoration = planned_line.anchor.block == usize::MAX; + let line_area = if is_decoration { + let mut decoration_area = area.clone(); + decoration_area.add_offset(Position::new( + self.left_margin_mm + scaled_units_to_mm(planned_line.x), + y, + )); + decoration_area + } else { + let mut content_area = body_area.clone(); + content_area + .add_offset(Position::new(scaled_units_to_mm(planned_line.x), y)); + content_area + }; let result = match &mut planned_line.content { PositionedLineContent::Text { line, font_size } => { let text_line = text_layout::TextLine::new( @@ -568,13 +592,13 @@ impl Element for PositionedPages { element, style, y, .. } => { let y = scaled_units_to_mm(*y); - let mut math_area = area.clone(); + let mut math_area = body_area.clone(); math_area.add_offset(Position::new(0.0, y)); (element.render(context, math_area, *style)?, y) } PositionedPageItem::Table { element, y, .. } => { let y = scaled_units_to_mm(*y); - let mut table_area = area.clone(); + let mut table_area = body_area.clone(); table_area.add_offset(Position::new(0.0, y)); ( element.render( @@ -590,7 +614,7 @@ impl Element for PositionedPages { } PositionedPageItem::Image { element, y, .. } => { let y = scaled_units_to_mm(*y); - let mut image_area = area.clone(); + let mut image_area = body_area.clone(); image_area.add_offset(Position::new(0.0, y)); ( element.render( @@ -606,7 +630,7 @@ impl Element for PositionedPages { } PositionedPageItem::FramedBox { element, y, .. } => { let y = scaled_units_to_mm(*y); - let mut box_area = area.clone(); + let mut box_area = body_area.clone(); box_area.add_offset(Position::new(0.0, y)); ( element.render( @@ -622,7 +646,7 @@ impl Element for PositionedPages { } PositionedPageItem::Centered { element, y, .. } => { let y = scaled_units_to_mm(*y); - let mut centered_area = area.clone(); + let mut centered_area = body_area.clone(); centered_area.add_offset(Position::new(0.0, y)); ( element.render( @@ -642,7 +666,12 @@ impl Element for PositionedPages { format!( "Rust page layout placed a {kind} outside its page frame (page {}, y {y:.2}mm, area {:.2}mm)", page_index + 1, - f64::from(area.size().height), + if matches!(item, PositionedPageItem::Line(line) if line.anchor.block == usize::MAX) + { + f64::from(area.size().height) + } else { + body_height + }, ), genpdf::error::ErrorKind::PageSizeExceeded, )); @@ -2066,12 +2095,7 @@ impl RenderResources { model.page.height_mm as f32, )); let mut decorator = genpdf::SimplePageDecorator::new(); - decorator.set_margins(Margins::trbl( - model.margins.top, - model.margins.right, - model.margins.bottom, - model.margins.left, - )); + decorator.set_margins(Margins::trbl(0.0, 0.0, 0.0, 0.0)); document.set_page_decorator(decorator); let mono_family = inputs @@ -2249,6 +2273,13 @@ pub(super) fn render_pdf( } = resources; document.push(PositionedPages::new( pages, + Margins::trbl( + model.margins.top, + model.margins.right, + model.margins.bottom, + model.margins.left, + ), + model.margins.left, cjk_family, mono_family, sans_family, @@ -2474,6 +2505,7 @@ pub(super) fn render_pdf( caption, alignments, rules, + .. } => { if let Some(caption) = caption { document.push( @@ -2505,6 +2537,7 @@ pub(super) fn render_pdf( path, options, caption, + .. } => { let image_path = PathBuf::from(&path); let image_path = if image_path.is_absolute() { diff --git a/src/rust_typeset/pdf/layout.rs b/src/rust_typeset/pdf/layout.rs index 5439bc3..386342e 100644 --- a/src/rust_typeset/pdf/layout.rs +++ b/src/rust_typeset/pdf/layout.rs @@ -176,6 +176,7 @@ fn page_block_keys(model: &DocumentModel, source_dir: &Path) -> Option Some(PageBlockKey::Table { rows: rows .iter() @@ -196,6 +197,7 @@ fn page_block_keys(model: &DocumentModel, source_dir: &Path) -> Option { let image_path = resolved_image_path(source_dir, path); let bytes = fs::read(&image_path).ok()?; @@ -205,6 +207,7 @@ fn page_block_keys(model: &DocumentModel, source_dir: &Path) -> Option { pre_display_size = None; let mut line_index = 0; @@ -1408,6 +1412,7 @@ pub(super) fn build_page_break_plan( path, options, caption, + .. } => { pre_display_size = None; let Some(figure) = layout_figure( @@ -1540,6 +1545,12 @@ pub(super) fn build_page_break_plan( text_font_fingerprint: metrics.fingerprint, math_font_fingerprint: math_metrics.fingerprint, math_layout_font_fingerprint: math_layout.font_fingerprint, + 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 { @@ -1934,6 +1945,7 @@ pub(super) fn build_positioned_pages( let page_goal = scaled_points(content_height_mm * PDF_POINTS_PER_INCH / 25.4).0 as i64; let mut pages = vec![PositionedPage::default()]; let mut block_end_pages: HashMap = HashMap::new(); + let mut block_start_pages: HashMap = HashMap::new(); let mut cursor = 0_i64; let mut has_previous_block = false; let mut pending_gap = 0_i64; @@ -1998,6 +2010,9 @@ pub(super) fn build_positioned_pages( } for (block_index, block) in model.blocks.iter().enumerate() { + block_start_pages + .entry(block_index) + .or_insert_with(|| pages.len().saturating_sub(1)); match block { Block::Paragraph(runs) | Block::Heading { runs, .. } => { let (font_size, is_heading) = match block { @@ -2420,6 +2435,7 @@ pub(super) fn build_positioned_pages( caption, alignments, rules, + .. } => { pre_display_size = None; let mut line_index = 0; @@ -2562,6 +2578,7 @@ pub(super) fn build_positioned_pages( path, options, caption, + placement, } => { pre_display_size = None; let Some(figure) = layout_figure( @@ -2591,28 +2608,50 @@ pub(super) fn build_positioned_pages( line: 0, }; let block_gap = if has_previous_block { pending_gap } else { 0 }; - position_box( - &mut pages, - &mut cursor, - page_breaks, - anchor, - figure_height, - figure_height, - block_gap, - page_goal, - top_skip, - max_depth, - ); - pages - .last_mut() - .expect("the page list starts with one page") - .items - .push(PositionedPageItem::Image { + let bottom_float = placement.contains('b') + && !placement.contains('h') + && !placement.contains('t') + && cursor > 0 + && cursor + .saturating_add(block_gap) + .saturating_add(figure_height) + <= page_goal; + if bottom_float { + let y = page_goal.saturating_sub(figure_height); + pages + .last_mut() + .expect("the page list starts with one page") + .items + .push(PositionedPageItem::Image { + anchor, + element: figure, + y, + }); + cursor = page_goal; + } else { + position_box( + &mut pages, + &mut cursor, + page_breaks, anchor, - element: figure, - y: cursor, - }); - cursor = cursor.saturating_add(figure_height); + figure_height, + figure_height, + block_gap, + page_goal, + top_skip, + max_depth, + ); + pages + .last_mut() + .expect("the page list starts with one page") + .items + .push(PositionedPageItem::Image { + anchor, + element: figure, + y: cursor, + }); + cursor = cursor.saturating_add(figure_height); + } pending_gap = paragraph_gap + (normal_line_height as f64 * 0.15).round() as i64; has_previous_block = true; } @@ -2750,6 +2789,10 @@ pub(super) fn build_positioned_pages( } Block::Penalty(_) => {} Block::PageBreak => { + if pages.last().is_some_and(|page| !page.items.is_empty()) { + pages.push(PositionedPage::default()); + cursor = 0; + } pending_gap = 0; has_previous_block = false; pre_display_size = None; @@ -2773,9 +2816,220 @@ pub(super) fn build_positioned_pages( cache, ); pages.retain(|page| !page.items.is_empty()); + append_page_decorations( + model, + &mut pages, + &block_start_pages, + content_width_mm, + metrics, + font_cache, + cjk_family, + mono_family, + sans_family, + math_metrics, + math_layout, + cache, + ); Some(pages) } +fn decoration_slot_runs(decoration: &PageDecoration, position: PageDecorationPosition) -> &[Run] { + match position { + PageDecorationPosition::Left => &decoration.left, + PageDecorationPosition::Center => &decoration.center, + PageDecorationPosition::Right => &decoration.right, + } +} + +fn resolved_page_number_runs(runs: &[Run], page_number: usize) -> Vec { + let number = page_number.to_string(); + runs.iter() + .map(|run| { + let mut run = run.clone(); + if run.text.contains(PAGE_NUMBER_MARKER) { + run.text = run.text.replace(PAGE_NUMBER_MARKER, &number); + } + run + }) + .collect() +} + +#[allow(clippy::too_many_arguments)] +fn effective_page_style_kind( + model: &DocumentModel, + page_index: usize, + page_count: usize, + block_start_pages: &HashMap, +) -> PageStyleKind { + let mut kind = model.page_style.kind; + for override_ in &model.page_style_overrides { + let page = block_start_pages + .get(&override_.anchor) + .copied() + .unwrap_or_else(|| page_count.saturating_sub(1)); + if page == page_index { + kind = override_.kind; + } + } + kind +} + +fn append_page_decorations( + model: &DocumentModel, + pages: &mut [PositionedPage], + block_start_pages: &HashMap, + content_width_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, + cache: &mut ParagraphLayoutCache, +) { + let page_count = pages.len(); + for (index, page) in pages.iter_mut().enumerate() { + let page_number = index + 1; + let kind = effective_page_style_kind(model, index, page_count, block_start_pages); + if kind == PageStyleKind::Empty { + continue; + } + if kind == PageStyleKind::Plain { + let runs = [Run::plain(page_number.to_string())]; + append_decoration( + page, + &runs, + page_number, + false, + PageDecorationPosition::Center, + content_width_mm, + model.page.height_mm, + metrics, + font_cache, + cjk_family, + mono_family, + sans_family, + math_metrics, + math_layout, + cache, + ); + continue; + } + for is_header in [false, true] { + let decoration = if is_header { + &model.page_style.header + } else { + &model.page_style.footer + }; + for position in [ + PageDecorationPosition::Left, + PageDecorationPosition::Center, + PageDecorationPosition::Right, + ] { + let runs = decoration_slot_runs(decoration, position); + if runs.is_empty() { + continue; + } + append_decoration( + page, + runs, + page_number, + is_header, + position, + content_width_mm, + model.page.height_mm, + metrics, + font_cache, + cjk_family, + mono_family, + sans_family, + math_metrics, + math_layout, + cache, + ); + } + } + } +} + +#[allow(clippy::too_many_arguments)] +fn append_decoration( + page: &mut PositionedPage, + runs: &[Run], + page_number: usize, + is_header: bool, + position: PageDecorationPosition, + content_width_mm: f64, + page_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, + cache: &mut ParagraphLayoutCache, +) { + let runs = resolved_page_number_runs(runs, page_number); + let lines = measure_positioned_lines( + &runs, + 9, + content_width_mm, + metrics, + font_cache, + cjk_family, + mono_family, + sans_family, + math_metrics, + math_layout, + cache, + ); + if lines.is_empty() { + return; + } + let body_width = millimeters_to_scaled(content_width_mm); + let page_height = millimeters_to_scaled(page_height_mm); + let top_skip = i64::from(scaled_points(ARTICLE_11PT_TOPSKIP_PT).0); + let total_height: i64 = lines.iter().map(|line| line.height).sum(); + let mut y = if is_header { + (top_skip / 2).max(0) + } else { + (page_height - millimeters_to_scaled(12.0) - total_height).max(0) + }; + for (line_index, line) in lines.into_iter().enumerate() { + let width = match &line.content { + PositionedLineContent::Text { line, font_size } => { + let text_line = text_layout::TextLine::new( + line, + cjk_family, + mono_family, + sans_family, + *font_size, + ); + millimeters_to_scaled(text_line.natural_width_mm(font_cache)) + } + PositionedLineContent::InlineMath(_) => 0, + }; + let x = match position { + PageDecorationPosition::Left => 0, + PageDecorationPosition::Center => (body_width - width) / 2, + PageDecorationPosition::Right => body_width - width, + }; + page.items.push(PositionedPageItem::Line(PositionedLine { + anchor: PageAnchor { + block: usize::MAX, + line: page_number.saturating_mul(1024).saturating_add(line_index), + }, + content: line.content, + y, + x, + centered: false, + })); + y = y.saturating_add(line.height); + } +} + #[allow(clippy::too_many_arguments)] fn append_vertical_text( nodes: &mut Vec, diff --git a/src/rust_typeset/texlang_adapter.rs b/src/rust_typeset/texlang_adapter.rs index 748be37..92a2b63 100644 --- a/src/rust_typeset/texlang_adapter.rs +++ b/src/rust_typeset/texlang_adapter.rs @@ -1687,6 +1687,138 @@ fn page_break_primitive( execute_layout_primitive(LayoutPrimitive::PageBreak, token, input) } +fn page_style_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + let content = read_unexpanded_argument(input, token, "expects a page style name")?; + let name = simple_token_text(strip_braced_tokens(&content)).to_ascii_lowercase(); + let kind = match name.trim() { + "empty" => texrra_core::document::PageStyleKind::Empty, + "fancy" => texrra_core::document::PageStyleKind::Fancy, + _ => texrra_core::document::PageStyleKind::Plain, + }; + write_event(input, token, FrontendEventKind::PageStyle(kind)); + Ok(()) +} + +fn this_page_style_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + let content = read_unexpanded_argument(input, token, "expects a page style name")?; + let name = simple_token_text(strip_braced_tokens(&content)).to_ascii_lowercase(); + let kind = match name.trim() { + "empty" => texrra_core::document::PageStyleKind::Empty, + "fancy" => texrra_core::document::PageStyleKind::Fancy, + _ => texrra_core::document::PageStyleKind::Plain, + }; + write_event(input, token, FrontendEventKind::ThisPageStyle(kind)); + Ok(()) +} + +fn fancy_decoration_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, + header: bool, +) -> texlang::prelude::Result<()> { + let position = read_optional_bracketed_argument(input, token, "decoration position")? + .map(|tokens| simple_token_text(&tokens)) + .and_then(|text| text.chars().find(|character| !character.is_whitespace())); + let position = match position { + Some('L') | Some('l') => texrra_core::document::PageDecorationPosition::Left, + Some('R') | Some('r') => texrra_core::document::PageDecorationPosition::Right, + _ => texrra_core::document::PageDecorationPosition::Center, + }; + let content = read_unexpanded_argument(input, token, "expects decoration content")?; + let inner = strip_braced_tokens(&content).to_vec(); + if inner.is_empty() { + write_event( + input, + token, + FrontendEventKind::PageDecorationClear { header }, + ); + return Ok(()); + } + write_event( + input, + token, + FrontendEventKind::PageDecorationStart { header, position }, + ); + let trace_key = token.trace_key(); + let mut expansion = inner; + expansion.push(control_sequence_token( + input, + "texrrapagedecorationend", + trace_key, + )); + input + .as_mut() + .expansions_mut() + .extend(expansion.into_iter().rev()); + Ok(()) +} + +fn fancy_head_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + fancy_decoration_primitive(token, input, true) +} + +fn fancy_foot_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + fancy_decoration_primitive(token, input, false) +} + +fn fancy_hf_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + write_event( + input, + token, + FrontendEventKind::PageDecorationClear { header: true }, + ); + write_event( + input, + token, + FrontendEventKind::PageDecorationClear { header: false }, + ); + Ok(()) +} + +fn page_decoration_end_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + write_event(input, token, FrontendEventKind::PageDecorationEnd); + Ok(()) +} + +fn page_number_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + write_event(input, token, FrontendEventKind::PageNumber); + Ok(()) +} + +fn simple_token_text(tokens: &[token::Token]) -> String { + let mut text = String::new(); + for token in tokens { + match token.value() { + token::Value::Letter(character) + | token::Value::Other(character) + | token::Value::Space(character) => text.push(character), + _ => {} + } + } + text +} + fn scan_engine_dimension( input: &mut vm::ExecutionInput, ) -> texlang::prelude::Result { @@ -6572,6 +6704,34 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn f64 { + let natural_space = Style::new() + .with_font_size(self.font_size) + .str_width(fonts, " "); + let mut x = Mm::from(0.0); + for item in &self.items { + match item { + TextLineItem::Text(span) => { + x += span.style.str_width(fonts, &span.text); + } + TextLineItem::Glue(_) => x += natural_space, + TextLineItem::Kern(width) => x += *width, + TextLineItem::Rule { width, .. } => x += *width, + TextLineItem::Frame { width, .. } => x += *width, + } + } + let width: printpdf::Mm = x.into(); + width.0 + } + pub(super) fn layout_spans(&self, fonts: &fonts::FontCache) -> TextLineLayout { let mut spans = Vec::with_capacity(self.items.len()); let mut rules = Vec::new(); diff --git a/tests/typeset.rs b/tests/typeset.rs index 23c5770..a22801a 100644 --- a/tests/typeset.rs +++ b/tests/typeset.rs @@ -280,6 +280,84 @@ C\hfill D\hfill E assert!(e > 150.0, "last hfill did not reach the right edge: {e}"); } +#[test] +fn figure_placement_and_newpage_split_pages() { + let image = format!("{}/examples/plot.png", env!("CARGO_MANIFEST_DIR")); + let template = r#"\documentclass{article} +\begin{document} +Before text. + +\begin{figure}[PLACE] +\includegraphics[width=3cm]{IMAGE} +\caption{Float caption.} +\end{figure} + +After text. +\end{document} +"#; + let compile = |placement: &str| { + let source = template + .replace("PLACE", placement) + .replace("IMAGE", &image); + fresh_preview(&source, "float.tex") + }; + + let top = compile("t"); + assert_eq!(top["status"], "ok", "{}", top["message"]); + assert_eq!(pages(&top).len(), 2, "[t] should move the figure to page 2"); + assert!( + !page_svg(&top, 0).contains("().ok()) + .unwrap_or_else(|| panic!("[b] image has no y coordinate: {bottom_svg}")); + assert!( + image_y > 200.0, + "[b] figure was not pushed to the bottom: {image_y}" + ); + assert!(page_svg(&bottom, 1).contains("After"), "[b] following text"); + + let newpage = r#"\documentclass{article} +\begin{document} +First page. + +\newpage + +Second page. +\end{document} +"#; + let value = fresh_preview(newpage, "newpage.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + assert_eq!(pages(&value).len(), 2, "\\newpage page count"); + assert!(page_svg(&value, 0).contains("First"), "first page text"); + assert!(page_svg(&value, 1).contains("Second"), "second page text"); +} + #[test] fn sans_family_selects_the_sans_face() { let source = r#"\documentclass{article} @@ -515,3 +593,92 @@ Body text. "title footnote is not at the page bottom: {note}" ); } + +#[test] +fn page_style_decorates_headers_and_footers() { + let source = r#"\documentclass{article} +\pagestyle{fancy} +\fancyhead[L]{Left head} +\fancyhead[C]{Middle head} +\fancyhead[R]{Right head} +\fancyfoot[C]{Foot \thepage} +\begin{document} +Body text. +\end{document} +"#; + let value = fresh_preview(source, "pagestyle.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + for text in ["Left", "Middle", "Right", "Foot"] { + assert!( + svg.contains(&format!(">{text}")), + "missing decoration `{text}`: {svg}" + ); + } + assert!( + text_x(&svg, "Left") < 1.0, + "left header is not at the left margin" + ); + assert!( + text_x(&svg, "Right") > 140.0, + "right header is not at the right edge" + ); + assert!( + text_y(&svg, "Left") < 15.0, + "header is not near the top of the page" + ); + assert!( + text_y(&svg, "Foot") > 275.0, + "footer is not near the bottom of the page" + ); +} + +#[test] +fn thispagestyle_empty_suppresses_one_page_decorations() { + let source = r#"\documentclass{article} +\pagestyle{fancy} +\fancyhead[L]{Left head} +\fancyfoot[C]{Foot \thepage} +\begin{document} +First page.\thispagestyle{empty} +\newpage +Second page. +\end{document} +"#; + let value = fresh_preview(source, "thispagestyle.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + assert_eq!(pages(&value).len(), 2, "page count"); + let first = page_svg(&value, 0); + assert!( + !first.contains(">Left"), + "page 1 header was not suppressed: {first}" + ); + assert!( + !first.contains(">Foot"), + "page 1 footer was not suppressed: {first}" + ); + let second = page_svg(&value, 1); + assert!( + second.contains(">Left"), + "page 2 header missing: {second}" + ); + assert!( + second.contains(">Foot"), + "page 2 footer missing: {second}" + ); + assert!( + second.contains(">2"), + "page 2 number missing: {second}" + ); +} + +#[test] +fn default_plain_style_prints_a_page_number() { + let value = fresh_preview(include_str!("../examples/hello.tex"), "hello.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + assert!( + text_y(&svg, "1") > 275.0, + "default page number is not in the footer" + ); +}