Skip to main content

hayro_font/
lib.rs

1/*!
2Parsing the fonts of PDF files.
3
4This crate turns PDF font dictionaries, together with their embedded font programs,
5into fonts that can map character codes to glyphs and draw the outlines of those glyphs.
6
7## Safety
8This crate forbids unsafe code via a crate-level attribute.
9
10## Cargo features
11- `embed-fonts`: Embed a light-weight set of fonts (around 240KB) that can be used as a
12  substitute for the 14 PDF standard fonts.
13*/
14
15#![forbid(unsafe_code)]
16#![deny(missing_docs)]
17
18use crate::cid::Type0Font;
19use crate::generated::{
20    glyph_names, mac_expert, mac_os_roman, mac_roman, standard, tex_glyph_names, win_ansi,
21    zapf_dings,
22};
23use crate::true_type::TrueTypeFont;
24use crate::type1::Type1Font;
25use crate::util::{CacheKey, hash128};
26use bitflags::bitflags;
27use hayro_cmap::{BfString, CMap, CMapName, CharacterCollection};
28use hayro_syntax::object::Name;
29use hayro_syntax::object::dict::keys::SUBTYPE;
30use hayro_syntax::object::dict::keys::*;
31use hayro_syntax::object::{Dict, Stream};
32use kurbo::{BezPath, Vec2};
33use outline::OutlineFont;
34use program::FontProgram;
35use rustc_hash::FxHashMap;
36use skrifa::ScalerFont;
37use std::borrow::Cow;
38use std::cell::RefCell;
39use std::fmt::Debug;
40use std::ops::Deref;
41use std::rc::Rc;
42use std::sync::Arc;
43
44mod cid;
45mod generated;
46mod outline;
47mod program;
48mod standard_font;
49mod true_type;
50mod type1;
51mod type3;
52mod util;
53
54pub use hayro_cmap;
55pub use hayro_syntax;
56pub use kurbo;
57pub use outline::OutlineFontData;
58pub use standard_font::StandardFont;
59pub use type3::{Type3Font, Type3Glyph};
60
61/// A callback function for resolving font queries.
62///
63/// The first argument is the raw data, the second argument is the index in case the font
64/// is a TTC, otherwise it should be 0.
65pub type FontResolverFn = Arc<dyn Fn(&FontQuery) -> Option<(FontData, u32)> + Send + Sync>;
66/// A callback function for resolving cmap names to their files.
67pub type CMapResolverFn = Arc<dyn Fn(CMapName<'_>) -> Option<&'static [u8]> + Send + Sync>;
68
69/// A container for the bytes of a font file.
70pub type FontData = Arc<dyn AsRef<[u8]> + Send + Sync>;
71
72/// The units per em that all outlines and metrics are scaled to.
73pub const UNITS_PER_EM: f32 = 1000.0;
74
75/// The ID of a glyph in a font.
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
77pub struct GlyphId(u32);
78
79impl GlyphId {
80    /// The ID of the `.notdef` glyph.
81    pub const NOTDEF: Self = Self(0);
82
83    /// Create a new glyph ID.
84    pub const fn new(id: u32) -> Self {
85        Self(id)
86    }
87
88    /// Return the ID as a number.
89    pub const fn to_u32(self) -> u32 {
90        self.0
91    }
92
93    pub(crate) fn to_skrifa(self) -> skrifa::GlyphId {
94        skrifa::GlyphId::new(self.0)
95    }
96
97    pub(crate) fn from_skrifa(glyph: skrifa::GlyphId) -> Self {
98        Self(glyph.to_u32())
99    }
100}
101
102/// A PDF font.
103#[derive(Clone, Debug)]
104pub struct Font<'a>(FontType<'a>);
105
106impl<'a> Font<'a> {
107    /// Map a character code to a glyph.
108    pub fn map_code(&self, code: u32) -> GlyphId {
109        match &self.0 {
110            FontType::Type1(f) => {
111                debug_assert!(code <= u8::MAX as u32);
112
113                f.map_code(code as u8)
114            }
115            FontType::TrueType(t) => {
116                debug_assert!(code <= u8::MAX as u32);
117
118                t.map_code(code as u8)
119            }
120            FontType::Type0(t) => t.map_code(code),
121            FontType::Type3(t) => {
122                debug_assert!(code <= u8::MAX as u32);
123
124                t.map_code(code as u8)
125            }
126        }
127    }
128
129    /// Return the glyph that a glyph ID refers to.
130    pub fn glyph(&self, glyph: GlyphId, char_code: u32) -> FontGlyph<'a> {
131        let font = match &self.0 {
132            FontType::Type1(t) => OutlineFont::Type1(t.clone()),
133            FontType::TrueType(t) => OutlineFont::TrueType(t.clone()),
134            FontType::Type0(t) => OutlineFont::Type0(t.clone()),
135            FontType::Type3(t) => {
136                return FontGlyph::Type3(Type3Glyph::new(t.clone(), glyph, char_code));
137            }
138        };
139
140        FontGlyph::Outline(OutlineGlyph::new(font, glyph, char_code))
141    }
142
143    /// Return the horizontal scale factor that stretches a glyph to the width the PDF
144    /// font expects for it.
145    pub fn glyph_stretch(&self, glyph: GlyphId, code: u32) -> f64 {
146        match &self.0 {
147            FontType::Type1(t) => t.glyph_stretch(glyph, code as u8),
148            FontType::TrueType(t) => t.glyph_stretch(glyph, code as u8),
149            FontType::Type0(t) => t.glyph_stretch(glyph, code),
150            FontType::Type3(_) => 1.0,
151        }
152    }
153
154    /// Return the advance of a character code.
155    pub fn code_advance(&self, code: u32) -> Vec2 {
156        match &self.0 {
157            FontType::Type1(t) => {
158                debug_assert!(code <= u8::MAX as u32);
159
160                Vec2::new(t.glyph_width(code as u8).unwrap_or(0.0) as f64, 0.0)
161            }
162            FontType::TrueType(t) => {
163                debug_assert!(code <= u8::MAX as u32);
164
165                Vec2::new(t.glyph_width(code as u8) as f64, 0.0)
166            }
167            FontType::Type0(t) => t.code_advance(code),
168            FontType::Type3(t) => {
169                debug_assert!(code <= u8::MAX as u32);
170
171                Vec2::new(t.glyph_width(code) as f64, 0.0)
172            }
173        }
174    }
175
176    /// Return the displacement of the glyph origin of a character code.
177    pub fn origin_displacement(&self, code: u32) -> Vec2 {
178        match &self.0 {
179            FontType::Type1(_) => Vec2::default(),
180            FontType::TrueType(_) => Vec2::default(),
181            FontType::Type0(t) => t.origin_displacement(code),
182            FontType::Type3(_) => Vec2::default(),
183        }
184    }
185
186    /// Read the next character code from a string, returning the code and its length.
187    pub fn read_code(&self, bytes: &[u8], offset: usize) -> (u32, usize) {
188        match &self.0 {
189            FontType::Type1(_) => (bytes[offset] as u32, 1),
190            FontType::TrueType(_) => (bytes[offset] as u32, 1),
191            FontType::Type0(t) => t.read_code(bytes, offset),
192            FontType::Type3(_) => (bytes[offset] as u32, 1),
193        }
194    }
195
196    /// Whether the font is written horizontally.
197    pub fn is_horizontal(&self) -> bool {
198        match &self.0 {
199            FontType::Type1(_) => true,
200            FontType::TrueType(_) => true,
201            FontType::Type0(t) => t.is_horizontal(),
202            FontType::Type3(_) => true,
203        }
204    }
205
206    fn new(dict: &Dict<'a>, loader: &FontLoader<'_>) -> Option<Self> {
207        let f_type = match dict.get::<Name<'_>>(SUBTYPE)?.deref() {
208            TYPE1 | MM_TYPE1 => FontType::Type1(Rc::new(Type1Font::new(dict, loader)?)),
209            // PDFBOX-5463: PDF viewers seem to accept OpenType as well.
210            TRUE_TYPE | OPEN_TYPE => FontType::TrueType(Rc::new(TrueTypeFont::new(dict, loader)?)),
211            TYPE0 => FontType::Type0(Rc::new(Type0Font::new(dict, loader)?)),
212            TYPE3 => FontType::Type3(Rc::new(Type3Font::new(dict, loader.cmap_resolver)?)),
213            _ => return None,
214        };
215
216        Some(Self(f_type))
217    }
218
219    fn new_standard(standard_font: StandardFont, loader: &ProgramLoader<'_>) -> Option<Self> {
220        let font = Type1Font::new_standard(standard_font, loader)?;
221
222        Some(Self(FontType::Type1(Rc::new(font))))
223    }
224}
225
226/// A cache for the fonts of a document and the font programs they use, so that each of
227/// them is only loaded once.
228#[derive(Clone, Default)]
229pub struct FontCache<'a>(Rc<FontCacheInner<'a>>);
230
231impl<'a> FontCache<'a> {
232    /// Create a new, empty cache.
233    pub fn new() -> Self {
234        Self::default()
235    }
236
237    /// Return the font described by a font dictionary.
238    pub fn font(
239        &self,
240        dict: &Dict<'a>,
241        font_resolver: &FontResolverFn,
242        cmap_resolver: &CMapResolverFn,
243    ) -> Option<Font<'a>> {
244        let key = dict.cache_key();
245
246        if let Some(font) = self.0.fonts.borrow().get(&key) {
247            return font.clone();
248        }
249
250        let loader = FontLoader {
251            programs: self.program_loader(font_resolver),
252            cmap_resolver,
253        };
254        let font = Font::new(dict, &loader);
255        self.0.fonts.borrow_mut().insert(key, font.clone());
256
257        font
258    }
259
260    /// Return one of the 14 standard fonts.
261    pub fn standard_font(
262        &self,
263        font: StandardFont,
264        font_resolver: &FontResolverFn,
265    ) -> Option<Font<'a>> {
266        Font::new_standard(font, &self.program_loader(font_resolver))
267    }
268
269    fn program_loader<'l>(&'l self, font_resolver: &'l FontResolverFn) -> ProgramLoader<'l> {
270        ProgramLoader {
271            font_resolver,
272            cache: &self.0.programs,
273        }
274    }
275}
276
277/// A cache for hinting font programs.
278#[derive(Clone, Default)]
279pub struct HintingCache(Rc<RefCell<HintedScalers>>);
280
281impl HintingCache {
282    /// Create a new, empty cache.
283    pub fn new() -> Self {
284        Self::default()
285    }
286
287    pub(crate) fn get_or_insert_with(
288        &self,
289        program: u128,
290        ppem: f32,
291        f: impl FnOnce() -> Option<ScalerFont>,
292    ) -> Option<Rc<ScalerFont>> {
293        let key = (program, ppem.to_bits());
294
295        if let Some(scaler) = self.0.borrow().get(&key) {
296            return scaler.clone();
297        }
298
299        let scaler = f().map(Rc::new);
300        self.0.borrow_mut().insert(key, scaler.clone());
301
302        scaler
303    }
304}
305
306/// A glyph of a [`Font`].
307#[derive(Clone, Debug)]
308pub enum FontGlyph<'a> {
309    /// A glyph defined by an outline.
310    Outline(OutlineGlyph),
311    /// A glyph of a Type 3 font, defined by a content stream of the font.
312    Type3(Type3Glyph<'a>),
313}
314
315/// A glyph defined by an outline.
316#[derive(Clone, Debug)]
317pub struct OutlineGlyph {
318    id: GlyphId,
319    program: FontProgram,
320    hidden: bool,
321    font: OutlineFont,
322    char_code: u32,
323}
324
325impl OutlineGlyph {
326    /// Return the outline of the glyph, assuming an upem value of 1000.
327    pub fn outline(&self) -> BezPath {
328        if self.hidden {
329            BezPath::new()
330        } else {
331            self.program.outline(self.id)
332        }
333    }
334
335    /// Return the outline of the glyph hinted at `ppem`, or `None` if its font can't be hinted.
336    pub fn hinted_outline(&self, ppem: f32, cache: &HintingCache) -> Option<BezPath> {
337        if self.hidden {
338            return Some(BezPath::new());
339        }
340
341        self.program.hinted_outline(self.id, ppem, cache)
342    }
343
344    /// Return the identifier of the glyph. You can use this to calculate the cache key
345    /// for the outline of the glyph.
346    pub fn identifier(&self) -> GlyphIdentifier {
347        GlyphIdentifier {
348            program: self.program.clone(),
349            glyph: (!self.hidden).then_some(self.id),
350        }
351    }
352
353    /// Returns the Unicode code point for this glyph, if available.
354    pub fn as_unicode(&self) -> Option<BfString> {
355        self.font.char_code_to_unicode(self.char_code)
356    }
357
358    /// Get raw font bytes and metadata for downstream use.
359    ///
360    /// Returns `None` for Type1 fonts.
361    pub fn font_data(&self) -> Option<OutlineFontData> {
362        self.font.font_data()
363    }
364
365    /// Get the glyph ID within the font.
366    pub fn glyph_id(&self) -> GlyphId {
367        self.id
368    }
369
370    /// Get the original character code that selected this glyph.
371    pub fn char_code(&self) -> u32 {
372        self.char_code
373    }
374
375    /// Get the advance width for this glyph.
376    ///
377    /// The advance width is how far to move horizontally after drawing
378    /// this glyph before drawing the next one.
379    pub fn advance_width(&self) -> Option<f32> {
380        self.font.glyph_advance_width(self.char_code)
381    }
382
383    fn new(font: OutlineFont, id: GlyphId, char_code: u32) -> Self {
384        Self {
385            id,
386            program: font.program(),
387            hidden: id == GlyphId::NOTDEF && font.hides_notdef(),
388            font,
389            char_code,
390        }
391    }
392}
393
394/// An identifier that uniquely identifies the outline of a glyph, for caching purposes.
395#[derive(Clone, Debug, PartialEq, Eq, Hash)]
396pub struct GlyphIdentifier {
397    program: FontProgram,
398    glyph: Option<GlyphId>,
399}
400
401impl GlyphIdentifier {
402    /// Return the cache key of the glyph.
403    pub fn cache_key(&self) -> u128 {
404        hash128(self)
405    }
406}
407
408/// A query for a font.
409#[derive(Hash)]
410pub enum FontQuery {
411    /// A query for one of the 14 PDF standard fonts.
412    Standard(StandardFont),
413    /// A query for a font that is not embedded in the PDF file.
414    ///
415    /// Note that this type of query is currently not supported,
416    /// but will be implemented in the future.
417    Fallback(FallbackFontQuery),
418}
419
420/// A query for a font with specific properties.
421#[derive(Debug, Clone, Hash)]
422pub struct FallbackFontQuery {
423    /// The postscript name of the font.
424    pub post_script_name: Option<String>,
425    /// The name of the font.
426    pub font_name: Option<String>,
427    /// The family of the font.
428    pub font_family: Option<String>,
429    /// The stretch of the font.
430    pub font_stretch: FontStretch,
431    /// The weight of the font.
432    pub font_weight: u32,
433    /// Whether the font is monospaced.
434    pub is_fixed_pitch: bool,
435    /// Whether the font is serif.
436    pub is_serif: bool,
437    /// Whether the font is italic.
438    pub is_italic: bool,
439    /// Whether the font is bold.
440    pub is_bold: bool,
441    /// Whether the font is small cap.
442    pub is_small_cap: bool,
443    /// The character collection (registry/ordering) if this is a CID font.
444    pub character_collection: Option<CharacterCollection>,
445}
446
447impl FallbackFontQuery {
448    pub(crate) fn new(dict: &Dict<'_>) -> Self {
449        let post_script_name = dict
450            .get::<Name<'_>>(BASE_FONT)
451            .map(|n| strip_subset_prefix(n.as_str()).to_string());
452
453        let mut data = Self {
454            post_script_name,
455            ..Default::default()
456        };
457
458        if let Some(descriptor) = dict.get::<Dict<'_>>(FONT_DESC) {
459            data.font_name = dict
460                .get::<Name<'_>>(FONT_NAME)
461                .map(|n| strip_subset_prefix(n.as_str()).to_string());
462            data.font_family = descriptor
463                .get::<Name<'_>>(FONT_FAMILY)
464                .map(|n| n.as_str().to_string());
465            data.font_stretch = descriptor
466                .get::<Name<'_>>(FONT_STRETCH)
467                .map(|n| FontStretch::from_string(n.as_str()))
468                .unwrap_or(FontStretch::Normal);
469            data.font_weight = descriptor.get::<u32>(FONT_WEIGHT).unwrap_or(400);
470
471            if let Some(flags) = descriptor
472                .get::<u32>(FLAGS)
473                .map(FontFlags::from_bits_truncate)
474            {
475                data.is_serif = flags.contains(FontFlags::SERIF);
476                data.is_italic = flags.contains(FontFlags::ITALIC);
477                data.is_small_cap = flags.contains(FontFlags::SMALL_CAP);
478            }
479        }
480
481        data.is_italic |= data
482            .post_script_name
483            .as_ref()
484            .is_some_and(|s| s.contains("Italic"));
485
486        data.is_bold |= data
487            .post_script_name
488            .as_ref()
489            .is_some_and(|s| s.contains("Bold"));
490
491        data
492    }
493
494    /// Do a best-effort fallback to the 14 standard fonts based on the query.
495    pub fn pick_standard_font(&self) -> StandardFont {
496        if self.is_fixed_pitch {
497            match (self.is_bold, self.is_italic) {
498                (true, true) => StandardFont::CourierBoldOblique,
499                (true, false) => StandardFont::CourierBold,
500                (false, true) => StandardFont::CourierOblique,
501                (false, false) => StandardFont::Courier,
502            }
503        } else if !self.is_serif {
504            match (self.is_bold, self.is_italic) {
505                (true, true) => StandardFont::HelveticaBoldOblique,
506                (true, false) => StandardFont::HelveticaBold,
507                (false, true) => StandardFont::HelveticaOblique,
508                (false, false) => StandardFont::Helvetica,
509            }
510        } else {
511            match (self.is_bold, self.is_italic) {
512                (true, true) => StandardFont::TimesBoldItalic,
513                (true, false) => StandardFont::TimesBold,
514                (false, true) => StandardFont::TimesItalic,
515                (false, false) => StandardFont::TimesRoman,
516            }
517        }
518    }
519}
520
521impl Default for FallbackFontQuery {
522    fn default() -> Self {
523        Self {
524            post_script_name: None,
525            font_name: None,
526            font_family: None,
527            font_stretch: FontStretch::Normal,
528            font_weight: 400,
529            is_fixed_pitch: false,
530            is_serif: false,
531            is_italic: false,
532            is_bold: false,
533            is_small_cap: false,
534            character_collection: None,
535        }
536    }
537}
538
539/// The font stretch.
540#[derive(Debug, Copy, Clone, Hash)]
541pub enum FontStretch {
542    /// Normal.
543    Normal,
544    /// Ultra condensed.
545    UltraCondensed,
546    /// Extra condensed.
547    ExtraCondensed,
548    /// Condensed.
549    Condensed,
550    /// Semi condensed.
551    SemiCondensed,
552    /// Semi expanded.
553    SemiExpanded,
554    /// Expanded.
555    Expanded,
556    /// Extra expanded.
557    ExtraExpanded,
558    /// Ultra expanded.
559    UltraExpanded,
560}
561
562impl FontStretch {
563    fn from_string(s: &str) -> Self {
564        match s {
565            "UltraCondensed" => Self::UltraCondensed,
566            "ExtraCondensed" => Self::ExtraCondensed,
567            "Condensed" => Self::Condensed,
568            "SemiCondensed" => Self::SemiCondensed,
569            "SemiExpanded" => Self::SemiExpanded,
570            "Expanded" => Self::Expanded,
571            "ExtraExpanded" => Self::ExtraExpanded,
572            "UltraExpanded" => Self::UltraExpanded,
573            _ => Self::Normal,
574        }
575    }
576}
577
578#[derive(Default)]
579struct FontCacheInner<'a> {
580    fonts: RefCell<FxHashMap<u128, Option<Font<'a>>>>,
581    programs: ProgramMap,
582}
583
584type ProgramMap = RefCell<FxHashMap<u128, Option<FontProgram>>>;
585type HintedScalers = FxHashMap<(u128, u32), Option<Rc<ScalerFont>>>;
586
587pub(crate) struct FontLoader<'l> {
588    pub(crate) programs: ProgramLoader<'l>,
589    pub(crate) cmap_resolver: &'l CMapResolverFn,
590}
591
592pub(crate) struct ProgramLoader<'l> {
593    font_resolver: &'l FontResolverFn,
594    cache: &'l ProgramMap,
595}
596
597impl ProgramLoader<'_> {
598    pub(crate) fn load(&self, stream: &Stream<'_>) -> Option<FontProgram> {
599        let key = hash128(&("font program", stream.cache_key()));
600
601        self.get_or_insert_with(key, || {
602            FontProgram::new(Arc::new(stream.decoded_data().ok()?.into_owned()), 0)
603        })
604    }
605
606    pub(crate) fn resolve(&self, query: &FontQuery) -> Option<FontProgram> {
607        let key = hash128(&("resolved font program", query));
608
609        self.get_or_insert_with(key, || {
610            let (data, index) = (self.font_resolver)(query)?;
611            FontProgram::new(data, index)
612        })
613    }
614
615    fn get_or_insert_with(
616        &self,
617        key: u128,
618        f: impl FnOnce() -> Option<FontProgram>,
619    ) -> Option<FontProgram> {
620        if let Some(program) = self.cache.borrow().get(&key) {
621            return program.clone();
622        }
623
624        let program = f();
625        self.cache.borrow_mut().insert(key, program.clone());
626
627        program
628    }
629}
630
631#[derive(Clone, Debug)]
632enum FontType<'a> {
633    Type1(Rc<Type1Font>),
634    TrueType(Rc<TrueTypeFont>),
635    Type0(Rc<Type0Font>),
636    Type3(Rc<Type3Font<'a>>),
637}
638
639#[derive(Debug)]
640enum Encoding {
641    Standard,
642    MacRoman,
643    WinAnsi,
644    MacExpert,
645    BuiltIn,
646}
647
648impl Encoding {
649    fn map_code(&self, code: u8) -> Option<&'static str> {
650        if code == 0 {
651            return Some(".notdef");
652        }
653        match self {
654            Self::Standard => standard::get(code),
655            Self::MacRoman => mac_roman::get(code).or_else(|| mac_os_roman::get(code)),
656            Self::WinAnsi => win_ansi::get(code),
657            Self::MacExpert => mac_expert::get(code),
658            Self::BuiltIn => None,
659        }
660    }
661}
662
663bitflags! {
664    /// Bitflags describing various characteristics of fonts.
665    #[derive(Debug)]
666    pub(crate) struct FontFlags: u32 {
667        const FIXED_PITCH = 1 << 0;
668        const SERIF = 1 << 1;
669        const SYMBOLIC = 1 << 2;
670        const SCRIPT = 1 << 3;
671        const NON_SYMBOLIC = 1 << 5;
672        const ITALIC = 1 << 6;
673        const ALL_CAP = 1 << 16;
674        const SMALL_CAP = 1 << 17;
675        const FORCE_BOLD = 1 << 18;
676    }
677}
678
679pub(crate) fn stretch_factor(expected_width: f32, actual_width: f32) -> f64 {
680    if actual_width != 0.0 && actual_width != expected_width {
681        f64::from(expected_width / actual_width)
682    } else {
683        1.0
684    }
685}
686
687/// Strip the 6-character subset prefix from a PostScript font name.
688///
689/// PDF subset fonts use names like "ABCDEF+TimesNewRoman". This function
690/// returns `TimesNewRoman` from such a name, or the original name if no
691/// valid prefix is found.
692pub(crate) fn strip_subset_prefix(name: &str) -> &str {
693    match name.split_once('+') {
694        Some((prefix, rest)) if prefix.len() == 6 => rest,
695        _ => name,
696    }
697}
698
699/// Convert a glyph name to its Unicode value, if possible, as described in the Adobe Glyph List
700/// Specification (<https://github.com/adobe-type-tools/agl-specification>), with the AGL
701/// extended by glyph names used in the Computer Modern and AMS fonts.
702pub(crate) fn glyph_name_to_unicode(name: &str, is_zapf_dingbats: bool) -> Option<BfString> {
703    let base = name.split('.').next().unwrap_or_default();
704    let mut out = String::new();
705
706    for component in base.split('_') {
707        if let Some(c) = is_zapf_dingbats
708            .then(|| zapf_dings::glyph_name_to_unicode(component))
709            .flatten()
710        {
711            out.push(c);
712        } else if let Some(unicode_str) =
713            glyph_names::get(component).or_else(|| tex_glyph_names::get(component))
714        {
715            out.push_str(unicode_str);
716        } else if let Some(unicode_str) = uni_component(component) {
717            out.push_str(&unicode_str);
718        } else if let Some(c) = u_component(component) {
719            out.push(c);
720        }
721    }
722
723    bf_string_from_str(&out)
724}
725
726fn uni_component(component: &str) -> Option<String> {
727    let digits = component.strip_prefix("uni")?.as_bytes();
728
729    if digits.is_empty() || digits.len() % 4 != 0 {
730        return None;
731    }
732
733    digits
734        .as_chunks::<4>()
735        .0
736        .iter()
737        .map(|group| char::from_u32(parse_uppercase_hex(group)?))
738        .collect()
739}
740
741fn u_component(component: &str) -> Option<char> {
742    let digits = component.strip_prefix('u')?.as_bytes();
743
744    if !(4..=6).contains(&digits.len()) {
745        return None;
746    }
747
748    char::from_u32(parse_uppercase_hex(digits)?)
749}
750
751fn parse_uppercase_hex(digits: &[u8]) -> Option<u32> {
752    digits.iter().try_fold(0_u32, |value, digit| {
753        let digit = match digit {
754            b'0'..=b'9' => digit - b'0',
755            b'A'..=b'F' => digit - b'A' + 10,
756            _ => return None,
757        };
758
759        Some(value * 16 + u32::from(digit))
760    })
761}
762
763fn bf_string_from_str(s: &str) -> Option<BfString> {
764    let mut chars = s.chars();
765    match (chars.next(), chars.next()) {
766        (Some(c), None) => Some(BfString::Char(c)),
767        (Some(_), Some(_)) => Some(BfString::String(s.to_string())),
768        (None, _) => None,
769    }
770}
771
772pub(crate) fn unicode_from_name(name: &str) -> Option<char> {
773    let convert = |input: &str| u32::from_str_radix(input, 16).ok().and_then(char::from_u32);
774
775    name.starts_with("uni")
776        .then(|| name.get(3..).and_then(convert))
777        .or_else(|| {
778            name.starts_with("u")
779                .then(|| name.get(1..).and_then(convert))
780        })
781        .flatten()
782}
783
784pub(crate) fn read_to_unicode(dict: &Dict<'_>, cmap_resolver: &CMapResolverFn) -> Option<CMap> {
785    dict.get::<Stream<'_>>(TO_UNICODE)
786        .and_then(|s| s.decoded_data().ok())
787        // See PDFJS-11915, where `Identity-H` is used for `ToUnicode`. I don't
788        // believe it's valid, but at least mupdf seems to be able to deal with it.
789        .or_else(|| {
790            dict.get::<Name<'_>>(TO_UNICODE)
791                .and_then(|name| (cmap_resolver)(CMapName::from_bytes(name.as_ref())))
792                .map(|d| Cow::Owned(d.to_vec()))
793        })
794        .and_then(|data| {
795            let cmap_resolver = cmap_resolver.clone();
796            CMap::parse(&data, move |name| (cmap_resolver)(name))
797        })
798}
799
800// When mapping to glyphs, some fonts might only have a glyph for the "normalized"
801// name.
802pub(crate) fn normalized_glyph_name(mut name: &str) -> &str {
803    if name == "nbspace" {
804        name = "space";
805    }
806
807    if name == "sfthyphen" {
808        name = "hyphen";
809    }
810
811    name
812}
813
814#[cfg(test)]
815mod tests {
816    use super::glyph_name_to_unicode;
817    use hayro_cmap::BfString;
818
819    fn map(name: &str) -> Option<String> {
820        glyph_name_to_unicode(name, false).map(|unicode| match unicode {
821            BfString::Char(c) => c.to_string(),
822            BfString::String(s) => s,
823        })
824    }
825
826    #[test]
827    fn agl_specification_examples() {
828        assert_eq!(map("Lcommaaccent").as_deref(), Some("\u{013B}"));
829        assert_eq!(map("uni20AC0308").as_deref(), Some("\u{20AC}\u{0308}"));
830        assert_eq!(map("u1040C").as_deref(), Some("\u{1040C}"));
831        assert_eq!(map("uniD801DC0C"), None);
832        assert_eq!(map("uni20ac"), None);
833        assert_eq!(
834            map("Lcommaaccent_uni20AC0308_u1040C.alternate").as_deref(),
835            Some("\u{013B}\u{20AC}\u{0308}\u{1040C}")
836        );
837        assert_eq!(map("foo"), None);
838        assert_eq!(map(".notdef"), None);
839    }
840
841    #[test]
842    fn components() {
843        assert_eq!(map("dalethatafpatah").as_deref(), Some("\u{05D3}\u{05B2}"));
844        assert_eq!(map("hyphen.case").as_deref(), Some("-"));
845        assert_eq!(map("f_f_l").as_deref(), Some("ffl"));
846        assert_eq!(map("f_g102").as_deref(), Some("f"));
847        assert_eq!(map("uni000A0020").as_deref(), Some("\n "));
848        assert_eq!(map("u41"), None);
849        assert_eq!(map("u110000"), None);
850    }
851}