diff --git a/crates/pdf/src/arabic.rs b/crates/pdf/src/arabic.rs index 96fd2de38b..d072f64c75 100644 --- a/crates/pdf/src/arabic.rs +++ b/crates/pdf/src/arabic.rs @@ -10,7 +10,7 @@ use skrifa::{ }; use unicode_bidi::BidiInfo; -use crate::{CID_FONT, Error, Font, TextDirection, n, needs_cid, pdf_string, pdf_utf16_string}; +use crate::{CID_FONT, EXT_FONT, Error, FONT_COUNT, Font, Run, TextDirection, n, pdf_ext_string, pdf_string, pdf_utf16_string, run_kind}; include!(concat!(env!("OUT_DIR"), "/arabic_fonts.rs")); @@ -197,9 +197,25 @@ fn has_weight_axis(bytes: &[u8]) -> bool { #[derive(Debug)] pub(crate) enum Item { - Glyph { id: u32, x: f32, y: f32, source: String }, - Latin { text: String, x: f32 }, - Cid { text: String, x: f32 }, + Glyph { + id: u32, + x: f32, + y: f32, + source: String, + }, + Latin { + text: String, + x: f32, + }, + /// Latin Extended-A letters WinAnsiEncoding lacks, set in the face's extended font. + Ext { + text: String, + x: f32, + }, + Cid { + text: String, + x: f32, + }, } pub(crate) struct Layout { @@ -250,10 +266,14 @@ pub(crate) fn layout(font: Font, text: &str, direction: TextDirection) -> Result if !embedded { let part = part.chars().map(|ch| if is_line_break(ch) { ' ' } else { ch }); let part: Vec = if rtl { part.rev().map(mirror_ansi).collect() } else { part.collect() }; - for run in part.chunk_by(|a, b| needs_cid(*a) == needs_cid(*b)) { + for run in part.chunk_by(|a, b| run_kind(*a) == run_kind(*b)) { let (text, x) = (run.iter().collect(), layout.width); layout.width += run.iter().map(|&ch| f32::from(font.char_width(ch))).sum::(); - layout.items.push(if run.first().is_some_and(|&ch| needs_cid(ch)) { Item::Cid { text, x } } else { Item::Latin { text, x } }); + layout.items.push(match run.first().map(|&ch| run_kind(ch)) { + Some(Run::Cid) => Item::Cid { text, x }, + Some(Run::Ext) => Item::Ext { text, x }, + _ => Item::Latin { text, x }, + }); } continue; } @@ -325,7 +345,7 @@ pub(crate) fn vertical_extents(font: Font, text: &str, direction: TextDirection) ascent = ascent.max(y + top); descent = descent.max(-y - bottom); } - Item::Latin { .. } | Item::Cid { .. } => { + Item::Latin { .. } | Item::Ext { .. } | Item::Cid { .. } => { ascent = ascent.max(800.0); descent = descent.max(220.0); } @@ -410,6 +430,8 @@ pub(crate) struct Subset { bytes: usize, /// Some text on the page set a run in the CJK CID font, so the page must declare it. pub(crate) uses_cid: bool, + /// The faces (by [`Font::index`]) whose Latin Extended-A font some text on the page used. + pub(crate) uses_ext: [bool; FONT_COUNT], } struct Glyph { @@ -479,6 +501,19 @@ impl Subset { Item::Latin { text, x } => { let _ = writeln!(out, "/F{} {} Tf 1 0 0 1 {} 0 Tm {} Tj", font.index() + 1, n(size), n(x * size / 1000.0), pdf_string(&text)); } + Item::Ext { text, x } => { + if let Some(used) = self.uses_ext.get_mut(font.index()) { + *used = true; + } + let _ = writeln!( + out, + "/F{} {} Tf 1 0 0 1 {} 0 Tm {} Tj", + EXT_FONT + font.index() + 1, + n(size), + n(x * size / 1000.0), + pdf_ext_string(&text) + ); + } Item::Cid { text, x } => { self.uses_cid = true; let _ = writeln!(out, "/F{} {} Tf 1 0 0 1 {} 0 Tm {} Tj", CID_FONT + 1, n(size), n(x * size / 1000.0), pdf_utf16_string(&text)); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 8dc9cf3399..a329c10ef9 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -1,7 +1,9 @@ //! PDF 1.7 drawing for GridCraft print/export, with shared object and xref framing. //! //! - The 14 standard fonts (no embedding) with WinAnsiEncoding, plus approximate width tables -//! ([`text_width`]) so callers can measure, align and wrap text. Characters outside +//! ([`text_width`]) so callers can measure, align and wrap text. Latin Extended-A letters +//! WinAnsiEncoding lacks (ő, ű, ł, č, …) are set in the same face through a second resource with +//! a `/Differences` encoding of standard glyph names. Other characters outside //! WinAnsiEncoding (CJK and other scripts) are set in a predefined, non-embedded Adobe-GB1 CID //! font with the `UniGB-UTF16-H` CMap instead of being replaced by `?`. Symbol uses its own //! built-in encoding ([`symbol_code`]), for Greek letters and mathematical operators. @@ -326,10 +328,73 @@ pub fn win_ansi(c: char) -> u8 { } } +/// Objects a font resource takes: the CID font also has its descendant font and font descriptor, +/// a Latin Extended-A face its font descriptor. +fn font_objects(slot: usize) -> u32 { + if slot == CID_FONT { + 3 + } else if slot >= EXT_FONT { + 2 + } else { + 1 + } +} + +/// Writes the Latin Extended-A resource of `face` as object `id`, with its font descriptor as +/// `id + 1`. +fn write_ext_font(out: &mut craft_pdf::classic::Writer, id: u32, face: Font) -> Result<(), Error> { + let names: Vec<&str> = metrics::LATIN_EXT_A.iter().map(|(name, _)| *name).collect(); + // Not every glyph name here is in the standard fonts' metrics (Ccircumflex + // isn't), so the resource states each width: without one a reader can give + // the glyph no advance and set the next letter on top of it. The PDF reference + // asks for /FirstChar, /LastChar, /Widths and /FontDescriptor together. + let widths: Vec = (0x100u32..0x180).map(|u| char::from_u32(u).map_or(0, |c| face.char_width(c)).to_string()).collect(); + let last = 127 + widths.len(); + let desc_id = id + 1; + out.object( + id, + &format!( + "<< /Type /Font /Subtype /Type1 /BaseFont /{} /Encoding << /Type /Encoding /Differences [128 /{}] >> /FirstChar 128 /LastChar {last} /Widths [{}] /FontDescriptor {desc_id} 0 R >>", + face.base_name(), + names.join(" /"), + widths.join(" ") + ), + )?; + out.object(desc_id, &font_descriptor(face))?; + Ok(()) +} + +/// The font descriptor of a standard face (values from its Adobe AFM), for a resource that states +/// its own widths. +fn font_descriptor(face: Font) -> String { + // (flags, bbox, italic angle, ascent, descent, cap height, StemV) + let (flags, bbox, italic, ascent, descent, cap, stem) = match face { + Font::Helvetica => (32, "-166 -225 1000 931", 0.0, 718, -207, 718, 88), + Font::HelveticaOblique => (96, "-170 -225 1116 931", -12.0, 718, -207, 718, 88), + Font::HelveticaBold => (32, "-170 -228 1003 962", 0.0, 718, -207, 718, 140), + Font::HelveticaBoldOblique => (96, "-174 -228 1114 962", -12.0, 718, -207, 718, 140), + Font::TimesRoman => (34, "-168 -218 1000 898", 0.0, 683, -217, 662, 84), + Font::TimesBold => (34, "-168 -218 1000 935", 0.0, 683, -217, 676, 139), + Font::TimesItalic => (98, "-169 -217 1010 883", -15.5, 683, -217, 653, 76), + Font::TimesBoldItalic => (98, "-200 -218 996 921", -15.0, 683, -217, 669, 121), + Font::Courier => (35, "-23 -250 715 805", 0.0, 629, -157, 562, 51), + Font::CourierBold => (35, "-113 -250 749 801", 0.0, 629, -157, 562, 106), + Font::CourierOblique => (99, "-27 -250 849 805", -12.0, 629, -157, 562, 51), + Font::CourierBoldOblique => (99, "-57 -250 869 801", -12.0, 629, -157, 562, 106), + Font::Symbol => (4, "-180 -293 1090 1010", 0.0, 1010, -293, 1010, 85), + }; + format!( + "<< /Type /FontDescriptor /FontName /{} /Flags {flags} /FontBBox [{bbox}] /ItalicAngle {italic} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem} >>", + face.base_name() + ) +} + /// Index of the CID font in a page's font flags (after the [`Font::ALL`] faces). const CID_FONT: usize = Font::ALL.len(); +/// Index of the first Latin Extended-A face (one per [`Font::ALL`] face, after the CID font). +const EXT_FONT: usize = CID_FONT + 1; /// Number of font resources a page can use. -const FONT_SLOTS: usize = CID_FONT + 1; +const FONT_SLOTS: usize = EXT_FONT + Font::ALL.len(); /// Base font of the CID font used for characters WinAnsiEncoding lacks. const CID_BASE_FONT: &str = "STSong-Light"; /// Default glyph width of the CID font (full-width), in 1/1000 em. @@ -337,7 +402,44 @@ const CID_WIDTH: u16 = 1000; /// True when `c` has no WinAnsiEncoding byte and is drawn with the CID font. fn needs_cid(c: char) -> bool { - !c.is_control() && c != '?' && win_ansi(c) == b'?' + !c.is_control() && c != '?' && win_ansi(c) == b'?' && ext_code(c).is_none() +} + +/// The byte of `c` in the Latin Extended-A encoding (U+0100..=U+017F at 0x80..=0xFF), for +/// characters WinAnsiEncoding lacks. These are set in the standard face with a `/Differences` +/// encoding of standard glyph names, not in the CID font. +fn ext_code(c: char) -> Option { + let u = c as u32; + ((0x100..=0x17F).contains(&u) && win_ansi(c) == b'?').then(|| (u - 0x80) as u8) +} + +/// How a character is encoded in a text run. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Run { + Ansi, + Ext, + Cid, +} + +fn run_kind(c: char) -> Run { + if ext_code(c).is_some() { + Run::Ext + } else if needs_cid(c) { + Run::Cid + } else { + Run::Ansi + } +} + +/// A PDF hex string `< … >` of `text` in the Latin Extended-A encoding of [`ext_code`]. +fn pdf_ext_string(text: &str) -> String { + let mut s = String::with_capacity(text.len() * 2 + 2); + s.push('<'); + for c in text.chars() { + let _ = write!(s, "{:02X}", ext_code(c).unwrap_or(b'?')); + } + s.push('>'); + s } /// A PDF hex string `< … >` of `text` in UTF-16BE (the `UniGB-UTF16-H` encoding). @@ -879,7 +981,8 @@ impl Page { return; } }; - for slot in [Some(font.index()), self.arabic.uses_cid.then_some(CID_FONT)].into_iter().flatten() { + let ext = self.arabic.uses_ext.get(font.index()).copied().unwrap_or(false).then_some(EXT_FONT + font.index()); + for slot in [Some(font.index()), self.arabic.uses_cid.then_some(CID_FONT), ext].into_iter().flatten() { if let Some(f) = self.fonts.get_mut(slot) { *f = true; } @@ -907,13 +1010,17 @@ impl Page { // advances the text position, so the runs follow each other on the baseline. // Symbol text is one run in Symbol's own encoding (the CID font has no maths symbols). let symbol = font == Font::Symbol; - let uses_cid = |c: char| !symbol && needs_cid(c); + let kind_of = |c: char| if symbol { Run::Ansi } else { run_kind(c) }; let mut rest: &str = &visual; while let Some(first) = rest.chars().next() { - let cid = uses_cid(first); - let end = rest.char_indices().find(|(_, c)| uses_cid(*c) != cid).map_or(rest.len(), |(i, _)| i); + let kind = kind_of(first); + let end = rest.char_indices().find(|(_, c)| kind_of(*c) != kind).map_or(rest.len(), |(i, _)| i); let (run, tail) = rest.split_at(end); - let (slot, string) = if cid { (CID_FONT, pdf_utf16_string(run)) } else { (fi, pdf_string_in(run, symbol)) }; + let (slot, string) = match kind { + Run::Cid => (CID_FONT, pdf_utf16_string(run)), + Run::Ext => (EXT_FONT + fi, pdf_ext_string(run)), + Run::Ansi => (fi, pdf_string_in(run, symbol)), + }; if let Some(f) = self.fonts.get_mut(slot) { *f = true; } @@ -1179,8 +1286,9 @@ impl PdfDoc { for (i, u) in used.iter().enumerate() { if *u { font_ids[i] = next; - // The CID font also needs its descendant font and font descriptor. - next += if i == CID_FONT { 3 } else { 1 }; + // The CID font also needs its descendant font and font descriptor; a Latin + // Extended-A face its font descriptor. + next += font_objects(i); } } // Page contents are moved out so each one is freed as soon as it is in the output. @@ -1215,6 +1323,10 @@ impl PdfDoc { )?; continue; } + if let Some(face) = i.checked_sub(EXT_FONT).and_then(|f| Font::ALL.get(f)) { + write_ext_font(&mut out, *id, *face)?; + continue; + } let name = Font::ALL.get(i).copied().unwrap_or_default().base_name(); let enc = if name.starts_with("Symbol") { "" } else { " /Encoding /WinAnsiEncoding" }; out.object(*id, &format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name}{enc} >>"))?; diff --git a/crates/pdf/src/metrics.rs b/crates/pdf/src/metrics.rs index 09fbbfbc2b..40ab4a168f 100644 --- a/crates/pdf/src/metrics.rs +++ b/crates/pdf/src/metrics.rs @@ -64,9 +64,150 @@ pub(crate) const TIMES_BOLD: [u16; 95] = [ 394, 220, 394, 520, // '{'..'~' ]; +/// Latin Extended-A (U+0100..=U+017F): the standard (Adobe Glyph List) glyph name of each +/// character and an ASCII character of similar width. +pub(crate) const LATIN_EXT_A: [(&str, char); 128] = [ + ("Amacron", 'A'), + ("amacron", 'a'), + ("Abreve", 'A'), + ("abreve", 'a'), + ("Aogonek", 'A'), + ("aogonek", 'a'), + ("Cacute", 'C'), + ("cacute", 'c'), + ("Ccircumflex", 'C'), + ("ccircumflex", 'c'), + ("Cdotaccent", 'C'), + ("cdotaccent", 'c'), + ("Ccaron", 'C'), + ("ccaron", 'c'), + ("Dcaron", 'D'), + ("dcaron", 'd'), + ("Dcroat", 'D'), + ("dcroat", 'd'), + ("Emacron", 'E'), + ("emacron", 'e'), + ("Ebreve", 'E'), + ("ebreve", 'e'), + ("Edotaccent", 'E'), + ("edotaccent", 'e'), + ("Eogonek", 'E'), + ("eogonek", 'e'), + ("Ecaron", 'E'), + ("ecaron", 'e'), + ("Gcircumflex", 'G'), + ("gcircumflex", 'g'), + ("Gbreve", 'G'), + ("gbreve", 'g'), + ("Gdotaccent", 'G'), + ("gdotaccent", 'g'), + ("Gcommaaccent", 'G'), + ("gcommaaccent", 'g'), + ("Hcircumflex", 'H'), + ("hcircumflex", 'h'), + ("Hbar", 'H'), + ("hbar", 'h'), + ("Itilde", 'I'), + ("itilde", 'i'), + ("Imacron", 'I'), + ("imacron", 'i'), + ("Ibreve", 'I'), + ("ibreve", 'i'), + ("Iogonek", 'I'), + ("iogonek", 'i'), + ("Idotaccent", 'I'), + ("dotlessi", 'i'), + ("IJ", 'N'), + ("ij", 'x'), + ("Jcircumflex", 'J'), + ("jcircumflex", 'j'), + ("Kcommaaccent", 'K'), + ("kcommaaccent", 'k'), + ("kgreenlandic", 'k'), + ("Lacute", 'L'), + ("lacute", 'l'), + ("Lcommaaccent", 'L'), + ("lcommaaccent", 'l'), + ("Lcaron", 'L'), + ("lcaron", 'l'), + ("Ldot", 'L'), + ("ldot", 'l'), + ("Lslash", 'L'), + ("lslash", 'l'), + ("Nacute", 'N'), + ("nacute", 'n'), + ("Ncommaaccent", 'N'), + ("ncommaaccent", 'n'), + ("Ncaron", 'N'), + ("ncaron", 'n'), + ("napostrophe", 'n'), + ("Eng", 'N'), + ("eng", 'n'), + ("Omacron", 'O'), + ("omacron", 'o'), + ("Obreve", 'O'), + ("obreve", 'o'), + ("Ohungarumlaut", 'O'), + ("ohungarumlaut", 'o'), + ("OE", 'W'), + ("oe", 'm'), + ("Racute", 'R'), + ("racute", 'r'), + ("Rcommaaccent", 'R'), + ("rcommaaccent", 'r'), + ("Rcaron", 'R'), + ("rcaron", 'r'), + ("Sacute", 'S'), + ("sacute", 's'), + ("Scircumflex", 'S'), + ("scircumflex", 's'), + ("Scedilla", 'S'), + ("scedilla", 's'), + ("Scaron", 'S'), + ("scaron", 's'), + ("Tcommaaccent", 'T'), + ("tcommaaccent", 't'), + ("Tcaron", 'T'), + ("tcaron", 't'), + ("Tbar", 'T'), + ("tbar", 't'), + ("Utilde", 'U'), + ("utilde", 'u'), + ("Umacron", 'U'), + ("umacron", 'u'), + ("Ubreve", 'U'), + ("ubreve", 'u'), + ("Uring", 'U'), + ("uring", 'u'), + ("Uhungarumlaut", 'U'), + ("uhungarumlaut", 'u'), + ("Uogonek", 'U'), + ("uogonek", 'u'), + ("Wcircumflex", 'W'), + ("wcircumflex", 'w'), + ("Ycircumflex", 'Y'), + ("ycircumflex", 'y'), + ("Ydieresis", 'Y'), + ("Zacute", 'Z'), + ("zacute", 'z'), + ("Zdotaccent", 'Z'), + ("zdotaccent", 'z'), + ("Zcaron", 'Z'), + ("zcaron", 'z'), + ("longs", 'f'), +]; + +/// The [`LATIN_EXT_A`] entry of `c`, if it is in that block. +pub(crate) fn latin_ext_a(c: char) -> Option<(&'static str, char)> { + LATIN_EXT_A.get((c as u32).checked_sub(0x100)? as usize).copied() +} + /// Maps a non-ASCII character to an ASCII character of similar width, or `None` to use the /// font's default width. pub(crate) fn fold(c: char) -> Option { + if let Some((_, base)) = latin_ext_a(c) { + return Some(base); + } Some(match c { 'À'..='Å' => 'A', 'Æ' => 'W', diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 5b4aa0233f..7d36e1cd95 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1071,6 +1071,31 @@ fn oversized_arabic_text_is_an_error_instead_of_partial_pdf() { assert!(doc.finish().unwrap_err().to_string().contains("128 KiB")); } +#[test] +fn arabic_fallback_sets_latin_extended_a_in_the_extended_font() { + if arabic::layout(Font::Helvetica, "مرحبا", TextDirection::Auto).is_err() && arabic::ARABIC_FONTS.is_empty() { + return; + } + // Noto Sans Arabic draws ő and Ş itself but lacks the Esperanto Ĉ and ĥ, which fall back to the standard face. + let text = "سلام ő Ĉu ĥ"; + let items = arabic::layout(Font::Helvetica, text, TextDirection::Auto).unwrap().items; + // Drawn by the face itself or in the extended font, never in WinAnsi. + assert!( + items.iter().any(|item| matches!(item, arabic::Item::Glyph { source: text, .. } | arabic::Item::Ext { text, .. } if text.contains('Ĉ'))), + "{items:?}" + ); + for item in items { + if let arabic::Item::Latin { text: drawn, .. } = &item { + assert!(!drawn.chars().any(|c| ext_code(c).is_some()), "{drawn:?} is set in WinAnsi, where it would print as ?"); + } + } + let mut subset = arabic::Subset::default(); + let body = subset.text(Font::Helvetica, text, 12.0, TextDirection::Auto).unwrap(); + let ext = format!("/F{} ", EXT_FONT + Font::Helvetica.index() + 1); + assert_eq!(body.contains(&ext), subset.uses_ext[Font::Helvetica.index()], "the page declares the extended font it uses"); + assert!(!body.contains("(?)") && !body.contains("?)"), "no letter falls back to ?: {body}"); +} + #[test] fn arabic_joining_marks_styles_and_rotation() { if arabic::layout(Font::Helvetica, "مرحبا", TextDirection::Auto).is_err() && arabic::ARABIC_FONTS.is_empty() { @@ -1146,7 +1171,7 @@ fn line_breaks_in_arabic_text_draw_as_spaces() { { let layout = arabic::layout(Font::Helvetica, text, direction).unwrap(); for item in &layout.items { - if let arabic::Item::Latin { text: drawn, .. } = item { + if let arabic::Item::Latin { text: drawn, .. } | arabic::Item::Ext { text: drawn, .. } = item { assert!(!drawn.chars().any(|ch| matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')), "{drawn:?} from {text:?}"); } } @@ -1244,7 +1269,7 @@ fn arabic_explicit_base_changes_visual_order_and_preserves_logical_text() { .into_iter() .map(|item| match item { arabic::Item::Glyph { source, .. } => source, - arabic::Item::Latin { text, .. } | arabic::Item::Cid { text, .. } => text, + arabic::Item::Latin { text, .. } | arabic::Item::Ext { text, .. } | arabic::Item::Cid { text, .. } => text, }) .collect::() }; @@ -1335,3 +1360,83 @@ fn shared_run_length_preserves_pixels_at_packet_boundaries() { // Two equal bytes may now terminate a literal packet. PDF pixel values stay exact. assert_eq!(run_length(&[1, 2, 2, 3]), [0, 1, 255, 2, 0, 3, 128]); } + +#[test] +fn latin_extended_letters_use_the_latin_font() { + let mut doc = PdfDoc::new(); + let p = doc.add_page(612.0, 792.0); + p.text(10.0, 20.0, 10.0, Font::Helvetica, [0, 0, 0], "tőrű ŐŰ"); + let c = page_content(&doc).to_string(); + assert!(!c.contains("<0151>") && !c.contains("<0171>"), "ő/ű set in the CJK font: {c}"); + // ő, ű, Ő, Ű are bytes 0xD1, 0xF1, 0xD0, 0xF0 of the Helvetica Latin Extended-A resource. + // Resources: the faces, then the CID font, then their Latin Extended-A twins. + let ext = format!("/F{}", EXT_FONT + 1); + let expected = format!( + "/F1 10 Tf\n1 0 0 1 10 772 Tm\n(t) Tj\n{ext} 10 Tf\n Tj\n/F1 10 Tf\n(r) Tj\n{ext} 10 Tf\n Tj\n/F1 10 Tf\n( ) Tj\n{ext} 10 Tf\n Tj\n" + ); + assert!(c.contains(&expected), "ő/ű not set through the Latin resource: {c}"); + let pdf = doc.finish().unwrap(); + check_xref(&pdf).unwrap(); + assert!(find(&pdf, CID_BASE_FONT.as_bytes()).is_none(), "CJK font used for Latin letters"); + for name in ["/ohungarumlaut", "/uhungarumlaut", "/Ohungarumlaut", "/Uhungarumlaut"] { + assert!(find(&pdf, name.as_bytes()).is_some(), "missing glyph name {name}"); + } + assert_eq!(text_width(Font::Helvetica, 10.0, "ő"), text_width(Font::Helvetica, 10.0, "o")); + assert_eq!(text_width(Font::TimesBold, 10.0, "Ű"), text_width(Font::TimesBold, 10.0, "U")); + assert_eq!(text_width(Font::Courier, 10.0, "ł"), 6.0); +} + +#[test] +fn latin_extended_resources_give_every_glyph_a_width() { + // Ccircumflex and other Extended-A names aren't in every standard font's metrics: the resource + // states each width, so no glyph gets a zero advance and overlaps the next letter. + for face in Font::ALL { + if face == Font::Symbol { + continue; + } + let mut doc = PdfDoc::new(); + let p = doc.add_page(612.0, 792.0); + p.text(10.0, 20.0, 10.0, face, [0, 0, 0], "Ĉu ő"); + let pdf = doc.finish().unwrap(); + check_xref(&pdf).unwrap(); + let text = String::from_utf8_lossy(&pdf); + let name = face.base_name(); + let dict = text + .split("<< /Type /Font /Subtype /Type1 /BaseFont /") + .find(|d| d.starts_with(&format!("{name} /Encoding << /Type /Encoding /Differences"))) + .unwrap(); + assert!(dict.contains("/FirstChar 128 /LastChar 255 /Widths ["), "{name}: {dict}"); + let widths = dict.split("/Widths [").nth(1).and_then(|w| w.split(']').next()).unwrap(); + let widths: Vec = widths.split_whitespace().map(|w| w.parse().unwrap()).collect(); + assert_eq!(widths.len(), 128, "{name}"); + assert!(widths.iter().all(|&w| w > 0), "{name}: {widths:?}"); + // Ĉ (U+0108) is set at its base letter's width. + assert_eq!(widths[8], face.char_width('C'), "{name}"); + let desc = dict.split("/FontDescriptor ").nth(1).and_then(|d| d.split(' ').next()).unwrap(); + assert!(text.contains(&format!("{desc} 0 obj\n<< /Type /FontDescriptor /FontName /{name} ")), "{name}: descriptor {desc}"); + } +} + +#[test] +fn latin_extended_letters_use_each_faces_own_resource() { + // Every face routed to a `/Differences` resource has the Latin glyphs; the symbolic standard + // fonts (Symbol, ZapfDingbats) lack them and are never routed there. + for face in Font::ALL { + let name = face.base_name(); + if name.starts_with("Symbol") || name.starts_with("ZapfDingbats") { + continue; + } + let mut doc = PdfDoc::new(); + let p = doc.add_page(612.0, 792.0); + p.text(10.0, 20.0, 10.0, face, [0, 0, 0], "ő"); + let ext = Font::ALL.len() + 2 + face.index(); + let c = page_content(&doc).to_string(); + assert!(c.contains(&format!("/F{ext} 10 Tf\n")) && c.contains(" Tj\n"), "{name}: {c}"); + let pdf = doc.finish().unwrap(); + check_xref(&pdf).unwrap(); + let dict = format!("/BaseFont /{name} /Encoding << /Type /Encoding /Differences [128 /Amacron"); + assert!(find(&pdf, dict.as_bytes()).is_some(), "{name}: no Latin Extended-A encoding"); + assert!(find(&pdf, format!("/F{ext} ").as_bytes()).is_some(), "{name}: resource missing"); + assert!(find(&pdf, CID_BASE_FONT.as_bytes()).is_none(), "{name}: CJK font used"); + } +}