write_calibrated_color.rs

Die Rust-Datei des Beispiels „Dieselben Zahlen, so gesagt, dass sie etwas bedeuten“. Sechs Farben und ein Grauverlauf, dreimal mit genau denselben Zahlen gemalt: zuerst dem Gerät überlassen, dann auf zwei Arten angegeben, die das Weiß nennen, an dem sie gemessen werden, die Kurve, die auf sie angewendet wird, und wie weit die Grundfarben reichen. Eine zweite Seite malt bloße Zahlen, die nichts über ihre Bedeutung sagen, und lässt die Seite selbst es für sie sagen. All das reist in einer Handvoll Zahlen, ohne Profil zum Mitnehmen.

Rust 752 Zeilen

Wofür dieses Beispiel da ist

Ein Farbprofil in einem Dokument mitzunehmen kostet einige hundert Kilobyte, bei jeder Kopie, und es gibt Dokumente, die sich das nicht leisten können: ein Kontoauszug an eine Million Menschen, ein Formular, das über eine schlechte Verbindung geladen wird. Es sieht aus wie eine Wahl zwischen Farbe, die etwas bedeutet, und einer Datei, die klein bleibt, aber das ist sie 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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! The same numbers, painted through spaces that say what they mean.
//!
//! `0.8 0.1 0.1 rg` is three numbers and a hope. A calibrated space says
//! instead what white the numbers are measured against, what exponent they are
//! raised to and — for colour — what the three primaries actually reach, so the
//! same numbers are the same colour wherever the file is opened. The page below
//! paints one row of colours and one grey ramp three times over, changing
//! nothing but the space they are said in.
//!
//! A second page paints the same row and the same ramp as plain device numbers,
//! naming no space, and says on the page itself which calibrated space plain
//! RGB and plain grey mean there: a reader goes by the page's default spaces.
//! That page is also composited as an isolated group blended in the ordinary
//! space.
//!
//! What the page reads is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn. The numbers the bands are painted
//! from are not language: they are the same colours whoever reads the page.
//!
//! Usage: `cargo run --example write_calibrated_color -- tmp/calibrated.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_calibrated_color --
//! tmp/calibree.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{
    CalGray, CalRgb, Color, ColorSpace, ColorSpaceHandle, Document, Error, Font, FontHandle, Page,
    PageGroup, Rgb,
};

#[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, and how wide a row runs.
const LEFT: f64 = 70.0;
/// See [`LEFT`].
const RUN: f64 = 455.0;

/// The white every calibrated space on the page is measured against, as CIE
/// XYZ.
const WHITE: [f64; 3] = [0.9505, 1.0, 1.089];

/// The six colours the first three rows paint, each as three numbers.
const COLORS: &[[f64; 3]] = &[
    [0.80, 0.10, 0.10],
    [0.90, 0.50, 0.10],
    [0.90, 0.85, 0.20],
    [0.15, 0.55, 0.30],
    [0.15, 0.35, 0.70],
    [0.45, 0.20, 0.55],
];

/// The size of one colour swatch, and the gap to the next.
const SWATCH: (f64, f64) = (70.0, 55.0);
/// See [`SWATCH`].
const SWATCH_GAP: f64 = 7.0;

/// How many steps the grey ramp is cut into, and how tall it stands.
const STEPS: usize = 10;
/// See [`STEPS`].
const RAMP_HEIGHT: f64 = 45.0;

/// The darkest black the wider colour space and the bent grey reach, as CIE
/// XYZ: a paper's black that reflects a little light rather than none.
const BLACK: [f64; 3] = [0.0080, 0.0083, 0.0069];

/// The words the page is written in, one set per language.
///
/// The numbers the bands are painted from are not here: three numbers are the
/// same three numbers in every language.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// The two lines under it, saying that nothing below was painted twice.
    intro: [&'static str; 2],
    /// The heading of each panel, and the line under it.
    panels: [[&'static str; 2]; 2],
    /// The caption each band stands under, in the order the bands are painted.
    captions: [&'static str; 6],
    /// The three lines at the foot of the page.
    closing: [&'static str; 3],
    /// The line at the head of the second page.
    defaults_title: &'static str,
    /// The two lines under it, saying what the page does.
    defaults_intro: [&'static str; 2],
    /// What stands over the row and over the ramp of the second page.
    defaults_captions: [&'static str; 2],
    /// What the second page says of the group it is composited as.
    group_note: &'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: "The same numbers, through spaces that say what they mean",
    intro: [
        "Nothing below was painted twice with different numbers. Each band holds the very same \
         numbers as",
        "the one above it, and what changes is the space they are said in.",
    ],
    panels: [
        [
            "Six colours, three ways of meaning them",
            "The three numbers are the same in every band. The primaries under them are not.",
        ],
        [
            "One grey ramp, three exponents",
            "Ten steps from 0.05 to 0.95, painted with the same ten numbers each time.",
        ],
    ],
    captions: [
        "Left to the device",
        "Through one set of primaries",
        "Through a wider set of primaries, over a measured black",
        "Left to the device",
        "Measured, raised to 1",
        "Measured, raised to 2.2, over a measured black",
    ],
    closing: [
        "A calibrated space carries its measurement in a handful of numbers rather than in a \
         profile,",
        "so a file states what its colours are without embedding anything and without asking \
         the",
        "reader to have the right profile installed.",
    ],
    defaults_title: "The same device numbers, read the way the page says",
    defaults_intro: [
        "Nothing below names a space: every colour is a plain rg or g. The page itself",
        "says which calibrated space plain numbers mean, and a reader goes by it.",
    ],
    defaults_captions: [
        "rg as written; the page's default RGB is the wider calibrated space",
        "g as written; the page's default grey is the grey raised to 2.2",
    ],
    group_note: "The page is composited as a group blended in the ordinary space, on its own.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Les mêmes nombres, dans des espaces qui disent ce qu’ils signifient",
    intro: [
        "Rien ci-dessous n’a été peint deux fois avec des nombres différents. Chaque \
bande reprend les mêmes",
        "nombres que celle du dessus ; ce qui change, c’est l’espace dans lequel on les exprime.",
    ],
    panels: [
        [
            "Six couleurs, trois façons de les définir",
            "Les trois nombres sont les mêmes dans chaque bande. Les primaires sous-jacentes, non.",
        ],
        [
            "Un dégradé de gris, trois exposants",
            "Dix paliers de 0.05 à 0.95, peints chaque fois avec les dix mêmes nombres.",
        ],
    ],
    captions: [
        "Laissé à l’appareil",
        "Rapporté à un jeu de primaires",
        "Rapporté à des primaires plus larges, sur un noir mesuré",
        "Laissé à l’appareil",
        "Mesuré, exposant 1",
        "Mesuré, exposant 2,2, sur un noir mesuré",
    ],
    closing: [
        "Un espace calibré exprime sa mesure en une poignée de nombres plutôt que par un profil,",
        "si bien qu’un fichier dit ce que sont ses couleurs sans rien incorporer et sans exiger",
        "que le logiciel de lecture ait le bon profil installé.",
    ],
    defaults_title: "Les mêmes nombres, lus comme l’indique la page",
    defaults_intro: [
        "Rien ci-dessous ne nomme d’espace : chaque couleur est un simple rg ou g. La page dit",
        "elle-même quel espace calibré ces nombres désignent ; le logiciel de lecture s’y tient.",
    ],
    defaults_captions: [
        "rg tel qu’écrit ; le RVB par défaut de la page est l’espace calibré plus large",
        "g tel qu’écrit ; le gris par défaut de la page est le gris élevé à la puissance 2,2",
    ],
    group_note: "La page est composée comme un groupe isolé, fusionné dans l’espace ordinaire.",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Dezelfde getallen, in ruimten die zeggen wat ze betekenen",
    intro: [
        "Niets hieronder is twee keer met andere getallen ingekleurd. Elke band bevat dezelfde getallen",
        "als die erboven; alleen de ruimte waarin ze worden uitgedrukt, verandert.",
    ],
    panels: [
        [
            "Zes kleuren, drie manieren om ze op te vatten",
            "De drie getallen zijn in elke band gelijk. De primaire kleuren eronder niet.",
        ],
        [
            "Eén grijsverloop, drie exponenten",
            "Tien stappen van 0,05 tot 0,95, telkens met dezelfde tien getallen geschilderd.",
        ],
    ],
    captions: [
        "Aan het apparaat overgelaten",
        "Via één set primaire kleuren",
        "Via ruimere primaire kleuren, boven een gemeten zwart",
        "Aan het apparaat overgelaten",
        "Gemeten, tot de macht 1",
        "Gemeten, tot de macht 2,2, boven een gemeten zwart",
    ],
    closing: [
        "Een gekalibreerde ruimte legt haar meting vast in een handvol getallen in plaats van in een profiel,",
        "dus zegt een bestand wat zijn kleuren zijn zonder iets in te sluiten en zonder van de",
        "lezer te vragen dat het juiste profiel geïnstalleerd is.",
    ],
    defaults_title: "Dezelfde apparaatgetallen, gelezen zoals de pagina zegt",
    defaults_intro: [
        "Niets hieronder noemt een ruimte: elke kleur is een gewone rg of g. De pagina zelf",
        "zegt welke gekalibreerde ruimte gewone getallen betekenen, en een lezer volgt haar.",
    ],
    defaults_captions: [
        "rg zoals geschreven; de standaard-RGB van de pagina is de ruimere gekalibreerde ruimte",
        "g zoals geschreven; het standaardgrijs van de pagina is het grijs tot de macht 2,2",
    ],
    group_note: "De pagina wordt samengesteld als een geïsoleerde groep, gemengd in de gewone ruimte.",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Os mesmos números, em espaços que dizem o que significam",
    intro: [
        "Nada abaixo foi pintado duas vezes com números diferentes. Cada faixa tem os mesmos números que",
        "a de cima, e o que muda é o espaço em que são ditos.",
    ],
    panels: [
        [
            "Seis cores, três formas de as entender",
            "Os três números são iguais em cada faixa. Os primários por baixo não.",
        ],
        [
            "Uma rampa de cinzentos, três expoentes",
            "Dez passos de 0,05 a 0,95, pintados de cada vez com os mesmos dez números.",
        ],
    ],
    captions: [
        "Entregue ao dispositivo",
        "Através de um conjunto de primários",
        "Através de primários mais amplos, sobre um preto medido",
        "Entregue ao dispositivo",
        "Medido, elevado a 1",
        "Medido, elevado a 2,2, sobre um preto medido",
    ],
    closing: [
        "Um espaço calibrado leva a sua medida em meia dúzia de números em vez de um perfil,",
        "por isso um ficheiro diz quais são as suas cores sem incorporar nada e sem pedir ao",
        "leitor que tenha instalado o perfil certo.",
    ],
    defaults_title: "Os mesmos números de dispositivo, lidos como diz a página",
    defaults_intro: [
        "Nada abaixo nomeia um espaço: cada cor é um simples rg ou g. A própria página",
        "diz que espaço calibrado significam os números simples, e o leitor segue-a.",
    ],
    defaults_captions: [
        "rg tal como escrito; o RGB por omissão da página é o espaço calibrado mais amplo",
        "g tal como escrito; o cinzento por omissão da página é o cinzento elevado a 2,2",
    ],
    group_note: "A página é composta como um grupo misturado no espaço corrente, por si só.",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Gli stessi numeri, in spazi che dicono cosa significano",
    intro: [
        "Niente qui sotto è stato dipinto due volte con numeri diversi. Ogni fascia porta gli stessi numeri di",
        "quella sopra, e ciò che cambia è lo spazio in cui sono espressi.",
    ],
    panels: [
        [
            "Sei colori, tre modi di intenderli",
            "I tre numeri sono uguali in ogni fascia. I primari sottostanti no.",
        ],
        [
            "Una scala di grigi, tre esponenti",
            "Dieci passi da 0,05 a 0,95, dipinti ogni volta con gli stessi dieci numeri.",
        ],
    ],
    captions: [
        "Lasciato al dispositivo",
        "Attraverso un insieme di primari",
        "Attraverso primari più ampi, su un nero misurato",
        "Lasciato al dispositivo",
        "Misurato, elevato a 1",
        "Misurato, elevato a 2,2, su un nero misurato",
    ],
    closing: [
        "Uno spazio calibrato porta la sua misura in pochi numeri anziché in un profilo,",
        "così un file dice quali sono i suoi colori senza incorporare nulla e senza chiedere al",
        "programma di lettura di avere installato il profilo giusto.",
    ],
    defaults_title: "Gli stessi numeri di dispositivo, letti come dice la pagina",
    defaults_intro: [
        "Niente qui sotto nomina uno spazio: ogni colore è un semplice rg o g. La pagina stessa",
        "dice in quale spazio calibrato si leggono i numeri semplici, e il programma di lettura la segue.",
    ],
    defaults_captions: [
        "rg così com’è; l’RGB predefinito della pagina è lo spazio calibrato più ampio",
        "g così com’è; il grigio predefinito della pagina è il grigio elevato a 2,2",
    ],
    group_note: "La pagina è composta come un gruppo fuso nello spazio ordinario, da sola.",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Los mismos números, en espacios que dicen lo que significan",
    intro: [
        "Nada de abajo se pintó dos veces con números distintos. Cada banda lleva los mismos números que",
        "la de encima, y lo que cambia es el espacio en que se expresan.",
    ],
    panels: [
        [
            "Seis colores, tres formas de entenderlos",
            "Los tres números son iguales en cada banda. Los primarios de debajo, no.",
        ],
        [
            "Una rampa de grises, tres exponentes",
            "Diez pasos de 0,05 a 0,95, pintados cada vez con los mismos diez números.",
        ],
    ],
    captions: [
        "Según el dispositivo",
        "Con un juego de primarios",
        "Con un juego de primarios más amplio, sobre un negro medido",
        "Según el dispositivo",
        "Medido, elevado a 1",
        "Medido, elevado a 2,2, sobre un negro medido",
    ],
    closing: [
        "Un espacio calibrado lleva su medida en unos pocos números en lugar de un perfil,",
        "así que un archivo dice cuáles son sus colores sin incrustar nada y sin pedir al",
        "lector que tenga instalado el perfil adecuado.",
    ],
    defaults_title: "Los mismos números de dispositivo, leídos como dice la página",
    defaults_intro: [
        "Nada de abajo nombra un espacio: cada color es un simple rg o g. La propia página",
        "dice qué espacio calibrado significan los números simples, y el lector la sigue.",
    ],
    defaults_captions: [
        "rg tal cual; el RGB por defecto de la página es el espacio calibrado más amplio",
        "g tal cual; el gris por defecto de la página es el gris elevado a 2,2",
    ],
    group_note: "La página se compone como un grupo mezclado en el espacio ordinario, por sí sola.",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Dieselben Zahlen in Farbräumen, die sagen, was sie bedeuten",
    intro: [
        "Nichts unten wurde zweimal mit verschiedenen Zahlen gemalt. Jedes Band enthält genau dieselben",
        "Zahlen wie das darüber; was sich ändert, ist der Farbraum, in dem sie gelten.",
    ],
    panels: [
        [
            "Sechs Farben, drei Lesarten",
            "Die drei Zahlen sind in jedem Band dieselben. Die Primärfarben dahinter nicht.",
        ],
        [
            "Ein Graukeil, drei Exponenten",
            "Zehn Stufen von 0,05 bis 0,95, jedes Mal mit denselben zehn Zahlen gemalt.",
        ],
    ],
    captions: [
        "Dem Gerät überlassen",
        "Über einen Satz Primärfarben",
        "Über einen weiteren Satz Primärfarben, über einem gemessenen Schwarz",
        "Dem Gerät überlassen",
        "Gemessen, hoch 1",
        "Gemessen, hoch 2,2, über einem gemessenen Schwarz",
    ],
    closing: [
        "Ein kalibrierter Farbraum trägt seine Messung in einer Handvoll Zahlen statt in einem Profil,",
        "also sagt eine Datei, was ihre Farben sind, ohne etwas einzubetten und ohne vom Leser zu",
        "verlangen, dass das richtige Profil installiert ist.",
    ],
    defaults_title: "Dieselben Gerätezahlen, so gelesen, wie die Seite es sagt",
    defaults_intro: [
        "Nichts unten nennt einen Farbraum: Jede Farbe ist ein schlichtes rg oder g. Die Seite selbst",
        "sagt, welchen kalibrierten Farbraum schlichte Zahlen meinen, und ein Leser richtet sich danach.",
    ],
    defaults_captions: [
        "rg wie geschrieben; das Standard-RGB der Seite ist der weitere kalibrierte Farbraum",
        "g wie geschrieben; das Standardgrau der Seite ist das Grau hoch 2,2",
    ],
    group_note: "Die Seite wird als Gruppe zusammengesetzt, für sich im gewöhnlichen Farbraum gemischt.",
};

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

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

/// Writes the small caption a band stands under.
fn caption(content: &mut Content, font: &FontHandle, y: f64, line: &str) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.45))?;
    text(content, font, 8.0, LEFT, y, line)?;
    content.restore_state();
    Ok(())
}

/// Draws one panel's heading, with the line under it.
fn panel_heading(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    title: &str,
    under: &str,
) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.2))?;
    text(content, font, 11.0, LEFT, y, title)?;
    content.set_fill(Color::Gray(0.45))?;
    text(content, font, 8.0, LEFT, y - 15.0, under)?;
    content.restore_state();
    Ok(())
}

/// Paints the six colours across, in whichever space `space` names; without one
/// they are left to the device.
fn band(content: &mut Content, space: Option<&ColorSpaceHandle>, bottom: f64) -> Result<(), Error> {
    let mut x = LEFT;
    for color in COLORS {
        content.save_state();
        match space {
            Some(space) => {
                content.set_fill_space(space);
                content.set_fill_components(color)?;
            }
            None => {
                content.set_fill(Rgb::new(color[0], color[1], color[2]))?;
            }
        }
        content.rect(x, bottom, SWATCH.0, SWATCH.1)?.fill();
        content.restore_state();
        x += SWATCH.0 + SWATCH_GAP;
    }
    Ok(())
}

/// Paints the grey ramp across, in whichever space `space` names; without one
/// it is left to the device.
fn ramp(content: &mut Content, space: Option<&ColorSpaceHandle>, bottom: f64) -> Result<(), Error> {
    #[expect(
        clippy::cast_precision_loss,
        reason = "ten steps are far short of what an f64 counts exactly"
    )]
    let width = RUN / STEPS as f64;
    let mut x = LEFT;
    let mut grey = 0.05;
    for _ in 0..STEPS {
        content.save_state();
        match space {
            Some(space) => {
                content.set_fill_space(space);
                content.set_fill_components(&[grey])?;
            }
            None => {
                content.set_fill(Color::Gray(grey))?;
            }
        }
        content.rect(x, bottom, width, RAMP_HEIGHT)?.fill();
        content.restore_state();
        x += width;
        grey += 0.1;
    }
    Ok(())
}

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

/// Draws the closing note.
fn closing(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    for (y, line) in [140.0, 126.0, 112.0].into_iter().zip(words.closing) {
        text(content, font, 9.0, LEFT, y, line)?;
    }
    content.restore_state();
    Ok(())
}

/// The second page: the row and the ramp in plain device numbers, the page
/// reading plain RGB through `rgb` and plain grey through `gray`, and
/// composited as an isolated group blended in `blended`.
fn defaults_page(
    font: &FontHandle,
    words: &Words,
    rgb: &ColorSpaceHandle,
    gray: &ColorSpaceHandle,
    blended: &ColorSpaceHandle,
) -> Result<Page, Error> {
    let mut content = Content::new();
    text(&mut content, font, 15.0, LEFT, 780.0, words.defaults_title)?;
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    text(
        &mut content,
        font,
        10.0,
        LEFT,
        762.0,
        words.defaults_intro[0],
    )?;
    text(
        &mut content,
        font,
        10.0,
        LEFT,
        748.0,
        words.defaults_intro[1],
    )?;
    content.restore_state();
    caption(&mut content, font, 706.0, words.defaults_captions[0])?;
    band(&mut content, None, 648.0)?;
    caption(&mut content, font, 632.0, words.defaults_captions[1])?;
    ramp(&mut content, None, 584.0)?;
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    text(&mut content, font, 9.0, LEFT, 550.0, words.group_note)?;
    content.restore_state();

    let mut page = Page::a4();
    page.content = content.into_bytes();
    page.default_rgb = Some(rgb.clone());
    page.default_gray = Some(gray.clone());
    page.group = Some(PageGroup::new(blended).isolated());
    Ok(page)
}

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("calibrated")));
    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 ordinary = doc.add_color_space(ColorSpace::CalRgb(
        CalRgb::new(WHITE).gamma([2.2, 2.2, 2.2]).primaries(
            [0.4124, 0.2126, 0.0193],
            [0.3576, 0.7152, 0.1192],
            [0.1805, 0.0722, 0.9505],
        ),
    ));
    let wider = doc.add_color_space(
        CalRgb::new(WHITE)
            .gamma([2.2, 2.2, 2.2])
            .primaries(
                [0.5767, 0.2974, 0.0270],
                [0.1856, 0.6273, 0.0707],
                [0.1882, 0.0753, 0.9911],
            )
            .black_point(BLACK),
    );
    let straight = doc.add_color_space(ColorSpace::CalGray(CalGray::new(WHITE).gamma(1.0)));
    let bent = doc.add_color_space(CalGray::new(WHITE).gamma(2.2).black_point(BLACK));

    let mut content = Content::new();
    heading(&mut content, &font, words)?;

    panel_heading(
        &mut content,
        &font,
        706.0,
        words.panels[0][0],
        words.panels[0][1],
    )?;
    caption(&mut content, &font, 668.0, words.captions[0])?;
    band(&mut content, None, 610.0)?;
    caption(&mut content, &font, 594.0, words.captions[1])?;
    band(&mut content, Some(&ordinary), 536.0)?;
    caption(&mut content, &font, 520.0, words.captions[2])?;
    band(&mut content, Some(&wider), 462.0)?;

    panel_heading(
        &mut content,
        &font,
        420.0,
        words.panels[1][0],
        words.panels[1][1],
    )?;
    caption(&mut content, &font, 382.0, words.captions[3])?;
    ramp(&mut content, None, 334.0)?;
    caption(&mut content, &font, 318.0, words.captions[4])?;
    ramp(&mut content, Some(&straight), 270.0)?;
    caption(&mut content, &font, 254.0, words.captions[5])?;
    ramp(&mut content, Some(&bent), 206.0)?;
    closing(&mut content, &font, words)?;

    let mut page = Page::a4();
    page.content = content.into_bytes();
    doc.add_page(page)?;
    doc.add_page(defaults_page(&font, words, &wider, &bent, &ordinary)?)?;

    let written = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &written)?;
    println!(
        "wrote {out}: {} bytes, {} colours and {STEPS} greys painted three times each",
        written.len(),
        COLORS.len()
    );
    Ok(())
}

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

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

    /// The lines two languages are allowed to write the same way. Every line
    /// here is a heading, a sentence or a caption, and two languages write one
    /// alike only where they spell it alike.
    const SPARED: [&str; 1] = [
        // Written the same way in Portuguese.
        r#""Medido, elevado a 1""#,
    ];

    /// A4's width, and the room the lines that stand over nothing have: they
    /// only have to stay on the paper.
    const PAGE_WIDTH: f64 = 595.276;
    /// See [`PAGE_WIDTH`].
    const PAPER: f64 = PAGE_WIDTH - LEFT;

    #[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 caption longer than the band
    /// it stands over runs past it, and the title and the two lines under it,
    /// which stand over nothing, run off the sheet.
    #[test]
    fn every_language_writes_lines_no_wider_than_the_bands_they_stand_over() {
        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((15.0, words.title, PAPER))
                .chain(words.intro.map(|line| (10.0, line, PAPER)))
                .chain(words.panels.map(|panel| (11.0, panel[0], RUN)))
                .chain(words.panels.map(|panel| (8.0, panel[1], RUN)))
                .chain(words.captions.map(|line| (8.0, line, RUN)))
                .chain(words.closing.map(|line| (9.0, line, RUN)))
                .chain([
                    (15.0, words.defaults_title, PAPER),
                    (9.0, words.group_note, RUN),
                ])
                .chain(words.defaults_intro.map(|line| (10.0, line, PAPER)))
                .chain(words.defaults_captions.map(|line| (8.0, line, RUN)));

            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 is given {room:.1}"
                );
            }
        }
    }
}