1pub mod cmap;
13pub mod encoding;
14pub mod glyph;
15mod metrics;
16pub mod system;
17mod type1;
18
19use std::collections::HashMap;
20use std::sync::{Arc, Mutex};
21
22use crate::document::Document;
23use crate::geom::Matrix;
24use crate::object::{Dict, Object};
25
26use cmap::CMap;
27use encoding::{base_encoding_name, glyph_name_to_unicode, Encoding};
28use glyph::{Outline, OutlineBuilder};
29
30#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
36pub struct FontFlags(pub u32);
37
38impl FontFlags {
39 pub const FIXED_PITCH: u32 = 1 << 0;
40 pub const SERIF: u32 = 1 << 1;
41 pub const SYMBOLIC: u32 = 1 << 2;
42 pub const CURSIVE: u32 = 1 << 3;
43 pub const ITALIC: u32 = 1 << 4;
44 pub const ALL_CAPS: u32 = 1 << 5;
45 pub const SMALL_CAPS: u32 = 1 << 6;
46 pub const BOLD: u32 = 1 << 7;
47 pub const SANS_SERIF: u32 = 1 << 8;
50
51 pub fn has(self, flag: u32) -> bool {
52 self.0 & flag != 0
53 }
54
55 fn set(&mut self, flag: u32, on: bool) {
56 if on {
57 self.0 |= flag;
58 } else {
59 self.0 &= !flag;
60 }
61 }
62
63 pub fn is_bold(self) -> bool {
64 self.has(Self::BOLD)
65 }
66
67 pub fn is_italic(self) -> bool {
68 self.has(Self::ITALIC)
69 }
70
71 pub fn is_serif(self) -> bool {
72 self.has(Self::SERIF)
73 }
74
75 pub fn is_fixed_pitch(self) -> bool {
76 self.has(Self::FIXED_PITCH)
77 }
78
79 pub fn is_symbolic(self) -> bool {
80 self.has(Self::SYMBOLIC)
81 }
82}
83
84mod desc_flag {
86 pub const FIXED_PITCH: i64 = 1 << 0;
87 pub const SERIF: i64 = 1 << 1;
88 pub const SYMBOLIC: i64 = 1 << 2;
89 pub const SCRIPT: i64 = 1 << 3;
90 pub const NONSYMBOLIC: i64 = 1 << 5;
91 pub const ITALIC: i64 = 1 << 6;
92 pub const ALL_CAP: i64 = 1 << 16;
93 pub const SMALL_CAP: i64 = 1 << 17;
94 pub const FORCE_BOLD: i64 = 1 << 18;
95}
96
97fn derive_flags(doc: &Document, descriptor: Option<&Dict>, base_font: &str) -> FontFlags {
99 let num = |key: &str| {
100 descriptor
101 .and_then(|d| doc.dict_get(d, key))
102 .and_then(|o| o.as_f32())
103 };
104 let raw = descriptor
105 .and_then(|d| doc.dict_get(d, "Flags"))
106 .and_then(|o| o.as_int())
107 .unwrap_or(0);
108
109 let name = base_font
112 .split('+')
113 .next_back()
114 .unwrap_or(base_font)
115 .to_ascii_lowercase();
116
117 let mut flags = FontFlags::default();
118
119 let symbolic = raw & desc_flag::SYMBOLIC != 0 && raw & desc_flag::NONSYMBOLIC == 0;
122 flags.set(FontFlags::SYMBOLIC, symbolic);
123
124 let serif = raw & desc_flag::SERIF != 0
125 || [
126 "times", "roman", "georgia", "garamond", "minion", "cambria", "book",
127 ]
128 .iter()
129 .any(|f| name.contains(f));
130 flags.set(FontFlags::SERIF, serif);
131 flags.set(FontFlags::SANS_SERIF, !serif && !symbolic);
132
133 flags.set(
134 FontFlags::FIXED_PITCH,
135 raw & desc_flag::FIXED_PITCH != 0 || name.contains("courier") || name.contains("mono"),
136 );
137
138 let italic = raw & desc_flag::ITALIC != 0
140 || num("ItalicAngle").is_some_and(|a| a.abs() > 0.5)
141 || name.contains("italic")
142 || name.contains("oblique");
143 flags.set(FontFlags::ITALIC, italic);
144
145 let bold = raw & desc_flag::FORCE_BOLD != 0
148 || num("FontWeight").is_some_and(|w| w >= 600.0)
149 || num("StemV").is_some_and(|s| s >= 120.0)
150 || name.contains("bold")
151 || name.contains("black")
152 || name.contains("heavy");
153 flags.set(FontFlags::BOLD, bold);
154
155 flags.set(
156 FontFlags::CURSIVE,
157 raw & desc_flag::SCRIPT != 0 || name.contains("script"),
158 );
159 flags.set(FontFlags::ALL_CAPS, raw & desc_flag::ALL_CAP != 0);
160 flags.set(FontFlags::SMALL_CAPS, raw & desc_flag::SMALL_CAP != 0);
161 flags
162}
163
164#[derive(Debug, Clone)]
166pub struct CodeItem {
167 pub code: u32,
169 pub cid: u32,
171 pub unicode: Option<String>,
173 pub width: f32,
175 pub is_word_space: bool,
177}
178
179enum Program {
181 Sfnt(Arc<[u8]>),
183 Cff(Arc<[u8]>),
185 Type1(Arc<[u8]>),
189 None,
191}
192
193impl Program {
194 fn builtin_encoding(&self) -> Option<type1::Builtin> {
196 match self {
197 Program::Type1(data) => type1::builtin_encoding(data),
198 _ => None,
199 }
200 }
201}
202
203enum Widths {
205 Simple {
207 first: u32,
208 widths: Vec<f32>,
209 missing: Option<f32>,
210 },
211 Cid {
213 default: f32,
214 map: HashMap<u32, f32>,
215 },
216}
217
218struct Composite {
220 cmap: CMap,
222 cid_to_gid: Option<Arc<[u8]>>,
224}
225
226pub struct Font {
231 pub base_font: String,
232 pub flags: FontFlags,
234 pub is_type3: bool,
235 pub font_matrix: Matrix,
238 names: Vec<String>,
240 symbolic: bool,
242 composite: Option<Composite>,
243 to_unicode: Option<CMap>,
244 widths: Widths,
245 program: Program,
246 char_procs: Dict,
248 outline_cache: Mutex<HashMap<u32, Option<Arc<Outline>>>>,
249 substitute: std::sync::OnceLock<Option<Arc<[u8]>>>,
251 cff_cid_to_gid: std::sync::OnceLock<HashMap<u16, u16>>,
254}
255
256impl std::fmt::Debug for Font {
257 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260 f.debug_struct("Font")
261 .field("base_font", &self.base_font)
262 .field("flags", &self.flags)
263 .field("is_type3", &self.is_type3)
264 .finish_non_exhaustive()
265 }
266}
267
268impl Font {
269 pub fn load(doc: &Document, dict: &Dict) -> Font {
275 let subtype = dict.get("Subtype").and_then(|o| o.as_name()).unwrap_or("");
276 let base_font = doc
277 .dict_get(dict, "BaseFont")
278 .as_ref()
279 .and_then(|o| o.as_name())
280 .unwrap_or("")
281 .to_string();
282
283 match subtype {
284 "Type0" => Self::load_type0(doc, dict, base_font),
285 "Type3" => Self::load_type3(doc, dict, base_font),
286 _ => Self::load_simple(doc, dict, base_font),
287 }
288 }
289
290 fn load_simple(doc: &Document, dict: &Dict, base_font: String) -> Font {
293 let descriptor = doc
294 .dict_get(dict, "FontDescriptor")
295 .and_then(|o| o.as_dict().cloned());
296 let flags = derive_flags(doc, descriptor.as_ref(), &base_font);
297 let symbolic = flags.is_symbolic();
298
299 let program = load_program(doc, descriptor.as_ref());
302 let names = build_encoding(doc, dict, &base_font, symbolic, &program);
303 let widths = simple_widths(doc, dict, descriptor.as_ref());
304
305 Font {
306 base_font,
307 flags,
308 is_type3: false,
309 font_matrix: Matrix::scale(0.001, 0.001),
310 names,
311 symbolic,
312 composite: None,
313 to_unicode: load_to_unicode(doc, dict),
314 widths,
315 program,
316 char_procs: Dict::new(),
317 outline_cache: Mutex::new(HashMap::new()),
318 substitute: std::sync::OnceLock::new(),
319 cff_cid_to_gid: std::sync::OnceLock::new(),
320 }
321 }
322
323 fn load_type0(doc: &Document, dict: &Dict, base_font: String) -> Font {
324 let cmap = match doc.dict_get(dict, "Encoding") {
326 Some(Object::Name(n)) => {
327 if n.starts_with("Identity") {
328 CMap::identity()
329 } else {
330 CMap::identity()
333 }
334 }
335 Some(obj) => obj
336 .as_stream()
337 .and_then(|s| doc.file.decode_stream(s).ok())
338 .map(|d| CMap::parse(&d.data))
339 .unwrap_or_else(CMap::identity),
340 None => CMap::identity(),
341 };
342
343 let descendant = doc
345 .dict_get(dict, "DescendantFonts")
346 .and_then(|o| match o {
347 Object::Array(items) => items.first().map(|i| doc.resolve(i)),
348 other => Some(other),
349 })
350 .and_then(|o| o.as_dict().cloned())
351 .unwrap_or_default();
352 let descriptor = doc
353 .dict_get(&descendant, "FontDescriptor")
354 .and_then(|o| o.as_dict().cloned());
355
356 let cid_to_gid = match doc.dict_get(&descendant, "CIDToGIDMap") {
357 Some(Object::Stream(s)) => doc
358 .file
359 .decode_stream(&s)
360 .ok()
361 .map(|d| Arc::from(d.data.as_slice())),
362 _ => None,
364 };
365
366 Font {
367 flags: derive_flags(doc, descriptor.as_ref(), &base_font),
368 base_font,
369 is_type3: false,
370 font_matrix: Matrix::scale(0.001, 0.001),
371 names: Vec::new(),
372 symbolic: true,
373 composite: Some(Composite { cmap, cid_to_gid }),
374 to_unicode: load_to_unicode(doc, dict),
375 widths: cid_widths(doc, &descendant),
376 program: load_program(doc, descriptor.as_ref()),
377 char_procs: Dict::new(),
378 outline_cache: Mutex::new(HashMap::new()),
379 substitute: std::sync::OnceLock::new(),
380 cff_cid_to_gid: std::sync::OnceLock::new(),
381 }
382 }
383
384 fn load_type3(doc: &Document, dict: &Dict, base_font: String) -> Font {
385 let font_matrix = doc
386 .dict_get(dict, "FontMatrix")
387 .as_ref()
388 .and_then(|o| o.as_array())
389 .map(|a| {
390 let v: Vec<f32> = a.iter().filter_map(|o| o.as_f32()).collect();
391 if v.len() >= 6 {
392 Matrix::new(v[0], v[1], v[2], v[3], v[4], v[5])
393 } else {
394 Matrix::scale(0.001, 0.001)
395 }
396 })
397 .unwrap_or_else(|| Matrix::scale(0.001, 0.001));
398
399 Font {
400 flags: FontFlags(FontFlags::SYMBOLIC),
403 base_font,
404 is_type3: true,
405 font_matrix,
406 names: build_encoding(doc, dict, "", true, &Program::None),
408 symbolic: true,
409 composite: None,
410 to_unicode: load_to_unicode(doc, dict),
411 widths: simple_widths(doc, dict, None),
412 program: Program::None,
413 char_procs: doc
414 .dict_get(dict, "CharProcs")
415 .and_then(|o| o.as_dict().cloned())
416 .unwrap_or_default(),
417 outline_cache: Mutex::new(HashMap::new()),
418 substitute: std::sync::OnceLock::new(),
419 cff_cid_to_gid: std::sync::OnceLock::new(),
420 }
421 }
422
423 pub fn decode(&self, bytes: &[u8]) -> Vec<CodeItem> {
427 match &self.composite {
428 Some(comp) => comp
429 .cmap
430 .codespace
431 .decode(bytes)
432 .into_iter()
433 .map(|code| {
434 let cid = comp.cmap.cid(code);
435 CodeItem {
436 code,
437 cid,
438 unicode: self.unicode_for(code),
439 width: self.width_for(code, cid),
440 is_word_space: false,
443 }
444 })
445 .collect(),
446 None => bytes
447 .iter()
448 .map(|&b| {
449 let code = u32::from(b);
450 CodeItem {
451 code,
452 cid: code,
453 unicode: self.unicode_for(code),
454 width: self.width_for(code, code),
455 is_word_space: b == 32,
456 }
457 })
458 .collect(),
459 }
460 }
461
462 fn unicode_for(&self, code: u32) -> Option<String> {
464 if let Some(map) = &self.to_unicode {
465 if let Some(s) = map.unicode(code) {
466 return Some(undo_symbol_pua(&s));
467 }
468 }
469 glyph_name_to_unicode(self.glyph_name(code))
470 }
471
472 fn glyph_name(&self, code: u32) -> &str {
474 self.names
475 .get(code as usize)
476 .map(String::as_str)
477 .unwrap_or("")
478 }
479
480 fn width_for(&self, code: u32, cid: u32) -> f32 {
481 match &self.widths {
482 Widths::Simple {
483 first,
484 widths,
485 missing,
486 } => {
487 if let Some(w) = code
488 .checked_sub(*first)
489 .and_then(|i| widths.get(i as usize))
490 .copied()
491 {
492 return w;
495 }
496 let standard = metrics::is_standard_font(&self.base_font);
500 if standard {
501 if let Some(w) = metrics::base14_width(&self.base_font, self.glyph_name(code)) {
502 return w;
503 }
504 }
505 missing
506 .or_else(|| metrics::base14_width(&self.base_font, self.glyph_name(code)))
507 .unwrap_or(500.0)
508 }
509 Widths::Cid { default, map } => map.get(&cid).copied().unwrap_or(*default),
510 }
511 }
512
513 pub fn outline(&self, item: &CodeItem) -> Option<Arc<Outline>> {
520 if let Some(hit) = self.outline_cache.lock().unwrap().get(&item.cid) {
521 return hit.clone();
522 }
523 let built = self.build_outline(item).map(Arc::new);
524 self.outline_cache
525 .lock()
526 .unwrap()
527 .insert(item.cid, built.clone());
528 built
529 }
530
531 fn build_outline(&self, item: &CodeItem) -> Option<Outline> {
532 self.embedded_outline(item)
533 .or_else(|| self.substitute_outline(item))
534 }
535
536 fn substitute_outline(&self, item: &CodeItem) -> Option<Outline> {
541 if self.is_type3 {
542 return None;
543 }
544 let data = self.substitute.get_or_init(|| {
545 system::substitute(system::Style {
546 serif: self.flags.is_serif(),
547 fixed_pitch: self.flags.is_fixed_pitch(),
548 bold: self.flags.is_bold(),
549 italic: self.flags.is_italic(),
550 })
551 });
552 let face = ttf_parser::Face::parse(data.as_ref()?, 0).ok()?;
553 let ch = item.unicode.as_deref()?.chars().next()?;
555 let gid = face.glyph_index(ch)?;
556 let mut sink = Sink::default();
557 face.outline_glyph(gid, &mut sink)?;
558 let upem = f32::from(face.units_per_em()).max(1.0);
559 Some(Outline {
560 is_substitute: true,
561 ..sink.finish(1000.0 / upem, item.width)
562 })
563 }
564
565 fn embedded_outline(&self, item: &CodeItem) -> Option<Outline> {
566 match &self.program {
567 Program::Sfnt(data) => {
568 let face = ttf_parser::Face::parse(data, 0).ok()?;
569 let gid = self.sfnt_glyph_id(&face, item)?;
570 let mut sink = Sink::default();
571 face.outline_glyph(gid, &mut sink)?;
572 let upem = f32::from(face.units_per_em()).max(1.0);
575 Some(sink.finish(1000.0 / upem, item.width))
576 }
577 Program::Cff(data) => {
578 let table = ttf_parser::cff::Table::parse(data)?;
579 let gid = self.cff_glyph_id(&table, item)?;
580 let mut sink = Sink::default();
581 table.outline(gid, &mut sink).ok()?;
582 let scale = table.matrix().sx * 1000.0;
584 Some(sink.finish(if scale.abs() < 1e-6 { 1.0 } else { scale }, item.width))
585 }
586 Program::Type1(_) | Program::None => None,
587 }
588 }
589
590 fn sfnt_glyph_id(
592 &self,
593 face: &ttf_parser::Face,
594 item: &CodeItem,
595 ) -> Option<ttf_parser::GlyphId> {
596 if self.composite.is_some() {
597 return Some(ttf_parser::GlyphId(self.composite_gid(item.cid)));
598 }
599 let name = self.glyph_name(item.code);
600
601 if self.symbolic {
604 if let Some(gid) = symbol_cmap_lookup(face, item.code) {
605 return Some(gid);
606 }
607 }
608 if !name.is_empty() {
609 if let Some(gid) = face.glyph_index_by_name(name) {
610 return Some(gid);
611 }
612 if let Some(ch) = glyph_name_to_unicode(name).and_then(|s| s.chars().next()) {
613 if let Some(gid) = face.glyph_index(ch) {
614 return Some(gid);
615 }
616 }
617 }
618 if !self.symbolic {
619 if let Some(gid) = symbol_cmap_lookup(face, item.code) {
620 return Some(gid);
621 }
622 }
623 Some(ttf_parser::GlyphId(item.code as u16))
625 }
626
627 fn cff_glyph_id(
629 &self,
630 table: &ttf_parser::cff::Table,
631 item: &CodeItem,
632 ) -> Option<ttf_parser::GlyphId> {
633 if self.composite.is_some() {
634 if let Some(gid) = self.cff_cid_to_gid(table, item.cid) {
641 return Some(ttf_parser::GlyphId(gid));
642 }
643 return Some(ttf_parser::GlyphId(self.composite_gid(item.cid)));
644 }
645 let name = self.glyph_name(item.code);
646 if !name.is_empty() {
647 if let Some(gid) = table.glyph_index_by_name(name) {
648 return Some(gid);
649 }
650 }
651 if let Ok(code) = u8::try_from(item.code) {
652 if let Some(gid) = table.glyph_index(code) {
653 return Some(gid);
654 }
655 }
656 Some(ttf_parser::GlyphId(item.cid as u16))
657 }
658
659 fn cff_cid_to_gid(&self, table: &ttf_parser::cff::Table, cid: u32) -> Option<u16> {
664 let map = self.cff_cid_to_gid.get_or_init(|| {
665 let mut map = HashMap::new();
666 for gid in 0..table.number_of_glyphs() {
667 if let Some(cid) = table.glyph_cid(ttf_parser::GlyphId(gid)) {
668 map.entry(cid).or_insert(gid);
670 }
671 }
672 map
673 });
674 map.get(&u16::try_from(cid).ok()?).copied()
675 }
676
677 fn composite_gid(&self, cid: u32) -> u16 {
679 let Some(map) = self.composite.as_ref().and_then(|c| c.cid_to_gid.as_ref()) else {
680 return cid as u16;
681 };
682 let i = cid as usize * 2;
683 match (map.get(i), map.get(i + 1)) {
684 (Some(&hi), Some(&lo)) => u16::from_be_bytes([hi, lo]),
685 _ => 0,
687 }
688 }
689
690 pub fn type3_proc(&self, doc: &Document, code: u32) -> Option<Object> {
694 let name = self.glyph_name(code);
695 if name.is_empty() {
696 return None;
697 }
698 doc.dict_get(&self.char_procs, name)
699 }
700}
701
702fn symbol_cmap_lookup(face: &ttf_parser::Face, code: u32) -> Option<ttf_parser::GlyphId> {
704 use ttf_parser::PlatformId;
705 let cmap = face.tables().cmap?;
706 for sub in cmap.subtables {
707 match sub.platform_id {
708 PlatformId::Windows if sub.encoding_id == 0 => {
711 for candidate in [0xF000 + (code & 0xFF), code] {
712 if let Some(gid) = sub.glyph_index(candidate) {
713 return Some(gid);
714 }
715 }
716 }
717 PlatformId::Macintosh if sub.encoding_id == 0 => {
719 if let Some(gid) = sub.glyph_index(code) {
720 return Some(gid);
721 }
722 }
723 _ => {}
724 }
725 }
726 None
727}
728
729fn undo_symbol_pua(text: &str) -> String {
741 if !text.chars().any(|c| ('\u{F020}'..='\u{F0FF}').contains(&c)) {
742 return text.to_string();
743 }
744 text.chars()
745 .map(|c| {
746 if !('\u{F020}'..='\u{F0FF}').contains(&c) {
747 return c.to_string();
748 }
749 let code = (u32::from(c) & 0xFF) as u8;
750 let name = base_encoding_name(Encoding::Symbol, code);
751 glyph_name_to_unicode(name).unwrap_or_else(|| c.to_string())
752 })
753 .collect()
754}
755
756#[derive(Default)]
758struct Sink {
759 builder: OutlineBuilder,
760}
761
762impl Sink {
763 fn finish(self, scale: f32, advance: f32) -> Outline {
764 let mut cmds = self.builder.finish();
765 if (scale - 1.0).abs() > 1e-6 {
766 for cmd in &mut cmds {
767 scale_cmd(cmd, scale);
768 }
769 }
770 Outline {
771 cmds,
772 advance,
773 is_substitute: false,
774 }
775 }
776}
777
778fn scale_cmd(cmd: &mut glyph::PathCmd, s: f32) {
779 use glyph::PathCmd::*;
780 let scale_point = |p: &mut crate::geom::Point| {
781 p.x *= s;
782 p.y *= s;
783 };
784 match cmd {
785 MoveTo(p) | LineTo(p) => scale_point(p),
786 CurveTo(a, b, c) => {
787 scale_point(a);
788 scale_point(b);
789 scale_point(c);
790 }
791 Close => {}
792 }
793}
794
795impl ttf_parser::OutlineBuilder for Sink {
796 fn move_to(&mut self, x: f32, y: f32) {
797 self.builder.move_to(x, y);
798 }
799
800 fn line_to(&mut self, x: f32, y: f32) {
801 self.builder.line_to(x, y);
802 }
803
804 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
805 let (x0, y0) = (self.builder.x, self.builder.y);
808 self.builder.curve_to(
809 x0 + 2.0 / 3.0 * (x1 - x0),
810 y0 + 2.0 / 3.0 * (y1 - y0),
811 x + 2.0 / 3.0 * (x1 - x),
812 y + 2.0 / 3.0 * (y1 - y),
813 x,
814 y,
815 );
816 }
817
818 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
819 self.builder.curve_to(x1, y1, x2, y2, x, y);
820 }
821
822 fn close(&mut self) {
823 self.builder.close();
824 }
825}
826
827fn load_to_unicode(doc: &Document, dict: &Dict) -> Option<CMap> {
830 let stream = doc.dict_get(dict, "ToUnicode")?;
831 let decoded = doc.file.decode_stream(stream.as_stream()?).ok()?;
832 let map = CMap::parse(&decoded.data);
833 map.has_unicode().then_some(map)
834}
835
836fn load_program(doc: &Document, descriptor: Option<&Dict>) -> Program {
838 let Some(desc) = descriptor else {
839 return Program::None;
840 };
841 for key in ["FontFile2", "FontFile3", "FontFile"] {
845 let Some(obj) = doc.dict_get(desc, key) else {
846 continue;
847 };
848 let Some(stream) = obj.as_stream() else {
849 continue;
850 };
851 let Ok(decoded) = doc.file.decode_stream(stream) else {
852 continue;
853 };
854 let data: Arc<[u8]> = Arc::from(decoded.data.as_slice());
855 let subtype = stream.dict.get("Subtype").and_then(|o| o.as_name());
856 return match key {
857 "FontFile2" => Program::Sfnt(data),
858 "FontFile3" => match subtype {
859 Some("OpenType") => Program::Sfnt(data),
861 _ => Program::Cff(data),
862 },
863 _ => Program::Type1(data),
864 };
865 }
866 Program::None
867}
868
869fn build_encoding(
880 doc: &Document,
881 dict: &Dict,
882 base_font: &str,
883 symbolic: bool,
884 program: &Program,
885) -> Vec<String> {
886 let encoding_obj = doc.dict_get(dict, "Encoding");
887
888 let named = |n: &str| match n {
889 "WinAnsiEncoding" => Some(Encoding::WinAnsi),
890 "MacRomanEncoding" => Some(Encoding::MacRoman),
891 "StandardEncoding" | "MacExpertEncoding" => Some(Encoding::Standard),
892 _ => None,
893 };
894
895 let mut base = match &encoding_obj {
896 Some(Object::Name(n)) => named(n),
897 Some(obj) => obj
898 .as_dict()
899 .and_then(|d| d.get("BaseEncoding"))
900 .and_then(|o| o.as_name())
901 .and_then(named),
902 None => None,
903 };
904
905 let mut names = vec![String::new(); 256];
907 let mut from_program = false;
908 if base.is_none() {
909 match program.builtin_encoding() {
910 Some(type1::Builtin::Standard) => base = Some(Encoding::Standard),
911 Some(type1::Builtin::Custom(builtin)) => {
912 names = builtin;
913 from_program = true;
914 }
915 None => {}
916 }
917 }
918
919 if base.is_none() && !from_program {
920 let lower = base_font.to_ascii_lowercase();
921 if lower.contains("symbol") {
922 base = Some(Encoding::Symbol);
923 } else if !symbolic {
924 base = Some(Encoding::Standard);
926 }
927 }
928
929 if let Some(enc) = base {
930 for (code, slot) in names.iter_mut().enumerate() {
931 *slot = base_encoding_name(enc, code as u8).to_string();
932 }
933 }
934
935 if let Some(diffs) = encoding_obj
938 .as_ref()
939 .and_then(|o| o.as_dict())
940 .and_then(|d| doc.dict_get(d, "Differences"))
941 .as_ref()
942 .and_then(|o| o.as_array())
943 {
944 let mut code: i64 = 0;
945 for item in diffs {
946 match doc.resolve(item) {
947 Object::Int(i) => code = i,
948 Object::Real(r) => code = r as i64,
949 Object::Name(n) => {
950 if let Some(slot) = usize::try_from(code).ok().and_then(|c| names.get_mut(c)) {
951 *slot = n;
952 }
953 code += 1;
954 }
955 _ => {}
956 }
957 }
958 }
959 names
960}
961
962fn simple_widths(doc: &Document, dict: &Dict, descriptor: Option<&Dict>) -> Widths {
963 let first = doc
964 .dict_get(dict, "FirstChar")
965 .and_then(|o| o.as_int())
966 .unwrap_or(0)
967 .clamp(0, u32::MAX as i64) as u32;
968 let widths: Vec<f32> = doc
969 .dict_get(dict, "Widths")
970 .as_ref()
971 .and_then(|o| o.as_array())
972 .map(|a| {
973 a.iter()
974 .map(|o| doc.resolve(o).as_f32().unwrap_or(0.0))
975 .collect()
976 })
977 .unwrap_or_default();
978 let missing = descriptor
979 .and_then(|d| doc.dict_get(d, "MissingWidth"))
980 .and_then(|o| o.as_f32());
981 Widths::Simple {
982 first,
983 widths,
984 missing,
985 }
986}
987
988fn cid_widths(doc: &Document, descendant: &Dict) -> Widths {
990 const MAX_RANGE: u32 = 65_536;
991
992 let default = doc
993 .dict_get(descendant, "DW")
994 .and_then(|o| o.as_f32())
995 .unwrap_or(1000.0);
996 let mut map = HashMap::new();
997
998 if let Some(w) = doc
999 .dict_get(descendant, "W")
1000 .as_ref()
1001 .and_then(|o| o.as_array())
1002 {
1003 let items: Vec<Object> = w.iter().map(|o| doc.resolve(o)).collect();
1004 let mut i = 0;
1005 while i < items.len() {
1006 let Some(start) = items[i].as_f32().map(|f| f.max(0.0) as u32) else {
1007 i += 1;
1008 continue;
1009 };
1010 match items.get(i + 1) {
1011 Some(Object::Array(list)) => {
1012 for (k, item) in list.iter().enumerate() {
1013 let Some(cid) = start.checked_add(k as u32) else {
1015 break;
1016 };
1017 if let Some(width) = doc.resolve(item).as_f32() {
1018 map.insert(cid, width);
1019 }
1020 }
1021 i += 2;
1022 }
1023 Some(end_obj) => {
1024 let end = end_obj.as_f32().map(|f| f.max(0.0) as u32).unwrap_or(start);
1025 let width = items.get(i + 2).and_then(|o| o.as_f32()).unwrap_or(default);
1026 for cid in start..=end.min(start.saturating_add(MAX_RANGE)) {
1028 map.insert(cid, width);
1029 }
1030 i += 3;
1031 }
1032 None => break,
1033 }
1034 }
1035 }
1036 Widths::Cid { default, map }
1037}
1038
1039#[cfg(test)]
1040mod symbol_pua_tests {
1041 use super::undo_symbol_pua;
1042
1043 #[test]
1044 fn microsofts_symbol_range_becomes_real_characters() {
1045 assert_eq!(undo_symbol_pua("\u{F061}"), "α");
1048 assert_eq!(undo_symbol_pua("\u{F062}"), "β");
1049 assert_eq!(undo_symbol_pua("\u{F06D}"), "\u{00B5}");
1053 assert_eq!(undo_symbol_pua("\u{F03D}"), "=");
1054 assert_eq!(undo_symbol_pua("\u{F061}\u{F03D}\u{F062}"), "α=β");
1055 }
1056
1057 #[test]
1058 fn ordinary_text_is_untouched() {
1059 assert_eq!(undo_symbol_pua("hello"), "hello");
1060 assert_eq!(undo_symbol_pua("α = β"), "α = β");
1061 assert_eq!(undo_symbol_pua(""), "");
1062 }
1063
1064 #[test]
1065 fn private_use_outside_the_symbol_range_is_left_alone() {
1066 assert_eq!(undo_symbol_pua("\u{E000}"), "\u{E000}");
1069 assert_eq!(undo_symbol_pua("\u{F8FF}"), "\u{F8FF}");
1070 }
1071
1072 #[test]
1073 fn an_unmapped_symbol_slot_keeps_its_character() {
1074 assert_eq!(undo_symbol_pua("\u{F010}"), "\u{F010}");
1077 }
1078}