f-office-pdf 0.3.0

Writes a display list as PDF.
Documentation
//! A face of a font file without the tables that give its glyphs in color, and the right edge
//! of its glyphs.
//!
//! F-Office draws every glyph with its outline in the color of its run. krilla draws a glyph
//! from a font's color tables when the font has them, so the writer gives krilla such a face
//! as a font file of its own without those tables: its glyphs keep their numbers, outlines,
//! widths and every other table.

/// The tags of the tables from which a reader can draw a glyph in color in place of its
/// outline: color layers and their palettes, SVG documents, and bitmaps.
const COLOR_TABLES: [[u8; 4]; 6] = [*b"COLR", *b"CPAL", *b"SVG ", *b"sbix", *b"CBDT", *b"CBLC"];

/// The tag of a font collection's header.
const COLLECTION: [u8; 4] = *b"ttcf";

/// The size of the header of a face and of each record of its table directory.
const HEADER: usize = 12;
const RECORD: usize = 16;

/// The face `index` of the font file `data` as a font file of its own without the tables of
/// [`COLOR_TABLES`], or `None` when the face has none of them or its table directory does not
/// read.
pub(crate) fn without_color_tables(data: &[u8], index: u32) -> Option<Vec<u8>> {
    let face = face_offset(data, index)?;
    let records = records(data, face)?;
    let kept: Vec<&Record<'_>> = records
        .iter()
        .filter(|record| !COLOR_TABLES.contains(&record.tag))
        .collect();
    if kept.len() == records.len() {
        return None;
    }
    font_file(data.get(face..face + 4)?, &kept)
}

/// The right edge of the glyphs of face `index` of the font file `data`, in font units: the
/// `xMax` of its `head` table, from which krilla takes the right edge of the font's box.
pub(crate) fn right_edge(data: &[u8], index: u32) -> Option<i16> {
    let face = face_offset(data, index)?;
    let head = records(data, face)?
        .into_iter()
        .find(|record| record.tag == *b"head")?;
    Some(i16::from_be_bytes(head.table.get(40..42)?.try_into().ok()?))
}

/// One table of a face: its tag, the first half of its record (the tag and the checksum), and
/// its bytes.
struct Record<'d> {
    tag: [u8; 4],
    tag_and_sum: &'d [u8],
    table: &'d [u8],
}

/// The tables of the face whose table directory starts at `face`.
fn records(data: &[u8], face: usize) -> Option<Vec<Record<'_>>> {
    let count = usize::from(u16_at(data, face + 4)?);
    (0..count)
        .map(|number| {
            let at = face + HEADER + number * RECORD;
            let record = data.get(at..at + RECORD)?;
            let start = usize::try_from(u32_at(record, 8)?).ok()?;
            let length = usize::try_from(u32_at(record, 12)?).ok()?;
            Some(Record {
                tag: record.get(..4)?.try_into().ok()?,
                tag_and_sum: record.get(..8)?,
                table: data.get(start..start.checked_add(length)?)?,
            })
        })
        .collect()
}

/// A font file of the version `version` that holds the tables `kept`, each starting at whole
/// four bytes.
fn font_file(version: &[u8], kept: &[&Record<'_>]) -> Option<Vec<u8>> {
    let tables = u16::try_from(kept.len()).ok()?;
    // The search fields of the directory: the largest power of two at most the table count.
    let selector = u16::try_from(kept.len().checked_ilog2().unwrap_or(0)).ok()?;
    let range = (1_u16 << selector).checked_mul(16)?;
    let shift = tables.checked_mul(16)?.checked_sub(range)?;
    let mut file = Vec::new();
    file.extend_from_slice(version);
    for field in [tables, range, selector, shift] {
        file.extend_from_slice(&field.to_be_bytes());
    }
    let mut offset = HEADER + kept.len() * RECORD;
    for record in kept {
        file.extend_from_slice(record.tag_and_sum);
        file.extend_from_slice(&u32::try_from(offset).ok()?.to_be_bytes());
        file.extend_from_slice(&u32::try_from(record.table.len()).ok()?.to_be_bytes());
        offset += padded(record.table.len());
    }
    for record in kept {
        file.extend_from_slice(record.table);
        file.resize(padded(file.len()), 0);
    }
    Some(file)
}

/// Where the table directory of face `index` starts: at the file's start for a single face,
/// and where a collection's header says for a face of a collection.
fn face_offset(data: &[u8], index: u32) -> Option<usize> {
    if data.get(..4)? != COLLECTION {
        return (index == 0).then_some(0);
    }
    let faces = u32_at(data, 8)?;
    if index >= faces {
        return None;
    }
    let entry = 12 + usize::try_from(index).ok()? * 4;
    usize::try_from(u32_at(data, entry)?).ok()
}

/// A length rounded up to whole four bytes, at which each table of a font file starts.
const fn padded(length: usize) -> usize {
    length.div_ceil(4) * 4
}

fn u16_at(data: &[u8], at: usize) -> Option<u16> {
    Some(u16::from_be_bytes(data.get(at..at + 2)?.try_into().ok()?))
}

fn u32_at(data: &[u8], at: usize) -> Option<u32> {
    Some(u32::from_be_bytes(data.get(at..at + 4)?.try_into().ok()?))
}

#[cfg(test)]
mod tests {
    use super::{right_edge, without_color_tables};

    /// A font file of one face whose tables have the tags `tags`, each holding its tag's
    /// bytes and one more byte.
    fn font(tags: &[&[u8; 4]]) -> Vec<u8> {
        let mut file = vec![0, 1, 0, 0];
        let count = u16::try_from(tags.len()).unwrap();
        file.extend_from_slice(&count.to_be_bytes());
        file.extend_from_slice(&[0; 6]);
        let mut offset = 12 + 16 * tags.len();
        for tag in tags {
            file.extend_from_slice(*tag);
            file.extend_from_slice(&[0; 4]);
            file.extend_from_slice(&u32::try_from(offset).unwrap().to_be_bytes());
            file.extend_from_slice(&5_u32.to_be_bytes());
            offset += 8;
        }
        for tag in tags {
            file.extend_from_slice(*tag);
            file.extend_from_slice(&[1, 0, 0, 0]);
        }
        file
    }

    /// The tags of a font file's tables with the bytes of each table.
    fn tables(file: &[u8]) -> Vec<(Vec<u8>, Vec<u8>)> {
        let count = usize::from(u16::from_be_bytes([file[4], file[5]]));
        (0..count)
            .map(|number| {
                let record = &file[12 + 16 * number..28 + 16 * number];
                let at = |i: usize| {
                    usize::try_from(u32::from_be_bytes(record[i..i + 4].try_into().unwrap()))
                        .unwrap()
                };
                (record[..4].to_vec(), file[at(8)..at(8) + at(12)].to_vec())
            })
            .collect()
    }

    #[test]
    fn leaves_out_the_color_tables_and_keeps_every_other_table() {
        let file = font(&[b"COLR", b"CPAL", b"OS/2", b"glyf", b"sbix"]);
        let without = without_color_tables(&file, 0).unwrap();
        let kept = tables(&without);
        assert_eq!(
            kept,
            vec![
                (b"OS/2".to_vec(), b"OS/2\x01".to_vec()),
                (b"glyf".to_vec(), b"glyf\x01".to_vec()),
            ]
        );
        // The search fields of two tables.
        assert_eq!(&without[6..12], &[0, 32, 0, 1, 0, 0]);
    }

    #[test]
    fn keeps_a_face_without_color_tables_as_it_is() {
        assert_eq!(without_color_tables(&font(&[b"OS/2", b"glyf"]), 0), None);
        assert_eq!(without_color_tables(&[0, 1], 0), None);
    }

    #[test]
    fn takes_a_face_of_a_collection_out_of_it() {
        let face = font(&[b"COLR", b"glyf"]);
        // A collection of one face, whose tables lie after the collection's header.
        let mut file = b"ttcf".to_vec();
        file.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 16]);
        let mut moved = face.clone();
        for number in 0..2 {
            let at = 12 + 16 * number + 8;
            let offset = u32::from_be_bytes(moved[at..at + 4].try_into().unwrap()) + 16;
            moved[at..at + 4].copy_from_slice(&offset.to_be_bytes());
        }
        file.extend_from_slice(&moved);
        let without = without_color_tables(&file, 0).unwrap();
        assert_eq!(
            tables(&without),
            vec![(b"glyf".to_vec(), b"glyf\x01".to_vec())]
        );
        assert_eq!(without_color_tables(&file, 1), None);
    }

    #[test]
    fn reads_the_right_edge_of_the_glyphs_from_the_head_table() {
        let mut head = vec![0_u8; 54];
        head[40..42].copy_from_slice(&1234_i16.to_be_bytes());
        let mut file = vec![0, 1, 0, 0, 0, 1, 0, 16, 0, 0, 0, 0];
        file.extend_from_slice(b"head");
        file.extend_from_slice(&[0; 4]);
        file.extend_from_slice(&28_u32.to_be_bytes());
        file.extend_from_slice(&54_u32.to_be_bytes());
        file.extend_from_slice(&head);
        assert_eq!(right_edge(&file, 0), Some(1234));
        assert_eq!(right_edge(&font(&[b"glyf"]), 0), None);
    }
}