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 | //! Writes a page of QR codes, drawn as squares.
//!
//! Whether a QR 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_qr.sh` points a decoder at the
//! rendered image and compares.
//!
//! 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.
//!
//! Under the first row stand four codes built other ways: figures in the
//! numeric mode, a text at the highest correction, bytes as they are, and bytes
//! at a stated correction. A line under them counts the last one's dark
//! modules, read square by square.
//!
//! Usage: `cargo run --example write_qr -- tmp/qr.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_qr -- tmp/qr_fr.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::qr::{Correction, Mode, QUIET_ZONE};
use hqf_pdf::{Document, Error, Font, FontHandle, License, Page, QrCode};
#[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: an invoice link, a payment reference, and a line of
/// mixed punctuation.
const CARRIED: &[&str] = &[
"https://example.test/invoice/FR-1964413",
"REF 2026-07-16/ACME",
"a-Z 0..9 +*#% and on",
];
/// A payload of figures only, written in the numeric mode.
const NUMERIC: &str = "20260716";
/// A payload written at the highest correction.
const CORRECTED: &str = "HQF-2026-0917";
/// A payload handed over as bytes, as they are.
const BYTES: &str = "HQF BYTES 2026";
/// A payload handed over as bytes, at a stated correction.
const LOT: &str = "LOT 4472";
/// How far the foot of one row of codes stands under the foot of the row above
/// it.
const ROW_STEP: f64 = 140.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;
/// Where the foot of the row of codes sits, in points up from the foot of the
/// sheet.
const TOP: f64 = 640.0;
/// How far in from the left edge of the sheet the head of the page is set. The
/// quiet zone of the first code starts here too, so the heading stands over the
/// left edge of the row of codes.
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 the codes that counts the last one's dark modules;
/// `{dark}` and `{all}` stand for the two counts.
dark: &'static str,
}
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: "QR codes, drawn as squares",
lines: [
"A QR code holds a link or a reference that a telephone reads in one shot. It is",
"drawn square by square here, so it stays readable at any size it is printed at.",
],
dark: "The last code holds {dark} dark modules out of {all}.",
};
/// The head of the sheet in French.
const FRENCH: Words = Words {
title: "Des codes QR, dessinés en carrés",
lines: [
"Un code QR contient un lien ou une référence qu’un téléphone lit d’un seul coup. Il",
"est dessiné ici carré par carré : il reste donc lisible à toute taille d’impression.",
],
dark: "Le dernier code compte {dark} modules sombres sur {all}.",
};
/// The head of the sheet in Dutch.
const DUTCH: Words = Words {
title: "QR-codes, getekend als vierkantjes",
lines: [
"Een QR-code bevat een link of een kenmerk dat een telefoon in één keer leest. Hij is",
"hier vierkantje voor vierkantje getekend, dus blijft hij leesbaar op elk drukformaat.",
],
dark: "De laatste code heeft {dark} donkere modules van de {all}.",
};
/// The head of the sheet in Portuguese.
const PORTUGUESE: Words = Words {
title: "Códigos QR, desenhados como quadrados",
lines: [
"Um código QR guarda uma ligação ou referência que um telemóvel lê de uma vez.",
"Aqui é desenhado quadrado a quadrado: lê-se em qualquer tamanho impresso.",
],
dark: "O último código tem {dark} módulos escuros em {all}.",
};
/// The head of the sheet in Italian.
const ITALIAN: Words = Words {
title: "Codici QR, disegnati a quadrati",
lines: [
"Un codice QR contiene un link o un riferimento che un telefono legge in un colpo.",
"Qui è disegnato quadrato per quadrato: resta leggibile a ogni formato di stampa.",
],
dark: "L’ultimo codice ha {dark} moduli scuri su {all}.",
};
/// The head of the sheet in Spanish.
const SPANISH: Words = Words {
title: "Códigos QR, dibujados como cuadrados",
lines: [
"Un código QR guarda un enlace o una referencia que un teléfono lee de una vez.",
"Aquí se dibuja cuadrado a cuadrado, así que se lee a cualquier tamaño de impresión.",
],
dark: "El último código tiene {dark} módulos oscuros de {all}.",
};
/// The head of the sheet in German.
const GERMAN: Words = Words {
title: "QR-Codes, als Quadrate gezeichnet",
lines: [
"Ein QR-Code fasst einen Link oder eine Referenz, die ein Handy mit einem Blick liest.",
"Hier Quadrat für Quadrat gezeichnet, bleibt er in jeder Druckgröße lesbar.",
],
dark: "Der letzte Code hat {dark} dunkle Module von {all}.",
};
/// 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("qr")));
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)?;
let quiet = f64::from(u32::try_from(QUIET_ZONE)?) * MODULE;
let mut left = MARGIN;
let top = TOP;
for carried in CARRIED {
let code = QrCode::new(carried)?;
let side = f64::from(u32::try_from(code.size())?) * MODULE;
let caption = font.measure(carried, 8.0);
// The quiet zone is the caller's: the code is drawn that far in, and
// nothing else is drawn beside it.
content.draw_qr(&code, left + quiet, top, side)?;
content.begin_text();
content.set_font(&font, 8.0)?;
content.text_origin(left + quiet, top - 12.0)?;
content.show_glyphs(&font.glyphs(carried));
content.end_text();
left += side.max(caption) + quiet.mul_add(2.0, 24.0);
}
// Four more, each built another way: figures in the numeric mode, a text at
// the highest correction, bytes as they are, and bytes at a stated
// correction.
let others = [
(QrCode::with_mode(NUMERIC, Mode::Numeric)?, NUMERIC),
(
QrCode::with_correction(CORRECTED, Correction::High)?,
CORRECTED,
),
(QrCode::from_bytes(BYTES.as_bytes())?, BYTES),
(
QrCode::from_bytes_with_correction(LOT.as_bytes(), Correction::Quartile)?,
LOT,
),
];
let mut row_top = TOP;
for row in others.chunks(3) {
row_top -= ROW_STEP;
let mut left = MARGIN;
for (code, carried) in row {
let side = f64::from(u32::try_from(code.size())?) * MODULE;
let caption = font.measure(carried, 8.0);
content.draw_qr(code, left + quiet, row_top, side)?;
content.begin_text();
content.set_font(&font, 8.0)?;
content.text_origin(left + quiet, row_top - 12.0)?;
content.show_glyphs(&font.glyphs(carried));
content.end_text();
left += side.max(caption) + quiet.mul_add(2.0, 24.0);
}
}
// How many modules of the last code are dark, read square by square.
let (last, _) = &others[others.len() - 1];
let size = last.size();
let lit = (0..size)
.flat_map(|row| (0..size).filter(move |column| last.is_dark(row, *column)))
.count();
let counted = words
.dark
.replace("{dark}", &lit.to_string())
.replace("{all}", &(size * size).to_string());
content.begin_text();
content.set_font(&font, BODY)?;
content.text_origin(MARGIN, row_top - 50.0)?;
content.show_glyphs(&font.glyphs(&counted));
content.end_text();
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, QrCode};
use super::{
BODY, CARRIED, HEAD_GAP, HEAD_TOP, HEADING, LINE_STEP, MARGIN, MODULE, 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. The heading
/// and the lines under it are the whole of `Words`, and no two languages
/// write one alike; what the codes carry is read by a scanner rather than
/// by a person, so it stands apart from them.
const SPARED: [&str; 0] = [];
/// 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}"
);
}
}
}
/// The head of the sheet is set above the codes, and the tallest of them is
/// the one that 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() {
let tallest = CARRIED
.iter()
.map(|carried| {
QrCode::new(carried)
.expect("what the codes carry is a code a QR symbol holds")
.size()
})
.max()
.expect("the page carries at least one code");
let codes = f64::from(u32::try_from(tallest).expect("a symbol is a few dozen modules"))
.mul_add(MODULE, TOP);
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 >= codes,
"the {} head ends on a line at {last:.1} points, and the codes \
reach {codes:.1}",
named.code()
);
}
}
}
|