Une page qui ne transporte aucune police

Quatre polices que tout lecteur dessine déjà, sur une seule page, donc le fichier n'en contient aucune — et l'exemple pèse les mêmes lignes des deux façons pour dire ce que cela économise.

Rust write_no_font_at_all.rs 290 lignes
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//! Sets a whole page in fonts the file does not carry, and weighs what that
//! saves.
//!
//! A reader is required to draw fourteen fonts whether the file carries them or
//! not, so a document that names one of them writes no font program: a few
//! hundred bytes of dictionary instead of the tens of kilobytes a subset costs.
//! The page below is set in four of them, and the last line says what the same
//! page weighs when the font is carried instead — the figure is measured by the
//! program, not written in by hand.
//!
//! Both sets of words are held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn.
//!
//! Usage: `cargo run --example write_no_font_at_all -- tmp/light.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_no_font_at_all`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::content::Content;
use hqf_pdf::{Document, Font, FontHandle, Page, Rgb, StandardFont, TextFlow};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

use language::Language;

/// The font weighed against the fourteen when none is given on the command
/// line: the one committed for the tests, so the example runs on any machine.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The page's title.
    title: &'static str,
    /// What the page is about.
    lead: &'static str,
    /// The label over the four samples.
    faces: &'static str,
    /// What each of the four samples says.
    samples: [&'static str; 4],
    /// The heading over the weight.
    weight: &'static str,
    /// What the two weights are called, and the sentence they are put into.
    saved: &'static str,
    /// What such a font cannot do.
    caveat: &'static str,
}

impl Words {
    /// The words the page is written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    title: "A page that carries no font",
    lead: "Every one of the lines below is set in a font this file does not hold. \
           A reader draws them from its own store, which is what the standard asks \
           of it, so nothing of the typefaces travels with the document.",
    faces: "Four of the fourteen",
    samples: [
        "Helvetica, the one without serifs.",
        "Times Bold Italic, and it is already accented: déjà, ç, ù, ô, ï.",
        "Courier, where every letter is the same width.",
        "\u{03A3} \u{221A} \u{222B} \u{03B1}\u{03B2}\u{03B3} \u{2265} \u{221E}",
    ],
    weight: "What it saves",
    saved: "Those four lines, on a page of their own, weigh %light% bytes. The \
            same four lines, with one font carried inside the file, weigh %heavy%. \
            Both figures are measured by the program that drew this page, not \
            written in by hand.",
    caveat: "It is not free. A file claiming an archival or accessibility standard \
             may not do this — those standards want every font carried — and these \
             faces draw only the letters their own encoding reaches, so a writing \
             system outside it needs a font the file does carry.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Une page qui ne transporte aucune police",
    lead: "Chacune des lignes ci-dessous est composée dans une police que ce \
           fichier ne contient pas. Le lecteur les prend dans sa propre réserve, \
           ce que la norme lui impose, et rien des caractères ne voyage avec le \
           document.",
    faces: "Quatre des quatorze",
    samples: [
        "Helvetica, celle qui n'a pas d'empattements.",
        "Times gras italique, et déjà accentuée : ç, ù, ô, ï, œ.",
        "Courier, où chaque lettre occupe la même largeur.",
        "\u{03A3} \u{221A} \u{222B} \u{03B1}\u{03B2}\u{03B3} \u{2265} \u{221E}",
    ],
    weight: "Ce que cela économise",
    saved: "Ces quatre lignes, sur une page à elles seules, pèsent %light% \
            octets. Les mêmes quatre lignes, avec une police transportée dans le \
            fichier, en pèsent %heavy%. Les deux chiffres sont mesurés par le \
            programme qui a dessiné cette page, pas écrits à la main.",
    caveat: "Ce n'est pas gratuit. Un fichier qui réclame une norme d'archivage ou \
             d'accessibilité n'a pas le droit de faire cela — ces normes veulent \
             toute police transportée — et ces caractères ne dessinent que les \
             lettres que leur propre encodage atteint : une écriture en dehors \
             exige une police que le fichier porte vraiment.",
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// The left edge of everything on the page.
const LEFT: f64 = 72.0;

/// How wide a block of text is.
const WIDTH: f64 = 450.0;

/// Sets a block of words with its first baseline at `top`, and hands back the
/// ordinate the block ends at.
fn block(
    c: &mut Content,
    handle: &FontHandle,
    size: f64,
    top: f64,
    text: &str,
) -> Result<f64, Box<dyn std::error::Error>> {
    let flow = TextFlow::new(handle, size);
    let lines = flow.break_lines(text, WIDTH);
    c.begin_text();
    flow.draw(c, &lines, LEFT, top, WIDTH)?;
    c.end_text();
    Ok(top - flow.height(&lines))
}

/// What a page holding nothing but the four samples weighs, set either in fonts
/// the file does not carry or in one it does.
///
/// This is the measurement the page reports. It is made on a page of its own so
/// that the prose around it — and the figures themselves — weigh nothing in it.
fn weighed(words: &Words, carried: Option<&Path>) -> Result<usize, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let handles: Vec<FontHandle> = match carried {
        Some(path) => {
            let one = doc.add_font(Font::parse(fs::read(path)?)?);
            vec![one; words.samples.len()]
        }
        None => [
            StandardFont::Helvetica,
            StandardFont::TimesBoldItalic,
            StandardFont::Courier,
            StandardFont::Symbol,
        ]
        .into_iter()
        .map(|face| doc.add_standard_font(face))
        .collect(),
    };

    let mut c = Content::new();
    let mut top = 760.0;
    for (handle, sample) in handles.iter().zip(words.samples) {
        top = block(&mut c, handle, 13.0, top, sample)? - 10.0;
    }

    let mut page = Page::a4();
    page.content = c.into_bytes();
    doc.add_page(page)?;
    Ok(doc.to_bytes()?.len())
}

/// Draws the whole page, stating `light` as its own weight and `heavy` as the
/// weight of the page that carries a font.
fn build(words: &Words, light: usize, heavy: usize) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let faces = [
        doc.add_standard_font(StandardFont::Helvetica),
        doc.add_standard_font(StandardFont::TimesBoldItalic),
        doc.add_standard_font(StandardFont::Courier),
        doc.add_standard_font(StandardFont::Symbol),
    ];
    let text = &faces[0];

    let mut c = Content::new();
    let mut top = 760.0;
    top = block(&mut c, text, 18.0, top, words.title)? - 14.0;
    top = block(&mut c, text, 10.0, top, words.lead)? - 24.0;

    top = block(&mut c, text, 12.0, top, words.faces)? - 12.0;
    for (face, sample) in faces.iter().zip(words.samples) {
        top = block(&mut c, face, 13.0, top, sample)? - 10.0;
    }

    top -= 14.0;
    top = block(&mut c, text, 12.0, top, words.weight)? - 10.0;
    let said = words
        .saved
        .replace("%light%", &spaced(light))
        .replace("%heavy%", &spaced(heavy));
    top = block(&mut c, text, 10.0, top, &said)? - 20.0;

    c.set_fill(Rgb::gray(0.35))?;
    block(&mut c, text, 9.0, top, words.caveat)?;

    let mut page = Page::a4();
    page.content = c.into_bytes();
    doc.add_page(page)?;
    Ok(doc.to_bytes()?)
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args = env::args().skip(1);
    // A named file is written as named; the default one carries the language,
    // so the two languages do not overwrite each other in `tmp/`.
    let out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("no_font_at_all")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let light = weighed(words, None)?;
    let heavy = weighed(words, Some(&font_path))?;
    let bytes = build(words, light, heavy)?;

    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;
    println!("wrote {out}: {} bytes", bytes.len());
    Ok(())
}

/// A count with a space between its thousands, which is how every language this
/// example is written in writes one.
fn spaced(count: usize) -> String {
    let digits = count.to_string();
    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index) % 3 == 0 {
            out.push('\u{00A0}');
        }
        out.push(digit);
    }
    out
}

#[cfg(test)]
mod tests {
    use super::{WORDS, language, spaced};

    /// The lines two languages are allowed to write the same way: the row of
    /// signs is not words, it is the same signs whoever reads it.
    const SPARED: [&str; 1] =
        ["\"\u{03A3} \u{221A} \u{222B} \u{03B1}\u{03B2}\u{03B3} \u{2265} \u{221E}\""];

    #[test]
    fn every_language_draws_the_page_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the page says these in more than one language: {untranslated:?}"
        );
    }

    #[test]
    fn a_count_is_written_with_a_space_between_its_thousands() {
        assert_eq!(spaced(7), "7");
        assert_eq!(spaced(999), "999");
        assert_eq!(spaced(1000), "1\u{00A0}000");
        assert_eq!(spaced(45_826), "45\u{00A0}826");
        assert_eq!(spaced(1_234_567), "1\u{00A0}234\u{00A0}567");
    }
}