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