diff --git a/README.md b/README.md index 4278863..8c8128c 100644 --- a/README.md +++ b/README.md @@ -576,7 +576,7 @@ default until the new core reaches layout parity. See `docs/TEX_CORE.md`. The first M7 service integration is available as `POST /api/route-d/preview`, with PDF export at `POST /api/route-d/pdf`. It accepts blank-line-separated source with a small `\section`/`\textbf`/`\emph`/display-math/list subset, lays it out with the route-D page builder, and returns the v1-compatible preview shape plus per-page hashes and -SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. `Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. The v1 `/preview` and project APIs are unchanged and remain the default. +SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. Embedded text fonts are subset per document to the glyphs actually used (retaining glyph IDs and composite components), and each subset carries a ToUnicode CMap covering its used characters. `Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. The v1 `/preview` and project APIs are unchanged and remain the default. Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline. The web client exposes this as the `引擎: v1` / `引擎: Route-D` toggle in the preview toolbar; the choice is stored in `localStorage` and switches both the preview request and `POST /api/projects/{id}/pdf`, since the PDF handler honors the same `engine=route-d` query. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages; text edits and structural edits with an unchanged paragraph prefix rebuild from the first difference through `Engine::relayout_from`, reusing the sealed pages before it, while edits without a reusable prefix fall back to a full layout. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D document and returns the same page list plus `changedPages` and diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index a0d91d9..88362fe 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -3,6 +3,7 @@ pub mod math; pub mod paragraph; pub mod pdf; pub mod render; +mod subset; pub mod tfm; pub use cmr10::Cmr10Metrics; @@ -2852,6 +2853,27 @@ mod tests { assert!(text.trim_end().ends_with("%%EOF")); } + #[test] + fn pdf_subset_keeps_only_used_glyphs() { + let document = Document::new(400, vec![Unit::paragraph(1, "caf\u{e9}")]); + let engine = Engine::layout(&document); + let list = engine.pages()[0].display_list(); + let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536); + let text = String::from_utf8_lossy(&pdf); + let length1 = text + .split("/Length1 ") + .nth(1) + .and_then(|rest| rest.split_whitespace().next()) + .and_then(|value| value.parse::().ok()) + .expect("FontFile2 /Length1"); + assert!( + length1 < crate::pdf::full_face_size(crate::render::FontFace::Roman), + "subset {length1} should be smaller than the full face {}", + crate::pdf::full_face_size(crate::render::FontFace::Roman) + ); + assert!(text.contains("/Filter /FlateDecode")); + } + #[test] fn pdf_embeds_only_the_used_faces() { let document = Document::new(400, vec![Unit::paragraph(1, "roman only")]); diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 8b1c7ce..5fb57bf 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -4,6 +4,7 @@ //! and raw-RGB image XObjects. use std::collections::BTreeMap; +use std::collections::BTreeSet; use std::io::Write as _; use std::sync::OnceLock; @@ -136,6 +137,11 @@ fn face(font: FontFace, faces: &'static [PdfFace; 6]) -> &'static PdfFace { &faces[font as usize] } +#[allow(dead_code)] +pub(crate) fn full_face_size(font: FontFace) -> usize { + FULL_FACES[font as usize].bytes.len() +} + fn face_font(face: &'static PdfFace) -> &'static Font<'static> { face.font .get_or_init(|| Font::from_bytes(face.bytes).expect("embedded face")) @@ -151,15 +157,19 @@ fn glyph_hex(face: &'static PdfFace, text: &str) -> String { out } -fn tounicode_cmap(face: &'static PdfFace) -> Vec { +fn tounicode_cmap(face: &'static PdfFace, characters: &BTreeSet) -> Vec { let font = face_font(face); let mut map = String::from( "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n /CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n 1 begincodespacerange\n<0000> \nendcodespacerange\n", ); - let chars: Vec = (0x20u8..=0x7e).map(char::from).collect(); - map.push_str(&format!("{} beginbfchar\n", chars.len())); - for character in chars { - let id = font.glyph(character).id().0; + let mut entries = std::collections::BTreeMap::new(); + for character in characters { + if (*character as u32) <= 0xffff { + entries.insert(font.glyph(*character).id().0, *character); + } + } + map.push_str(&format!("{} beginbfchar\n", entries.len())); + for (id, character) in entries { map.push_str(&format!("<{id:04X}> <{:04X}>\n", character as u32)); } map.push_str("endbfchar\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n"); @@ -327,10 +337,12 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()); objects.push(Vec::new()); // pages object filled below let mut used_faces = [false; 6]; + let mut used_chars: [BTreeSet; 6] = Default::default(); for page in pages { for item in &page.items { - if let DisplayItem::Text { font, .. } = item { + if let DisplayItem::Text { font, text, .. } = item { used_faces[*font as usize] = true; + used_chars[*font as usize].extend(text.chars()); } } } @@ -373,17 +385,18 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec ) .into_bytes(), ); - let compressed = deflate(face.bytes); + let font_bytes = crate::subset::subset_font(face.bytes, face_font(face), &used_chars[slot]); + let compressed = deflate(&font_bytes); let mut font_stream = format!( "<< /Length {} /Length1 {} /Filter /FlateDecode >>\nstream\n", compressed.len(), - face.bytes.len() + font_bytes.len() ) .into_bytes(); font_stream.extend_from_slice(&compressed); font_stream.extend_from_slice(b"\nendstream"); objects.push(font_stream); - let cmap = tounicode_cmap(face); + let cmap = tounicode_cmap(face, &used_chars[slot]); let compressed_cmap = deflate(&cmap); let mut cmap_object = format!( "<< /Length {} /Filter /FlateDecode >>\nstream\n", diff --git a/crates/texrra-tex-core/src/subset.rs b/crates/texrra-tex-core/src/subset.rs new file mode 100644 index 0000000..4b64eed --- /dev/null +++ b/crates/texrra-tex-core/src/subset.rs @@ -0,0 +1,287 @@ +//! Minimal TrueType `glyf` subsetting for embedded PDF fonts. +//! +//! Glyph IDs deliberately stay unchanged: the PDF Type0 font uses Identity-H +//! with CID = glyph ID, and `CIDToGIDMap /Identity`, so a subset may only +//! replace unused glyph outlines with empty ones. Other tables are copied +//! verbatim and only the SFNT offsets/checksums are rebuilt. + +use std::collections::BTreeSet; + +use rusttype::Font; + +fn be_u16(bytes: &[u8], offset: usize) -> u16 { + u16::from_be_bytes([bytes[offset], bytes[offset + 1]]) +} + +fn be_u32(bytes: &[u8], offset: usize) -> u32 { + u32::from_be_bytes([ + bytes[offset], + bytes[offset + 1], + bytes[offset + 2], + bytes[offset + 3], + ]) +} + +fn be_i16(bytes: &[u8], offset: usize) -> i16 { + i16::from_be_bytes([bytes[offset], bytes[offset + 1]]) +} + +fn table_checksum(data: &[u8]) -> u32 { + let mut sum = 0_u32; + for chunk in data.chunks(4) { + let mut word = [0_u8; 4]; + word[..chunk.len()].copy_from_slice(chunk); + sum = sum.wrapping_add(u32::from_be_bytes(word)); + } + sum +} + +struct Table { + tag: [u8; 4], + data: Vec, +} + +/// Component glyph IDs referenced by a composite glyph. +fn components(glyph: &[u8]) -> Vec { + if glyph.len() < 10 || be_i16(glyph, 0) >= 0 { + return Vec::new(); + } + let mut result = Vec::new(); + let mut offset = 10; + loop { + if offset + 4 > glyph.len() { + break; + } + let flags = be_u16(glyph, offset); + let index = be_u16(glyph, offset + 2); + result.push(index); + offset += 4; + offset += if flags & 0x0001 != 0 { 4 } else { 2 }; + if flags & 0x0008 != 0 { + offset += 2; + } else if flags & 0x0040 != 0 { + offset += 4; + } else if flags & 0x0080 != 0 { + offset += 8; + } + if flags & 0x0020 == 0 { + break; + } + } + result +} + +/// Subset a TrueType font to `characters`, preserving glyph IDs. +/// +/// The returned font is still a valid SFNT file. Unused glyphs have empty +/// outlines, which is enough for PDF viewers because the page only references +/// used CIDs. +pub fn subset_font(bytes: &[u8], font: &Font, characters: &BTreeSet) -> Vec { + if bytes.len() < 12 { + return bytes.to_vec(); + } + let num_tables = usize::from(be_u16(bytes, 4)); + let mut tables = Vec::with_capacity(num_tables); + for index in 0..num_tables { + let record = 12 + index * 16; + if record + 16 > bytes.len() { + return bytes.to_vec(); + } + let mut tag = [0_u8; 4]; + tag.copy_from_slice(&bytes[record..record + 4]); + let offset = be_u32(bytes, record + 8) as usize; + let length = be_u32(bytes, record + 12) as usize; + if offset + length > bytes.len() { + return bytes.to_vec(); + } + tables.push(Table { + tag, + data: bytes[offset..offset + length].to_vec(), + }); + } + + let Some(head_index) = tables.iter().position(|table| &table.tag == b"head") else { + return bytes.to_vec(); + }; + let Some(loca_index) = tables.iter().position(|table| &table.tag == b"loca") else { + return bytes.to_vec(); + }; + let Some(glyf_index) = tables.iter().position(|table| &table.tag == b"glyf") else { + return bytes.to_vec(); + }; + let Some(maxp_index) = tables.iter().position(|table| &table.tag == b"maxp") else { + return bytes.to_vec(); + }; + if tables[head_index].data.len() < 54 || tables[maxp_index].data.len() < 6 { + return bytes.to_vec(); + } + + let num_glyphs = usize::from(be_u16(&tables[maxp_index].data, 4)); + let long_loca = be_i16(&tables[head_index].data, 50) != 0; + let loca_len = if long_loca { + (num_glyphs + 1) * 4 + } else { + (num_glyphs + 1) * 2 + }; + if tables[loca_index].data.len() < loca_len { + return bytes.to_vec(); + } + + let mut offsets = Vec::with_capacity(num_glyphs + 1); + for index in 0..=num_glyphs { + let value = if long_loca { + be_u32(&tables[loca_index].data, index * 4) as usize + } else { + usize::from(be_u16(&tables[loca_index].data, index * 2)) * 2 + }; + offsets.push(value); + } + let glyf = &tables[glyf_index].data; + + let mut used = BTreeSet::new(); + used.insert(0_u16); + for character in characters { + used.insert(font.glyph(*character).id().0 as u16); + } + // Composite glyphs reference component glyphs by ID. Keep those too, or + // the subsetted outline points at empty glyphs. + loop { + let mut added = false; + for glyph in used.clone() { + let index = usize::from(glyph); + if index >= num_glyphs { + continue; + } + let start = offsets[index]; + let end = offsets[index + 1]; + if end <= start || end > glyf.len() { + continue; + } + for component in components(&glyf[start..end]) { + if used.insert(component) { + added = true; + } + } + } + if !added { + break; + } + } + + let mut new_glyf = Vec::new(); + let mut new_loca = Vec::with_capacity(num_glyphs + 1); + for glyph in 0..num_glyphs { + let start = offsets[glyph]; + let end = offsets[glyph + 1]; + new_loca.push(new_glyf.len()); + if used.contains(&(glyph as u16)) && end > start && end <= glyf.len() { + new_glyf.extend_from_slice(&glyf[start..end]); + } + while new_glyf.len() % 2 != 0 { + new_glyf.push(0); + } + } + new_loca.push(new_glyf.len()); + if long_loca { + let mut bytes = Vec::with_capacity(new_loca.len() * 4); + for offset in &new_loca { + bytes.extend_from_slice(&(*offset as u32).to_be_bytes()); + } + tables[loca_index].data = bytes; + } else { + if new_glyf.len() / 2 > usize::from(u16::MAX) { + return bytes.to_vec(); + } + let mut bytes = Vec::with_capacity(new_loca.len() * 2); + for offset in &new_loca { + bytes.extend_from_slice(&((*offset / 2) as u16).to_be_bytes()); + } + tables[loca_index].data = bytes; + } + tables[glyf_index].data = new_glyf; + + // The head checksum adjustment must be zero while table checksums are + // computed. + tables[head_index].data[8..12].fill(0); + + let mut output = Vec::new(); + output.extend_from_slice(&bytes[..12]); + let directory_len = 12 + tables.len() * 16; + let mut data_offset = directory_len; + let mut records = Vec::with_capacity(tables.len()); + for table in &tables { + let checksum = table_checksum(&table.data); + records.push((table.tag, checksum, data_offset, table.data.len())); + data_offset += table.data.len(); + data_offset = data_offset.div_ceil(4) * 4; + } + for (tag, checksum, offset, length) in &records { + output.extend_from_slice(tag); + output.extend_from_slice(&checksum.to_be_bytes()); + output.extend_from_slice(&(*offset as u32).to_be_bytes()); + output.extend_from_slice(&(*length as u32).to_be_bytes()); + } + for table in &tables { + output.extend_from_slice(&table.data); + while output.len() % 4 != 0 { + output.push(0); + } + } + + let adjustment = 0xB1B0_AFBA_u32.wrapping_sub(table_checksum(&output)); + if let Some((_, _, offset, _)) = records.iter().find(|(tag, _, _, _)| tag == b"head") { + output[offset + 8..offset + 12].copy_from_slice(&adjustment.to_be_bytes()); + } + output +} + +#[cfg(test)] +mod tests { + use super::*; + + fn table<'a>(font: &'a [u8], tag: &[u8; 4]) -> &'a [u8] { + let count = usize::from(be_u16(font, 4)); + for index in 0..count { + let record = 12 + index * 16; + if &font[record..record + 4] == tag { + let offset = be_u32(font, record + 8) as usize; + let length = be_u32(font, record + 12) as usize; + return &font[offset..offset + length]; + } + } + panic!("missing table"); + } + + #[test] + fn composite_components_survive_subsetting() { + let bytes = include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"); + let font = Font::from_bytes(&bytes[..]).expect("font"); + let mut characters = BTreeSet::new(); + characters.insert('\u{e9}'); + let subset = subset_font(bytes, &font, &characters); + + let maxp = table(&subset, b"maxp"); + let num_glyphs = usize::from(be_u16(maxp, 4)); + let head = table(&subset, b"head"); + let long_loca = be_i16(head, 50) != 0; + let loca = table(&subset, b"loca"); + let glyf = table(&subset, b"glyf"); + let offset = |glyph: usize| { + if long_loca { + be_u32(loca, glyph * 4) as usize + } else { + usize::from(be_u16(loca, glyph * 2)) * 2 + } + }; + let glyph_len = |glyph: usize| { + assert!(glyph < num_glyphs); + offset(glyph + 1) - offset(glyph) + }; + + let composite = font.glyph('\u{e9}').id().0 as usize; + let component = font.glyph('e').id().0 as usize; + assert!(glyph_len(composite) > 0, "accented glyph has no outline"); + assert!(glyph_len(component) > 0, "component glyph was dropped"); + assert!(glyf.len() < 4096, "subset kept too much glyph data"); + } +} diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 8fc251a..62c781a 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -238,7 +238,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; interpreted `\output` absent | | 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; only faces used on a page are embedded, and ASCII documents use the 110-glyph minimal tier (one-page Roman PDF is about 21 KB); no Base-14 dependency; SVG carries family/weight/style | +| 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 | | 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 | @@ -270,7 +270,7 @@ M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row hei Math coverage includes fractions/roots, scripts, `\left...\right` with body-scaled delimiters, `\middle`, `\big`/`\Big`/`\bigg`/`\Bigg` and their `l`/`r` forms, control-sequence delimiters, accents (dot/check/breve/acute/grave/ring), `\text`/`\mathrm`, `\overbrace`/`\underbrace`, `\overset`/`\underset`, `\binom`, `\cancel`/`\bcancel`/`\xcancel`, `\bmod`/`\pmod`, fence symbols, `\operatorname*` and `\mathop` limits. -The crate currently has 161 unit tests plus three route-D integration tests. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 261 tests (161 route-D unit, 3 route-D integration, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 2 binary units). v1 remains the live server path. +The crate currently has 163 unit tests plus three route-D integration tests. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 263 tests (163 route-D unit, 3 route-D integration, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 2 binary units). v1 remains the live server path. ### M0 incremental demo @@ -297,7 +297,7 @@ deliberately open rather than approximated: - **M1**: TeX tolerance/demerits are still fitted to a few fixtures; multi-width pdfTeX line breaks and full hyphenation demerits are not reproduced generally. -- **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. only used text faces embed Liberation Serif/Mono as Type0/Identity-H with width arrays (ASCII uses the minimal tier); the FontFile2 and ToUnicode streams use Flate compression; ff/fi/fl/ffi/ffl ligatures come from TFM, and CMR10 italic corrections are applied at line ends; full NFSS family switching is not implemented. +- **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. only used text faces embed Liberation Serif/Mono as Type0/Identity-H; each face is subset to the glyphs actually used (composite components included, glyph IDs retained); FontFile2 and ToUnicode streams use Flate compression; the ToUnicode CMap follows the used characters; ff/fi/fl/ffi/ffl ligatures come from TFM, and CMR10 italic corrections are applied at line ends; full NFSS family switching is not implemented. - **M6**: `\output`, `\insert`, mark/float output policies, class-file execution and math limit policies are only partially modeled; `OutputRoutine::wants_break` can force a page break between units, and insertion material is stacked by class from the page bottom; `\output` is still Rust code rather than interpreted tokens. - Page hashes cover rendered items/insertions/marks/floats, not source-dependency