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
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360 | //! 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.
//!
//! It also says, in so many words, that the toolbar, the menu bar and the
//! window's controls stay shown, and that its pages are read from left to
//! right.
//!
//! 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, ReadingOrder, 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 à la fenêtre d’impression",
],
cover_body: [
"Cette couverture est la page un, mais ce document ne s’ouvre pas sur elle. Un logiciel",
"de lecture qui suit ce que le fichier déclare va droit au sommaire, affiche les signets",
"à côté et laisse la couverture seule — comme un livre ouvert dont la première page",
"n’a rien en regard.",
],
contents_body: [
"C’est la page sur laquelle le fichier s’ouvre, et elle s’affiche en montrant ce qui",
"y figure plutôt que la feuille entière : les mots remplissent la fenêtre, pas",
"le papier autour. Voir la page trois pour la liste complète de ce que ce fichier",
"demande, et la page quatre pour ce qu’il demande à une imprimante.",
],
terms_lead: [
"Le lien ci-dessous va vers {}, et nulle part ailleurs. Il fonctionne 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 est rompu — sauf si l’adresse",
"déclarée suit. C’est tout le rôle d’une adresse de base : une seule ligne à corriger,",
"au lieu de réécrire chaque lien relatif du document.",
],
screen_lead: [
"Chaque ligne ci-dessous est un souhait, pas un ordre. Un logiciel de lecture que son",
"utilisateur a réglé autrement obéit à ce réglage, et un logiciel qui ne connaît pas l’une",
"de ces entrées l’ignore et affiche le fichier malgré tout.",
],
screen_settings: [
["S’ouvre sur", "le sommaire, pas la couverture"],
["Affiche", "le contenu seul, à pleine fenêtre"],
["À 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: [
"Aucun de ces réglages n’est tracé sur une page. Imprimez ce fichier : pas un ne laisse de",
"trace. Ils vivent dans le catalogue, la première chose que lit un logiciel de \
lecture et la dernière",
"dont se soucie une imprimante.",
],
printer_lead: [
"Une fenêtre d’impression s’ouvre avec des réglages déjà remplis. Un fichier",
"peut dire lesquels, ce qui évite de régler les quatre mêmes cases à chaque fois.",
],
printer_settings: [
[
"Mise à l’échelle",
"aucune : chaque page s’imprime à sa taille d’origine",
],
["Faces", "les deux, feuille retournée sur le bord long"],
["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: "retournée sur le bord long",
printer_note: [
"L’impression à taille réelle est celle qui compte pour un document destiné à",
"être mesuré : un formulaire, une planche d’étiquettes, un plan. Une fenêtre qui",
"réduit la page au format du papier fausse en silence chacune de ses distances.",
],
};
/// The handbook in Dutch.
const DUTCH: Words = Words {
handbook: "Veldhandboek",
subject: "Hoe een document vraagt geopend, getoond en afgedrukt te worden",
sections: [
"De omslag",
"Inhoud",
"Wat dit bestand van leessoftware vraagt",
"Wat het van een afdrukvenster vraagt",
],
cover_body: [
"Deze omslag is pagina één, maar het document opent niet hier. Leessoftware",
"die respecteert wat het bestand zegt, gaat meteen naar de inhoud, toont de bladwijzers",
"ernaast en laat de omslag alleen, zoals een boek dat openvalt met de eerste pagina",
"tegenover niets.",
],
contents_body: [
"Dit is de pagina waarop het bestand opent, en het opent met wat erop getekend staat",
"in plaats van het hele blad: de woorden vullen het venster, niet het papier eromheen.",
"Ga naar pagina drie voor de volledige lijst van wat dit bestand vraagt, en naar",
"pagina vier voor wat het van een printer vraagt.",
],
terms_lead: [
"De link hieronder gaat naar {}, en nergens anders heen. Hij werkt omdat dit",
"bestand het adres noemt waaronder het is gepubliceerd:",
],
terms_link: "De volledige voorwaarden lezen",
base_note: [
"Verplaats dit bestand naar een ander adres en die link breekt, tenzij het adres",
"meeverhuist. Daar is een basisadres voor: één regel om aan te passen, in plaats",
"van elke relatieve link in het document te herschrijven.",
],
screen_lead: [
"Elke regel hieronder is een wens, geen bevel. Leessoftware waarvan de eigenaar iets",
"anders heeft ingesteld, doet wat de eigenaar zei, en leessoftware die nooit van een",
"van deze gegevens heeft gehoord, negeert ze en toont het bestand toch.",
],
screen_settings: [
["Opent op", "de inhoudspagina, niet de omslag"],
["Toont", "wat getekend is, het venster vullend"],
["Naast de pagina", "de lijst met bladwijzers"],
["Schikt de pagina’s", "twee tegelijk, pagina één apart"],
[
"Venster",
"passend op de eerste pagina, midden op het scherm",
],
[
"Titelbalk",
"de titel die dit bestand noemt, niet de bestandsnaam",
],
[
"Bij verlaten van volledig scherm",
"terug naar de bladwijzers",
],
],
relative_links: "Relatieve links",
screen_note: [
"Niets hiervan wordt op een pagina getekend. Druk dit bestand af en geen van deze regels",
"laat een spoor na: ze staan in de catalogus, het eerste wat leessoftware leest en het",
"laatste waar een printer om geeft.",
],
printer_lead: [
"Een afdrukvenster opent met iets al ingevuld. Een bestand kan zeggen wat,",
"zodat wie afdrukt niet elke keer dezelfde vier vakjes hoeft in te stellen.",
],
printer_settings: [
["Schaal", "geen: elke pagina op ware grootte"],
["Zijden", "beide, het blad gekeerd over de lange kant"],
["Papierlade", "gekozen naar het paginaformaat"],
["Exemplaren", "twee"],
[
"Pagina’s",
"twee tot vier: de omslag is de toner niet waard",
],
],
front: "voorkant: pagina twee",
back: "achterkant: pagina drie",
long_edge: "gekeerd over de lange kant",
printer_note: [
"Afdrukken op ware grootte telt bij een document dat bedoeld is om",
"gemeten te worden: een formulier, een etikettenvel, een plattegrond. Een venster dat",
"de pagina tot het papier laat krimpen, vervalst stilletjes elke afstand.",
],
};
/// The handbook in Portuguese.
const PORTUGUESE: Words = Words {
handbook: "Manual de campo",
subject: "Como um documento pede para ser aberto, mostrado e impresso",
sections: [
"A capa",
"Índice",
"O que o ficheiro pede ao programa de leitura",
"O que pede a uma janela de impressão",
],
cover_body: [
"Esta capa é a página um, mas o documento não abre nela. Um programa de leitura",
"que respeite o que o ficheiro indica vai direto ao índice, mostra os marcadores",
"ao lado e deixa a capa sozinha, como um livro que abre com a primeira página",
"de frente para nada.",
],
contents_body: [
"Esta é a página em que o ficheiro abre, e abre a mostrar o que nela está desenhado",
"em vez da folha inteira: as palavras enchem a janela, não o papel à volta",
"delas. Vá à página três para a lista completa do que este ficheiro pede, e à",
"página quatro para o que pede a uma impressora.",
],
terms_lead: [
"A ligação abaixo leva a {}, e a mais nada. Funciona porque este",
"ficheiro indica o endereço com que foi publicado:",
],
terms_link: "Ler as condições completas",
base_note: [
"Mude este ficheiro para outro endereço e essa ligação parte-se, salvo se o endereço",
"se mudar com ele. Para isso serve um endereço base: uma linha a reescrever, em vez",
"de cada ligação relativa do documento.",
],
screen_lead: [
"Cada linha abaixo é um desejo, não uma ordem. Um programa de leitura cujo utilizador",
"disse outra coisa faz o que o utilizador disse, e um que nunca ouviu falar de uma",
"destas entradas ignora-a e mostra o ficheiro na mesma.",
],
screen_settings: [
["Abre em", "a página do índice, não a capa"],
["Mostra", "o que está desenhado, a encher a janela"],
["Ao lado da página", "a lista de marcadores"],
["Dispõe as páginas", "duas de cada vez, a página um sozinha"],
["Janela", "ajustada à primeira página, centrada no ecrã"],
[
"Barra de título",
"o título que este ficheiro indica, não o nome do ficheiro",
],
["Ao sair do ecrã inteiro", "volta aos marcadores"],
],
relative_links: "Ligações relativas",
screen_note: [
"Nada disto é desenhado numa página. Imprima este ficheiro e nenhuma destas linhas",
"deixa marca: vivem no catálogo, a primeira coisa que um programa de leitura lê e a",
"última com que uma impressora se importa.",
],
printer_lead: [
"Uma janela de impressão abre com algo já preenchido. Um ficheiro pode dizer o quê,",
"o que poupa a quem imprime acertar as mesmas quatro caixas de cada vez.",
],
printer_settings: [
["Escala", "nenhuma: cada página em tamanho real"],
["Faces", "as duas, a folha virada pelo lado maior"],
["Tabuleiro de papel", "escolhido pelo tamanho da página"],
["Cópias", "duas"],
["Páginas", "da dois à quatro: a capa não vale o toner"],
],
front: "frente: página dois",
back: "verso: página três",
long_edge: "virada pelo lado maior",
printer_note: [
"Imprimir em tamanho real é o que conta num documento feito para ser",
"medido: um formulário, uma folha de etiquetas, uma planta. Uma janela que reduz a página",
"ao papel é uma janela que falseia em silêncio cada distância.",
],
};
/// The handbook in Italian.
const ITALIAN: Words = Words {
handbook: "Manuale da campo",
subject: "Come un documento chiede di essere aperto, mostrato e stampato",
sections: [
"La copertina",
"Indice",
"Cosa chiede il file al programma di lettura",
"Cosa chiede a una finestra di stampa",
],
cover_body: [
"Questa copertina è la pagina uno, ma il documento non si apre qui. Un programma",
"di lettura che rispetta il file passa subito all’indice, mostra i segnalibri",
"accanto e lascia la copertina da sola, come un libro che si apre con la prima pagina",
"di fronte al nulla.",
],
contents_body: [
"Questa è la pagina su cui si apre il file, e si apre mostrando ciò che vi è disegnato",
"anziché il foglio intero: le parole riempiono la finestra, non la carta intorno",
"a esse. Andate a pagina tre per l’elenco completo di ciò che chiede questo file, e a",
"pagina quattro per ciò che chiede a una stampante.",
],
terms_lead: [
"Il collegamento qui sotto porta a {}, e a nient’altro. Funziona perché questo",
"file indica l’indirizzo con cui è stato pubblicato:",
],
terms_link: "Leggere le condizioni complete",
base_note: [
"Spostate questo file a un altro indirizzo e quel collegamento si rompe, a meno che l’indirizzo",
"non si sposti con esso. È tutto ciò a cui serve un indirizzo di base: una riga da riscrivere, anziché",
"ogni collegamento relativo del documento.",
],
screen_lead: [
"Ogni riga qui sotto è un desiderio, non un ordine. Un programma di lettura a cui l’utente",
"ha detto altro fa ciò che ha detto l’utente, e uno che non ha mai sentito parlare di una",
"di queste voci la ignora e mostra il file lo stesso.",
],
screen_settings: [
["Si apre su", "la pagina dell’indice, non la copertina"],
["Mostra", "ciò che è disegnato, riempiendo la finestra"],
["Accanto alla pagina", "l’elenco dei segnalibri"],
["Dispone le pagine", "due alla volta, la pagina uno da sola"],
[
"Finestra",
"adattata alla prima pagina, centrata sullo schermo",
],
[
"Barra del titolo",
"il titolo che indica questo file, non il nome del file",
],
["Uscendo dallo schermo intero", "torna ai segnalibri"],
],
relative_links: "Collegamenti relativi",
screen_note: [
"Niente di tutto questo è disegnato su una pagina. Stampate il file e nessuna di queste righe",
"lascia traccia: vivono nel catalogo, la prima cosa che legge un programma di lettura e l’ultima",
"che interessa a una stampante.",
],
printer_lead: [
"Una finestra di stampa si apre con qualcosa già compilato. Un file può dire cosa,",
"il che risparmia a chi stampa di impostare ogni volta le stesse quattro caselle.",
],
printer_settings: [
["Scala", "nessuna: ogni pagina si stampa a grandezza reale"],
["Lati", "entrambi, il foglio girato sul lato lungo"],
[
"Vassoio della carta",
"scelto in base al formato della pagina",
],
["Copie", "due"],
[
"Pagine",
"dalla due alla quattro: la copertina non vale il toner",
],
],
front: "fronte: pagina due",
back: "retro: pagina tre",
long_edge: "girato sul lato lungo",
printer_note: [
"Stampare in dimensione reale è ciò che conta in un documento fatto per essere",
"misurato: un modulo, un foglio di etichette, una pianta. Una finestra lasciata a ridurre la pagina",
"alla carta è una finestra che falsa in silenzio ogni distanza.",
],
};
/// The handbook in Spanish.
const SPANISH: Words = Words {
handbook: "Manual de campo",
subject: "Cómo pide un documento que se abra, se muestre y se imprima",
sections: [
"La cubierta",
"Índice",
"Lo que el archivo pide al programa de lectura",
"Lo que pide a un cuadro de impresión",
],
cover_body: [
"Esta cubierta es la página uno, pero el documento no se abre en ella. Un programa",
"de lectura que respeta lo que indica el archivo pasa directamente al índice, muestra",
"los marcadores a su lado y deja la cubierta sola, como un libro que se abre con su",
"primera página sin nada enfrente.",
],
contents_body: [
"Esta es la página en que se abre el archivo, y se abre mostrando lo que tiene dibujado",
"y no la hoja entera: las palabras llenan la ventana, no el papel que las",
"rodea. Vaya a la página tres para ver la lista completa de lo que pide el archivo, y a la",
"página cuatro para ver lo que pide a una impresora.",
],
terms_lead: [
"El enlace de abajo lleva a {}, y a nada más. Funciona porque este",
"archivo indica la dirección con la que se publicó:",
],
terms_link: "Leer las condiciones completas",
base_note: [
"Mueva este archivo a otra dirección y ese enlace se rompe, salvo que la dirección",
"se mueva con él. Para eso sirve una dirección base: una línea que cambiar en lugar",
"de reescribir cada enlace relativo del documento.",
],
screen_lead: [
"Cada línea de abajo es un deseo, no una orden. Un programa de lectura cuyo dueño",
"ha dicho otra cosa hace lo que dijo su dueño, y uno que nunca ha oído hablar de una",
"de estas entradas la ignora y muestra el archivo igualmente.",
],
screen_settings: [
["Se abre en", "la página del índice, no la cubierta"],
["Muestra", "lo dibujado, llenando la ventana"],
["Junto a la página", "la lista de marcadores"],
["Coloca las páginas", "de dos en dos, la página uno sola"],
[
"Ventana",
"ajustada a la primera página, centrada en la pantalla",
],
[
"Barra de título",
"el título que indica este archivo, no su nombre de archivo",
],
["Al salir de pantalla completa", "vuelve a los marcadores"],
],
relative_links: "Enlaces relativos",
screen_note: [
"Nada de esto se dibuja en una página. Imprima este archivo y ninguna de estas líneas deja",
"huella: viven en el catálogo, que es lo primero que lee un programa de lectura y lo último",
"que le importa a una impresora.",
],
printer_lead: [
"Un cuadro de impresión se abre con algo ya rellenado. Un archivo puede decir qué,",
"lo que ahorra a quien lo imprime marcar las mismas cuatro casillas cada vez.",
],
printer_settings: [
["Escala", "ninguna: cada página se imprime a su tamaño real"],
["Caras", "las dos, la hoja volteada por el borde largo"],
["Bandeja de papel", "elegida por el tamaño de la página"],
["Copias", "dos"],
[
"Páginas",
"de la dos a la cuatro: la cubierta no merece el tóner",
],
],
front: "anverso: página dos",
back: "reverso: página tres",
long_edge: "volteada por el borde largo",
printer_note: [
"Imprimir a tamaño real es lo que importa en un documento hecho para",
"medirse: un formulario, una hoja de etiquetas, un plano. Un cuadro que reduce la página para",
"que quepa en el papel es un cuadro que falsea en silencio cada distancia.",
],
};
/// The handbook in German.
const GERMAN: Words = Words {
handbook: "Feldhandbuch",
subject: "Wie ein Dokument geöffnet, gezeigt und gedruckt werden möchte",
sections: [
"Der Umschlag",
"Inhalt",
"Was diese Datei von der Lesesoftware erbittet",
"Was sie von einem Druckdialog erbittet",
],
cover_body: [
"Dieser Umschlag ist Seite eins, doch die Datei öffnet nicht hier. Eine Lesesoftware,",
"die befolgt, was die Datei angibt, schlägt gleich den Inhalt auf, zeigt daneben",
"die Lesezeichen und stellt den Umschlag allein — wie ein Buch aufklappt, die erste Seite",
"gegenüber von nichts.",
],
contents_body: [
"Auf dieser Seite öffnet die Datei, und sie zeigt, was darauf gezeichnet ist,",
"statt des ganzen Bogens: Die Wörter füllen das Fenster, nicht das Papier um sie.",
"Auf Seite drei steht die ganze Liste dessen, was diese Datei erbittet, und auf",
"Seite vier, was sie von einem Drucker erbittet.",
],
terms_lead: [
"Der Link unten führt zu {} und nirgendwohin sonst. Er funktioniert, weil diese",
"Datei die Adresse angibt, unter der sie veröffentlicht wurde:",
],
terms_link: "Die vollständigen Bedingungen lesen",
base_note: [
"Zieht die Datei an eine andere Adresse, bricht der Link — außer die Adresse",
"zieht mit. Mehr leistet eine Basisadresse nicht: eine Zeile neu angeben, statt jeden",
"relativen Link im Dokument umzuschreiben.",
],
screen_lead: [
"Jede Zeile unten ist ein Wunsch, keine Anweisung. Eine Lesesoftware, deren Besitzer",
"anderes festlegte, folgt ihm, und eine, die einen dieser Einträge nicht kennt,",
"übergeht ihn und zeigt die Datei trotzdem.",
],
screen_settings: [
["Öffnet auf", "der Inhaltsseite, nicht dem Umschlag"],
["Zeigt", "das Gezeichnete, fensterfüllend"],
["Neben der Seite", "die Liste der Lesezeichen"],
["Ordnet die Seiten an", "zu zweit, Seite eins für sich"],
[
"Fenster",
"auf die erste Seite angepasst, mittig auf dem Bildschirm",
],
[
"Titelleiste",
"der Titel, den die Datei angibt, nicht ihr Dateiname",
],
["Beim Verlassen des Vollbilds", "zurück zu den Lesezeichen"],
],
relative_links: "Relative Links",
screen_note: [
"Nichts davon ist auf eine Seite gezeichnet. Wer diese Datei druckt, sieht keine dieser Zeilen: Sie",
"stehen im Katalog, den eine Lesesoftware zuerst liest und der einen Drucker am wenigsten",
"kümmert.",
],
printer_lead: [
"Ein Druckdialog öffnet sich mit bereits ausgefüllten Angaben. Eine Datei kann",
"sagen, welche, und erspart so, jedes Mal dieselben vier Felder zu setzen.",
],
printer_settings: [
["Skalierung", "keine: Jede Seite druckt in Originalgröße"],
["Duplex", "beidseitig, Bogen über die lange Kante gewendet"],
["Papierfach", "nach der Seitengröße gewählt"],
["Exemplare", "zwei"],
[
"Seiten",
"zwei bis vier: Der Umschlag ist den Toner nicht wert",
],
],
front: "Vorderseite: Seite zwei",
back: "Rückseite: Seite drei",
long_edge: "über die lange Kante gewendet",
printer_note: [
"Der Druck in Originalgröße zählt bei einem Dokument, das gemessen werden soll:",
"ein Formular, ein Etikettenbogen, ein Plan. Ein Dialog, der die Seite aufs Papier",
"verkleinern darf, macht still und leise jeden Abstand darauf falsch.",
],
};
/// 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 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()
.hide_toolbar(false)
.hide_menu_bar(false)
.hide_window_controls(false)
.reading_order(ReadingOrder::LeftToRight)
.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; 9] = [
"\"Copies\"",
"\"Pages\"",
// Written the same way in Portuguese.
r#""Barra de título""#,
r#""Escala""#,
r#""Faces""#,
r#""Mostra""#,
r#""Páginas""#,
r#""Índice""#,
r#"handbook: "Manual de campo""#,
];
/// 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"
);
}
}
|