Une feuille qui mesure ce qu'elle annonce

Trois réglettes — centimètres, pouces et points — sur une page qui annonce qu'elle doit s'imprimer exactement à la taille où elle a été dessinée, et que le logiciel de lecture ne doit rien proposer d'autre. Cette seconde demande n'existe que depuis le PDF 2.0 : le fichier déclare donc 2.0, au lieu de changer de version à votre insu.

Rust write_true_to_scale.rs 477 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! A sheet that measures what it says, and asks not to be resized.
//!
//! A drawing printed to be measured is worth nothing if the printer shrinks it
//! to fit its own margins. This page carries three rules — centimetres, inches
//! and points — and states, in the file itself, that it is to print at the size
//! it was drawn and that the reader is not to offer anything else. That last
//! part arrived with PDF 2.0, so the file declares 2.0: nothing is raised on
//! the caller's behalf, and a file that asked for it while declaring less would
//! be refused rather than written.
//!
//! It shows the two other things a caller decides about the file rather than
//! about its pages: how hard its streams are squeezed, and where the bytes go —
//! here straight into the file, a piece at a time, rather than into memory
//! first.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is captioned in. What a rule is called is not one of
//! them: the length is worked out from the rule itself and only the unit is a
//! word, so no language can name a rule a length it does not run. The entries
//! set beside what the file asks for are not words either — they are what the
//! file writes, spelled the same way whoever reads the page.
//!
//! Usage: `cargo run --example write_true_to_scale -- tmp/scale.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_true_to_scale --
//! tmp/echelle.pdf`

use std::env;
use std::fs::{self, File};
use std::io::BufWriter;
use std::path::{Path, PathBuf};

use hqf_pdf::content::Content;
use hqf_pdf::{
    Color, Compression, Document, Error, Font, FontHandle, OpenAction, Page, PageFit, Rgb, Version,
    ViewerPreferences,
};

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

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

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

use language::Language;

/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// A4, in points.
const SHEET: (f64, f64) = (595.276, 841.890);

/// How far in from the edge of the sheet everything is set.
const MARGIN: f64 = 64.0;

/// How far in from the left edge the entries the file writes stand, leaving the
/// asking to their left.
const ENTRY: f64 = 290.0;

/// One centimetre, in points.
const CM: f64 = 72.0 / 2.54;

/// One inch, in points.
const INCH: f64 = 72.0;

/// A rule laid across the page.
struct Rule {
    /// How far apart the ticks stand, in points.
    step: f64,
    /// How many steps the rule runs for.
    steps: usize,
    /// Every so many ticks stands tall and carries a number.
    tall: usize,
    /// What one step is worth in the unit the rule is named for.
    worth: usize,
}

/// The three rules, from the top of the page down.
const RULES: [(f64, Rule); 3] = [
    (
        590.0,
        Rule {
            step: CM,
            steps: 16,
            tall: 1,
            worth: 1,
        },
    ),
    (
        500.0,
        Rule {
            step: INCH,
            steps: 6,
            tall: 1,
            worth: 1,
        },
    ),
    (
        410.0,
        Rule {
            step: 10.0,
            steps: 20,
            tall: 5,
            worth: 10,
        },
    ),
];

/// The entries the file writes to ask for what it asks. They are read off the
/// file rather than off the page, and stand the same way in every language.
const WRITTEN: [&str; 3] = [
    "/PrintScaling /None",
    "/Enforce [ /PrintScaling ]",
    "/OpenAction [ page /Fit ]",
];

/// The words the page is set in, one set per language.
#[derive(Debug)]
struct Words {
    /// The title in the band across the head of the page.
    title: &'static str,
    /// The three lines under the band.
    intro: [&'static str; 3],
    /// The unit each of the three rules measures in. The length itself is
    /// worked out from the rule, so a rule cannot be named a length it does not
    /// run.
    units: [&'static str; 3],
    /// The heading over what the file asks for.
    asks: &'static str,
    /// What the file asks for, one line per entry of [`WRITTEN`].
    asked: [&'static str; 3],
    /// The two closing paragraphs, set with a blank line between them.
    closing: ([&'static str; 3], [&'static str; 4]),
}

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

    /// What the rule at `index` is called: the length it runs, then the unit it
    /// runs in.
    fn rule_name(&self, index: usize, spec: &Rule) -> String {
        format!("{} {}", spec.steps * spec.worth, self.units[index])
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    title: "True to scale",
    intro: [
        "Print this page at its own size and the three rules below measure what",
        "they say. Hold a ruler against them to see whether whatever printed it",
        "did as the file asked.",
    ],
    units: ["centimetres", "inches", "points, at 72 to the inch"],
    asks: "What this file asks for, and what it writes to ask",
    asked: [
        "Print every page at the size it was drawn.",
        "Do not offer to print it at any other size.",
        "Open on the whole sheet, rules and all.",
    ],
    closing: (
        [
            "The second of those entries arrived with PDF 2.0, so this file declares 2.0 on",
            "its first line. Nothing is raised on the caller's behalf: a file that asked for",
            "it while declaring less would be refused rather than quietly written.",
        ],
        [
            "Two more things were decided about the file rather than about its pages. Its",
            "streams were squeezed as small as the compressor goes, which costs time and",
            "saves bytes. And it went into the file a piece at a time as it was made, rather",
            "than being built whole in memory and written at the end.",
        ],
    ),
};

/// The page in French.
const FRENCH: Words = Words {
    title: "À l'échelle exacte",
    intro: [
        "Imprimez cette page à sa taille et les trois règles ci-dessous mesurent",
        "ce qu'elles annoncent. Posez un mètre dessus pour voir si ce qui l'a",
        "imprimée a fait ce que le fichier demandait.",
    ],
    units: ["centimètres", "pouces", "points, à 72 pour un pouce"],
    asks: "Ce que ce fichier demande, et ce qu'il écrit pour le demander",
    asked: [
        "Imprimer chaque page à la taille dessinée.",
        "Ne proposer aucune autre taille d'impression.",
        "Ouvrir sur la feuille entière, règles comprises.",
    ],
    closing: (
        [
            "La deuxième de ces entrées est arrivée avec PDF 2.0, donc ce fichier annonce",
            "2.0 sur sa première ligne. Rien n'est relevé à la place de l'appelant : un",
            "fichier qui la demanderait en annonçant moins serait refusé, pas écrit.",
        ],
        [
            "Deux autres choses ont été décidées sur le fichier plutôt que sur ses pages.",
            "Ses flux ont été serrés aussi petit que le compresseur sait le faire, ce qui",
            "coûte du temps et gagne des octets. Et il est parti dans le fichier morceau",
            "par morceau à mesure, au lieu d'être monté entier en mémoire puis écrit.",
        ],
    ),
};

/// 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)];

/// Draws one line of text with its baseline at `(x, y)`.
fn text(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    x: f64,
    y: f64,
    line: &str,
) -> Result<(), Error> {
    content.begin_text();
    content.set_font(font.name(), size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(line));
    content.end_text();
    Ok(())
}

/// How far along the page the tick at `index` stands.
#[expect(
    clippy::cast_precision_loss,
    reason = "a rule is twenty ticks long, not four thousand million"
)]
#[expect(
    clippy::suboptimal_flops,
    reason = "the Python twin multiplies and adds apart, and the two write one file"
)]
fn along(step: f64, index: usize) -> f64 {
    MARGIN + step * index as f64
}

/// Draws a rule: a baseline with a tick at every step, the tall ones numbered,
/// and the name of the rule set above it.
///
/// The ticks run up from the baseline and the numbers sit under it, so nothing
/// a ruler is laid against is covered.
fn rule(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    spec: &Rule,
    name: &str,
) -> Result<(), Error> {
    content.save_state();
    content.set_stroke(Color::Gray(0.1))?;
    content.set_line_width(0.6)?;
    content.move_to(MARGIN, y)?;
    content.line_to(along(spec.step, spec.steps), y)?;
    content.stroke();

    for index in 0..=spec.steps {
        let x = along(spec.step, index);
        let height = if index % spec.tall == 0 { 14.0 } else { 7.0 };
        content.move_to(x, y)?;
        content.line_to(x, y + height)?;
        content.stroke();
    }
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    for index in (0..=spec.steps).step_by(spec.tall) {
        let x = along(spec.step, index);
        let number = format!("{}", index * spec.worth);
        text(content, font, 8.0, x - 2.0, y - 12.0, &number)?;
    }
    content.set_fill(Color::Gray(0.1))?;
    text(content, font, 10.0, MARGIN, y + 22.0, name)?;
    content.restore_state();
    Ok(())
}

/// The band across the head of the page, and what stands under it.
fn head(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Rgb::new(0.16, 0.20, 0.26))?;
    content.rect(0.0, SHEET.1 - 96.0, SHEET.0, 96.0)?.fill();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    text(content, font, 20.0, MARGIN, SHEET.1 - 58.0, words.title)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.25))?;
    let mut y = SHEET.1 - 140.0;
    for line in words.intro {
        text(content, font, 11.0, MARGIN, y, line)?;
        y -= 18.0;
    }
    content.restore_state();
    Ok(())
}

/// What the file asks of whatever shows and prints it, set beside the entries
/// it writes to ask.
fn asks(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_stroke(Color::Gray(0.82))?;
    content.set_line_width(0.4)?;
    content.move_to(MARGIN, 350.0)?;
    content.line_to(SHEET.0 - MARGIN, 350.0)?;
    content.stroke();
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.1))?;
    text(content, font, 13.0, MARGIN, 322.0, words.asks)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.3))?;
    let mut y = 294.0;
    for (asked, written) in words.asked.iter().zip(WRITTEN) {
        text(content, font, 11.0, MARGIN, y, asked)?;
        text(content, font, 10.0, MARGIN + ENTRY, y, written)?;
        y -= 20.0;
    }
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.45))?;
    let mut y = 212.0;
    for paragraph in [words.closing.0.as_slice(), words.closing.1.as_slice()] {
        for line in paragraph {
            text(content, font, 10.5, MARGIN, y, line)?;
            y -= 17.0;
        }
        y -= 17.0;
    }
    content.restore_state();
    Ok(())
}

/// The page: the band across its head, the three rules, and what the file asks
/// of whatever prints it.
fn sheet(font: &FontHandle, words: &Words) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    head(&mut content, font, words)?;
    for (index, (y, spec)) in RULES.iter().enumerate() {
        rule(&mut content, font, *y, spec, &words.rule_name(index, spec))?;
    }
    asks(&mut content, font, words)?;

    content.save_state();
    content.set_fill(Color::Gray(0.5))?;
    text(&mut content, font, 8.0, MARGIN, 62.0, "HQF Development")?;
    content.restore_state();
    Ok(content.into_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("scale")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);

    let mut page = Page::new(SHEET.0, SHEET.1);
    page.content = sheet(&font, words)?;
    doc.add_page(page)?;

    // Asking for the size the pages print at is one entry; taking the choice
    // away from the reader is a second, which PDF 2.0 brought and which the
    // file must therefore declare itself as.
    doc.set_viewer_preferences(ViewerPreferences::new().lock_actual_size());
    doc.set_open_action(OpenAction::new(0).view(PageFit::WholePage));
    doc.set_version(Version::V2_0);
    doc.set_compression_level(Compression::SMALLEST);

    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    doc.write_to(BufWriter::new(File::create(&out)?))?;

    println!(
        "wrote {out}: {} bytes, one sheet that prints at the size it was drawn",
        fs::metadata(&out)?.len()
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::{Document, Font};

    use super::{ENTRY, MARGIN, RULES, SHEET, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way. Every line
    /// here is a title, a caption or a sentence, and no two languages write one
    /// alike; the entries the file writes are not in `Words` at all.
    const SPARED: [&str; 0] = [];

    /// The room a line set from the left margin has before it reaches the
    /// margin on the other side.
    const PAPER: f64 = SHEET.0 - 2.0 * MARGIN;

    /// The room a line of asking has before it reaches the entry set beside it.
    const GUTTER: f64 = 10.0;

    #[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:?}"
        );
    }

    /// Nothing on the page is broken to a width: a line longer than the room it
    /// has runs on over whatever stands beside it, and the lines of asking have
    /// the least room of all, because the entry the file writes stands at a
    /// fixed distance from them.
    #[test]
    fn every_language_writes_lines_that_fit_the_room_they_have() {
        let mut doc = Document::new();
        let font = Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
            .expect("the committed font parses");
        let text = doc.add_font(font);

        for (named, words) in WORDS {
            let code = named.code();
            let lines = std::iter::once((20.0, words.title.to_owned(), PAPER))
                .chain(words.intro.map(|line| (11.0, line.to_owned(), PAPER)))
                .chain(
                    RULES
                        .iter()
                        .enumerate()
                        .map(|(index, (_, spec))| (10.0, words.rule_name(index, spec), PAPER)),
                )
                .chain([(13.0, words.asks.to_owned(), PAPER)])
                .chain(
                    words
                        .asked
                        .map(|line| (11.0, line.to_owned(), ENTRY - GUTTER)),
                )
                .chain(words.closing.0.map(|line| (10.5, line.to_owned(), PAPER)))
                .chain(words.closing.1.map(|line| (10.5, line.to_owned(), PAPER)));

            for (size, line, room) in lines {
                let measured = text.measure(&line, size);
                assert!(
                    measured <= room,
                    "the {code} page draws {line:?} over {measured:.1} points, \
                     and it has {room:.1}"
                );
            }
        }
    }
}