write_gradient.rs

Die Rust-Datei des Beispiels „Verläufe in einer Linie, in einem Kreis und aus einer Funktion gelesen“. Fünf Felder: ein Kopfbereich, der ausblendet, dieselbe Ausblendung diagonal, ein Leuchten über seinen eigenen Kreis hinaus fortgesetzt, sodass sich die Ecken füllen, eine Mischung, die über eine dritte Farbe geht, und ein Schachbrett, dessen Farbe daraus berechnet wird, wo jeder Punkt steht, nach rechts röter und nach oben grüner.

Rust 683 Zeilen

Wofür dieses Beispiel da ist

Ein Verlauf ist der günstigste Weg, eine flache Seite so aussehen zu lassen, als hätte jemand sie gestaltet: ein Kopfbereich, der ausblendet, ein Balken mit etwas Tiefe, ein Feld, das nicht einfach ein einfarbiges Rechteck ist. Er ist auch das, was am häufigsten mit einem Bild nachgeahmt wird, und die Nachahmung fällt auf, sobald die Seite gedruckt oder genau betrachtet wird.

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
//! Paints axial, radial and function-based gradients, each into a clipped box.
//!
//! Six panels: a horizontal two-colour gradient, a diagonal one, a radial one
//! whose outer colour is extended to fill the corners, a three-stop gradient
//! built from a stitched function, a checkerboard whose colour is read from a
//! calculation of both coordinates of the point, the reader asked to filter its
//! sudden colour steps against aliasing, and a radial gradient extended both
//! ways that holds itself to its box. Each is added to the document once; the
//! first five are painted into a rectangle the page clips to, the last is
//! painted with no clip at all.
//!
//! The second page says the same kind of gradient in the inks a press lays
//! down: from one process colour to another, a radial one in the same inks, one
//! ink of the press's own from none to full, and two such inks at once, one
//! fading as the other rises. Under them, a gradient said in CIE L*a*b*, a
//! space the document holds, runs through three colours set at three places
//! along it. Each label counts the numbers a point of its gradient is made of,
//! read from the space it is said in.
//!
//! The title and the eleven labels are held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn.
//!
//! Usage: `cargo run --example write_gradient -- tmp/gradient.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_gradient -- tmp/degrade.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::shading::FunctionBased;
use hqf_pdf::{
    Axial, Calculation, Cmyk, DeviceN, DeviceSpace, Document, Exponential, ExtendEnds, Font,
    FontHandle, Lab, Op, Page, Radial, Rect, Rgb, Separation, Shading, ShadingHandle, ShadingSpace,
    Stitching,
};

#[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 words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The title across the top of the page.
    title: &'static str,
    /// The label under each of the six panels.
    horizontal: &'static str,
    diagonal: &'static str,
    radial: &'static str,
    three_stops: &'static str,
    checkerboard: &'static str,
    bounded: &'static str,
    /// The second page's title.
    inks_title: &'static str,
    /// The label under each of the second page's four panels; `{n}` stands for
    /// the count of numbers a point of the gradient is made of.
    inks: [&'static str; 4],
    /// The label under the gradient said in L*a*b*; `{n}` as in `inks`.
    lab: &'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: "Gradients, and a colour read from a function",
    horizontal: "Axial, two colours",
    diagonal: "Axial, on the diagonal",
    radial: "Radial, outer extended",
    three_stops: "Axial, three stops",
    checkerboard: "Function-based: a checkerboard on x and y at once, anti-aliasing asked for",
    bounded: "Radial, held to its own box",
    inks_title: "The same gradients, in the inks a press lays down",
    inks: [
        "Axial, four inks: {n} numbers a point",
        "Radial, four inks, outer extended",
        "One ink of its own: {n} number a point",
        "Two inks at once: {n} numbers a point",
    ],
    lab: "L*a*b*, three stops: {n} numbers a point",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Dégradés, et une couleur lue dans une fonction",
    horizontal: "Linéaire, deux couleurs",
    diagonal: "Linéaire, en diagonale",
    radial: "Radial, couleur extérieure prolongée",
    three_stops: "Linéaire, trois couleurs",
    checkerboard: "Par fonction : un damier en largeur et en hauteur à la fois, anticrénelage \
demandé",
    bounded: "Radial, limité à sa propre boîte",
    inks_title: "Les mêmes dégradés, dans les encres d’imprimerie",
    inks: [
        "Linéaire, quatre encres : {n} nombres par point",
        "Radial, quatre encres, extérieur prolongé",
        "Un ton direct : {n} nombre par point",
        "Deux encres à la fois : {n} nombres par point",
    ],
    lab: "L*a*b*, trois couleurs : {n} nombres par point",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Verlopen, en een kleur gelezen uit een functie",
    horizontal: "Axiaal, twee kleuren",
    diagonal: "Axiaal, op de diagonaal",
    radial: "Radiaal, buitenkant doorgetrokken",
    three_stops: "Axiaal, drie stops",
    checkerboard: "Op functie gebaseerd: een dambord in x en y tegelijk, met anti-aliasing gevraagd",
    bounded: "Radiaal, binnen zijn eigen kader gehouden",
    inks_title: "Dezelfde verlopen, in de inkten die een pers neerlegt",
    inks: [
        "Axiaal, vier inkten: {n} getallen per punt",
        "Radiaal, vier inkten, buitenkant doorgetrokken",
        "Eén eigen inkt: {n} getal per punt",
        "Twee inkten tegelijk: {n} getallen per punt",
    ],
    lab: "L*a*b*, drie stops: {n} getallen per punt",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Degradés, e uma cor lida de uma função",
    horizontal: "Axial, duas cores",
    diagonal: "Axial, na diagonal",
    radial: "Radial, exterior prolongado",
    three_stops: "Axial, três pontos de cor",
    checkerboard: "Baseado em função: um tabuleiro de xadrez em x e y ao mesmo tempo, com suavização pedida",
    bounded: "Radial, preso à sua caixa",
    inks_title: "Os mesmos degradés, nas tintas que uma gráfica põe",
    inks: [
        "Axial, quatro tintas: {n} números por ponto",
        "Radial, quatro tintas, exterior prolongado",
        "Uma tinta própria: {n} número por ponto",
        "Duas tintas juntas: {n} números por ponto",
    ],
    lab: "L*a*b*, três cores: {n} números por ponto",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Gradienti, e un colore letto da una funzione",
    horizontal: "Assiale, due colori",
    diagonal: "Assiale, in diagonale",
    radial: "Radiale, esterno esteso",
    three_stops: "Assiale, tre arresti",
    checkerboard: "Basato su funzione: una scacchiera in x e y insieme, con antialias richiesto",
    bounded: "Radiale, tenuto nel suo riquadro",
    inks_title: "Gli stessi gradienti, negli inchiostri da stampa",
    inks: [
        "Assiale, quattro inchiostri: {n} numeri per punto",
        "Radiale, quattro inchiostri, esterno esteso",
        "Un inchiostro proprio: {n} numero per punto",
        "Due inchiostri insieme: {n} numeri per punto",
    ],
    lab: "L*a*b*, tre arresti: {n} numeri per punto",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Degradados, y un color leído de una función",
    horizontal: "Axial, dos colores",
    diagonal: "Axial, en diagonal",
    radial: "Radial, exterior prolongado",
    three_stops: "Axial, tres paradas",
    checkerboard: "Basado en función: un damero en x e y a la vez, con suavizado pedido",
    bounded: "Radial, ceñido a su propia caja",
    inks_title: "Los mismos degradados, en tintas de imprenta",
    inks: [
        "Axial, cuatro tintas: {n} números por punto",
        "Radial, cuatro tintas, exterior prolongado",
        "Una tinta propia: {n} número por punto",
        "Dos tintas a la vez: {n} números por punto",
    ],
    lab: "L*a*b*, tres paradas: {n} números por punto",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Verläufe und eine Farbe aus einer Funktion",
    horizontal: "Axial, zwei Farben",
    diagonal: "Axial, auf der Diagonale",
    radial: "Radial, außen verlängert",
    three_stops: "Axial, drei Stufen",
    checkerboard: "Funktionsbasiert: Schachbrett über x und y, mit Kantenglättung",
    bounded: "Radial, auf seinen eigenen Rahmen begrenzt",
    inks_title: "Dieselben Verläufe in Druckfarben",
    inks: [
        "Axial, vier Farben: {n} Zahlen je Punkt",
        "Radial, vier Farben, außen verlängert",
        "Eine eigene Farbe: {n} Zahl je Punkt",
        "Zwei Farben zugleich: {n} Zahlen je Punkt",
    ],
    lab: "L*a*b*, drei Stufen: {n} Zahlen je Punkt",
};

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

/// The width and height of every panel, in points.
const BOX: (f64, f64) = (210.0, 170.0);

/// How many squares the checkerboard is cut into along each of its two axes.
const SQUARES: f64 = 8.0;

/// How much of the colour it lands on a darkened square of the checkerboard
/// keeps.
const SHADED: f64 = 0.45;

/// Paints a gradient into the box at `(x, y)`, sized [`BOX`], and writes a
/// label under it.
fn panel(
    content: &mut Content,
    font: &FontHandle,
    shading: &ShadingHandle,
    x: f64,
    y: f64,
    label: &str,
) -> Result<(), hqf_pdf::Error> {
    content.save_state();
    content.rect(x, y, BOX.0, BOX.1)?.clip().end_path();
    content.draw_shading(shading);
    content.restore_state();

    self::label(content, font, x, y - 15.0, label)
}

/// Writes `text` at ten points with its baseline at `(x, y)`.
fn label(
    content: &mut Content,
    font: &FontHandle,
    x: f64,
    y: f64,
    text: &str,
) -> Result<(), hqf_pdf::Error> {
    content.begin_text();
    content.set_font(font, 10.0)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(text));
    content.end_text();
    Ok(())
}

/// The gradient that paints a checkerboard into the box at `(x, y)`, sized
/// [`BOX`], its colour read from a calculation of both coordinates of the point
/// at once: red grows across the box, green grows up it, and every other square
/// of the [`SQUARES`] by [`SQUARES`] board keeps only [`SHADED`] of the colour
/// it lands on. The reader is asked to filter the sudden steps between squares
/// against aliasing.
fn checkerboard(x: f64, y: f64) -> Result<Shading, hqf_pdf::Error> {
    Ok(Shading::from(
        FunctionBased::new(
            [[0.0, 1.0], [0.0, 1.0]],
            [BOX.0, 0.0, 0.0, BOX.1, x, y],
            DeviceSpace::Rgb,
            Calculation::new(
                [[0.0, 1.0], [0.0, 1.0]],
                [[0.0, 1.0]; 3],
                vec![
                    Op::Integer(2),
                    Op::Copy,
                    Op::Real(SQUARES),
                    Op::Multiply,
                    Op::Floor,
                    Op::Exchange,
                    Op::Real(SQUARES),
                    Op::Multiply,
                    Op::Floor,
                    Op::Add,
                    Op::ToInteger,
                    Op::Integer(2),
                    Op::Modulo,
                    Op::Integer(0),
                    Op::NotEqual,
                    Op::Integer(3),
                    Op::Integer(1),
                    Op::Roll,
                    Op::Real(0.2),
                    Op::Integer(4),
                    Op::Integer(3),
                    Op::Roll,
                    Op::If(vec![
                        Op::Real(SHADED),
                        Op::Multiply,
                        Op::Integer(3),
                        Op::Integer(1),
                        Op::Roll,
                        Op::Real(SHADED),
                        Op::Multiply,
                        Op::Integer(3),
                        Op::Integer(1),
                        Op::Roll,
                        Op::Real(SHADED),
                        Op::Multiply,
                        Op::Integer(3),
                        Op::Integer(1),
                        Op::Roll,
                    ]),
                ],
            ),
        )?
        .anti_alias(true),
    ))
}

/// A stitched function of three stops: red to green over the first half, green
/// to blue over the second.
fn three_stops() -> Stitching {
    Stitching::new(
        [0.0, 1.0],
        vec![
            Exponential::new([0.0, 1.0], 1.0)
                .endpoints(vec![0.85, 0.12, 0.12], vec![0.12, 0.6, 0.2])
                .into(),
            Exponential::new([0.0, 1.0], 1.0)
                .endpoints(vec![0.12, 0.6, 0.2], vec![0.12, 0.2, 0.8])
                .into(),
        ],
        vec![0.5],
        vec![[0.0, 1.0], [0.0, 1.0]],
    )
}

/// A radial gradient in the box whose lower-left corner is `(x, y)`, extended
/// both ways so it would cover the whole page, and held to the box by its own
/// bounding box.
fn held_to_its_box(x: f64, y: f64) -> Shading {
    Shading::from(
        Radial::rgb(
            (x + BOX.0 / 2.0, y + BOX.1 / 2.0, 10.0),
            (x + BOX.0 / 2.0, y + BOX.1 / 2.0, BOX.1 / 2.0),
            Rgb::new(0.95, 0.75, 0.2),
            Rgb::new(0.55, 0.1, 0.35),
        )
        .extend(ExtendEnds {
            before: true,
            after: true,
        })
        .bounding_box(Rect::new(x, y, BOX.0, BOX.1)),
    )
}

/// What one point of Corporate Blue lays down on each process plate, 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 white the L*a*b* gradient is measured against: daylight at 5000 K, as
/// CIE XYZ.
const D50: [f64; 3] = [0.9642, 1.0, 0.8249];

/// The three colours of the L*a*b* gradient and where along it each one is
/// reached: a deep blue, a near white and a warm orange, as lightness, then
/// green to red, then blue to yellow.
const LAB_STOPS: [(f64, [f64; 3]); 3] = [
    (0.0, [30.0, 20.0, -60.0]),
    (0.5, [95.0, 0.0, 0.0]),
    (1.0, [65.0, 45.0, 70.0]),
];

/// The program that shows the two inks together where their plates are not to
/// hand: each process plate takes the first ink's share at the first tint plus
/// the second ink's 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.
fn mix_two_inks() -> Calculation {
    let mut body = Vec::new();
    for (reach, (first, second)) in (1..).zip(BLUE.iter().zip(&GOLD)) {
        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)
}

/// A label whose `{n}` is the count of numbers a colour in `space` is made of.
fn counted(label: &str, space: &ShadingSpace) -> String {
    label.replace("{n}", &space.components().to_string())
}

/// Draws the second page: the gradients said in the inks a press lays down.
fn inks_page(
    doc: &mut Document,
    font: &FontHandle,
    words: &Words,
) -> Result<Content, hqf_pdf::Error> {
    let (left, right, top, bottom, lowest) = (70.0, 315.0, 560.0, 330.0, 100.0);

    let process = ShadingSpace::Device(DeviceSpace::Cmyk);
    let axial = doc.add_shading(&Shading::from(Axial::cmyk(
        (left, top),
        (left + BOX.0, top),
        Cmyk::new(1.0, 0.0, 0.0, 0.0),
        Cmyk::new(0.0, 1.0, 0.0, 0.0),
    )))?;
    let radial = doc.add_shading(&Shading::from(
        Radial::cmyk(
            (right + BOX.0 / 2.0, top + BOX.1 / 2.0, 0.0),
            (right + BOX.0 / 2.0, top + BOX.1 / 2.0, BOX.0 / 2.0),
            Cmyk::new(0.0, 0.0, 1.0, 0.0),
            Cmyk::new(0.0, 0.9, 0.9, 0.2),
        )
        .extend(ExtendEnds {
            before: false,
            after: true,
        }),
    ))?;

    let one = ShadingSpace::Separation(Separation::ink(
        "Corporate Blue",
        Cmyk::new(BLUE[0], BLUE[1], BLUE[2], BLUE[3]),
    ));
    let one_label = counted(words.inks[2], &one);
    let tint = doc.add_shading(&Shading::from(Axial::new(
        (left, bottom),
        (left + BOX.0, bottom),
        one,
        Exponential::new([0.0, 1.0], 1.0),
    )?))?;

    let two = ShadingSpace::DeviceN(DeviceN::new(
        vec!["Corporate Blue".to_owned(), "Corporate Gold".to_owned()],
        DeviceSpace::Cmyk,
        mix_two_inks(),
    )?);
    let two_label = counted(words.inks[3], &two);
    let pair = doc.add_shading(&Shading::from(Axial::new(
        (right, bottom),
        (right + BOX.0, bottom),
        two,
        Exponential::new([0.0, 1.0], 1.0).endpoints([1.0, 0.0], [0.0, 1.0]),
    )?))?;

    let measured = ShadingSpace::from(doc.add_color_space(Lab::new(D50)));
    let lab_label = counted(words.lab, &measured);
    let lab = doc.add_shading(&Shading::from(Axial::through_stops(
        (left, lowest),
        (left + BOX.0, lowest),
        measured,
        LAB_STOPS,
    )?))?;

    let mut content = Content::new();
    content.begin_text();
    content.set_font(font, 18.0)?;
    content.text_origin(left, 770.0)?;
    content.show_glyphs(&font.glyphs(words.inks_title));
    content.end_text();

    panel(
        &mut content,
        font,
        &axial,
        left,
        top,
        &counted(words.inks[0], &process),
    )?;
    panel(&mut content, font, &radial, right, top, words.inks[1])?;
    panel(&mut content, font, &tint, left, bottom, &one_label)?;
    panel(&mut content, font, &pair, right, bottom, &two_label)?;
    panel(&mut content, font, &lab, left, lowest, &lab_label)?;
    Ok(content)
}

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("gradient")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

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

    // Left column x, right column x, then the foot of each of the three rows.
    let (left, right, top, middle, bottom) = (70.0, 315.0, 560.0, 320.0, 100.0);

    // A horizontal two-colour gradient across the top-left box.
    let horizontal = doc.add_shading(&Shading::from(Axial::rgb(
        (left, top),
        (left + BOX.0, top),
        Rgb::new(0.85, 0.12, 0.12),
        Rgb::new(0.12, 0.2, 0.8),
    )))?;

    // A diagonal two-colour gradient across the top-right box.
    let diagonal = doc.add_shading(&Shading::from(Axial::rgb(
        (right, middle + BOX.1),
        (right + BOX.0, top + BOX.1),
        Rgb::new(0.95, 0.8, 0.1),
        Rgb::new(0.1, 0.55, 0.2),
    )))?;

    // A radial gradient in the middle-left box, its outer colour extended so it
    // reaches the corners.
    let radial = doc.add_shading(&Shading::from(
        Radial::rgb(
            (left + BOX.0 / 2.0, middle + BOX.1 / 2.0, 0.0),
            (left + BOX.0 / 2.0, middle + BOX.1 / 2.0, BOX.0 / 2.0),
            Rgb::new(1.0, 1.0, 1.0),
            Rgb::new(0.1, 0.15, 0.45),
        )
        .extend(ExtendEnds {
            before: false,
            after: true,
        }),
    ))?;

    // A three-stop gradient in the middle-right box.
    let rainbow = doc.add_shading(&Shading::from(Axial::new(
        (right, middle),
        (right + BOX.0, middle),
        DeviceSpace::Rgb,
        three_stops(),
    )?))?;

    // A checkerboard across the bottom-left box.
    let board = doc.add_shading(&checkerboard(left, bottom)?)?;

    let held = doc.add_shading(&held_to_its_box(right, bottom))?;

    let mut content = Content::new();

    content.begin_text();
    content.set_font(&handle, 18.0)?;
    content.text_origin(left, 770.0)?;
    content.show_glyphs(&handle.glyphs(words.title));
    content.end_text();

    panel(
        &mut content,
        &handle,
        &horizontal,
        left,
        top,
        words.horizontal,
    )?;
    panel(&mut content, &handle, &diagonal, right, top, words.diagonal)?;
    panel(&mut content, &handle, &radial, left, middle, words.radial)?;
    panel(
        &mut content,
        &handle,
        &rainbow,
        right,
        middle,
        words.three_stops,
    )?;
    panel(
        &mut content,
        &handle,
        &board,
        left,
        bottom,
        words.checkerboard,
    )?;

    // No clip: the gradient's bounding box is what keeps it in its panel.
    content.draw_shading(&held);
    label(&mut content, &handle, right, bottom - 30.0, words.bounded)?;

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

    let mut page = Page::a4();
    page.content = inks_page(&mut doc, &handle, words)?.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};

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

    /// The lines two languages are allowed to write the same way, where two
    /// languages spell a word alike. Every word is a word of the language it is
    /// written in.
    const SPARED: [&str; 1] = [
        // Written the same way in Portuguese.
        r#"radial: "Radial, exterior prolongado""#,
    ];

    #[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 label of the second page that ran past its panel would run into the
    /// label of the panel beside it, 35 points further.
    #[test]
    fn every_label_of_the_second_page_stays_under_its_panel() {
        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 = BOX.0 + 30.0;
        for (_, words) in WORDS {
            let title = font.measure(words.inks_title, 18.0);
            assert!(
                title <= 495.0,
                "{:?} needs {title} of 495",
                words.inks_title
            );
            for label in words.inks.into_iter().chain([words.lab]) {
                let label = label.replace("{n}", "4");
                let width = font.measure(&label, 10.0);
                assert!(width <= room, "{label:?} needs {width} of {room}");
            }
        }
    }
}