write_codes.rs

Die Rust-Datei des Beispiels „QR- und Data-Matrix-Einstellungen nebeneinander“. Derselbe Text in den vier QR-Fehlerkorrekturstufen, ein QR-Code pro Textart und Data-Matrix-Codes als Streifen oder in einer vorab festgelegten Größe.

Rust 595 Zeilen

Wofür dieses Beispiel da ist

Quadratcode ist nicht gleich Quadratcode. Ein Code auf einer Kiste, die verkratzt wird, braucht mehr Reserve als ein Code auf einem Bildschirm; ein Code für ein schmales Etikett muss ein Streifen statt eines Quadrats sein; ein Code, für den die Druckerei im Layout vorab Platz gelassen hat, muss genau in dieser Größe herauskommen. Wer hier falsch wählt, merkt es am anderen Ende: Der Code lässt sich nicht scannen.

Was dieses Beispiel zeigt

  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
//! Draws the two square codes a page can carry — QR and Data Matrix — at the
//! correction levels, the modes, the shapes and the sizes a request can ask
//! for.
//!
//! A square code is a grid of modules with a clear margin round it. Each box on
//! this page is filled the way a request fills it: a margin of `QUIET_ZONE`
//! modules each side — four for a QR code, one for a Data Matrix — and the grid
//! taking the rest of the width.
//!
//! What the page says about the codes is held in `Words`, once per language,
//! and `HQF_PDF_LANG` picks which set the sheet is written in. What the codes
//! carry stands apart from them: a scanner reads it, and it is the same in
//! every language.
//!
//! Usage: `cargo run --example write_codes -- tmp/codes.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_codes -- tmp/codes_fr.pdf`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::content::Content;
use hqf_pdf::layout::Align;
use hqf_pdf::qr::{Correction, Mode};
use hqf_pdf::{DataMatrix, Document, Error, Font, FontHandle, Page, QrCode, TextFlow};
use hqf_pdf::{datamatrix, qr};

#[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 words the sheet is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// What the file says it is, in what it says of itself.
    title: &'static str,
    /// The heading at the top of the sheet.
    heading: &'static str,
    /// What stands above each row of codes, in the order the page draws them.
    captions: [&'static str; 4],
}

impl Words {
    /// The words the sheet is written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }
}

/// The sheet in English.
const ENGLISH: Words = Words {
    title: "The codes a request can ask for by shape, by size, by level and by mode",
    heading: "Codes asked for by shape, by size, by level and by mode",
    captions: [
        "The same text at the four correction levels: low, medium, quartile, high.",
        "One text to a mode: digits, capitals and punctuation, and any byte at all.",
        "A Data Matrix on a strip: the smallest oblong symbol that holds the text.",
        "A Data Matrix of a size the request names: two texts, one symbol size.",
    ],
};

/// The sheet in French.
const FRENCH: Words = Words {
    title: "Les codes qu’une requête peut demander par forme, taille, niveau et mode",
    heading: "Des codes demandés par forme, taille, niveau et mode",
    captions: [
        "Le même texte aux quatre niveaux de correction : faible, moyen, quartile, élevé.",
        "Un texte par mode : chiffres, majuscules et ponctuation, puis n’importe quel octet.",
        "Un Data Matrix en bandeau : le plus petit symbole rectangulaire qui contient le texte.",
        "Un Data Matrix de la taille que nomme la requête : deux textes, une seule taille.",
    ],
};

/// The sheet in German.
const GERMAN: Words = Words {
    title: "Die Codes, die eine Anfrage nach Form, Größe, Stufe und Modus verlangen kann",
    heading: "Codes nach Form, Größe, Stufe und Modus",
    captions: [
        "Derselbe Text in den vier Korrekturstufen: niedrig, mittel, Quartil, hoch.",
        "Ein Text pro Modus: Ziffern, Großbuchstaben mit Satzzeichen, beliebige Bytes.",
        "Ein Data-Matrix-Code als Streifen: das kleinste rechteckige Symbol für den Text.",
        "Ein Data-Matrix-Code in angefragter Größe: zwei Texte, eine Symbolgröße.",
    ],
};

/// The sheet in Spanish.
const SPANISH: Words = Words {
    title: "Los códigos que una solicitud puede pedir por forma, tamaño, nivel y modo",
    heading: "Códigos pedidos por forma, tamaño, nivel y modo",
    captions: [
        "El mismo texto en los cuatro niveles de corrección: bajo, medio, cuartil, alto.",
        "Un texto por modo: cifras, mayúsculas y puntuación, y cualquier byte.",
        "Un Data Matrix en tira: el símbolo rectangular más pequeño que contiene el texto.",
        "Un Data Matrix del tamaño que indica la petición: dos textos, un solo tamaño.",
    ],
};

/// The sheet in Italian.
const ITALIAN: Words = Words {
    title: "I codici che una richiesta può chiedere per forma, misura, livello e modo",
    heading: "Codici chiesti per forma, misura, livello e modo",
    captions: [
        "Lo stesso testo ai quattro livelli di correzione: basso, medio, quartile, alto.",
        "Un testo per ciascun modo: cifre; maiuscole e punteggiatura; qualsiasi byte.",
        "Un Data Matrix a striscia: il simbolo oblungo più piccolo che contiene il testo.",
        "Un Data Matrix della misura indicata dalla richiesta: due testi, una sola misura.",
    ],
};

/// The sheet in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Os códigos que um pedido pode designar por forma, tamanho, nível e modo",
    heading: "Códigos pedidos por forma, tamanho, nível e modo",
    captions: [
        "O mesmo texto nos quatro níveis de correção: baixo, médio, quartil, alto.",
        "Um texto por modo: algarismos, maiúsculas e pontuação, e qualquer byte.",
        "Um Data Matrix em tira: o menor símbolo retangular que contém o texto.",
        "Um Data Matrix do tamanho indicado pelo pedido: dois textos, um só tamanho.",
    ],
};

/// The sheet in Dutch.
const DUTCH: Words = Words {
    title: "De codes die een verzoek naar vorm, grootte, niveau en modus kan opvragen",
    heading: "Codes opgevraagd naar vorm, grootte, niveau en modus",
    captions: [
        "Dezelfde tekst op de vier correctieniveaus: laag, gemiddeld, kwartiel, hoog.",
        "Eén tekst per modus: cijfers, hoofdletters met leestekens, en willekeurige bytes.",
        "Een Data Matrix als strook: het kleinste langwerpige symbool dat de tekst bevat.",
        "Een Data Matrix in de grootte die het verzoek noemt: twee teksten, één symboolgrootte.",
    ],
};

/// 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 box a block of words goes in, and how it is set.
struct Block {
    size: f64,
    left: f64,
    top: f64,
    width: f64,
    set: Option<(f64, Align)>,
}

/// The box a square code goes in: its lower-left corner, its width, and how
/// many modules of margin its symbology reserves each side.
struct Square {
    left: f64,
    low: f64,
    width: f64,
    quiet: usize,
}

fn main() -> std::process::ExitCode {
    failure::reported(run())
}

/// Writes the file, and says where it went.
fn run() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args = env::args().skip(1);
    // A named file is written as named; the default one carries the language,
    // so the languages do not overwrite each other in `tmp/`.
    let path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("codes")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_info(hqf_pdf::cos::Name::new("Title"), words.title);

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    doc.add_page(sheet(&font, 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 {path}: {} bytes", bytes.len());
    Ok(())
}

/// The one page: every code, each under the words that name it.
fn sheet(font: &FontHandle, words: &Words) -> Result<Page, Error> {
    let mut c = Content::new();

    run_1(&mut c, font, words)?;
    run_2(&mut c, font, words)?;
    run_3(&mut c, font, words)?;
    run_4(&mut c)?;

    let mut page = Page::a4();
    page.content = c.into_bytes();
    Ok(page)
}

/// The 1ᵗʰ run of what the page draws, in order.
fn run_1(c: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    block(
        c,
        font,
        &Block {
            size: 16.0,
            left: 56.000,
            top: 813.200,
            width: 483.000,
            set: None,
        },
        words.heading,
    )?;
    block(
        c,
        font,
        &Block {
            size: 10.5,
            left: 56.000,
            top: 782.600,
            width: 483.000,
            set: None,
        },
        words.captions[0],
    )?;
    square(
        c,
        &QrCode::with_encoding(
            "https://example.test/lot/FR-1964413",
            Mode::Byte,
            Correction::Low,
        )?,
        |c, code, x, y, side| {
            c.draw_qr(code, x, y, side)?;
            Ok(())
        },
        QrCode::size,
        &Square {
            left: 56.000,
            low: 650.000,
            width: 110.000,
            quiet: qr::QUIET_ZONE,
        },
    )?;
    square(
        c,
        &QrCode::with_encoding(
            "https://example.test/lot/FR-1964413",
            Mode::Byte,
            Correction::Medium,
        )?,
        |c, code, x, y, side| {
            c.draw_qr(code, x, y, side)?;
            Ok(())
        },
        QrCode::size,
        &Square {
            left: 180.000,
            low: 650.000,
            width: 110.000,
            quiet: qr::QUIET_ZONE,
        },
    )?;
    square(
        c,
        &QrCode::with_encoding(
            "https://example.test/lot/FR-1964413",
            Mode::Byte,
            Correction::Quartile,
        )?,
        |c, code, x, y, side| {
            c.draw_qr(code, x, y, side)?;
            Ok(())
        },
        QrCode::size,
        &Square {
            left: 304.000,
            low: 650.000,
            width: 110.000,
            quiet: qr::QUIET_ZONE,
        },
    )?;
    Ok(())
}

/// The 2ᵗʰ run of what the page draws, in order.
fn run_2(c: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    square(
        c,
        &QrCode::with_encoding(
            "https://example.test/lot/FR-1964413",
            Mode::Byte,
            Correction::High,
        )?,
        |c, code, x, y, side| {
            c.draw_qr(code, x, y, side)?;
            Ok(())
        },
        QrCode::size,
        &Square {
            left: 428.000,
            low: 650.000,
            width: 110.000,
            quiet: qr::QUIET_ZONE,
        },
    )?;
    block(
        c,
        font,
        &Block {
            size: 10.5,
            left: 56.000,
            top: 640.600,
            width: 483.000,
            set: None,
        },
        words.captions[1],
    )?;
    square(
        c,
        &QrCode::with_encoding("31964413000271026", Mode::Numeric, Correction::Medium)?,
        |c, code, x, y, side| {
            c.draw_qr(code, x, y, side)?;
            Ok(())
        },
        QrCode::size,
        &Square {
            left: 56.000,
            low: 500.000,
            width: 110.000,
            quiet: qr::QUIET_ZONE,
        },
    )?;
    square(
        c,
        &QrCode::with_encoding(
            "LOT FR-1964413/2026",
            Mode::Alphanumeric,
            Correction::Medium,
        )?,
        |c, code, x, y, side| {
            c.draw_qr(code, x, y, side)?;
            Ok(())
        },
        QrCode::size,
        &Square {
            left: 180.000,
            low: 500.000,
            width: 110.000,
            quiet: qr::QUIET_ZONE,
        },
    )?;
    square(
        c,
        &QrCode::with_encoding("lot fr-1964413", Mode::Byte, Correction::Quartile)?,
        |c, code, x, y, side| {
            c.draw_qr(code, x, y, side)?;
            Ok(())
        },
        QrCode::size,
        &Square {
            left: 304.000,
            low: 500.000,
            width: 110.000,
            quiet: qr::QUIET_ZONE,
        },
    )?;
    Ok(())
}

/// The 3ᵗʰ run of what the page draws, in order.
fn run_3(c: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    block(
        c,
        font,
        &Block {
            size: 10.5,
            left: 56.000,
            top: 490.600,
            width: 483.000,
            set: None,
        },
        words.captions[2],
    )?;
    square(
        c,
        &DataMatrix::rectangular("SN:ACME-4472")?,
        |c, code, x, y, side| {
            c.draw_data_matrix(code, x, y, side)?;
            Ok(())
        },
        DataMatrix::width,
        &Square {
            left: 56.000,
            low: 380.000,
            width: 180.000,
            quiet: datamatrix::QUIET_ZONE,
        },
    )?;
    square(
        c,
        &DataMatrix::rectangular("TUBE-77")?,
        |c, code, x, y, side| {
            c.draw_data_matrix(code, x, y, side)?;
            Ok(())
        },
        DataMatrix::width,
        &Square {
            left: 260.000,
            low: 380.000,
            width: 180.000,
            quiet: datamatrix::QUIET_ZONE,
        },
    )?;
    block(
        c,
        font,
        &Block {
            size: 10.5,
            left: 56.000,
            top: 370.600,
            width: 483.000,
            set: None,
        },
        words.captions[3],
    )?;
    square(
        c,
        &DataMatrix::with_size("FR-1964413", 16, 48)?,
        |c, code, x, y, side| {
            c.draw_data_matrix(code, x, y, side)?;
            Ok(())
        },
        DataMatrix::width,
        &Square {
            left: 56.000,
            low: 240.000,
            width: 240.000,
            quiet: datamatrix::QUIET_ZONE,
        },
    )?;
    Ok(())
}

/// The 4ᵗʰ run of what the page draws, in order.
fn run_4(c: &mut Content) -> Result<(), Error> {
    square(
        c,
        &DataMatrix::with_size("FR-2", 16, 48)?,
        |c, code, x, y, side| {
            c.draw_data_matrix(code, x, y, side)?;
            Ok(())
        },
        DataMatrix::width,
        &Square {
            left: 300.000,
            low: 240.000,
            width: 240.000,
            quiet: datamatrix::QUIET_ZONE,
        },
    )?;
    square(
        c,
        &DataMatrix::with_size("FR-1964413/2026-08", 22, 22)?,
        |c, code, x, y, side| {
            c.draw_data_matrix(code, x, y, side)?;
            Ok(())
        },
        DataMatrix::width,
        &Square {
            left: 56.000,
            low: 120.000,
            width: 120.000,
            quiet: datamatrix::QUIET_ZONE,
        },
    )?;
    Ok(())
}

/// Draws one block of words in the box it is given.
fn block(c: &mut Content, font: &FontHandle, at: &Block, text: &str) -> Result<(), Error> {
    let mut flow = TextFlow::new(font, at.size);
    if let Some((leading, align)) = at.set {
        flow = flow.leading(leading).align(align);
    }
    let lines = flow.break_lines(text, at.width);
    c.begin_text();
    flow.draw(c, &lines, at.left, at.top, at.width)?;
    c.end_text();
    Ok(())
}

/// Draws one square code in the box it is given, with a margin of `QUIET_ZONE`
/// modules each side and the grid taking the rest of the width.
fn square<T>(
    c: &mut Content,
    code: &T,
    drawn: impl Fn(&mut Content, &T, f64, f64, f64) -> Result<(), Error>,
    across: impl Fn(&T) -> usize,
    at: &Square,
) -> Result<(), Error> {
    let modules = f64::from(u32::try_from(across(code)).unwrap_or(u32::MAX));
    let quiet = f64::from(u32::try_from(at.quiet).unwrap_or(u32::MAX));
    let unit = at.width / 2.0f64.mul_add(quiet, modules);
    c.save_state();
    c.set_fill_rgb(0.0, 0.0, 0.0)?;
    drawn(
        c,
        code,
        quiet.mul_add(unit, at.left),
        quiet.mul_add(unit, at.low),
        modules * unit,
    )?;
    c.restore_state();
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::{Document, Font, TextFlow};

    use super::{WORDS, default_font, language};

    /// The width every block of words on the sheet is set in.
    const WIDTH: f64 = 483.0;

    /// The lines two languages are allowed to write the same way. What the
    /// codes carry is read by a scanner and stands apart from `Words`, and no
    /// two languages say the rest alike.
    const SPARED: [&str; 0] = [];

    #[test]
    fn every_language_writes_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:?}"
        );
    }

    /// Each block is set on one line, a row of codes standing a fixed step
    /// under it. A block broken onto a second line is drawn over the codes.
    #[test]
    fn every_block_of_every_language_stays_on_one_line() {
        let mut doc = Document::new();
        let font = 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 blocks = std::iter::once((16.0, words.heading))
                .chain(words.captions.map(|caption| (10.5, caption)));
            for (size, text) in blocks {
                let lines = TextFlow::new(&font, size).break_lines(text, WIDTH).len();
                assert_eq!(
                    lines,
                    1,
                    "the {} sheet breaks {text:?} onto {lines} lines",
                    named.code()
                );
            }
        }
    }
}