Embed Computer Modern Type1 outlines in route-D PDFs

This commit is contained in:
gloamxun committed 2026-10-24 03:28:10 +08:00
1 parent 6eef2f7a54
commit 5f5fc393a4
6 files changed
+295 -10

No files matched your search

+230 -2
View File
@@ -14,6 +14,7 @@ use rusttype::Font;
use crate::cmr10::Cmr10Metrics;
use crate::render::{DisplayItem, DisplayList, FontFace};
use crate::type1::Type1Font;
fn deflate(bytes: &[u8]) -> Vec<u8> {
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
@@ -235,6 +236,21 @@ fn font_resource(font: FontFace) -> &'static str {
}
}
/// Which outline format the PDF writer embeds for text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FontBackend {
/// Embedded Liberation TrueType subsets (the default).
TrueType,
/// Knuth's Computer Modern Type1 programs when they cover the text.
ComputerModern,
}
fn cmr10_type1() -> Option<&'static Type1Font> {
static FONT: OnceLock<Option<Type1Font>> = OnceLock::new();
FONT.get_or_init(|| Type1Font::from_pfb(include_bytes!("../../../assets/fonts/cmr10.pfb")))
.as_ref()
}
/// TeX page origin offsets (`\hoffset`, `\voffset`) in scaled points.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PageOrigin {
@@ -247,6 +263,7 @@ fn page_content(
height: i64,
image_names: &BTreeMap<usize, String>,
faces: &'static [PdfFace; 6],
cm_codes: Option<&BTreeMap<char, u8>>,
origin: PageOrigin,
) -> String {
let mut content = String::from("q\n0 0 0 rg\n");
@@ -266,13 +283,26 @@ fn page_content(
text,
font,
} => {
let operand = match cm_codes {
Some(codes) if matches!(*font, FontFace::Roman) => {
let mut literal = String::from("(");
for character in text.chars() {
if let Some(code) = codes.get(&character) {
literal.push_str(&format!("\\{:03o}", code));
}
}
literal.push(')');
literal
}
_ => format!("<{}>", glyph_hex(face(*font, faces), text)),
};
content.push_str(&format!(
"BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n",
font_resource(*font),
pt(*size),
pt(*x),
pt(height - *y),
format!("<{}>", glyph_hex(face(*font, faces), text))
operand
));
}
DisplayItem::Rule {
@@ -365,6 +395,39 @@ pub fn display_lists_to_pdf_with_paper(
page_width: i64,
page_height: i64,
origin: PageOrigin,
) -> Vec<u8> {
write_pdf(
pages,
page_width,
page_height,
origin,
FontBackend::TrueType,
)
}
/// Write PDFs with Knuth's Computer Modern Type1 outlines whenever the programs
/// cover the text, falling back to Liberation TrueType for other characters.
pub fn display_lists_to_pdf_with_cm_type1(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
) -> Vec<u8> {
write_pdf(
pages,
page_width,
page_height,
origin,
FontBackend::ComputerModern,
)
}
fn write_pdf(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
backend: FontBackend,
) -> Vec<u8> {
let width = page_width;
let height = page_height;
@@ -382,6 +445,23 @@ pub fn display_lists_to_pdf_with_paper(
}
}
}
let cm_codes: Option<(&Type1Font, BTreeMap<char, u8>)> = if backend
== FontBackend::ComputerModern
&& used_faces[0]
{
cmr10_type1().and_then(|font| {
if !font.covers(used_chars[0].iter().copied()) {
return None;
}
let codes = used_chars[0]
.iter()
.filter_map(|character| font.code_for(*character).map(|code| (*character, code)))
.collect();
Some((font, codes))
})
} else {
None
};
let minimal = pages.iter().all(|page| {
page.items.iter().all(|item| match item {
DisplayItem::Text { text, .. } => text.chars().all(minimal_text_char),
@@ -394,6 +474,68 @@ pub fn display_lists_to_pdf_with_paper(
if !used_faces[slot] {
continue;
}
if slot == 0
&& let Some((font, codes)) = &cm_codes
{
let font_id = objects.len() + 1;
let descriptor_id = font_id + 1;
let file_id = font_id + 2;
font_ids[slot] = font_id;
let metrics = Cmr10Metrics::for_pdf_slot(slot);
let mut by_code = BTreeMap::new();
for (character, code) in codes {
by_code.insert(*code, *character);
}
let first = *by_code.keys().next().unwrap_or(&32);
let last = *by_code.keys().next_back().unwrap_or(&32);
let mut widths = Vec::new();
let mut differences = Vec::new();
let mut next_code = first;
for code in first..=last {
let width = by_code.get(&code).map_or(0, |character| {
(metrics.width(*character) * 100 / 65_536) as i64
});
widths.push(width.to_string());
if let Some((code, name)) = by_code
.get(&code)
.and_then(|character| font.code_and_name_for(*character))
{
if code != next_code {
differences.push(code.to_string());
}
differences.push(format!("/{name}"));
next_code = code + 1;
}
}
objects.push(
format!(
"<< /Type /Font /Subtype /Type1 /BaseFont /{} /FirstChar {first} /LastChar {last} /Widths [{}] /Encoding << /Type /Encoding /Differences [{}] >> /FontDescriptor {descriptor_id} 0 R >>",
font.name,
widths.join(" "),
differences.join(" ")
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /FontDescriptor /FontName /{} /Flags 34 /FontBBox [-40 -250 1009 750] /ItalicAngle 0 /Ascent 694 /Descent -194 /CapHeight 683 /StemV 69 /FontFile {file_id} 0 R >>",
font.name
)
.into_bytes(),
);
let mut stream = format!(
"<< /Length {} /Length1 {} /Length2 {} /Length3 {} >>\nstream\n",
font.program.len(),
font.length1,
font.length2,
font.length3
)
.into_bytes();
stream.extend_from_slice(&font.program);
stream.extend_from_slice(b"\nendstream");
objects.push(stream);
continue;
}
let type0_id = objects.len() + 1;
let cid_id = type0_id + 1;
let descriptor_id = type0_id + 2;
@@ -514,7 +656,14 @@ pub fn display_lists_to_pdf_with_paper(
for (index, slot) in &used {
names.insert(*index, format!("Im{slot}"));
}
let content = page_content(list, height, &names, faces, origin);
let content = page_content(
list,
height,
&names,
faces,
cm_codes.as_ref().map(|(_, codes)| codes),
origin,
);
objects.push(
format!(
"<< /Length {} >>\nstream\n{}endstream",
@@ -614,3 +763,82 @@ mod tests {
assert_eq!(escape("中文"), "??");
}
}
#[cfg(test)]
mod type1_pdf_tests {
use super::*;
fn hello_list() -> DisplayList {
let mut list = DisplayList {
width: 200 * 65_536,
height: 100 * 65_536,
items: Vec::new(),
images: Vec::new(),
};
list.push(DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "Hi".to_string(),
font: FontFace::Roman,
});
list
}
fn write(list: &[DisplayList]) -> Vec<u8> {
display_lists_to_pdf_with_cm_type1(list, 200 * 65_536, 800 * 65_536, PageOrigin::default())
}
#[test]
fn type1_backend_embeds_computer_modern_outlines() {
let pdf = write(&[hello_list()]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/Subtype /Type1"), "{text}");
assert!(text.contains("/BaseFont /CMR10"), "{text}");
assert!(text.contains("/FontFile"), "{text}");
assert!(text.contains("(\\110\\151)"), "{text}");
assert!(!text.contains("/Subtype /Type0"), "{text}");
}
#[test]
fn type1_backend_falls_back_for_uncovered_characters() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "café".to_string(),
font: FontFace::Roman,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(!text.contains("/BaseFont /CMR10"), "{text}");
assert!(text.contains("/Subtype /Type0"), "{text}");
}
#[test]
fn pdffonts_accepts_the_embedded_type1_font() {
let probe = std::process::Command::new("pdffonts").arg("-v").output();
if probe.is_err() {
return;
}
let pdf = write(&[hello_list()]);
let path = std::env::temp_dir().join(format!(
"texrra-type1-{}-{}.pdf",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|value| value.subsec_nanos())
.unwrap_or(0)
));
std::fs::write(&path, &pdf).expect("write pdf");
let output = std::process::Command::new("pdffonts")
.arg(&path)
.output()
.expect("run pdffonts");
let _ = std::fs::remove_file(&path);
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("Type 1"), "{stdout}");
assert!(stdout.contains("CMR10"), "{stdout}");
}
}
+7
View File
@@ -112,6 +112,13 @@ impl Type1Font {
.find_map(|name| self.codes.get(*name).copied())
}
/// PDF character code plus the PostScript glyph name it selects.
pub fn code_and_name_for(&self, ch: char) -> Option<(u8, &'static str)> {
glyph_names(ch)
.iter()
.find_map(|name| self.codes.get(*name).map(|code| (*code, *name)))
}
/// Whether the program has a glyph for every character in `chars`.
pub fn covers(&self, chars: impl IntoIterator<Item = char>) -> bool {
chars.into_iter().all(|ch| self.code_for(ch).is_some())
+50 -1
View File
@@ -4,7 +4,10 @@
use texrra_tex_core::{
Document, Engine, ParagraphFont, ParagraphStyle, Unit, VerticalItem,
cmr10::Cmr10Metrics,
pdf::{PageOrigin, display_lists_to_pdf, display_lists_to_pdf_with_origin},
pdf::{
PageOrigin, display_lists_to_pdf, display_lists_to_pdf_with_cm_type1,
display_lists_to_pdf_with_origin,
},
};
/// Paragraph style in TeX scaled points, driven by the CMR10 font metrics.
@@ -530,6 +533,52 @@ fn accented_text_round_trips_through_pdf_extraction() {
);
}
#[test]
fn computer_modern_outlines_keep_extracted_text() {
use std::process::Command;
if Command::new("pdftotext")
.arg("-v")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_err()
{
return;
}
let body = "The quick brown fox jumps over the lazy dog";
let document = Document::new(62, vec![Unit::paragraph_with_style(1, body, body_style())]);
let engine = Engine::layout(&document);
let lists: Vec<_> = engine
.pages()
.iter()
.map(|page| page.display_list())
.collect();
let pdf = display_lists_to_pdf_with_cm_type1(
&lists,
612 * 65_536,
792 * 65_536,
PageOrigin::default(),
);
let path = std::env::temp_dir().join(format!("texrra-cm-type1-{}.pdf", std::process::id()));
std::fs::write(&path, &pdf).expect("write PDF");
let output = Command::new("pdftotext")
.arg(&path)
.arg("-")
.output()
.expect("pdftotext");
let _ = std::fs::remove_file(&path);
let text = String::from_utf8_lossy(&output.stdout)
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
assert!(
text.contains("The quick brown fox jumps over the lazy dog"),
"got {text:?}"
);
}
#[test]
fn route_d_text_matches_pdftex_extraction() {
use std::process::Command;
+1 -1
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`). 529 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 532 workspace tests are green and no oracle
fixture is ignored.
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
+3 -3
View File
@@ -331,7 +331,7 @@ for a later overlaid slash.
| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`; `Engine::layout_paged` builds pages through it for documents made of box/glue/penalty/mark vertical material (a unit may span pages), while in-text floats flow inline through the page builder; paged layouts replay edits from the edited page (insertions, bottom floats and interpreted `\output` force a full rebuild), and insertions are placed through the builder too; `\output` interpreted for a `\shipout`/`\ifdim`/`\ifnum` register subset over page globals and `\outputpenalty`/`\pageno`/`\deadcycles` |
| M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter |
| M4 math | partial | atoms, scripts, fractions, roots, delimiters, accents, operators, classes, braces, boxed, negated; no math painter/shrink wrapping |
| M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style; Knuth's `cmr10.pfb` is parsed into a PDF-ready Type1 program (`Length1/2/3` segments and the built-in encoding) for the coming outline path |
| M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style; route-D PDFs embed Knuth's `cmr10.pfb` as a `/Subtype /Type1` font with `/FontFile` (`Length1/2/3`), `/Encoding /Differences` and TFM `/Widths`, falling back to Liberation for characters the program does not encode |
| M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; class/package execution absent |
| M7 incremental integration | partial | route-D preview/PDF/edit endpoints plus opt-in `?engine=route-d` project preview, content-based page hashes and section/emphasis/display-math/itemize/enumerate/description/quote/center/flushright mapping; editor toggle in `texrra-web`; inline math pending |
@@ -353,7 +353,7 @@ M3 painter: `Page::display_list()` and `Halign::display_list()` produce absolute
PDF writer: `crates/texrra-tex-core/src/pdf.rs` writes multi-page PDF 1.4 with five embedded Liberation Type0/CID faces (Identity-H + ToUnicode + `/W` arrays), filled rectangles, diagonal rules, raw-RGB `/XObject` images, `/Annots` URI links and arbitrary `/special` operators. Ligature substitution and line-end italic correction are implemented; full NFSS family switching remains open.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono}`. Roman/Bold/Italic/BoldItalic/Mono text are painted with embedded Liberation Type0/CID fonts, each with a ToUnicode CMap and `/W` width array. `cmr10.tfm` is parsed at runtime for widths, heights/depths, kern pairs and ff/fi/fl/ffi/ffl ligatures; line-end and math-script italic corrections and monospace/sans paragraph faces are applied; paragraph-level NFSS declarations (`\rmfamily`, `\sffamily`, `\ttfamily`, `\bfseries`, `\itshape`, `\texttt`, `\textsf`) select those faces and the `\fontfamily`/`\fontseries`/`\fontshape`/`\fontencoding`/`\selectfont` command forms plus legacy `\rm`/`\sf`/`\tt`/`\bf`/`\it`/`\sl`/`\up`/`\normalfont` declarations are parsed; inline `\textbf`/`\emph`/`\textit`/`\texttt`/`\textsf` groups and `{\bfseries ...}` declaration groups (including nesting) split a paragraph into styled runs, each shaped by its own TFM and painted with its own face; nested faces compose relatively (`\emph` inside bold yields bold italic via cmbxti10, `\emph` inside italic returns upright); styled runs are stored on the paragraph unit, so incremental edits rebuild them through `Engine::edit_runs` instead of flattening the paragraph back to one face; true family/series/shape switching remains open; the Type1 path parses `assets/fonts/cmr10.pfb` into a PDF-ready program with its built-in encoding and character-code map, but the PDF writer still paints Liberation outlines. `Unit::paragraph` now builds its item stream with `layout_paragraph_with_font`, so CMR10 advances, kerns and ligatures drive paragraph widths; each glyph box also carries the TFM height/depth, and the painter emits 10pt glyphs and the Type0 `/W` array reports CMR10 advances, and ligature boxes paint their component letters, so `pdftotext` keeps word boundaries instead of inserting spaces between letters.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono}`. Roman/Bold/Italic/BoldItalic/Mono text are painted with embedded Liberation Type0/CID fonts, each with a ToUnicode CMap and `/W` width array. `cmr10.tfm` is parsed at runtime for widths, heights/depths, kern pairs and ff/fi/fl/ffi/ffl ligatures; line-end and math-script italic corrections and monospace/sans paragraph faces are applied; paragraph-level NFSS declarations (`\rmfamily`, `\sffamily`, `\ttfamily`, `\bfseries`, `\itshape`, `\texttt`, `\textsf`) select those faces and the `\fontfamily`/`\fontseries`/`\fontshape`/`\fontencoding`/`\selectfont` command forms plus legacy `\rm`/`\sf`/`\tt`/`\bf`/`\it`/`\sl`/`\up`/`\normalfont` declarations are parsed; inline `\textbf`/`\emph`/`\textit`/`\texttt`/`\textsf` groups and `{\bfseries ...}` declaration groups (including nesting) split a paragraph into styled runs, each shaped by its own TFM and painted with its own face; nested faces compose relatively (`\emph` inside bold yields bold italic via cmbxti10, `\emph` inside italic returns upright); styled runs are stored on the paragraph unit, so incremental edits rebuild them through `Engine::edit_runs` instead of flattening the paragraph back to one face; true family/series/shape switching remains open; route-D PDFs now embed Knuth's `cmr10.pfb` Type1 program as a simple font (PFB `Length1/2/3`, `/Encoding /Differences` from the program's built-in encoding, `/Widths` in 1000-unit text space from CMR10 advances) whenever the program covers every Roman character on the page, and fall back to the Liberation Type0 subset otherwise; `pdffonts` reports `Type 1 CMR10` and `pdftotext` still extracts the text. `Unit::paragraph` now builds its item stream with `layout_paragraph_with_font`, so CMR10 advances, kerns and ligatures drive paragraph widths; each glyph box also carries the TFM height/depth, and the painter emits 10pt glyphs and the Type0 `/W` array reports CMR10 advances, and ligature boxes paint their component letters, so `pdftotext` keeps word boundaries instead of inserting spaces between letters.
M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` becomes `/Annots /Subtype /Link /URI`; `DisplayItem::Special` injects raw content-stream operators. SVG previews show images as grey rectangles and specials as comments.
@@ -367,7 +367,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 347 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 529 tests (350 route-D unit, 34 engine binary unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
The crate currently has 347 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 532 tests (353 route-D unit, 33 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
### M0 incremental demo
+4 -3
View File
@@ -11,7 +11,9 @@ use std::sync::{Mutex, OnceLock};
use texrra_tex_core::cmr10::Cmr10Metrics;
use texrra_tex_core::math::{MathAtom, parse_math, split_math_lines};
use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_paper};
use texrra_tex_core::pdf::{
PageOrigin, display_lists_to_pdf_with_cm_type1, display_lists_to_pdf_with_paper,
};
use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit};
const SCALE: i64 = 65_536;
@@ -587,7 +589,7 @@ pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
list
})
.collect();
Ok(display_lists_to_pdf_with_paper(
Ok(display_lists_to_pdf_with_cm_type1(
&pages,
document.paper_width,
document.paper_height,
@@ -2034,7 +2036,6 @@ mod inline_tests {
assert_eq!(runs[1], (ParagraphFont::Sans, " and text".to_string()));
}
#[test]
#[test]
fn declaration_groups_switch_the_face() {
let runs = inline_runs("{\\bfseries bold} normal", ParagraphFont::Roman).expect("runs");