write_slideshow.rs

Die Rust-Datei des Beispiels „Eine Diashow, die von selbst läuft“. Eine schlichte erste Folie und dreizehn weitere, von denen jede den Effekt angibt, mit dem sie erscheint — die zwölf, die die PDF-Norm (ISO 32000) definiert —, wie lange dieser Effekt dauert und wie lange die Folie stehen bleibt, bevor die nächste kommt. Die Datei bittet darum, im Vollbild geöffnet zu werden, denn dort laufen die Effekte, und ein Link auf der ersten Folie zeigt den Bildschirm wieder, mit einer Überblendung eingeblendet.

Rust 833 Zeilen

Wofür dieses Beispiel da ist

Ein Dokument, das von selbst läuft, ist genau das, was ein Bildschirm im Empfangsbereich, auf einem Messestand oder im Wartezimmer braucht: keine Präsentationssoftware zu installieren, keine Lizenz auf der Maschine, niemand muss etwas anklicken. Die Datei ist die Vorführung, und sie läuft auf jedem Gerät, das dort steht, denn jede Maschine öffnet bereits PDF-Dateien.

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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
//! A slideshow: fourteen pages, each arriving by a different effect.
//!
//! The file opens full screen, and every page states how it arrives and how
//! long it stands before the next one comes by itself. Nothing here is drawn by
//! the effect: each page simply names the one that brings it in, so what
//! reading software does can be checked against what the file asked for.
//!
//! Open it in reading software that honours full screen to see them run.
//!
//! The title slide also carries a link that acts rather than leads: following
//! it asks reading software to show the screen again, brought in by dissolving.
//! Each slide keeps the effect it states for itself.
//!
//! The slides are written in the language `HQF_PDF_LANG` names: what an effect
//! is called and what it does are words a person reads. The entries the file
//! writes for it are not — `/S /Split /Dm /V /M /O` is what reading software
//! parses, and it is the same in every language, so each slide carries both.
//!
//! Once out of full screen the file shows one page at a time with the
//! thumbnails beside it, and printing leaves the scaling to the reader.
//!
//! Usage: `cargo run --example write_slideshow -- tmp/slideshow.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_slideshow`

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

use hqf_pdf::action::Action;
use hqf_pdf::content::Content;
use hqf_pdf::transition::{Axis, Effect, Heading, Motion, Transition};
use hqf_pdf::viewer::{PageLayout, PrintScaling, SidePanel, ViewerPreferences};
use hqf_pdf::{Color, Document, Error, Font, FontHandle, Link, OpenMode, Page, 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")
}

/// A slide, laid down sideways: a projected page is wider than it is tall.
const SHEET: (f64, f64) = (720.0, 540.0);

/// How far in from the edge of the slide everything is set.
const MARGIN: f64 = 64.0;

/// How long each slide stands before the next arrives, in seconds.
const STANDS: f64 = 4.0;

/// How long each effect takes, in seconds.
const TAKES: f64 = 1.0;

/// The size a slide's name is set at, in points.
const NAME: f64 = 54.0;

/// The size the line under a slide's name is set at, in points.
const DOES: f64 = 15.0;

/// The size the title slide's heading is set at, in points.
const TITLE: f64 = 42.0;

/// The size the lines of the title slide are set at, in points.
const INTRO: f64 = 12.0;

/// How far apart the lines of the title slide are stacked, in points.
const INTRO_STEP: f64 = 20.0;

/// The baseline of the line on the title slide that a link lies over.
const FOLLOW_AT: f64 = 90.0;

/// How far below its baseline, and how far above, the link over that line
/// reaches.
const FOLLOW_REACH: (f64, f64) = (4.0, 12.0);

/// How wide the link over that line is: the room between the two margins.
const FOLLOW_WIDTH: f64 = SHEET.0 - 2.0 * MARGIN;

/// The words the slides are written in, one set per language.
///
/// What is not language stays out of it: the entries the file writes for each
/// effect are what reading software parses, and the name on the footer is a
/// name.
#[derive(Debug)]
struct Words {
    /// What the title slide is headed by.
    title: &'static str,
    /// The line under that heading.
    strapline: &'static str,
    /// What the title slide says the file asks reading software for.
    intro: [&'static str; 4],
    /// What the title slide says of itself.
    stands_still: &'static str,
    /// The line on the title slide a link lies over, saying what following it
    /// does.
    follow: &'static str,
    /// What stands between a slide's number and the count of them.
    of: &'static str,
    /// What is written over the entries the file states for a slide.
    states_label: &'static str,
    /// What each effect is called, in the order `EFFECTS` sets them.
    names: [&'static str; EFFECTS.len()],
    /// What each effect does, in the same order.
    does: [&'static str; EFFECTS.len()],
}

impl Words {
    /// The words the slides are written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }
}

/// The slides in English.
const ENGLISH: Words = Words {
    title: "Twelve ways in",
    strapline: "Every effect a PDF can ask reading software for, one to a slide.",
    intro: [
        "This file opens full screen, and each slide states how it arrives and how long",
        "it stands before the next one comes by itself. Reading software that honours",
        "all of it runs the whole thing unattended; one that honours none of it shows",
        "fourteen pages, and nothing is lost.",
    ],
    stands_still: "This first slide arrives by nothing at all: it is the one already on the screen.",
    follow: "Click this line and the screen you are on is shown again, dissolving in.",
    of: "of",
    states_label: "the file states",
    names: [
        "Split",
        "Blinds",
        "Box",
        "Wipe",
        "Dissolve",
        "Glitter",
        "Fly",
        "Fly, at the reader",
        "Push",
        "Cover",
        "Uncover",
        "Fade",
        "Replace",
    ],
    does: [
        "Two lines sweep apart to reveal the slide.",
        "Many lines sweep across at once, like a blind opening.",
        "A rectangle closes in on the middle of the slide.",
        "One line sweeps left to right.",
        "The slide before it dissolves into this one.",
        "The dissolve travels from the top-left corner down.",
        "The slide before it flies off downwards.",
        "What has changed flies out of the screen, starting small.",
        "Both slides slide together, the old one pushing this on.",
        "This slide slides up over the one before it.",
        "The slide before it slides down off this one.",
        "The slide fades up out of reading software's own background.",
        "Nothing sweeps or fades: the slide is simply there.",
    ],
};

/// The slides in French.
const FRENCH: Words = Words {
    title: "Douze façons d’entrer",
    strapline: "Tous les effets qu’un PDF demande au logiciel de lecture, un par diapositive.",
    intro: [
        "Ce fichier s’ouvre en plein écran, et chaque diapositive indique comment elle arrive et",
        "combien de temps elle reste avant que la suivante vienne d’elle-même. Un logiciel",
        "de lecture qui respecte tout cela déroule l’ensemble tout seul ; celui qui n’en respecte",
        "rien affiche quatorze pages, et rien n’est perdu.",
    ],
    stands_still: "Cette première diapositive n’arrive par aucun effet : c’est celle qui est déjà \
à l’écran.",
    follow: "Cliquez sur cette ligne : l’écran actuel s’affiche de nouveau, en dissolution.",
    of: "sur",
    states_label: "ce que le fichier écrit",
    names: [
        "Séparation",
        "Stores",
        "Boîte",
        "Balayage",
        "Dissolution",
        "Scintillement",
        "Envol",
        "Envol vers l’avant",
        "Poussée",
        "Recouvrement",
        "Dévoilement",
        "Fondu",
        "Remplacement",
    ],
    does: [
        "Deux traits s’écartent et découvrent la diapositive.",
        "Plusieurs traits balaient l’écran d’un coup, comme un store qui s’ouvre.",
        "Un rectangle se referme sur le milieu de la diapositive.",
        "Un trait balaie l’écran de la gauche vers la droite.",
        "La diapositive précédente se dissout dans celle-ci.",
        "La dissolution part du coin supérieur gauche et descend.",
        "La diapositive précédente file vers le bas et sort de l’écran.",
        "Ce qui a changé surgit de l’écran, d’abord petit puis grand.",
        "Les deux diapositives glissent ensemble, l’ancienne poussant celle-ci.",
        "Cette diapositive glisse vers le haut par-dessus la précédente.",
        "La diapositive précédente glisse vers le bas et libère celle-ci.",
        "La diapositive apparaît en fondu depuis le fond du logiciel de lecture.",
        "Rien ne balaie ni ne s’estompe : la diapositive est simplement là.",
    ],
};

/// The slides in Dutch.
const DUTCH: Words = Words {
    title: "Twaalf ingangen",
    strapline: "Elk effect dat een pdf aan leessoftware kan vragen, één per dia.",
    intro: [
        "Dit bestand opent op volledig scherm, en elke dia zegt hoe ze binnenkomt en hoe lang",
        "ze blijft staan voordat de volgende vanzelf komt. Leessoftware die alles",
        "respecteert, speelt het geheel zonder toezicht af; software die niets respecteert, toont",
        "veertien pagina’s, en er gaat niets verloren.",
    ],
    stands_still: "Deze eerste dia komt op geen enkele manier binnen: ze staat al op het scherm.",
    follow: "Klik op deze regel en het huidige scherm wordt opnieuw getoond, invloeiend.",
    of: "van",
    states_label: "het bestand noemt",
    names: [
        "Splitsen",
        "Jaloezieën",
        "Kader",
        "Vegen",
        "Oplossen",
        "Glinsteren",
        "Vliegen",
        "Vliegen naar de lezer",
        "Duwen",
        "Bedekken",
        "Onthullen",
        "Vervagen",
        "Vervangen",
    ],
    does: [
        "Twee lijnen schuiven uiteen om de dia te onthullen.",
        "Veel lijnen vegen tegelijk, als een jaloezie die opengaat.",
        "Een rechthoek sluit zich naar het midden van de dia.",
        "Eén lijn veegt van links naar rechts.",
        "De vorige dia lost op in deze.",
        "Het oplossen loopt van de linkerbovenhoek naar beneden.",
        "De vorige dia vliegt naar beneden weg.",
        "Wat veranderd is, vliegt het scherm uit, klein beginnend.",
        "Beide dia’s schuiven samen, de oude door deze weggeduwd.",
        "Deze dia schuift omhoog over de vorige.",
        "De vorige dia schuift naar beneden van deze af.",
        "De dia verschijnt uit de eigen achtergrond van de leessoftware.",
        "Niets veegt of vervaagt: de dia is er gewoon.",
    ],
};

/// The slides in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Doze formas de entrar",
    strapline: "Cada efeito que um PDF pede a um programa de leitura, um por diapositivo.",
    intro: [
        "Este ficheiro abre em ecrã inteiro, e cada diapositivo indica como chega e quanto",
        "tempo fica antes de o seguinte vir sozinho. Um programa de leitura que respeite",
        "tudo passa-o inteiro sem que ninguém toque em nada; um que não respeite nada mostra",
        "catorze páginas, e não se perde nada.",
    ],
    stands_still: "Este primeiro diapositivo não chega de forma nenhuma: é o que já está no ecrã.",
    follow: "Clique nesta linha e o ecrã atual volta a ser mostrado, a dissolver-se.",
    of: "de",
    states_label: "o ficheiro indica",
    names: [
        "Divisão",
        "Persianas",
        "Caixa",
        "Varrimento",
        "Dissolução",
        "Cintilação",
        "Voo",
        "Voo, para o leitor",
        "Empurrão",
        "Cobertura",
        "Revelação",
        "Desvanecimento",
        "Substituição",
    ],
    does: [
        "Duas linhas afastam-se para revelar o diapositivo.",
        "Muitas linhas varrem ao mesmo tempo, como uma persiana a abrir.",
        "Um retângulo fecha-se para o meio do diapositivo.",
        "Uma linha varre da esquerda para a direita.",
        "O diapositivo anterior dissolve-se neste.",
        "A dissolução avança do canto superior esquerdo para baixo.",
        "O diapositivo anterior voa para baixo.",
        "O que mudou voa para fora do ecrã, a começar pequeno.",
        "Os dois diapositivos deslizam juntos, o antigo empurrado por este.",
        "Este diapositivo sobe a deslizar por cima do anterior.",
        "O diapositivo anterior desce a deslizar e deixa ver este.",
        "O diapositivo surge a partir do fundo próprio do programa de leitura.",
        "Nada varre nem desvanece: o diapositivo simplesmente está lá.",
    ],
};

/// The slides in Italian.
const ITALIAN: Words = Words {
    title: "Dodici modi di entrare",
    strapline: "Ogni effetto che un PDF chiede al programma di lettura, uno a diapositiva.",
    intro: [
        "Questo file si apre a schermo intero, e ogni diapositiva indica come arriva e quanto",
        "resta prima che la successiva arrivi da sola. Un programma di lettura che rispetta",
        "tutto lo fa scorrere da sé; uno che non rispetta nulla mostra",
        "quattordici pagine, e non si perde niente.",
    ],
    stands_still: "Questa prima diapositiva non arriva in alcun modo: è quella già sullo schermo.",
    follow: "Cliccate su questa riga e lo schermo attuale si mostra di nuovo, dissolvendosi.",
    of: "di",
    states_label: "il file indica",
    names: [
        "Divisione",
        "Veneziane",
        "Riquadro",
        "Tendina",
        "Dissolvenza",
        "Scintillio",
        "Volo",
        "Volo, verso il lettore",
        "Spinta",
        "Copertura",
        "Scopertura",
        "Sfumatura",
        "Sostituzione",
    ],
    does: [
        "Due linee si separano per scoprire la diapositiva.",
        "Molte linee scorrono insieme, come una veneziana che si apre.",
        "Un rettangolo si stringe verso il centro della diapositiva.",
        "Una linea scorre da sinistra a destra.",
        "La diapositiva precedente si dissolve in questa.",
        "La dissolvenza procede dall’angolo in alto a sinistra verso il basso.",
        "La diapositiva precedente vola via verso il basso.",
        "Ciò che è cambiato vola fuori dallo schermo, partendo piccolo.",
        "Le due diapositive scorrono insieme, la vecchia spinta da questa.",
        "Questa diapositiva sale scorrendo sopra la precedente.",
        "La diapositiva precedente scende scorrendo e scopre questa.",
        "La diapositiva sfuma dallo sfondo proprio del programma di lettura.",
        "Niente scorre né sfuma: la diapositiva è semplicemente lì.",
    ],
};

/// The slides in Spanish.
const SPANISH: Words = Words {
    title: "Doce formas de entrar",
    strapline: "Cada efecto que un PDF pide a un programa de lectura, uno por diapositiva.",
    intro: [
        "Este archivo se abre a pantalla completa, y cada diapositiva indica cómo llega y cuánto",
        "tiempo se queda antes de que la siguiente venga sola. Un programa de lectura que lo respeta",
        "todo lo pasa entero sin que nadie toque nada; uno que no respeta nada muestra",
        "catorce páginas, y no se pierde nada.",
    ],
    stands_still: "Esta primera diapositiva no llega de ninguna forma: es la que ya está en pantalla.",
    follow: "Haga clic en esta línea y la pantalla actual se vuelve a mostrar, fundiéndose.",
    of: "de",
    states_label: "el archivo indica",
    names: [
        "División",
        "Persianas",
        "Caja",
        "Barrido",
        "Disolución",
        "Destellos",
        "Vuelo",
        "Vuelo, hacia el lector",
        "Empuje",
        "Cubrir",
        "Descubrir",
        "Fundido",
        "Reemplazo",
    ],
    does: [
        "Dos líneas se separan para descubrir la diapositiva.",
        "Muchas líneas barren a la vez, como una persiana que se abre.",
        "Un rectángulo se cierra hacia el centro de la diapositiva.",
        "Una línea barre de izquierda a derecha.",
        "La diapositiva anterior se disuelve en esta.",
        "La disolución avanza desde la esquina superior izquierda hacia abajo.",
        "La diapositiva anterior sale volando hacia abajo.",
        "Lo que ha cambiado sale volando de la pantalla, empezando pequeño.",
        "Las dos diapositivas se deslizan juntas, la anterior empujando a esta.",
        "Esta diapositiva sube deslizándose sobre la anterior.",
        "La diapositiva anterior baja deslizándose y deja ver esta.",
        "La diapositiva aparece desde el fondo propio del programa de lectura.",
        "Nada barre ni se funde: la diapositiva simplemente está.",
    ],
};

/// The slides in German.
const GERMAN: Words = Words {
    title: "Zwölf Auftritte",
    strapline: "Jeder Effekt, den ein PDF verlangen kann, einer je Folie.",
    intro: [
        "Die Datei öffnet im Vollbild, und jede Folie sagt, wie sie erscheint und wie lange",
        "sie steht, bevor die nächste von selbst kommt. Eine Lesesoftware, die alles befolgt,",
        "spielt das Ganze unbeaufsichtigt ab; eine, die nichts davon befolgt, zeigt vierzehn",
        "Seiten, und nichts geht verloren.",
    ],
    stands_still: "Diese erste Folie erscheint durch gar nichts: Sie ist schon auf dem Bildschirm.",
    follow: "Ein Klick auf diese Zeile zeigt den aktuellen Bildschirm erneut, eingeblendet.",
    of: "von",
    states_label: "die Datei gibt an",
    names: [
        "Teilen",
        "Jalousie",
        "Rechteck",
        "Wischen",
        "Auflösen",
        "Glitzern",
        "Fliegen",
        "Fliegen, zum Leser",
        "Schieben",
        "Überdecken",
        "Aufdecken",
        "Überblenden",
        "Ersetzen",
    ],
    does: [
        "Zwei Linien fahren auseinander und geben die Folie frei.",
        "Viele Linien fahren zugleich darüber, wie eine sich öffnende Jalousie.",
        "Ein Rechteck schließt sich zur Mitte der Folie hin.",
        "Eine Linie fährt von links nach rechts.",
        "Die vorige Folie löst sich in diese auf.",
        "Das Auflösen wandert von der linken oberen Ecke nach unten.",
        "Die vorige Folie fliegt nach unten weg.",
        "Was sich geändert hat, fliegt aus dem Bildschirm, klein beginnend.",
        "Beide Folien gleiten zusammen, die alte schiebt diese herein.",
        "Diese Folie gleitet von unten über die vorige.",
        "Die vorige Folie gleitet nach unten von dieser weg.",
        "Die Folie blendet aus dem eigenen Hintergrund der Lesesoftware auf.",
        "Nichts fährt oder blendet: Die Folie ist einfach da.",
    ],
};

/// 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(())
}

/// One slide: a wash of colour, the name of the effect that brings it in, what
/// that effect does, and the entries the file states for it.
fn slide(
    font: &FontHandle,
    words: &Words,
    wash: Rgb,
    number: &str,
    name: &str,
    does: &str,
    states: &str,
) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    content.save_state();
    content.set_fill(wash)?;
    content.rect(0.0, 0.0, SHEET.0, SHEET.1)?.fill();
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    content.rect(0.0, SHEET.1 - 8.0, SHEET.0, 8.0)?.fill();
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    text(&mut content, font, DOES, MARGIN, SHEET.1 - 70.0, number)?;
    text(&mut content, font, NAME, MARGIN, 300.0, name)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.92))?;
    text(&mut content, font, DOES, MARGIN, 254.0, does)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.82))?;
    text(
        &mut content,
        font,
        11.0,
        MARGIN,
        MARGIN + 34.0,
        words.states_label,
    )?;
    text(&mut content, font, 11.0, MARGIN, MARGIN + 16.0, states)?;
    content.restore_state();
    Ok(content.into_bytes())
}

/// The title slide, which nothing brings in: it is the one already there.
fn title(font: &FontHandle, words: &Words) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    content.save_state();
    content.set_fill(Rgb::new(0.09, 0.11, 0.16))?;
    content.rect(0.0, 0.0, SHEET.0, SHEET.1)?.fill();
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    text(&mut content, font, TITLE, MARGIN, 330.0, words.title)?;
    content.set_fill(Color::Gray(0.72))?;
    text(&mut content, font, DOES, MARGIN, 286.0, words.strapline)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.55))?;
    let mut y = 210.0;
    for line in words.intro {
        text(&mut content, font, INTRO, MARGIN, y, line)?;
        y -= INTRO_STEP;
    }
    // The line that speaks of this slide alone stands a blank line clear of the
    // ones that speak of the file.
    y -= INTRO_STEP;
    text(&mut content, font, INTRO, MARGIN, y, words.stands_still)?;
    text(&mut content, font, INTRO, MARGIN, FOLLOW_AT, words.follow)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.4))?;
    text(&mut content, font, 11.0, MARGIN, MARGIN, "HQF Development")?;
    content.restore_state();
    Ok(content.into_bytes())
}

/// One slide's worth: how it arrives, the wash it is laid on, and the entries
/// the file writes for it. What the effect is called and what it does are words
/// a person reads, and are held in `Words`.
type Slide = (Effect, Rgb, &'static str);

/// The thirteen slides after the title one: the twelve effects the format
/// defines, `Fly` standing on two of them.
const EFFECTS: [Slide; 13] = [
    (
        Effect::Split {
            axis: Axis::Vertical,
            motion: Motion::Outward,
        },
        Rgb::new(0.13, 0.29, 0.36),
        "/S /Split /Dm /V /M /O",
    ),
    (
        Effect::Blinds {
            axis: Axis::Horizontal,
        },
        Rgb::new(0.16, 0.34, 0.31),
        "/S /Blinds /Dm /H",
    ),
    (
        Effect::Box {
            motion: Motion::Inward,
        },
        Rgb::new(0.24, 0.33, 0.22),
        "/S /Box /M /I",
    ),
    (
        Effect::Wipe {
            heading: Heading::Rightwards,
        },
        Rgb::new(0.36, 0.32, 0.16),
        "/S /Wipe /Di 0",
    ),
    (Effect::Dissolve, Rgb::new(0.40, 0.26, 0.16), "/S /Dissolve"),
    (
        Effect::Glitter {
            heading: Heading::Diagonally,
        },
        Rgb::new(0.42, 0.20, 0.20),
        "/S /Glitter /Di 315",
    ),
    (
        Effect::Fly {
            heading: Some(Heading::Downwards),
            scale: None,
            whole_page: true,
        },
        Rgb::new(0.38, 0.17, 0.30),
        "/S /Fly /Di 270 /B true",
    ),
    (
        Effect::Fly {
            heading: None,
            scale: Some(0.6),
            whole_page: false,
        },
        Rgb::new(0.31, 0.18, 0.38),
        "/S /Fly /Di /None /SS 0.6 /B false",
    ),
    (
        Effect::Push {
            heading: Heading::Leftwards,
        },
        Rgb::new(0.21, 0.20, 0.42),
        "/S /Push /Di 180",
    ),
    (
        Effect::Cover {
            heading: Heading::Upwards,
        },
        Rgb::new(0.14, 0.26, 0.42),
        "/S /Cover /Di 90",
    ),
    (
        Effect::Uncover {
            heading: Heading::Downwards,
        },
        Rgb::new(0.11, 0.31, 0.38),
        "/S /Uncover /Di 270",
    ),
    (Effect::Fade, Rgb::new(0.20, 0.20, 0.22), "/S /Fade"),
    (Effect::Replace, Rgb::new(0.09, 0.11, 0.16), "/S /R"),
];

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

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

    let mut first = Page::new(SHEET.0, SHEET.1);
    first.content = title(&font, words)?;
    first.duration = Some(STANDS);
    first.links.push(Link::acting(
        MARGIN,
        FOLLOW_AT - FOLLOW_REACH.0,
        FOLLOW_WIDTH,
        FOLLOW_REACH.0 + FOLLOW_REACH.1,
        Action::Transition(Transition::new(Effect::Dissolve).seconds(TAKES)),
    ));
    doc.add_page(first)?;

    let total = EFFECTS.len() + 1;
    for (index, (effect, wash, states)) in EFFECTS.into_iter().enumerate() {
        let number = format!("{} {} {total}", index + 2, words.of);
        let mut page = Page::new(SHEET.0, SHEET.1);
        page.content = slide(
            &font,
            words,
            wash,
            &number,
            words.names[index],
            words.does[index],
            states,
        )?;
        page.transition = Some(Transition::new(effect).seconds(TAKES));
        page.duration = Some(STANDS);
        doc.add_page(page)?;
    }

    // A transition is read in full screen and nowhere else, so a slideshow that
    // does not ask for full screen asks for nothing.
    doc.set_open_mode(OpenMode::FullScreen);

    doc.set_page_layout(PageLayout::SinglePage);

    doc.set_viewer_preferences(
        ViewerPreferences::new()
            .after_full_screen(SidePanel::Thumbnails)
            .print_scaling(PrintScaling::Viewer),
    );

    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, {} slides, each arriving by a different effect",
        written.len(),
        doc.page_count()
    );
    Ok(())
}

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

    use super::{DOES, EFFECTS, INTRO, MARGIN, NAME, SHEET, TITLE, WORDS, default_font, language};

    /// The room a line set from the left margin has before it reaches the
    /// margin on the other side of the slide.
    const ROOM: f64 = SHEET.0 - 2.0 * MARGIN;

    /// The lines two languages are allowed to write the same way, where two
    /// languages spell a word alike. The entries the file writes for each
    /// effect are held outside the words, and so is the name on the footer.
    const SPARED: [&str; 2] = [
        // Written the same way in Portuguese.
        r#""Persianas""#,
        r#"of: "de""#,
    ];

    #[test]
    fn every_language_writes_the_slides_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the slides say these in more than one language: {untranslated:?}"
        );
    }

    /// Nothing on a slide is broken to a width: a line longer than the slide
    /// runs off the edge of it, and the name of an effect is set at 54 points,
    /// where a word or two more is all it takes.
    #[test]
    fn every_language_writes_lines_that_fit_the_slide() {
        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"),
        );

        for (named, words) in WORDS {
            let lines = [(TITLE, words.title), (DOES, words.strapline)]
                .into_iter()
                .chain(words.intro.map(|line| (INTRO, line)))
                .chain([(INTRO, words.stands_still), (INTRO, words.follow)])
                .chain(words.names.map(|name| (NAME, name)))
                .chain(words.does.map(|does| (DOES, does)));

            for (size, line) in lines {
                let measured = font.measure(line, size);
                assert!(
                    measured <= ROOM,
                    "the {} slides draw {line:?} over {measured:.1} points, \
                     and they have {ROOM:.1}",
                    named.code()
                );
            }
        }
    }

    /// The strapline of the title slide promises every effect the format
    /// defines, one to a slide. Each slide is named here by the entries the
    /// file writes for it, which are the same in every language.
    #[test]
    fn every_effect_the_format_defines_stands_on_a_slide() {
        const DEFINED: [&str; 12] = [
            "/S /R",
            "/S /Split",
            "/S /Blinds",
            "/S /Box",
            "/S /Wipe",
            "/S /Dissolve",
            "/S /Glitter",
            "/S /Fly",
            "/S /Push",
            "/S /Cover",
            "/S /Uncover",
            "/S /Fade",
        ];

        let missing: Vec<&str> = DEFINED
            .into_iter()
            .filter(|entries| {
                !EFFECTS
                    .iter()
                    .any(|(_, _, states)| states.starts_with(*entries))
            })
            .collect();

        assert!(missing.is_empty(), "no slide arrives by {missing:?}");
    }

    /// The heading of the title slide counts the effects in words, and the
    /// lines under it count the pages the same way. Neither can be worked out
    /// from the table, so an effect added or dropped has to be carried into
    /// every language by hand — and this is what says so.
    #[test]
    fn the_counts_written_in_words_are_the_counts_the_file_has() {
        assert_eq!(
            EFFECTS.len(),
            13,
            "the title slide says twelve effects, and `Fly` stands on two slides"
        );
        assert_eq!(EFFECTS.len() + 1, 14, "the title slide says fourteen pages");
    }
}