write_reading_preferences.rs

The Rust file of the “A handbook that says how it wants to be read” example. Four pages that say how they want to be opened: which page comes up and how much of the window it fills, the chapters beside it, the pages two at a time, a print dialog already filled in — every one of them a wish reading software answers for itself.

Rust 922 lines

What this example is for

You send out a hundred-page handbook. The person who opens it lands on the cover, half magnified, with no list of chapters in sight — and now somebody has to be told where to click. A PDF can say for itself how it wants to be opened: on this page, at this size, with the list of chapters already unfolded down the side. It is a wish and not an order. Desktop reading software such as Adobe Acrobat Reader follows most of it; the reading software built into a browser follows little of it, and each browser draws its own line. Open the document below in both, one after the other, and the difference takes five seconds to see.

What this example shows

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
//! A handbook that says how it would like to be opened, shown and printed.
//!
//! None of what this document states changes a single mark on its pages. It
//! changes what happens the moment somebody double-clicks the file: which page
//! comes up, how much of it fills the window, what stands beside it, and what
//! the print dialogue is already set to when it opens.
//!
//! What the handbook says is written in the language `HQF_PDF_LANG` names. The
//! address it is published under is not, and neither is the name of the file
//! its one relative link points at.
//!
//! Usage: `cargo run --example write_reading_preferences -- tmp/handbook.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_reading_preferences`

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

use hqf_pdf::content::Content;
use hqf_pdf::metadata::xmp::Metadata;
use hqf_pdf::{
    Bookmark, Color, Document, Duplex, Error, Font, FontHandle, Link, LinkTarget, OpenAction,
    OpenMode, Page, PageFit, PageLayout, PrintScaling, Rgb, SidePanel, ViewerPreferences,
};

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

/// A4, in points.
const SHEET: (f64, f64) = (595.276, 841.890);

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

/// The colour the band across the head of a page is laid in.
const BAND: Rgb = Rgb {
    r: 0.13,
    g: 0.29,
    b: 0.36,
};

/// The address this document is published under, and the address its relative
/// links are read against.
const BASE: &str = "https://example.org/handbook/";

/// The file the one relative link on the contents page points at.
const TERMS_FILE: &str = "terms.html";

/// Who publishes the handbook, which no language renames.
const PUBLISHER: &str = "HQF Development";

/// How many copies the print dialogue is asked to offer, which a row of the
/// table spells out in words.
const COPIES: u32 = 2;

/// The run of pages the print dialogue is asked to offer, counting from zero,
/// which a row of the table spells out in words.
const PRINT_RUN: (usize, usize) = (1, 3);

/// The sizes the handbook is set in, in points.
const COVER_TITLE_SIZE: f64 = 34.0;
const COVER_SUBJECT_SIZE: f64 = 13.0;
const PUBLISHER_SIZE: f64 = 10.0;
const HEAD_SIZE: f64 = 20.0;
const BODY_SIZE: f64 = 10.5;
const SECTION_SIZE: f64 = 11.0;
const SETTING_SIZE: f64 = 9.5;
const NOTE_SIZE: f64 = 9.5;
const FOOT_SIZE: f64 = 8.0;
const SKETCH_SIZE: f64 = 8.0;

/// How far in from the left of a settings row what the setting does is drawn.
const SETTING_GAP: f64 = 190.0;

/// The words the handbook is written in, one set per language.
///
/// The address the file is published under, the name of the file its link
/// points at and the name of the publisher are not among them.
#[derive(Debug)]
struct Words {
    /// What the handbook is called, on its cover, at the foot of every page and
    /// in what the file says of itself.
    handbook: &'static str,
    /// What the handbook is about, under the title and in the metadata.
    subject: &'static str,
    /// What each section is called. One array, read three times over: the list
    /// on the contents page, the heading of the two pages that have one, and
    /// the bookmarks a reader is shown beside the page. No language can make
    /// the three disagree.
    sections: [&'static str; 4],
    /// The paragraph on the cover.
    cover_body: [&'static str; 4],
    /// The paragraph under the list of sections.
    contents_body: [&'static str; 4],
    /// The two lines above the link, the first of which names the file it
    /// points at.
    terms_lead: [&'static str; 2],
    /// The words the link is laid over.
    terms_link: &'static str,
    /// The paragraph that says what a base address is for.
    base_note: [&'static str; 3],
    /// The paragraph above the table of what the file asks of reading software.
    screen_lead: [&'static str; 3],
    /// What each row of that table asks for, and what it does.
    screen_settings: [[&'static str; 2]; 7],
    /// What the last row of it asks for, whose answer is the address itself.
    relative_links: &'static str,
    /// The paragraph under it.
    screen_note: [&'static str; 3],
    /// The paragraph above the table of what the file asks of a printer.
    printer_lead: [&'static str; 2],
    /// What each row of that table asks for, and what it does.
    printer_settings: [[&'static str; 2]; 5],
    /// What the sheet drawn front-side-up is called.
    front: &'static str,
    /// What the sheet drawn back-side-up is called.
    back: &'static str,
    /// What the arrow between the two says.
    long_edge: &'static str,
    /// The paragraph under them.
    printer_note: [&'static str; 3],
}

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

/// The handbook in English.
const ENGLISH: Words = Words {
    handbook: "Field handbook",
    subject: "How a document asks to be opened, shown and printed",
    sections: [
        "The cover",
        "Contents",
        "What this file asks of reading software",
        "What it asks of a print dialogue",
    ],
    cover_body: [
        "This cover is page one, and it is not the page this document opens on. Reading software",
        "that honours what the file states turns straight to the contents, shows the bookmarks",
        "beside it, and stands the cover on its own — the way a book falls open with its first page",
        "facing nothing.",
    ],
    contents_body: [
        "This is the page the file opens on, and it opens showing what is drawn on it",
        "rather than the whole sheet: the words fill the window, not the paper around",
        "them. Turn to page three for the whole list of what this file asks for, and to",
        "page four for what it asks of a printer.",
    ],
    terms_lead: [
        "The link below goes to {}, and to nothing else. It works because this",
        "file states the address it was published under:",
    ],
    terms_link: "Read the full terms",
    base_note: [
        "Move this file to another address and that link breaks — unless the address",
        "moves with it. That is all a base address is for: one line to restate, instead",
        "of every relative link in the document to rewrite.",
    ],
    screen_lead: [
        "Every line below is a wish, not an instruction. Reading software whose owner has said",
        "otherwise does what its owner said, and reading software that has never heard of one",
        "of these entries ignores it and shows the file all the same.",
    ],
    screen_settings: [
        ["Opens on", "the contents page, not the cover"],
        ["Shows", "what is drawn, filling the window"],
        ["Beside the page", "the list of bookmarks"],
        ["Arranges the pages", "two at a time, page one on its own"],
        ["Window", "resized to the first page, centred on the screen"],
        ["Title bar", "the title this file states, not its file name"],
        ["Leaving full screen", "back to the bookmarks"],
    ],
    relative_links: "Relative links",
    screen_note: [
        "Nothing here is drawn on a page. Print this file and not one of these lines leaves a mark: they live",
        "in the catalogue, which is the first thing reading software reads and the last thing a printer cares",
        "about.",
    ],
    printer_lead: [
        "A print dialogue opens with something already filled in. A file may say what,",
        "which saves whoever prints it from setting the same four boxes every time.",
    ],
    printer_settings: [
        [
            "Scaling",
            "none: every page prints at the size it was drawn",
        ],
        ["Sides", "both, the sheet turned on its long edge"],
        ["Paper tray", "chosen by the size of the page"],
        ["Copies", "two"],
        ["Pages", "two to four: the cover is not worth the toner"],
    ],
    front: "front: page two",
    back: "back: page three",
    long_edge: "turned on the long edge",
    printer_note: [
        "Printing at actual size is the one that matters on a document meant to be",
        "measured: a form, a label sheet, a plan. A dialogue left to shrink the page to",
        "fit the paper is a dialogue that quietly makes every distance on it wrong.",
    ],
};

/// The handbook in French.
const FRENCH: Words = Words {
    handbook: "Manuel de terrain",
    subject: "Comment un document demande à être ouvert, affiché et imprimé",
    sections: [
        "La couverture",
        "Sommaire",
        "Ce qu'il demande au logiciel de lecture",
        "Ce qu'il demande à une boîte d'impression",
    ],
    cover_body: [
        "Cette couverture est la page un, et ce n'est pas la page sur laquelle ce document",
        "s'ouvre. Un logiciel de lecture qui honore ce que le fichier déclare va droit au sommaire,",
        "affiche les signets à côté, et laisse la couverture seule — comme un livre qui s'ouvre",
        "avec sa première page face à rien.",
    ],
    contents_body: [
        "C'est la page sur laquelle le fichier s'ouvre, et il l'ouvre en montrant ce qui",
        "y est dessiné plutôt que la feuille entière : les mots remplissent la fenêtre,",
        "pas le papier autour. Page trois pour la liste complète de ce que ce fichier",
        "demande, et page quatre pour ce qu'il demande à une imprimante.",
    ],
    terms_lead: [
        "Le lien ci-dessous va vers {}, et nulle part ailleurs. Il marche parce que",
        "ce fichier déclare l'adresse sous laquelle il a été publié :",
    ],
    terms_link: "Lire les conditions",
    base_note: [
        "Déplacez ce fichier à une autre adresse et ce lien casse — sauf si l'adresse",
        "le suit. C'est tout ce à quoi sert une adresse de base : une ligne à refaire,",
        "au lieu de tous les liens relatifs du document à réécrire.",
    ],
    screen_lead: [
        "Chaque ligne ci-dessous est un souhait, pas un ordre. Un logiciel de lecture dont le",
        "propriétaire a dit autre chose fait ce qu'il a dit, et un logiciel de lecture qui n'a jamais",
        "entendu parler d'une de ces entrées l'ignore et affiche le fichier quand même.",
    ],
    screen_settings: [
        ["S'ouvre sur", "le sommaire, pas la couverture"],
        ["Affiche", "ce qui est dessiné, plein cadre"],
        ["À côté de la page", "la liste des signets"],
        ["Dispose les pages", "deux par deux, la page un seule"],
        [
            "Fenêtre",
            "à la taille de la première page, centrée à l'écran",
        ],
        [
            "Barre de titre",
            "le titre déclaré par le fichier, pas son nom",
        ],
        ["En quittant le plein écran", "retour aux signets"],
    ],
    relative_links: "Liens relatifs",
    screen_note: [
        "Rien ici n'est dessiné sur une page. Imprimez ce fichier et pas une de ces lignes ne laisse de",
        "trace : elles vivent dans le catalogue, la première chose qu'un logiciel de lecture lit et la dernière",
        "dont une imprimante se soucie.",
    ],
    printer_lead: [
        "Une boîte d'impression s'ouvre avec quelque chose de déjà rempli. Un fichier",
        "peut dire quoi, ce qui évite de régler les mêmes quatre cases à chaque fois.",
    ],
    printer_settings: [
        [
            "Mise à l'échelle",
            "aucune : chaque page s'imprime à la taille dessinée",
        ],
        ["Faces", "les deux, feuille tournée sur son grand côté"],
        ["Bac papier", "choisi selon la taille de la page"],
        ["Copies", "deux"],
        ["Pages", "deux à quatre : la couverture ne vaut pas l'encre"],
    ],
    front: "recto : page deux",
    back: "verso : page trois",
    long_edge: "tournée sur le grand côté",
    printer_note: [
        "L'impression à taille réelle est celle qui compte sur un document fait pour",
        "être mesuré : un formulaire, une planche d'étiquettes, un plan. Une boîte qui",
        "réduit la page au papier fausse en silence toutes les distances dessus.",
    ],
};

/// 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); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// The first line above the link, which names the file the link points at.
fn terms_first_line(words: &Words) -> String {
    words.terms_lead[0].replace("{}", TERMS_FILE)
}

/// Every row of the table of what the file asks of reading software, the last
/// of which answers with the address itself.
fn screen_rows(words: &'static Words) -> Vec<[&'static str; 2]> {
    let mut rows = words.screen_settings.to_vec();
    rows.push([words.relative_links, BASE]);
    rows
}

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

/// Draws the band across the head of a page and the heading standing in it.
fn head(content: &mut Content, font: &FontHandle, heading: &str) -> Result<(), Error> {
    content.save_state();
    content.set_fill(BAND)?;
    content.rect(0.0, SHEET.1 - 96.0, SHEET.0, 96.0)?.fill();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    text(content, font, HEAD_SIZE, MARGIN, SHEET.1 - 58.0, heading)?;
    content.restore_state();
    Ok(())
}

/// Draws the hairline and the line of small print that close a page.
fn foot(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    number: &str,
) -> Result<(), Error> {
    content.save_state();
    content.set_stroke(Color::Gray(0.82))?;
    content.set_line_width(0.4)?;
    content.move_to(MARGIN, 78.0)?;
    content.line_to(SHEET.0 - MARGIN, 78.0)?;
    content.stroke();
    content.set_fill(Color::Gray(0.5))?;
    text(content, font, FOOT_SIZE, MARGIN, 62.0, words.handbook)?;
    text(
        content,
        font,
        FOOT_SIZE,
        SHEET.0 - MARGIN - 6.0,
        62.0,
        number,
    )?;
    content.restore_state();
    Ok(())
}

/// Draws a run of lines down the page from `top`, and hands back the baseline
/// the next thing would go on.
fn lines(
    content: &mut Content,
    font: &FontHandle,
    top: f64,
    size: f64,
    step: f64,
    body: &[&str],
) -> Result<f64, Error> {
    let mut y = top;
    for line in body {
        if !line.is_empty() {
            text(content, font, size, MARGIN, y, line)?;
        }
        y -= step;
    }
    Ok(y)
}

/// Draws a row of the settings table: what was asked for, and what it does.
fn setting(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    asked: &str,
    does: &str,
) -> Result<(), Error> {
    content.save_state();
    content.set_fill(BAND)?;
    text(content, font, SETTING_SIZE, MARGIN, y, asked)?;
    content.set_fill(Color::Gray(0.3))?;
    text(content, font, SETTING_SIZE, MARGIN + SETTING_GAP, y, does)?;
    content.set_stroke(Color::Gray(0.85))?;
    content.set_line_width(0.4)?;
    content.move_to(MARGIN, y - 7.0)?;
    content.line_to(SHEET.0 - MARGIN, y - 7.0)?;
    content.stroke();
    content.restore_state();
    Ok(())
}

/// The cover: the one page nobody is meant to land on.
fn cover(font: &FontHandle, words: &Words) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    content.save_state();
    content.set_fill(BAND)?;
    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,
        COVER_TITLE_SIZE,
        MARGIN,
        540.0,
        words.handbook,
    )?;
    content.set_fill(Rgb::new(0.72, 0.83, 0.86))?;
    text(
        &mut content,
        font,
        COVER_SUBJECT_SIZE,
        MARGIN,
        504.0,
        words.subject,
    )?;
    text(&mut content, font, PUBLISHER_SIZE, MARGIN, 120.0, PUBLISHER)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::new(0.72, 0.83, 0.86))?;
    lines(
        &mut content,
        font,
        420.0,
        BODY_SIZE,
        16.0,
        &words.cover_body,
    )?;
    content.restore_state();
    Ok(content.into_bytes())
}

/// Where the underlined words of the link sit, and how tall the rectangle a
/// reader may click stands. How wide it runs is not here: it is the width of
/// the words themselves, so nothing a language writes there can fall outside
/// what a reader may click.
const LINK: (f64, f64) = (290.0, 16.0);

/// The page a reader is shown for each section, in the order they are listed.
const SECTION_PAGES: [&str; 4] = ["1", "2", "3", "4"];

/// Where the two sheets of the little diagram stand.
const SKETCHES: [(f64, f64); 2] = [(MARGIN + 40.0, 216.0), (MARGIN + 260.0, 216.0)];

/// Draws the list of sections, each under a hairline, and hands back the
/// baseline the next thing would go on.
fn section_list(content: &mut Content, font: &FontHandle, words: &Words) -> Result<f64, Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.25))?;
    let mut y = SHEET.1 - 160.0;
    for (item, page) in words.sections.iter().zip(SECTION_PAGES) {
        text(content, font, SECTION_SIZE, MARGIN, y, item)?;
        text(
            content,
            font,
            SECTION_SIZE,
            SHEET.0 - MARGIN - 10.0,
            y,
            page,
        )?;
        content.save_state();
        content.set_stroke(Color::Gray(0.85))?;
        content.set_line_width(0.4)?;
        content.move_to(MARGIN, y - 7.0)?;
        content.line_to(SHEET.0 - MARGIN, y - 7.0)?;
        content.stroke();
        content.restore_state();
        y -= 34.0;
    }
    content.restore_state();
    Ok(y)
}

/// Draws the base address, and the underlined words the link is laid over.
fn terms(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    let (y, _) = LINK;
    let width = font.measure(words.terms_link, SECTION_SIZE);
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    text(
        content,
        font,
        BODY_SIZE,
        MARGIN,
        y + 72.0,
        &terms_first_line(words),
    )?;
    text(
        content,
        font,
        BODY_SIZE,
        MARGIN,
        y + 56.0,
        words.terms_lead[1],
    )?;
    content.set_fill(BAND)?;
    text(content, font, BODY_SIZE, MARGIN, y + 34.0, BASE)?;
    content.set_fill(Rgb::new(0.10, 0.35, 0.65))?;
    text(
        content,
        font,
        SECTION_SIZE,
        MARGIN,
        y + 4.0,
        words.terms_link,
    )?;
    content.set_stroke(Rgb::new(0.10, 0.35, 0.65))?;
    content.set_line_width(0.6)?;
    content.move_to(MARGIN, y)?;
    content.line_to(MARGIN + width, y)?;
    content.stroke();
    content.restore_state();
    Ok(())
}

/// The contents page: what the document opens on, and the one relative link.
fn contents(font: &FontHandle, words: &Words) -> Result<(Vec<u8>, Link), Error> {
    let mut content = Content::new();
    head(&mut content, font, words.sections[1])?;
    let y = section_list(&mut content, font, words)?;

    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    lines(
        &mut content,
        font,
        y - 66.0,
        BODY_SIZE,
        16.0,
        &words.contents_body,
    )?;
    content.restore_state();

    terms(&mut content, font, words)?;

    content.save_state();
    content.set_fill(Color::Gray(0.45))?;
    lines(&mut content, font, 170.0, NOTE_SIZE, 14.0, &words.base_note)?;
    content.restore_state();
    foot(&mut content, font, words, SECTION_PAGES[1])?;

    let link = Link::new(
        MARGIN,
        LINK.0,
        font.measure(words.terms_link, SECTION_SIZE),
        LINK.1,
        LinkTarget::Uri(TERMS_FILE.to_owned()),
    );
    Ok((content.into_bytes(), link))
}

/// What the file asks of reading software on the screen.
fn on_screen(font: &FontHandle, words: &'static Words) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    head(&mut content, font, words.sections[2])?;

    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    let mut y = lines(
        &mut content,
        font,
        SHEET.1 - 148.0,
        BODY_SIZE,
        16.0,
        &words.screen_lead,
    )?;
    content.restore_state();

    y -= 24.0;
    for [asked, does] in screen_rows(words) {
        setting(&mut content, font, y, asked, does)?;
        y -= 44.0;
    }

    content.save_state();
    content.set_fill(Color::Gray(0.45))?;
    lines(
        &mut content,
        font,
        160.0,
        NOTE_SIZE,
        14.0,
        &words.screen_note,
    )?;
    content.restore_state();
    foot(&mut content, font, words, SECTION_PAGES[2])?;
    Ok(content.into_bytes())
}

/// Draws one sheet of the little diagram: an outline, a band marking its head,
/// and a caption under it.
fn sheet_sketch(
    content: &mut Content,
    font: &FontHandle,
    corner: (f64, f64),
    caption: &str,
) -> Result<(), Error> {
    let (x, y) = corner;
    content.save_state();
    content.set_stroke(Color::Gray(0.55))?;
    content.set_line_width(0.8)?;
    content.rect(x, y, 84.0, 118.0)?.stroke();
    content.set_fill(BAND)?;
    content.rect(x + 8.0, y + 96.0, 68.0, 14.0)?.fill();
    content.set_fill(Color::Gray(0.45))?;
    text(content, font, SKETCH_SIZE, x, y - 14.0, caption)?;
    content.restore_state();
    Ok(())
}

/// Draws what turning a sheet on its long edge does: the back of the sheet
/// stands the same way up as its front.
fn long_edge(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    sheet_sketch(content, font, SKETCHES[0], words.front)?;
    sheet_sketch(content, font, SKETCHES[1], words.back)?;

    content.save_state();
    content.set_stroke(Color::Gray(0.55))?;
    content.set_line_width(1.2)?;
    content.move_to(MARGIN + 146.0, 275.0)?;
    content.line_to(MARGIN + 246.0, 275.0)?;
    content.line_to(MARGIN + 234.0, 283.0)?;
    content.move_to(MARGIN + 246.0, 275.0)?;
    content.line_to(MARGIN + 234.0, 267.0)?;
    content.stroke();
    content.set_fill(Color::Gray(0.45))?;
    text(
        content,
        font,
        SKETCH_SIZE,
        MARGIN + 148.0,
        291.0,
        words.long_edge,
    )?;
    content.restore_state();
    Ok(())
}

/// What the file asks of the print dialogue.
fn at_the_printer(font: &FontHandle, words: &Words) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    head(&mut content, font, words.sections[3])?;

    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    let mut y = lines(
        &mut content,
        font,
        SHEET.1 - 148.0,
        BODY_SIZE,
        16.0,
        &words.printer_lead,
    )?;
    content.restore_state();

    y -= 24.0;
    for [asked, does] in words.printer_settings {
        setting(&mut content, font, y, asked, does)?;
        y -= 44.0;
    }

    long_edge(&mut content, font, words)?;

    content.save_state();
    content.set_fill(Color::Gray(0.45))?;
    lines(
        &mut content,
        font,
        160.0,
        NOTE_SIZE,
        14.0,
        &words.printer_note,
    )?;
    content.restore_state();
    foot(&mut content, font, words, SECTION_PAGES[3])?;
    Ok(content.into_bytes())
}

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

#[allow(clippy::expect_used, reason = "the count of copies is not zero")]
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("handbook")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let mut facts = Metadata::default();
    facts.title = Some(words.handbook.to_owned());
    facts.author = Some(PUBLISHER.to_owned());
    facts.subject = Some(words.subject.to_owned());
    doc.set_metadata(facts);
    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);

    let mut first = Page::new(SHEET.0, SHEET.1);
    first.content = cover(&font, words)?;
    doc.add_page(first)?;

    let (drawn, link) = contents(&font, words)?;
    let mut second = Page::new(SHEET.0, SHEET.1);
    second.content = drawn;
    second.links.push(link);
    doc.add_page(second)?;

    let mut third = Page::new(SHEET.0, SHEET.1);
    third.content = on_screen(&font, words)?;
    doc.add_page(third)?;

    let mut fourth = Page::new(SHEET.0, SHEET.1);
    fourth.content = at_the_printer(&font, words)?;
    doc.add_page(fourth)?;

    for (page, title) in words.sections.iter().enumerate() {
        doc.add_bookmark(Bookmark::new(*title, page));
    }

    // The document opens on its contents, filled with what is drawn there, with
    // the bookmarks beside it and the cover standing on its own.
    doc.set_open_action(OpenAction::new(1).view(PageFit::WholeDrawing));
    doc.set_open_mode(OpenMode::Bookmarks);
    doc.set_page_layout(PageLayout::TwoPagesOddRight);
    doc.set_base_uri(BASE);
    doc.set_viewer_preferences(
        ViewerPreferences::new()
            .fit_window(true)
            .center_window(true)
            .show_title(true)
            .after_full_screen(SidePanel::Bookmarks)
            .print_scaling(PrintScaling::ActualSize)
            .duplex(Duplex::LongEdge)
            .tray_by_page_size(true)
            .copies(NonZeroU32::new(COPIES).expect("the count of copies is not zero"))
            .print_run(PRINT_RUN.0..=PRINT_RUN.1),
    );

    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, {} pages, and a catalogue that says how to open, \
         show and print them",
        written.len(),
        doc.page_count()
    );
    Ok(())
}

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

    use super::{
        BODY_SIZE, COPIES, COVER_SUBJECT_SIZE, COVER_TITLE_SIZE, HEAD_SIZE, MARGIN, NOTE_SIZE,
        PRINT_RUN, SECTION_SIZE, SETTING_GAP, SETTING_SIZE, SHEET, SKETCH_SIZE, WORDS, Words,
        default_font, language, screen_rows, terms_first_line,
    };

    /// The lines two languages are allowed to write the same way. Both call a
    /// copy a copy and a page a page.
    const SPARED: [&str; 2] = ["\"Copies\"", "\"Pages\""];

    /// The font every measurement here is taken in, which is the one the
    /// example draws with when the command line says nothing.
    fn font(document: &mut Document) -> FontHandle {
        document.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        )
    }

    /// Every line the handbook draws where it is asked to, each with the size
    /// it is set at and the room it has before it reaches whatever stands to
    /// its right.
    fn lines(words: &'static Words) -> Vec<(String, f64, f64)> {
        // A line set from the left margin runs until the margin on the other
        // side of the sheet.
        let paper = SHEET.0 - MARGIN - MARGIN;
        // What a setting asks for stands in the room before what it does; what
        // it does runs to the far margin.
        let asked_room = SETTING_GAP;
        let does_room = paper - SETTING_GAP;

        let mut measured = vec![
            (words.handbook.to_owned(), COVER_TITLE_SIZE, paper),
            (words.subject.to_owned(), COVER_SUBJECT_SIZE, paper),
            (terms_first_line(words), BODY_SIZE, paper),
            (words.terms_lead[1].to_owned(), BODY_SIZE, paper),
            (words.front.to_owned(), SKETCH_SIZE, 200.0),
            (words.back.to_owned(), SKETCH_SIZE, 200.0),
            (words.long_edge.to_owned(), SKETCH_SIZE, 200.0),
        ];
        // A section is listed with its page number against the far margin, and
        // the two must not meet.
        for section in words.sections {
            measured.push((section.to_owned(), SECTION_SIZE, paper - 20.0));
        }
        // The heading of a page stands in the band across its head.
        for section in [words.sections[1], words.sections[2], words.sections[3]] {
            measured.push((section.to_owned(), HEAD_SIZE, paper));
        }
        for body in [
            words.cover_body.as_slice(),
            words.contents_body.as_slice(),
            words.screen_lead.as_slice(),
            words.printer_lead.as_slice(),
        ] {
            for line in body {
                measured.push(((*line).to_owned(), BODY_SIZE, paper));
            }
        }
        for note in [
            words.base_note.as_slice(),
            words.screen_note.as_slice(),
            words.printer_note.as_slice(),
        ] {
            for line in note {
                measured.push(((*line).to_owned(), NOTE_SIZE, paper));
            }
        }
        for [asked, does] in screen_rows(words).into_iter().chain(words.printer_settings) {
            measured.push((asked.to_owned(), SETTING_SIZE, asked_room));
            measured.push((does.to_owned(), SETTING_SIZE, does_room));
        }
        measured
    }

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

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

    /// Nothing here is broken to a width: every line is drawn where it is asked
    /// for, so one longer than its room runs over the column beside it or off
    /// the sheet.
    #[test]
    fn every_language_writes_lines_that_fit_the_room_they_have() {
        let mut document = Document::new();
        let font = font(&mut document);

        for (named, words) in WORDS {
            for (line, size, room) in lines(words) {
                let measured = font.measure(&line, size);

                assert!(
                    measured <= room,
                    "the {} handbook draws {line:?} over {measured:.1} points, \
                     and it has {room:.1}",
                    named.code()
                );
            }
        }
    }

    /// Two rows of the print table spell a number out in words, which no
    /// language can work out from the setting. Changing either has to send
    /// whoever changes it back to every language.
    #[test]
    fn the_numbers_the_print_table_spells_out_are_the_numbers_that_are_asked_for() {
        assert_eq!(
            COPIES, 2,
            "a row of the table calls the count of copies two"
        );
        assert_eq!(
            (PRINT_RUN.0 + 1, PRINT_RUN.1 + 1),
            (2, 4),
            "a row of the table calls the run of pages two to four"
        );
    }
}