diff --git a/README.md b/README.md index f9e7d46..ce97017 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,8 @@ It handles document metadata, `\maketitle`, and `\today` (UTC), A4 pages, `geometry` margins (`margin`, `top`, `right`, `bottom`, `left`, `hmargin`, and `vmargin` with `mm`, `cm`, `in`, `pt`, or `bp` units), paragraphs, numbered and starred heading levels, paragraph indentation (`\parindent`), -`\hfill`, bold, italic and monospaced text, itemize/enumerate lists, page +`\hfill`, serif/sans/monospaced text, true small caps, itemize/enumerate lists, +page breaks, basic display and inline math, figures, simple tables, section/figure/table references, and numeric citations from a manual bibliography or a local `.bib` file. A4 pages use 25 mm margins unless @@ -187,16 +188,17 @@ are applied only when framing is requested. Like `\fbox`, a `\parbox` is an atomic vertical block rather than an inline object. NFSS-style **declarations** are supported with TeX group scoping: -`\bfseries`/`\bf`, `\itshape`/`\slshape`/`\it`, `\ttfamily`/`\tt`, and the -resets `\normalfont`, `\upshape`, `\rmfamily`, `\mdseries`, `\rm`. They stay -active until the end of the current group and nest correctly -(`{\bfseries a {\normalfont b} c}` restores bold for `c`). `\textrm`, `\textup`, `\textmd`, `\textsl`, `\textnormal` are grouped -style commands for roman/upright/medium/slanted/normal text; `\em` is an -italic declaration (an approximation of the LaTeX toggling behaviour). -`\sffamily` is still accepted but does not switch to a sans family. -`\scshape` and `\textsc{...}` are supported as an **uppercase approximation** -(the text is uppercased with unchanged size); real small-caps glyphs and the -usual 80% size reduction are not implemented yet. +`\bfseries`/`\bf`, `\itshape`/`\slshape`/`\it`, `\ttfamily`/`\tt`, +`\sffamily`/`\sf`, and the resets `\normalfont`, `\upshape`, `\rmfamily`, +`\mdseries`, `\rm`. They stay active until the end of the current group and +nest correctly (`{\bfseries a {\normalfont b} c}` restores bold for `c`). +`\textrm`, `\textup`, `\textmd`, `\textsl`, `\textsf`, `\textnormal` are +grouped style commands for roman/upright/medium/slanted/sans/normal text; `\em` +is an italic declaration (an approximation of the LaTeX toggling behaviour). +`\scshape` and `\textsc{...}` use **true small caps**: lowercase letters are +rendered as uppercase glyphs at 80% of the surrounding size, while existing +uppercase letters keep the full size. Sans, bold, and italic small caps select +the matching family and face. `\mbox{...}` and `\makebox{...}` are **inline horizontal boxes**: the content is measured as a single unbreakable unit, spaces inside become fixed-width kerns @@ -424,7 +426,8 @@ The default font paths cover common Linux installations. Set set `TEXRRA_CJK_FONT` to a TrueType font file with the required glyphs when the system fallback cannot be found. For `\texttt` output, set `TEXRRA_MONO_FONT_DIR` when Liberation Mono is not in a common Linux font -directory. +directory; for `\textsf` output, set `TEXRRA_SANS_FONT_DIR` when Liberation +Sans is not in a common Linux font directory. ## Experimental HTML endpoint @@ -451,7 +454,7 @@ advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`, | Area | Implemented | Remaining | | --- | --- | --- | | Boxes | `\rule`, `\fbox`, `\parbox`, inline `\mbox`/`\makebox`, `center`, `\hrule` | inline framed `\fbox`, `\raisebox`, `\minipage`, VBox | -| Fonts | serif/mono faces, bold/italic/mono declarations, group scoping, uppercase small caps | `\sffamily` (sans face), real small-cap glyphs | +| 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 | — | footnote insertion area, figure/table floats | | Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak` | headers/footers (`fancyhdr`), unified planner/renderer | diff --git a/crates/texrra-core/src/document.rs b/crates/texrra-core/src/document.rs index 1551ab8..d846b1b 100644 --- a/crates/texrra-core/src/document.rs +++ b/crates/texrra-core/src/document.rs @@ -219,6 +219,8 @@ pub struct Run { pub bold: bool, pub italic: bool, pub monospace: bool, + pub sans: bool, + pub small_caps: bool, /// True for the synthetic kern that carries paragraph indentation. pub paragraph_indent: bool, } @@ -237,6 +239,8 @@ impl Run { bold: false, italic: false, monospace: false, + sans: false, + small_caps: false, paragraph_indent: false, } } diff --git a/crates/texrra-core/src/document_parser.rs b/crates/texrra-core/src/document_parser.rs index 535c000..a50b594 100644 --- a/crates/texrra-core/src/document_parser.rs +++ b/crates/texrra-core/src/document_parser.rs @@ -384,8 +384,9 @@ struct Parser { bold: bool, italic: bool, monospace: bool, + sans: bool, small_caps: bool, - text_style_stack: Vec<(expanded::TextStyle, bool, bool, bool, bool)>, + text_style_stack: Vec<(expanded::TextStyle, bool, bool, bool, bool, bool)>, style_declarations: Vec<(usize, expanded::TextStyle)>, group_depth: usize, section_numbers: [u32; 3], @@ -423,6 +424,7 @@ impl Parser { bold: false, italic: false, monospace: false, + sans: false, small_caps: false, text_style_stack: Vec::new(), style_declarations: Vec::new(), @@ -596,6 +598,7 @@ impl Parser { && !self.bold && !self.italic && !self.monospace + && !self.sans && self.text_style_stack.is_empty() } @@ -621,17 +624,20 @@ impl Parser { self.bold, self.italic, self.monospace, + self.sans, self.small_caps, )); match style { expanded::TextStyle::Bold => self.bold = true, expanded::TextStyle::Italic => self.italic = true, expanded::TextStyle::Monospace => self.monospace = true, + expanded::TextStyle::Sans => self.sans = true, expanded::TextStyle::SmallCaps => self.small_caps = true, expanded::TextStyle::Normal => { self.bold = false; self.italic = false; self.monospace = false; + self.sans = false; self.small_caps = false; } } @@ -641,12 +647,14 @@ impl Parser { if self .text_style_stack .last() - .is_some_and(|(active_style, _, _, _, _)| *active_style == style) - && let Some((_, bold, italic, monospace, small_caps)) = self.text_style_stack.pop() + .is_some_and(|(active_style, _, _, _, _, _)| *active_style == style) + && let Some((_, bold, italic, monospace, sans, small_caps)) = + self.text_style_stack.pop() { self.bold = bold; self.italic = italic; self.monospace = monospace; + self.sans = sans; self.small_caps = small_caps; } } @@ -693,6 +701,9 @@ impl Parser { monospace: false, paragraph_indent: false, + + sans: false, + small_caps: false, }; self.target_runs().push(run); } @@ -959,6 +970,9 @@ impl Parser { monospace: false, paragraph_indent: false, + + sans: false, + small_caps: false, }); } @@ -1008,16 +1022,11 @@ impl Parser { { self.paragraph_source = self.current_source.clone(); } - let uppercased; - let text: &str = if self.small_caps { - uppercased = text.to_uppercase(); - uppercased.as_str() - } else { - text - }; let bold = self.bold; let italic = self.italic; let monospace = self.monospace; + let sans = self.sans; + let small_caps = self.small_caps; if self.table.is_some() { let mut pieces = text.split('&').peekable(); while let Some(piece) = pieces.next() { @@ -1027,6 +1036,8 @@ impl Parser { bold, italic, monospace, + sans, + small_caps, ); if pieces.peek().is_some() { self.finish_table_cell(); @@ -1039,6 +1050,8 @@ impl Parser { bold, italic, monospace, + sans, + small_caps, ); } } @@ -1077,6 +1090,9 @@ impl Parser { monospace, paragraph_indent: false, + + sans: false, + small_caps: false, }); } @@ -1107,6 +1123,9 @@ impl Parser { monospace, paragraph_indent: false, + + sans: false, + small_caps: false, }); } @@ -1142,6 +1161,9 @@ impl Parser { monospace, paragraph_indent: false, + + sans: false, + small_caps: false, }); } @@ -1187,6 +1209,9 @@ impl Parser { monospace, paragraph_indent: false, + + sans: false, + small_caps: false, }); } @@ -1254,7 +1279,17 @@ impl Parser { let bold = self.bold; let italic = self.italic; let monospace = self.monospace; - append_run(self.target_runs(), "&".to_string(), bold, italic, monospace); + let sans = self.sans; + let small_caps = self.small_caps; + append_run( + self.target_runs(), + "&".to_string(), + bold, + italic, + monospace, + sans, + small_caps, + ); } fn append_reference(&mut self, reference: UnresolvedReference) { @@ -1288,6 +1323,9 @@ impl Parser { monospace, paragraph_indent: false, + + sans: false, + small_caps: false, }); } @@ -1612,6 +1650,8 @@ fn indent_run(indent: common::Scaled) -> Run { bold: false, italic: false, monospace: false, + sans: false, + small_caps: false, paragraph_indent: true, } } @@ -1628,7 +1668,15 @@ fn strip_paragraph_indent(runs: &mut Vec) { } } -fn append_run(runs: &mut Vec, mut text: String, bold: bool, italic: bool, monospace: bool) { +fn append_run( + runs: &mut Vec, + mut text: String, + bold: bool, + italic: bool, + monospace: bool, + sans: bool, + small_caps: bool, +) { if text.is_empty() { return; } @@ -1649,6 +1697,8 @@ fn append_run(runs: &mut Vec, mut text: String, bold: bool, italic: bool, m && last.bold == bold && last.italic == italic && last.monospace == monospace + && last.sans == sans + && last.small_caps == small_caps { last.text.push_str(&text); return; @@ -1665,7 +1715,8 @@ fn append_run(runs: &mut Vec, mut text: String, bold: bool, italic: bool, m bold, italic, monospace, - + sans, + small_caps, paragraph_indent: false, }); } diff --git a/crates/texrra-core/src/expanded.rs b/crates/texrra-core/src/expanded.rs index aea741d..a7c8971 100644 --- a/crates/texrra-core/src/expanded.rs +++ b/crates/texrra-core/src/expanded.rs @@ -13,6 +13,7 @@ use crate::{ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum TextStyle { + Sans, Bold, Italic, Monospace, diff --git a/crates/texrra-core/src/math_parser.rs b/crates/texrra-core/src/math_parser.rs index 7cc28bf..9e91672 100644 --- a/crates/texrra-core/src/math_parser.rs +++ b/crates/texrra-core/src/math_parser.rs @@ -867,7 +867,7 @@ fn parse_math_text_group( TextStyle::Bold => bold = true, TextStyle::Italic => italic = true, TextStyle::Monospace => monospace = true, - TextStyle::SmallCaps => {} + TextStyle::SmallCaps | TextStyle::Sans => {} TextStyle::Normal => { bold = false; italic = false; diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index fe2b919..927aa11 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -3,21 +3,10 @@ This file lists the concrete implementation plans for the foundational items that are still missing. Each item names the files/functions to touch. -Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil` (see -`docs/STATUS.md`). +Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil`; sans +family and true scaled small caps (see `docs/STATUS.md`). -## 1. Sans family (`\sffamily`) - -- Load Liberation Sans in `latin_dir` alongside serif/mono (see - `font_inputs`/`register_box_font_family` in `src/rust_typeset/pdf.rs`). -- Add `sans: bool` to `Run` and to the style map key; `paragraph_font_id` - selects the sans family when set. -- Thread a `sans_family` through `TextLine`/`TextLine::new` and the SVG - font-family choice (`TexrraSans`), and add a `@font-face` in the preview. -- `\sffamily`/`\textsf{...}` become declaration primitives like - `\ttfamily`. - -## 2. Inline framed boxes / `\raisebox` +## 1. Inline framed boxes / `\raisebox` - Add `y_offset: Mm` to `PositionedSpan` and `PositionedRule`; PDF/SVG painters add it to the baseline. @@ -28,7 +17,7 @@ Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil` (see box rectangle when `frame` is set. - `\raisebox{lift}{...}` reuses the same nested item with `raise = lift`. -## 3. Footnotes +## 2. Footnotes - Parser: capture `\footnote{...}`/`\thanks{...}` into a per-paragraph list with a number marker run (superscript approximation via smaller raised text @@ -37,7 +26,7 @@ Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil` (see text height and place footnotes with a separator rule at the bottom. - Paint footnotes as normal positioned lines after the page's content. -## 4. Floats +## 3. Floats - Classify figure/table blocks as floats with `[htbp]` placement hints. - Planner: maintain pending floats and try top/bottom/page placements; keep @@ -45,13 +34,13 @@ Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil` (see - Renderer: place deferred floats at the saved slots; page keys must include float placement decisions. -## 5. Page styles / headers-footers +## 4. 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. -## 6. Unified pagination +## 5. Unified pagination - Extract the current duplicated planner (`build_page_break_plan`) and renderer (`build_positioned_pages`) vertical logic into one page builder returning an diff --git a/docs/STATUS.md b/docs/STATUS.md index c86b00c..c452466 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -14,8 +14,9 @@ the source changes; the SVG preview is refreshed per page. `\section*` variants (starred headings do not advance the counter). - Box material: `\rule` (raise/width/height), block `\fbox`, `\parbox`, inline `\mbox`/`\makebox`, `center`, `\hrule` with `width`/`height`. -- Fonts: Liberation Serif/Mono faces, bold/italic/monospace declarations with - group scoping, grouped text-style commands, uppercase small-caps approximation. +- Fonts: Liberation Serif/Sans/Mono faces, bold/italic/monospace/sans + declarations with group scoping, grouped text-style commands, true small caps + (lowercase uppercase glyphs at 80% size), and sans/serif/mono small caps. - Paragraphs: Knuth-Plass breaking, TeX hyphenation patterns, justification, centering, first-line `\parindent` (17pt default, group-scoped, `\setlength`/ `\addtolength`/`\noindent` aware), and `\hfill`/`\hfil` infinite glue. @@ -35,7 +36,6 @@ See `docs/ROADMAP.md` for concrete implementation plans. ## Known approximations / gaps -- Fonts: no sans family (`\sffamily` is a no-op); small caps are uppercase-only. - Boxes: `\fbox`/`\parbox` are block-level (an inline `\fbox` starts a block); `\raisebox`, `\minipage`, and VBox material are missing. - Pages: no footnote insertion area, no floats, no headers/footers (fancyhdr @@ -50,7 +50,7 @@ See `docs/ROADMAP.md` for concrete implementation plans. - `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` (15 tests) covers the three +- `cargo fmt --check` passes; `cargo test --workspace` (17 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. diff --git a/src/rust_typeset.rs b/src/rust_typeset.rs index e6a799a..dbec076 100644 --- a/src/rust_typeset.rs +++ b/src/rust_typeset.rs @@ -811,6 +811,19 @@ fn preview_font_path(name: &str) -> Option { pdf::latin_font_directory().ok()?, "LiberationSerif-BoldItalic.ttf", ), + "sans-regular.ttf" => ( + pdf::sans_font_directory().ok()?, + "LiberationSans-Regular.ttf", + ), + "sans-bold.ttf" => (pdf::sans_font_directory().ok()?, "LiberationSans-Bold.ttf"), + "sans-italic.ttf" => ( + pdf::sans_font_directory().ok()?, + "LiberationSans-Italic.ttf", + ), + "sans-bolditalic.ttf" => ( + pdf::sans_font_directory().ok()?, + "LiberationSans-BoldItalic.ttf", + ), "mono-regular.ttf" => ( pdf::monospace_font_directory().ok()?, "LiberationMono-Regular.ttf", @@ -848,6 +861,10 @@ pub fn preview_font_css() -> Result { ("TexrraMath", "700", "normal", "serif-bold.ttf"), ("TexrraMath", "400", "italic", "serif-italic.ttf"), ("TexrraMath", "700", "italic", "serif-bolditalic.ttf"), + ("TexrraSans", "400", "normal", "sans-regular.ttf"), + ("TexrraSans", "700", "normal", "sans-bold.ttf"), + ("TexrraSans", "400", "italic", "sans-italic.ttf"), + ("TexrraSans", "700", "italic", "sans-bolditalic.ttf"), ("TexrraMono", "400", "normal", "mono-regular.ttf"), ("TexrraMono", "700", "normal", "mono-bold.ttf"), ("TexrraMono", "400", "italic", "mono-italic.ttf"), diff --git a/src/rust_typeset/frontend.rs b/src/rust_typeset/frontend.rs index fda0166..c3ef94b 100644 --- a/src/rust_typeset/frontend.rs +++ b/src/rust_typeset/frontend.rs @@ -379,7 +379,7 @@ const PRELUDE: &str = r#" \def\@makefnmark{} \def\@thefnmark{} \def\sc{} -\def\sf{} +\def\sf{\sffamily} \def\sl{} \def\em{} \def\scshape{\texrrascshape} @@ -452,8 +452,9 @@ const PRELUDE: &str = r#" \def\textperiodcentered{·} \def\textsection{§} \def\textparagraph{¶} -\def\sffamily{} +\def\sffamily{\texrrasffamily} \def\textsc#1{{\texrrascshape #1}} +\def\textsf#1{{\sffamily #1}} \def\nicefrac#1#2{#1/#2} \def\cref#1{\texrraref{#1}} \def\Cref#1{\texrraref{#1}} diff --git a/src/rust_typeset/pdf.rs b/src/rust_typeset/pdf.rs index b6f0fb2..187f1b5 100644 --- a/src/rust_typeset/pdf.rs +++ b/src/rust_typeset/pdf.rs @@ -196,6 +196,7 @@ impl PositionedFigure { inherited_style: Style, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, ) -> Result { if scaled_units_to_mm(self.height) > f64::from(area.size().height) { return Ok(RenderResult { @@ -219,11 +220,15 @@ impl PositionedFigure { line_area.add_offset(Position::new(0.0, scaled_units_to_mm(y))); line_area.set_height(Mm::from(scaled_units_to_mm(line.height))); let result = match &mut line.content { - PositionedLineContent::Text { line, font_size } => { - text_layout::TextLine::new(line, cjk_family, mono_family, *font_size) - .aligned(Alignment::Center) - .render(context, line_area, inherited_style)? - } + PositionedLineContent::Text { line, font_size } => text_layout::TextLine::new( + line, + cjk_family, + mono_family, + sans_family, + *font_size, + ) + .aligned(Alignment::Center) + .render(context, line_area, inherited_style)?, PositionedLineContent::InlineMath(element) => { element.set_alignment(Alignment::Center); element.render(context, line_area, inherited_style)? @@ -252,6 +257,7 @@ impl PositionedTable { inherited_style: Style, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, ) -> Result { if scaled_units_to_mm(self.height) > f64::from(area.size().height) { return Ok(RenderResult { @@ -282,9 +288,19 @@ impl PositionedTable { line_area.set_height(Mm::from(scaled_units_to_mm(line.height))); let result = match &mut line.content { PositionedLineContent::Text { line, font_size } => { - text_layout::TextLine::new(line, cjk_family, mono_family, *font_size) - .aligned(alignment) - .render(context, line_area, inherited_style)? + text_layout::TextLine::new( + line, + cjk_family, + mono_family, + sans_family, + *font_size, + ) + .aligned(alignment) + .render( + context, + line_area, + inherited_style, + )? } PositionedLineContent::InlineMath(element) => { element.set_alignment(alignment); @@ -369,6 +385,7 @@ impl PositionedFramedBox { inherited_style: Style, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, ) -> Result { let width = scaled_units_to_mm(self.width); let height = scaled_units_to_mm(self.height); @@ -394,13 +411,20 @@ impl PositionedFramedBox { let mut line_y = self.inset_mm; for line in &self.lines { - let (ascent, depth) = - text_line_metrics_scaled(&context.font_cache, line, cjk_family, mono_family, 11); + let (ascent, depth) = text_line_metrics_scaled( + &context.font_cache, + line, + cjk_family, + mono_family, + sans_family, + 11, + ); let line_height = scaled_units_to_mm(ascent.saturating_add(depth)); let mut line_area = area.clone(); line_area.add_offset(Position::new(self.inset_mm, line_y)); line_area.set_height(Mm::from(line_height)); - let mut text_line = text_layout::TextLine::new(line, cjk_family, mono_family, 11); + let mut text_line = + text_layout::TextLine::new(line, cjk_family, mono_family, sans_family, 11); let result = text_line.render(context, line_area, inherited_style)?; if result.has_more { return Ok(RenderResult { @@ -429,17 +453,25 @@ impl PositionedCentered { inherited_style: Style, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, ) -> Result { let mut line_y = 0.0_f64; for line in &self.lines { - let (ascent, depth) = - text_line_metrics_scaled(&context.font_cache, line, cjk_family, mono_family, 11); + let (ascent, depth) = text_line_metrics_scaled( + &context.font_cache, + line, + cjk_family, + mono_family, + sans_family, + 11, + ); let line_height = scaled_units_to_mm(ascent.saturating_add(depth)); let mut line_area = area.clone(); line_area.add_offset(Position::new(0.0, line_y)); line_area.set_height(Mm::from(line_height)); let mut text_line = - text_layout::TextLine::new(line, cjk_family, mono_family, 11).centered(); + text_layout::TextLine::new(line, cjk_family, mono_family, sans_family, 11) + .centered(); let result = text_line.render(context, line_area, inherited_style)?; if result.has_more { return Ok(RenderResult { @@ -461,6 +493,7 @@ struct PositionedPages { next_page: usize, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, } impl PositionedPages { @@ -468,12 +501,14 @@ impl PositionedPages { pages: Vec, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, ) -> Self { Self { pages, next_page: 0, cjk_family, mono_family, + sans_family, } } } @@ -513,6 +548,7 @@ impl Element for PositionedPages { line, self.cjk_family, self.mono_family, + self.sans_family, *font_size, ); let mut text_line = if planned_line.centered { @@ -547,6 +583,7 @@ impl Element for PositionedPages { inherited_style, self.cjk_family, self.mono_family, + self.sans_family, )?, y, ) @@ -562,6 +599,7 @@ impl Element for PositionedPages { inherited_style, self.cjk_family, self.mono_family, + self.sans_family, )?, y, ) @@ -577,6 +615,7 @@ impl Element for PositionedPages { inherited_style, self.cjk_family, self.mono_family, + self.sans_family, )?, y, ) @@ -592,6 +631,7 @@ impl Element for PositionedPages { inherited_style, self.cjk_family, self.mono_family, + self.sans_family, )?, y, ) @@ -803,6 +843,7 @@ struct BoxFontMetrics { latin_fonts: BoxFontFamily, cjk_font: Option>>, monospace_fonts: Option, + sans_fonts: Option, fingerprint: u64, } @@ -813,6 +854,7 @@ impl BoxFontMetrics { latin_dir: &Path, cjk_path: Option<&Path>, monospace_dir: Option<&Path>, + sans_dir: Option<&Path>, ) -> Result { let mut hasher = DefaultHasher::new(); let latin_fonts = load_box_font_family(latin_dir, "LiberationSerif", &mut hasher)?; @@ -822,10 +864,14 @@ impl BoxFontMetrics { let monospace_fonts = monospace_dir .map(|directory| load_box_font_family(directory, "LiberationMono", &mut hasher)) .transpose()?; + let sans_fonts = sans_dir + .map(|directory| load_box_font_family(directory, "LiberationSans", &mut hasher)) + .transpose()?; Ok(Self { latin_fonts, cjk_font: cjk_font.map(Rc::new), monospace_fonts, + sans_fonts, fingerprint: hasher.finish(), }) } @@ -835,6 +881,7 @@ impl BoxFontMetrics { size: u8, bold: bool, italic: bool, + sans: bool, monospace: bool, character: char, ) -> BoxFont { @@ -845,6 +892,11 @@ impl BoxFontMetrics { .as_ref() .map(|family| box_font_variant(family, bold, italic)) .unwrap_or_else(|| box_font_variant(&self.latin_fonts, bold, italic)) + } else if sans { + self.sans_fonts + .as_ref() + .map(|family| box_font_variant(family, bold, italic)) + .unwrap_or_else(|| box_font_variant(&self.latin_fonts, bold, italic)) } else { box_font_variant(&self.latin_fonts, bold, italic) }; @@ -906,25 +958,32 @@ fn register_box_font_family( font_repo: &mut box_font::Repo, metrics: &BoxFontMetrics, size: u8, + sans: bool, monospace: bool, ) -> FontFamily { FontFamily { - regular: font_repo.register(metrics.at_size(size, false, false, monospace, 'a')), - bold: font_repo.register(metrics.at_size(size, true, false, monospace, 'a')), - italic: font_repo.register(metrics.at_size(size, false, true, monospace, 'a')), - bold_italic: font_repo.register(metrics.at_size(size, true, true, monospace, 'a')), + regular: font_repo.register(metrics.at_size(size, false, false, sans, monospace, 'a')), + bold: font_repo.register(metrics.at_size(size, true, false, sans, monospace, 'a')), + italic: font_repo.register(metrics.at_size(size, false, true, sans, monospace, 'a')), + bold_italic: font_repo.register(metrics.at_size(size, true, true, sans, monospace, 'a')), } } fn register_style_ids( - map: &mut HashMap, + map: &mut HashMap, family: &FontFamily, + sans: bool, monospace: bool, + font_size: u8, ) { - map.insert(family.regular, (false, false, monospace)); - map.insert(family.bold, (true, false, monospace)); - map.insert(family.italic, (false, true, monospace)); - map.insert(family.bold_italic, (true, true, monospace)); + map.insert(family.regular, (false, false, monospace, sans, font_size)); + map.insert(family.bold, (true, false, monospace, sans, font_size)); + map.insert(family.italic, (false, true, monospace, sans, font_size)); + map.insert(family.bold_italic, (true, true, monospace, sans, font_size)); +} + +fn small_caps_size(size: u8) -> u8 { + ((f32::from(size) * 0.8).round() as u8).max(1) } fn box_font_id_variant( @@ -947,6 +1006,7 @@ fn paragraph_font_id( latin: &FontFamily, cjk: Option, monospace: Option<&FontFamily>, + sans: Option<&FontFamily>, run: &Run, character: char, ) -> box_font::Id { @@ -956,6 +1016,9 @@ fn paragraph_font_id( monospace .map(|family| box_font_id_variant(family, run.bold, run.italic)) .unwrap_or_else(|| box_font_id_variant(latin, run.bold, run.italic)) + } else if run.sans { + sans.map(|family| box_font_id_variant(family, run.bold, run.italic)) + .unwrap_or_else(|| box_font_id_variant(latin, run.bold, run.italic)) } else { box_font_id_variant(latin, run.bold, run.italic) } @@ -970,6 +1033,7 @@ fn flatten_inline_boxes( font_repo: &mut box_font::Repo, latin_font_ids: &FontFamily, monospace_font_ids: Option<&FontFamily>, + sans_font_ids: Option<&FontFamily>, cjk_font_id: Option, inside: bool, ) -> Vec { @@ -990,6 +1054,7 @@ fn flatten_inline_boxes( font_repo, latin_font_ids, monospace_font_ids, + sans_font_ids, cjk_font_id, true, )); @@ -1028,8 +1093,14 @@ fn flatten_inline_boxes( if run.text.is_empty() { continue; } - let space_font_id = - paragraph_font_id(latin_font_ids, cjk_font_id, monospace_font_ids, run, ' '); + let space_font_id = paragraph_font_id( + latin_font_ids, + cjk_font_id, + monospace_font_ids, + sans_font_ids, + run, + ' ', + ); let space_width = font_repo.get(space_font_id).default_space().width; let mut segment = String::new(); for character in run.text.chars() { @@ -1072,31 +1143,63 @@ fn boxworks_line_break( return None; } let mut font_repo = box_font::Repo::::default(); - let latin_font_ids = register_box_font_family(&mut font_repo, metrics, size, false); + let latin_font_ids = register_box_font_family(&mut font_repo, metrics, size, false, false); let monospace_font_ids = metrics .monospace_fonts .as_ref() - .map(|_| register_box_font_family(&mut font_repo, metrics, size, true)); + .map(|_| register_box_font_family(&mut font_repo, metrics, size, false, true)); + let sans_font_ids = metrics + .sans_fonts + .as_ref() + .map(|_| register_box_font_family(&mut font_repo, metrics, size, true, false)); let cjk_font_id = metrics .cjk_font .as_ref() - .map(|_| font_repo.register(metrics.at_size(size, false, false, false, '中'))); + .map(|_| font_repo.register(metrics.at_size(size, false, false, false, false, '中'))); let null_font_id = font_repo.register(BoxFont::null()); let mut rules: HashMap = HashMap::new(); let mut next_rule_anchor = 0xF0000_u32; let mut style_by_font = HashMap::new(); - register_style_ids(&mut style_by_font, &latin_font_ids, false); + register_style_ids(&mut style_by_font, &latin_font_ids, false, false, size); if let Some(monospace) = &monospace_font_ids { - register_style_ids(&mut style_by_font, monospace, true); + register_style_ids(&mut style_by_font, monospace, false, true, size); + } + if let Some(sans) = &sans_font_ids { + register_style_ids(&mut style_by_font, sans, true, false, size); } if let Some(cjk) = cjk_font_id { - style_by_font.insert(cjk, (false, false, false)); + style_by_font.insert(cjk, (false, false, false, false, size)); + } + let small_size = small_caps_size(size); + let small_latin_font_ids = + register_box_font_family(&mut font_repo, metrics, small_size, false, false); + let small_monospace_font_ids = metrics + .monospace_fonts + .as_ref() + .map(|_| register_box_font_family(&mut font_repo, metrics, small_size, false, true)); + let small_sans_font_ids = metrics + .sans_fonts + .as_ref() + .map(|_| register_box_font_family(&mut font_repo, metrics, small_size, true, false)); + register_style_ids( + &mut style_by_font, + &small_latin_font_ids, + false, + false, + small_size, + ); + if let Some(monospace) = &small_monospace_font_ids { + register_style_ids(&mut style_by_font, monospace, false, true, small_size); + } + if let Some(sans) = &small_sans_font_ids { + register_style_ids(&mut style_by_font, sans, true, false, small_size); } let flattened = flatten_inline_boxes( runs, &mut font_repo, &latin_font_ids, monospace_font_ids.as_ref(), + sans_font_ids.as_ref(), cjk_font_id, false, ); @@ -1176,6 +1279,7 @@ fn boxworks_line_break( &latin_font_ids, cjk_font_id, monospace_font_ids.as_ref(), + sans_font_ids.as_ref(), run, ' ', ); @@ -1194,18 +1298,43 @@ fn boxworks_line_break( if character == ' ' && horizontal.is_empty() { continue; } - let font_id = paragraph_font_id( + let mut glyph_character = character; + let mut font_id = paragraph_font_id( &latin_font_ids, cjk_font_id, monospace_font_ids.as_ref(), + sans_font_ids.as_ref(), run, character, ); + if run.small_caps && character.is_lowercase() { + let mut upper = character.to_uppercase(); + if let Some(upper_character) = upper.next() + && upper.next().is_none() + { + glyph_character = upper_character; + let small_family = if run.monospace { + small_monospace_font_ids + .as_ref() + .unwrap_or(&small_latin_font_ids) + } else if run.sans { + small_sans_font_ids + .as_ref() + .unwrap_or(&small_latin_font_ids) + } else { + &small_latin_font_ids + }; + font_id = box_font_id_variant(small_family, run.bold, run.italic); + } + } if let Some(previous) = previous_character { - let cjk_boundary = is_cjk(previous) || is_cjk(character); - let can_break = cjk_boundary && !prohibits_cjk_line_break(previous, character); + let cjk_boundary = is_cjk(previous) || is_cjk(glyph_character); + let can_break = + cjk_boundary && !prohibits_cjk_line_break(previous, glyph_character); if !can_break && previous_font_id == Some(font_id) { - let kerning = font_repo.get(font_id).pair_kerning(previous, character); + let kerning = font_repo + .get(font_id) + .pair_kerning(previous, glyph_character); if kerning != Scaled::ZERO { horizontal.push( ds::Kern { @@ -1229,12 +1358,12 @@ fn boxworks_line_break( } horizontal.push( ds::Char { - char: character, + char: glyph_character, font: font_id, } .into(), ); - previous_character = Some(character); + previous_character = Some(glyph_character); previous_font_id = Some(font_id); } } @@ -1339,15 +1468,17 @@ fn boxworks_line_break( height: rule.height, }); } else { - let (bold, italic, monospace) = style_by_font + let (bold, italic, monospace, sans, glyph_size) = style_by_font .get(&character.font) .copied() - .unwrap_or_default(); + .unwrap_or((false, false, false, false, size)); line_items.push(text_layout::LineItem::Glyph { character: character.char, bold, italic, monospace, + sans, + font_size: glyph_size, }); } } @@ -1499,6 +1630,20 @@ pub(super) fn monospace_font_directory() -> Result { }) } +pub(super) fn sans_font_directory() -> Result { + env::var_os("TEXRRA_SANS_FONT_DIR") + .map(PathBuf::from) + .into_iter() + .chain([ + "/usr/share/fonts/liberation-sans-fonts".into(), + "/usr/share/fonts/truetype/liberation2".into(), + ]) + .find(|directory| directory.join("LiberationSans-Regular.ttf").is_file()) + .ok_or_else(|| { + "could not find Liberation Sans fonts; set TEXRRA_SANS_FONT_DIR to a directory containing LiberationSans-Regular.ttf and its bold/italic variants".to_string() + }) +} + pub(super) fn latin_font_family_fingerprint(latin_dir: &Path) -> Result { let mut hasher = DefaultHasher::new(); for face in ["Regular", "Bold", "Italic", "BoldItalic"] { @@ -1618,6 +1763,8 @@ struct FontInputs { cjk_font: Option, monospace_dir: Option, monospace_fonts: Option>, + sans_dir: Option, + sans_fonts: Option>, box_metrics: BoxFontMetrics, } @@ -1648,8 +1795,23 @@ impl FontInputs { } else { None }; - let box_metrics = - BoxFontMetrics::load(&latin_dir, cjk_path.as_deref(), monospace_dir.as_deref())?; + let sans_dir = document_contains_sans(model) + .then(sans_font_directory) + .transpose()?; + let sans_fonts = if let Some(sans_dir) = &sans_dir { + Some( + fonts::from_files(sans_dir, "LiberationSans", None) + .map_err(|error| format!("could not load sans-serif fonts: {error}"))?, + ) + } else { + None + }; + let box_metrics = BoxFontMetrics::load( + &latin_dir, + cjk_path.as_deref(), + monospace_dir.as_deref(), + sans_dir.as_deref(), + )?; Ok(Self { latin_dir, latin_fonts, @@ -1657,6 +1819,8 @@ impl FontInputs { cjk_font, monospace_dir, monospace_fonts, + sans_dir, + sans_fonts, box_metrics, }) } @@ -1676,6 +1840,7 @@ pub(super) struct RenderResources { document: Document, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, box_metrics: BoxFontMetrics, math_metrics: math_font::MathFontMetrics, math_layout: MathLayoutEnvironment, @@ -1712,6 +1877,10 @@ impl RenderResources { let cjk_family = inputs .cjk_family() .map(|family| document.add_font_family(family)); + let sans_family = inputs + .sans_fonts + .clone() + .map(|family| document.add_font_family(family)); let math_layout = MathLayoutEnvironment { cache: math_layout_cache, font_fingerprint: math_font_family_fingerprint( @@ -1729,6 +1898,7 @@ impl RenderResources { document, cjk_family, mono_family, + sans_family, box_metrics: inputs.box_metrics, math_metrics, math_layout, @@ -1741,6 +1911,7 @@ pub(super) struct PreviewResourceKey { latin_dir: PathBuf, cjk_path: Option, monospace_dir: Option, + sans_dir: Option, math_metrics_fingerprint: u64, } @@ -1756,10 +1927,14 @@ impl PreviewResourceKey { let monospace_dir = document_contains_monospace(model) .then(monospace_font_directory) .transpose()?; + let sans_dir = document_contains_sans(model) + .then(sans_font_directory) + .transpose()?; Ok(Self { latin_dir, cjk_path, monospace_dir, + sans_dir, math_metrics_fingerprint, }) } @@ -1770,6 +1945,7 @@ pub(super) struct PreviewResources { font_cache: fonts::FontCache, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, box_metrics: BoxFontMetrics, math_metrics: math_font::MathFontMetrics, math_layout: MathLayoutEnvironment, @@ -1791,6 +1967,10 @@ impl PreviewResources { let cjk_family = inputs .cjk_family() .map(|family| font_cache.add_font_family(family)); + let sans_family = inputs + .sans_fonts + .clone() + .map(|family| font_cache.add_font_family(family)); let math_layout = MathLayoutEnvironment { cache: math_layout_cache, font_fingerprint: math_font_family_fingerprint( @@ -1808,11 +1988,13 @@ impl PreviewResources { latin_dir: inputs.latin_dir, cjk_path: inputs.cjk_path, monospace_dir: inputs.monospace_dir, + sans_dir: inputs.sans_dir, math_metrics_fingerprint, }, font_cache, cjk_family, mono_family, + sans_family, box_metrics: inputs.box_metrics, math_metrics, math_layout, @@ -1846,6 +2028,7 @@ pub(super) fn render_pdf( resources.document.font_cache(), resources.cjk_family, resources.mono_family, + resources.sans_family, &resources.math_metrics, &resources.math_layout, paragraph_layout_cache, @@ -1857,9 +2040,15 @@ pub(super) fn render_pdf( mut document, cjk_family, mono_family, + sans_family, .. } = resources; - document.push(PositionedPages::new(pages, cjk_family, mono_family)); + document.push(PositionedPages::new( + pages, + cjk_family, + mono_family, + sans_family, + )); let mut pdf = Vec::new(); document .render(&mut pdf) @@ -1874,6 +2063,7 @@ pub(super) fn render_pdf( mut document, cjk_family, mono_family, + sans_family, box_metrics, math_metrics, math_layout, @@ -1977,7 +2167,13 @@ pub(super) fn render_pdf( document.push(elements::PageBreak::new()); } document.push(StyledElement::new( - text_layout::TextLine::new(&line, cjk_family, mono_family, 11), + text_layout::TextLine::new( + &line, + cjk_family, + mono_family, + sans_family, + 11, + ), Style::new().with_font_size(11), )); } @@ -2031,7 +2227,13 @@ pub(super) fn render_pdf( document.push(elements::PageBreak::new()); } document.push(StyledElement::new( - text_layout::TextLine::new(&line, cjk_family, mono_family, size), + text_layout::TextLine::new( + &line, + cjk_family, + mono_family, + sans_family, + size, + ), Style::new().with_font_size(size), )); } @@ -2159,6 +2361,9 @@ pub(super) fn render_pdf( monospace: false, paragraph_indent: false, + + sans: false, + small_caps: false, }]; document.push(paragraph( &heading, @@ -2588,6 +2793,36 @@ pub(super) fn document_contains_monospace(model: &DocumentModel) -> bool { }) } +pub(super) fn document_contains_sans(model: &DocumentModel) -> bool { + let runs_have_sans = |runs: &[Run]| runs.iter().any(|run| run.sans); + model.blocks.iter().any(|block| match block { + Block::Paragraph(runs) | Block::Heading { runs, .. } => runs_have_sans(runs), + Block::List(list) => list_contains_sans(list, &runs_have_sans), + Block::Table { rows, caption, .. } => { + rows.iter().flatten().any(|runs| runs_have_sans(runs)) + || caption.as_ref().is_some_and(|runs| runs_have_sans(runs)) + } + Block::Image { caption, .. } => caption.as_ref().is_some_and(|runs| runs_have_sans(runs)), + Block::FramedBox { runs, .. } | Block::Centered { runs } => runs_have_sans(runs), + Block::HorizontalRule { .. } => false, + Block::Bibliography(items) => items.iter().any(|(_, runs)| runs_have_sans(runs)), + Block::Math { .. } => false, + Block::VerticalKern(_) | Block::VerticalGlue(_) | Block::Penalty(_) | Block::PageBreak => { + false + } + }) +} + +fn list_contains_sans(list: &ListBlock, predicate: &impl Fn(&[Run]) -> bool) -> bool { + list.items.iter().any(|item| { + predicate(&item.runs) + || item + .nested + .iter() + .any(|child| list_contains_sans(child, predicate)) + }) +} + pub(super) fn image_scale( options: &str, pixel_width: u32, diff --git a/src/rust_typeset/pdf/layout.rs b/src/rust_typeset/pdf/layout.rs index 7fcf3db..84cbd5f 100644 --- a/src/rust_typeset/pdf/layout.rs +++ b/src/rust_typeset/pdf/layout.rs @@ -35,6 +35,7 @@ pub(super) fn layout_document( 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, @@ -49,6 +50,7 @@ pub(super) fn layout_document( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, paragraph_cache, @@ -70,6 +72,7 @@ pub(super) fn layout_document( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, paragraph_cache, @@ -456,6 +459,7 @@ fn append_list_layout_tokens( font_cache: &fonts::FontCache, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, math_metrics: &math_font::MathFontMetrics, math_layout: &MathLayoutEnvironment, cache: &mut ParagraphLayoutCache, @@ -486,12 +490,14 @@ fn append_list_layout_tokens( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, ); if lines.is_empty() { - let height = font_line_height_scaled(font_cache, cjk_family, mono_family, 11); + let height = + font_line_height_scaled(font_cache, cjk_family, mono_family, sans_family, 11); lines.push(MeasuredLine { line_index: 0, content: PositionedLineContent::Text { @@ -537,6 +543,7 @@ fn append_list_layout_tokens( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -588,6 +595,7 @@ fn layout_table( font_cache: &fonts::FontCache, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, math_metrics: &math_font::MathFontMetrics, math_layout: &MathLayoutEnvironment, cache: &mut ParagraphLayoutCache, @@ -601,7 +609,8 @@ fn layout_table( return None; } - let empty_row_height = font_line_height_scaled(font_cache, cjk_family, mono_family, 10); + let empty_row_height = + font_line_height_scaled(font_cache, cjk_family, mono_family, sans_family, 10); let mut positioned_rows = Vec::with_capacity(rows.len()); let mut total_height = 0_i64; for row in rows { @@ -617,6 +626,7 @@ fn layout_table( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -670,6 +680,7 @@ fn layout_figure( font_cache: &fonts::FontCache, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, math_metrics: &math_font::MathFontMetrics, math_layout: &MathLayoutEnvironment, cache: &mut ParagraphLayoutCache, @@ -703,6 +714,7 @@ fn layout_figure( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -783,6 +795,7 @@ fn measure_framed_box( font_cache: &fonts::FontCache, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, cache: &mut ParagraphLayoutCache, frame: bool, width: Option, @@ -806,8 +819,14 @@ fn measure_framed_box( let lines = cached_paragraph_lines(runs, inner_mm, metrics, 11, cache); let mut content_height = 0_i64; for line in &lines { - let (ascent, depth) = - text_line_metrics_scaled(font_cache, line, cjk_family, mono_family, 11); + let (ascent, depth) = text_line_metrics_scaled( + font_cache, + line, + cjk_family, + mono_family, + sans_family, + 11, + ); content_height = content_height.saturating_add(ascent).saturating_add(depth); } let content_height = content_height.max(baseline_skip_scaled(11)); @@ -819,7 +838,8 @@ fn measure_framed_box( frame, }); } - let (line, ascent, descent) = layout_framed_runs(runs, font_cache, cjk_family, mono_family, 11); + let (line, ascent, descent) = + layout_framed_runs(runs, font_cache, cjk_family, mono_family, sans_family, 11); let content_mm = f64::from(scaled_units_to_mm(i64::from(line.width.0))).min(max_content_mm); let content_height = i64::from(scaled_points(f64::from(ascent + descent) * PDF_POINTS_PER_INCH / 25.4).0) @@ -838,6 +858,7 @@ fn layout_framed_runs( font_cache: &fonts::FontCache, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, font_size: u8, ) -> (text_layout::LineBox, Mm, Mm) { let mut items = Vec::new(); @@ -874,10 +895,22 @@ fn layout_framed_runs( if run.math.is_some() { continue; } + let small_size = ((f32::from(font_size) * 0.8).round() as u8).max(1); for character in run.text.chars() { - let character_is_cjk = is_cjk(character); + let mut glyph_character = character; + let mut glyph_size = font_size; + if run.small_caps && character.is_lowercase() { + let mut upper = character.to_uppercase(); + if let Some(upper_character) = upper.next() + && upper.next().is_none() + { + glyph_character = upper_character; + glyph_size = small_size; + } + } + let character_is_cjk = is_cjk(glyph_character); let mut style = Style::new() - .with_font_size(font_size) + .with_font_size(glyph_size) .with_line_spacing(1.22); if character_is_cjk { if let Some(family) = cjk_family { @@ -887,6 +920,10 @@ fn layout_framed_runs( && let Some(family) = mono_family { style = style.with_font_family(family); + } else if run.sans + && let Some(family) = sans_family + { + style = style.with_font_family(family); } if !character_is_cjk { if run.bold { @@ -896,16 +933,18 @@ fn layout_framed_runs( style = style.italic(); } } - let glyph_height = style.font(font_cache).glyph_height(font_size); + let glyph_height = style.font(font_cache).glyph_height(glyph_size); let line_height = style.line_height(font_cache); ascent = ascent.max(glyph_height); descent = descent.max((line_height - glyph_height).max(Mm::from(0.0))); - width += style.str_width(font_cache, &character.to_string()); + width += style.str_width(font_cache, &glyph_character.to_string()); items.push(text_layout::LineItem::Glyph { - character, + character: glyph_character, bold: run.bold, italic: run.italic, monospace: run.monospace, + sans: run.sans, + font_size: glyph_size, }); } } @@ -933,13 +972,14 @@ fn measure_centered( font_cache: &fonts::FontCache, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, cache: &mut ParagraphLayoutCache, ) -> MeasuredCentered { let lines = cached_paragraph_lines(runs, content_width_mm, metrics, 11, cache); let mut height = 0_i64; for line in &lines { let (ascent, depth) = - text_line_metrics_scaled(font_cache, line, cjk_family, mono_family, 11); + text_line_metrics_scaled(font_cache, line, cjk_family, mono_family, sans_family, 11); height = height.saturating_add(ascent).saturating_add(depth); } if height == 0 { @@ -957,12 +997,14 @@ pub(super) fn build_page_break_plan( 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 normal_line_height = font_line_height_scaled(font_cache, cjk_family, mono_family, 11); + let normal_line_height = + font_line_height_scaled(font_cache, cjk_family, mono_family, sans_family, 11); 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; @@ -989,6 +1031,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, paragraph_cache, ); nodes.push(VerticalNode::Penalty(10_000)); @@ -1011,6 +1054,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, ) @@ -1025,6 +1069,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, paragraph_cache, ) }; @@ -1041,6 +1086,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, paragraph_cache, *frame, *width, @@ -1071,6 +1117,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, paragraph_cache, ); nodes.push(VerticalNode::fixed_glue( @@ -1124,6 +1171,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, ) @@ -1138,6 +1186,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, paragraph_cache, ) }; @@ -1190,6 +1239,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, paragraph_cache, @@ -1279,6 +1329,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, paragraph_cache, @@ -1310,6 +1361,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, paragraph_cache, @@ -1351,6 +1403,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, paragraph_cache, @@ -1392,6 +1445,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, paragraph_cache, @@ -1430,6 +1484,7 @@ pub(super) fn build_page_break_plan( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, paragraph_cache, @@ -1491,6 +1546,7 @@ fn measure_positioned_lines( font_cache: &fonts::FontCache, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, math_metrics: &math_font::MathFontMetrics, math_layout: &MathLayoutEnvironment, cache: &mut ParagraphLayoutCache, @@ -1540,8 +1596,14 @@ fn measure_positioned_lines( if line.items.is_empty() { return None; } - let (ascent, descent) = - text_line_metrics_scaled(font_cache, &line, cjk_family, mono_family, font_size); + let (ascent, descent) = text_line_metrics_scaled( + font_cache, + &line, + cjk_family, + mono_family, + sans_family, + font_size, + ); let pre_display_size = line.pre_display_size.map(|size| i64::from(size.0)); Some(MeasuredLine { line_index, @@ -1623,11 +1685,13 @@ pub(super) fn build_positioned_pages( font_cache: &fonts::FontCache, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, math_metrics: &math_font::MathFontMetrics, math_layout: &MathLayoutEnvironment, cache: &mut ParagraphLayoutCache, ) -> Option> { - let normal_line_height = font_line_height_scaled(font_cache, cjk_family, mono_family, 11); + let normal_line_height = + font_line_height_scaled(font_cache, cjk_family, mono_family, sans_family, 11); 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 paragraph_gap = (normal_line_height as f64 * 0.35).round() as i64; @@ -1658,6 +1722,7 @@ pub(super) fn build_positioned_pages( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -1721,6 +1786,7 @@ pub(super) fn build_positioned_pages( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -1781,6 +1847,7 @@ pub(super) fn build_positioned_pages( font_cache, cjk_family, mono_family, + sans_family, cache, *frame, *width, @@ -1831,6 +1898,7 @@ pub(super) fn build_positioned_pages( font_cache, cjk_family, mono_family, + sans_family, cache, ); let anchor = PageAnchor { @@ -1998,6 +2066,7 @@ pub(super) fn build_positioned_pages( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -2110,6 +2179,7 @@ pub(super) fn build_positioned_pages( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -2161,6 +2231,7 @@ pub(super) fn build_positioned_pages( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -2250,6 +2321,7 @@ pub(super) fn build_positioned_pages( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -2307,6 +2379,7 @@ pub(super) fn build_positioned_pages( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -2368,6 +2441,7 @@ pub(super) fn build_positioned_pages( font_cache, cjk_family, mono_family, + sans_family, math_metrics, math_layout, cache, @@ -2444,6 +2518,7 @@ fn append_vertical_text( 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); @@ -2455,8 +2530,14 @@ fn append_vertical_text( 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, font_size); + 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( @@ -2485,6 +2566,7 @@ fn append_vertical_inline_math( font_cache: &fonts::FontCache, cjk_family: Option>, mono_family: Option>, + _sans_family: Option>, metrics: &math_font::MathFontMetrics, layout: &MathLayoutEnvironment, ) -> Option { @@ -2607,6 +2689,7 @@ pub(super) fn text_line_metrics_scaled( line: &text_layout::LineBox, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, font_size: u8, ) -> (i64, i64) { let mut ascent_mm = Mm::from(0.0); @@ -2627,13 +2710,15 @@ pub(super) fn text_line_metrics_scaled( bold, italic, monospace, + sans, + font_size: glyph_size, } = item else { continue; }; let character_is_cjk = is_cjk(*character); let mut style = Style::new() - .with_font_size(font_size) + .with_font_size(*glyph_size) .with_line_spacing(1.22); if character_is_cjk { if let Some(family) = cjk_family { @@ -2641,6 +2726,8 @@ pub(super) fn text_line_metrics_scaled( } } else if *monospace && let Some(family) = mono_family { style = style.with_font_family(family); + } else if *sans && let Some(family) = sans_family { + style = style.with_font_family(family); } if !character_is_cjk { if *bold { @@ -2671,10 +2758,11 @@ fn font_line_height_scaled( font_cache: &fonts::FontCache, cjk_family: Option>, mono_family: Option>, + sans_family: Option>, font_size: u8, ) -> i64 { let (mut ascent_mm, mut descent_mm) = style_line_dimensions(font_cache, None, font_size); - for family in [cjk_family, mono_family].into_iter().flatten() { + for family in [cjk_family, mono_family, sans_family].into_iter().flatten() { let (family_ascent, family_descent) = style_line_dimensions(font_cache, Some(family), font_size); ascent_mm = ascent_mm.max(family_ascent); diff --git a/src/rust_typeset/pdf/preview.rs b/src/rust_typeset/pdf/preview.rs index c5b84cb..9f8698f 100644 --- a/src/rust_typeset/pdf/preview.rs +++ b/src/rust_typeset/pdf/preview.rs @@ -34,6 +34,7 @@ pub(in crate::rust_typeset) fn render_pages( &resources.font_cache, resources.cjk_family, resources.mono_family, + resources.sans_family, &resources.math_metrics, &resources.math_layout, paragraph_layout_cache, @@ -66,6 +67,7 @@ fn page_svg( let fonts = &resources.font_cache; let cjk_family = resources.cjk_family; let monospace_family = resources.mono_family; + let sans_family = resources.sans_family; let mut output = String::new(); let page_width = model.page.width_mm; let page_height = model.page.height_mm; @@ -98,6 +100,7 @@ fn page_svg( fonts, cjk_family, monospace_family, + sans_family, ), PositionedPageItem::DisplayMath { element, style, y, .. @@ -117,6 +120,7 @@ fn page_svg( fonts, cjk_family, monospace_family, + sans_family, ), PositionedPageItem::Centered { element, y, .. } => write_centered( &mut output, @@ -126,6 +130,7 @@ fn page_svg( fonts, cjk_family, monospace_family, + sans_family, ), PositionedPageItem::FramedBox { element, y, .. } => write_framed_box( &mut output, @@ -134,6 +139,7 @@ fn page_svg( fonts, cjk_family, monospace_family, + sans_family, ), PositionedPageItem::Image { element, y, .. } => write_figure( &mut output, @@ -143,6 +149,7 @@ fn page_svg( fonts, cjk_family, monospace_family, + sans_family, ), } } @@ -158,6 +165,7 @@ fn write_table( fonts: &fonts::FontCache, cjk_family: Option>, monospace_family: Option>, + sans_family: Option>, ) { let width_mm = f64::from(content_width); let column_width = Mm::from(width_mm / table.column_count.max(1) as f64); @@ -181,6 +189,7 @@ fn write_table( fonts, cjk_family, monospace_family, + sans_family, ); cell_y += scaled_units_to_mm(line.height); } @@ -200,6 +209,7 @@ fn write_figure( fonts: &fonts::FontCache, cjk_family: Option>, monospace_family: Option>, + sans_family: Option>, ) { let height_mm = scaled_units_to_mm(figure.image_height); let x = ((f64::from(content_width) - figure.image_width_mm).max(0.0)) / 2.0; @@ -227,6 +237,7 @@ fn write_figure( fonts, cjk_family, monospace_family, + sans_family, ); cursor += scaled_units_to_mm(line.height); } @@ -243,15 +254,17 @@ fn write_line_content( fonts: &fonts::FontCache, cjk_family: Option>, monospace_family: Option>, + sans_family: Option>, ) { match content { PositionedLineContent::Text { line, font_size } => { - text_layout::TextLine::new(line, cjk_family, monospace_family, *font_size) + text_layout::TextLine::new(line, cjk_family, monospace_family, sans_family, *font_size) .aligned(alignment) .write_svg( fonts, cjk_family, monospace_family, + sans_family, area_width, x, y, @@ -288,6 +301,7 @@ fn write_framed_box( fonts: &fonts::FontCache, cjk_family: Option>, monospace_family: Option>, + sans_family: Option>, ) { let width = scaled_units_to_mm(element.width); let height = scaled_units_to_mm(element.height); @@ -303,7 +317,7 @@ fn write_framed_box( let mut line_y = y + Mm::from(element.inset_mm); for line in &element.lines { let (ascent, depth) = - text_line_metrics_scaled(fonts, line, cjk_family, monospace_family, 11); + text_line_metrics_scaled(fonts, line, cjk_family, monospace_family, sans_family, 11); let line_height = scaled_units_to_mm(ascent.saturating_add(depth)); let content = PositionedLineContent::Text { line: line.clone(), @@ -319,6 +333,7 @@ fn write_framed_box( fonts, cjk_family, monospace_family, + sans_family, ); line_y += Mm::from(line_height); } @@ -332,11 +347,12 @@ fn write_centered( fonts: &fonts::FontCache, cjk_family: Option>, monospace_family: Option>, + sans_family: Option>, ) { let mut line_y = y; for line in &element.lines { let (ascent, depth) = - text_line_metrics_scaled(fonts, line, cjk_family, monospace_family, 11); + text_line_metrics_scaled(fonts, line, cjk_family, monospace_family, sans_family, 11); let line_height = scaled_units_to_mm(ascent.saturating_add(depth)); let content = PositionedLineContent::Text { line: line.clone(), @@ -352,6 +368,7 @@ fn write_centered( fonts, cjk_family, monospace_family, + sans_family, ); line_y += Mm::from(line_height); } diff --git a/src/rust_typeset/texlang_adapter.rs b/src/rust_typeset/texlang_adapter.rs index 166f082..837afcd 100644 --- a/src/rust_typeset/texlang_adapter.rs +++ b/src/rust_typeset/texlang_adapter.rs @@ -3001,6 +3001,18 @@ fn ttfamily_primitive( Ok(()) } +fn sffamily_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + write_event( + input, + token, + FrontendEventKind::TextStyleDeclare(texrra_core::expanded::TextStyle::Sans), + ); + Ok(()) +} + fn normalfont_primitive( token: token::Token, input: &mut vm::ExecutionInput, @@ -6314,6 +6326,10 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn>, monospace_family: Option>, + sans_family: Option>, font_size: u8, ) -> Self { let mut items = Vec::new(); @@ -95,6 +98,8 @@ impl TextLine { bold, italic, monospace, + sans, + font_size: glyph_size, } if is_cjk(*character) => { flush_text( &mut items, @@ -102,6 +107,7 @@ impl TextLine { &mut text_style, cjk_family, monospace_family, + sans_family, font_size, ); items.push(TextLineItem::Text(TextSpan { @@ -110,10 +116,12 @@ impl TextLine { *bold, *italic, *monospace, + *sans, true, cjk_family, monospace_family, - font_size, + sans_family, + *glyph_size, ), })); } @@ -122,8 +130,10 @@ impl TextLine { bold, italic, monospace, + sans, + font_size: glyph_size, } => { - let style_key = (*bold, *italic, *monospace); + let style_key = (*bold, *italic, *monospace, *sans, *glyph_size); if text_style != Some(style_key) { flush_text( &mut items, @@ -131,6 +141,7 @@ impl TextLine { &mut text_style, cjk_family, monospace_family, + sans_family, font_size, ); text_style = Some(style_key); @@ -148,6 +159,7 @@ impl TextLine { &mut text_style, cjk_family, monospace_family, + sans_family, font_size, ); items.push(TextLineItem::Rule { @@ -163,6 +175,7 @@ impl TextLine { &mut text_style, cjk_family, monospace_family, + sans_family, font_size, ); items.push(TextLineItem::Glue(scaled_to_mm(*width))); @@ -174,6 +187,7 @@ impl TextLine { &mut text_style, cjk_family, monospace_family, + sans_family, font_size, ); items.push(TextLineItem::Kern(scaled_to_mm(*width))); @@ -186,6 +200,7 @@ impl TextLine { &mut text_style, cjk_family, monospace_family, + sans_family, font_size, ); Self { @@ -273,6 +288,7 @@ impl TextLine { fonts: &fonts::FontCache, cjk_family: Option>, monospace_family: Option>, + sans_family: Option>, area_width: Mm, x: Mm, y: Mm, @@ -301,6 +317,8 @@ impl TextLine { "TexrraCjk" } else if monospace_family.is_some_and(|family| family.regular == regular) { "TexrraMono" + } else if sans_family.is_some_and(|family| family.regular == regular) { + "TexrraSans" } else { "TexrraSerif" }; @@ -325,26 +343,31 @@ impl TextLine { fn flush_text( items: &mut Vec, text: &mut String, - style_key: &mut Option<(bool, bool, bool)>, + style_key: &mut Option<(bool, bool, bool, bool, u8)>, cjk_family: Option>, monospace_family: Option>, + sans_family: Option>, font_size: u8, ) { if text.is_empty() { *style_key = None; return; } - let (bold, italic, monospace) = style_key.take().unwrap_or_default(); + let (bold, italic, monospace, sans, glyph_size) = style_key + .take() + .unwrap_or((false, false, false, false, font_size)); items.push(TextLineItem::Text(TextSpan { text: std::mem::take(text), style: text_style_for( bold, italic, monospace, + sans, false, cjk_family, monospace_family, - font_size, + sans_family, + glyph_size, ), })); } @@ -353,9 +376,11 @@ fn text_style_for( bold: bool, italic: bool, monospace: bool, + sans: bool, is_cjk: bool, cjk_family: Option>, monospace_family: Option>, + sans_family: Option>, font_size: u8, ) -> Style { let mut style = Style::new().with_font_size(font_size); @@ -371,6 +396,8 @@ fn text_style_for( } } else if monospace && let Some(family) = monospace_family { style = style.with_font_family(family); + } else if sans && let Some(family) = sans_family { + style = style.with_font_family(family); } style } diff --git a/tests/typeset.rs b/tests/typeset.rs index 97fd262..ac25211 100644 --- a/tests/typeset.rs +++ b/tests/typeset.rs @@ -279,3 +279,60 @@ C\hfill D\hfill E assert!(d > 70.0 && d < 100.0, "middle hfill is not centered: {d}"); assert!(e > 150.0, "last hfill did not reach the right edge: {e}"); } + +#[test] +fn sans_family_selects_the_sans_face() { + let source = r#"\documentclass{article} +\begin{document} +\setlength{\parindent}{0pt} +Serif text. + +{\sffamily Sans family text.} + +\textsf{Textsf sans} and {\sffamily\bfseries bold sans}. +\end{document} +"#; + let value = fresh_preview(source, "sans.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + assert!( + svg.contains("font-family=\"TexrraSans\""), + "sans face missing" + ); + assert!( + svg.contains("font-family=\"TexrraSerif\""), + "serif face missing" + ); + assert!(svg.contains(">Sans"), "sans text missing"); + assert!(svg.contains("extsf"), "textsf text missing"); + assert!( + svg.contains("font-family=\"TexrraSans\" font-size=\"3.8806\" font-weight=\"700\""), + "bold sans face missing" + ); +} + +#[test] +fn small_caps_uses_reduced_uppercase_glyphs() { + let source = r#"\documentclass{article} +\begin{document} +\setlength{\parindent}{0pt} +\textsc{Small Caps} and {\scshape mixed Case}. +\end{document} +"#; + let value = fresh_preview(source, "smallcaps.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + assert!( + svg.contains(">MALL"), + "lowercase letters were not uppercased" + ); + assert!(!svg.contains("mall"), "small caps leaked lowercase glyphs"); + assert!( + svg.contains("font-size=\"3.1750\""), + "small caps were not reduced to 80%" + ); + assert!( + svg.contains("font-size=\"3.8806\""), + "full-size capitals should remain full-size" + ); +}