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