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 | //! Writes a page of barcodes, drawn as bars: Code 128 for arbitrary text, an
//! EAN-13 for a thirteen-digit article number, a UPC-A for its twelve-digit
//! North American cousin, and a short EAN-8.
//!
//! A second page sizes its modules as a whole number of pixels of the device,
//! sets the same digits in Code 128 paired and one by one, sets a UPC-E with
//! its digits and the UPC-A it stands for, and an EAN-13 with a five-digit
//! add-on beside it, the add-on's digits over it.
//!
//! Whether a barcode 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
//! barcode says under it, and `scripts/check_barcode.sh` points a decoder at
//! the rendered image and compares.
//!
//! The head of the sheet says what the bars 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 barcodes carry stands apart from them: a
//! scanner reads it, not a person, and it is the same in every language.
//!
//! The digits under the three retail codes are set in Spectral, whatever font
//! the rest is written in: they are sized by the capital height a face states,
//! and Spectral states it.
//!
//! Usage: `cargo run --example write_barcode -- tmp/barcode.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_barcode --
//! tmp/barcode_fr.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::barcode::{
ADD_ON_SEPARATION, DIGIT_DEPTH, DIGIT_HEIGHT, GUARD_EXTENSION, Module, QUIET_ZONE,
};
use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::{
AddOn5, Code128, Document, Ean8, Ean13, Error, Font, FontHandle, License, Page, UpcA, UpcE,
};
#[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")
}
/// The font the digits under the retail codes are set in.
fn digit_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("Spectral-Regular.ttf")
}
/// What the Code 128 barcodes carry: an invoice number, a payment reference,
/// and a line holding every kind of character code set B carries.
const CARRIED: &[&str] = &["FR-1964413", "REF 2026-07-16/ACME", "a-Z 0..9 +*#%"];
/// The thirteen-digit article number the EAN-13 barcode carries.
const ARTICLE: &str = "9780201379624";
/// The twelve-digit article number the UPC-A barcode carries.
const UPC_ARTICLE: &str = "036000291452";
/// The eight-digit article number the EAN-8 barcode carries.
const EAN8_ARTICLE: &str = "96385074";
/// The digits the two Code 128 barcodes of the second page carry, the one
/// packing them two to a character, the other setting them one by one.
const PAIRED: &str = "40063813339301";
/// The eight digits the UPC-E barcode carries.
const UPC_E_ARTICLE: &str = "01234565";
/// The five digits the add-on beside the second page's EAN-13 carries.
const ADD_ON: &str = "52495";
/// The resolution the modules of the second page are a whole number of pixels
/// at, in dots per inch: the one `scripts/check_barcode.sh` renders at.
const DPI: f64 = 288.0;
/// The size the lines under the second page's codes are set at, in points.
const CAPTION: f64 = 9.0;
/// The width of the narrowest bar, in points. Everything else is a whole number
/// of these.
const MODULE: f64 = 1.0;
/// How tall the bars are drawn, in points.
const BAR_HEIGHT: f64 = 40.0;
/// Where the foot of the first barcode 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
/// quiet zone of the first barcode starts here too, so the heading stands over
/// the left edge of the block of bars.
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 second page's heading.
more_title: &'static str,
/// What the second page says under its heading.
more_lines: [&'static str; 2],
/// What the Code 128 packing digits in pairs is; `{modules}` stands for how
/// many modules it counts and `{pixels}` for the pixels to a module.
paired: &'static str,
/// What the Code 128 setting the same digits one by one is; `{modules}`
/// stands for how many modules it counts.
spelt: &'static str,
/// What the UPC-E is; `{upc_a}` stands for the UPC-A it stands for.
short: &'static str,
/// What the EAN-13 and its add-on are; `{extra}` stands for the add-on's
/// digits and `{gap}` for the modules between the two.
add_on: &'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: "Barcodes, drawn as bars",
lines: [
"Each barcode below is drawn as bars, not pasted in as a picture, so it prints",
"exactly as wide as it should. Under each one is what a scanner reads back.",
],
more_title: "Codes built and sized other ways",
more_lines: [
"Each module below is a whole number of printer pixels, so every bar edge falls",
"on a pixel. Under each code, what it carries and how it was built.",
],
paired: "Digits packed two to a character: {modules} modules of {pixels} pixels at 288 dpi",
spelt: "The same digits one character at a time: {modules} modules",
short: "A UPC-E, its zeros left out: a scanner hands back the UPC-A {upc_a}",
add_on: "An EAN-13 with the five-digit add-on {extra} beside it, {gap} modules away",
};
/// The head of the sheet in French.
const FRENCH: Words = Words {
title: "Des codes-barres, dessinés en barres",
lines: [
"Chaque code-barres ci-dessous est dessiné en barres, pas collé comme une image :",
"il s’imprime exactement à la bonne largeur. Sous chacun, ce qu’un scanner y lit.",
],
more_title: "Des codes construits et dimensionnés autrement",
more_lines: [
"Chaque module ci-dessous vaut un nombre entier de pixels de l’imprimante :",
"tout bord de barre tombe sur un pixel. Sous chaque code : contenu et construction.",
],
paired: "Chiffres groupés par deux : {modules} modules de {pixels} pixels à 288 ppp",
spelt: "Les mêmes chiffres un par un : {modules} modules",
short: "Un UPC-E, ses zéros omis : un scanner y lit l’UPC-A {upc_a}",
add_on: "Un EAN-13 suivi de son code complémentaire à cinq chiffres {extra}, à {gap} modules",
};
/// The head of the sheet in Dutch.
const DUTCH: Words = Words {
title: "Streepjescodes, getekend als streepjes",
lines: [
"Elke code hieronder is getekend als streepjes, niet als afbeelding geplakt, dus",
"wordt hij precies zo breed gedrukt als hij moet. Eronder wat een scanner leest.",
],
more_title: "Codes die anders zijn opgebouwd en bemeten",
more_lines: [
"Elke module hieronder is een geheel aantal printerpixels breed, dus valt elke",
"streeprand op een pixel. Eronder wat hij bevat en hoe hij is opgebouwd.",
],
paired: "Cijfers per twee in een teken: {modules} modules van {pixels} pixels bij 288 dpi",
spelt: "Dezelfde cijfers één per teken: {modules} modules",
short: "Een UPC-E zonder zijn nullen: een scanner geeft de UPC-A {upc_a} terug",
add_on: "Een EAN-13 met de vijfcijferige toevoeging {extra} ernaast, {gap} modules verderop",
};
/// The head of the sheet in Portuguese.
const PORTUGUESE: Words = Words {
title: "Códigos de barras, desenhados como barras",
lines: [
"Cada código abaixo é desenhado como barras, não colado como imagem, por isso",
"imprime-se com a largura exata. Por baixo de cada um, o que um leitor lê.",
],
more_title: "Códigos construídos e dimensionados de outras formas",
more_lines: [
"Cada módulo abaixo mede um número inteiro de píxeis da impressora, por isso cada",
"aresta de barra cai num píxel. Por baixo, o que leva e como foi construído.",
],
paired: "Algarismos dois a dois por carácter: {modules} módulos de {pixels} píxeis a 288 ppp",
spelt: "Os mesmos algarismos um a um: {modules} módulos",
short: "Um UPC-E sem os seus zeros: um leitor devolve o UPC-A {upc_a}",
add_on: "Um EAN-13 com o suplemento de cinco algarismos {extra} ao lado, a {gap} módulos",
};
/// The head of the sheet in Italian.
const ITALIAN: Words = Words {
title: "Codici a barre, disegnati a barre",
lines: [
"Ogni codice qui sotto è disegnato a barre, non incollato come immagine, così si",
"stampa esattamente largo quanto deve. Sotto ciascuno, ciò che legge uno scanner.",
],
more_title: "Codici costruiti e dimensionati in altri modi",
more_lines: [
"Ogni modulo qui sotto misura un numero intero di pixel di stampante, così ogni",
"bordo di barra cade su un pixel. Sotto, ciò che porta e come è stato costruito.",
],
paired: "Cifre, due per carattere: {modules} moduli di {pixels} pixel a 288 dpi",
spelt: "Le stesse cifre, una per carattere: {modules} moduli",
short: "Un UPC-E senza i suoi zeri: uno scanner restituisce l’UPC-A {upc_a}",
add_on: "Un EAN-13 con l’aggiunta a cinque cifre {extra} accanto, a {gap} moduli",
};
/// The head of the sheet in Spanish.
const SPANISH: Words = Words {
title: "Códigos de barras, dibujados como barras",
lines: [
"Cada código de abajo se dibuja como barras, no se pega como imagen, así que se",
"imprime con el ancho exacto. Debajo de cada uno, lo que lee un escáner.",
],
more_title: "Códigos construidos y dimensionados de otras formas",
more_lines: [
"Cada módulo de abajo mide un número entero de píxeles de impresora, así que",
"cada borde de barra cae en un píxel. Debajo, lo que lleva y cómo se construyó.",
],
paired: "Dos cifras por carácter: {modules} módulos de {pixels} píxeles a 288 ppp",
spelt: "Las mismas cifras, una por carácter: {modules} módulos",
short: "Un UPC-E sin sus ceros: un escáner devuelve el UPC-A {upc_a}",
add_on: "Un EAN-13 con el complemento de cinco cifras {extra} al lado, a {gap} módulos",
};
/// The head of the sheet in German.
const GERMAN: Words = Words {
title: "Strichcodes, als Balken gezeichnet",
lines: [
"Jeder Strichcode unten ist als Balken gezeichnet, nicht als Bild, und wird",
"genau so breit gedruckt, wie er soll. Darunter steht, was ein Scanner liest.",
],
more_title: "Codes, anders aufgebaut und bemessen",
more_lines: [
"Jedes Modul unten misst ganze Druckerpixel, also fällt jede Balkenkante",
"auf ein Pixel. Unter jedem Code steht, was er trägt und wie er gebaut wurde.",
],
paired: "Zwei Ziffern je Zeichen: {modules} Module zu je {pixels} Pixeln bei 288 dpi",
spelt: "Dieselben Ziffern, ein Zeichen nach dem anderen: {modules} Module",
short: "Ein UPC-E ohne seine Nullen: Ein Scanner gibt den UPC-A {upc_a} zurück",
add_on: "Ein EAN-13 mit dem fünfstelligen Zusatz {extra} daneben, {gap} Module entfernt",
};
/// 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 `title`, and the `lines` under it that say what the page is for.
fn head(
content: &mut Content,
font: &FontHandle,
title: &str,
lines: [&str; 2],
) -> Result<(), Error> {
content.begin_text();
content.set_font(font, HEADING)?;
content.text_origin(MARGIN, HEAD_TOP)?;
content.show_glyphs(&font.glyphs(title));
content.end_text();
let mut y = HEAD_TOP - HEAD_GAP;
for line in 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(())
}
/// `lines` set at `left`, the first with its baseline at `y` and each next one
/// a line below it.
fn caption(
content: &mut Content,
font: &FontHandle,
left: f64,
y: f64,
lines: [&str; 2],
) -> Result<(), Error> {
let mut baseline = y;
for line in lines {
content.begin_text();
content.set_font(font, CAPTION)?;
content.text_origin(left, baseline)?;
content.show_glyphs(&font.glyphs(line));
content.end_text();
baseline -= 11.0;
}
Ok(())
}
/// The second page: modules of a whole number of pixels, Code 128 paired and
/// spelt, a UPC-E with its digits, and an EAN-13 with its add-on. `digit_cap`
/// is the capital height of the digits' face at one point.
fn second_page(
font: &FontHandle,
digits: &FontHandle,
digit_cap: f64,
words: &Words,
) -> Result<Page, Box<dyn std::error::Error>> {
let mut content = Content::new();
content.set_fill_rgb(0.0, 0.0, 0.0)?;
head(&mut content, font, words.more_title, words.more_lines)?;
// A third of a millimetre asked for, made a whole number of pixels.
let module = Module::on_pixels(0.33 * 72.0 / 25.4, DPI)?;
let left = MARGIN + module.across(QUIET_ZONE);
let mut top = TOP - 20.0;
for (code, said) in [
(Code128::numeric(PAIRED)?, words.paired),
(Code128::new(PAIRED)?, words.spelt),
] {
let count = code.module_count();
content.draw_barcode(&code, left, top, module.across(count), BAR_HEIGHT)?;
let described = said
.replace("{modules}", &count.to_string())
.replace("{pixels}", &module.pixels().to_string());
caption(&mut content, font, left, top - 12.0, [PAIRED, &described])?;
top -= 100.0;
}
// Six pixels to a module: half as wide again as the codes above.
let wide = Module::pixels_at(6, DPI)?;
let upc_e = UpcE::new(UPC_E_ARTICLE)?;
let left_e = MARGIN + wide.across(QUIET_ZONE);
let width = wide.across(upc_e.module_count());
content.draw_upc_e(&upc_e, left_e, top, width, BAR_HEIGHT)?;
content.draw_upc_e_digits(&upc_e, digits, left_e, top, width)?;
let described = words.short.replace("{upc_a}", &upc_e.expanded());
let below = DIGIT_DEPTH.mul_add(-wide.points(), top) - 12.0;
caption(
&mut content,
font,
left_e,
below,
[UPC_E_ARTICLE, &described],
)?;
top -= 130.0;
let ean = Ean13::new(ARTICLE)?;
let width = module.across(ean.module_count());
content.draw_ean13(&ean, left, top, width, BAR_HEIGHT)?;
let supplement = AddOn5::new(ADD_ON)?;
let beside = left + width + module.across(ADD_ON_SEPARATION);
content.draw_add_on5(
&supplement,
beside,
top,
module.across(supplement.module_count()),
BAR_HEIGHT,
)?;
// The add-on's digits stand over it, as tall as a retail code's digits.
content.begin_text();
content.set_font(digits, DIGIT_HEIGHT * module.points() / digit_cap)?;
content.text_origin(beside, top + BAR_HEIGHT + 2.0)?;
content.show_glyphs(&digits.glyphs(ADD_ON));
content.end_text();
let described = words
.add_on
.replace("{extra}", ADD_ON)
.replace("{gap}", &ADD_ON_SEPARATION.to_string());
// The guard bars reach below the box: the caption stands under them.
let below = top - module.across(GUARD_EXTENSION) - 12.0;
caption(&mut content, font, left, below, [ARTICLE, &described])?;
let mut page = Page::a4();
page.content = content.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 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("barcode")));
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 digit_face = Font::parse(fs::read(digit_font())?)?;
let digit_cap = digit_face.cap_height(1.0);
let digits: FontHandle = doc.add_font(digit_face);
let mut content = Content::new();
content.set_fill_rgb(0.0, 0.0, 0.0)?;
head(&mut content, &font, words.title, words.lines)?;
let mut top = TOP;
for carried in CARRIED {
let code = Code128::new(carried)?;
// The quiet zone is the caller's: the bars start ten modules in, and
// nothing else is drawn beside them.
let left = f64::from(u32::try_from(QUIET_ZONE)?).mul_add(MODULE, MARGIN);
let width = f64::from(u32::try_from(code.module_count())?) * MODULE;
content.draw_barcode(&code, left, top, width, BAR_HEIGHT)?;
content.begin_text();
content.set_font(&font, 9.0)?;
content.text_origin(left, top - 12.0)?;
content.show_glyphs(&font.glyphs(carried));
content.end_text();
top -= 120.0;
}
let left = f64::from(u32::try_from(QUIET_ZONE)?).mul_add(MODULE, MARGIN);
let ean = Ean13::new(ARTICLE)?;
let width = f64::from(u32::try_from(ean.module_count())?) * MODULE;
content.draw_ean13(&ean, left, top, width, BAR_HEIGHT)?;
// The digits a shop assistant types in stand where the standard sets them,
// with the `>` that marks how far the quiet zone runs.
content.draw_ean13_digits(&ean, &digits, left, top, width, true)?;
top -= 120.0;
let upc = UpcA::new(UPC_ARTICLE)?;
let width = f64::from(u32::try_from(upc.module_count())?) * MODULE;
content.draw_upc_a(&upc, left, top, width, BAR_HEIGHT)?;
content.draw_upc_a_digits(&upc, &digits, left, top, width)?;
top -= 120.0;
let ean8 = Ean8::new(EAN8_ARTICLE)?;
let width = f64::from(u32::try_from(ean8.module_count())?) * MODULE;
content.draw_ean8(&ean8, left, top, width, BAR_HEIGHT)?;
content.draw_ean8_digits(&ean8, &digits, left, top, width, true)?;
let mut page = Page::a4();
page.content = content.into_bytes();
doc.add_page(page)?;
doc.add_page(second_page(&font, &digits, digit_cap, words)?)?;
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::{
BAR_HEIGHT, BODY, CAPTION, 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. The heading
/// and the lines under it are the whole of `Words`, and no two languages
/// write one alike; what the barcodes 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 captions = [words.paired, words.spelt, words.short, words.add_on].map(|line| {
line.replace("{modules}", "189")
.replace("{pixels}", "4")
.replace("{upc_a}", "012345000065")
.replace("{extra}", "52495")
.replace("{gap}", "9")
});
let lines = [(HEADING, words.title), (HEADING, words.more_title)]
.into_iter()
.chain(words.lines.map(|line| (BODY, line)))
.chain(words.more_lines.map(|line| (BODY, line)))
.chain(captions.iter().map(|line| (CAPTION, line.as_str())));
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 bars, and the bars start where
/// the first barcode is drawn. A line too many at the head would be drawn
/// over them.
#[test]
fn the_head_of_the_sheet_stands_clear_of_the_bars() {
let bars = TOP + BAR_HEIGHT;
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 >= bars,
"the {} head ends on a line at {last:.1} points, and the bars \
reach {bars:.1}",
named.code()
);
}
}
}
|