write_provenance.rs

Die Rust-Datei des Beispiels „Ein Register, dessen Seiten sagen, woher sie stammen“. Zwei Sitzungen in einer Datei gebunden. Jede Seite trägt einen eigenen Vermerk — was sie ist, wessen Hand sie geschrieben hat, der Tag, an dem sie geschrieben wurde —, das Foto auf der zweiten Seite trägt ebenfalls einen, und jede Transkription ist an die Seite gebunden, die sie transkribiert, statt an die Datei insgesamt.

Rust 919 Zeilen

Wofür dieses Beispiel da ist

Eine Datei sagt einmal, was sie ist, für die ganze Datei: ein Titel, ein Autor, ein Datum. Für einen Brief genügt das. Über etwas, das aus Teilen gebunden ist, sagt es nichts Brauchbares — ein Register aus zwei Sitzungen, die Jahre auseinanderliegen, oder ein Scan, dessen Foto jemand anderem gehört als dem, der das Papier besitzt. Wer eine alte Sammlung digitalisiert, stößt bereits beim ersten Karton darauf.

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
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
//! A file whose every part says where it came from.
//!
//! A document says what it is, and that has always been written once, for the
//! whole file. It is not enough for anything assembled out of pieces: a
//! register bound from two sittings, a scan whose plate belongs to somebody
//! other than whoever holds the paper. Here each page carries a packet of its
//! own, the plate on the second page carries one too, and the transcription of
//! each sitting is tied to the page it transcribes rather than to the file at
//! large. A paperclip in the top corner of each page opens that transcription.
//!
//! Tying a carried file to anything but the document as a whole arrived with
//! PDF 2.0, so the file declares 2.0. Nothing is raised on the caller's behalf:
//! a file that tied one while declaring less would be refused rather than
//! written.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the register is bound in. Every one of them is written twice: once
//! on the page and once in the packet the page carries, from the one set, so
//! that what a person reads and what a machine reads cannot drift apart. What
//! is not a word stands apart from them — the names the carried files are
//! looked up by, the clerks' own names, and the dates the sittings were written
//! down.
//!
//! Usage: `cargo run --example write_provenance -- tmp/provenance.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_provenance --
//! tmp/provenance_fr.pdf`

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

use hqf_pdf::annotation::{AttachmentIcon, FileAttachment};
use hqf_pdf::content::Content;
use hqf_pdf::metadata::attachment::{Attachment, Relationship};
use hqf_pdf::metadata::xmp::{Metadata, Xmp};
use hqf_pdf::{
    AttachmentHandle, Color, Document, Error, Font, FontHandle, Image, ImageHandle, Page, Rgb,
    Version,
};

#[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;

/// How far in from the left edge what a part says stands, leaving the label to
/// its left.
const SAID: f64 = 220.0;

/// How wide the plate is drawn on the page, in points.
const PLATE: f64 = 180.0;

/// The name the record of the scan is carried under.
const SCAN: &str = "plate-12-scan.xml";

/// One sitting of the register: who wrote it down, when, and the name its
/// transcription is carried under. What the page says of it is a word, and
/// stands in [`Words`] under the same order.
struct Sitting {
    /// Who wrote what is on it, before what such a person is called.
    hand: &'static str,
    /// When it was written down, as the packet states it.
    written: &'static str,
    /// The name the transcription of this sitting is carried under.
    transcript: &'static str,
}

/// The two sittings the register is bound from.
const SITTINGS: [Sitting; 2] = [
    Sitting {
        hand: "R. Delaunay",
        written: "1911-03-14T09:00:00+01:00",
        transcript: "first-sitting.xml",
    },
    Sitting {
        hand: "M. Aubert",
        written: "1911-06-02T14:30:00+02:00",
        transcript: "second-sitting.xml",
    },
];

/// The words the register is bound in, one set per language.
#[derive(Debug)]
struct Words {
    /// What the file says it is.
    title: &'static str,
    /// What each sitting is called, in its band and in its own packet.
    sittings: [&'static str; 2],
    /// What whoever wrote a sitting down is called, set after their name.
    clerk: &'static str,
    /// What a page says it is about.
    subject: &'static str,
    /// What each page says under its band.
    lines: [[&'static str; 3]; 2],
    /// The heading over what a page says of itself, the one over what the file
    /// carries, and the one over what the plate says of itself.
    headings: [&'static str; 3],
    /// What a part is asked about: its title, the hand that wrote it, when it
    /// was written, and the file tied to it.
    asked: [&'static str; 4],
    /// What claims each carried file, in the order they are carried.
    claimed_by: [&'static str; 3],
    /// The row that says the file at large claims none of them.
    at_large: [&'static str; 2],
    /// What the plate is called, on the page and in its own packet.
    plate: &'static str,
    /// What the plate is asked, and who answers to it.
    holder: [&'static str; 2],
    /// What the plate says it is about.
    plate_subject: &'static str,
    /// What each carried file says it is: a transcription, and the record of a
    /// scan.
    carried: [&'static str; 2],
    /// The closing note at the foot of the last page.
    closing: [&'static str; 4],
}

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

    /// Who wrote the sitting at `index` down: their name, then what such a
    /// person is called.
    fn hand(&self, index: usize) -> String {
        format!("{}, {}", SITTINGS[index].hand, self.clerk)
    }
}

/// The register in English.
const ENGLISH: Words = Words {
    title: "A register bound from two sittings",
    sittings: ["First sitting", "Second sitting"],
    clerk: "clerk",
    subject: "One sitting of the register",
    lines: [
        [
            "This page carries a packet of its own, saying what it is, whose hand",
            "wrote it and when. The file says nothing on its behalf: read the page",
            "out of the file and what it says travels with it.",
        ],
        [
            "The plate below is a part in its own right. It says who holds it, which",
            "is not who holds the paper, and it carries the record of the scan it",
            "came off — tied to the plate, not to the file.",
        ],
    ],
    headings: [
        "What this page says about itself",
        "What this file carries, and which part claims it",
        "What the plate says about itself",
    ],
    asked: [
        "Its title",
        "The hand that wrote it",
        "When it was written",
        "The file tied to it",
    ],
    claimed_by: [
        "The first page",
        "The second page",
        "The plate on the second page",
    ],
    at_large: ["Claimed by the file at large", "nothing"],
    plate: "Plate 12, second sitting",
    holder: ["Who holds it", "Departmental archive"],
    plate_subject: "The plate, which is held apart from the paper",
    carried: ["The sitting, transcribed", "How the plate was scanned"],
    closing: [
        "Every carried file is offered to every reader through the list of embedded",
        "files, whichever part of the document claims it. What the tie adds is which",
        "part it belongs to — and a file one part claims leaves the tie the document",
        "itself holds, so nothing is ever said to belong to two things at once.",
    ],
};

/// The register in French.
const FRENCH: Words = Words {
    title: "Deux séances reliées en un registre",
    sittings: ["Première séance", "Deuxième séance"],
    clerk: "greffier",
    subject: "Une séance du registre",
    lines: [
        [
            "Cette page a son propre paquet, qui dit ce qu’elle est, quelle",
            "main l’a écrite et quand. Le fichier ne parle pas pour elle :",
            "sortez la page du fichier, ce qu’elle dit part avec elle.",
        ],
        [
            "La planche ci-dessous est une pièce à part entière. Elle dit qui la",
            "détient, qui n’est pas le détenteur du papier, et elle comporte le",
            "relevé de la numérisation dont elle est issue — lié à elle, pas au fichier.",
        ],
    ],
    headings: [
        "Ce que cette page dit d’elle-même",
        "Ce que ce fichier contient, et quelle partie le revendique",
        "Ce que la planche dit d’elle-même",
    ],
    asked: [
        "Son titre",
        "La main qui l’a écrite",
        "Quand elle a été écrite",
        "Le fichier qui lui est lié",
    ],
    claimed_by: [
        "La première page",
        "La deuxième page",
        "La planche de la deuxième page",
    ],
    at_large: ["Revendiqué par le fichier entier", "rien"],
    plate: "Planche 12, deuxième séance",
    holder: ["Qui la détient", "Archives départementales"],
    plate_subject: "La planche, détenue séparément du papier",
    carried: [
        "La séance, transcrite",
        "Comment la planche a été numérisée",
    ],
    closing: [
        "Chaque fichier joint est proposé à tout lecteur par la liste des pièces",
        "jointes, quelle que soit la partie du document qui le revendique. Le lien",
        "indique à quelle partie il appartient — et un fichier qu’une partie revendique",
        "quitte le lien du document : rien n’appartient jamais à deux choses à la fois.",
    ],
};

/// The register in Dutch.
const DUTCH: Words = Words {
    title: "Een register gebonden uit twee zittingen",
    sittings: ["Eerste zitting", "Tweede zitting"],
    clerk: "griffier",
    subject: "Eén zitting van het register",
    lines: [
        [
            "Deze pagina heeft een eigen pakket, dat zegt wat ze is, wiens hand",
            "haar schreef en wanneer. Het bestand zegt niets namens haar: haal de pagina",
            "uit het bestand en wat ze zegt reist met haar mee.",
        ],
        [
            "De plaat hieronder is een deel op zichzelf. Ze zegt wie haar beheert,",
            "en dat is niet wie het papier beheert, en ze bevat het verslag van de scan",
            "waar ze vandaan komt, gekoppeld aan de plaat, niet aan het bestand.",
        ],
    ],
    headings: [
        "Wat deze pagina over zichzelf zegt",
        "Wat dit bestand bevat, en welk deel het claimt",
        "Wat de plaat over zichzelf zegt",
    ],
    asked: [
        "De titel",
        "De hand die haar schreef",
        "Wanneer ze geschreven is",
        "Het eraan gekoppelde bestand",
    ],
    claimed_by: [
        "De eerste pagina",
        "De tweede pagina",
        "De plaat op de tweede pagina",
    ],
    at_large: ["Geclaimd door het bestand als geheel", "niets"],
    plate: "Plaat 12, tweede zitting",
    holder: ["Wie haar beheert", "Departementaal archief"],
    plate_subject: "De plaat, die apart van het papier bewaard wordt",
    carried: ["De zitting, uitgeschreven", "Hoe de plaat gescand is"],
    closing: [
        "Elk bijgevoegd bestand wordt aan elke lezer aangeboden via de lijst van ingesloten",
        "bestanden, welk deel van het document het ook claimt. De koppeling voegt toe bij welk",
        "deel het hoort, en een bestand dat een deel claimt, verlaat de koppeling van het",
        "document zelf, dus wordt nooit gezegd dat iets bij twee dingen tegelijk hoort.",
    ],
};

/// The register in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Um registo encadernado de duas sessões",
    sittings: ["Primeira sessão", "Segunda sessão"],
    clerk: "escrivão",
    subject: "Uma sessão do registo",
    lines: [
        [
            "Esta página leva um pacote próprio, que diz o que é, de que mão",
            "é e quando. O ficheiro não diz nada em seu nome: tire a página",
            "do ficheiro e o que ela diz viaja com ela.",
        ],
        [
            "A estampa abaixo é uma parte de pleno direito. Diz quem a guarda,",
            "que não é quem guarda o papel, e leva o registo da digitalização",
            "de onde saiu, ligado à estampa e não ao ficheiro.",
        ],
    ],
    headings: [
        "O que esta página diz de si mesma",
        "O que este ficheiro leva, e que parte o reclama",
        "O que a estampa diz de si mesma",
    ],
    asked: [
        "O seu título",
        "A mão que a escreveu",
        "Quando foi escrita",
        "O ficheiro ligado a ela",
    ],
    claimed_by: [
        "A primeira página",
        "A segunda página",
        "A estampa da segunda página",
    ],
    at_large: ["Reclamado pelo ficheiro no seu todo", "nada"],
    plate: "Estampa 12, segunda sessão",
    holder: ["Quem a guarda", "Arquivo distrital"],
    plate_subject: "A estampa, guardada à parte do papel",
    carried: ["A sessão, transcrita", "Como a estampa foi digitalizada"],
    closing: [
        "Cada ficheiro incluído é dado a qualquer leitor pela lista de ficheiros incorporados,",
        "seja qual for a parte do documento que o reclame. A ligação acrescenta a que parte",
        "pertence, e um ficheiro que uma parte reclama sai da ligação que o próprio documento",
        "guarda, por isso nunca se diz que algo pertence a duas coisas ao mesmo tempo.",
    ],
};

/// The register in Italian.
const ITALIAN: Words = Words {
    title: "Un registro rilegato da due sedute",
    sittings: ["Prima seduta", "Seconda seduta"],
    clerk: "cancelliere",
    subject: "Una seduta del registro",
    lines: [
        [
            "Questa pagina porta un pacchetto proprio, che dice cos’è, di quale mano",
            "è e quando. Il file non dice nulla per lei: estraete la pagina",
            "dal file e ciò che dice viaggia con essa.",
        ],
        [
            "La tavola qui sotto è una parte a pieno titolo. Dice chi la custodisce,",
            "che non è chi custodisce la carta, e porta la registrazione della scansione",
            "da cui viene, legata alla tavola e non al file.",
        ],
    ],
    headings: [
        "Ciò che questa pagina dice di sé",
        "Ciò che porta questo file, e quale parte lo rivendica",
        "Ciò che la tavola dice di sé",
    ],
    asked: [
        "Il suo titolo",
        "La mano che l’ha scritta",
        "Quando è stata scritta",
        "Il file legato a essa",
    ],
    claimed_by: [
        "La prima pagina",
        "La seconda pagina",
        "La tavola della seconda pagina",
    ],
    at_large: ["Rivendicato dal file nel suo insieme", "nulla"],
    plate: "Tavola 12, seconda seduta",
    holder: ["Chi la custodisce", "Archivio dipartimentale"],
    plate_subject: "La tavola, custodita separatamente dalla carta",
    carried: [
        "La seduta, trascritta",
        "Come è stata scansionata la tavola",
    ],
    closing: [
        "Ogni file incorporato è offerto a ogni lettore dall’elenco dei file incorporati,",
        "qualunque parte del documento lo rivendichi. Il legame aggiunge a quale parte",
        "appartiene, e un file rivendicato da una parte esce dal legame che tiene il documento",
        "stesso, così non si dice mai che qualcosa appartenga a due cose insieme.",
    ],
};

/// The register in Spanish.
const SPANISH: Words = Words {
    title: "Un registro encuadernado de dos sesiones",
    sittings: ["Primera sesión", "Segunda sesión"],
    clerk: "escribano",
    subject: "Una sesión del registro",
    lines: [
        [
            "Esta página lleva un paquete propio que dice qué es, de qué mano",
            "salió y cuándo. El archivo no dice nada en su nombre: saque la página",
            "del archivo y lo que dice viaja con ella.",
        ],
        [
            "La lámina de abajo es una parte por derecho propio. Dice quién la custodia,",
            "que no es quien custodia el papel, y lleva el registro del escaneo del",
            "que salió, atado a la lámina y no al archivo.",
        ],
    ],
    headings: [
        "Lo que esta página dice de sí misma",
        "Lo que lleva este archivo, y qué parte lo reclama",
        "Lo que la lámina dice de sí misma",
    ],
    asked: [
        "Su título",
        "La mano que la escribió",
        "Cuándo se escribió",
        "El archivo atado a ella",
    ],
    claimed_by: [
        "La primera página",
        "La segunda página",
        "La lámina de la segunda página",
    ],
    at_large: ["Reclamado por el archivo entero", "nada"],
    plate: "Lámina 12, segunda sesión",
    holder: ["Quién la custodia", "Archivo departamental"],
    plate_subject: "La lámina, que se guarda aparte del papel",
    carried: ["La sesión, transcrita", "Cómo se escaneó la lámina"],
    closing: [
        "Cada archivo incrustado se ofrece al lector en la lista de archivos incrustados,",
        "sea cual sea la parte del documento que lo reclame. El vínculo añade a qué parte",
        "pertenece, y un archivo que reclama una parte sale del vínculo que guarda el propio",
        "documento, así que nunca se dice que algo pertenezca a dos cosas a la vez.",
    ],
};

/// The register in German.
const GERMAN: Words = Words {
    title: "Ein aus zwei Sitzungen gebundenes Register",
    sittings: ["Erste Sitzung", "Zweite Sitzung"],
    clerk: "Schreiber",
    subject: "Eine Sitzung des Registers",
    lines: [
        [
            "Diese Seite trägt ein eigenes Paket, das sagt, was sie ist, wessen",
            "Hand sie schrieb und wann. Die Datei spricht nicht für sie: Wer die",
            "Seite aus der Datei holt, nimmt mit, was sie sagt.",
        ],
        [
            "Die Tafel unten ist ein eigener Teil. Sie sagt, wer sie verwahrt,",
            "(ein anderer als der, der das Papier verwahrt), und trägt den Nachweis",
            "ihres Scans — an die Tafel gebunden, nicht an die Datei.",
        ],
    ],
    headings: [
        "Was diese Seite über sich sagt",
        "Was diese Datei trägt und welcher Teil es beansprucht",
        "Was die Tafel über sich sagt",
    ],
    asked: [
        "Ihr Titel",
        "Die Hand, die sie schrieb",
        "Wann sie geschrieben wurde",
        "Die daran gebundene Datei",
    ],
    claimed_by: [
        "Die erste Seite",
        "Die zweite Seite",
        "Die Tafel auf der zweiten Seite",
    ],
    at_large: ["Von der Datei insgesamt beansprucht", "nichts"],
    plate: "Tafel 12, zweite Sitzung",
    holder: ["Wer sie verwahrt", "Abteilungsarchiv"],
    plate_subject: "Die Tafel, getrennt vom Papier verwahrt",
    carried: ["Die Sitzung, abgeschrieben", "Wie die Tafel gescannt wurde"],
    closing: [
        "Jede mitgeführte Datei wird jedem Leser über die Liste der eingebetteten",
        "Dateien angeboten, welcher Teil des Dokuments sie auch beansprucht. Die Bindung",
        "sagt, zu welchem Teil sie gehört — und eine von einem Teil beanspruchte Datei",
        "verlässt die Bindung des Dokuments, also gehört nichts je zwei Dingen zugleich.",
    ],
};

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

/// The plate: a square of grey read off a pattern, so that the example needs no
/// file beside it.
fn plate() -> Result<Image, Error> {
    let side: u32 = 64;
    let mut samples = Vec::with_capacity((side * side) as usize);
    for down in 0..side {
        for across in 0..side {
            let value = ((across * 4) ^ (down * 4)) & 0xFF;
            samples.push(u8::try_from(value).unwrap_or(u8::MAX));
        }
    }
    Image::from_gray(side, side, &samples)
}

/// The band across the head of a page, and the lines under it.
fn head(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    index: usize,
) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Rgb::new(0.16, 0.20, 0.26))?;
    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,
        20.0,
        MARGIN,
        SHEET.1 - 58.0,
        words.sittings[index],
    )?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.25))?;
    let mut y = SHEET.1 - 140.0;
    for line in words.lines[index] {
        text(content, font, 11.0, MARGIN, y, line)?;
        y -= 18.0;
    }
    content.restore_state();
    Ok(())
}

/// What one part of the file says about itself, set as a pair of columns.
fn says(
    content: &mut Content,
    font: &FontHandle,
    top: f64,
    heading: &str,
    rows: &[(&str, &str)],
) -> Result<(), Error> {
    content.save_state();
    content.set_stroke(Color::Gray(0.82))?;
    content.set_line_width(0.4)?;
    content.move_to(MARGIN, top)?;
    content.line_to(SHEET.0 - MARGIN, top)?;
    content.stroke();
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.1))?;
    text(content, font, 13.0, MARGIN, top - 28.0, heading)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.3))?;
    let mut y = top - 56.0;
    for (said, written) in rows {
        text(content, font, 11.0, MARGIN, y, said)?;
        text(content, font, 10.0, MARGIN + SAID, y, written)?;
        y -= 20.0;
    }
    content.restore_state();
    Ok(())
}

/// The closing note, set at the foot of the last page.
fn foot(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.45))?;
    let mut y = 178.0;
    for line in words.closing {
        text(content, font, 10.5, MARGIN, y, line)?;
        y -= 17.0;
    }
    content.set_fill(Color::Gray(0.5))?;
    text(content, font, 8.0, MARGIN, 62.0, "HQF Development")?;
    content.restore_state();
    Ok(())
}

/// The first page: what it says of itself, and the transcription tied to it.
fn first_sheet(font: &FontHandle, words: &Words) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    head(&mut content, font, words, 0)?;
    let hand = words.hand(0);
    says(
        &mut content,
        font,
        SHEET.1 - 220.0,
        words.headings[0],
        &[
            (words.asked[0], words.sittings[0]),
            (words.asked[1], &hand),
            (words.asked[2], SITTINGS[0].written),
            (words.asked[3], SITTINGS[0].transcript),
        ],
    )?;
    says(
        &mut content,
        font,
        SHEET.1 - 380.0,
        words.headings[1],
        &[
            (SITTINGS[0].transcript, words.claimed_by[0]),
            (SITTINGS[1].transcript, words.claimed_by[1]),
            (SCAN, words.claimed_by[2]),
            (words.at_large[0], words.at_large[1]),
        ],
    )?;
    Ok(content.into_bytes())
}

/// The second page: the plate, what the plate says of itself, and the note.
fn second_sheet(font: &FontHandle, plate: &ImageHandle, words: &Words) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    head(&mut content, font, words, 1)?;

    let top = SHEET.1 - 220.0;
    content.draw_image(plate, MARGIN, top - PLATE, PLATE, PLATE)?;
    content.save_state();
    content.set_stroke(Color::Gray(0.7))?;
    content.set_line_width(0.5)?;
    content.rect(MARGIN, top - PLATE, PLATE, PLATE)?.stroke();
    content.set_fill(Color::Gray(0.45))?;
    text(
        &mut content,
        font,
        9.0,
        MARGIN,
        top - PLATE - 14.0,
        words.plate,
    )?;
    content.restore_state();

    says(
        &mut content,
        font,
        top - PLATE - 44.0,
        words.headings[2],
        &[
            (words.asked[0], words.plate),
            (words.holder[0], words.holder[1]),
            (words.asked[3], SCAN),
        ],
    )?;
    foot(&mut content, font, words)?;
    Ok(content.into_bytes())
}

/// The packet a page speaks in: what it is, whose hand wrote it, and when.
fn said_by(words: &Words, index: usize) -> Xmp {
    let mut facts = Metadata::default();
    facts.title = Some(words.sittings[index].to_owned());
    facts.author = Some(words.hand(index));
    facts.subject = Some(words.subject.to_owned());
    facts.created = Some(SITTINGS[index].written.to_owned());
    Xmp::facts(facts)
}

/// A transcription carried inside the file, under the name it is looked up by.
fn transcription(words: &Words, index: usize) -> Attachment {
    Attachment::new(
        SITTINGS[index].transcript,
        words.carried[0],
        "text/xml",
        Relationship::Alternative,
        SITTINGS[index].written,
        format!("<sitting hand=\"{}\"/>\n", words.hand(index)).into_bytes(),
    )
}

/// A paperclip in the top corner of the sheet opening `file`, which says what
/// it opens.
fn paperclip(file: AttachmentHandle, words: &Words) -> FileAttachment {
    FileAttachment::new(SHEET.0 - 56.0, SHEET.1 - 56.0, file)
        .icon(AttachmentIcon::Paperclip)
        .contents(words.carried[0])
}

/// The two pages, each carrying its own packet and the file tied to it.
fn bind(
    doc: &mut Document,
    font: &FontHandle,
    plate: &ImageHandle,
    words: &Words,
    carried: [AttachmentHandle; 2],
) -> Result<(), Error> {
    let mut first = Page::new(SHEET.0, SHEET.1);
    first.content = first_sheet(font, words)?;
    first.metadata = Some(said_by(words, 0));
    first.associated_files = vec![carried[0]];
    first.annotations.push(paperclip(carried[0], words).into());
    doc.add_page(first)?;

    let mut second = Page::new(SHEET.0, SHEET.1);
    second.content = second_sheet(font, plate, words)?;
    second.metadata = Some(said_by(words, 1));
    second.associated_files = vec![carried[1]];
    second.annotations.push(paperclip(carried[1], words).into());
    doc.add_page(second)?;
    Ok(())
}

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("provenance")));
    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)?)?);

    // Each transcription is claimed by the page it transcribes; the record of
    // the scan is claimed by the plate itself. Nothing here is claimed by the
    // file at large, so the file ties nothing to its catalogue.
    let carried = [
        doc.attach(transcription(words, 0)),
        doc.attach(transcription(words, 1)),
    ];
    let scan = doc.attach(Attachment::new(
        SCAN,
        words.carried[1],
        "text/xml",
        Relationship::Supplement,
        "2026-02-19T11:05:00+01:00",
        b"<scan dpi=\"600\" bits=\"8\"/>\n".to_vec(),
    ));

    let mut said = Metadata::default();
    said.title = Some(words.plate.to_owned());
    said.author = Some(words.holder[1].to_owned());
    said.subject = Some(words.plate_subject.to_owned());
    let plate = doc.add_image(
        plate()?
            .with_metadata(Some(Xmp::facts(said)))
            .associated_with(&[scan]),
    );

    bind(&mut doc, &font, &plate, words, carried)?;

    // Tying a carried file to anything but the document as a whole is ISO
    // 32000-2, so the file says 2.0 on its first line.
    doc.set_version(Version::V2_0);
    let mut facts = Metadata::default();
    facts.title = Some(words.title.to_owned());
    facts.producer = Some("hqf-pdf".to_owned());
    doc.set_metadata(facts);

    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, every part saying where it came from",
        written.len()
    );
    Ok(())
}

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

    use super::{MARGIN, SAID, SHEET, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way. Every line in
    /// `Words` is drawn on a page and written into a packet, and two languages
    /// write one alike only where they spell it alike; the names the carried
    /// files are looked up by, the clerks' names and the dates are not in
    /// `Words` at all.
    const SPARED: [&str; 1] = [
        // Written the same way in Portuguese.
        r#""nada""#,
    ];

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

    /// The room a label has before it reaches what the part says beside it.
    const GUTTER: f64 = 10.0;

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

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

    /// Nothing on either page is broken to a width: a label longer than the
    /// room it has runs on under what the part says beside it, and a line of
    /// prose longer than the paper runs off the sheet.
    #[test]
    fn every_language_writes_lines_that_fit_the_room_they_have() {
        let mut doc = Document::new();
        let text = 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 code = named.code();
            let lines = words
                .sittings
                .map(|line| (20.0, line.to_owned(), PAPER))
                .into_iter()
                .chain(
                    words
                        .lines
                        .into_iter()
                        .flatten()
                        .map(|line| (11.0, line.to_owned(), PAPER)),
                )
                .chain(words.headings.map(|line| (13.0, line.to_owned(), PAPER)))
                .chain(
                    words
                        .asked
                        .map(|line| (11.0, line.to_owned(), SAID - GUTTER)),
                )
                .chain([
                    (11.0, words.at_large[0].to_owned(), SAID - GUTTER),
                    (11.0, words.holder[0].to_owned(), SAID - GUTTER),
                ])
                .chain(words.closing.map(|line| (10.5, line.to_owned(), PAPER)));

            for (size, line, room) in lines {
                let measured = text.measure(&line, size);
                assert!(
                    measured <= room,
                    "the {code} register draws {line:?} over {measured:.1} \
                     points, and it has {room:.1}"
                );
            }
        }
    }

    /// The right-hand column of every pair is set from the same left edge, so
    /// what a part says has to stay on the paper from there.
    #[test]
    fn every_language_keeps_what_a_part_says_on_the_paper() {
        let mut doc = Document::new();
        let text = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );
        let room = SHEET.0 - MARGIN - (MARGIN + SAID);

        for (named, words) in WORDS {
            let code = named.code();
            let said = words
                .sittings
                .map(str::to_owned)
                .into_iter()
                .chain([words.hand(0), words.hand(1)])
                .chain(words.claimed_by.map(str::to_owned))
                .chain([
                    words.at_large[1].to_owned(),
                    words.holder[1].to_owned(),
                    words.plate.to_owned(),
                ]);

            for line in said {
                let measured = text.measure(&line, 10.0);
                assert!(
                    measured <= room,
                    "the {code} register says {line:?} over {measured:.1} \
                     points, and the column leaves {room:.1}"
                );
            }
        }
    }
}