Une page composée dans une police de 1990

Une police écrite dans le plus vieux format d'Adobe, lue pour ses largeurs et rangée entière dans le fichier. Chaque chiffre que la page énonce à son sujet est lu dans la police, pas recopié à la main.

Rust write_type_one_font.rs 409 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Sets a page in a font read from a Type 1 program, and states what the
//! program says about itself.
//!
//! Adobe's first font format is not a table anybody can look a glyph up in: it
//! is a PostScript program whose glyphs are ciphered, and every measurement
//! below is read out of it rather than written in by hand. The program itself
//! is carried into the file whole, so a reader draws from the very bytes that
//! were handed in.
//!
//! The face is `HqfStroke`, HQF Development's own: a stroke face built by
//! `scripts/build_type1_sample.py`, committed beside the fonts the tests run
//! against. It draws capitals, figures and the marked letters French needs, and
//! nothing else — which is what the page says of it, and what the page is set
//! in.
//!
//! 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_type_one_font -- tmp/type1.pdf [face.pfb]`
//!        `HQF_PDF_LANG=fr cargo run --example write_type_one_font`

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

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

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

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

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

use language::Language;

/// The Type 1 program the page is set in when none is given on the command
/// line: the one committed for the tests, so the example runs on any machine.
fn default_face() -> PathBuf {
    fonts().join("HqfStroke.pfb")
}

/// The font the prose is set in: the page says more than a stroke face of
/// capitals can hold.
fn prose_face() -> PathBuf {
    fonts().join("DejaVuSans.ttf")
}

/// Where the fonts committed for the tests sit.
fn fonts() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
}

/// 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 three lines set in the face itself.
    shown: &'static str,
    /// The three lines, in the capitals the face draws.
    samples: [&'static str; 3],
    /// The label over what the program states about itself.
    stated: &'static str,
    /// The sentence those figures are put into.
    facts: &'static str,
    /// The label over the weight.
    weight: &'static str,
    /// The sentence the two weights are put into.
    weighed: &'static str,
    /// The label over what is left for a later version.
    later: &'static str,
    /// Why the whole program travels, and what it would take not to.
    postponed: &'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 set in a Type 1 font",
    lead: "The three lines below are drawn from a font program in Adobe's first \
           format. It is not a font file with tables to look a glyph up in: it \
           is a PostScript program, its glyphs ciphered one by one, and the \
           library reads it to find out how wide each of them is and which code \
           reaches it. The program is then carried into this file whole, and \
           the reader draws from those very bytes.",
    shown: "Drawn from the program",
    samples: [
        "HQF DEVELOPMENT",
        "ABCDEFGHIJKLM NOPQRSTUVWXYZ 0123456789",
        "A STROKE FACE, READ AND CARRIED WHOLE.",
    ],
    stated: "What the program states about itself",
    facts: "It calls itself %name% and holds %glyphs% glyphs, of which %reached% \
            are reached by a code. Every glyph stands in one box, whose corners \
            are %low% and %high%; a vertical stem is %stem% thousandths of an em \
            thick, and an underline sits %underline% below the line. Not one of \
            those figures is written into this page: each is read out of the \
            program.",
    weight: "What it weighs",
    weighed: "The program itself is %program% bytes on disk, and a page carrying \
              it weighs %document% bytes. Both figures are measured by the \
              program that drew this page, not written in by hand.",
    later: "What travels with it, and why",
    postponed: "Every other kind of font this library carries travels light: \
                only the letters a page actually draws go into the file, so a \
                page that says one word carries the letters of that word and not \
                a whole alphabet. A Type 1 program does not. It travels whole, \
                and the reason is in the format itself: each glyph is ciphered \
                on its own inside the program, so keeping some and dropping the \
                rest means deciphering the program, rewriting its list of \
                glyphs, and ciphering it again — while holding on to the pieces \
                of outline that several glyphs share, and to the glyphs that are \
                built out of two others. That is a piece of work of its own, and \
                it is deliberately left to a later version of this library. It \
                costs nothing on a face of a few dozen glyphs. It costs real \
                bytes on a large one: a face of sixty thousand bytes travels \
                sixty thousand bytes even where the page shows three words.",
    caveat: "A Type 1 font is a simple font: its codes are one byte, so at most \
             256 of its glyphs are reachable at a time and it never sets text \
             down the page. Which code reaches which glyph is the program's own \
             business — this file repeats the program's own names for them.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Une page composée dans une police de type 1",
    lead: "Les trois lignes ci-dessous sont dessinées par un programme de police \
           écrit dans le premier format d'Adobe. Ce n'est pas un fichier de \
           police avec des tables où chercher un dessin : c'est un programme \
           PostScript, dont chaque dessin est chiffré à part, et la \
           bibliothèque le lit pour savoir la largeur de chacun et le code qui \
           l'atteint. Le programme est ensuite transporté entier dans ce \
           fichier, et le lecteur dessine à partir de ces octets-là.",
    shown: "Dessiné par le programme",
    samples: [
        "HQF DEVELOPMENT",
        "ABCDEFGHIJKLM NOPQRSTUVWXYZ 0123456789",
        "UNE POLICE DE TRAITS, LUE ET PORTÉE ENTIÈRE.",
    ],
    stated: "Ce que le programme dit de lui-même",
    facts: "Il s'appelle %name% et porte %glyphs% dessins, dont %reached% sont \
            atteints par un code. Chaque dessin tient dans une seule boîte, dont \
            les coins sont %low% et %high% ; un fût vertical fait %stem% \
            millièmes de cadratin d'épaisseur, et un soulignement se pose \
            %underline% sous la ligne. Aucun de ces chiffres n'est écrit dans \
            cette page : chacun est lu dans le programme.",
    weight: "Ce que cela pèse",
    weighed: "Le programme lui-même pèse %program% octets sur le disque, et une \
              page qui le transporte pèse %document% octets. Les deux chiffres \
              sont mesurés par le programme qui a dessiné cette page, pas écrits \
              à la main.",
    later: "Ce qui voyage avec, et pourquoi",
    postponed: "Toutes les autres sortes de polices que cette bibliothèque \
                transporte voyagent légères : seules les lettres réellement \
                dessinées entrent dans le fichier, si bien qu'une page qui écrit \
                un mot transporte les lettres de ce mot et pas un alphabet \
                entier. Un programme de type 1, lui, voyage entier, et la raison \
                tient au format lui-même : chaque dessin y est chiffré à part, \
                donc n'en garder qu'une partie veut dire déchiffrer le \
                programme, réécrire sa liste de dessins, puis tout rechiffrer — \
                en gardant les morceaux de tracé que plusieurs lettres se \
                partagent, et les lettres fabriquées à partir de deux autres. \
                C'est un chantier à lui tout seul, et il est volontairement \
                laissé à une version suivante de cette bibliothèque. Cela ne \
                coûte rien sur une police de quelques dizaines de dessins. Cela \
                coûte de vrais octets sur une grande : une police de soixante \
                mille octets voyage soixante mille octets, même là où la page ne \
                montre que trois mots.",
    caveat: "Une police de type 1 est une police simple : ses codes tiennent sur \
             un octet, donc 256 de ses dessins au plus sont atteignables à la \
             fois, et elle ne compose jamais de haut en bas. Quel code atteint \
             quel dessin ne regarde que le programme — ce fichier reprend les \
             noms que le programme leur donne.",
};

/// 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 three samples weighs.
///
/// It is measured on a page of its own: a page that states its own weight never
/// settles, because writing the figure changes the figure.
fn weighed(words: &Words, face: &Type1Font) -> Result<usize, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let handle = doc.add_type1_font(face.clone());

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

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

/// How many of the program's glyphs a code reaches.
fn reached(face: &Type1Font) -> usize {
    (0..=u8::MAX)
        .filter(|code| face.character_at(*code).is_some())
        .count()
}

/// The two corners of the box a face states, as the page writes them.
fn corners(face: &Type1Font) -> (String, String) {
    let [llx, lly, urx, ury] = face.bbox();
    (format!("{llx} · {lly}"), format!("{urx} · {ury}"))
}

/// Draws the whole page.
fn build(
    words: &Words,
    face: &Type1Font,
    prose: Font,
    program: usize,
    document: usize,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let text = doc.add_font(prose);
    let drawn = doc.add_type1_font(face.clone());

    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.shown)? - 14.0;
    for sample in words.samples {
        top = block(&mut c, &drawn, 15.0, top, sample)? - 10.0;
    }

    top -= 14.0;
    top = block(&mut c, &text, 12.0, top, words.stated)? - 10.0;
    let stated = words
        .facts
        .replace("%name%", face.name())
        .replace("%glyphs%", &face.glyph_names().count().to_string())
        .replace("%reached%", &reached(face).to_string())
        .replace("%low%", &corners(face).0)
        .replace("%high%", &corners(face).1)
        .replace(
            "%stem%",
            &face
                .stem_v()
                .map_or_else(|| "—".to_owned(), |v| v.to_string()),
        )
        .replace(
            "%underline%",
            &face
                .underline()
                .map_or_else(|| "—".to_owned(), |(position, _)| (-position).to_string()),
        );
    top = block(&mut c, &text, 10.0, top, &stated)? - 20.0;

    top = block(&mut c, &text, 12.0, top, words.weight)? - 10.0;
    let said = words
        .weighed
        .replace("%program%", &spaced(program))
        .replace("%document%", &spaced(document));
    top = block(&mut c, &text, 10.0, top, &said)? - 20.0;

    top = block(&mut c, &text, 12.0, top, words.later)? - 10.0;
    top = block(&mut c, &text, 10.0, top, words.postponed)? - 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("type_one_font")));
    let face_path = args.next().map_or_else(default_face, PathBuf::from);

    let bytes = fs::read(&face_path)?;
    let face = Type1Font::parse(&bytes)?;
    let prose = Font::parse(fs::read(prose_face())?)?;

    let document = weighed(words, &face)?;
    let drawn = build(words, &face, prose, bytes.len(), document)?;

    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &drawn)?;
    println!("wrote {out}: {} bytes", drawn.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::{Language, WORDS, default_face, language, spaced};
    use hqf_pdf::Type1Font;

    /// The lines two languages are allowed to write the same way: a mark, a run
    /// of letters and figures, and the name of the firm are the same whoever
    /// reads them.
    const SPARED: [&str; 2] = [
        "\"HQF DEVELOPMENT\"",
        "\"ABCDEFGHIJKLM NOPQRSTUVWXYZ 0123456789\"",
    ];

    #[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 every_line_the_page_shows_is_one_the_face_can_draw() {
        // The face draws capitals, figures and the marked letters French needs,
        // and nothing else. A sample holding anything more would be drawn with
        // a hole in it.
        let face = Type1Font::parse(std::fs::read(default_face()).expect("the face is committed"))
            .expect("the face reads");

        for language in [Language::English, Language::French] {
            for sample in super::Words::of(language).samples {
                let missing: Vec<char> = sample
                    .chars()
                    .filter(|character| face.code_of(*character).is_none())
                    .collect();
                assert!(missing.is_empty(), "{sample:?} needs {missing:?}");
            }
        }
    }

    #[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(8117), "8\u{00A0}117");
    }
}