PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M7: draw new characters with the source font's own embedded program (#1760)
komo1iddin432d3172d4e1
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex d1ee5c656..555e608df 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -3640,3 +3640,76 @@ fn kept_rows_stay_in_place_when_rows_wrap_or_move_with_quote_operators() {}assert!(lines_of(&doc).len() > 3, "the edited row wrapped: {text}");}++/// A page whose `/F1` is Inter embedded as a simple WinAnsi TrueType font, under `base_font`.+fn embedded_program_page(content: &str, base_font: &str) -> Document {+ let mut doc = text_page(content);+ let program = doc.add(Object::Stream(Stream::flate(Dict::new(), include_bytes!("../../../assets/fonts/Inter-Regular.ttf"))));+ let mut descriptor = Dict::new();+ descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor"));+ descriptor.set(b"FontName".to_vec(), Object::name(base_font));+ descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));+ let mut font = Dict::new();+ font.set(b"Type".to_vec(), Object::name("Font"));+ font.set(b"Subtype".to_vec(), Object::name("TrueType"));+ font.set(b"BaseFont".to_vec(), Object::name(base_font));+ font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));+ font.set(b"FirstChar".to_vec(), Object::Int(32));+ font.set(b"LastChar".to_vec(), Object::Int(126));+ font.set(b"Widths".to_vec(), Object::Array((32..=126).map(|_| Object::Int(560)).collect()));+ font.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor));+ doc.set(pdfcraft_cos::ObjRef::new(5, 0), Object::Dict(font));+ reopen(&doc)+}++/// The font programs and subtypes of the page's font resources.+fn page_font_programs(doc: &Document) -> Vec<(Vec<u8>, Option<Vec<u8>>)> {+ let page = pdfcraft_model::pages(doc).remove(0);+ let resources = page.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();+ let fonts = resources.get(b"Font").and_then(|f| doc.resolve(f).as_dict().cloned()).unwrap_or_default();+ fonts+ .iter()+ .filter_map(|(_, f)| doc.resolve(f).as_dict().cloned())+ .map(|f| (f.name(b"Subtype").unwrap_or_default().to_vec(), pdfcraft_fonts::pdf::embedded_sfnt(doc, &f)))+ .collect()+}++#[test]+fn a_new_character_comes_from_the_source_fonts_own_embedded_program() {+ let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf");+ for (content, from, to) in [+ // One row (the single-style path) and a row of a two-row paragraph (the row editor's path).+ ("BT /F1 12 Tf 72 700 Td (Stable text) Tj ET", "text", "tőxt"),+ ("BT /F1 12 Tf 14 TL 72 700 Td (First row) Tj T* (Second row) Tj ET", "Second", "Sőcond"),+ ] {+ let mut doc = embedded_program_page(content, "Inter-Regular");+ let block = text::text_blocks(&doc, 0).unwrap()[0].clone();+ let draft = block.editor_text.replacen(from, to, 1);+ let edit = text::rewrite_block(&mut doc, 0, 0, Some(&draft), &text::BlockStyle::default()).unwrap();+ assert_eq!(edit.substituted, None, "{to}: no other family stands in");+ let doc = reopen(&doc);+ // The new character is its own run in the other resource, read back into the same word.+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].editor_text, draft, "{to}");+ let fonts = page_font_programs(&doc);+ assert!(fonts.iter().all(|(subtype, _)| subtype != b"Type3"), "{to}: no fallback glyphs");+ assert!(+ fonts.iter().any(|(subtype, program)| subtype == b"Type0" && program.as_deref() == Some(inter.as_slice())),+ "{to}: the source program draws it"+ );+ }+}++#[test]+fn a_subset_program_is_not_trusted_for_new_characters_and_the_error_names_the_character() {+ let mut doc = embedded_program_page("BT /F1 12 Tf 72 700 Td (Stable text) Tj ET", "ABCDEF+Inter-Regular");+ let before = page_content_bytes(&doc, 0);+ let result = text::rewrite_block(&mut doc, 0, 0, Some("Stable tőxt"), &text::BlockStyle::default());+ if pdfcraft_fonts::document_japanese_font().is_some() {+ eprintln!("built with craft-fonts: the fallback font draws the new character");+ assert!(result.is_ok(), "{result:?}");+ return;+ }+ let Err(EditError::Invalid(msg)) = result else { panic!("expected a clear error, got {result:?}") };+ assert!(msg.contains("ő (U+0151)") && msg.contains("Load font") && !msg.contains("Japanese"), "{msg}");+ assert_eq!(page_content_bytes(&doc, 0), before);+}diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rsindex 13233f71d..d434d01a9 100644--- a/crates/edit/src/text.rs+++ b/crates/edit/src/text.rs@@ -1166,6 +1166,22 @@ fn unicode_hex(ch: char) -> String {encoded.iter().map(|u| format!("{u:04X}")).collect()}+/// No font this build has can draw `text`. Only Japanese text is about the Japanese face: other+/// characters are missing from the paragraph's font, and choosing a font that has them works too.+fn no_fallback_font(text: &str) -> EditError {+ let japanese = |c: char| matches!(u32::from(c), 0x3000..=0x30FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0xFF00..=0xFFEF);+ if text.chars().any(japanese) {+ return no_japanese_font();+ }+ let Some(ch) = text.chars().find(|c| !c.is_whitespace() && !is_win_ansi_char(*c)) else { return no_japanese_font() };+ EditError::Invalid(format!(+ "the paragraph's font has no glyph for {ch} (U+{:04X}) and this build has no fallback font for it; \+ choose a font that has it (Load font… or Installed fonts…), or use an official release, which includes \+ PdfCraft's fallback fonts (to build them in, set CRAFT_FONTS_DIR to a craft-fonts checkout)",+ u32::from(ch)+ ))+}+/// This build has no Japanese face to draw replacement text with.fn no_japanese_font() -> EditError {EditError::Invalid(@@ -1230,7 +1246,7 @@ fn type3_font(// character. When none has them all, the best face reports the character it lacks. Hebrew// text keeps the Hebrew face and takes each character it lacks from the next face that has it.let face = if hebrew { faces.first().copied() } else { fallback_face(&faces, &chars, |face, ch| japanese_glyph_from(face, ch).is_ok()) }- .ok_or_else(no_japanese_font)?;+ .ok_or_else(|| no_fallback_font(text))?;let others: &[&CraftFont] = if hebrew { faces.get(1..).unwrap_or_default() } else { &[] };// Every outline is read before the document is touched, so a character that fails leaves it// as it was. Each font takes the next `per_font` characters; codes restart at 1 in each.@@ -1338,6 +1354,28 @@ fn type3_encode(fallback: &Type3Fallback, text: &str) -> Option<Vec<(String, Vecruns.into_iter().map(|(font, bytes)| Some((fallback.names.get(font)?.clone(), bytes))).collect()}+/// The source font's own TrueType/OpenType program, when the document embeds a complete one whose+/// licence allows editable embedding. A subset (an `ABCDEF+` name) is left out: a character can keep+/// its mapping there after the subsetter dropped its outline.+fn source_program(doc: &Document, fonts: &Dict, name: &str) -> Option<Vec<u8>> {+ let font = fonts.get(name.as_bytes()).and_then(|f| doc.resolve(f).as_dict().cloned())?;+ let base = Metrics::from_dict(doc, &font).base_font;+ if base.split_once('+').is_some_and(|(tag, _)| tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase())) {+ return None;+ }+ let bytes = pdfcraft_fonts::pdf::embedded_sfnt(doc, &font)?;+ pdfcraft_fonts::embedding::validate(&bytes).is_ok().then_some(bytes)+}++/// Whether `text` has characters `line`'s font can't encode that its own program can draw.+fn source_program_completes(doc: &Document, fonts: &Dict, line: &TextLine, text: &str) -> bool {+ let Some(metrics) = fonts.get(line.font.as_bytes()).and_then(|f| doc.resolve(f).as_dict().cloned()).map(|f| Metrics::from_dict(doc, &f)) else {+ return false;+ };+ let missing: String = text.chars().filter(|c| !c.is_whitespace() && !source_encodes(&metrics, &c.to_string())).collect();+ !missing.is_empty() && source_program(doc, fonts, &line.font).is_some_and(|bytes| pdfcraft_fonts::embedding::covers(&bytes, &missing))+}+/// A subset may contain all the letters but no space glyph: producers use another subset/// or a positioning operator for spaces. Do the same instead of substituting the whole font.fn source_encodes(metrics: &Metrics, text: &str) -> bool {@@ -1722,6 +1760,7 @@ pub(crate) fn rewrite_block_with_limit(|| pdfcraft_fonts::source_shaping::required(draft)|| !pdfcraft_fonts::embedding::matching_faces(&b.base_font).is_empty()}) || registered_face+ || text.is_some_and(|draft| source_program_completes(doc, &fonts_res, first, draft))|| b.rows.iter().any(|row| row.len() > 1)|| members.iter().any(|line| line.font != first.font || line.size != first.size || line.color != first.color))&& style.family.is_none()diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rsindex 614349681..59e160702 100644--- a/crates/edit/src/text_regions.rs+++ b/crates/edit/src/text_regions.rs@@ -384,6 +384,7 @@ pub(super) fn rewrite_styled_block(let mut substituted = None;let mut fallback_names: std::collections::BTreeMap<(String, char), String> = std::collections::BTreeMap::new();let mut full_faces: HashMap<String, String> = HashMap::new();+ let mut programs: HashMap<String, Option<std::sync::Arc<Vec<u8>>>> = HashMap::new();for (range, index) in styled_spans {let source = lines.get(index).unwrap_or(first);for ch in draft.get(range).unwrap_or_default().chars() {@@ -419,6 +420,28 @@ pub(super) fn rewrite_styled_block(full_faces.insert(key, name.clone());name}+ } else if let Some(bytes) = programs+ .entry(source.font.clone())+ .or_insert_with(|| source_program(doc, &fonts, &source.font).map(std::sync::Arc::new))+ .clone()+ .filter(|bytes| pdfcraft_fonts::embedding::covers(bytes, &s))+ {+ // The document's own complete program of this font has the glyph: draw it with+ // that face rather than another family's fallback.+ let key = format!("source {}", source.font);+ if let Some(name) = full_faces.get(&key) {+ name.clone()+ } else {+ let family = pdfcraft_fonts::embedding::names(&bytes).map_or_else(|_| source.base_font.clone(), |(family, _)| family);+ let name = pdfcraft_fonts::embedding::embed(doc, &mut fonts, &bytes, &family).map_err(EditError::Invalid)?;+ let font = fonts+ .get(name.as_bytes())+ .and_then(|f| doc.dict(f))+ .ok_or_else(|| EditError::Invalid("the source font could not be loaded".into()))?;+ metrics.insert(name.clone(), Metrics::from_dict(doc, &font));+ full_faces.insert(key, name.clone());+ name+ }} else {let family = source_family(&source.base_font);if needs_type3(&s) {diff --git a/docs/editing-existing-text.md b/docs/editing-existing-text.mdindex 07104d79e..67a3a4f87 100644--- a/docs/editing-existing-text.md+++ b/docs/editing-existing-text.md@@ -15,7 +15,10 @@ reconstructed from a glyph the PDF does not contain. **Load font…** imports anembeddable standalone `.ttf` or `.otf` face. **Installed fonts…** discovers eligible user-installedfaces on request, off the UI thread; the document-font menu selects resources already on thepage. Select **Keep source fonts** to preserve each run's original face. A matching full face-completes its subsets automatically, including new Chinese characters. Choosing another face+completes its subsets automatically, including new Chinese characters. When the PDF itself embeds+the complete program of a paragraph's font (not a subset) and its licence allows editable+embedding, a character the font's encoding can't show is drawn with that same program. A+character no available face has is refused with an error that names it. Choosing another faceis explicit. Fonts with restricted embedding, unsupported collections, excluded families orno open-licence declaration are refused. Interface fallback fonts are never exported.