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