write_devicen.rs

Die Rust-Datei des Beispiels „Mehrere Platten zugleich, jede in eigener Stärke“. Acht Plattenkombinationen aus den vier üblichen Druckfarben, jede mit dem kleinen Programm darunter gedruckt, das sie zeigt, und zwei Druckfarben, die die Maschine selbst führt, gemeinsam verwendet, jede Stärke der einen gegen jede Stärke der anderen.

Rust 635 Zeilen

Wofür dieses Beispiel da ist

Manche Druckmaschinen führen sechs oder acht Druckfarben statt vier. Manche Aufträge müssen Schwarz über ein Bild legen, ohne die drei Farbplatten darunter anzutasten. Beides lässt sich auf die gewöhnliche Art, eine Farbe zu nennen, nicht sagen, denn die gewöhnliche Art spricht alle Platten zugleich an, ob man es wollte oder nicht.

Was dieses Beispiel zeigt

  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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Several named colorants at once, each on a plate of its own.
//!
//! A colour in such a space is one tint per colorant, and one program says what
//! the lot of them look like where those plates are not to hand. Naming some of
//! the process plates and no others is how a document lays ink on those and
//! leaves the rest as they stand; naming inks of its own is how a press that
//! carries more than four is painted in.
//!
//! The space's attributes say the rest: each subset's plates are the components
//! of the process space, and each of the two inks is described alone, as the
//! colour it lays down at full strength, for a preview that shows one plate at
//! a time. The line under the grid names the inks the attributes describe.
//!
//! The words the page draws are held in `Words`, one set per language, and
//! `HQF_PDF_LANG` picks which set is drawn. The colorants are not words: their
//! names are written into the file and drawn back from it.
//!
//! Usage: `cargo run --example write_devicen -- tmp/devicen.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_devicen -- tmp/devicen_fr.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{
    Calculation, Cmyk, ColorSpace, ColorSpaceHandle, DeviceN, DeviceNAttributes, DeviceSpace,
    Document, Font, FontHandle, Op, Page, Rgb, Separation,
};

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

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

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

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

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")
}

/// The left edge of everything.
const LEFT: f64 = 70.0;

/// The words the page is written in, one set per language.
///
/// What is not language stays out of it: a colorant's name is written into the
/// file and drawn back from it, and so are the programs and the tints.
#[derive(Debug)]
struct Words {
    /// The title across the top of the page.
    title: &'static str,
    /// The two lines under the title, each already broken to the page.
    lead: [&'static str; 2],
    /// The heading of the panel of subsets.
    subsets: &'static str,
    /// The heading of the panel of two inks, and the line under it.
    inks: &'static str,
    inks_under: &'static str,
    /// The line under the grid, before the names of the inks described alone.
    described: &'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: "Several plates at once, each with a tint of its own",
    lead: [
        "Naming some of the process plates and no others lays ink on those and leaves the rest as",
        "they stand, which painting in full CMYK cannot do. One program fills in the plates left out.",
    ],
    subsets: "Subsets of the process plates, and the program each one is shown through",
    inks: "Two inks of the press's own on one space, every tint of each against the other",
    inks_under: "Down the side, Corporate Blue. Across the top, Corporate Gold. Two numbers say a \
                 colour here.",
    described: "Each ink is also described alone, for a reader that lays one plate at a time:",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Plusieurs plaques à la fois, chacune à son intensité",
    lead: [
        "Ne nommer que certaines plaques de quadrichromie dépose l’encre sur celles-ci et laisse",
        "les autres intactes, impossible en quadrichromie complète. Un programme remplit le reste.",
    ],
    subsets: "Sous-ensembles des plaques de quadrichromie, et le programme qui affiche chacun",
    inks: "Deux tons directs dans un espace, chaque intensité de l’un croisée avec l’autre",
    inks_under: "Sur le côté, Corporate Blue. En haut, Corporate Gold. Ici, une couleur tient \
en deux nombres.",
    described: "Chaque encre est aussi décrite seule, pour un aperçu plaque par plaque :",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Meerdere platen tegelijk, elk met een eigen tint",
    lead: [
        "Wie alleen sommige procesplaten noemt, zet alleen daarop inkt en laat de rest zoals",
        "hij is, wat schilderen in volledige CMYK niet kan. Eén programma vult de weggelaten platen in.",
    ],
    subsets: "Deelverzamelingen van de procesplaten, en het programma waarmee elk getoond wordt",
    inks: "Twee eigen inkten van de drukpers in één ruimte, elke tint van de een tegen de ander",
    inks_under: "Langs de zijkant Corporate Blue. Bovenaan Corporate Gold. Twee getallen geven hier een kleur aan.",
    described: "Elke inkt wordt ook apart beschreven, voor een lezer die één plaat tegelijk legt:",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Várias chapas de uma vez, cada uma com o seu tom",
    lead: [
        "Nomear só algumas chapas de quadricromia põe tinta nessas e deixa as outras como",
        "estão, o que pintar em CMYK completo não faz. Um programa preenche as chapas omitidas.",
    ],
    subsets: "Subconjuntos das chapas de quadricromia, e o programa com que cada um é mostrado",
    inks: "Duas tintas próprias da gráfica num espaço, cada tom de uma contra a outra",
    inks_under: "Na lateral, Corporate Blue. Em cima, Corporate Gold. Aqui dois números dizem uma cor.",
    described: "Cada tinta é também descrita à parte, para quem imprime chapa a chapa:",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Più lastre alla volta, ciascuna con una tinta propria",
    lead: [
        "Nominare solo alcune lastre di quadricromia mette inchiostro su quelle e lascia le altre come",
        "sono, cosa che dipingere in CMYK completo non fa. Un programma riempie le lastre omesse.",
    ],
    subsets: "Sottoinsiemi delle lastre di quadricromia, e il programma con cui si mostra ciascuno",
    inks: "Due inchiostri propri della macchina su uno spazio, ogni tinta dell’uno contro l’altro",
    inks_under: "Di lato, Corporate Blue. In alto, Corporate Gold. Qui due numeri dicono un colore.",
    described: "Ogni inchiostro anche da solo, per chi guarda una lastra alla volta:",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Varias planchas a la vez, cada una con su propio tono",
    lead: [
        "Nombrar solo algunas planchas de cuatricromía pone tinta en esas y deja el resto como",
        "está, cosa que no hace pintar en CMYK completo. Un programa rellena las planchas omitidas.",
    ],
    subsets: "Subconjuntos de las planchas de cuatricromía, y el programa con que se muestra cada uno",
    inks: "Dos tintas propias de la imprenta en un espacio, cada tono de una frente a la otra",
    inks_under: "En el lateral, Corporate Blue. Arriba, Corporate Gold. Aquí dos números dicen un color.",
    described: "Cada tinta se describe también sola, para quien imprime plancha a plancha:",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Mehrere Druckplatten zugleich, jede mit ihrem eigenen Tonwert",
    lead: [
        "Werden nur einige Prozessplatten genannt, kommt Farbe auf diese, die übrigen bleiben,",
        "wie sie sind – was volles CMYK nicht kann. Ein Programm füllt die fehlenden Platten.",
    ],
    subsets: "Teilmengen der Prozessplatten und das Programm, durch das jede angezeigt wird",
    inks: "Zwei Hausfarben in einem Farbraum, jeder Tonwert der einen gegen die andere",
    inks_under: "An der Seite Corporate Blue, oben Corporate Gold. Zwei Zahlen ergeben hier eine Farbe.",
    described: "Jede Farbe auch einzeln beschrieben, für Leser, die Platte für Platte auftragen:",
};

/// 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); 7] = [
    (Language::English, &ENGLISH),
    (Language::French, &FRENCH),
    (Language::German, &GERMAN),
    (Language::Spanish, &SPANISH),
    (Language::Italian, &ITALIAN),
    (Language::Portuguese, &PORTUGUESE),
    (Language::Dutch, &DUTCH),
];

/// One subset of the process plates: the plates it names, the program that
/// fills in the ones it leaves out, and the tint each named plate is shown at.
struct Subset {
    colorants: &'static [&'static str],
    body: &'static [Op],
    tints: &'static [f64],
}

/// The subsets the first panel shows, each with the program that turns its
/// tints into a full set of process inks.
const SUBSETS: &[Subset] = &[
    Subset {
        colorants: &["Cyan"],
        body: &[Op::Integer(0), Op::Integer(0), Op::Integer(0)],
        tints: &[0.8],
    },
    Subset {
        colorants: &["Magenta"],
        body: &[
            Op::Integer(0),
            Op::Integer(0),
            Op::Integer(0),
            Op::Integer(4),
            Op::Integer(1),
            Op::Roll,
        ],
        tints: &[0.8],
    },
    Subset {
        colorants: &["Yellow"],
        body: &[
            Op::Integer(0),
            Op::Integer(0),
            Op::Integer(0),
            Op::Integer(4),
            Op::Integer(2),
            Op::Roll,
        ],
        tints: &[0.8],
    },
    Subset {
        colorants: &["Black"],
        body: &[
            Op::Integer(0),
            Op::Integer(0),
            Op::Integer(0),
            Op::Integer(4),
            Op::Integer(3),
            Op::Roll,
        ],
        tints: &[0.8],
    },
    Subset {
        colorants: &["Cyan", "Magenta"],
        body: &[Op::Integer(0), Op::Integer(0)],
        tints: &[0.7, 0.7],
    },
    Subset {
        colorants: &["Cyan", "Yellow"],
        body: &[Op::Integer(0), Op::Exchange, Op::Integer(0)],
        tints: &[0.7, 0.7],
    },
    Subset {
        colorants: &["Magenta", "Yellow"],
        body: &[
            Op::Integer(0),
            Op::Integer(0),
            Op::Integer(4),
            Op::Integer(1),
            Op::Roll,
        ],
        tints: &[0.7, 0.7],
    },
    Subset {
        colorants: &["Cyan", "Magenta", "Yellow"],
        body: &[Op::Integer(0)],
        tints: &[0.6, 0.6, 0.6],
    },
];

/// The left edge of each column of the first panel, and the size of one swatch.
const SUBSET_X: &[f64] = &[70.0, 185.0, 300.0, 415.0];
/// See [`SUBSET_X`].
const SUBSET_SIZE: (f64, f64) = (100.0, 52.0);
/// The baseline the first row of swatches sits on, and the drop to the second.
const SUBSET_Y: f64 = 620.0;
/// See [`SUBSET_Y`].
const SUBSET_DROP: f64 = 108.0;

/// The two inks the second panel paints in, as the process inks show them at
/// full strength.
const BLUE: [f64; 4] = [0.92, 0.58, 0.0, 0.06];
/// See [`BLUE`].
const GOLD: [f64; 4] = [0.0, 0.28, 0.95, 0.04];

/// The tints the duotone grid runs through, along both of its axes.
const DUOTONE_TINTS: &[f64] = &[0.0, 0.25, 0.5, 0.75, 1.0];
/// The left edge and the top of the duotone grid, and the size of one cell.
const DUOTONE_ORIGIN: (f64, f64) = (110.0, 355.0);
/// See [`DUOTONE_ORIGIN`].
const DUOTONE_CELL: f64 = 52.0;

/// 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<(), hqf_pdf::Error> {
    content.begin_text();
    content.set_font(font, size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(line));
    content.end_text();
    Ok(())
}

/// The program mixing two inks: each output is the first ink's share of that
/// process plate taken at the first tint, plus the second ink's taken at the
/// second.
///
/// Both tints stay at the bottom of the stack while the four outputs are worked
/// out above them, so each one is reached again by counting down past the
/// outputs already there; the pair is then turned to the top and thrown away.
#[allow(clippy::expect_used, reason = "four plates count")]
fn mix_two_inks() -> Calculation {
    let mut body = Vec::new();
    for (plate, (first, second)) in BLUE.iter().zip(&GOLD).enumerate() {
        let reach = i64::try_from(plate).expect("four plates count") + 1;
        body.extend([
            Op::Integer(reach),
            Op::Index,
            Op::Real(*first),
            Op::Multiply,
            Op::Integer(reach),
            Op::Index,
            Op::Real(*second),
            Op::Multiply,
            Op::Add,
        ]);
    }
    body.extend([Op::Integer(6), Op::Integer(4), Op::Roll, Op::Pop, Op::Pop]);
    Calculation::new([[0.0, 1.0]; 2], [[0.0, 1.0]; 4], body)
}

/// Draws one swatch of a subset of the process plates, with the plates it names
/// above it and the program that fills in the rest below.
fn subset_swatch(
    content: &mut Content,
    font: &FontHandle,
    space: &ColorSpaceHandle,
    subset: &Subset,
    x: f64,
    y: f64,
) -> Result<(), hqf_pdf::Error> {
    let (width, height) = SUBSET_SIZE;

    content.save_state();
    content.set_fill_space(space);
    content.set_fill_components(subset.tints)?;
    content.rect(x, y, width, height)?.fill();
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::gray(0.2))?;
    text(
        content,
        font,
        8.0,
        x,
        y + height + 7.0,
        &subset.colorants.join(" "),
    )?;
    content.set_fill(Rgb::gray(0.45))?;
    text(
        content,
        font,
        7.0,
        x,
        y - 11.0,
        &Calculation::new(
            vec![[0.0, 1.0]; subset.colorants.len()],
            [[0.0, 1.0]; 4],
            subset.body,
        )
        .program()?,
    )?;
    content.restore_state();
    Ok(())
}

/// Draws the grid of the two inks against one another, every tint of the first
/// crossed with every tint of the second.
fn duotone_grid(
    content: &mut Content,
    font: &FontHandle,
    space: &ColorSpaceHandle,
) -> Result<(), hqf_pdf::Error> {
    let (left, top) = DUOTONE_ORIGIN;

    for (row, blue) in DUOTONE_TINTS.iter().enumerate() {
        #[expect(
            clippy::cast_precision_loss,
            reason = "the grid is five cells each way, so the count is exact as a real"
        )]
        let down = (row as f64).mul_add(-DUOTONE_CELL, top);
        for (column, gold) in DUOTONE_TINTS.iter().enumerate() {
            #[expect(
                clippy::cast_precision_loss,
                reason = "the grid is five cells each way, so the count is exact as a real"
            )]
            let across = (column as f64).mul_add(DUOTONE_CELL, left);
            content.save_state();
            content.set_fill_space(space);
            content.set_fill_components(&[*blue, *gold])?;
            content
                .rect(across, down, DUOTONE_CELL - 4.0, DUOTONE_CELL - 4.0)?
                .fill();
            content.restore_state();
        }

        content.save_state();
        content.set_fill(Rgb::gray(0.45))?;
        text(
            content,
            font,
            7.0,
            LEFT,
            down + DUOTONE_CELL / 2.0 - 7.0,
            &format!("{:.0}%", blue * 100.0),
        )?;
        content.restore_state();
    }

    for (column, gold) in DUOTONE_TINTS.iter().enumerate() {
        #[expect(
            clippy::cast_precision_loss,
            reason = "the grid is five cells each way, so the count is exact as a real"
        )]
        let across = (column as f64).mul_add(DUOTONE_CELL, left);
        content.save_state();
        content.set_fill(Rgb::gray(0.45))?;
        text(
            content,
            font,
            7.0,
            across,
            top + DUOTONE_CELL - 1.0,
            &format!("{:.0}%", gold * 100.0),
        )?;
        content.restore_state();
    }
    Ok(())
}

/// Draws the title and the two lines saying what the page is showing.
fn heading(
    content: &mut Content,
    font: &FontHandle,
    words: &'static Words,
) -> Result<(), hqf_pdf::Error> {
    text(content, font, 15.0, LEFT, 780.0, words.title)?;
    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    text(content, font, 10.0, LEFT, 762.0, words.lead[0])?;
    text(content, font, 10.0, LEFT, 748.0, words.lead[1])?;
    content.restore_state();
    Ok(())
}

/// Draws one panel's heading, with the line under it that a panel may have.
fn panel_heading(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    title: &str,
    under: Option<&str>,
) -> Result<(), hqf_pdf::Error> {
    content.save_state();
    content.set_fill(Rgb::gray(0.2))?;
    text(content, font, 11.0, LEFT, y, title)?;
    if let Some(line) = under {
        content.set_fill(Rgb::gray(0.45))?;
        text(content, font, 8.0, LEFT, y - 16.0, line)?;
    }
    content.restore_state();
    Ok(())
}

/// Draws every subset of the process plates, four to a row.
fn subset_panel(
    doc: &mut Document,
    content: &mut Content,
    font: &FontHandle,
) -> Result<(), hqf_pdf::Error> {
    for (place, subset) in SUBSETS.iter().enumerate() {
        // The plates a subset names are the components of the process space,
        // which the attributes say under the names the space takes them by.
        let space = doc.add_color_space(
            DeviceN::new(
                subset
                    .colorants
                    .iter()
                    .map(|colorant| (*colorant).to_owned())
                    .collect::<Vec<_>>(),
                DeviceSpace::Cmyk,
                Calculation::new(
                    vec![[0.0, 1.0]; subset.colorants.len()],
                    [[0.0, 1.0]; 4],
                    subset.body,
                ),
            )?
            .with_attributes(DeviceNAttributes::new().with_process(
                DeviceSpace::Cmyk,
                ["Cyan", "Magenta", "Yellow", "Black"].map(str::to_owned),
            )?),
        );
        let x = SUBSET_X[place % SUBSET_X.len()];
        #[expect(
            clippy::cast_precision_loss,
            reason = "the panel holds two rows, so the count is exact as a real"
        )]
        let y = ((place / SUBSET_X.len()) as f64).mul_add(-SUBSET_DROP, SUBSET_Y);
        subset_swatch(content, font, &space, subset, x, y)?;
    }
    Ok(())
}

fn main() -> std::process::ExitCode {
    failure::reported(run())
}

fn run() -> 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("devicen")));
    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 content = Content::new();
    heading(&mut content, &font, words)?;
    panel_heading(&mut content, &font, 700.0, words.subsets, None)?;
    subset_panel(&mut doc, &mut content, &font)?;

    panel_heading(
        &mut content,
        &font,
        440.0,
        words.inks,
        Some(words.inks_under),
    )?;
    // Each ink is also said on its own, as the colour it lays down at full
    // strength, for a reader that shows one plate at a time.
    let [blue, gold] = [("Corporate Blue", BLUE), ("Corporate Gold", GOLD)]
        .map(|(name, [c, m, y, k])| Separation::ink(name, Cmyk::new(c, m, y, k)));
    let two_inks = DeviceN::new(
        vec!["Corporate Blue".to_owned(), "Corporate Gold".to_owned()],
        DeviceSpace::Cmyk,
        mix_two_inks(),
    )?
    .with_attributes(
        DeviceNAttributes::new()
            .with_colorant(blue)?
            .with_colorant(gold)?,
    );
    let described: Vec<&str> = two_inks
        .attributes()
        .into_iter()
        .flat_map(|attributes| {
            two_inks
                .colorants()
                .iter()
                .filter_map(|name| attributes.colorant(name))
        })
        .map(Separation::colorant)
        .collect();
    let line = format!("{} {}", words.described, described.join(", "));
    let inks = doc.add_color_space(ColorSpace::DeviceN(two_inks));
    duotone_grid(&mut content, &font, &inks)?;
    content.save_state();
    content.set_fill(Rgb::gray(0.45))?;
    text(&mut content, &font, 8.0, LEFT, 110.0, &line)?;
    content.restore_state();

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

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;
    println!(
        "wrote {out}: {} bytes, {} subsets of the process plates and two inks of its own",
        bytes.len(),
        SUBSETS.len()
    );
    Ok(())
}

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

    use super::{LEFT, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way. There are
    /// none: an ink's name is drawn from the file, not from `Words`.
    const SPARED: [&str; 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:?}"
        );
    }

    /// The line under the grid is set on one line, with the names of both inks
    /// after it, and stops short of the right margin.
    #[test]
    fn the_line_under_the_grid_stops_short_of_the_margin() {
        let mut doc = Document::new();
        let font = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );
        let room = 595.0 - LEFT - LEFT;
        for (_, words) in WORDS {
            let line = format!("{} Corporate Blue, Corporate Gold", words.described);
            let width = font.measure(&line, 8.0);
            assert!(width <= room, "{line:?} needs {width} of {room}");
        }
    }
}