use std::{ collections::{HashMap, HashSet}, path::PathBuf, }; use crate::{TeXGlue, math_expr::MathExpr, source::SourceLocation}; /// Physical page dimensions in millimetres. #[derive(Clone, Copy, Debug, PartialEq)] pub struct PageSize { pub width_mm: f64, pub height_mm: f64, } impl PageSize { pub const A4: Self = Self { width_mm: 210.0, height_mm: 297.0, }; pub const A5: Self = Self { width_mm: 148.0, height_mm: 210.0, }; pub const B5: Self = Self { width_mm: 176.0, height_mm: 250.0, }; /// US letter, 8.5 by 11 inches. pub const LETTER: Self = Self { width_mm: 215.9, height_mm: 279.4, }; /// US legal, 8.5 by 14 inches. pub const LEGAL: Self = Self { width_mm: 215.9, height_mm: 355.6, }; /// US executive, 7.25 by 10.5 inches. pub const EXECUTIVE: Self = Self { width_mm: 184.15, height_mm: 266.7, }; pub fn landscape(self) -> Self { Self { width_mm: self.height_mm, height_mm: self.width_mm, } } } impl Default for PageSize { fn default() -> Self { Self::A4 } } /// Layout style for the document title block. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum TitleStyle { /// The generic article title: title, author, date, no rules. #[default] Article, /// Preprint-style title block with rules, an undertitle, and author columns. Preprint, /// Journal-style title block: title, author/affiliation columns, abstract, /// and keywords. Journal, } /// One author block in a structured front matter. #[derive(Clone, Default, PartialEq, Eq)] pub struct AuthorBlock { pub runs: Vec, /// One-based affiliation indices attached to this author. pub affiliations: Vec, pub email: Option, /// Author marked with `*` (corresponding author). pub corresponding: bool, } /// One numbered affiliation in a structured front matter. #[derive(Clone, Default, PartialEq, Eq)] pub struct Affiliation { pub index: usize, pub runs: Vec, } #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct CitationMetadata { pub author: String, pub year: String, } #[derive(Clone)] pub struct Footnote { pub number: u32, pub runs: Vec, } #[derive(Clone)] pub struct DocumentModel { pub title: String, /// Rich title runs, preserving inline emphases such as . pub title_runs: Vec, pub author: String, pub date: String, /// Style selected by the document's class/package layer. pub title_style: TitleStyle, /// Optional line printed under the title rules, e.g. "A Preprint". pub undertitle: Option, /// Short title from `\title[short]{long}`. pub short_title: Option, /// Structured author blocks from `\author` / `\affil` / `\email`. pub authors: Vec, /// Numbered affiliations from `\affil[n]{...}`. pub affiliations: Vec, /// Body of `\abstract{...}` captured for journal title blocks. pub abstract_runs: Vec, /// Body of `\keywords{...}` captured for journal title blocks. pub keywords: Vec, pub page: PageSize, pub parindent: common::Scaled, /// Base font size selected by the document class (10, 11, or 12pt). /// Number of text columns (1 for article, 2 for `iicol`/`twocolumn`). pub columns: u8, pub base_font_size: u8, pub margins: PageMargins, pub show_title: bool, pub blocks: Vec, pub block_sources: Vec>, pub labels: HashMap, pub citations: HashMap, pub citation_metadata: HashMap, /// Display text -> hyperlink URL for `\href` annotations. pub link_targets: HashMap, pub orcid_urls: Vec, /// Bibliography keys in the order their metadata was declared. Needed to /// assign natbib-style year suffixes (2014a, 2014b, ...) deterministically. pub bibliography_order: Vec, pub author_year_citations: bool, pub footnotes: Vec, pub page_style: PageStyle, pub page_style_overrides: Vec, } impl Default for DocumentModel { fn default() -> Self { Self { title: String::new(), title_runs: Vec::new(), author: String::new(), date: String::new(), title_style: TitleStyle::default(), undertitle: None, short_title: None, authors: Vec::new(), affiliations: Vec::new(), abstract_runs: Vec::new(), keywords: Vec::new(), page: PageSize::default(), // article's default \parindent for 10/11pt text. parindent: common::Scaled(17 * 65_536), columns: 1, base_font_size: 10, margins: PageMargins::default(), show_title: false, blocks: Vec::new(), block_sources: Vec::new(), labels: HashMap::new(), citations: HashMap::new(), citation_metadata: HashMap::new(), link_targets: HashMap::new(), orcid_urls: Vec::new(), bibliography_order: Vec::new(), author_year_citations: false, 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. /// Private-use marker for a dotted leader in generated contents lines. /// Private-use marker toggling hyperlink paint for the following glyphs. pub const LINK_START_MARKER: char = '\u{F3000}'; pub const LINK_END_MARKER: char = '\u{F3001}'; pub const CONTENTS_LEADER_MARKER: char = '\u{F6000}'; 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)] pub struct PageMargins { pub top: f64, pub right: f64, pub bottom: f64, pub left: f64, } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct EquationNumber { pub text: String, pub parenthesized: bool, } impl Default for PageMargins { fn default() -> Self { Self { top: 25.0, right: 25.0, bottom: 25.0, left: 25.0, } } } #[derive(Clone)] pub enum Block { Paragraph(Vec), Heading { level: u8, runs: Vec, }, List(ListBlock), Table { rows: Vec>>, caption: Option>, alignments: Vec, rules: Vec, /// Per-cell span and alignment metadata, parallel to `rows`. cell_styles: 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}{...}`. FramedBox { runs: Vec, frame: bool, width: Option, }, /// Center-aligned content produced by the `center` environment. Centered { runs: Vec, }, /// A horizontal rule such as `\hrule` (full width when `width` is None). HorizontalRule { height: common::Scaled, width: Option, }, Math { expression: MathExpr, equation_numbers: Vec>, }, VerticalKern(common::Scaled), VerticalGlue(TeXGlue), Penalty(i32), PageBreak, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum ColumnAlignment { Left, Center, Right, } /// Per-cell table metadata: a multicolumn span and an optional local alignment. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct TableCellStyle { pub colspan: usize, pub alignment: Option, } /// A horizontal table rule. `end_column` is exclusive; `usize::MAX` means the /// rule spans every column. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct TableRule { pub row: usize, pub start_column: usize, pub end_column: usize, pub trim_left: bool, pub trim_right: bool, } impl TableRule { pub fn full(row: usize) -> Self { Self { row, start_column: 0, end_column: usize::MAX, trim_left: false, trim_right: false, } } } #[derive(Clone, PartialEq, Eq, Hash)] pub struct ListBlock { pub ordered: bool, pub items: Vec, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct ListItem { pub runs: Vec, pub nested: Vec, pub vertical_glue_after: Vec, } #[derive(Clone, PartialEq, Eq, Hash)] pub enum UnresolvedReference { Label(String), Citation(Vec), /// A textual citation such as natbib's `\citet`, rendered as /// `Author (year)` instead of a parenthetical citation. TextualCitation(Vec), /// A table-of-contents/list page number for the block with this index. /// The target is resolved to a page number during page layout. TocPage(usize), } /// Horizontal alignment of a fixed-width inline box. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum InlineBoxAlign { #[default] Left, Center, Right, } /// An unbreakable inline box such as `\mbox{...}`, `\makebox{...}`, /// `\raisebox{...}`, or `\fbox{...}`. #[derive(Clone, PartialEq, Eq, Hash)] pub struct InlineBox { pub runs: Vec, /// Fixed width from `\makebox[width]{...}`, if any. pub width: Option, pub align: InlineBoxAlign, /// Vertical lift from `\raisebox{lift}{...}`. pub raise: common::Scaled, /// Draw a frame around the box (`\fbox`). pub frame: bool, } /// A filled rectangle produced by `\rule`. #[derive(Clone, PartialEq, Eq, Hash)] pub struct RuleBox { pub width: common::Scaled, /// Distance from the baseline to the bottom edge of the ink. /// /// A positive raise leaves a gap between the baseline and the rule; a /// negative raise moves the rule below the baseline. pub raise: common::Scaled, /// Thickness of the rule. pub height: common::Scaled, /// Optional fill colour; means the regular black rule. pub color: Option<[u8; 3]>, pub image: Option, } /// Paragraph-level alignment requested by `\raggedright` or `\raggedleft`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum ParagraphAlignment { #[default] Justified, RaggedRight, RaggedLeft, Centered, Quote, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct Run { pub text: String, pub math: Option, pub kern: Option, pub glue: Option, pub penalty: Option, pub rule: Option, pub box_run: Option, pub y_offset: Option, pub footnote_number: Option, pub unresolved_reference: Option, pub bold: bool, pub italic: bool, pub monospace: bool, pub sans: bool, pub small_caps: bool, /// Hyperlink text (rendered in the hyperref link colour). pub link: bool, /// True for the synthetic kern that carries paragraph indentation. pub paragraph_indent: bool, /// Alignment declaration active when this run started its paragraph. pub alignment: Option, } impl Run { pub fn plain(text: String) -> Self { Self { text, math: None, kern: None, glue: None, penalty: None, rule: None, box_run: None, y_offset: None, footnote_number: None, unresolved_reference: None, bold: false, italic: false, monospace: false, sans: false, small_caps: false, link: false, paragraph_indent: false, alignment: None, } } } impl DocumentModel { pub fn math_font_files(&self) -> HashSet { fn collect_runs(runs: &[Run], files: &mut HashSet) { for run in runs { if let Some(expression) = &run.math { expression.collect_math_font_files(files); } } } fn collect_list(list: &ListBlock, files: &mut HashSet) { for item in &list.items { collect_runs(&item.runs, files); for nested in &item.nested { collect_list(nested, files); } } } let mut files = HashSet::new(); for block in &self.blocks { match block { Block::Paragraph(runs) | Block::Heading { runs, .. } => { collect_runs(runs, &mut files); } Block::List(list) => collect_list(list, &mut files), Block::Table { rows, caption, .. } => { for cell in rows.iter().flatten() { collect_runs(cell, &mut files); } if let Some(caption) = caption { collect_runs(caption, &mut files); } } Block::Image { caption, .. } => { if let Some(caption) = caption { collect_runs(caption, &mut files); } } Block::FramedBox { runs, .. } | Block::Centered { runs } => { collect_runs(runs, &mut files); } Block::Bibliography(items) => { for (_, runs) in items { collect_runs(runs, &mut files); } } Block::Math { expression, .. } => expression.collect_math_font_files(&mut files), Block::HorizontalRule { .. } | Block::VerticalKern(_) | Block::VerticalGlue(_) | Block::Penalty(_) | Block::PageBreak => {} } } files } }