write_links.rs

Die Rust-Datei des Beispiels „Interne und externe Links“. Ein Dokument, gemacht, um ihm zu folgen statt es anzusehen: Jede Zeile des Inhaltsverzeichnisses landet auf der Seite, die sie nennt, und jede Seite führt dorthin zurück, woher sie kam. Unterwegs zeigt es einen über zwei Zeilen verteilten Link, die fünf Rahmen, die ein Link zeichnen kann, und acht Arten, die Seite zu zeigen, auf der ein Link landet.

Rust 821 Zeilen

Wofür dieses Beispiel da ist

Ein Link zeichnet nichts, also beweist nichts auf einer Seite, dass er da ist: Nur ihm zu folgen beweist es. Deshalb sind Links der Teil eines Dokuments, der am häufigsten unbemerkt kaputtgeht — die Datei wird neu erzeugt, die Seiten verschieben sich um eine, und jede Zeile des Inhaltsverzeichnisses landet nun eine Seite zu früh.

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
//! Writes a document whose pages link out of themselves and to each other.
//!
//! A link draws nothing, so nothing on the page proves it is there: only
//! reading software does, by following it. The first page carries a table of
//! contents whose lines lead to the pages after it, and an address that leaves
//! the document; each of the pages after it leads back. The navigation panel
//! holds the same contents, and a last row that opens the same address.
//!
//! The chapter titles and the lines around them are held in `Words`, once per
//! language, and `HQF_PDF_LANG` picks which set is drawn. A chapter title is
//! written once and read twice: it is what the contents shows, and what the
//! navigation panel shows.
//!
//! Each chapter's page shows one side of a link. The first carries a link that
//! covers two lines and nothing between them, and one that goes to the contents
//! by the name it is filed under. The second carries five links, one per border
//! a link can draw, each pressed its own way, the border read back from the
//! link, all on a layer of their own. The third goes back to the contents eight
//! times, each showing the page its own way, every link carrying the same
//! flags, read back beside them. The navigation panel sets the first chapter
//! before the others once they are listed, and ends on a separating line and a
//! bold blue italic row to the named contents.
//!
//! Usage: `cargo run --example write_links -- tmp/links.pdf [font.ttf]`
//!        `cargo run --example write_links -- tmp/links.pdf --archival`
//!        `HQF_PDF_LANG=fr cargo run --example write_links -- tmp/liens.pdf`

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

use hqf_pdf::action::Action;
use hqf_pdf::content::{BorderStyle, Content, Dash};
use hqf_pdf::cos::Name;
use hqf_pdf::metadata::xmp::{Metadata, PdfA};
use hqf_pdf::{
    AnnotationFlags, Bookmark, Document, Font, FontHandle, Layer, LayerHandle, License, Link,
    LinkBorder, LinkTarget, Page, PageFit, PressHighlight, Rect, 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")
}

/// How many chapters the contents lists, each on the page after it.
const CHAPTER_COUNT: usize = 3;

/// The address the contents leaves the document by. It is not language.
const ADDRESS: &str = "https://example.org/hqf-pdf";

/// The words the document is written in, one set per language.
///
/// A chapter title is written once and read twice: the contents draws it, and
/// the navigation panel carries it. Both read the same field, so the two can
/// never fall out of step.
#[derive(Debug)]
struct Words {
    /// The line at the head of the contents, and the name its bookmark takes.
    contents: &'static str,
    /// The line that says which text on the page can be clicked.
    what_is_clickable: &'static str,
    /// The chapters the contents lists, in the order they are laid out.
    chapters: [&'static str; CHAPTER_COUNT],
    /// The line each chapter page leads back by.
    back: &'static str,
    /// The row of the navigation panel that opens the address.
    online: &'static str,
    /// The title the document carries in its information dictionary, and in its
    /// metadata when it is written as an archival file.
    document_title: &'static str,
    /// The two lines one link covers on the first chapter's page.
    over: [&'static str; 2],
    /// The line that reads back how many areas that link covers; `{n}` stands
    /// for the count.
    covered: &'static str,
    /// The line leading back to the contents by the name it is filed under.
    named: &'static str,
    /// The heading over the links of the second chapter's page.
    borders: &'static str,
    /// What each style of border is called: solid, dashed, bevelled, inset,
    /// underlined.
    styles: [&'static str; 5],
    /// The heading over the links of the third chapter's page.
    views: &'static str,
    /// How each of those links shows the contents page.
    fits: [&'static str; 8],
    /// The line that reads back the flags those links carry; `{bits}` stands
    /// for them.
    flags: &'static str,
    /// The name of the layer the second chapter's links belong to.
    layer: &'static str,
    /// The line of the navigation panel that separates the chapters from the
    /// rest.
    separator: &'static str,
}

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

/// The document in English.
const ENGLISH: Words = Words {
    contents: "Contents",
    what_is_clickable: "Blue text is clickable; black text is not.",
    chapters: ["What a link is", "What a link draws", "Where a link goes"],
    back: "Back to the contents",
    online: "The same, online",
    document_title: "A document that links to itself",
    over: [
        "One link covers this line",
        "and this one, and nothing between them.",
    ],
    covered: "The link above covers {n} areas.",
    named: "Back to the contents, by the name it is filed under",
    borders: "Five borders a link can draw, each read back from the link:",
    styles: ["solid", "dashed", "bevelled", "inset", "underlined"],
    views: "Back to the contents, the page shown eight ways:",
    fits: [
        "whole page",
        "full width",
        "full height",
        "a rectangle",
        "whole drawing",
        "drawing width",
        "drawing height",
        "fixed place",
    ],
    flags: "Each of these links carries the flags {bits}.",
    layer: "Links",
    separator: "Elsewhere",
};

/// The document in French.
const FRENCH: Words = Words {
    contents: "Sommaire",
    what_is_clickable: "Le texte bleu est cliquable, le noir ne l’est pas.",
    chapters: [
        "Ce qu’est un lien",
        "Ce qu’un lien affiche",
        "Où mène un lien",
    ],
    back: "Retour au sommaire",
    online: "La même chose, en ligne",
    document_title: "Un document qui renvoie à lui-même",
    over: [
        "Un même lien couvre cette ligne",
        "et celle-ci, et rien entre elles.",
    ],
    covered: "Le lien ci-dessus couvre {n} zones.",
    named: "Retour au sommaire, par le nom sous lequel il est rangé",
    borders: "Cinq bordures qu’un lien peut tracer, chacune relue sur le lien\u{a0}:",
    styles: ["plein", "tireté", "biseauté", "en creux", "souligné"],
    views: "Retour au sommaire, la page montrée de huit façons\u{a0}:",
    fits: [
        "page entière",
        "pleine largeur",
        "pleine hauteur",
        "un rectangle",
        "dessin entier",
        "largeur du dessin",
        "hauteur du dessin",
        "position fixe",
    ],
    flags: "Chacun de ces liens porte les indicateurs {bits}.",
    layer: "Liens",
    separator: "Ailleurs",
};

/// The document in Dutch.
const DUTCH: Words = Words {
    contents: "Inhoud",
    what_is_clickable: "Blauwe tekst is klikbaar; zwarte tekst niet.",
    chapters: [
        "Wat een link is",
        "Wat een link tekent",
        "Waar een link heen gaat",
    ],
    back: "Terug naar de inhoud",
    online: "Hetzelfde, online",
    document_title: "Een document dat naar zichzelf linkt",
    over: ["Eén link dekt deze regel", "en deze, en niets ertussen."],
    covered: "De link hierboven dekt {n} gebieden.",
    named: "Terug naar de inhoud, via de naam waaronder die bewaard is",
    borders: "Vijf randen van een link, elk teruggelezen uit de link:",
    styles: [
        "doorgetrokken",
        "gestreept",
        "afgeschuind",
        "verzonken",
        "onderstreept",
    ],
    views: "Terug naar de inhoud, de pagina op acht manieren getoond:",
    fits: [
        "hele pagina",
        "volle breedte",
        "volle hoogte",
        "een rechthoek",
        "hele tekening",
        "breedte van de tekening",
        "hoogte van de tekening",
        "vaste plek",
    ],
    flags: "Elk van deze links heeft de vlaggen {bits}.",
    layer: "Links",
    separator: "Elders",
};

/// The document in Portuguese.
const PORTUGUESE: Words = Words {
    contents: "Índice",
    what_is_clickable: "O texto azul é clicável; o preto não.",
    chapters: [
        "O que é uma ligação",
        "O que uma ligação desenha",
        "Para onde vai uma ligação",
    ],
    back: "Voltar ao índice",
    online: "O mesmo, online",
    document_title: "Um documento que se liga a si próprio",
    over: ["Uma ligação cobre esta linha", "e esta, e nada entre elas."],
    covered: "A ligação acima cobre {n} zonas.",
    named: "Voltar ao índice, pelo nome com que está arquivado",
    borders: "Cinco contornos de ligação, cada um relido da ligação:",
    styles: [
        "contínuo",
        "tracejado",
        "biselado",
        "embutido",
        "sublinhado",
    ],
    views: "Voltar ao índice, com a página mostrada de oito formas:",
    fits: [
        "página inteira",
        "toda a largura",
        "toda a altura",
        "um retângulo",
        "desenho inteiro",
        "largura do desenho",
        "altura do desenho",
        "posição fixa",
    ],
    flags: "Cada uma destas ligações leva os indicadores {bits}.",
    layer: "Ligações",
    separator: "Noutro lado",
};

/// The document in Italian.
const ITALIAN: Words = Words {
    contents: "Indice",
    what_is_clickable: "Il testo blu è cliccabile; quello nero no.",
    chapters: [
        "Che cos’è un collegamento",
        "Che cosa disegna un collegamento",
        "Dove porta un collegamento",
    ],
    back: "Torna all’indice",
    online: "Lo stesso, online",
    document_title: "Un documento che rimanda a sé stesso",
    over: [
        "Un collegamento copre questa riga",
        "e questa, e niente in mezzo.",
    ],
    covered: "Il collegamento qui sopra copre {n} zone.",
    named: "Torna all’indice, col nome sotto cui è archiviato",
    borders: "Cinque bordi di link, ciascuno riletto dal link:",
    styles: [
        "continuo",
        "tratteggiato",
        "smussato",
        "incassato",
        "sottolineato",
    ],
    views: "Torna all’indice, con la pagina mostrata in otto modi:",
    fits: [
        "pagina intera",
        "tutta la larghezza",
        "tutta l’altezza",
        "un rettangolo",
        "disegno intero",
        "larghezza del disegno",
        "altezza del disegno",
        "posizione fissa",
    ],
    flags: "Ognuno di questi collegamenti porta gli indicatori {bits}.",
    layer: "Collegamenti",
    separator: "Altrove",
};

/// The document in Spanish.
const SPANISH: Words = Words {
    contents: "Índice",
    what_is_clickable: "El texto azul es clicable; el negro no.",
    chapters: [
        "Qué es un enlace",
        "Qué dibuja un enlace",
        "Adónde lleva un enlace",
    ],
    back: "Volver al índice",
    online: "Lo mismo, en línea",
    document_title: "Un documento que se enlaza a sí mismo",
    over: [
        "Un enlace cubre esta línea",
        "y esta otra, y nada entre ellas.",
    ],
    covered: "El enlace de arriba cubre {n} zonas.",
    named: "Volver al índice, por el nombre con que está archivado",
    borders: "Cinco bordes de enlace, cada uno leído del enlace:",
    styles: [
        "continuo",
        "discontinuo",
        "biselado",
        "hundido",
        "subrayado",
    ],
    views: "Volver al índice, con la página mostrada de ocho formas:",
    fits: [
        "página entera",
        "todo el ancho",
        "toda la altura",
        "un rectángulo",
        "dibujo entero",
        "ancho del dibujo",
        "altura del dibujo",
        "lugar fijo",
    ],
    flags: "Cada uno de estos enlaces lleva los indicadores {bits}.",
    layer: "Enlaces",
    separator: "En otro sitio",
};

/// The document in German.
const GERMAN: Words = Words {
    contents: "Inhalt",
    what_is_clickable: "Blauer Text ist anklickbar; schwarzer Text nicht.",
    chapters: [
        "Was ein Link ist",
        "Was ein Link zeichnet",
        "Wohin ein Link führt",
    ],
    back: "Zurück zum Inhalt",
    online: "Dasselbe, online",
    document_title: "Ein Dokument, das auf sich selbst verweist",
    over: [
        "Ein Link deckt diese Zeile ab",
        "und diese, und nichts dazwischen.",
    ],
    covered: "Der Link oben deckt {n} Bereiche ab.",
    named: "Zurück zum Inhalt, über ein benanntes Ziel",
    borders: "Fünf Linkrahmen, jeder aus dem Link zurückgelesen:",
    styles: [
        "durchgezogen",
        "gestrichelt",
        "abgeschrägt",
        "vertieft",
        "unterstrichen",
    ],
    views: "Zurück zum Inhalt, die Seite auf acht Arten gezeigt:",
    fits: [
        "ganze Seite",
        "volle Breite",
        "volle Höhe",
        "ein Rechteck",
        "ganze Zeichnung",
        "Breite der Zeichnung",
        "Höhe der Zeichnung",
        "fester Ort",
    ],
    flags: "Jeder dieser Links trägt die Kennzeichen {bits}.",
    layer: "Links",
    separator: "Anderswo",
};

/// 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 size the contents and the chapter titles are set at.
const SIZE: f64 = 14.0;

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

/// The contents page: one line per chapter, each clickable, and an address that
/// leaves the document.
fn contents_page(font: &FontHandle, words: &'static Words) -> Result<Page, hqf_pdf::Error> {
    let mut content = Content::new();
    let mut page = Page::a4();

    draw(&mut content, font, 20.0, 72.0, 760.0, words.contents)?;

    // A black line that is not a link, beside the blue lines that are.
    draw(
        &mut content,
        font,
        10.0,
        72.0,
        735.0,
        words.what_is_clickable,
    )?;

    let mut top = 700.0;
    for (index, chapter) in words.chapters.iter().enumerate() {
        let line = format!("{}. {chapter}", index + 1);
        content.set_fill_rgb(0.0, 0.2, 0.8)?;
        draw(&mut content, font, SIZE, 72.0, top, &line)?;
        content.set_fill_rgb(0.0, 0.0, 0.0)?;
        page.links.push(Link::new(
            72.0,
            top - 3.0,
            font.measure(&line, SIZE),
            SIZE,
            // Chapter one is the page after this one, which is index 1.
            LinkTarget::Page(index + 1),
        ));
        top = SIZE.mul_add(-2.0, top);
    }

    content.set_fill_rgb(0.0, 0.2, 0.8)?;
    draw(&mut content, font, SIZE, 72.0, top - 20.0, ADDRESS)?;
    content.set_fill_rgb(0.0, 0.0, 0.0)?;
    page.links.push(Link::new(
        72.0,
        top - 23.0,
        font.measure(ADDRESS, SIZE),
        SIZE,
        LinkTarget::Uri(ADDRESS.to_owned()),
    ));

    page.content = content.into_bytes();
    Ok(page)
}

/// What each link of the third chapter's page shows the contents page as.
const fn fits() -> [PageFit; 8] {
    [
        PageFit::WholePage,
        PageFit::FullWidth { top: 780.0 },
        PageFit::FullHeight { left: 72.0 },
        PageFit::Rectangle(Rect::new(72.0, 600.0, 300.0, 180.0)),
        PageFit::WholeDrawing,
        PageFit::DrawingWidth { top: 780.0 },
        PageFit::DrawingHeight { left: 72.0 },
        PageFit::Fixed {
            left: Some(72.0),
            top: Some(780.0),
            zoom: Some(2.0),
        },
    ]
}

/// The words a link's border is described by, from the style it reads back.
#[allow(
    clippy::match_same_arms,
    reason = "a style the page has no word for reads as the plainest one"
)]
const fn style_name(words: &Words, style: &BorderStyle) -> &'static str {
    match style {
        BorderStyle::Solid => words.styles[0],
        BorderStyle::Dashed(_) => words.styles[1],
        BorderStyle::Beveled => words.styles[2],
        BorderStyle::Inset => words.styles[3],
        BorderStyle::Underline => words.styles[4],
        _ => words.styles[0],
    }
}

/// What each chapter's page shows under its title: one link over two lines and
/// one to a name, five borders, or eight ways of showing the contents.
#[allow(clippy::too_many_lines, reason = "one arm per chapter, read in order")]
fn chapter_links(
    content: &mut Content,
    page: &mut Page,
    font: &FontHandle,
    words: &'static Words,
    index: usize,
    shown: &Shown,
) -> Result<(), hqf_pdf::Error> {
    let blue = Rgb::new(0.0, 0.2, 0.8);
    match index {
        0 => {
            content.set_fill(blue)?;
            draw(content, font, SIZE, 72.0, 640.0, words.over[0])?;
            draw(content, font, SIZE, 72.0, 620.0, words.over[1])?;
            draw(content, font, SIZE, 72.0, 560.0, words.named)?;
            content.set_fill(Rgb::BLACK)?;
            let first = font.measure(words.over[0], SIZE);
            let second = font.measure(words.over[1], SIZE);
            let link = Link::new(72.0, 617.0, first.max(second), 37.0, LinkTarget::Page(0))
                .over([
                    Rect::new(72.0, 637.0, first, SIZE).quad(),
                    Rect::new(72.0, 617.0, second, SIZE).quad(),
                ])
                .description(words.back);
            let covered = link.areas().len();
            page.links.push(link);
            draw(
                content,
                font,
                9.0,
                72.0,
                600.0,
                &words.covered.replace("{n}", &covered.to_string()),
            )?;
            page.links.push(Link::new(
                72.0,
                557.0,
                font.measure(words.named, SIZE),
                SIZE,
                LinkTarget::Named("contents".to_owned()),
            ));
        }
        1 => {
            draw(content, font, SIZE, 72.0, 650.0, words.borders)?;
            let dash = Dash::on_off(3.0, 2.0)?;
            let borders = [
                (LinkBorder::solid(blue, 1.0), PressHighlight::None),
                (LinkBorder::dashed(blue, 1.0, dash), PressHighlight::Invert),
                (LinkBorder::beveled(blue, 2.0), PressHighlight::Outline),
                (LinkBorder::inset(blue, 2.0), PressHighlight::Push),
                (LinkBorder::underline(blue, 1.5), PressHighlight::Invert),
            ];
            let mut top = 620.0;
            for (border, highlight) in borders {
                let pattern = border.dash().map_or_else(String::new, |dash| {
                    let lengths: Vec<String> = dash
                        .lengths()
                        .iter()
                        .map(|length| format!("{length:.0}"))
                        .collect();
                    format!(" [{}]", lengths.join(" "))
                });
                let line = format!(
                    "{}, {} pt{pattern}, {}",
                    style_name(words, border.style()),
                    border.width(),
                    border
                        .color()
                        .to_components()
                        .iter()
                        .map(|value| format!("{value:.1}"))
                        .collect::<Vec<_>>()
                        .join(" ")
                );
                draw(content, font, 10.0, 80.0, top, &line)?;
                page.links.push(
                    Link::new(72.0, top - 6.0, 300.0, 20.0, LinkTarget::Page(0))
                        .border(border)
                        .highlight(highlight)
                        .layer(&shown.layer),
                );
                top -= 30.0;
            }
        }
        _ => {
            draw(content, font, SIZE, 72.0, 650.0, words.views)?;
            let mut top = 620.0;
            for (view, fit) in fits().into_iter().zip(words.fits) {
                content.set_fill(blue)?;
                draw(content, font, 10.0, 80.0, top, fit)?;
                content.set_fill(Rgb::BLACK)?;
                page.links.push(
                    Link::new(72.0, top - 4.0, 200.0, 16.0, LinkTarget::Page(0))
                        .view(view)
                        .flags(shown.flags),
                );
                top -= 24.0;
            }
            let line = words
                .flags
                .replace("{bits}", &shown.flags.bits().to_string());
            draw(content, font, 9.0, 72.0, top - 10.0, &line)?;
            if !shown.archival {
                // A link nobody sees, printed nowhere and never shown, which
                // reading software still lists: an archival file refuses it.
                page.links.push(
                    Link::new(500.0, 40.0, 20.0, 20.0, LinkTarget::Page(0)).flags(
                        AnnotationFlags::none()
                            .invisible()
                            .hidden()
                            .no_view()
                            .toggle_no_view(),
                    ),
                );
            }
        }
    }
    Ok(())
}

/// What the chapter pages share: the layer their bordered links sit on, the
/// flags their shown links carry, and whether the file is archival.
struct Shown {
    /// The layer the bordered links of the second chapter belong to.
    layer: LayerHandle,
    /// The flags every link of the third chapter carries.
    flags: AnnotationFlags,
    /// Whether the file is written as an archival one, which refuses a link
    /// nobody sees.
    archival: bool,
}

/// A chapter page, with a line leading back to the contents.
fn chapter_page(
    font: &FontHandle,
    words: &'static Words,
    index: usize,
    shown: &Shown,
) -> Result<Page, hqf_pdf::Error> {
    let mut content = Content::new();
    let mut page = Page::a4();

    let title = format!("{}. {}", index + 1, words.chapters[index]);
    draw(&mut content, font, 20.0, 72.0, 760.0, &title)?;

    content.set_fill_rgb(0.0, 0.2, 0.8)?;
    draw(&mut content, font, SIZE, 72.0, 700.0, words.back)?;
    content.set_fill_rgb(0.0, 0.0, 0.0)?;
    page.links.push(Link::new(
        72.0,
        697.0,
        font.measure(words.back, SIZE),
        SIZE,
        LinkTarget::Page(0),
    ));
    chapter_links(&mut content, &mut page, font, words, index, shown)?;

    page.content = content.into_bytes();
    Ok(page)
}

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

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args: Vec<String> = env::args().skip(1).collect();

    let evaluation = args.iter().any(|arg| arg == "--evaluation");
    // A linked archival file, for a validator to be pointed at: PDF/A has rules
    // of its own about what an annotation may be.
    let archival = args.iter().any(|arg| arg == "--archival");
    args.retain(|arg| !arg.starts_with("--"));

    let mut args = args.into_iter();
    // 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 path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("links")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(if evaluation {
        License::evaluation()
    } else {
        licence::licensed()
    });
    if archival {
        doc.set_conformance(PdfA::A3B);
        let mut facts = Metadata::default();
        facts.title = Some(words.document_title.to_owned());
        facts.producer = Some("hqf-pdf".to_owned());
        facts.created = Some("2026-07-16T09:30:00+02:00".to_owned());
        doc.set_metadata(facts);
    }
    doc.set_info(Name::new("Title"), words.document_title);

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);

    doc.add_page(contents_page(&font, words)?)?;
    let shown = Shown {
        layer: doc.add_layer(Layer::new(words.layer))?,
        flags: AnnotationFlags::from_bits(4)
            .no_zoom()
            .no_rotate()
            .read_only()
            .locked()
            .locked_contents(),
        archival,
    };
    for index in 0..CHAPTER_COUNT {
        doc.add_page(chapter_page(&font, words, index, &shown)?)?;
    }
    doc.add_destination("contents", 0, PageFit::FullWidth { top: 780.0 })?;

    // The same contents again, as the panel a reader navigates by: the first
    // chapter set before the others once they are listed, a line that only
    // separates, and the row to the named contents in bold blue italics.
    let mut contents = Bookmark::new(words.contents, 0).open();
    for (index, chapter) in words.chapters.iter().enumerate().skip(1) {
        contents = contents.child(
            Bookmark::new(format!("{}. {chapter}", index + 1), index + 1)
                .view(PageFit::FullWidth { top: 780.0 }),
        );
    }
    contents = contents.child_at(
        0,
        Bookmark::new(format!("1. {}", words.chapters[0]), 1).view(PageFit::WholePage),
    );
    doc.add_bookmark(contents);
    doc.add_bookmark(Bookmark::separator(words.separator));
    doc.add_bookmark(
        Bookmark::named(words.named, "contents")
            .color(Rgb::new(0.0, 0.2, 0.8))
            .bold()
            .italic(),
    );
    doc.add_bookmark(Bookmark::acting(
        words.online,
        Action::Uri {
            uri: ADDRESS.to_owned(),
            track_pointer: false,
        },
    ));

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&path).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, &bytes)?;
    println!("wrote {} ({} bytes)", path, bytes.len());
    Ok(())
}

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

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

    /// The lines two languages are allowed to write the same way, where two
    /// languages spell a word alike. The address the contents leaves by is held
    /// outside the words.
    const SPARED: [&str; 4] = [
        // Written the same way in German.
        r#"layer: "Links""#,
        // Written the same way in Italian.
        r#""continuo""#,
        // Written the same way in Portuguese.
        r#""biselado""#,
        r#"contents: "Índice""#,
    ];

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

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

    /// No line a chapter page sets runs past the paper's right margin.
    #[test]
    fn every_line_of_the_chapter_pages_stays_on_the_paper() {
        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 (_, words) in WORDS {
            for line in [
                words.over[0],
                words.over[1],
                words.named,
                words.borders,
                words.views,
            ] {
                let width = font.measure(line, SIZE);
                assert!(width <= 450.0, "{line:?} needs {width}");
            }
        }
    }
}