Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M7: pick a Japanese fallback face that has every glyph of the edited text (#384) (#472)

MarekSpodBiedryff496918a173
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs
index 0a0830fda..6711ba4a1 100644
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@ -414,6 +414,28 @@ fn japanese_fallback_reports_the_face_after_save_and_reopen() {
}
}
+#[test]
+fn cyrillic_in_a_serif_line_falls_back_to_a_face_that_has_it() {
+ if without_craft_fonts("cyrillic_in_a_serif_line_falls_back_to_a_face_that_has_it") {
+ return;
+ }
+ let replacement = "Привет, world";
+ let has_all = |f: &pdfcraft_fonts::CraftFont| replacement.chars().all(|ch| pdfcraft_fonts::japanese_glyph_from(f, ch).is_ok());
+ if !pdfcraft_fonts::CRAFT_FONTS.iter().any(|f| f.covers("Jpan") && has_all(f)) {
+ eprintln!("skipping: no Japanese fallback face has Cyrillic");
+ return;
+ }
+ for paragraph in [false, true] {
+ let mut doc = styled_text_page("Times-Roman");
+ if paragraph {
+ text::replace_block(&mut doc, 0, 0, replacement).unwrap();
+ } else {
+ text::replace_line(&mut doc, 0, 0, replacement).unwrap();
+ }
+ assert_eq!(text::text_lines(&reopen(&doc), 0).unwrap()[0].text, replacement);
+ }
+}
+
#[test]
fn japanese_paragraph_uses_unicode_type3_fallback() {
if without_craft_fonts("japanese_paragraph_uses_unicode_type3_fallback") {
diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs
index d8a2dd933..bf74edfb5 100644
--- a/crates/edit/src/text.rs
+++ b/crates/edit/src/text.rs
@@ -570,9 +570,13 @@ fn no_japanese_font() -> EditError {
)
}
+/// The first of `faces` (best match first) that has a glyph for every one of `chars`, else the first.
+fn fallback_face<'a>(faces: &[&'a CraftFont], chars: &[char], has_glyph: impl Fn(&CraftFont, char) -> bool) -> Option<&'a CraftFont> {
+ faces.iter().copied().find(|face| chars.iter().all(|ch| has_glyph(face, *ch))).or_else(|| faces.first().copied())
+}
+
fn type3_font(doc: &mut Document, fonts_res: &mut Dict, text: &str, family: crate::added::Family, bold: bool) -> Result<Type3Fallback, EditError> {
- let face = pdfcraft_fonts::document_japanese_font_for_style(family == crate::added::Family::Times, bold).ok_or_else(no_japanese_font)?;
- let family = face.family;
+ let faces = pdfcraft_fonts::document_japanese_fonts_for_style(family == crate::added::Family::Times, bold);
let mut chars = Vec::new();
for ch in text.chars() {
if !chars.contains(&ch) {
@@ -585,6 +589,10 @@ fn type3_font(doc: &mut Document, fonts_res: &mut Dict, text: &str, family: crat
if chars.is_empty() {
return Err(EditError::Invalid("replacement text is empty".into()));
}
+ // The faces differ in coverage (e.g. of Cyrillic), so use the best face that has every
+ // character. When none has them all, the best face reports the character it lacks.
+ let face = fallback_face(&faces, &chars, |face, ch| japanese_glyph_from(face, ch).is_ok()).ok_or_else(no_japanese_font)?;
+ let family = face.family;
let mut codes = Vec::with_capacity(chars.len());
let mut charprocs = Dict::new();
let mut widths = Vec::with_capacity(chars.len());
@@ -1138,4 +1146,20 @@ mod tests {
assert_eq!(wrap("A\u{2028}B C", 3.0, width), ["A B", "C"]);
assert_eq!(wrap(" \tA B\r\nC ", 3.0, width), ["A B", "C"]);
}
+
+ #[test]
+ fn fallback_face_moves_on_when_the_best_face_lacks_a_character() {
+ static JPAN: &[&str] = &["Jpan"];
+ let mincho = CraftFont { family: "Mincho", style: "Regular", scripts: JPAN, bytes: b"" };
+ let gothic = CraftFont { family: "Gothic", style: "Regular", scripts: JPAN, bytes: b"" };
+ let faces = [&mincho, &gothic];
+ // Only the Gothic face has the Cyrillic letter.
+ let has = |face: &CraftFont, ch: char| ch.is_ascii() || face.family == "Gothic";
+ assert_eq!(fallback_face(&faces, &['a', 'ф'], has).map(|f| f.family), Some("Gothic"));
+ // Characters the best face has keep it.
+ assert_eq!(fallback_face(&faces, &['a', 'b'], has).map(|f| f.family), Some("Mincho"));
+ // No face has them all: the best face stays, and names the missing glyph.
+ assert_eq!(fallback_face(&faces, &['a', 'ф'], |_, ch| ch.is_ascii()).map(|f| f.family), Some("Mincho"));
+ assert!(fallback_face(&[], &['a'], has).is_none());
+ }
}
diff --git a/crates/fonts/README.md b/crates/fonts/README.md
index 133b44ab1..0f59dd6b4 100644
--- a/crates/fonts/README.md
+++ b/crates/fonts/README.md
@@ -33,6 +33,9 @@ set). Without that variable `CRAFT_FONTS` is empty and everything below copes:
keep Mincho. Type 3 paths and advances both come from that selected face. Missing weights
fall back to a real Regular face, never synthetic bold; no italic face is supplied. The
default `document_japanese_font` / `japanese_glyph` APIs still use regular document Mincho.
+- `document_japanese_fonts_for_style`: every `Jpan` face in that order of preference, so the
+ editor can use the first one that has all of the replacement's glyphs (the faces differ in
+ coverage, e.g. of Cyrillic).
- `SHIPPORI_MINCHO`: Shippori Mincho's bytes, or `None`.
Generated Japanese Type 3 fonts record the fallback face's family and style in an indirect
diff --git a/crates/fonts/src/craft.rs b/crates/fonts/src/craft.rs
index 322d9b2f8..84bc0d04c 100644
--- a/crates/fonts/src/craft.rs
+++ b/crates/fonts/src/craft.rs
@@ -96,22 +96,36 @@ pub fn document_japanese_font_for_style(serif: bool, bold: bool) -> Option<&'sta
document_face(CRAFT_FONTS, serif, bold)
}
+/// Every `Jpan` face that can stand in for the document text, the best match for the style first
+/// (the face [`document_japanese_font_for_style`] returns), then the others. Not every face has
+/// every glyph (their coverage of e.g. Cyrillic differs), so a caller can move on to the next one.
+/// Empty without craft-fonts.
+pub fn document_japanese_fonts_for_style(serif: bool, bold: bool) -> Vec<&'static CraftFont> {
+ document_faces(CRAFT_FONTS, serif, bold)
+}
+
fn document_face(faces: &[CraftFont], serif: bool, bold: bool) -> Option<&CraftFont> {
+ document_faces(faces, serif, bold).into_iter().next()
+}
+
+fn document_faces(faces: &[CraftFont], serif: bool, bold: bool) -> Vec<&CraftFont> {
let jpan = || faces.iter().filter(|f| f.covers("Jpan"));
+ let mut preferred = Vec::new();
if !serif {
let style = if bold { "Bold" } else { "Regular" };
- if let Some(face) = jpan()
- .find(|f| f.family == "BIZ UDPGothic" && f.style == style)
- .or_else(|| jpan().find(|f| f.family == "BIZ UDPGothic" && f.style == "Regular"))
- {
- return Some(face);
+ preferred.extend(jpan().find(|f| f.family == "BIZ UDPGothic" && f.style == style));
+ preferred.extend(jpan().find(|f| f.family == "BIZ UDPGothic" && f.style == "Regular"));
+ }
+ for family in ["Shippori Mincho", "BIZ UDMincho"] {
+ preferred.extend(jpan().find(|f| f.family == family && f.style == "Regular"));
+ }
+ let mut out: Vec<&CraftFont> = Vec::new();
+ for face in preferred.into_iter().chain(jpan().filter(|f| f.style == "Regular")).chain(jpan()) {
+ if !out.iter().any(|f| std::ptr::eq(*f, face)) {
+ out.push(face);
}
}
- ["Shippori Mincho", "BIZ UDMincho"]
- .iter()
- .find_map(|family| jpan().find(|f| f.family == *family && f.style == "Regular"))
- .or_else(|| jpan().find(|f| f.style == "Regular"))
- .or_else(|| jpan().next())
+ out
}
const fn str_eq(a: &str, b: &str) -> bool {
@@ -191,6 +205,11 @@ mod tests {
assert_eq!(document_face(&faces, true, true).unwrap().bytes, b"serif");
assert_eq!(document_face(&faces[..2], false, true).unwrap().bytes, b"sans");
assert_eq!(document_face(&faces[..1], false, true).unwrap().bytes, b"serif");
+ // Every Japanese face is a candidate, the style's match first and none twice.
+ let order: Vec<&[u8]> = document_faces(&faces, false, true).iter().map(|f| f.bytes).collect();
+ assert_eq!(order, [b"bold".as_slice(), b"sans", b"serif"]);
+ let order: Vec<&[u8]> = document_faces(&faces, true, false).iter().map(|f| f.bytes).collect();
+ assert_eq!(order, [b"serif".as_slice(), b"sans", b"bold"]);
assert!(document_face(&faces[3..], false, true).is_none());
assert!(document_face(&[], false, true).is_none());
}
diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs
index 9c3ce6d14..1dc6ced27 100644
--- a/crates/fonts/src/lib.rs
+++ b/crates/fonts/src/lib.rs
@@ -10,8 +10,8 @@ mod encodings;
pub mod pdf;
mod script;
pub use craft::{
- CRAFT_FONTS, CraftFont, SHIPPORI_MINCHO, document_japanese_font, document_japanese_font_for_style, ui_arabic_fonts, ui_chinese_fonts,
- ui_cjk_fonts, ui_japanese_fonts, ui_telugu_fonts,
+ CRAFT_FONTS, CraftFont, SHIPPORI_MINCHO, document_japanese_font, document_japanese_font_for_style, document_japanese_fonts_for_style,
+ ui_arabic_fonts, ui_chinese_fonts, ui_cjk_fonts, ui_japanese_fonts, ui_telugu_fonts,
};
pub use script::{GlyphError, GlyphOutline, MAX_SIGNATURE_CHARS, ScriptOutline, japanese_glyph, japanese_glyph_from, script_outline};