Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / pdf / src / main / rust / src / fonts_part6.rs

fonts_part6.rs319 lines · 14.5 KiBRaw
1#[cfg(test)]
2mod type1_tests {
3 use super::*;
4
5 #[test]
6 fn type1_encoding_scan() {
7 let text = b"/Encoding 256 array\n0 1 255 {1 index exch /.notdef put} for\ndup 65 /A put\ndup 97 /a put\ndup 233 /eacute put\nreadonly def";
8 let m = parse_type1_encoding_text(text);
9 assert_eq!(m.get(&65), Some(&'A'));
10 assert_eq!(m.get(&97), Some(&'a'));
11 assert_eq!(m.get(&233), Some(&'\u{00E9}'));
12 }
13
14 #[test]
15 fn rksj_codespace_segments_mixed_width_codes() {
16 // 90ms-RKSJ-H interleaves 1-byte and 2-byte codes. Decoding as fixed
17 // 2-byte codes would pair 'A' with the kanji lead byte and desynchronize
18 // the rest of the string.
19 let cs = cmap::predefined_codespace("90ms-RKSJ-H").expect("RKSJ recognized");
20 let cm = cmap::EncodingCMap { codespace: cs, ..Default::default() };
21 assert_eq!(cm.code_len(b'A'), 1, "ASCII is single-byte");
22 assert_eq!(cm.code_len(0x82), 2, "kanji lead byte is double-byte");
23 assert_eq!(cm.code_len(0xB0), 1, "half-width katakana is single-byte");
24 assert_eq!(cm.code_len(0xE0), 2, "second kanji lead range is double-byte");
25 }
26
27 #[test]
28 fn ucs2_cmaps_are_not_given_a_codespace() {
29 // Pure 2-byte families already decode correctly via the Identity path.
30 assert!(cmap::predefined_codespace("UniJIS-UCS2-H").is_none());
31 assert!(cmap::predefined_codespace("UniGB-UCS2-H").is_none());
32 assert!(cmap::predefined_codespace("UniKS-UCS2-H").is_none());
33 assert!(cmap::predefined_codespace("Identity-H").is_none());
34 assert!(cmap::predefined_codespace("Identity-V").is_none());
35 // The ISO-2022 families are <2121>-<7E7E>, i.e. pure 2-byte.
36 assert!(cmap::predefined_codespace("Add-H").is_none());
37 assert!(cmap::predefined_codespace("Ext-V").is_none());
38 }
39
40 #[test]
41 fn mixed_width_cmap_families_are_recognized() {
42 // Each of these has 1-byte ranges alongside its 2-byte ranges, so a fixed
43 // 2-byte decode desynchronizes the byte stream (PDF 9.7.6.2).
44 let len = |name: &str, b: u8| {
45 let cs = cmap::predefined_codespace(name).unwrap_or_else(|| panic!("{name} recognized"));
46 cmap::EncodingCMap { codespace: cs, ..Default::default() }.code_len(b)
47 };
48 // Big5, GBK, EUC-CN, UHC, EUC-KR: ASCII single-byte, lead byte double.
49 for (name, lead) in [
50 ("ETen-B5-H", 0xA1u8),
51 ("B5pc-H", 0xA1),
52 ("GBK-EUC-H", 0x81),
53 ("GB-EUC-H", 0xA1),
54 ("GBpc-EUC-V", 0xA1),
55 ("KSCms-UHC-H", 0x81),
56 ("KSC-EUC-H", 0x81),
57 ("KSCpc-EUC-H", 0x81),
58 ] {
59 assert_eq!(len(name, b'A'), 1, "{name}: ASCII must be single-byte");
60 assert_eq!(len(name, lead), 2, "{name}: lead byte must be double-byte");
61 }
62 // Japanese EUC: 1-byte ASCII, 2-byte for both the 0x8E single-shift form
63 // and the standard 0xA1.. plane.
64 assert_eq!(len("EUC-H", b'A'), 1);
65 assert_eq!(len("EUC-H", 0x8E), 2);
66 assert_eq!(len("EUC-H", 0xA1), 2);
67 }
68
69 #[test]
70 fn utf8_and_utf16_cmaps_segment_by_lead_byte() {
71 // UniJIS-UTF8-H etc. are 1-4 bytes; a fixed 2-byte read desynchronizes on
72 // the first ASCII character.
73 let cs = cmap::predefined_codespace("UniJIS-UTF8-H").expect("UTF8 recognized");
74 let cm = cmap::EncodingCMap { codespace: cs, ..Default::default() };
75 assert_eq!(cm.code_len(b'A'), 1);
76 assert_eq!(cm.code_len(0xC3), 2);
77 assert_eq!(cm.code_len(0xE3), 3);
78 assert_eq!(cm.code_len(0xF0), 4);
79 // UTF-16 is 2 bytes except surrogate pairs, which are 4.
80 let cs = cmap::predefined_codespace("UniGB-UTF16-H").expect("UTF16 recognized");
81 let cm = cmap::EncodingCMap { codespace: cs, ..Default::default() };
82 assert_eq!(cm.code_len(0x00), 2);
83 assert_eq!(cm.code_len(0xD8), 4, "high surrogate starts a 4-byte code");
84 assert_eq!(cm.code_len(0xE0), 2);
85 }
86
87 #[test]
88 fn gb18030_four_byte_plane_needs_the_second_byte() {
89 // GBK2K-H is GB18030: <81 30 81 30>-<FE 39 FE 39> is a FOUR-byte code, and it is
90 // distinguished from the two-byte plane only by the second byte being 0x30-0x39.
91 // Reading it as two 2-byte codes desynchronizes the rest of the string.
92 let cs = cmap::predefined_codespace("GBK2K-H").expect("GBK2K recognized");
93 let cm = cmap::EncodingCMap { codespace: cs, ..Default::default() };
94 assert_eq!(cm.code_len_at(&[0x81, 0x30, 0x81, 0x30]), 4);
95 assert_eq!(cm.code_len_at(&[0x81, 0x40]), 2, "the two-byte plane is untouched");
96 assert_eq!(cm.code_len_at(&[0x41]), 1, "ASCII is still single-byte");
97 // The lookahead is a strict refinement: every other predefined codespace answers
98 // exactly what the first-byte-only `code_len` answers.
99 for name in ["GBK-EUC-H", "90ms-RKSJ-H", "UniJIS-UTF8-H", "UniGB-UTF16-H", "ETen-B5-H"] {
100 let cs = cmap::predefined_codespace(name).unwrap();
101 let cm = cmap::EncodingCMap { codespace: cs, ..Default::default() };
102 for b1 in 0u16..=255 {
103 for b2 in [0x00u8, 0x30, 0x39, 0x40, 0x80, 0xA0, 0xFE, 0xFF] {
104 assert_eq!(
105 cm.code_len_at(&[b1 as u8, b2]),
106 cm.code_len(b1 as u8),
107 "{name} changed segmentation at {b1:#04x} {b2:#04x}"
108 );
109 }
110 }
111 }
112 }
113
114 #[test]
115 fn for_each_code_resegments_a_mixed_width_string() {
116 // End-to-end: the whole point of the codespace is that a 1-byte code in
117 // the middle of a CJK string does not shift every following code by one
118 // byte. "A" + 2-byte kanji + "B" must yield exactly three codes.
119 let cs = cmap::predefined_codespace("90ms-RKSJ-H").unwrap();
120 let fi = FontInfo {
121 two_byte: true,
122 cmap: Some(Arc::new(cmap::EncodingCMap { codespace: cs, ..Default::default() })),
123 ..simple_font_with_encoding()
124 };
125 let mut got = Vec::new();
126 fi.for_each_code(&[0x41, 0x82, 0xA0, 0x42], |c, sp| got.push((c, sp)));
127 assert_eq!(got, vec![(0x41, false), (0x82A0, false), (0x42, false)]);
128 // A single-byte code 32 still reports as a word-spacing space, and a
129 // 2-byte code whose value happens to be 0x20 does not (PDF 9.3.3).
130 let mut spaces = Vec::new();
131 fi.for_each_code(&[0x20, 0x82, 0x20], |c, sp| spaces.push((c, sp)));
132 assert_eq!(spaces, vec![(0x20, true), (0x8220, false)]);
133 }
134
135 #[test]
136 fn w_range_form_cannot_allocate_unbounded_widths() {
137 // A hostile `cLast` must not drive a multi-billion-iteration insert loop.
138 let mut doc = Document::new();
139 let desc = doc.add_object(lopdf::dictionary! {
140 "Type" => "Font",
141 "Subtype" => "CIDFontType2",
142 "W" => vec![0.into(), 4_000_000_000u32.into(), 500.into()],
143 });
144 let font = lopdf::dictionary! {
145 "Type" => "Font",
146 "Subtype" => "Type0",
147 "DescendantFonts" => vec![desc.into()],
148 };
149 let (widths, _) = cid_widths(&doc, &font);
150 assert!(widths.len() <= MAX_CID as usize + 1);
151 assert_eq!(widths.get(&0), Some(&0.5));
152 assert_eq!(widths.get(&MAX_CID), Some(&0.5));
153 }
154
155 #[test]
156 fn bfrange_cannot_allocate_unbounded_strings() {
157 // A 4-byte `hi` in a bfrange must be clamped, not expanded to 4 billion
158 // entries.
159 let map = cmap::parse(b"1 beginbfrange\n<00000000> <FFFFFFFF> <0041>\nendbfrange");
160 assert!(map.len() <= MAX_CID as usize + 1);
161 assert_eq!(map.get(&0).map(String::as_str), Some("A"));
162 }
163
164 #[test]
165 fn tw_applies_only_to_single_byte_code_32() {
166 // PDF 9.3.3: Tw applies to code 32 and nothing else -- notably not NBSP,
167 // which must not stretch under justification.
168 let fi = simple_font_with_encoding();
169 let mut seen = Vec::new();
170 fi.for_each_code(&[32, 0xA0, b'A'], |code, is_space| seen.push((code, is_space)));
171 assert_eq!(seen, vec![(32, true), (0xA0, false), (65, false)]);
172 }
173
174 #[test]
175 fn font_cache_shares_parsed_fonts_only_inside_a_scope() {
176 // The cache exists because `fonts_from_resources` runs per page and
177 // re-parses each font's embedded program every time. Assert on Arc
178 // identity rather than on equality: equal contents would also hold if the
179 // font had been re-parsed, which is exactly the bug being fixed.
180 let mut doc = Document::with_version("1.7");
181 let tu = doc.add_object(Stream::new(
182 dictionary! {},
183 b"1 beginbfchar\n<41> <0041>\nendbfchar".to_vec(),
184 ));
185 let font = doc.add_object(dictionary! {
186 "Type" => "Font",
187 "Subtype" => "TrueType",
188 "BaseFont" => "Helvetica",
189 "ToUnicode" => tu,
190 });
191 let res = dictionary! { "Font" => dictionary! { "F1" => font } };
192
193 // No scope active: the default must stay uncached, so nothing can ever go
194 // stale in a mutated document.
195 let a = fonts_from_resources(&doc, &res);
196 let b = fonts_from_resources(&doc, &res);
197 let (au, bu) = (
198 a[b"F1".as_ref()].to_unicode.as_ref().unwrap(),
199 b[b"F1".as_ref()].to_unicode.as_ref().unwrap(),
200 );
201 assert_eq!(au.get(&0x41).map(String::as_str), Some("A"), "parse still works");
202 assert!(!Arc::ptr_eq(au, bu), "must not cache without an active scope");
203
204 // Inside a scope the second lookup reuses the first parse.
205 let _scope = FontCacheScope::new();
206 let c = fonts_from_resources(&doc, &res);
207 let d = fonts_from_resources(&doc, &res);
208 assert!(
209 Arc::ptr_eq(
210 c[b"F1".as_ref()].to_unicode.as_ref().unwrap(),
211 d[b"F1".as_ref()].to_unicode.as_ref().unwrap()
212 ),
213 "font should be parsed once per scope"
214 );
215 }
216
217 // The font cache is keyed by the font's OBJECT ID, not by its resource name. Two
218 // pages may each bind /F1 to a different font object, so a name-keyed cache would
219 // render page 2's text in page 1's font. This is the cross-page leak the interaction
220 // review was looking for; it asserts the key, since a name-keyed regression here
221 // would be silent.
222 #[test]
223 fn font_cache_does_not_confuse_two_fonts_that_share_a_resource_name() {
224 let mut doc = Document::with_version("1.7");
225 let mut font_named_f1 = |ch: u8, uni: &str| {
226 let tu = doc.add_object(Stream::new(
227 dictionary! {},
228 format!("1 beginbfchar\n<{ch:02X}> <{uni}>\nendbfchar").into_bytes(),
229 ));
230 let font = doc.add_object(dictionary! {
231 "Type" => "Font",
232 "Subtype" => "TrueType",
233 "BaseFont" => "Helvetica",
234 "ToUnicode" => tu,
235 });
236 dictionary! { "Font" => dictionary! { "F1" => font } }
237 };
238 let res_a = font_named_f1(0x41, "0041");
239 let res_b = font_named_f1(0x41, "0042");
240 let _scope = FontCacheScope::new();
241 let a = fonts_from_resources(&doc, &res_a);
242 let b = fonts_from_resources(&doc, &res_b);
243 let (au, bu) = (
244 a[b"F1".as_ref()].to_unicode.as_ref().unwrap(),
245 b[b"F1".as_ref()].to_unicode.as_ref().unwrap(),
246 );
247 assert_eq!(au.get(&0x41).map(String::as_str), Some("A"));
248 assert_eq!(
249 bu.get(&0x41).map(String::as_str),
250 Some("B"),
251 "the second /F1 is a different font object and must not be served from the cache"
252 );
253 assert!(!Arc::ptr_eq(au, bu));
254 }
255
256 // A colliding object id from a DIFFERENT document must not be served. The cache used
257 // to key on the `Document`'s raw ADDRESS, which is not an identity: overwriting a
258 // `Box<Document>` in place puts the replacement at the same address, and a scope
259 // spanning both then rendered the second document with the first one's font metrics.
260 // A hit now also has to match the dictionary the id resolves to.
261 #[test]
262 fn font_cache_rejects_a_colliding_id_from_another_document() {
263 let build = |base: &str| {
264 let mut doc = Document::with_version("1.7");
265 // Burn object 1 so the font lands on the same id in both documents.
266 doc.add_object(Object::Null);
267 let font = doc.add_object(dictionary! {
268 "Type" => "Font",
269 "Subtype" => "Type1",
270 "BaseFont" => base,
271 });
272 let res = dictionary! { "Font" => dictionary! { "F1" => font } };
273 (doc, res, font)
274 };
275 let (doc_a, res_a, id_a) = build("Helvetica");
276 let (doc_b, res_b, id_b) = build("Courier");
277 assert_eq!(id_a, id_b, "precondition: the two fonts share an object id");
278
279 let _scope = FontCacheScope::new();
280 let a = fonts_from_resources(&doc_a, &res_a);
281 let b = fonts_from_resources(&doc_b, &res_b);
282 // Courier is monospaced, Helvetica is not: a stale hit shows up as `i` and `M`
283 // having different widths, which is what the address-keyed cache produced.
284 let wi = b[b"F1".as_ref()].widths.get(&(b'i' as u32)).copied();
285 let wm = b[b"F1".as_ref()].widths.get(&(b'M' as u32)).copied();
286 assert_eq!(wi, wm, "the second document must get Courier's uniform advance");
287 assert_ne!(
288 a[b"F1".as_ref()].widths.get(&(b'i' as u32)).copied(),
289 a[b"F1".as_ref()].widths.get(&(b'M' as u32)).copied(),
290 "precondition: Helvetica is proportional, so the two are distinguishable"
291 );
292 }
293
294 fn simple_font_with_encoding() -> FontInfo {
295 FontInfo {
296 two_byte: false,
297 wmode: 0,
298 vertical_metrics: Arc::default(),
299 default_vertical: (0.880, -1.0),
300 cid_to_gid: None,
301 to_unicode: None,
302 encoding: Arc::new(encoding::win_ansi()),
303 cmap_uni: Arc::default(),
304 cmap: None,
305 widths: Arc::default(),
306 default_width: 0.5,
307 t3: None,
308 style: FontStyle::default(),
309 family: 0,
310 base_font: String::new(),
311 glyph_program: None,
312 glyph_names: Arc::default(),
313 }
314 }
315}
316
317// ---------------------------------------------------------------------------
318// ToUnicode CMap parsing
319// ---------------------------------------------------------------------------