Cotton code
758 lines · 32.8 KB · RustRaw
//! A note laid out as a PDF by the core, as other notes apps print one: A4,//! Print's colours, Figtree for the words (embedded whole, every script it//! draws), Courier for code (a PDF's own face: JetBrains Mono embedded would//! add a quarter of a megabyte to every app), the title large, headings,//! paragraphs, lists with their bullets, numbers and boxes, quotes with their//! bar, code on its grey, tables as a grid, dividers, and pictures at their//! widths (JPEG and PNG; another kind is named in words). Bold is Figtree//! drawn with a stroke (one face embedded, not three). Several notes are one//! document, each starting a page. Web links are live.use std::collections::BTreeMap;use std::io::Write as _;use cotton_core::cotton_rules::writing::{self, style};use super::notes_export::{runs, Exported, Run};// The crate's own copies of CottonPaper's Figtree (with its OFL), so the core's// build reads nothing outside its own directory (xcframework-key-closure).const FIGTREE: &[u8] = include_bytes!("../../fonts/Figtree.ttf");const FIGTREE_ITALIC: &[u8] = include_bytes!("../../fonts/Figtree-Italic.ttf");const PAGE_W: f32 = 595.28;const PAGE_H: f32 = 841.89;const LEFT: f32 = 64.0;const RIGHT: f32 = 64.0;const TOP: f32 = 72.0;const BOTTOM: f32 = 64.0;const WIDTH: f32 = PAGE_W - LEFT - RIGHT;const BODY: f32 = 11.0;const CODE: f32 = 9.5;const LEADING: f32 = 1.45;/// Print's light colours, as RGB 0–1.const TEXT: [f32; 3] = [0.0, 0.0, 0.0];const SECONDARY: [f32; 3] = [0.2, 0.2, 0.2];const ACCENT: [f32; 3] = [0.702, 0.149, 0.118];const LINK: [f32; 3] = [0.043, 0.310, 0.659];const HIGHLIGHT: [f32; 3] = [1.0, 0.922, 0.231];const CODE_GROUND: [f32; 3] = [0.929, 0.929, 0.929];const RULE: [f32; 3] = [0.102, 0.102, 0.102];/// The three faces a page draws with.#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]enum Face {    Regular,    Italic,    Mono,}/// An embedded face: its tables read, and the glyphs used (for the widths/// and the text a reader copies out).struct Embedded {    face: ttf_parser::Face<'static>,    bytes: &'static [u8],    used: BTreeMap<u16, char>,}impl Embedded {    fn new(bytes: &'static [u8]) -> Option<Embedded> {        Some(Embedded { face: ttf_parser::Face::parse(bytes, 0).ok()?, bytes, used: BTreeMap::new() })    }    fn per_em(&self) -> f32 {        f32::from(self.face.units_per_em().max(1))    }    fn glyph(&self, c: char) -> u16 {        self.face.glyph_index(c).map_or(0, |g| g.0)    }    fn advance(&self, glyph: u16) -> f32 {        f32::from(self.face.glyph_hor_advance(ttf_parser::GlyphId(glyph)).unwrap_or(0)) / self.per_em() * 1000.0    }}struct Fonts {    regular: Option<Embedded>,    italic: Option<Embedded>,}impl Fonts {    fn embedded(&mut self, face: Face) -> Option<&mut Embedded> {        match face {            Face::Regular => self.regular.as_mut(),            Face::Italic => self.italic.as_mut().or(self.regular.as_mut()),            Face::Mono => None,        }    }    /// Width of `text` at `size` points.    fn width(&mut self, face: Face, text: &str, size: f32) -> f32 {        match self.embedded(face) {            Some(font) => text.chars().map(|c| font.advance(font.glyph(c))).sum::<f32>() * size / 1000.0,            None => text.chars().count() as f32 * 600.0 * size / 1000.0,        }    }    /// `text` as the bytes a `Tj` shows: glyph ids for an embedded face,    /// WinAnsi for Courier.    fn shown(&mut self, face: Face, text: &str) -> Vec<u8> {        match self.embedded(face) {            Some(font) => {                let mut out = b"<".to_vec();                for c in text.chars() {                    let glyph = font.glyph(c);                    font.used.entry(glyph).or_insert(c);                    out.extend(format!("{glyph:04X}").bytes());                }                out.push(b'>');                out            }            None => {                let mut out = b"(".to_vec();                for c in text.chars() {                    let byte = if (c as u32) < 256 { c as u32 as u8 } else { b'?' };                    if matches!(byte, b'(' | b')' | b'\\') {                        out.push(b'\\');                    }                    out.push(byte);                }                out.push(b')');                out            }        }    }}/// One piece of a laid line: words in one look.struct Piece {    text: String,    face: Face,    bold: bool,    size: f32,    colour: [f32; 3],    width: f32,    underline: bool,    strike: bool,    highlight: bool,    link: Option<String>,}/// What a page is drawn from.#[derive(Default)]struct Page {    ops: Vec<u8>,    links: Vec<([f32; 4], String)>,    images: Vec<usize>,}/// A picture ready to embed.struct Image {    width: u32,    height: u32,    /// `DCTDecode` (JPEG as it is) or `FlateDecode` (PNG's pixels).    filter: &'static str,    colours: u8,    data: Vec<u8>,    /// PNG's own rows, predicted: the decode parameters say so.    predicted: bool,}struct Layout {    fonts: Fonts,    pages: Vec<Page>,    images: Vec<Image>,    /// From the top of the page, where the next line's top stands.    y: f32,}fn f(n: f32) -> String {    let s = format!("{n:.2}");    s.trim_end_matches('0').trim_end_matches('.').to_string()}impl Layout {    fn page(&mut self) -> &mut Page {        if self.pages.is_empty() {            self.pages.push(Page::default());        }        self.pages.last_mut().expect("a page")    }    fn new_page(&mut self) {        self.pages.push(Page::default());        self.y = TOP;    }    /// Make room for `height` more: a new page when it does not fit.    fn room(&mut self, height: f32) {        if self.y + height > PAGE_H - BOTTOM && self.y > TOP + 1.0 {            self.new_page();        }    }    fn rect(&mut self, x: f32, top: f32, w: f32, h: f32, colour: [f32; 3]) {        let ops = format!("q {} {} {} rg {} {} {} {} re f Q\n", f(colour[0]), f(colour[1]), f(colour[2]), f(x), f(PAGE_H - top - h), f(w), f(h));        self.page().ops.extend(ops.bytes());    }    fn line(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, colour: [f32; 3], width: f32) {        let ops = format!("q {} {} {} RG {} w {} {} m {} {} l S Q\n", f(colour[0]), f(colour[1]), f(colour[2]), f(width), f(x1), f(PAGE_H - y1), f(x2), f(PAGE_H - y2));        self.page().ops.extend(ops.bytes());    }    /// Draw a laid line of pieces with its baseline at `baseline` from the top.    fn draw(&mut self, x: f32, baseline: f32, pieces: &[Piece]) {        let mut at = x;        for piece in pieces {            if piece.highlight {                self.rect(at, baseline - piece.size * 0.85, piece.width, piece.size * 1.15, HIGHLIGHT);            }            let font = match piece.face {                Face::Regular => "F1",                Face::Italic => "F2",                Face::Mono => "F3",            };            let shown = self.fonts.shown(piece.face, &piece.text);            let [r, g, b] = piece.colour;            let mut ops = format!("BT /{font} {} Tf {} {} {} rg ", f(piece.size), f(r), f(g), f(b)).into_bytes();            if piece.bold && piece.face != Face::Mono {                ops.extend(format!("2 Tr {} w {} {} {} RG ", f(piece.size * 0.035), f(r), f(g), f(b)).bytes());            }            ops.extend(format!("{} {} Td ", f(at), f(PAGE_H - baseline)).bytes());            ops.extend(shown);            ops.extend(b" Tj ET\n");            self.page().ops.extend(ops);            if piece.underline || piece.link.as_deref().is_some_and(|l| !l.starts_with("note:")) {                self.line(at, baseline + piece.size * 0.12, at + piece.width, baseline + piece.size * 0.12, piece.colour, piece.size * 0.06);            }            if piece.strike {                self.line(at, baseline - piece.size * 0.3, at + piece.width, baseline - piece.size * 0.3, piece.colour, piece.size * 0.06);            }            if let Some(url) = piece.link.as_ref().filter(|l| l.starts_with("http://") || l.starts_with("https://")) {                let rect = [at, PAGE_H - baseline - piece.size * 0.25, at + piece.width, PAGE_H - baseline + piece.size * 0.9];                self.page().links.push((rect, url.clone()));            }            at += piece.width;        }    }    /// Lay `runs` as wrapped lines from `x` across `width`: each line drawn    /// as it fills, pages broken between lines.    fn words(&mut self, runs: &[Run], x: f32, width: f32, size: f32, base: Look) {        let height = size * LEADING;        let mut line: Vec<Piece> = Vec::new();        let mut used = 0.0f32;        let mut first = true;        let flush = |me: &mut Layout, line: &mut Vec<Piece>, first: &mut bool| {            me.room(height);            // Trailing spaces draw nothing.            if let Some(last) = line.last_mut() {                let trimmed = last.text.trim_end().to_string();                if trimmed.len() != last.text.len() {                    last.width = me.fonts.width(last.face, &trimmed, last.size);                    last.text = trimmed;                }            }            let baseline = me.y + size * 1.05;            me.draw(x, baseline, line);            me.y += height;            line.clear();            *first = false;        };        for run in runs {            let face = if run.code { Face::Mono } else if run.italic || base.italic { Face::Italic } else { Face::Regular };            let piece_size = if run.code && !base.code { size * 0.92 } else { size };            let colour = if run.link.is_some() {                LINK            } else if run.tag {                ACCENT            } else if run.done {                SECONDARY            } else {                base.colour            };            // Words and the spaces after them, each kept whole unless wider than a line.            let mut rest = run.text.as_str();            while !rest.is_empty() {                let cut = rest.find(' ').map_or(rest.len(), |k| k + 1);                let (word, after) = rest.split_at(cut);                rest = after;                let mut word = word.to_string();                loop {                    let w = self.fonts.width(face, &word, piece_size);                    if used + w.min(width) > width + 0.01 && !line.is_empty() && !word.trim().is_empty() {                        flush(self, &mut line, &mut first);                        used = 0.0;                    }                    if w > width && word.chars().count() > 1 {                        // A word wider than a line: cut where it fills.                        let mut fit = String::new();                        for c in word.chars() {                            if self.fonts.width(face, &format!("{fit}{c}"), piece_size) > width - used && !fit.is_empty() {                                break;                            }                            fit.push(c);                        }                        let tail = word[fit.len()..].to_string();                        let fw = self.fonts.width(face, &fit, piece_size);                        line.push(Piece { text: fit, face, bold: run.bold || base.bold, size: piece_size, colour, width: fw, underline: run.underline, strike: run.strike, highlight: run.highlight || (run.code && !base.code), link: run.link.clone() });                        flush(self, &mut line, &mut first);                        used = 0.0;                        word = tail;                        if word.is_empty() {                            break;                        }                        continue;                    }                    if !(line.is_empty() && word.trim().is_empty()) {                        line.push(Piece { text: word.clone(), face, bold: run.bold || base.bold, size: piece_size, colour, width: w, underline: run.underline, strike: run.strike, highlight: run.highlight, link: run.link.clone() });                        used += w;                    }                    break;                }            }        }        if !line.is_empty() || first {            flush(self, &mut line, &mut first);        }    }    fn picture(&mut self, image: Image, wanted: Option<&str>) {        let natural = image.width as f32 * 0.75;        let mut w = match wanted {            Some("small") => 160.0,            Some("medium") => 320.0,            _ => WIDTH,        }        .min(WIDTH)        .min(natural.max(24.0));        let mut h = w * image.height as f32 / image.width.max(1) as f32;        let tallest = PAGE_H - TOP - BOTTOM;        if h > tallest {            w *= tallest / h;            h = tallest;        }        self.room(h + 6.0);        let index = self.images.len();        self.images.push(image);        let top = self.y + 3.0;        let ops = format!("q {} 0 0 {} {} {} cm /Im{index} Do Q\n", f(w), f(h), f(LEFT), f(PAGE_H - top - h));        let page = self.page();        page.ops.extend(ops.bytes());        page.images.push(index);        self.y += h + 9.0;    }}/// A block's own look under its runs.#[derive(Clone, Copy)]struct Look {    bold: bool,    italic: bool,    code: bool,    colour: [f32; 3],}const PLAIN: Look = Look { bold: false, italic: false, code: false, colour: TEXT };/// A JPEG's size and colours, read from its frame header.fn jpeg(bytes: &[u8]) -> Option<Image> {    let mut k = 2;    if !bytes.starts_with(&[0xFF, 0xD8]) {        return None;    }    while k + 9 < bytes.len() {        if bytes[k] != 0xFF {            k += 1;            continue;        }        let marker = bytes[k + 1];        let len = u16::from_be_bytes([bytes[k + 2], bytes[k + 3]]) as usize;        if matches!(marker, 0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF) {            let height = u32::from(u16::from_be_bytes([bytes[k + 5], bytes[k + 6]]));            let width = u32::from(u16::from_be_bytes([bytes[k + 7], bytes[k + 8]]));            let colours = bytes[k + 9];            return (width > 0 && height > 0 && matches!(colours, 1 | 3)).then(|| Image { width, height, filter: "DCTDecode", colours, data: bytes.to_vec(), predicted: false });        }        k += 2 + len;    }    None}/// A PNG's pixels: grey and RGB rows go in as written (PNG's predictors are/// PDF's); with alpha they are laid on white first. Eight bits, not/// interlaced, else none.fn png(bytes: &[u8]) -> Option<Image> {    if !bytes.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]) {        return None;    }    let mut k = 8;    let (mut width, mut height, mut depth, mut kind, mut interlace) = (0u32, 0u32, 0u8, 0u8, 0u8);    let mut idat = Vec::new();    while k + 8 <= bytes.len() {        let len = u32::from_be_bytes(bytes[k..k + 4].try_into().ok()?) as usize;        let name = &bytes[k + 4..k + 8];        let data = bytes.get(k + 8..k + 8 + len)?;        match name {            b"IHDR" => {                width = u32::from_be_bytes(data[0..4].try_into().ok()?);                height = u32::from_be_bytes(data[4..8].try_into().ok()?);                depth = data[8];                kind = data[9];                interlace = data[12];            }            b"IDAT" => idat.extend_from_slice(data),            b"IEND" => break,            _ => {}        }        k += 12 + len;    }    if depth != 8 || interlace != 0 || width == 0 || height == 0 {        return None;    }    match kind {        0 => Some(Image { width, height, filter: "FlateDecode", colours: 1, data: idat, predicted: true }),        2 => Some(Image { width, height, filter: "FlateDecode", colours: 3, data: idat, predicted: true }),        4 | 6 => {            let channels = if kind == 4 { 2 } else { 4 };            let mut raw = Vec::new();            flate2::read::ZlibDecoder::new(&idat[..]).read_to_end_into(&mut raw)?;            let stride = width as usize * channels;            let mut prior = vec![0u8; stride];            let mut out = Vec::with_capacity(width as usize * height as usize * 3);            for row in 0..height as usize {                let start = row * (stride + 1);                let line = raw.get(start..start + stride + 1)?;                let filter = line[0];                let mut cur = line[1..].to_vec();                for i in 0..stride {                    let a = if i >= channels { cur[i - channels] } else { 0 };                    let b = prior[i];                    let c = if i >= channels { prior[i - channels] } else { 0 };                    let add = match filter {                        1 => a,                        2 => b,                        3 => ((u16::from(a) + u16::from(b)) / 2) as u8,                        4 => {                            let p = i16::from(a) + i16::from(b) - i16::from(c);                            let (pa, pb, pc) = ((p - i16::from(a)).abs(), (p - i16::from(b)).abs(), (p - i16::from(c)).abs());                            if pa <= pb && pa <= pc { a } else if pb <= pc { b } else { c }                        }                        _ => 0,                    };                    cur[i] = cur[i].wrapping_add(add);                }                for px in cur.chunks(channels) {                    let alpha = u16::from(*px.last().unwrap_or(&255));                    let on_white = |v: u8| ((u16::from(v) * alpha + 255 * (255 - alpha)) / 255) as u8;                    if channels == 2 {                        let g = on_white(px[0]);                        out.extend([g, g, g]);                    } else {                        out.extend([on_white(px[0]), on_white(px[1]), on_white(px[2])]);                    }                }                prior = cur;            }            let mut packed = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());            packed.write_all(&out).ok()?;            Some(Image { width, height, filter: "FlateDecode", colours: 3, data: packed.finish().ok()?, predicted: false })        }        _ => None,    }}trait ReadAll {    fn read_to_end_into(self, out: &mut Vec<u8>) -> Option<()>;}impl<R: std::io::Read> ReadAll for R {    fn read_to_end_into(mut self, out: &mut Vec<u8>) -> Option<()> {        self.read_to_end(out).ok().map(|_| ())    }}fn lay_note(me: &mut Layout, note: &Exported) {    let text = &note.text;    let styled = style::style(text, None);    let blocks = &styled.blocks;    let mut k = 0;    while k < blocks.len() {        let block = &blocks[k];        let these = runs(text, &styled.spans, block.content, block.end);        match block.kind {            style::Kind::Blank => me.y += BODY * 0.5,            style::Kind::Heading => {                let size = if block.title {                    24.0                } else {                    match block.level.unwrap_or(1) {                        1 => 20.0,                        2 => 17.0,                        3 => 14.5,                        _ => 12.5,                    }                };                if me.y > TOP + 1.0 {                    me.y += size * 0.5;                }                me.room(size * LEADING * 2.0);                me.words(&these, LEFT, WIDTH, size, Look { bold: true, ..PLAIN });                me.y += size * 0.2;            }            style::Kind::Paragraph => {                me.words(&these, LEFT, WIDTH, BODY, PLAIN);                me.y += BODY * 0.4;            }            style::Kind::Bullet | style::Kind::Numbered | style::Kind::Check => {                let indent = 18.0 + f32::from(block.depth) * 16.0;                me.room(BODY * LEADING);                let top = me.y;                let baseline = top + BODY * 1.05;                match block.kind {                    style::Kind::Bullet => {                        let w = me.fonts.width(Face::Regular, "•", BODY);                        me.draw(LEFT + indent - 11.0, baseline, &[Piece { text: "•".into(), face: Face::Regular, bold: false, size: BODY, colour: SECONDARY, width: w, underline: false, strike: false, highlight: false, link: None }]);                    }                    style::Kind::Numbered => {                        let said = format!("{}.", block.number.unwrap_or(1));                        let w = me.fonts.width(Face::Regular, &said, BODY);                        me.draw(LEFT + indent - 4.0 - w, baseline, &[Piece { text: said, face: Face::Regular, bold: false, size: BODY, colour: SECONDARY, width: w, underline: false, strike: false, highlight: false, link: None }]);                    }                    _ => {                        let (x, y, s) = (LEFT + indent - 13.0, baseline - BODY * 0.72, BODY * 0.78);                        me.line(x, y, x + s, y, SECONDARY, 0.8);                        me.line(x + s, y, x + s, y + s, SECONDARY, 0.8);                        me.line(x + s, y + s, x, y + s, SECONDARY, 0.8);                        me.line(x, y + s, x, y, SECONDARY, 0.8);                        if block.checked == Some(true) {                            me.line(x + s * 0.2, y + s * 0.5, x + s * 0.45, y + s * 0.78, ACCENT, 1.1);                            me.line(x + s * 0.45, y + s * 0.78, x + s * 0.85, y + s * 0.2, ACCENT, 1.1);                        }                    }                }                me.words(&these, LEFT + indent, WIDTH - indent, BODY, PLAIN);                me.y += BODY * 0.15;            }            style::Kind::Quote => {                let top = me.y;                let page = me.pages.len();                me.words(&these, LEFT + 14.0, WIDTH - 14.0, BODY, Look { italic: true, colour: SECONDARY, ..PLAIN });                if me.pages.len() == page {                    me.line(LEFT + 3.0, top + 2.0, LEFT + 3.0, me.y - 2.0, RULE, 1.5);                }                me.y += BODY * 0.4;            }            style::Kind::Divider => {                me.room(BODY * 1.5);                me.y += BODY * 0.7;                me.line(LEFT, me.y, LEFT + WIDTH, me.y, RULE, 0.6);                me.y += BODY * 0.8;            }            style::Kind::Fence | style::Kind::Code => {                let mut lines = Vec::new();                while k < blocks.len() && matches!(blocks[k].kind, style::Kind::Fence | style::Kind::Code) {                    if blocks[k].kind == style::Kind::Code {                        lines.push(text[writing::byte_at(text, blocks[k].start)..writing::byte_at(text, blocks[k].end)].to_string());                    }                    k += 1;                }                me.y += 3.0;                for said in lines {                    let height = CODE * LEADING;                    me.room(height);                    me.rect(LEFT, me.y, WIDTH, height, CODE_GROUND);                    let run = Run { text: if said.is_empty() { " ".into() } else { said }, code: true, ..Run::default() };                    me.words(&[run], LEFT + 8.0, WIDTH - 16.0, CODE, Look { code: true, ..PLAIN });                }                me.y += BODY * 0.6;                continue;            }            style::Kind::Table | style::Kind::TableRule => {                if let Some(table) = styled.tables.iter().find(|t| t.start <= block.start && block.end <= t.end) {                    let columns = table.rows.iter().map(Vec::len).max().unwrap_or(1).max(1);                    let col = WIDTH / columns as f32;                    me.y += 4.0;                    for (r, row) in table.rows.iter().enumerate() {                        me.room(CODE * LEADING + 6.0);                        let top = me.y;                        let page = me.pages.len();                        let mut bottom = top;                        for (c, cell) in row.iter().enumerate() {                            me.y = top + 3.0;                            let cell_runs = runs(text, &styled.spans, cell.start, cell.end);                            me.words(&cell_runs, LEFT + col * c as f32 + 5.0, col - 10.0, CODE + 0.5, Look { bold: r == 0, ..PLAIN });                            bottom = bottom.max(me.y + 3.0);                        }                        if me.pages.len() == page {                            for c in 0..=columns {                                let x = LEFT + col * c as f32;                                me.line(x, top, x, bottom, RULE, 0.5);                            }                            me.line(LEFT, top, LEFT + WIDTH, top, RULE, 0.5);                            me.line(LEFT, bottom, LEFT + WIDTH, bottom, RULE, 0.5);                        }                        me.y = bottom;                    }                    me.y += BODY * 0.6;                    while k < blocks.len() && matches!(blocks[k].kind, style::Kind::Table | style::Kind::TableRule) && blocks[k].end <= table.end {                        k += 1;                    }                    continue;                }            }            style::Kind::Picture => {                let src = block.src.clone().unwrap_or_default();                let image = note.pictures.iter().find(|p| p.src == src).and_then(|p| jpeg(&p.bytes).or_else(|| png(&p.bytes)));                match image {                    Some(image) => me.picture(image, block.width.as_deref()),                    None => {                        let said = super::notes::line("export.picture_missing", &[]).unwrap_or_default();                        me.words(&[Run { text: said, italic: true, ..Run::default() }], LEFT, WIDTH, BODY, Look { colour: SECONDARY, ..PLAIN });                    }                }            }        }        k += 1;    }}/// The notes as one PDF.pub(crate) fn pdf(notes: &[Exported]) -> Vec<u8> {    let mut me = Layout { fonts: Fonts { regular: Embedded::new(FIGTREE), italic: Embedded::new(FIGTREE_ITALIC) }, pages: Vec::new(), images: Vec::new(), y: TOP };    for (n, note) in notes.iter().enumerate() {        if n > 0 {            me.new_page();        }        lay_note(&mut me, note);    }    if me.pages.is_empty() {        me.pages.push(Page::default());    }    write_pdf(me)}/// The objects written out: catalogue, pages, fonts, pictures, cross-reference.fn write_pdf(me: Layout) -> Vec<u8> {    let mut objects: Vec<Vec<u8>> = Vec::new();    // Ids are fixed up front: 1 catalogue, 2 pages, 3–5 fonts, then the rest.    let mut next = 6usize;    let mut take = |n: usize| {        let at = next;        next += n;        at    };    let font_ids = [3usize, 4, 5];    let regular_parts = take(4); // descendant, descriptor, file, ToUnicode    let italic_parts = take(4);    let image_ids: Vec<usize> = me.images.iter().map(|_| take(1)).collect();    let page_ids: Vec<(usize, usize, Vec<usize>)> = me        .pages        .iter()        .map(|page| {            let at = take(2);            let links: Vec<usize> = page.links.iter().map(|_| take(1)).collect();            (at, at + 1, links)        })        .collect();    let total = next;    objects.resize(total, Vec::new());    objects[1] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec();    let kids: Vec<String> = page_ids.iter().map(|(page, _, _)| format!("{page} 0 R")).collect();    objects[2] = format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids.join(" "), page_ids.len()).into_bytes();    let Layout { fonts, pages, images, .. } = me;    for (slot, (font, parts, name)) in [(fonts.regular.as_ref(), regular_parts, "Figtree"), (fonts.italic.as_ref().or(fonts.regular.as_ref()), italic_parts, "Figtree-Italic")].into_iter().enumerate() {        let Some(font) = font else {            objects[font_ids[slot]] = b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec();            continue;        };        let (descendant, descriptor, file, cmap) = (parts, parts + 1, parts + 2, parts + 3);        objects[font_ids[slot]] = format!("<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /DescendantFonts [{descendant} 0 R] /ToUnicode {cmap} 0 R >>").into_bytes();        let widths: Vec<String> = font.used.keys().map(|g| format!("{g} [{}]", f(font.advance(*g)))).collect();        objects[descendant] = format!("<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{name} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor} 0 R /CIDToGIDMap /Identity /DW 500 /W [{}] >>", widths.join(" ")).into_bytes();        let scale = 1000.0 / font.per_em();        let bbox = font.face.global_bounding_box();        objects[descriptor] = format!(            "<< /Type /FontDescriptor /FontName /{name} /Flags {} /FontBBox [{} {} {} {}] /ItalicAngle {} /Ascent {} /Descent {} /CapHeight {} /StemV 80 /FontFile2 {file} 0 R >>",            if slot == 1 { 96 } else { 32 },            f(f32::from(bbox.x_min) * scale),            f(f32::from(bbox.y_min) * scale),            f(f32::from(bbox.x_max) * scale),            f(f32::from(bbox.y_max) * scale),            if slot == 1 { -9 } else { 0 },            f(f32::from(font.face.ascender()) * scale),            f(f32::from(font.face.descender()) * scale),            f(f32::from(font.face.capital_height().unwrap_or(700)) * scale),        )        .into_bytes();        objects[file] = stream(&format!("/Length1 {}", font.bytes.len()), font.bytes, true);        let mut map = String::from("/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> <FFFF> endcodespacerange\n");        let used: Vec<(&u16, &char)> = font.used.iter().collect();        for chunk in used.chunks(100) {            map.push_str(&format!("{} beginbfchar\n", chunk.len()));            for (glyph, c) in chunk {                let units: String = c.encode_utf16(&mut [0u16; 2]).iter().map(|u| format!("{u:04X}")).collect();                map.push_str(&format!("<{glyph:04X}> <{units}>\n"));            }            map.push_str("endbfchar\n");        }        map.push_str("endcmap CMapName currentdict /CMap defineresource pop end end");        objects[cmap] = stream("", map.as_bytes(), true);    }    objects[5] = b"<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>".to_vec();    for (image, id) in images.iter().zip(&image_ids) {        let space = if image.colours == 1 { "/DeviceGray" } else { "/DeviceRGB" };        let params = if image.predicted { format!(" /DecodeParms << /Predictor 15 /Colors {} /BitsPerComponent 8 /Columns {} >>", image.colours, image.width) } else { String::new() };        let dict = format!("/Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {space} /BitsPerComponent 8 /Filter /{}{params}", image.width, image.height, image.filter);        objects[*id] = stream(&dict, &image.data, false);    }    for (page, (page_id, content_id, link_ids)) in pages.iter().zip(&page_ids) {        let xobjects: Vec<String> = page.images.iter().map(|i| format!("/Im{i} {} 0 R", image_ids[*i])).collect();        let annots = if link_ids.is_empty() { String::new() } else { format!(" /Annots [{}]", link_ids.iter().map(|id| format!("{id} 0 R")).collect::<Vec<_>>().join(" ")) };        objects[*page_id] = format!(            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources << /Font << /F1 3 0 R /F2 4 0 R /F3 5 0 R >> /XObject << {} >> >> /Contents {content_id} 0 R{annots} >>",            f(PAGE_W),            f(PAGE_H),            xobjects.join(" ")        )        .into_bytes();        objects[*content_id] = stream("", &page.ops, true);        for ((rect, url), id) in page.links.iter().zip(link_ids) {            let url: String = url.chars().filter(|c| c.is_ascii() && !matches!(c, '(' | ')' | '\\')).collect();            objects[*id] = format!("<< /Type /Annot /Subtype /Link /Rect [{} {} {} {}] /Border [0 0 0] /A << /S /URI /URI ({url}) >> >>", f(rect[0]), f(rect[1]), f(rect[2]), f(rect[3])).into_bytes();        }    }    let mut out = b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n".to_vec();    let mut offsets = vec![0usize; total];    for (id, body) in objects.iter().enumerate().skip(1) {        offsets[id] = out.len();        out.extend(format!("{id} 0 obj\n").bytes());        out.extend(body);        out.extend(b"\nendobj\n");    }    let xref = out.len();    out.extend(format!("xref\n0 {total}\n0000000000 65535 f \n").bytes());    for offset in offsets.iter().skip(1) {        out.extend(format!("{offset:010} 00000 n \n").bytes());    }    out.extend(format!("trailer\n<< /Size {total} /Root 1 0 R /Info << /Producer (Cotton Words) >> >>\nstartxref\n{xref}\n%%EOF\n").bytes());    out}/// A stream object, deflated when asked.fn stream(dict: &str, bytes: &[u8], deflate: bool) -> Vec<u8> {    let (body, filter) = if deflate {        let mut packed = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());        let _ = packed.write_all(bytes);        (packed.finish().unwrap_or_default(), " /Filter /FlateDecode")    } else {        (bytes.to_vec(), "")    };    let mut out = format!("<< {dict} /Length {}{filter} >>\nstream\n", body.len()).into_bytes();    out.extend(body);    out.extend(b"\nendstream");    out}