write_page_group.rs

The Rust file of the “Overlaps Mixed in Linear Light” example. A page that asks for its half-transparent colours to be mixed in linear light: two pairs of overlapping discs, each beside the colour its overlap should take and the one it takes when the request is ignored.

Rust 664 lines

What This Example Is For

A logo has two half-transparent circles that overlap, and the overlap comes out a muddy olive in one program and a clear yellow in another. Nothing is wrong with the colours: each program mixed them its own way, in the numbers as written or as light really adds up, and the file never said which.

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
//! Writes a page that says which colour space its marks are mixed in: every
//! page of the document is a transparency group blended in a calibrated RGB in
//! linear light, isolated from whatever lies behind it.
//!
//! The page shows two pairs of overlapping discs, the second disc of each laid
//! at half opacity over the first. Beside each pair stand two plain squares:
//! the colour the overlap comes to when mixed in linear light, as the page
//! asks, and the colour it comes to when mixed in the numbers as written, which
//! is what a reader that ignores the request shows. Whoever opens the file
//! compares the overlap with the two squares. A paragraph at the foot says what
//! the file writes for the group.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is written in. The colours of the discs and the entries
//! of the group are the same in every language.
//!
//! Usage: `cargo run --example write_page_group -- tmp/page_group.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_page_group --
//! tmp/page_group.fr.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{
    CalRgb, Color, ColorSpace, Document, ExtGState, FontHandle, GStateHandle, Page, PageGroup, Rgb,
    TextFlow,
};

#[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 sets its text in 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")
}

/// How far in from the left and right edges of the sheet the text stands, in
/// points.
const MARGIN: f64 = 56.0;

/// How wide the text runs, in points: the A4 sheet less both margins.
const WIDTH: f64 = 595.0 - 2.0 * MARGIN;

/// Where the top of the first line stands, in points up from the foot of the
/// sheet.
const TOP: f64 = 800.0;

/// The radius of each disc, in points.
const RADIUS: f64 = 56.0;

/// How far the second disc of a pair stands to the right of the first, in
/// points, centre to centre.
const SHIFT: f64 = 72.0;

/// The side of each plain square, in points.
const SWATCH: f64 = 40.0;

/// Where the plain squares stand, in points from the left edge of the sheet.
const SWATCH_X: f64 = MARGIN + 2.0 * RADIUS + SHIFT + 32.0;

/// Where the caption beside a square starts, in points from the left edge of
/// the sheet.
const CAPTION_X: f64 = SWATCH_X + SWATCH + 12.0;

/// How wide the caption beside a square runs, in points.
const CAPTION_WIDTH: f64 = MARGIN + WIDTH - CAPTION_X;

/// How far one line of the caption beside a square stands below the one above
/// it, in points.
const CAPTION_LEADING: f64 = 12.0;

/// How far the top of the lower square stands below the top of the upper one,
/// in points.
const SWATCH_PITCH: f64 = 56.0;

/// The white point of the space the page is blended in: D65.
const WHITE: [f64; 3] = [0.9505, 1.0, 1.089];

/// The two pairs of discs, each as the colour painted first and the colour laid
/// over it at half opacity.
const PAIRS: [(Rgb, Rgb); 2] = [
    (Rgb::new(0.9, 0.1, 0.1), Rgb::new(0.1, 0.8, 0.1)),
    (Rgb::new(0.95, 0.8, 0.1), Rgb::new(0.1, 0.2, 0.85)),
];

/// The entries of the group every page writes, the same in every language.
const GROUP_ENTRIES: &str =
    "/Type /Group /S /Transparency /CS [/CalRGB << /Gamma [1 1 1] … >>] /I true";

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// What the page shows, set large at its top.
    title: &'static str,
    /// The paragraph saying what mixing two colours means and what the page
    /// asks for.
    intro: &'static str,
    /// The line above each pair of discs, naming its two colours.
    pairs: [&'static str; 2],
    /// The caption beside the square mixed in linear light.
    linear: &'static str,
    /// The caption beside the square mixed in the numbers as written.
    plain: &'static str,
    /// The heading of the paragraph at the foot of the page.
    file_title: &'static str,
    /// The paragraph at the foot of the page, saying what the group writes.
    file_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 space a page mixes its colours in",
    intro: "Where a half-transparent colour lies over another, the software showing the page \
works out the colour of the overlap, and the result depends on the numbers it works with. \
Mixed in the numbers as written, red and green give a dull olive; mixed in linear light, the \
way light itself adds up, they give a brighter yellow. Every page of this document says which \
colour space its marks are mixed in: a calibrated RGB in linear light. Software that honours \
the request gives each overlap the same colour, on screen as on paper, whatever space each \
mark was painted in.",
    pairs: [
        "Red, then green at half opacity",
        "Yellow, then blue at half opacity",
    ],
    linear: "Mixed in linear light, as every page here asks: the overlap in software that \
honours the request.",
    plain: "Mixed in the numbers as written: the overlap in software that ignores it.",
    file_title: "What the file writes",
    file_note: "Each page carries a transparency group. /S /Transparency names it, /CS points \
at the space the mixing is done in, and /I true starts the page from nothing rather than from \
what lies behind it: that changes nothing on a sheet printed alone, and matters once the page \
is placed onto another. The setting holds for every page of the document; the half opacity of \
each green or blue disc comes from its own graphics state, /ca 0.5.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "L’espace où une page mélange ses couleurs",
    intro: "Là où une couleur à demi transparente en recouvre une autre, le logiciel \
qui affiche la page calcule la couleur de la superposition, et le résultat \
dépend des valeurs sur lesquelles il travaille. Mélangés d’après leurs \
valeurs telles qu’écrites, le rouge et le vert donnent un olive terne ; \
mélangés en lumière linéaire, à la manière dont la lumière s’additionne, \
ils donnent un jaune plus lumineux. Chaque page de ce document indique dans \
quel espace de couleurs ses tracés sont mélangés : un RVB calibré en \
lumière linéaire. Un logiciel qui respecte cette demande donne à chaque \
superposition la même couleur, à l’écran comme sur papier, quel que soit \
l’espace dans lequel chaque tracé a été peint.",
    pairs: [
        "Rouge, puis vert à 50 % d’opacité",
        "Jaune, puis bleu à 50 % d’opacité",
    ],
    linear: "Mélange en lumière linéaire, comme le demande chaque page ici : la \
superposition dans un logiciel qui respecte la demande.",
    plain: "Mélange des valeurs telles qu’écrites : la superposition dans un logiciel \
qui l’ignore.",
    file_title: "Ce qu’écrit le fichier",
    file_note: "Chaque page contient un groupe de transparence. /S /Transparency le \
désigne, /CS indique l’espace où se fait le mélange, et /I true fait \
démarrer la page d’un fond vide plutôt que de ce qui se trouve derrière \
elle : cela ne change rien sur une feuille imprimée seule, mais compte \
dès que la page est posée sur une autre. Ce réglage vaut pour toutes \
les pages du document ; l’opacité de 50 % de chaque disque vert ou bleu \
vient de son propre état graphique, /ca 0.5.",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Der Farbraum, in dem eine Seite ihre Farben mischt",
    intro: "Liegt eine halbtransparente Farbe über einer anderen, berechnet die \
Software, die die Seite anzeigt, die Farbe der Überlappung, und das \
Ergebnis hängt davon ab, mit welchen Zahlen sie rechnet. Rechnet sie mit \
den Farbwerten, wie sie in der Datei stehen, ergeben Rot und Grün ein \
trübes Oliv. Mischt sie in linearem Licht, also so, wie sich Licht \
tatsächlich addiert, entsteht ein helleres Gelb. Jede Seite dieses \
Dokuments legt fest, in welchem Farbraum ihre Elemente gemischt werden: in \
einem kalibrierten RGB-Raum mit linearem Licht. Software, die sich nach \
dieser Angabe richtet, zeigt jede Überlappung in derselben Farbe, am \
Bildschirm wie auf Papier, gleich in welchem Farbraum die einzelnen \
Elemente gemalt wurden.",
    pairs: [
        "Rot, darüber Grün mit 50 % Deckkraft",
        "Gelb, darüber Blau mit 50 % Deckkraft",
    ],
    linear: "In linearem Licht gemischt, wie es jede Seite hier verlangt: So erscheint \
die Überlappung in Software, die sich nach der Angabe richtet.",
    plain: "Mit den Farbwerten gerechnet, wie sie in der Datei stehen: So erscheint die \
Überlappung in Software, die die Angabe nicht beachtet.",
    file_title: "Was in der Datei steht",
    file_note: "Jede Seite enthält eine Transparenzgruppe. /S /Transparency weist sie \
als solche aus, /CS verweist auf den Farbraum, in dem gemischt wird, \
und /I true lässt die Seite auf leerem Grund beginnen statt auf dem, \
was darunter liegt: Auf einem einzeln gedruckten Blatt ändert das \
nichts, wichtig wird es, sobald die Seite auf eine andere gelegt wird. \
Die Einstellung gilt für alle Seiten des Dokuments; dass jede grüne \
oder blaue Scheibe zu 50 % deckt, legt ihr eigener Grafikzustand fest: \
/ca 0.5.",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "En qué espacio mezcla la página sus colores",
    intro: "Donde un color semitransparente se superpone a otro, el programa que \
muestra la página calcula el color de la superposición, y el resultado \
depende de los valores con los que trabaja. Si se calcula con los valores \
tal como figuran en el archivo, el rojo y el verde dan un oliva apagado; si \
se mezclan en luz lineal, que es como se suma la luz en la realidad, dan un \
amarillo más vivo. Cada página de este documento indica en qué espacio de \
color se mezclan sus elementos: un RGB calibrado en luz lineal. Un programa \
que respeta esta indicación da a cada superposición el mismo color en \
pantalla y en papel, sea cual sea el espacio en que se pintó cada elemento.",
    pairs: [
        "Rojo y, encima, verde al 50 % de opacidad",
        "Amarillo y, encima, azul al 50 % de opacidad",
    ],
    linear: "Mezcla en luz lineal, como pide cada página de este documento: la \
superposición en un programa que respeta la indicación.",
    plain: "Mezcla con los valores tal como figuran en el archivo: la superposición en \
un programa que no la tiene en cuenta.",
    file_title: "Lo que figura en el archivo",
    file_note: "Cada página contiene un grupo de transparencia. /S /Transparency lo \
identifica, /CS remite al espacio en que se hace la mezcla, y con /I \
true la página parte de un fondo vacío en lugar de lo que haya detrás: \
en una hoja que se imprime sola no cambia nada, pero importa en cuanto \
la página se coloca sobre otra. El ajuste vale para todas las páginas \
del documento; el 50 % de opacidad de cada disco verde o azul procede \
de su propio estado gráfico, /ca 0.5.",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Lo spazio in cui la pagina mescola i colori",
    intro: "Quando un colore semitrasparente si posa su un altro, il programma che \
visualizza la pagina calcola il colore della sovrapposizione, e il \
risultato dipende dai valori su cui lavora. Mescolati con i valori così \
come sono scritti, rosso e verde danno un verde oliva spento; mescolati in \
luce lineare, cioè nel modo in cui la luce si somma davvero, danno un \
giallo più luminoso. Ogni pagina di questo documento indica in quale spazio \
colore si mescolano i suoi elementi: un RGB calibrato in luce lineare. Un \
programma che rispetta l’indicazione dà a ogni sovrapposizione lo stesso \
colore, sullo schermo come sulla carta, qualunque sia lo spazio in cui è \
stato dipinto ciascun elemento.",
    pairs: [
        "Rosso, poi verde con opacità del 50%",
        "Giallo, poi blu con opacità del 50%",
    ],
    linear: "Mescolata in luce lineare, come chiedono tutte le pagine del documento: la \
sovrapposizione in un programma che rispetta l’indicazione.",
    plain: "Mescolata con i valori così come sono scritti: la sovrapposizione in un \
programma che ignora l’indicazione.",
    file_title: "Che cosa contiene il file",
    file_note: "Ogni pagina contiene un gruppo di trasparenza. /S /Transparency lo \
identifica, /CS indica lo spazio in cui si mescolano i colori e /I true \
fa partire la pagina da zero anziché da ciò che le sta dietro: su un \
foglio stampato da solo non cambia nulla, ma conta quando la pagina \
viene collocata sopra un’altra. L’impostazione vale per tutte le pagine \
del documento; l’opacità del 50% di ogni disco verde o blu deriva \
invece dal suo stato grafico, /ca 0.5.",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "O espaço em que uma página mistura as cores",
    intro: "Onde uma cor semitransparente fica por cima de outra, o programa que mostra \
a página calcula a cor da sobreposição, e o resultado depende dos valores \
com que faz as contas. Misturados com os valores tal como estão escritos, o \
vermelho e o verde dão um verde-azeitona baço; misturados em luz linear, \
tal como a própria luz se soma, dão um amarelo mais vivo. Cada página deste \
documento indica em que espaço de cor se misturam os elementos nela \
pintados: um RGB calibrado em luz linear. Um programa que respeite essa \
indicação dá a cada sobreposição a mesma cor, no ecrã e no papel, seja qual \
for o espaço em que cada elemento foi pintado.",
    pairs: [
        "Vermelho, depois verde a 50 % de opacidade",
        "Amarelo, depois azul a 50 % de opacidade",
    ],
    linear: "Mistura em luz linear, como pede cada página deste documento: a \
sobreposição num programa que respeita a indicação.",
    plain: "Mistura com os valores tal como estão escritos: a sobreposição num programa \
que a ignora.",
    file_title: "O que está escrito no ficheiro",
    file_note: "Cada página contém um grupo de transparência. /S /Transparency \
identifica-o, /CS indica o espaço em que a mistura é feita e /I true \
faz a página começar num fundo vazio, e não sobre o que estiver por \
trás dela: numa folha impressa isoladamente isso não muda nada, mas \
passa a contar quando a página é colocada sobre outra. A definição vale \
para todas as páginas do documento; a opacidade de 50 % de cada disco \
verde ou azul vem do seu próprio estado gráfico, /ca 0.5.",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "De ruimte waarin een pagina haar kleuren mengt",
    intro: "Waar een halfdoorzichtige kleur over een andere ligt, berekent het \
programma dat de pagina weergeeft de kleur van de overlapping, en de \
uitkomst hangt af van de getallen waarmee het rekent. Rekent het met de \
kleurwaarden zoals ze in het bestand staan, dan geven rood en groen een dof \
olijfgroen; mengt het in lineair licht, zoals licht in werkelijkheid \
optelt, dan ontstaat een helderder geel. Elke pagina van dit document geeft \
aan in welke kleurruimte haar elementen gemengd worden: een gekalibreerde \
RGB-ruimte in lineair licht. Een programma dat zich aan die aanwijzing \
houdt, geeft elke overlapping dezelfde kleur, op het scherm net als op \
papier, in welke ruimte elk element ook is geschilderd.",
    pairs: [
        "Rood, daarna groen met 50% dekking",
        "Geel, daarna blauw met 50% dekking",
    ],
    linear: "Gemengd in lineair licht, zoals elke pagina hier vraagt: de overlapping in \
een programma dat zich aan de aanwijzing houdt.",
    plain: "Gerekend met de kleurwaarden zoals ze in het bestand staan: de overlapping \
in een programma dat de aanwijzing negeert.",
    file_title: "Wat er in het bestand staat",
    file_note: "Elke pagina bevat een transparantiegroep. /S /Transparency duidt de \
groep aan, /CS verwijst naar de ruimte waarin gemengd wordt, en /I true \
laat de pagina beginnen vanuit het niets in plaats van vanuit wat \
eronder ligt: op een vel dat los wordt afgedrukt verandert dat niets, \
maar zodra de pagina op een andere wordt geplaatst, maakt het verschil. \
De instelling geldt voor elke pagina van het document; de 50% dekking \
van elke groene of blauwe schijf komt uit haar eigen grafische \
toestand, /ca 0.5.",
};

/// 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 sRGB component `encoded` as a share of linear light.
fn to_linear(encoded: f64) -> f64 {
    if encoded <= 0.040_45 {
        encoded / 12.92
    } else {
        ((encoded + 0.055) / 1.055).powf(2.4)
    }
}

/// The share of linear light `linear` as an sRGB component.
#[expect(
    clippy::suboptimal_flops,
    reason = "a fused multiply-add rounds once, and the Python twin rounds twice"
)]
fn to_encoded(linear: f64) -> f64 {
    if linear <= 0.003_130_8 {
        linear * 12.92
    } else {
        1.055 * linear.powf(1.0 / 2.4) - 0.055
    }
}

/// The colour `over` at half opacity comes to over `under` when the two are
/// mixed in linear light.
fn linear_mix(under: Rgb, over: Rgb) -> Rgb {
    let mix = |a: f64, b: f64| to_encoded(f64::midpoint(to_linear(a), to_linear(b)));
    Rgb::new(
        mix(under.r, over.r),
        mix(under.g, over.g),
        mix(under.b, over.b),
    )
}

/// The colour `over` at half opacity comes to over `under` when the two are
/// mixed in the numbers as written.
const fn plain_mix(under: Rgb, over: Rgb) -> Rgb {
    Rgb::new(
        f64::midpoint(under.r, over.r),
        f64::midpoint(under.g, over.g),
        f64::midpoint(under.b, over.b),
    )
}

/// The flow the caption beside a square is set in.
fn caption_flow(handle: &FontHandle) -> TextFlow<'_> {
    TextFlow::new(handle, 9.5).leading(CAPTION_LEADING)
}

/// Sets `text` in `flow` across `width` points from `x`, its top at `top`, and
/// returns how tall it stands.
fn set(
    content: &mut Content,
    flow: &TextFlow<'_>,
    text: &str,
    x: f64,
    top: f64,
    width: f64,
) -> hqf_pdf::Result<f64> {
    let lines = flow.break_lines(text, width);
    content.begin_text();
    flow.draw(content, &lines, x, top, width)?;
    content.end_text();
    Ok(flow.height(&lines))
}

/// A plain square filled with `color`, its top left corner at (`x`, `top`),
/// edged with a thin grey line.
fn swatch(content: &mut Content, color: Rgb, x: f64, top: f64) -> hqf_pdf::Result<()> {
    content.save_state();
    content.set_fill(color)?;
    content.set_stroke(Color::Gray(0.6))?.set_line_width(0.5)?;
    content
        .rect(x, top - SWATCH, SWATCH, SWATCH)?
        .fill_and_stroke();
    content.restore_state();
    Ok(())
}

/// Paints one pair of discs whose centres stand at height `y`, `under` first
/// and then `over` at half opacity through `half`, and beside them the two
/// squares with their captions.
fn pair(
    content: &mut Content,
    handle: &FontHandle,
    words: &Words,
    half: &GStateHandle,
    (under, over): (Rgb, Rgb),
    y: f64,
) -> hqf_pdf::Result<()> {
    let left = MARGIN + RADIUS;
    content.save_state();
    content.set_fill(under)?;
    content.circle(left, y, RADIUS)?.fill();
    content.set_ext_gstate(half).set_fill(over)?;
    content.circle(left + SHIFT, y, RADIUS)?.fill();
    content.restore_state();

    let caption = caption_flow(handle);
    let upper = y + RADIUS - 4.0;
    swatch(content, linear_mix(under, over), SWATCH_X, upper)?;
    set(
        content,
        &caption,
        words.linear,
        CAPTION_X,
        upper,
        CAPTION_WIDTH,
    )?;
    let lower = upper - SWATCH_PITCH;
    swatch(content, plain_mix(under, over), SWATCH_X, lower)?;
    set(
        content,
        &caption,
        words.plain,
        CAPTION_X,
        lower,
        CAPTION_WIDTH,
    )?;
    Ok(())
}

/// Sets the whole page in `words` onto `content`, from the top of the sheet
/// down, and returns where the last line ends, in points up from the foot of
/// the sheet.
#[expect(
    clippy::suboptimal_flops,
    reason = "a fused multiply-add rounds once, and the Python twin rounds twice"
)]
fn compose(
    content: &mut Content,
    handle: &FontHandle,
    words: &Words,
    half: &GStateHandle,
) -> hqf_pdf::Result<f64> {
    let mut top = TOP;

    let title = TextFlow::new(handle, 20.0).leading(24.0);
    top -= set(content, &title, words.title, MARGIN, top, WIDTH)? + 14.0;
    let body = TextFlow::new(handle, 10.5).leading(15.0);
    top -= set(content, &body, words.intro, MARGIN, top, WIDTH)? + 24.0;

    let heading = TextFlow::new(handle, 11.0).leading(14.0);
    for (name, colors) in words.pairs.iter().zip(PAIRS) {
        top -= set(content, &heading, name, MARGIN, top, WIDTH)? + 10.0;
        pair(content, handle, words, half, colors, top - RADIUS)?;
        top -= 2.0 * RADIUS + 26.0;
    }

    top -= set(content, &heading, words.file_title, MARGIN, top, WIDTH)? + 6.0;
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    let entries = TextFlow::new(handle, 9.0).leading(12.0);
    top -= set(content, &entries, GROUP_ENTRIES, MARGIN, top, WIDTH)? + 8.0;
    content.restore_state();
    let small = TextFlow::new(handle, 9.5).leading(13.0);
    top -= set(content, &small, words.file_note, MARGIN, top, WIDTH)?;
    Ok(top)
}

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 languages do not overwrite each other in `tmp/`.
    let out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("page_group")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let handle = doc.add_font(hqf_pdf::Font::parse(fs::read(&font_path)?)?);
    let half = doc.add_ext_gstate(ExtGState::new().fill_alpha(0.5));
    // A calibrated RGB with the sRGB primaries and no curve: its numbers are
    // shares of linear light.
    let linear_light = doc.add_color_space(ColorSpace::CalRgb(
        CalRgb::new(WHITE).gamma([1.0, 1.0, 1.0]).primaries(
            [0.4124, 0.2126, 0.0193],
            [0.3576, 0.7152, 0.1192],
            [0.1805, 0.0722, 0.9505],
        ),
    ));

    let mut content = Content::new();
    compose(&mut content, &handle, words, &half)?;

    let mut page = Page::a4();
    page.content = content.into_bytes();
    // The page's marks are mixed in `linear_light`, starting from nothing
    // rather than from what lies behind the page.
    page.group = Some(PageGroup::new(&linear_light).isolated());
    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::content::Content;
    use hqf_pdf::{Document, ExtGState, Font, Rgb};

    use super::{
        CAPTION_LEADING, CAPTION_WIDTH, MARGIN, PAIRS, SWATCH_PITCH, WIDTH, WORDS, caption_flow,
        compose, language, linear_mix, plain_mix, to_encoded, to_linear,
    };

    /// How low the last line may come, in points up from the foot of the sheet.
    const BOTTOM: f64 = MARGIN;

    /// The lines two languages are allowed to write the same way. There are
    /// none: every line is written in the words of its language.
    const SPARED: [&str; 0] = [];

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

    #[test]
    fn every_language_holds_its_captions_beside_their_squares_and_the_page_on_the_sheet() {
        let font = std::fs::read(super::default_font()).unwrap();
        let mut doc = Document::new();
        let handle = doc.add_font(Font::parse(font).unwrap());
        let half = doc.add_ext_gstate(ExtGState::new().fill_alpha(0.5));
        let caption = caption_flow(&handle);
        let heading = hqf_pdf::TextFlow::new(&handle, 11.0);

        for (language, words) in &WORDS {
            for text in [words.linear, words.plain] {
                let lines = caption.break_lines(text, CAPTION_WIDTH).len();
                assert!(
                    f64::from(u32::try_from(lines).unwrap()) * CAPTION_LEADING <= SWATCH_PITCH,
                    "{}: {text} takes {lines} lines beside its square, more than reach the next",
                    language.code()
                );
            }
            for name in words.pairs {
                assert_eq!(
                    heading.break_lines(name, WIDTH).len(),
                    1,
                    "{}: {name} takes two lines",
                    language.code()
                );
            }
            let bottom = compose(&mut Content::new(), &handle, words, &half).unwrap();
            assert!(
                bottom >= BOTTOM,
                "{}: the page ends {bottom} pt up from the foot of the sheet, under {BOTTOM}",
                language.code()
            );
        }
    }

    #[test]
    fn the_srgb_curve_reads_back_what_it_wrote() {
        for step in 0..=20 {
            let encoded = f64::from(step) / 20.0;

            assert!((to_encoded(to_linear(encoded)) - encoded).abs() < 1e-12);
        }
    }

    #[test]
    fn red_and_green_mixed_in_linear_light_come_to_a_brighter_yellow() {
        let (red, green) = PAIRS[0];

        assert_eq!(plain_mix(red, green), Rgb::new(0.5, 0.45, 0.1));
        let linear = linear_mix(red, green);
        let expected = [0.6642, 0.5899, 0.1];
        for (got, want) in [linear.r, linear.g, linear.b].into_iter().zip(expected) {
            assert!((got - want).abs() < 1e-4, "{linear:?} is not {expected:?}");
        }
    }

    #[test]
    fn each_pair_s_two_squares_differ_enough_to_be_told_apart() {
        for (under, over) in PAIRS {
            let linear = linear_mix(under, over);
            let plain = plain_mix(under, over);
            let apart = (linear.r - plain.r)
                .abs()
                .max((linear.g - plain.g).abs())
                .max((linear.b - plain.b).abs());

            assert!(apart > 0.1, "{under:?} under {over:?}: {apart}");
        }
    }
}