Skip to main content

pdf2_render/
font.rs

1//! Fonts for text rendering: a provider trait, a built-in base-14 fallback,
2//! TrueType outlines through `ttf-parser`, and CFF outlines — CID-keyed or
3//! plain — by wrapping the bare CFF program in the smallest OpenType container
4//! `ttf-parser` will read.
5//!
6//! The wrapper exists because PDF carries two shapes of CFF: `/Subtype
7//! /OpenType` (already an sfnt, read directly) and `/Subtype /CIDFontType0C` or
8//! `/Type1C` (a bare CFF table, which `ttf-parser` refuses: "Invalid sfnt
9//! version"). Five synthesised tables — `head`, `hhea`, `maxp`, `hmtx` and the
10//! program itself — are enough, and the decision, its measurements and what it
11//! refuses are in `docs/adr/0003-cff-without-a-dependency.md`.
12
13use std::cell::RefCell;
14use std::collections::BTreeMap;
15use std::rc::Rc;
16
17use pdf2::Encoding;
18
19use crate::geom::Point;
20
21/// A font's parsed answers, shared by its clones.
22///
23/// `ttf-parser` borrows the program, so a parsed face cannot outlive the call
24/// that made it — but its answers can. Two maps memoise the expensive steps:
25/// character → glyph id (the `cmap` lookup) and glyph id → outline. Measured on
26/// `book.pdf` at scale 0.25, where the rasteriser is not the bottleneck, this
27/// halves the page: 5.4 ms → 3.9 ms.
28#[derive(Debug, Default)]
29pub struct Cache {
30    /// Character → glyph id, `None` when the `cmap` does not cover it.
31    cmap: BTreeMap<char, Option<u16>>,
32    /// Glyph id → outline and advance.
33    glyphs: BTreeMap<u16, Option<Glyph>>,
34}
35
36/// The shared cache behind a font's clones.
37pub type GlyphCache = Rc<RefCell<Cache>>;
38
39/// One glyph's outline in em units: y grows upwards, the baseline is y = 0 and
40/// one em is 1.0.
41#[derive(Debug, Clone, Default, PartialEq)]
42pub struct Glyph {
43    /// Closed contours of the outline.
44    pub contours: Vec<Vec<Point>>,
45    /// Advance width in em units.
46    pub advance: f64,
47}
48
49/// A resolved font ready to place glyphs.
50#[derive(Debug, Clone)]
51pub enum Font {
52    /// The built-in fallback: a 5×7 bitmap alphabet, used when the document
53    /// carries no usable font program (all of the base-14 cases).
54    Builtin {
55        /// Code → character table.
56        encoding: Encoding,
57    },
58    /// An embedded Type 1 program (`/FontFile`), whose glyphs are charstrings
59    /// (`crate::type1`). A simple font's code reaches a glyph through its
60    /// encoding's *name*, so the program is indexed by the character each name
61    /// stands for.
62    Type1 {
63        /// Code → character table.
64        encoding: Encoding,
65        /// The parsed program, shared with the clones of this font.
66        program: Rc<crate::type1::Program>,
67        /// Character → glyph name, for the names the library can resolve.
68        names: std::collections::HashMap<char, Vec<u8>>,
69    },
70    /// An embedded CFF program, wrapped so the outlines come out of the same
71    /// code path as TrueType. CID-keyed fonts select glyphs through their
72    /// charset, not by using the CID as a glyph id.
73    Cff {
74        /// Code → character table, for the (rare) simple CFF font.
75        encoding: Encoding,
76        /// The program as sfnt bytes.
77        data: Vec<u8>,
78        /// CID → glyph id from the CFF charset, empty when the font is not
79        /// CID-keyed.
80        cid_to_gid: Vec<(u16, u16)>,
81        /// A **simple** (non-CID) CFF font selects its glyphs by name: the
82        /// charset names each glyph, and a code reaches one through the
83        /// encoding's character. A bare CFF carries no `cmap`, so this is the
84        /// only route to its outlines.
85        names: std::collections::HashMap<char, u16>,
86        /// Parsed answers, shared by clones.
87        cache: GlyphCache,
88    },
89    /// An embedded TrueType program.
90    TrueType {
91        /// Code → character table.
92        encoding: Encoding,
93        /// The font program, still compressed in the PDF sense is not our
94        /// business: this is the decoded `/FontFile2`.
95        data: Vec<u8>,
96        /// Whether the program carries a `cmap` table at all: when it does not,
97        /// a simple font's code is the glyph id.
98        has_cmap: bool,
99        /// Parsed answers, shared by clones.
100        cache: GlyphCache,
101    },
102}
103
104impl Font {
105    /// The built-in fallback with an encoding.
106    pub fn builtin(encoding: Encoding) -> Self {
107        Self::Builtin { encoding }
108    }
109
110    /// An embedded CFF program, bare or already wrapped in OpenType.
111    ///
112    /// `/CIDFontType0C` and `/Type1C` programs are a CFF table with no container;
113    /// they are wrapped here so the same outline code reads them.
114    pub fn cff(encoding: Encoding, data: Vec<u8>) -> Option<Self> {
115        let wrapped = data.starts_with(b"OTTO");
116        let table: Vec<u8> = if wrapped {
117            cff_table_of_sfnt(&data)?.to_vec()
118        } else {
119            data.clone()
120        };
121        let (charset_at, glyphs) = cff_layout(&table)?;
122        // A CID-keyed font's Top DICT declares an ROS; without one the charset
123        // holds *names* (SIDs), which is what a simple font selects by.
124        let cid_to_gid = if top_dict_declares_ros(&table) {
125            cff_charset(&table, charset_at, glyphs)
126        } else {
127            Vec::new()
128        };
129        let program = if wrapped {
130            data
131        } else {
132            wrap_cff(&table, glyphs)?
133        };
134        // Parse once here so a program that cannot be read is rejected at load,
135        // not at the first glyph.
136        let face = ttf_parser::Face::parse(&program, 0).ok()?;
137        let names = if cid_to_gid.is_empty() {
138            glyph_names(&face)
139        } else {
140            std::collections::HashMap::new()
141        };
142        Some(Self::Cff {
143            encoding,
144            data: program,
145            cid_to_gid,
146            names,
147            cache: GlyphCache::default(),
148        })
149    }
150
151    /// A Type 1 program, indexed by the character each glyph name stands for.
152    ///
153    /// `None` when the program has no usable glyphs, which is what makes the
154    /// caller fall back rather than draw nothing.
155    pub fn type1(encoding: Encoding, program: crate::type1::Program) -> Option<Self> {
156        if !program.is_usable() {
157            return None;
158        }
159        let mut names = std::collections::HashMap::new();
160        for name in program.names() {
161            if let Some(character) = pdf2::encoding::glyph_name_character(name) {
162                names.entry(character).or_insert_with(|| name.to_vec());
163            }
164        }
165        Some(Self::Type1 {
166            encoding,
167            program: Rc::new(program),
168            names,
169        })
170    }
171
172    /// An embedded TrueType program, rejected when it cannot be parsed.
173    pub fn true_type(encoding: Encoding, data: Vec<u8>) -> Option<Self> {
174        let face = ttf_parser::Face::parse(&data, 0).ok()?;
175        if face.units_per_em() == 0 {
176            return None;
177        }
178        let has_cmap = face.tables().cmap.is_some();
179        Some(Self::TrueType {
180            encoding,
181            data,
182            has_cmap,
183            cache: GlyphCache::default(),
184        })
185    }
186
187    /// The outline and advance for a byte code, or `None` when there is no
188    /// glyph for it.
189    ///
190    /// A simple font's code goes through its encoding to a character, and the
191    /// character through the program's `cmap` to a glyph id. A program with **no
192    /// `cmap` table at all** cannot be consulted that way, and the files that
193    /// lack one mean the code *is* the glyph id — pdf.js's
194    /// `TrueType_without_cmap.pdf` is the case, and refusing to guess drew a
195    /// blank page while reporting nothing at all.
196    pub fn glyph(&self, code: u8) -> Option<Glyph> {
197        match self {
198            Self::Builtin { encoding } => builtin_glyph(encoding.character(code)?),
199            Self::Type1 {
200                encoding,
201                program,
202                names,
203            } => {
204                let character = encoding.character(code)?;
205                program.glyph(names.get(&character)?)
206            }
207            Self::TrueType {
208                encoding,
209                data,
210                cache,
211                ..
212            } => {
213                let character = encoding.character(code)?;
214                cached_glyph(data, cache, glyph_id(data, cache, character)?)
215            }
216            Self::Cff {
217                encoding,
218                data,
219                names,
220                cache,
221                ..
222            } => {
223                let character = encoding.character(code)?;
224                // A simple (non-CID) CFF font reaches its glyphs through the
225                // charset's names; a CID-keyed one through the CID it is asked
226                // for, which is the composite path.
227                let id = if names.is_empty() {
228                    glyph_id(data, cache, character)?
229                } else {
230                    ttf_parser::GlyphId(*names.get(&character)?)
231                };
232                cached_glyph(data, cache, id)
233            }
234        }
235    }
236
237    /// Whether glyphs are selectable at all — the name map of a simple CFF, a
238    /// `cmap` of a TrueType program.
239    pub fn has_glyph_names(&self) -> bool {
240        match self {
241            Self::Type1 { names, .. } => !names.is_empty(),
242            Self::Cff { names, .. } => !names.is_empty(),
243            Self::TrueType { has_cmap, .. } => *has_cmap,
244            Self::Builtin { .. } => false,
245        }
246    }
247
248    /// Whether this font has a character map at all.
249    ///
250    /// A simple TrueType program with none cannot be decoded from its codes, so
251    /// the caller reports the page instead of drawing an empty one.
252    pub fn has_character_map(&self) -> bool {
253        match self {
254            Self::Builtin { .. } | Self::Cff { .. } | Self::Type1 { .. } => true,
255            Self::TrueType { has_cmap, .. } => *has_cmap,
256        }
257    }
258
259    /// The advance of a code in em units, falling back to the built-in metric.
260    pub fn advance(&self, code: u8) -> f64 {
261        self.glyph(code)
262            .map_or(BUILTIN_ADVANCE, |glyph| glyph.advance)
263    }
264
265    /// The outline for a glyph id, which is how composite (Type 0) fonts select
266    /// glyphs: a CID maps to an id through `/CIDToGIDMap`, not through a cmap.
267    ///
268    /// The built-in bitmap alphabet has no glyph ids, so it has no answer here.
269    pub fn glyph_by_id(&self, id: u16) -> Option<Glyph> {
270        match self {
271            Self::Builtin { .. } => None,
272            Self::TrueType { data, cache, .. } => {
273                cached_glyph(data, cache, ttf_parser::GlyphId(id))
274            }
275            Self::Type1 { .. } => None,
276            Self::Cff {
277                data,
278                cid_to_gid,
279                cache,
280                ..
281            } => {
282                // In a CID-keyed CFF the charset maps glyph ids to CIDs, so a
283                // CID has to be looked up rather than used as the glyph id.
284                let glyph = cid_to_gid
285                    .iter()
286                    .find(|(cid, _)| *cid == id)
287                    .map_or(id, |(_, gid)| *gid);
288                cached_glyph(data, cache, ttf_parser::GlyphId(glyph))
289            }
290        }
291    }
292}
293
294/// The character each glyph of a simple CFF font is named for.
295///
296/// A name that is not a character name (`/uni20AC` style is handled by the
297/// library's table) simply does not appear, and the code that would have
298/// selected it draws nothing rather than a wrong glyph.
299fn glyph_names(face: &ttf_parser::Face<'_>) -> std::collections::HashMap<char, u16> {
300    let mut map = std::collections::HashMap::new();
301    for id in 0..face.number_of_glyphs() {
302        let Some(name) = face.glyph_name(ttf_parser::GlyphId(id)) else {
303            continue;
304        };
305        if let Some(character) = pdf2::encoding::glyph_name_character(name.as_bytes()) {
306            map.entry(character).or_insert(id);
307        }
308    }
309    map
310}
311
312/// A character's glyph id, memoised: the `cmap` lookup needs a parsed face.
313fn glyph_id(data: &[u8], cache: &GlyphCache, character: char) -> Option<ttf_parser::GlyphId> {
314    if let Some(cached) = cache.borrow().cmap.get(&character) {
315        return cached.map(ttf_parser::GlyphId);
316    }
317    let face = ttf_parser::Face::parse(data, 0).ok()?;
318    let found = face.glyph_index(character).map(|id| id.0);
319    cache.borrow_mut().cmap.insert(character, found);
320    found.map(ttf_parser::GlyphId)
321}
322
323/// An outline and advance, memoised: the parse is the expensive part.
324fn cached_glyph(data: &[u8], cache: &GlyphCache, id: ttf_parser::GlyphId) -> Option<Glyph> {
325    if let Some(cached) = cache.borrow().glyphs.get(&id.0) {
326        return cached.clone();
327    }
328    let glyph = glyph_from_face(data, id);
329    cache.borrow_mut().glyphs.insert(id.0, glyph.clone());
330    glyph
331}
332
333/// Wrap a bare CFF table in the smallest OpenType container `ttf-parser` reads.
334///
335/// The synthesised tables say only what outlines need: 1000 units per em (CFF's
336/// default `/FontMatrix` is 0.001), the glyph count from the CFF `CharStrings`
337/// INDEX, and zero advances, because a CID font's advances come from `/W` in the
338/// PDF. Checksums are left zero: `ttf-parser` does not read them, and inventing
339/// them would be a claim nobody checks.
340fn wrap_cff(cff: &[u8], glyphs: u16) -> Option<Vec<u8>> {
341    let mut head = [0_u8; 54];
342    head[0..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
343    head[4..8].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
344    head[12..16].copy_from_slice(&0x5F0F_3CF5_u32.to_be_bytes());
345    head[18..20].copy_from_slice(&1000_u16.to_be_bytes());
346    let mut hhea = [0_u8; 36];
347    hhea[0..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
348    hhea[34..36].copy_from_slice(&glyphs.to_be_bytes());
349    let mut maxp = [0_u8; 6];
350    maxp[0..4].copy_from_slice(&0x0000_5000_u32.to_be_bytes());
351    maxp[4..6].copy_from_slice(&glyphs.to_be_bytes());
352    let hmtx = vec![0_u8; usize::from(glyphs) * 4];
353
354    let tables: [(&[u8; 4], &[u8]); 5] = [
355        (b"CFF ", cff),
356        (b"head", &head),
357        (b"hhea", &hhea),
358        (b"hmtx", &hmtx),
359        (b"maxp", &maxp),
360    ];
361    let count = u16::try_from(tables.len()).ok()?;
362    let mut out = Vec::with_capacity(cff.len() + 256);
363    out.extend_from_slice(&0x4F54_544F_u32.to_be_bytes());
364    out.extend_from_slice(&count.to_be_bytes());
365    let pow2 = 1_u32 << u32::from(count).ilog2();
366    #[allow(clippy::cast_possible_truncation)]
367    let search_range = pow2 * 16;
368    out.extend_from_slice(&u16::try_from(search_range).ok()?.to_be_bytes());
369    #[allow(clippy::cast_possible_truncation)]
370    let entry_selector = count.trailing_zeros() as u16;
371    out.extend_from_slice(&entry_selector.to_be_bytes());
372    #[allow(clippy::cast_possible_truncation)]
373    let range_shift = (u32::from(count) * 16).saturating_sub(search_range) as u16;
374    out.extend_from_slice(&range_shift.to_be_bytes());
375
376    let mut offset = 12 + usize::from(count) * 16;
377    let mut body: Vec<u8> = Vec::with_capacity(cff.len() + 128);
378    for (tag, data) in &tables {
379        let mut table = data.to_vec();
380        while !table.len().is_multiple_of(4) {
381            table.push(0);
382        }
383        out.extend_from_slice(*tag);
384        out.extend_from_slice(&0_u32.to_be_bytes());
385        out.extend_from_slice(&u32::try_from(offset).ok()?.to_be_bytes());
386        out.extend_from_slice(&u32::try_from(data.len()).ok()?.to_be_bytes());
387        offset += table.len();
388        body.extend_from_slice(&table);
389    }
390    out.extend_from_slice(&body);
391    Some(out)
392}
393
394/// The `CFF ` table inside an OpenType file.
395fn cff_table_of_sfnt(data: &[u8]) -> Option<&[u8]> {
396    let count = usize::from(u16::from_be_bytes([*data.get(4)?, *data.get(5)?]));
397    for index in 0..count {
398        let at = 12 + index * 16;
399        if data.get(at..at + 4)? == b"CFF " {
400            let offset = u32::from_be_bytes([
401                *data.get(at + 8)?,
402                *data.get(at + 9)?,
403                *data.get(at + 10)?,
404                *data.get(at + 11)?,
405            ]);
406            let length = u32::from_be_bytes([
407                *data.get(at + 12)?,
408                *data.get(at + 13)?,
409                *data.get(at + 14)?,
410                *data.get(at + 15)?,
411            ]);
412            let start = usize::try_from(offset).ok()?;
413            let end = start.checked_add(usize::try_from(length).ok()?)?;
414            return data.get(start..end);
415        }
416    }
417    None
418}
419
420/// A CFF table's charset offset and glyph count.
421fn cff_layout(cff: &[u8]) -> Option<(usize, u16)> {
422    let header_size = usize::from(*cff.get(2)?);
423    let (_, after_name) = cff_index(cff, header_size)?;
424    let (top_count, after_top) = cff_index(cff, after_name)?;
425    if top_count == 0 {
426        return None;
427    }
428    let (_, after_strings) = cff_index(cff, after_top)?;
429    let (_, after_global_subrs) = cff_index(cff, after_strings)?;
430    let _ = after_global_subrs;
431    let top_dict = cff_index_item(cff, after_name, 0)?;
432    let charstrings_at = top_dict_operator(top_dict, 17)?;
433    let (glyphs, _) = cff_index(cff, charstrings_at)?;
434    let charset_at = top_dict_operator(top_dict, 15).unwrap_or(0);
435    Some((charset_at, u16::try_from(glyphs).ok()?))
436}
437
438/// Whether the Top DICT declares an ROS (registry, ordering, supplement), which
439/// is what makes a CFF font CID-keyed (`9.7.4` of the CFF spec).
440fn top_dict_declares_ros(cff: &[u8]) -> bool {
441    let Some(header_size) = cff.get(2).map(|size| usize::from(*size)) else {
442        return false;
443    };
444    let Some((_, after_name)) = cff_index(cff, header_size) else {
445        return false;
446    };
447    let Some(dict) = cff_index_item(cff, after_name, 0) else {
448        return false;
449    };
450    // Operator 12 30 (ROS): operands, then the two bytes, in that order.
451    dict.array_windows::<2>().any(|window| window == &[12, 30])
452}
453
454/// The CID → glyph id pairs a CID-keyed CFF charset declares.
455///
456/// Formats 0, 1 and 2 are read; the three predefined charsets (offsets 0, 1 and
457/// 2) are the standard Latin character sets, which are not CID-keyed, so they
458/// yield no pairs and the CID is used as the glyph id.
459fn cff_charset(cff: &[u8], at: usize, glyphs: u16) -> Vec<(u16, u16)> {
460    let mut pairs = Vec::new();
461    if at < 3 {
462        return pairs;
463    }
464    let Some(&format) = cff.get(at) else {
465        return pairs;
466    };
467    let mut index = at + 1;
468    let mut gid = 1u16;
469    match format {
470        0 => {
471            while gid < glyphs {
472                let cid = cff
473                    .get(index..index + 2)
474                    .map(|bytes| u16::from_be_bytes([bytes[0], bytes[1]]));
475                let Some(cid) = cid else { break };
476                pairs.push((cid, gid));
477                gid += 1;
478                index += 2;
479            }
480        }
481        1 | 2 => {
482            while gid < glyphs {
483                let width = if format == 1 { 1 } else { 2 };
484                let first = cff
485                    .get(index..index + 2)
486                    .map(|bytes| u16::from_be_bytes([bytes[0], bytes[1]]));
487                let left = cff.get(index + 2..index + 2 + width).map(|bytes| {
488                    if width == 1 {
489                        u16::from(bytes[0])
490                    } else {
491                        u16::from_be_bytes([bytes[0], bytes[1]])
492                    }
493                });
494                let (Some(first), Some(left)) = (first, left) else {
495                    break;
496                };
497                for offset in 0..=left {
498                    if gid >= glyphs {
499                        break;
500                    }
501                    pairs.push((first.wrapping_add(offset), gid));
502                    gid += 1;
503                }
504                index += 2 + width;
505            }
506        }
507        _ => {}
508    }
509    pairs
510}
511
512/// A CFF INDEX: its entry count and the offset just past it.
513fn cff_index(data: &[u8], at: usize) -> Option<(usize, usize)> {
514    let count = usize::from(u16::from_be_bytes([*data.get(at)?, *data.get(at + 1)?]));
515    if count == 0 {
516        return Some((0, at + 2));
517    }
518    let off_size = usize::from(*data.get(at + 2)?);
519    if !(1..=4).contains(&off_size) {
520        return None;
521    }
522    let offsets_at = at + 3;
523    let data_at = offsets_at + (count + 1) * off_size;
524    let mut last = 0;
525    for index in 0..off_size {
526        last = (last << 8) | usize::from(*data.get(offsets_at + count * off_size + index)?);
527    }
528    Some((count, data_at + last.saturating_sub(1)))
529}
530
531/// One entry of a CFF INDEX, by position.
532fn cff_index_item(data: &[u8], at: usize, item: usize) -> Option<&[u8]> {
533    let count = usize::from(u16::from_be_bytes([*data.get(at)?, *data.get(at + 1)?]));
534    if item >= count {
535        return None;
536    }
537    let off_size = usize::from(*data.get(at + 2)?);
538    let offsets_at = at + 3;
539    let data_at = offsets_at + (count + 1) * off_size;
540    let read = |position: usize| -> Option<usize> {
541        let base = offsets_at + position * off_size;
542        let mut value = 0;
543        for index in 0..off_size {
544            value = (value << 8) | usize::from(*data.get(base + index)?);
545        }
546        Some(value)
547    };
548    let start = read(item)?;
549    let end = read(item + 1)?;
550    data.get(data_at + start - 1..data_at + end - 1)
551}
552
553/// The last operand of `operator` inside a CFF Top DICT.
554fn top_dict_operator(dict: &[u8], operator: u8) -> Option<usize> {
555    let mut operands: Vec<f64> = Vec::new();
556    let mut index = 0;
557    while index < dict.len() {
558        let byte = *dict.get(index)?;
559        index += 1;
560        match byte {
561            28 => {
562                let value = i16::from_be_bytes([*dict.get(index)?, *dict.get(index + 1)?]);
563                operands.push(f64::from(value));
564                index += 2;
565            }
566            29 => {
567                let mut bytes = [0_u8; 4];
568                for (offset, slot) in bytes.iter_mut().enumerate() {
569                    *slot = *dict.get(index + offset)?;
570                }
571                operands.push(f64::from(i32::from_be_bytes(bytes)));
572                index += 4;
573            }
574            32..=246 => operands.push(f64::from(byte) - 139.0),
575            247..=250 => {
576                let next = f64::from(*dict.get(index)?);
577                operands.push((f64::from(byte) - 247.0) * 256.0 + next + 108.0);
578                index += 1;
579            }
580            251..=254 => {
581                let next = f64::from(*dict.get(index)?);
582                operands.push(-(f64::from(byte) - 251.0) * 256.0 - next - 108.0);
583                index += 1;
584            }
585            30 => {
586                // A real number; no Top DICT operand this module reads needs
587                // one, so it is consumed and ignored.
588                while index < dict.len() {
589                    let nibble = dict[index];
590                    index += 1;
591                    if nibble & 0x0F == 0x0F || nibble >> 4 == 0x0F {
592                        break;
593                    }
594                }
595                operands.push(f64::NAN);
596            }
597            0..=21 => {
598                if byte == 12 {
599                    index += 1;
600                }
601                if byte == operator {
602                    if let Some(value) = operands.last()
603                        && value.is_finite()
604                        && *value >= 0.0
605                    {
606                        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
607                        return Some(*value as usize);
608                    }
609                    return None;
610                }
611                operands.clear();
612            }
613            _ => operands.clear(),
614        }
615    }
616    None
617}
618
619/// An outline for a glyph id, from a parsed TrueType program.
620fn glyph_from_face(data: &[u8], glyph_id: ttf_parser::GlyphId) -> Option<Glyph> {
621    let face = ttf_parser::Face::parse(data, 0).ok()?;
622    let units = f64::from(face.units_per_em());
623    let mut builder = OutlineBuilder::new(units);
624    face.outline_glyph(glyph_id, &mut builder)?;
625    let advance = f64::from(face.glyph_hor_advance(glyph_id).unwrap_or(0)) / units;
626    Some(Glyph {
627        contours: builder.contours,
628        advance,
629    })
630}
631
632const BUILTIN_ADVANCE: f64 = 6.0 / 9.0;
633const BUILTIN_CELL: f64 = 1.0 / 9.0;
634const BUILTIN_WIDTH: u8 = 5;
635const BUILTIN_HEIGHT: u8 = 7;
636
637/// A 5×7 bitmap alphabet. Lowercase letters use the uppercase shapes; anything
638/// without a pattern is drawn as a notdef box.
639fn builtin_glyph(character: char) -> Option<Glyph> {
640    let code = u8::try_from(u32::from(character)).ok()?;
641    if character == ' ' {
642        return Some(Glyph {
643            contours: Vec::new(),
644            advance: BUILTIN_ADVANCE,
645        });
646    }
647    if let Some(rows) = glyph_rows(code) {
648        return Some(Glyph {
649            contours: rows_to_contours(&rows),
650            advance: BUILTIN_ADVANCE,
651        });
652    }
653    if character == '\u{2022}' {
654        return Some(Glyph {
655            contours: rows_to_contours(&[0, 0, 0b00100, 0b01110, 0b00100, 0, 0]),
656            advance: BUILTIN_ADVANCE,
657        });
658    }
659    // Latin-1 text is the common case for base-14 fonts, so an accented letter
660    // is drawn as its unaccented base plus the mark rather than as .notdef.
661    if let Some((base, accent)) = decompose(character) {
662        let rows = glyph_rows(u8::try_from(u32::from(base)).unwrap_or(b'?'))
663            .or_else(|| upper(base).and_then(|upper| glyph_rows(upper as u8)))
664            .unwrap_or_else(notdef_rows);
665        let mut contours = rows_to_contours(&rows);
666        contours.extend(
667            accent
668                .cells()
669                .iter()
670                .map(|&(column, layer)| mark_cell(column, layer)),
671        );
672        return Some(Glyph {
673            contours,
674            advance: BUILTIN_ADVANCE,
675        });
676    }
677    if character == '\u{00F8}' || character == '\u{00D8}' {
678        // `ø` is `o` with a slash through it, which no mark above the box can
679        // show, so the slash goes across the glyph body instead.
680        let mut contours = rows_to_contours(&glyph_rows(b'O').unwrap_or_else(notdef_rows));
681        contours.extend(
682            [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1)]
683                .iter()
684                .map(|&(column, layer)| mark_cell(column, layer)),
685        );
686        return Some(Glyph {
687            contours,
688            advance: BUILTIN_ADVANCE,
689        });
690    }
691    let rows = upper(character)
692        .and_then(|upper| glyph_rows(upper as u8))
693        .unwrap_or_else(notdef_rows);
694    Some(Glyph {
695        contours: rows_to_contours(&rows),
696        advance: BUILTIN_ADVANCE,
697    })
698}
699
700/// A mark that can sit on a 5×7 base letter: above the glyph box (layers 0 and
701/// up) or below the baseline (negative layers, used by the cedilla).
702#[derive(Clone, Copy, PartialEq, Eq, Debug)]
703enum Accent {
704    Acute,
705    Grave,
706    Circumflex,
707    Diaeresis,
708    Tilde,
709    Ring,
710    Cedilla,
711}
712
713impl Accent {
714    /// Cell coordinates: `column` across the five-column box, `layer` up from
715    /// the top of the glyph (layer 0 starts at 7/9 em) or, when negative, down
716    /// from the baseline.
717    fn cells(self) -> &'static [(u8, i8)] {
718        match self {
719            Self::Acute => &[(2, 0), (3, 0), (3, 1)],
720            Self::Grave => &[(2, 1), (3, 1), (3, 0)],
721            Self::Circumflex => &[(1, 0), (2, 1), (3, 0)],
722            Self::Diaeresis => &[(1, 1), (3, 1)],
723            Self::Tilde => &[(1, 1), (2, 0), (3, 1)],
724            Self::Ring => &[(1, 0), (2, 1), (3, 0), (2, 0)],
725            Self::Cedilla => &[(2, -1), (3, -1), (3, -2)],
726        }
727    }
728}
729
730/// One cell of a mark, as a rectangle in em units.
731fn mark_cell(column: u8, layer: i8) -> Vec<Point> {
732    let x0 = f64::from(column) * BUILTIN_CELL;
733    let x1 = x0 + BUILTIN_CELL;
734    let (bottom, top) = if layer < 0 {
735        (
736            f64::from(layer) * BUILTIN_CELL,
737            f64::from(layer + 1) * BUILTIN_CELL,
738        )
739    } else {
740        (
741            f64::from(BUILTIN_HEIGHT + layer as u8) * BUILTIN_CELL,
742            f64::from(BUILTIN_HEIGHT + layer as u8 + 1) * BUILTIN_CELL,
743        )
744    };
745    vec![
746        Point::new(x0, bottom),
747        Point::new(x1, bottom),
748        Point::new(x1, top),
749        Point::new(x0, top),
750    ]
751}
752
753/// The base letter and mark for a precomposed Latin-1 / Latin Extended-A
754/// character the 5×7 alphabet does not carry itself.
755fn decompose(character: char) -> Option<(char, Accent)> {
756    let (base, accent) = match character {
757        'á' | 'Á' => ('a', Accent::Acute),
758        'é' | 'É' => ('e', Accent::Acute),
759        'í' | 'Í' => ('i', Accent::Acute),
760        'ó' | 'Ó' => ('o', Accent::Acute),
761        'ú' | 'Ú' => ('u', Accent::Acute),
762        'ý' | 'Ý' => ('y', Accent::Acute),
763        'à' | 'À' => ('a', Accent::Grave),
764        'è' | 'È' => ('e', Accent::Grave),
765        'ì' | 'Ì' => ('i', Accent::Grave),
766        'ò' | 'Ò' => ('o', Accent::Grave),
767        'ù' | 'Ù' => ('u', Accent::Grave),
768        'â' | 'Â' => ('a', Accent::Circumflex),
769        'ê' | 'Ê' => ('e', Accent::Circumflex),
770        'î' | 'Î' => ('i', Accent::Circumflex),
771        'ô' | 'Ô' => ('o', Accent::Circumflex),
772        'û' | 'Û' => ('u', Accent::Circumflex),
773        'ä' | 'Ä' => ('a', Accent::Diaeresis),
774        'ë' | 'Ë' => ('e', Accent::Diaeresis),
775        'ï' | 'Ï' => ('i', Accent::Diaeresis),
776        'ö' | 'Ö' => ('o', Accent::Diaeresis),
777        'ü' | 'Ü' => ('u', Accent::Diaeresis),
778        'ÿ' | 'Ÿ' => ('y', Accent::Diaeresis),
779        'ã' | 'Ã' => ('a', Accent::Tilde),
780        'õ' | 'Õ' => ('o', Accent::Tilde),
781        'ñ' | 'Ñ' => ('n', Accent::Tilde),
782        'å' | 'Å' => ('a', Accent::Ring),
783        'ç' | 'Ç' => ('c', Accent::Cedilla),
784        _ => return None,
785    };
786    Some((base, accent))
787}
788
789fn upper(character: char) -> Option<char> {
790    character
791        .to_uppercase()
792        .next()
793        .filter(|upper| *upper != character)
794}
795
796fn notdef_rows() -> [u8; BUILTIN_HEIGHT as usize] {
797    [
798        0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111,
799    ]
800}
801
802fn rows_to_contours(rows: &[u8; BUILTIN_HEIGHT as usize]) -> Vec<Vec<Point>> {
803    let mut contours = Vec::new();
804    for (row, bits) in rows.iter().enumerate() {
805        for column in 0..BUILTIN_WIDTH {
806            let mask = 1_u8 << (BUILTIN_WIDTH - 1 - column);
807            if bits & mask == 0 {
808                continue;
809            }
810            let x0 = f64::from(column) * BUILTIN_CELL;
811            let x1 = x0 + BUILTIN_CELL;
812            let top = f64::from(BUILTIN_HEIGHT - 1 - row as u8) * BUILTIN_CELL;
813            let bottom = top + BUILTIN_CELL;
814            contours.push(vec![
815                Point::new(x0, bottom),
816                Point::new(x1, bottom),
817                Point::new(x1, top),
818                Point::new(x0, top),
819            ]);
820        }
821    }
822    contours
823}
824
825fn glyph_rows(code: u8) -> Option<[u8; 7]> {
826    let rows = match code {
827        b'A' => [
828            0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
829        ],
830        b'B' => [
831            0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110,
832        ],
833        b'C' => [
834            0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110,
835        ],
836        b'D' => [
837            0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110,
838        ],
839        b'E' => [
840            0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111,
841        ],
842        b'F' => [
843            0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000,
844        ],
845        b'G' => [
846            0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110,
847        ],
848        b'H' => [
849            0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
850        ],
851        b'I' => [
852            0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
853        ],
854        b'J' => [
855            0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100,
856        ],
857        b'K' => [
858            0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001,
859        ],
860        b'L' => [
861            0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111,
862        ],
863        b'M' => [
864            0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001,
865        ],
866        b'N' => [
867            0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001,
868        ],
869        b'O' => [
870            0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
871        ],
872        b'P' => [
873            0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000,
874        ],
875        b'Q' => [
876            0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101,
877        ],
878        b'R' => [
879            0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001,
880        ],
881        b'S' => [
882            0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110,
883        ],
884        b'T' => [
885            0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100,
886        ],
887        b'U' => [
888            0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
889        ],
890        b'V' => [
891            0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100,
892        ],
893        b'W' => [
894            0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001,
895        ],
896        b'X' => [
897            0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001,
898        ],
899        b'Y' => [
900            0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100,
901        ],
902        b'Z' => [
903            0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111,
904        ],
905        b'0' => [
906            0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
907        ],
908        b'1' => [
909            0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
910        ],
911        b'2' => [
912            0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111,
913        ],
914        b'3' => [
915            0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110,
916        ],
917        b'4' => [
918            0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
919        ],
920        b'5' => [
921            0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
922        ],
923        b'6' => [
924            0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
925        ],
926        b'7' => [
927            0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
928        ],
929        b'8' => [
930            0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
931        ],
932        b'9' => [
933            0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
934        ],
935        b'.' => [0, 0, 0, 0, 0, 0b01100, 0b01100],
936        b',' => [0, 0, 0, 0, 0b01100, 0b01100, 0b01000],
937        b'!' => [
938            0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100,
939        ],
940        b'?' => [
941            0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b00000, 0b00100,
942        ],
943        b'-' => [0, 0, 0, 0b11111, 0, 0, 0],
944        b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0],
945        b';' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0b01000],
946        b'\'' => [0b00100, 0b00100, 0b01000, 0, 0, 0, 0],
947        b'"' => [0b01010, 0b01010, 0, 0, 0, 0, 0],
948        b'(' => [
949            0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010,
950        ],
951        b')' => [
952            0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000,
953        ],
954        b'/' => [
955            0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000,
956        ],
957        b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0],
958        b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0],
959        b'*' => [0, 0b10101, 0b01110, 0b11111, 0b01110, 0b10101, 0],
960        b'#' => [
961            0b01010, 0b01010, 0b11111, 0b01010, 0b11111, 0b01010, 0b01010,
962        ],
963        b'%' => [
964            0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011,
965        ],
966        b'&' => [
967            0b01100, 0b10010, 0b10100, 0b01000, 0b10101, 0b10010, 0b01101,
968        ],
969        _ => return None,
970    };
971    Some(rows)
972}
973
974/// Collects `ttf-parser` outlines into em-space contours.
975struct OutlineBuilder {
976    units: f64,
977    contours: Vec<Vec<Point>>,
978    current: Vec<Point>,
979}
980
981impl OutlineBuilder {
982    fn new(units: f64) -> Self {
983        Self {
984            units,
985            contours: Vec::new(),
986            current: Vec::new(),
987        }
988    }
989
990    fn point(&self, x: f32, y: f32) -> Point {
991        Point::new(f64::from(x) / self.units, f64::from(y) / self.units)
992    }
993
994    fn finish_contour(&mut self) {
995        if self.current.len() > 1 {
996            self.contours.push(std::mem::take(&mut self.current));
997        }
998    }
999}
1000
1001impl ttf_parser::OutlineBuilder for OutlineBuilder {
1002    fn move_to(&mut self, x: f32, y: f32) {
1003        self.finish_contour();
1004        self.current.push(self.point(x, y));
1005    }
1006
1007    fn line_to(&mut self, x: f32, y: f32) {
1008        self.current.push(self.point(x, y));
1009    }
1010
1011    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
1012        let Some(&start) = self.current.last() else {
1013            return;
1014        };
1015        let control = self.point(x1, y1);
1016        let end = self.point(x, y);
1017        for step in 1..=8 {
1018            let t = f64::from(step) / 8.0;
1019            let u = 1.0 - t;
1020            self.current.push(Point::new(
1021                u * u * start.x + 2.0 * u * t * control.x + t * t * end.x,
1022                u * u * start.y + 2.0 * u * t * control.y + t * t * end.y,
1023            ));
1024        }
1025    }
1026
1027    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
1028        let Some(&start) = self.current.last() else {
1029            return;
1030        };
1031        let c1 = self.point(x1, y1);
1032        let c2 = self.point(x2, y2);
1033        let end = self.point(x, y);
1034        for step in 1..=12 {
1035            let t = f64::from(step) / 12.0;
1036            let u = 1.0 - t;
1037            self.current.push(Point::new(
1038                u * u * u * start.x
1039                    + 3.0 * u * u * t * c1.x
1040                    + 3.0 * u * t * t * c2.x
1041                    + t * t * t * end.x,
1042                u * u * u * start.y
1043                    + 3.0 * u * u * t * c1.y
1044                    + 3.0 * u * t * t * c2.y
1045                    + t * t * t * end.y,
1046            ));
1047        }
1048    }
1049
1050    fn close(&mut self) {
1051        self.finish_contour();
1052    }
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057    use super::Font;
1058    use pdf2::Encoding;
1059
1060    #[test]
1061    fn the_builtin_font_draws_letters_as_ink() {
1062        let font = Font::builtin(Encoding::standard());
1063        let glyph = font.glyph(b'H').expect("H");
1064        assert!(!glyph.contours.is_empty());
1065        assert!((glyph.advance - 0.6667).abs() < 1e-3);
1066        // Every contour is a rectangle inside the glyph box.
1067        for contour in &glyph.contours {
1068            assert_eq!(contour.len(), 4);
1069            for point in contour {
1070                assert!(point.x >= 0.0 && point.x <= 6.0 / 9.0 + 1e-9);
1071                assert!(point.y >= 0.0 && point.y <= 7.0 / 9.0 + 1e-9);
1072            }
1073        }
1074    }
1075
1076    #[test]
1077    fn the_builtin_font_is_blank_for_space() {
1078        let font = Font::builtin(Encoding::standard());
1079        let glyph = font.glyph(b' ').expect("space");
1080        assert!(glyph.contours.is_empty());
1081        assert!(glyph.advance > 0.0);
1082    }
1083
1084    #[test]
1085    fn glyph_ids_are_selected_directly_for_composite_fonts() {
1086        let font = Font::builtin(Encoding::standard());
1087        assert!(
1088            font.glyph_by_id(1).is_none(),
1089            "the bitmap alphabet has no glyph ids"
1090        );
1091    }
1092
1093    #[test]
1094    fn a_broken_font_program_is_rejected() {
1095        assert!(Font::true_type(Encoding::standard(), vec![0, 1, 2, 3]).is_none());
1096        assert!(Font::true_type(Encoding::standard(), Vec::new()).is_none());
1097    }
1098
1099    #[test]
1100    fn accented_latin_composes_instead_of_drawing_notdef() {
1101        let font = Font::builtin(Encoding::win_ansi());
1102        // code, the ASCII base the accent is composed onto, and the number of
1103        // mark cells the accent contributes.
1104        for (code, base, marks) in [
1105            (0xE9_u8, b'E', 3), // é, acute
1106            (0xF1, b'N', 3),    // ñ, tilde
1107            (0xFC, b'U', 2),    // ü, diaeresis
1108            (0xE7, b'C', 3),    // ç, cedilla
1109            (0xE5, b'A', 4),    // å, ring
1110            (0xE2, b'A', 3),    // â, circumflex
1111        ] {
1112            let glyph = font.glyph(code).expect("a composed glyph");
1113            let plain = font.glyph(base).expect("the base letter");
1114            assert_eq!(
1115                glyph.contours.len(),
1116                plain.contours.len() + marks,
1117                "{} on {}",
1118                code as char,
1119                base as char
1120            );
1121            assert_ne!(glyph.contours, plain.contours);
1122        }
1123        // Anything the table does not name still falls back to .notdef, and
1124        // that is a hollow box, not a panic.
1125        let other = font.glyph(0xA4).expect("undefined code");
1126        assert_eq!(other.contours.len(), 20, "the notdef box");
1127    }
1128
1129    #[test]
1130    fn marks_sit_outside_the_glyph_box_and_cedillas_below_the_baseline() {
1131        let font = Font::builtin(Encoding::win_ansi());
1132        let acute = font.glyph(0xE9).expect("é");
1133        let top = acute
1134            .contours
1135            .iter()
1136            .flatten()
1137            .fold(f64::MIN, |max, point| max.max(point.y));
1138        assert!((7.0 / 9.0..=1.0).contains(&top), "accent tops out at {top}");
1139        let cedilla = font.glyph(0xE7).expect("ç");
1140        let bottom = cedilla
1141            .contours
1142            .iter()
1143            .flatten()
1144            .fold(f64::MAX, |min, point| min.min(point.y));
1145        assert!(bottom < 0.0, "the cedilla hangs to {bottom}");
1146    }
1147
1148    #[test]
1149    fn unknown_characters_become_the_notdef_box() {
1150        let font = Font::builtin(Encoding::standard());
1151        // 0xA4 is undefined in StandardEncoding, so there is no glyph at all.
1152        assert!(font.glyph(0xA4).is_none());
1153        // A mapped but unpatterned character gets the notdef box, not a panic.
1154        let glyph = font.glyph(b'@').expect("@");
1155        assert_eq!(
1156            glyph.contours.len(),
1157            20,
1158            "the notdef box is a hollow 5×7 frame"
1159        );
1160    }
1161}
1162
1163#[cfg(test)]
1164mod cff_tests {
1165    use super::{Font, cff_layout, top_dict_operator, wrap_cff};
1166
1167    /// A three-glyph bare CFF built by hand: header, one-entry Name INDEX, a Top
1168    /// DICT pointing at its CharStrings, empty String and Global Subr INDEXes,
1169    /// and three empty charstrings (`endchar`).
1170    fn synthetic_cff() -> Vec<u8> {
1171        let mut cff = vec![1, 0, 4, 4];
1172        // Name INDEX: one entry, "A".
1173        cff.extend_from_slice(&[0, 1, 1, 1, 2, b'A']);
1174        // Top DICT INDEX: one entry of 6 bytes, CharStrings at offset 25.
1175        cff.extend_from_slice(&[0, 1, 1, 1, 7]);
1176        cff.extend_from_slice(&[29, 0, 0, 0, 25, 17]);
1177        // String INDEX and Global Subr INDEX: both empty.
1178        cff.extend_from_slice(&[0, 0]);
1179        cff.extend_from_slice(&[0, 0]);
1180        assert_eq!(cff.len(), 25, "the CharStrings offset above");
1181        // CharStrings INDEX: three entries, all empty.
1182        cff.extend_from_slice(&[0, 3, 1, 1, 1, 1, 1]);
1183        cff
1184    }
1185
1186    #[test]
1187    fn a_bare_cff_becomes_a_face_ttf_parser_reads() {
1188        let cff = synthetic_cff();
1189        let (charset_at, glyphs) = cff_layout(&cff).expect("layout");
1190        assert_eq!((charset_at, glyphs), (0, 3), "predefined charset, 3 glyphs");
1191        let wrapped = wrap_cff(&cff, glyphs).expect("wrap");
1192        let face = ttf_parser::Face::parse(&wrapped, 0).expect("parse the wrapper");
1193        assert_eq!(face.number_of_glyphs(), 3);
1194        assert_eq!(face.units_per_em(), 1000);
1195        assert!(Font::cff(pdf2::Encoding::standard(), cff).is_some());
1196    }
1197
1198    #[test]
1199    fn a_program_without_charstrings_is_refused() {
1200        // The same file with its Top DICT truncated: no CharStrings operator.
1201        let cff = synthetic_cff();
1202        assert!(cff_layout(&cff[..8]).is_none());
1203        assert!(Font::cff(pdf2::Encoding::standard(), vec![0, 1]).is_none());
1204    }
1205
1206    #[test]
1207    fn the_top_dict_operator_reader_handles_each_number_encoding() {
1208        // 29 = 32-bit integer, 28 = 16-bit, 32..=246 = byte - 139.
1209        assert_eq!(top_dict_operator(&[29, 0, 0, 1, 0, 17], 17), Some(256));
1210        assert_eq!(top_dict_operator(&[28, 1, 0, 17], 17), Some(256));
1211        assert_eq!(top_dict_operator(&[139 + 42, 17], 17), Some(42));
1212        // 251..=254 encode negative numbers, which no offset may be.
1213        assert_eq!(top_dict_operator(&[251, 0, 17], 17), None);
1214        assert_eq!(
1215            top_dict_operator(&[29, 0, 0, 0, 9], 17),
1216            None,
1217            "no operator"
1218        );
1219    }
1220}
1221
1222#[cfg(test)]
1223mod cache_tests {
1224    use super::Font;
1225    use pdf2::Encoding;
1226
1227    fn subset_font() -> Vec<u8> {
1228        std::fs::read(concat!(
1229            env!("CARGO_MANIFEST_DIR"),
1230            "/../../tests/fixtures/fonts/CrimsonText-Regular-subset.ttf"
1231        ))
1232        .expect("the committed subset font")
1233    }
1234
1235    #[test]
1236    fn a_glyph_looked_up_twice_is_the_same_outline() {
1237        let font = Font::true_type(Encoding::standard(), subset_font()).expect("font");
1238        let first = font.glyph(b'A').expect("A");
1239        let second = font.glyph(b'A').expect("A");
1240        assert_eq!(first, second, "the cache returns what the parser did");
1241        assert!(!first.contours.is_empty(), "A is a drawn glyph");
1242        assert!(first.advance > 0.0);
1243        // A different code is a different glyph, not a cache collision.
1244        let b = font.glyph(b'B').expect("B");
1245        assert_ne!(first, b);
1246    }
1247
1248    #[test]
1249    fn the_cache_is_shared_by_clones_and_survives_them() {
1250        let font = Font::true_type(Encoding::standard(), subset_font()).expect("font");
1251        let clone = font.clone();
1252        let from_original = font.glyph(b'C').expect("C");
1253        let from_clone = clone.glyph(b'C').expect("C");
1254        assert_eq!(from_original, from_clone);
1255    }
1256
1257    #[test]
1258    fn a_program_with_a_cmap_answers_the_question_honestly() {
1259        let with_cmap = Font::true_type(Encoding::standard(), subset_font()).expect("font");
1260        assert!(with_cmap.has_character_map());
1261        assert!(with_cmap.glyph(b'Z').is_some(), "the subset carries Z");
1262        assert!(
1263            with_cmap.glyph(0x00).is_none(),
1264            "an unmapped code has no glyph"
1265        );
1266    }
1267}