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 | //! Writes a page of Aztec codes, drawn as squares.
//!
//! Whether an Aztec code works is not a question the page can answer, and not
//! one a human eye can: it is answered by a scanner. So the page carries what
//! each code says under it, and `scripts/check_aztec.sh` points a decoder at
//! the rendered image and compares.
//!
//! An Aztec code needs no quiet zone: a scanner finds the bullseye at its
//! centre without one. The codes are still set apart from each other, so that
//! one code's modules are not read as another's.
//!
//! The head of the sheet says what the squares are for, so that the page is
//! worth something to whoever opens it without the code beside it. Those words
//! are held in `Words`, once per language, and `HQF_PDF_LANG` picks which set
//! the sheet is headed in. What the codes carry stands apart from them: a
//! scanner reads it, not a person, and it is the same in every language.
//!
//! A second column holds three more, each built another way: a text at the
//! correction the library chooses, bytes as they are, and bytes at a stated
//! correction. Each says under its payload how many layers it has, whether it
//! is compact, and how many of its modules are dark.
//!
//! Usage: `cargo run --example write_aztec -- tmp/aztec.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_aztec --
//! tmp/aztec_fr.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::aztec::DEFAULT_CORRECTION;
use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::{Aztec, Document, Error, Font, FontHandle, License, Page};
#[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")
}
/// What the codes carry, and how much of each is given over to error
/// correction: a boarding pass at the share the standard advises, a tracking
/// link at twice that, and a line of mixed punctuation at the least a code will
/// take.
const CARRIED: &[(&str, u32)] = &[
("HQF2026 PARIS LONDON 14B 07JUL", DEFAULT_CORRECTION),
("https://example.test/track/FR-1964413", 46),
("a-Z 0..9 +*#% and on", 5),
];
/// A text at the correction the library chooses when none is given.
const PLAIN: &str = "HQF AZTEC 2026";
/// A payload handed over as bytes, as they are.
const BYTES: &str = "AZTEC BYTES";
/// A payload handed over as bytes, at a stated correction.
const LOT: &str = "LOT 4472";
/// Where the second column of codes stands.
const SECOND_COLUMN: f64 = 330.0;
/// The side of one module, in points. Four pixels to a module at 288dpi, so
/// every module's edge lands on a pixel boundary.
const MODULE: f64 = 3.0;
/// The clear space left between one code and the next, in points.
const GAP: f64 = 18.0;
/// How far to the right of a code its label is set, in points.
const LABEL: f64 = 12.0;
/// Where the head of the first code sits, in points up from the foot of the
/// sheet.
const TOP: f64 = 700.0;
/// How far in from the left edge of the sheet the head of the page is set. The
/// codes stand there too, so the heading stands over their left edge.
const MARGIN: f64 = 72.0;
/// Where the baseline of the heading sits, in points up from the foot of the
/// sheet.
const HEAD_TOP: f64 = 794.0;
/// The size the heading is set at, in points.
const HEADING: f64 = 16.0;
/// The size the lines under the heading are set at, in points.
const BODY: f64 = 10.5;
/// How far under the heading the first line beneath it sits, in points.
const HEAD_GAP: f64 = 24.0;
/// How far below one line under the heading the next one sits, in points.
const LINE_STEP: f64 = 15.0;
/// The words the sheet is headed in, one set per language.
#[derive(Debug)]
struct Words {
/// What the page says it is, at its head and in what the file says of
/// itself.
title: &'static str,
/// What the page says under its heading.
lines: [&'static str; 2],
/// The line under a code of the second column that says its shape;
/// `{layers}`, `{kind}` and `{dark}` stand for what is read back from it.
shape: &'static str,
/// What a compact code and a full-range one are called.
kinds: [&'static str; 2],
}
impl Words {
/// The words the sheet is headed in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The head of the sheet in English.
const ENGLISH: Words = Words {
title: "Aztec codes, drawn as squares",
lines: [
"An Aztec code asks for no white margin around it, so it fits where nothing else",
"would; a train ticket carries one. Beside each is what a scanner reads back.",
],
shape: "{kind}, layers: {layers}, dark modules: {dark}",
kinds: ["compact", "full-range"],
};
/// The head of the sheet in French.
const FRENCH: Words = Words {
title: "Des codes Aztec, dessinés en carrés",
lines: [
"Un code Aztec ne demande aucune marge blanche autour de lui : il tient là où rien",
"d’autre ne tiendrait. Un billet de train en comporte un. À côté, ce qu’un scanner y lit.",
],
shape: "{kind}, couches\u{a0}: {layers}, modules sombres\u{a0}: {dark}",
kinds: ["compact", "pleine taille"],
};
/// The head of the sheet in Dutch.
const DUTCH: Words = Words {
title: "Aztec-codes, getekend als vierkantjes",
lines: [
"Een Aztec-code vraagt geen witte rand, dus past hij waar niets anders zou",
"passen; op een treinkaartje staat er een. Ernaast wat een scanner teruggeeft.",
],
shape: "{kind}, lagen: {layers}, donkere modules: {dark}",
kinds: ["compact", "volledig bereik"],
};
/// The head of the sheet in Portuguese.
const PORTUGUESE: Words = Words {
title: "Códigos Aztec, desenhados como quadrados",
lines: [
"Um código Aztec não pede margem branca à volta, por isso cabe onde nada mais",
"caberia; um bilhete de comboio leva um. Ao lado, o que um leitor lê nele.",
],
shape: "{kind}, camadas: {layers}, módulos escuros: {dark}",
kinds: ["compacto", "completo"],
};
/// The head of the sheet in Italian.
const ITALIAN: Words = Words {
title: "Codici Aztec, disegnati a quadrati",
lines: [
"Un codice Aztec non chiede margine bianco intorno, così entra dove nient’altro",
"entrerebbe; un biglietto del treno ne porta uno. Accanto, ciò che legge uno scanner.",
],
shape: "{kind}, strati: {layers}, moduli scuri: {dark}",
kinds: ["compatto", "gamma completa"],
};
/// The head of the sheet in Spanish.
const SPANISH: Words = Words {
title: "Códigos Aztec, dibujados como cuadrados",
lines: [
"Un código Aztec no pide margen blanco alrededor, así que cabe donde nada más",
"cabría; un billete de tren lleva uno. Al lado, lo que lee un escáner.",
],
shape: "{kind}, capas: {layers}, módulos oscuros: {dark}",
kinds: ["compacto", "rango completo"],
};
/// The head of the sheet in German.
const GERMAN: Words = Words {
title: "Aztec-Codes, als Quadrate gezeichnet",
lines: [
"Ein Aztec-Code braucht keinen weißen Rand und passt, wo sonst nichts",
"Platz hätte; eine Fahrkarte trägt einen. Daneben steht, was ein Scanner liest.",
],
shape: "{kind}, Lagen: {layers}, dunkle Module: {dark}",
kinds: ["kompakt", "Vollformat"],
};
/// 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 heading, and the lines under it that say what the page is for.
fn head(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
content.begin_text();
content.set_font(font, HEADING)?;
content.text_origin(MARGIN, HEAD_TOP)?;
content.show_glyphs(&font.glyphs(words.title));
content.end_text();
let mut y = HEAD_TOP - HEAD_GAP;
for line in words.lines {
content.begin_text();
content.set_font(font, BODY)?;
content.text_origin(MARGIN, y)?;
content.show_glyphs(&font.glyphs(line));
content.end_text();
y -= LINE_STEP;
}
Ok(())
}
fn main() -> std::process::ExitCode {
failure::reported(run())
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
let language = Language::from_environment()?;
let words = Words::of(language);
let mut args: Vec<String> = env::args().skip(1).collect();
let evaluation = args.iter().any(|arg| arg == "--evaluation");
args.retain(|arg| !arg.starts_with("--"));
let mut args = args.into_iter();
// A named file is written as named; the default one carries the language,
// so the two languages do not overwrite each other in `tmp/`.
let path = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("aztec")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let mut doc = Document::new();
doc.set_license(if evaluation {
License::evaluation()
} else {
licence::licensed()
});
doc.set_info(Name::new("Title"), words.title);
let font: FontHandle = doc.add_font(Font::parse(fs::read(&font_path)?)?);
let mut content = Content::new();
content.set_fill_rgb(0.0, 0.0, 0.0)?;
head(&mut content, &font, words)?;
// One code to a row, its label level with the middle of it, so no label
// runs into the code or the label beside it.
let left = MARGIN;
let mut top = TOP;
for (carried, correction) in CARRIED {
let code = Aztec::with_correction(carried, *correction)?;
let side = f64::from(u32::try_from(code.size())?) * MODULE;
let bottom = top - side;
content.draw_aztec(&code, left, bottom, side)?;
content.begin_text();
content.set_font(&font, 8.0)?;
content.text_origin(left + side + LABEL, bottom + side / 2.0)?;
content.show_glyphs(&font.glyphs(carried));
content.end_text();
top = bottom - GAP;
}
// A second column, each code built another way and read back for its shape:
// how many layers it has, whether it is compact, and how many of its
// modules are dark.
let others = [
(Aztec::new(PLAIN)?, PLAIN),
(Aztec::from_bytes(BYTES.as_bytes())?, BYTES),
(Aztec::from_bytes_with_correction(LOT.as_bytes(), 50)?, LOT),
];
let mut top = TOP;
for (code, carried) in &others {
let modules = code.size();
let side = f64::from(u32::try_from(modules)?) * MODULE;
let bottom = top - side;
content.draw_aztec(code, SECOND_COLUMN, bottom, side)?;
let lit = (0..modules)
.flat_map(|row| (0..modules).filter(move |column| code.is_dark(row, *column)))
.count();
let shape = words
.shape
.replace("{layers}", &code.layers().to_string())
.replace("{kind}", words.kinds[usize::from(!code.is_compact())])
.replace("{dark}", &lit.to_string());
for (line, lift) in [(*carried, 5.0), (shape.as_str(), -6.0)] {
content.begin_text();
content.set_font(&font, 8.0)?;
content.text_origin(SECOND_COLUMN + side + LABEL, bottom + side / 2.0 + lift)?;
content.show_glyphs(&font.glyphs(line));
content.end_text();
}
top = bottom - GAP;
}
let mut page = Page::a4();
page.content = content.into_bytes();
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 hqf_pdf::{Document, Font};
use super::{
BODY, HEAD_GAP, HEAD_TOP, HEADING, LINE_STEP, MARGIN, TOP, WORDS, default_font, language,
};
/// The width of the sheet, in points: A4, which the page is.
const SHEET_WIDTH: f64 = 595.276;
/// The lines two languages are allowed to write the same way: a compact
/// code is called compact in French as in English. What the codes carry is
/// read by a scanner rather than by a person, so it stands apart from the
/// words.
const SPARED: [&str; 2] = [
"\"compact\"",
// Written the same way in Portuguese.
r#""compacto""#,
];
/// The room a line set from the left margin has before it reaches the
/// margin on the other side of the sheet.
const PAPER: f64 = SHEET_WIDTH - 2.0 * MARGIN;
#[test]
fn every_language_heads_the_sheet_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the sheet says these in more than one language: {untranslated:?}"
);
}
/// Nothing at the head of the sheet is broken to a width: a line longer
/// than the paper runs off the edge of it.
#[test]
fn every_language_writes_lines_that_fit_the_room_they_have() {
let mut doc = Document::new();
let text = doc.add_font(
Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
.expect("the committed font parses"),
);
for (named, words) in WORDS {
let code = named.code();
let lines =
std::iter::once((HEADING, words.title)).chain(words.lines.map(|line| (BODY, line)));
for (size, line) in lines {
let measured = text.measure(line, size);
assert!(
measured <= PAPER,
"the {code} sheet draws {line:?} over {measured:.1} points, \
and it has {PAPER:.1}"
);
}
}
}
/// Every code hangs from the same head, so the first of them reaches
/// highest. A line too many at the head would be drawn over it.
#[test]
fn the_head_of_the_sheet_stands_clear_of_the_codes() {
for (named, words) in WORDS {
let count = u32::try_from(words.lines.len()).expect("a head has few lines");
let last = LINE_STEP.mul_add(-f64::from(count - 1), HEAD_TOP - HEAD_GAP);
assert!(
last - BODY >= TOP,
"the {} head ends on a line at {last:.1} points, and the codes \
reach {TOP:.1}",
named.code()
);
}
}
}
|