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 | //! Writes pictures made in memory and read from files, each drawn under a
//! setting of its own, with what the image says of itself under it.
//!
//! The first page builds its pictures from samples: red, green and blue;
//! cyan, magenta, yellow and black; four-bit places in a table of colours;
//! and samples carrying their own opacity. It then shows them through a colour
//! key, a soft mask, a stencil mask and as a stencil, decoded upside down,
//! smoothed and not, read through a colour profile under a rendering intent,
//! stripped of their opacity, laid down in one and in two inks named for the
//! press, and held within a clipping path. The pictures that let the page
//! through stand over a grey band, so what they leave out shows.
//!
//! The second page turns one picture every way a camera may have stored it,
//! and reads pictures from files through the constructor made for each
//! format, saying what size they come out at a given resolution and what
//! resolution they state; the last of them lies on a layer a reader can hide.
//! Its last picture is read as measured colour, CIE 1976 L*a*b* against the
//! D50 white.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the pages are written in.
//!
//! Usage: `cargo run --example write_image_settings -- tmp/image_settings.pdf`
//! `HQF_PDF_LANG=fr cargo run --example write_image_settings --
//! tmp/image_settings_fr.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::color::icc;
use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::function::{Calculation, Op};
use hqf_pdf::image::{ClippingPath, Contour, ImageSpace, Knot, Orientation, Resolution};
use hqf_pdf::{
Cmyk, DeviceN, DeviceSpace, Document, Font, FontHandle, Image, Lab, Layer, Page,
RenderingIntent, Separation,
};
#[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;
/// Where the committed fonts and pictures are.
fn tests_dir() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests")
}
/// How far in from the left edge of the sheet the grid starts, in points.
const LEFT: f64 = 56.0;
/// How far apart two cells of the grid are across, in points.
const ACROSS: f64 = 124.0;
/// How far apart two rows of the grid are down, in points.
const DOWN: f64 = 170.0;
/// How wide and tall a picture is drawn, in points.
const SIDE: f64 = 90.0;
/// Where the top of the first row of pictures sits, in points up from the foot
/// of the sheet.
const FIRST_ROW: f64 = 740.0;
/// The size the captions are set at, in points.
const CAPTION: f64 = 7.5;
/// How many pixels across and down the pictures made in memory are.
const TILE: u32 = 32;
/// Every word the pages say, in one language.
#[derive(Debug)]
struct Words {
/// The first page's heading, and what the file says of itself.
title: &'static str,
/// The second page's heading.
files: &'static str,
/// What each picture of the first page is, in the order it is drawn.
made: [&'static str; 16],
/// Yes, then no.
yes_no: [&'static str; 2],
/// A picture's size and components; `{width}`, `{height}` and `{count}`
/// stand for them.
size: &'static str,
/// The width of a component; `{bits}` stands for it.
bits: &'static str,
/// Whether a picture carries a soft mask; `{answer}` stands for it.
soft: &'static str,
/// The ranges a colour key leaves out; `{ranges}` stands for them.
keyed: &'static str,
/// Whether a picture carries a stencil mask; `{answer}` stands for it.
stencil_mask: &'static str,
/// Whether a picture is a stencil; `{answer}` stands for it.
stencil: &'static str,
/// The ranges a picture is decoded through; `{ranges}` stands for them.
decoded: &'static str,
/// Whether a picture is smoothed; `{answer}` stands for it.
smoothed: &'static str,
/// A picture's profile and intent; `{bytes}` and `{intent}` stand for how
/// long the profile is and the intent.
profile: &'static str,
/// The four rendering intents: perceptual, relative colorimetric,
/// saturation, absolute colorimetric.
intents: [&'static str; 4],
/// How many components a pixel carries; `{count}` stands for them.
components: &'static str,
/// A clipping path; `{contours}` and `{knots}` stand for how many.
path: &'static str,
/// What each orientation is, in the order of the tags one to eight.
orientations: [&'static str; 8],
/// An orientation's tag and whether it swaps the axes; `{tag}` and `{swap}`
/// stand for them.
tag: &'static str,
/// Whether the axes are swapped: yes, then no.
swaps: [&'static str; 2],
/// The start of an orientation's matrix; `{matrix}` stands for it.
matrix: &'static str,
/// What each file picture is, in the order it is drawn.
read: [&'static str; 4],
/// A picture's size at 300 dots to the inch; `{width}` and `{height}` stand
/// for it.
at_dpi: &'static str,
/// The resolution a picture states; `{x}`, `{y}` and `{square}` stand for
/// it.
stated: &'static str,
/// Whether it is the same both ways: yes, then no.
square: [&'static str; 2],
/// What a picture stating no resolution is said to state.
unstated: &'static str,
/// How many extra channels a TIFF names; `{count}` stands for them.
channels: &'static str,
/// The name of the layer the last picture lies on.
layer: &'static str,
/// Where the last picture lies; `{layer}` stands for the layer.
on_layer: &'static str,
/// What stands under the letter drawn inline.
inline: &'static str,
/// What stands under the picture read as measured colour.
measured: &'static str,
}
impl Words {
/// The words the pages are written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The pages in English.
const ENGLISH: Words = Words {
title: "Pictures made in memory, and what each is told",
files: "One picture turned eight ways, and pictures read from files",
made: [
"From red, green and blue",
"From four process inks",
"From a table of colours",
"From samples with opacity",
"Through a colour key",
"Through a soft mask",
"Through a stencil mask",
"A stencil in the page's colour",
"Decoded upside down",
"Smoothed when enlarged",
"Left as its pixels",
"A profile and an intent",
"Its opacity dropped",
"In one press ink",
"In two press inks",
"Held within a clipping path",
],
yes_no: ["yes", "no"],
size: "{width} × {height} px, {count} components",
bits: "{bits} bits a component",
soft: "soft mask: {answer}",
keyed: "keyed out: {ranges}",
stencil_mask: "stencil mask: {answer}",
stencil: "stencil: {answer}",
decoded: "decoded: {ranges}",
smoothed: "smoothed: {answer}",
profile: "profile {bytes} bytes, {intent}",
intents: [
"perceptual",
"relative colorimetric",
"saturation",
"absolute colorimetric",
],
components: "components a pixel: {count}",
path: "contours: {contours}; knots: {knots}",
orientations: [
"Upright",
"Mirrored left to right",
"Upside down",
"Mirrored top to bottom",
"Mirrored, turned left",
"Turned right",
"Mirrored, turned right",
"Turned left",
],
tag: "tag {tag}; {swap}",
swaps: ["axes swapped", "axes kept"],
matrix: "matrix [{matrix}]",
read: [
"A PNG, read as a PNG",
"A JPEG, read as a JPEG",
"A BMP, read as a BMP",
"A TIFF, read as a TIFF",
],
at_dpi: "at 300 dpi: {width} × {height} pt",
stated: "{x} × {y} dpi, {square}",
square: ["square", "not square"],
unstated: "states no resolution",
channels: "extra channels named: {count}",
layer: "Photographs",
on_layer: "on the layer \u{201C}{layer}\u{201D}",
inline: "the letter, written into the page's own stream",
measured: "Read as measured colour, L*a*b*",
};
/// The pages in French.
const FRENCH: Words = Words {
title: "Des images créées en mémoire, et ce qu’on dit à chacune",
files: "Une image en huit sens, et des images de fichiers",
made: [
"En rouge, vert et bleu",
"En quadrichromie",
"D’après une table de couleurs",
"Avec sa propre opacité",
"Par une clé de couleur",
"Par un masque progressif",
"Par un masque au pochoir",
"En pochoir, couleur de la page",
"Décodée à l’envers",
"Lissée quand on l’agrandit",
"Laissée en pixels",
"Un profil et une intention",
"Son opacité retirée",
"En une encre d’imprimerie",
"En deux encres d’imprimerie",
"Dans un tracé de détourage",
],
yes_no: ["oui", "non"],
size: "{width} × {height} px, {count} composantes",
bits: "{bits} bits par composante",
soft: "masque progressif : {answer}",
keyed: "exclues : {ranges}",
stencil_mask: "masque au pochoir : {answer}",
stencil: "pochoir : {answer}",
decoded: "décodage : {ranges}",
smoothed: "lissée : {answer}",
profile: "profil {bytes} octets, {intent}",
intents: [
"perceptuelle",
"colorimétrique relative",
"saturation",
"colorimétrique absolue",
],
components: "composantes par pixel : {count}",
path: "contours : {contours} ; nœuds : {knots}",
orientations: [
"À l’endroit",
"En miroir de gauche à droite",
"À l’envers",
"En miroir de haut en bas",
"En miroir, tournée à gauche",
"Tournée à droite",
"En miroir, tournée à droite",
"Tournée à gauche",
],
tag: "étiquette {tag} ; {swap}",
swaps: ["axes échangés", "axes gardés"],
matrix: "matrice [{matrix}]",
read: [
"Un PNG, lu comme un PNG",
"Un JPEG, lu comme un JPEG",
"Un BMP, lu comme un BMP",
"Un TIFF, lu comme un TIFF",
],
at_dpi: "à 300 ppp : {width} × {height} pt",
stated: "{x} × {y} ppp, {square}",
square: ["carrée", "non carrée"],
unstated: "n’indique aucune résolution",
channels: "autres canaux nommés : {count}",
layer: "Photographies",
on_layer: "sur le calque « {layer} »",
inline: "la lettre, écrite dans le flux de la page même",
measured: "Lue en couleur mesurée, L*a*b*",
};
/// The pages in Dutch.
const DUTCH: Words = Words {
title: "Afbeeldingen uit het geheugen, en hun instellingen",
files: "Eén afbeelding in acht standen, en beelden uit bestanden",
made: [
"Uit rood, groen en blauw",
"Uit vier procesinkten",
"Uit een kleurentabel",
"Uit waarden met dekking",
"Via een kleursleutel",
"Via een zacht masker",
"Via een sjabloonmasker",
"Sjabloon in paginakleur",
"Ondersteboven gedecodeerd",
"Gladgemaakt bij vergroten",
"Als pixels gelaten",
"Een profiel en een intentie",
"Dekking verlaagd",
"In één persinkt",
"In twee persinkten",
"Binnen een uitknippad",
],
yes_no: ["ja", "nee"],
size: "{width} × {height} px, {count} componenten",
bits: "{bits} bits per component",
soft: "zacht masker: {answer}",
keyed: "sleutel: {ranges}",
stencil_mask: "sjabloonmasker: {answer}",
stencil: "sjabloon: {answer}",
decoded: "gedecodeerd: {ranges}",
smoothed: "gladgemaakt: {answer}",
profile: "profiel {bytes} bytes, {intent}",
intents: [
"perceptueel",
"relatief colorimetrisch",
"verzadiging",
"absoluut colorimetrisch",
],
components: "componenten per pixel: {count}",
path: "contouren: {contours}; knopen: {knots}",
orientations: [
"Rechtop",
"Links-rechts gespiegeld",
"Ondersteboven",
"Boven-onder gespiegeld",
"Gespiegeld, linksom gedraaid",
"Rechtsom gedraaid",
"Gespiegeld, rechtsom gedraaid",
"Linksom gedraaid",
],
tag: "tag {tag}; {swap}",
swaps: ["assen verwisseld", "assen behouden"],
matrix: "matrix [{matrix}]",
read: [
"Een PNG, gelezen als PNG",
"Een JPEG, gelezen als JPEG",
"Een BMP, gelezen als BMP",
"Een TIFF, gelezen als TIFF",
],
at_dpi: "op 300 dpi: {width} × {height} pt",
stated: "{x} × {y} dpi, {square}",
square: ["vierkant", "niet vierkant"],
unstated: "vermeldt geen resolutie",
channels: "extra kanalen met een naam: {count}",
layer: "Foto’s",
on_layer: "op de laag „{layer}”",
inline: "de letter, geschreven in de eigen stroom van de pagina",
measured: "Gelezen als gemeten L*a*b*-kleur",
};
/// The pages in Portuguese.
const PORTUGUESE: Words = Words {
title: "Imagens feitas em memória, e o que se diz a cada uma",
files: "Uma imagem em oito orientações e imagens de ficheiros",
made: [
"De vermelho, verde e azul",
"De quadricromia",
"De uma tabela de cores",
"De amostras com opacidade",
"Com uma chave de cor",
"Com uma máscara suave",
"Com uma máscara de estêncil",
"Um estêncil na cor da página",
"Descodificada invertida",
"Suavizada ao ampliar",
"Deixada nos seus píxeis",
"Um perfil e uma intenção",
"Opacidade reduzida",
"Numa tinta de gráfica",
"Em duas tintas de gráfica",
"Num traçado de recorte",
],
yes_no: ["sim", "não"],
size: "{width} × {height} px, {count} componentes",
bits: "{bits} bits por componente",
soft: "máscara suave: {answer}",
keyed: "exclui {ranges}",
stencil_mask: "máscara de estêncil: {answer}",
stencil: "estêncil: {answer}",
decoded: "descodificada: {ranges}",
smoothed: "suavizada: {answer}",
profile: "perfil {bytes} bytes, {intent}",
intents: [
"percetual",
"colorimétrica relativa",
"saturação",
"colorimétrica absoluta",
],
components: "componentes por píxel: {count}",
path: "contornos: {contours}; nós: {knots}",
orientations: [
"Na posição normal",
"Espelhada na horizontal",
"De pernas para o ar",
"Espelhada na vertical",
"Espelhada, rodada à esquerda",
"Rodada à direita",
"Espelhada, rodada à direita",
"Rodada à esquerda",
],
tag: "etiqueta {tag}; {swap}",
swaps: ["eixos trocados", "eixos mantidos"],
matrix: "matriz [{matrix}]",
read: [
"Um PNG, lido como PNG",
"Um JPEG, lido como JPEG",
"Um BMP, lido como BMP",
"Um TIFF, lido como TIFF",
],
at_dpi: "a 300 ppp: {width} × {height} pt",
stated: "{x} × {y} ppp, {square}",
square: ["quadrado", "não quadrado"],
unstated: "não indica resolução",
channels: "canais extra com nome: {count}",
layer: "Fotografias",
on_layer: "na camada «{layer}»",
inline: "a letra, escrita no próprio fluxo da página",
measured: "Lida como cor medida em L*a*b*",
};
/// The pages in Italian.
const ITALIAN: Words = Words {
title: "Immagini create in memoria, e ciò che si dice a ciascuna",
files: "Un’immagine ruotata in otto modi, e immagini lette da file",
made: [
"Da rosso, verde e blu",
"In quadricromia",
"Da una tabella di colori",
"Da campioni con opacità",
"Con una chiave di colore",
"Con una maschera morbida",
"Con una maschera a stencil",
"Stencil nel colore di pagina",
"Decodificata capovolta",
"Smussata quando ingrandita",
"Non smussata",
"Profilo e intento di rendering",
"Opacità ridotta",
"In un inchiostro da stampa",
"In due inchiostri da stampa",
"In un tracciato di ritaglio",
],
yes_no: ["sì", "no"],
size: "{width} × {height} px, {count} componenti",
bits: "{bits} bit per componente",
soft: "maschera morbida: {answer}",
keyed: "esclude {ranges}",
stencil_mask: "maschera a stencil: {answer}",
stencil: "stencil: {answer}",
decoded: "decodificata: {ranges}",
smoothed: "smussata: {answer}",
profile: "profilo: {bytes} byte, {intent}",
intents: [
"percettivo",
"colorimetrico relativo",
"saturazione",
"colorimetrico assoluto",
],
components: "componenti per pixel: {count}",
path: "contorni: {contours}; nodi: {knots}",
orientations: [
"Diritta",
"Specchiata in orizzontale",
"Capovolta",
"Specchiata in verticale",
"Specchiata, ruotata a sinistra",
"Ruotata a destra",
"Specchiata, ruotata a destra",
"Ruotata a sinistra",
],
tag: "tag {tag}; {swap}",
swaps: ["assi scambiati", "assi mantenuti"],
matrix: "matrice [{matrix}]",
read: [
"Un PNG, letto come PNG",
"Un JPEG, letto come JPEG",
"Un BMP, letto come BMP",
"Un TIFF, letto come TIFF",
],
at_dpi: "a 300 dpi: {width} × {height} pt",
stated: "{x} × {y} dpi, {square}",
square: ["quadrati", "non quadrati"],
unstated: "non indica risoluzione",
channels: "canali extra con nome: {count}",
layer: "Fotografie",
on_layer: "sul livello «{layer}»",
inline: "la lettera, scritta nel flusso proprio della pagina",
measured: "Letta come colore CIE L*a*b*",
};
/// The pages in Spanish.
const SPANISH: Words = Words {
title: "Imágenes en memoria y lo que se indica a cada una",
files: "Una imagen en ocho orientaciones, e imágenes de archivos",
made: [
"De rojo, verde y azul",
"De cuatricromía",
"De una tabla de colores",
"De muestras con opacidad",
"Con una clave de color",
"Con una máscara suave",
"Con una máscara de estarcido",
"Estarcido en color de página",
"Decodificada cabeza abajo",
"Suavizada al ampliarse",
"Dejada en sus píxeles",
"Un perfil y una intención",
"Su opacidad rebajada",
"En una tinta de imprenta",
"En dos tintas de imprenta",
"En un trazado de recorte",
],
yes_no: ["sí", "no"],
size: "{width} × {height} px, {count} componentes",
bits: "{bits} bits por componente",
soft: "máscara suave: {answer}",
keyed: "excluye {ranges}",
stencil_mask: "máscara de estarcido: {answer}",
stencil: "estarcido: {answer}",
decoded: "decodificada: {ranges}",
smoothed: "suavizada: {answer}",
profile: "perfil: {bytes} bytes, {intent}",
intents: [
"perceptual",
"colorimétrica relativa",
"saturación",
"colorimétrica absoluta",
],
components: "componentes por píxel: {count}",
path: "contornos: {contours}; nodos: {knots}",
orientations: [
"Sin girar",
"Volteada en horizontal",
"Cabeza abajo",
"Volteada en vertical",
"Reflejada, girada a la izquierda",
"Girada a la derecha",
"Reflejada, girada a la derecha",
"Girada a la izquierda",
],
tag: "etiqueta {tag}; {swap}",
swaps: ["ejes intercambiados", "ejes conservados"],
matrix: "matriz [{matrix}]",
read: [
"Un PNG, leído como PNG",
"Un JPEG, leído como JPEG",
"Un BMP, leído como BMP",
"Un TIFF, leído como TIFF",
],
at_dpi: "a 300 ppp: {width} × {height} pt",
stated: "{x} × {y} ppp, {square}",
square: ["cuadrado", "no cuadrado"],
unstated: "no indica resolución",
channels: "canales extra con nombre: {count}",
layer: "Fotografías",
on_layer: "en la capa «{layer}»",
inline: "la letra, escrita en el propio flujo de la página",
measured: "Leída como color medido, L*a*b*",
};
/// The pages in German.
const GERMAN: Words = Words {
title: "Bilder aus dem Speicher und was jedem mitgegeben wird",
files: "Ein Bild, achtfach gedreht, und Bilder aus Dateien",
made: [
"Aus Rot, Grün und Blau",
"Aus vier Prozessfarben",
"Aus einer Farbtabelle",
"Aus Werten mit Deckkraft",
"Über einen Farbschlüssel",
"Über eine weiche Maske",
"Über eine Schablonenmaske",
"Schablone in Seitenfarbe",
"Invertiert dekodiert",
"Beim Vergrößern geglättet",
"Als Pixel belassen",
"Profil und Wiedergabeabsicht",
"Mit verringerter Deckkraft",
"In einer Druckfarbe",
"In zwei Druckfarben",
"In einem Schnittpfad",
],
yes_no: ["ja", "nein"],
size: "{width} × {height} px, {count} Komponenten",
bits: "{bits} Bit je Komponente",
soft: "weiche Maske: {answer}",
keyed: "ausgespart: {ranges}",
stencil_mask: "Schablonenmaske: {answer}",
stencil: "Schablone: {answer}",
decoded: "dekodiert: {ranges}",
smoothed: "geglättet: {answer}",
profile: "Profil {bytes} Bytes, {intent}",
intents: [
"perzeptiv",
"relativ farbmetrisch",
"Sättigung",
"absolut farbmetrisch",
],
components: "Komponenten je Pixel: {count}",
path: "Konturen: {contours}; Knoten: {knots}",
orientations: [
"Aufrecht",
"Links-rechts gespiegelt",
"Auf dem Kopf",
"Oben-unten gespiegelt",
"Gespiegelt, links gedreht",
"Nach rechts gedreht",
"Gespiegelt, rechts gedreht",
"Nach links gedreht",
],
tag: "Wert {tag}; {swap}",
swaps: ["Achsen vertauscht", "Achsen beibehalten"],
matrix: "Matrix [{matrix}]",
read: [
"Ein PNG, als PNG gelesen",
"Ein JPEG, als JPEG gelesen",
"Ein BMP, als BMP gelesen",
"Ein TIFF, als TIFF gelesen",
],
at_dpi: "bei 300 dpi: {width} × {height} pt",
stated: "{x} × {y} dpi, {square}",
square: ["quadratisch", "rechteckig"],
unstated: "gibt keine Auflösung an",
channels: "benannte Zusatzkanäle: {count}",
layer: "Fotos",
on_layer: "auf der Ebene „{layer}“",
inline: "der Buchstabe, in den eigenen Datenstrom der Seite geschrieben",
measured: "Als L*a*b*-Messwerte gelesen",
};
/// 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),
];
/// `count` as a pixel count or a component value, as the samples below need it.
fn byte(count: u32) -> u8 {
u8::try_from(count.min(255)).unwrap_or(u8::MAX)
}
/// Red rising across the tile, green rising down it, a steady blue.
fn rgb_samples() -> Vec<u8> {
let mut samples = Vec::new();
for y in 0..TILE {
for x in 0..TILE {
samples.extend([byte(x * 8), byte(y * 8), 128]);
}
}
samples
}
/// Cyan rising across the tile, magenta rising down it, no yellow, no black.
fn cmyk_samples() -> Vec<u8> {
let mut samples = Vec::new();
for y in 0..TILE {
for x in 0..TILE {
samples.extend([byte(x * 8), byte(y * 8), 0, 0]);
}
}
samples
}
/// A grey rising across the tile.
fn gray_ramp() -> Vec<u8> {
let mut samples = Vec::new();
for _ in 0..TILE {
for x in 0..TILE {
samples.push(byte(x * 8));
}
}
samples
}
/// A steady lightness, the green-to-red number rising across the tile and the
/// blue-to-yellow one rising down it, each byte read over the range of
/// [`lab_space`].
fn lab_samples() -> Vec<u8> {
let mut samples = Vec::new();
for y in 0..TILE {
for x in 0..TILE {
samples.extend([180, byte(x * 8), byte(y * 8)]);
}
}
samples
}
/// CIE 1976 L*a*b* against the D50 white, both colour numbers running from −128
/// to 127.
const fn lab_space() -> Lab {
Lab::new([0.9642, 1.0, 0.8249]).range([-128.0, 127.0, -128.0, 127.0])
}
/// Squares of eight pixels, one bit a pixel, alternately set and clear.
fn checker_bits() -> Vec<u8> {
let mut samples = Vec::new();
for y in 0..TILE {
for column in 0..TILE / 8 {
samples.push(if (column + y / 8) % 2 == 0 {
0xFF
} else {
0x00
});
}
}
samples
}
/// A table of sixteen colours, and the tile's pixels as four-bit places in it,
/// two to a byte.
fn indexed() -> (Vec<u8>, Vec<u8>) {
let mut palette = Vec::new();
for entry in 0..16 {
palette.extend([byte(entry * 16), byte(255 - entry * 16), byte(entry * 8)]);
}
let mut samples = Vec::new();
for y in 0..TILE {
for x in (0..TILE).step_by(2) {
let first = byte((x + y) % 16);
let second = byte((x + 1 + y) % 16);
samples.push(first << 4 | second);
}
}
(palette, samples)
}
/// A letter F on white, eight pixels by twelve, which shows which way it was
/// turned.
fn letter_f() -> Vec<u8> {
let rows = [
"########", "########", "##......", "##......", "######..", "######..", "##......",
"##......", "##......", "##......", "##......", "##......",
];
let mut samples = Vec::new();
for row in rows {
for mark in row.chars() {
let value = if mark == '#' { 20 } else { 255 };
samples.extend([value, value, value]);
}
}
samples
}
/// Two inks named for the press, and the program laying them down on the four
/// process plates: the first ink is all cyan, the second all yellow.
fn two_inks() -> Result<DeviceN, hqf_pdf::Error> {
let body = vec![Op::Integer(0), Op::Exchange, Op::Integer(0)];
DeviceN::new(
vec!["Harbour Cyan".to_owned(), "Harbour Yellow".to_owned()],
DeviceSpace::Cmyk,
Calculation::new([[0.0, 1.0]; 2], [[0.0, 1.0]; 4], body),
)
}
/// `answer` in `words`.
const fn yes_no(answer: bool, words: &Words) -> &'static str {
if answer {
words.yes_no[0]
} else {
words.yes_no[1]
}
}
/// Where `intent` stands in [`Words::intents`].
#[allow(
clippy::match_same_arms,
reason = "an intent the library adds later reads as the first"
)]
const fn intent_place(intent: RenderingIntent) -> usize {
match intent {
RenderingIntent::Perceptual => 0,
RenderingIntent::RelativeColorimetric => 1,
RenderingIntent::Saturation => 2,
RenderingIntent::AbsoluteColorimetric => 3,
_ => 0,
}
}
/// `ranges` as the page writes them.
fn ranges<T: std::fmt::Display>(ranges: &[(T, T)]) -> String {
ranges
.iter()
.map(|(low, high)| format!("{low}–{high}"))
.collect::<Vec<_>>()
.join(", ")
}
/// A clipping path with one contour: a diamond whose sides bow outwards.
fn diamond() -> ClippingPath {
let knot = |anchor: (f64, f64), arriving: (f64, f64), leaving: (f64, f64)| Knot {
arriving,
anchor,
leaving,
};
ClippingPath::new(vec![Contour::new(vec![
knot((0.5, 1.0), (0.2, 0.95), (0.8, 0.95)),
knot((1.0, 0.5), (0.95, 0.8), (0.95, 0.2)),
knot((0.5, 0.0), (0.8, 0.05), (0.2, 0.05)),
knot((0.0, 0.5), (0.05, 0.2), (0.05, 0.8)),
])])
}
/// The sixteen pictures of the first page, each with the one line it says of
/// itself.
#[allow(
clippy::too_many_lines,
reason = "sixteen pictures, each built and then described"
)]
fn made(words: &Words) -> Result<Vec<(Image, String)>, Box<dyn std::error::Error>> {
let rgb = Image::from_rgb(TILE, TILE, &rgb_samples())?;
let cmyk = Image::from_cmyk(TILE, TILE, &cmyk_samples())?;
let (palette, places) = indexed();
let table = Image::from_raw(TILE, TILE, 4, ImageSpace::Indexed(palette), &places)?;
let mut rgba_samples = Vec::new();
for (pixel, alpha) in rgb_samples().chunks(3).zip(gray_ramp()) {
rgba_samples.extend_from_slice(pixel);
rgba_samples.push(alpha);
}
let rgba = Image::from_rgba(TILE, TILE, &rgba_samples)?;
let keyed = rgb.clone().with_color_key(&[(0, 90), (0, 90), (0, 255)])?;
let soft = rgb
.clone()
.with_soft_mask(Image::from_gray(TILE, TILE, &gray_ramp())?)?;
let checker = Image::from_raw(TILE, TILE, 1, ImageSpace::Gray, &checker_bits())?;
let masked = rgb
.clone()
.with_stencil_mask(checker.clone().into_stencil()?)?;
let stencil = checker.into_stencil()?;
let decoded = rgb
.clone()
.with_decode(Some(&[(1.0, 0.0), (1.0, 0.0), (1.0, 0.0)]))?;
let small = Image::from_rgb(4, 4, &rgb_samples()[..48])?;
let profiled = rgb
.clone()
.with_icc_profile(icc::srgb())?
.with_rendering_intent(Some(RenderingIntent::Perceptual));
let dropped = rgba.clone().without_transparency();
let one_ink = Image::from_gray(TILE, TILE, &gray_ramp())?.into_named_inks(Separation::ink(
"Harbour Blue",
Cmyk::new(0.9, 0.5, 0.0, 0.1),
))?;
let mut paired = Vec::new();
for (tint, other) in gray_ramp().iter().zip(gray_ramp().iter().rev()) {
paired.extend([*tint, *other]);
}
let two = Image::from_raw(TILE, TILE, 8, ImageSpace::DeviceN(two_inks()?), &paired)?;
let clipped = rgb.clone().with_clipping_path(Some(diamond()));
let smoothed = small.clone().with_interpolation(true);
let size = |image: &Image| {
words
.size
.replace("{width}", &image.width().to_string())
.replace("{height}", &image.height().to_string())
.replace("{count}", &image.color_space().components().to_string())
};
let said = [
size(&rgb),
size(&cmyk),
words
.bits
.replace("{bits}", &table.bits_per_component().to_string()),
words
.soft
.replace("{answer}", yes_no(rgba.soft_mask().is_some(), words)),
words
.keyed
.replace("{ranges}", &ranges(keyed.color_key().unwrap_or_default())),
words
.soft
.replace("{answer}", yes_no(soft.soft_mask().is_some(), words)),
words
.stencil_mask
.replace("{answer}", yes_no(masked.stencil_mask().is_some(), words)),
words
.stencil
.replace("{answer}", yes_no(stencil.is_stencil(), words)),
words
.decoded
.replace("{ranges}", &ranges(decoded.decode().unwrap_or_default())),
words
.smoothed
.replace("{answer}", yes_no(smoothed.is_interpolated(), words)),
words
.smoothed
.replace("{answer}", yes_no(small.is_interpolated(), words)),
words
.profile
.replace(
"{bytes}",
&profiled.icc_profile().map_or(0, <[u8]>::len).to_string(),
)
.replace(
"{intent}",
profiled
.rendering_intent()
.map_or("", |intent| words.intents[intent_place(intent)]),
),
words
.soft
.replace("{answer}", yes_no(dropped.soft_mask().is_some(), words)),
words
.components
.replace("{count}", &one_ink.color_space().components().to_string()),
words
.components
.replace("{count}", &two.color_space().components().to_string()),
clipped.clipping_path().map_or_else(String::new, |path| {
words
.path
.replace("{contours}", &path.contours().len().to_string())
.replace(
"{knots}",
&path
.contours()
.iter()
.map(|contour| contour.knots().len())
.sum::<usize>()
.to_string(),
)
}),
];
let pictures = [
rgb, cmyk, table, rgba, keyed, soft, masked, stencil, decoded, smoothed, small, profiled,
dropped, one_ink, two, clipped,
];
Ok(pictures.into_iter().zip(said).collect())
}
/// `line` set at `(x, y)` in `font` at the captions' size.
fn caption(
c: &mut Content,
font: &FontHandle,
(x, y): (f64, f64),
line: &str,
) -> Result<(), hqf_pdf::Error> {
c.begin_text();
c.set_font(font, CAPTION)?;
c.text_origin(x, y)?;
c.show_glyphs(&font.glyphs(line));
c.end_text();
Ok(())
}
/// Where cell `index` of a grid four across starts: its left edge and the top
/// of its picture. How wide the line tracing a clipping path over its picture
/// is, in points.
const TRACE: f64 = 0.6;
fn cell(index: usize) -> Result<(f64, f64), Box<dyn std::error::Error>> {
let column = f64::from(u8::try_from(index % 4)?);
let row = f64::from(u8::try_from(index / 4)?);
Ok((ACROSS.mul_add(column, LEFT), DOWN.mul_add(-row, FIRST_ROW)))
}
/// The first page: the sixteen pictures made in memory, each over its title and
/// the line it says of itself.
fn first_page(
doc: &mut Document,
font: &FontHandle,
words: &Words,
) -> Result<Page, Box<dyn std::error::Error>> {
let mut c = Content::new();
c.begin_text();
c.set_font(font, 16.0)?;
c.text_origin(LEFT, 790.0)?;
c.show_glyphs(&font.glyphs(words.title));
c.end_text();
for (index, (picture, said)) in made(words)?.into_iter().enumerate() {
let (x, top) = cell(index)?;
let bottom = top - SIDE;
// A band behind the pictures that leave the page showing through.
if (3..=7).contains(&index) || index == 15 {
c.set_fill_rgb(0.75, 0.75, 0.75)?;
c.rect(x, bottom + SIDE / 3.0, SIDE, SIDE / 3.0)?.fill();
}
c.set_fill_rgb(0.85, 0.35, 0.1)?;
let clipped = picture.clipping_path().is_some();
let handle = doc.add_image(picture);
if clipped {
c.draw_image_clipped(&handle, x, bottom, SIDE, SIDE)?;
// The path itself, traced over the picture it holds: its points are
// fractions of the picture, so it is traced into the same square.
if let Some(path) = handle.clipping_path() {
c.save_state();
c.transform([SIDE, 0.0, 0.0, SIDE, x, bottom])?;
c.set_line_width(TRACE / SIDE)?;
c.set_stroke_rgb(0.1, 0.1, 0.1)?;
c.trace_clipping_path(path)?;
c.stroke();
c.restore_state();
}
} else {
c.draw_image(&handle, x, bottom, SIDE, SIDE)?;
}
c.set_fill_rgb(0.0, 0.0, 0.0)?;
caption(&mut c, font, (x, bottom - 12.0), words.made[index])?;
caption(&mut c, font, (x, bottom - 22.0), &said)?;
}
let mut page = Page::a4();
page.content = c.into_bytes();
Ok(page)
}
/// The last cell of the second page: a picture read as L*a*b*, over its title
/// and the components each of its pixels carries.
fn measured_cell(
doc: &mut Document,
c: &mut Content,
font: &FontHandle,
words: &Words,
) -> Result<(), Box<dyn std::error::Error>> {
let measured = Image::from_rgb(TILE, TILE, &lab_samples())?.into_measured_color(lab_space())?;
let components = words
.components
.replace("{count}", &measured.color_space().components().to_string());
let (x, top) = cell(15)?;
let handle = doc.add_image(measured);
c.draw_image(&handle, x, top - SIDE, SIDE, SIDE)?;
caption(c, font, (x, top - SIDE - 12.0), words.measured)?;
caption(c, font, (x, top - SIDE - 22.0), &components)?;
Ok(())
}
/// The second page: the letter turned by each of the eight orientations, and
/// four pictures read from files, the last on a layer, then the letter written
/// inline and a picture read as measured colour.
fn second_page(
doc: &mut Document,
font: &FontHandle,
words: &Words,
) -> Result<Page, Box<dyn std::error::Error>> {
let mut c = Content::new();
c.begin_text();
c.set_font(font, 16.0)?;
c.text_origin(LEFT, 790.0)?;
c.show_glyphs(&font.glyphs(words.files));
c.end_text();
let letter = Image::from_rgb(8, 12, &letter_f())?;
for number in 1..=8u16 {
let index = usize::from(number - 1);
let (x, top) = cell(index)?;
let Some(orientation) = Orientation::from_tag(number) else {
continue;
};
let turned = letter.clone().with_orientation(Some(orientation));
// The box is the picture as it is seen: turned a quarter, it is as wide
// as it was tall.
let (box_width, box_height) = if orientation.swaps_axes() {
(SIDE, SIDE * 8.0 / 12.0)
} else {
(SIDE * 8.0 / 12.0, SIDE)
};
let handle = doc.add_image(turned);
c.draw_image(&handle, x, top - box_height, box_width, box_height)?;
let kept_or_swapped = words.swaps[usize::from(!orientation.swaps_axes())];
let said = words
.tag
.replace("{tag}", &orientation.tag().to_string())
.replace("{swap}", kept_or_swapped);
let entries = orientation.matrix()[..4]
.iter()
.map(f64::to_string)
.collect::<Vec<_>>()
.join(" ");
caption(
&mut c,
font,
(x, top - SIDE - 12.0),
words.orientations[index],
)?;
caption(&mut c, font, (x, top - SIDE - 22.0), &said)?;
caption(
&mut c,
font,
(x, top - SIDE - 32.0),
&words.matrix.replace("{matrix}", &entries),
)?;
}
let (x, top) = cell(12)?;
c.draw_inline_image(&letter, x, top - SIDE, SIDE * 8.0 / 12.0, SIDE)?;
caption(&mut c, font, (x, top - SIDE - 12.0), words.inline)?;
measured_cell(doc, &mut c, font, words)?;
let images = tests_dir().join("images");
let photographs = doc.add_layer(Layer::new(words.layer))?;
let pictures = [
Image::from_png(&fs::read(images.join("logo.png"))?)?,
Image::from_jpeg(fs::read(images.join("jfif_300dpi.jpg"))?)?,
Image::from_bmp(&fs::read(images.join("truecolour.bmp"))?)?,
Image::from_tiff(&fs::read(images.join("photograph.tif"))?)?.layer(&photographs),
];
let channels = Image::tiff_channel_names(&fs::read(images.join("pages.tif"))?, 0)?.len();
for (place, picture) in pictures.into_iter().enumerate() {
let (x, top) = cell(8 + place)?;
let (wide, tall) = picture.size_at_dpi(300.0)?;
let at_dpi = words
.at_dpi
.replace("{width}", &format!("{wide:.0}"))
.replace("{height}", &format!("{tall:.0}"));
let stated = picture.resolution().map_or_else(
|| words.unstated.to_owned(),
|dpi| {
let same = Resolution::square(dpi.x()).is_ok_and(|square| square == dpi);
words
.stated
.replace("{x}", &format!("{:.0}", dpi.x()))
.replace("{y}", &format!("{:.0}", dpi.y()))
.replace("{square}", words.square[usize::from(!same)])
},
);
let last = match place {
3 => words.channels.replace("{count}", &channels.to_string()),
_ => String::new(),
};
let handle = doc.add_image(picture);
let (fitted_width, fitted_height) = handle.fit_within(SIDE, SIDE)?;
c.draw_image(&handle, x, top - fitted_height, fitted_width, fitted_height)?;
caption(&mut c, font, (x, top - SIDE - 12.0), words.read[place])?;
caption(&mut c, font, (x, top - SIDE - 22.0), &at_dpi)?;
caption(&mut c, font, (x, top - SIDE - 32.0), &stated)?;
if !last.is_empty() {
caption(&mut c, font, (x, top - SIDE - 42.0), &last)?;
caption(
&mut c,
font,
(x, top - SIDE - 52.0),
&words.on_layer.replace("{layer}", words.layer),
)?;
}
}
let mut page = Page::a4();
page.content = c.into_bytes();
Ok(page)
}
fn main() -> std::process::ExitCode {
failure::reported(run())
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
let language = Language::from_environment()?;
let words = Words::of(language);
let path = env::args()
.nth(1)
.unwrap_or_else(|| language.file_name(&out::default_path("image_settings")));
let mut doc = Document::new();
doc.set_license(licence::licensed());
doc.set_info(Name::new("Title"), words.title);
let font = doc.add_font(Font::parse(fs::read(
tests_dir().join("fonts").join("DejaVuSans.ttf"),
)?)?);
let page = first_page(&mut doc, &font, words)?;
doc.add_page(page)?;
let page = second_page(&mut doc, &font, words)?;
doc.add_page(page)?;
let bytes = doc.to_bytes()?;
if let Some(parent) = Path::new(&path).parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, &bytes)?;
println!("wrote {} ({} bytes)", path, bytes.len());
Ok(())
}
#[cfg(test)]
mod tests {
use super::{WORDS, language};
/// The lines two languages are allowed to write the same way: the words the
/// two languages share for one rendering intent.
const SPARED: [&str; 21] = [
"\"saturation\"",
// Written the same way in German.
r#"stated: "{x} × {y} dpi, {square}""#,
// Written the same way in Spanish.
r#""no""#,
r#""perceptual""#,
// Written the same way in Italian.
r#"matrix: "matrice [{matrix}]""#,
r#"stencil: "stencil: {answer}""#,
r#"tag: "tag {tag}; {swap}""#,
// Written the same way in Portuguese.
r#""colorimétrica absoluta""#,
r#""colorimétrica relativa""#,
r#"at_dpi: "a 300 ppp: {width} × {height} pt""#,
r#"bits: "{bits} bits por componente""#,
r#"components: "componentes por píxel: {count}""#,
r#"matrix: "matriz [{matrix}]""#,
r#"profile: "perfil de {bytes} bytes, {intent}""#,
r#"size: "{width} × {height} px, {count} componentes""#,
r#"smoothed: "suavizada: {answer}""#,
r#"soft: "máscara suave: {answer}""#,
r#"stated: "{x} × {y} ppp, {square}""#,
r#"tag: "etiqueta {tag}; {swap}""#,
// Written the same way in Dutch.
r#""ja""#,
r#"matrix: "matrix [{matrix}]""#,
];
#[test]
fn every_language_writes_the_pages_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the pages say these in more than one language: {untranslated:?}"
);
}
/// Every caption is set on one line under a picture, and runs no wider than
/// the room left before the next picture; the figures are the widest the
/// pages give them.
#[test]
fn every_language_writes_captions_that_fit_their_cell() {
let mut doc = hqf_pdf::Document::new();
let font = doc.add_font(
hqf_pdf::Font::parse(
std::fs::read(super::tests_dir().join("fonts").join("DejaVuSans.ttf"))
.expect("the committed font is there"),
)
.expect("the committed font parses"),
);
let room = super::ACROSS - 4.0;
for (named, words) in WORDS {
let code = named.code();
let mut lines: Vec<String> = words
.made
.iter()
.chain(&words.orientations)
.chain(&words.read)
.map(|line| (*line).to_owned())
.collect();
lines.extend([
words
.size
.replace("{width}", "32")
.replace("{height}", "32")
.replace("{count}", "4"),
words.keyed.replace("{ranges}", "0–90, 0–90, 0–255"),
words.decoded.replace("{ranges}", "1–0, 1–0, 1–0"),
words
.profile
.replace("{bytes}", "6656")
.replace("{intent}", words.intents[0]),
words
.stated
.replace("{x}", "300")
.replace("{y}", "300")
.replace("{square}", words.square[1]),
words
.at_dpi
.replace("{width}", "100")
.replace("{height}", "100"),
words.channels.replace("{count}", "0"),
words.on_layer.replace("{layer}", words.layer),
words
.tag
.replace("{tag}", "8")
.replace("{swap}", words.swaps[0]),
]);
for title in [words.title, words.files] {
let measured = font.measure(title, 16.0);
assert!(
measured <= 483.0,
"the {code} pages head a page with {title:?} over {measured:.1} points"
);
}
for line in lines {
let measured = font.measure(&line, super::CAPTION);
assert!(
measured <= room,
"the {code} pages set {line:?} over {measured:.1} points, and a \
cell has {room:.1}"
);
}
}
}
}
|