write_press_settings.rs

The Rust file of the “Settings Only the Press Reads” example. Swatches each painted under one printing setting and labelled with what it asks: overprinting, the twenty-one shapes of a halftone dot, tone curves, the four ways of converting a colour, and how finely curves are traced.

Rust 681 lines

What This Example Is For

Some settings in a PDF change nothing on a screen. They are there for the printer: whether a colour printed over another hides it or mixes with it, the shape each dot of ink takes as a grey gets darker, how a tone is bent before it reaches the paper. A proofing tool or a check before printing reads them; a screen does not. Here each of those settings is used on a swatch of its own, and each swatch is labelled with what it asks for.

What This Example Shows

  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
//! Shows what an extended graphics state says to the press and to nothing else:
//! overprinting, halftone screens, transfer curves, the rendering intent and
//! black point compensation, and how finely a curve is cut into lines.
//!
//! None of these settings changes what a screen shows. Each swatch on the page
//! is painted under one of them and labelled beside it, so the page reads the
//! same on a screen and tells a press, a proofing tool or a preflight check
//! what to do with each part. The last swatch is painted under the state that
//! puts every setting back as a page begins.
//!
//! The file is written as PDF 2.0: the halftone origin and black point
//! compensation are entries of that version.
//!
//! Every sentence is held in `Words`, once per language, and `HQF_PDF_LANG`
//! picks which set is drawn. The halftone swatches are labelled with the name
//! the file writes for their dot shape, and the colour swatches with the name
//! it writes for their intent or compensation: those are the same in every
//! language.
//!
//! Usage: `cargo run --example write_press_settings -- tmp/press_settings.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_press_settings`

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

use hqf_pdf::content::Content;
use hqf_pdf::{
    BlackPointCompensation, Cmyk, Document, Exponential, ExtGState, Font, FontHandle, Function,
    Halftone, OverprintMode, Page, RenderingIntent, Screen, SpotFunction, TextFlow, Transfer,
    Version,
};

#[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: the
/// one committed for the tests, so that the example runs on any machine.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The left edge everything lines up on.
const X: f64 = 60.0;

/// How wide a heading or a paragraph may run.
const WIDTH: f64 = 475.0;

/// The size of the running text.
const TEXT_SIZE: f64 = 8.0;

/// The size of a swatch's label.
const LABEL_SIZE: f64 = 6.5;

/// How far one swatch stands from the next, left edge to left edge.
const STEP: f64 = 80.0;

/// The dot shapes a screen can grow, each under the name the file writes.
const SPOTS: [(&str, SpotFunction); 21] = [
    ("SimpleDot", SpotFunction::SimpleDot),
    ("InvertedSimpleDot", SpotFunction::InvertedSimpleDot),
    ("DoubleDot", SpotFunction::DoubleDot),
    ("InvertedDoubleDot", SpotFunction::InvertedDoubleDot),
    ("CosineDot", SpotFunction::CosineDot),
    ("Double", SpotFunction::Double),
    ("InvertedDouble", SpotFunction::InvertedDouble),
    ("Line", SpotFunction::Line),
    ("LineX", SpotFunction::LineX),
    ("LineY", SpotFunction::LineY),
    ("Round", SpotFunction::Round),
    ("Ellipse", SpotFunction::Ellipse),
    ("EllipseA", SpotFunction::EllipseA),
    ("InvertedEllipseA", SpotFunction::InvertedEllipseA),
    ("EllipseB", SpotFunction::EllipseB),
    ("EllipseC", SpotFunction::EllipseC),
    ("InvertedEllipseC", SpotFunction::InvertedEllipseC),
    ("Square", SpotFunction::Square),
    ("Cross", SpotFunction::Cross),
    ("Rhomboid", SpotFunction::Rhomboid),
    ("Diamond", SpotFunction::Diamond),
];

/// The four rendering intents, each under the name the file writes.
const INTENTS: [(&str, RenderingIntent); 4] = [
    ("Perceptual", RenderingIntent::Perceptual),
    (
        "RelativeColorimetric",
        RenderingIntent::RelativeColorimetric,
    ),
    ("Saturation", RenderingIntent::Saturation),
    (
        "AbsoluteColorimetric",
        RenderingIntent::AbsoluteColorimetric,
    ),
];

/// The three settings of black point compensation, each under the name the file
/// writes.
const COMPENSATIONS: [(&str, BlackPointCompensation); 3] = [
    ("ON", BlackPointCompensation::On),
    ("OFF", BlackPointCompensation::Off),
    ("Default", BlackPointCompensation::Reader),
];

/// The words the page is written in, one set per language.
///
/// What is not language stays out of it: the halftone and colour swatches are
/// labelled with the names the file writes.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// The paragraph under it.
    intro: &'static str,
    /// The heading above the overprint swatches.
    overprint: &'static str,
    /// The label under each overprint swatch, in the order they are painted.
    overprint_labels: [&'static str; 3],
    /// The heading above the halftone swatches.
    screens: &'static str,
    /// The label of the swatch screened ink by ink.
    per_ink: &'static str,
    /// The label of the swatch whose screen is precise and moved.
    accurate: &'static str,
    /// The heading above the transfer swatches.
    transfer: &'static str,
    /// The label under each transfer swatch, in the order they are painted.
    transfer_labels: [&'static str; 3],
    /// The heading above the colour swatches.
    color: &'static str,
    /// The heading above the path swatches.
    paths: &'static str,
    /// The label under each path swatch, in the order they are painted.
    path_labels: [&'static str; 4],
}

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: "What a graphics state tells the press",
    intro: "None of these settings changes what a screen shows. Each swatch is painted under one \
of them and labelled with what it asks: a press, a proofing tool or a preflight check reads the \
rest.",
    overprint: "Overprinting: a yellow square over a cyan bar, the cyan left in place under it.",
    overprint_labels: [
        "fill overprints, zero keeps",
        "all overprints, zero erases",
        "only the stroke overprints",
    ],
    screens: "Halftone screens: the shape each dot grows into as the grey darkens.",
    per_ink: "one screen per ink",
    accurate: "precise, moved",
    transfer: "Transfer curves: the tone laid down bent away from the tone asked for.",
    transfer_labels: [
        "one curve, every ink",
        "one curve per ink",
        "the page’s own curve",
    ],
    color: "Rendering intents and black point compensation, read where a colour is converted.",
    paths: "How finely curves and shadings are approximated, and how a thin stroke is snapped.",
    path_labels: [
        "coarse flatness",
        "smooth shadings",
        "stroke adjustment",
        "everything reset",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Ce qu’un état graphique dit à l’imprimeur",
    intro: "Aucun de ces réglages ne change l’affichage à l’écran. Chaque pavé est peint \
sous l’un d’eux, avec à côté ce qu’il demande : le reste est lu par la presse, l’outil \
d’épreuvage ou le contrôle prépresse.",
    overprint: "Surimpression : un carré jaune sur une barre cyan, qui reste en place dessous.",
    overprint_labels: [
        "fond en surimpression, zéro gardé",
        "tout en surimpression, zéro effacé",
        "contour seul en surimpression",
    ],
    screens: "Trames : la forme que prend chaque point quand le gris fonce.",
    per_ink: "une trame par encre",
    accurate: "précise, décalée",
    transfer: "Courbes de transfert : le ton déposé s’écarte du ton demandé.",
    transfer_labels: [
        "une courbe commune",
        "une courbe par encre",
        "la courbe de la page",
    ],
    color: "Intentions de rendu et compensation du point noir, lues à la conversion des couleurs.",
    paths: "La finesse d’approximation des courbes et des dégradés, et le calage d’un trait fin.",
    path_labels: [
        "découpage grossier",
        "dégradés lissés",
        "trait calé",
        "tout remis à zéro",
    ],
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Wat een grafische status de pers vertelt",
    intro: "Geen van deze instellingen verandert wat een scherm toont. Elk staal wordt onder een ervan geschilderd en heeft als label wat het vraagt: een pers, een proefhulpmiddel of een preflightcontrole leest de rest.",
    overprint: "Overdrukken: een geel vierkant over een cyaan balk; het cyaan eronder blijft staan.",
    overprint_labels: [
        "vulling drukt over, nul behoudt",
        "alles drukt over, nul wist",
        "alleen de lijn drukt over",
    ],
    screens: "Rasters: de vorm waartoe elk punt groeit naarmate het grijs donkerder wordt.",
    per_ink: "één raster per inkt",
    accurate: "precies, verschoven",
    transfer: "Overdrachtscurven: de neergelegde toon wijkt af van de gevraagde toon.",
    transfer_labels: ["één curve voor alles", "één curve per inkt", "paginacurve"],
    color: "Weergave-intenties en zwartpuntcompensatie, gelezen waar een kleur wordt omgezet.",
    paths: "Hoe fijn curven en arceringen benaderd worden, en hoe een dunne lijn wordt uitgelijnd.",
    path_labels: [
        "grove vlakheid",
        "gladde arceringen",
        "lijnaanpassing",
        "alles teruggezet",
    ],
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "O que um estado gráfico diz à gráfica",
    intro: "Nenhuma destas definições muda o que um ecrã mostra. Cada amostra é pintada sob uma delas e leva escrito o que pede: uma máquina de impressão, uma ferramenta de provas ou uma verificação prévia leem o resto.",
    overprint: "Sobreimpressão: um quadrado amarelo sobre uma barra ciano, que fica por baixo.",
    overprint_labels: [
        "preenchimento sobreimprime, zero mantém",
        "tudo sobreimprime, zero apaga",
        "só o traço sobreimprime",
    ],
    screens: "Retículas: a forma em que cresce cada ponto à medida que o cinzento escurece.",
    per_ink: "uma retícula por tinta",
    accurate: "precisa, deslocada",
    transfer: "Curvas de transferência: o tom impresso afasta-se do tom pedido.",
    transfer_labels: ["a mesma curva", "uma curva por tinta", "a curva da página"],
    color: "Intenções de reprodução e compensação do ponto preto, lidas onde uma cor é convertida.",
    paths: "Com que finura se aproximam curvas e sombreados, e como se ajusta um traço fino.",
    path_labels: [
        "planura grosseira",
        "sombreados suaves",
        "ajuste de traço",
        "tudo reposto",
    ],
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Ciò che uno stato grafico dice alla macchina da stampa",
    intro: "Nessuna di queste impostazioni cambia ciò che mostra uno schermo. Ogni campione è dipinto sotto una di esse e porta scritto ciò che chiede: una macchina da stampa, uno strumento di prova o un controllo preliminare leggono il resto.",
    overprint: "Sovrastampa: un quadrato giallo su una barra ciano, che resta sotto.",
    overprint_labels: [
        "il riempimento sovrastampa, zero conserva",
        "tutto sovrastampa, zero cancella",
        "solo il tratto sovrastampa",
    ],
    screens: "Retini: la forma in cui cresce ogni punto man mano che il grigio scurisce.",
    per_ink: "un retino per colore",
    accurate: "preciso, spostato",
    transfer: "Curve di trasferimento: il tono steso si discosta dal tono chiesto.",
    transfer_labels: [
        "la stessa curva",
        "una per inchiostro",
        "la curva della pagina",
    ],
    color: "Intenti di rendering e compensazione del punto nero, letti dove si converte un colore.",
    paths: "Con quale finezza si approssimano curve e sfumature, e come si aggancia un tratto sottile.",
    path_labels: [
        "planarità grossolana",
        "sfumature morbide",
        "regolazione del tratto",
        "tutto azzerato",
    ],
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Lo que un estado gráfico dice a la imprenta",
    intro: "Ninguno de estos ajustes cambia lo que muestra una pantalla. Cada muestra se pinta bajo uno de ellos y lleva escrito lo que pide: una prensa, una herramienta de pruebas o un control previo leen el resto.",
    overprint: "Sobreimpresión: un cuadrado amarillo sobre una barra cian, que se conserva debajo.",
    overprint_labels: [
        "el relleno sobreimprime, cero conserva",
        "todo sobreimprime, cero borra",
        "solo el trazo sobreimprime",
    ],
    screens: "Tramas de semitono: la forma en que crece cada punto al oscurecerse el gris.",
    per_ink: "una trama por tinta",
    accurate: "precisa, desplazada",
    transfer: "Curvas de transferencia: el tono impreso se aparta del tono pedido.",
    transfer_labels: [
        "la misma curva",
        "una curva por tinta",
        "la curva de la página",
    ],
    color: "Intenciones de reproducción y compensación del punto negro, leídas donde se convierte un color.",
    paths: "Con qué finura se aproximan curvas y sombreados, y cómo se ajusta un trazo fino.",
    path_labels: [
        "planitud gruesa",
        "sombreados suaves",
        "ajuste del trazo",
        "todo restablecido",
    ],
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Was ein Grafikzustand der Druckmaschine sagt",
    intro: "Keine dieser Einstellungen ändert, was ein Bildschirm zeigt. Jedes Farbfeld wird unter einer davon gemalt und mit dem beschriftet, was sie verlangt: Den Rest liest eine Druckmaschine, ein Proofwerkzeug oder eine Preflight-Prüfung.",
    overprint: "Überdrucken: ein gelbes Quadrat über einem Cyanbalken, das Cyan bleibt darunter stehen.",
    overprint_labels: [
        "Fläche überdruckt, null bleibt",
        "alles überdruckt, null löscht",
        "nur der Strich überdruckt",
    ],
    screens: "Rasterungen: die Form, zu der jeder Punkt wächst, wenn das Grau dunkler wird.",
    per_ink: "ein Raster je Farbe",
    accurate: "präzise, verschoben",
    transfer: "Übertragungskurven: der aufgetragene Ton, weg vom verlangten gebogen.",
    transfer_labels: [
        "eine Kurve, alle Farben",
        "eine Kurve je Farbe",
        "Kurve der Seite",
    ],
    color: "Wiedergabeabsichten und Tiefenkompensierung, gelesen, wo eine Farbe umgerechnet wird.",
    paths: "Wie fein Kurven und Schattierungen angenähert werden und wie ein dünner Strich eingerastet wird.",
    path_labels: [
        "grobe Glättung",
        "weiche Schattierungen",
        "Strichanpassung",
        "alles zurückgesetzt",
    ],
};

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

/// Sets `text` from `(left, top)`, broken into lines `width` wide, at `size`.
fn paragraph(
    c: &mut Content,
    font: &FontHandle,
    size: f64,
    left: f64,
    top: f64,
    width: f64,
    text: &str,
) -> Result<(), hqf_pdf::Error> {
    let flow = TextFlow::new(font, size);
    let lines = flow.break_lines(text, width);
    c.begin_text();
    flow.draw(c, &lines, left, top, width)?;
    c.end_text();
    Ok(())
}

/// Paints a swatch of `color` at `(left, bottom)` under `state`, and labels it
/// underneath.
fn swatch(
    doc: &mut Document,
    c: &mut Content,
    font: &FontHandle,
    at: (f64, f64),
    state: ExtGState,
    color: Cmyk,
    label: &str,
) -> Result<(), hqf_pdf::Error> {
    let (left, bottom) = at;
    let state = doc.add_ext_gstate(state);
    c.save_state().set_ext_gstate(&state).set_fill(color)?;
    c.rect(left, bottom, 70.0, 26.0)?.fill();
    c.restore_state();
    paragraph(c, font, LABEL_SIZE, left, bottom - 8.0, STEP - 4.0, label)
}

/// A curve that lifts the middle tones: the input raised to the power
/// `exponent`.
fn curve(exponent: f64) -> Function {
    Function::from(Exponential::new([0.0, 1.0], exponent))
}

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

#[allow(
    clippy::too_many_lines,
    reason = "the page is one list of swatches, read from top to bottom"
)]
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("press_settings")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_version(Version::V2_0);
    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    let grey = Cmyk::new(0.0, 0.0, 0.0, 0.5);

    let mut c = Content::new();
    paragraph(&mut c, &font, 14.0, X, 790.0, WIDTH, words.title)?;
    paragraph(&mut c, &font, TEXT_SIZE, X, 768.0, WIDTH, words.intro)?;

    // Overprinting: the cyan bar is painted plainly, and the yellow square over
    // it under each state in turn.
    paragraph(&mut c, &font, TEXT_SIZE, X, 730.0, WIDTH, words.overprint)?;
    let overprints = [
        ExtGState::new()
            .fill_overprint(true)
            .overprint_mode(OverprintMode::KeepZero),
        ExtGState::new()
            .overprint(true)
            .overprint_mode(OverprintMode::EraseZero),
        ExtGState::new()
            .stroke_overprint(true)
            .fill_overprint(false),
    ];
    let mut left = X;
    for (state, label) in overprints.into_iter().zip(words.overprint_labels) {
        c.set_fill(Cmyk::new(1.0, 0.0, 0.0, 0.0))?
            .rect(left, 686.0, 140.0, 20.0)?
            .fill();
        let state = doc.add_ext_gstate(state);
        c.save_state()
            .set_ext_gstate(&state)
            .set_fill(Cmyk::new(0.0, 0.0, 1.0, 0.0))?
            .set_stroke(Cmyk::new(0.0, 0.0, 1.0, 0.0))?
            .set_line_width(3.0)?;
        c.rect(left + 30.0, 676.0, 40.0, 40.0)?.fill_and_stroke();
        c.restore_state();
        paragraph(&mut c, &font, LABEL_SIZE, left, 666.0, 150.0, label)?;
        left += 160.0;
    }

    // Halftone screens: one swatch per dot shape, six to a row, then the two
    // that screen ink by ink and precisely.
    paragraph(&mut c, &font, TEXT_SIZE, X, 640.0, WIDTH, words.screens)?;
    let mut spots: Vec<(ExtGState, &str)> = SPOTS
        .iter()
        .map(|(name, spot)| {
            (
                ExtGState::new().halftone(Halftone::Every(Screen::new(60.0, 45.0, *spot))),
                *name,
            )
        })
        .collect();
    spots.push((
        ExtGState::new().halftone(Halftone::PerInk {
            inks: vec![
                (
                    "Cyan".to_owned(),
                    Screen::new(60.0, 15.0, SpotFunction::Round),
                ),
                (
                    "Magenta".to_owned(),
                    Screen::new(60.0, 75.0, SpotFunction::Round),
                ),
                (
                    "Yellow".to_owned(),
                    Screen::new(60.0, 0.0, SpotFunction::Round),
                ),
            ],
            default: Screen::new(60.0, 45.0, SpotFunction::Ellipse),
        }),
        words.per_ink,
    ));
    spots.push((
        ExtGState::new()
            .halftone(Halftone::Every(
                Screen::new(150.0, 45.0, SpotFunction::EllipseC).accurate(true),
            ))
            .halftone_origin(X, 400.0),
        words.accurate,
    ));
    let mut bottom = 598.0;
    for row in spots.chunks(6) {
        let mut left = X;
        for (state, label) in row {
            swatch(
                &mut doc,
                &mut c,
                &font,
                (left, bottom),
                state.clone(),
                grey,
                label,
            )?;
            left += STEP;
        }
        bottom -= 46.0;
    }

    // Transfer curves.
    paragraph(&mut c, &font, TEXT_SIZE, X, 420.0, WIDTH, words.transfer)?;
    let transfers = [
        Transfer::Every(curve(0.6)),
        Transfer::PerInk(Box::new([curve(0.8), curve(0.9), curve(1.0), curve(1.2)])),
        Transfer::Page,
    ];
    let mut left = X;
    for (transfer, label) in transfers.into_iter().zip(words.transfer_labels) {
        swatch(
            &mut doc,
            &mut c,
            &font,
            (left, 378.0),
            ExtGState::new().transfer(transfer),
            Cmyk::new(0.2, 0.5, 0.0, 0.1),
            label,
        )?;
        left += STEP;
    }

    // Rendering intents and black point compensation.
    paragraph(&mut c, &font, TEXT_SIZE, X, 340.0, WIDTH, words.color)?;
    let mut left = X;
    for (label, intent) in INTENTS {
        swatch(
            &mut doc,
            &mut c,
            &font,
            (left, 298.0),
            ExtGState::new().rendering_intent(intent),
            Cmyk::new(0.0, 0.8, 0.9, 0.0),
            label,
        )?;
        left += STEP;
    }
    let mut left = X;
    for (label, compensation) in COMPENSATIONS {
        swatch(
            &mut doc,
            &mut c,
            &font,
            (left, 252.0),
            ExtGState::new().black_point_compensation(compensation),
            Cmyk::new(0.6, 0.0, 0.3, 0.7),
            label,
        )?;
        left += STEP;
    }

    // How curves and shadings are approximated, and how a thin stroke is
    // snapped: four rings, the last under the state that puts everything back.
    paragraph(&mut c, &font, TEXT_SIZE, X, 214.0, WIDTH, words.paths)?;
    let rings = [
        ExtGState::new().flatness(20.0),
        ExtGState::new().smoothness(0.01),
        ExtGState::new().stroke_adjustment(true),
        ExtGState::initial(),
    ];
    let mut left = X;
    for (state, label) in rings.into_iter().zip(words.path_labels) {
        let state = doc.add_ext_gstate(state);
        c.save_state()
            .set_ext_gstate(&state)
            .set_stroke(Cmyk::new(0.0, 0.0, 0.0, 1.0))?
            .set_line_width(0.3)?;
        c.circle(left + 35.0, 172.0, 22.0)?.stroke();
        c.restore_state();
        paragraph(&mut c, &font, LABEL_SIZE, left, 140.0, STEP - 4.0, label)?;
        left += STEP;
    }

    let mut page = Page::a4();
    page.content = c.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", bytes.len());
    Ok(())
}

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

    use super::{LABEL_SIZE, STEP, TEXT_SIZE, WIDTH, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way.
    const SPARED: [&str; 1] = [
        // Written the same way in Portuguese.
        r#""sombreados suaves""#,
    ];

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

    /// A heading that wrapped would set its second line over the swatches under
    /// it, and a label that wrapped would run into the next row.
    #[test]
    fn every_heading_and_every_label_takes_one_line() {
        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 handle = doc.add_font(font);
        let text = TextFlow::new(&handle, TEXT_SIZE);
        let label = TextFlow::new(&handle, LABEL_SIZE);

        for (_, words) in WORDS {
            for line in [
                words.overprint,
                words.screens,
                words.transfer,
                words.color,
                words.paths,
            ] {
                assert_eq!(text.break_lines(line, WIDTH).len(), 1, "{line:?} wraps");
            }
            for line in words.overprint_labels {
                assert_eq!(label.break_lines(line, 150.0).len(), 1, "{line:?} wraps");
            }
            let short = words
                .transfer_labels
                .iter()
                .chain(&words.path_labels)
                .chain([&words.per_ink, &words.accurate]);
            for line in short {
                assert_eq!(
                    label.break_lines(line, STEP - 4.0).len(),
                    1,
                    "{line:?} wraps"
                );
            }
            assert!(
                text.break_lines(words.intro, WIDTH).len() <= 3,
                "the introduction runs past three lines"
            );
        }
    }
}