write_code_charsets.rs

Die Rust-Datei des Beispiels „Codes, die ihren Zeichensatz nennen“. Neun Codes, deren Bytes sagen, in welchem Zeichensatz sie geschrieben sind, sodass Griechisch als Griechisch und Kyrillisch als Kyrillisch zurückkommt, auf welchen Zeichensatz der Scanner auch zurückgegriffen hätte.

Rust 523 Zeilen

Wofür dieses Beispiel da ist

Ein Code trägt Bytes, keine Buchstaben. Der Scanner, der ihn liest, muss herausfinden, welcher Zeichensatz die Buchstaben in diese Bytes verwandelt hat, und wenn der Code es nicht sagt, greift er auf den zurück, mit dem er gebaut wurde. Eine einfache Referenz aus Großbuchstaben und Ziffern übersteht dieses Raten. Ein griechischer Gruß, eine polnische Stadt oder ein Preis mit Eurozeichen kommt auf einem Scanner richtig heraus und auf dem nächsten als Reihe falscher Buchstaben, und nichts auf der Seite verrät es, bis jemand scannt.

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
//! Writes a page of two-dimensional codes whose bytes name the character set
//! they are written in.
//!
//! A code that names no set is read in whatever set the scanner falls back on,
//! so a text with an accent in it comes back right on one scanner and wrong on
//! the next. Each code here is handed its payload as bytes already written in a
//! set, and names that set ahead of them: a QR code in Latin-1, a Data Matrix
//! in Greek and an Aztec code in Latin-9 side by side, then a column of PDF417
//! codes in Latin-2, Cyrillic, Shift JIS, Windows-1252, ASCII and binary, each
//! at a level of correction of its own. Under each stand the text its bytes
//! spell and the number the register gives the set.
//!
//! Whether a code works is not a question the page can answer, and not one a
//! human eye can: it is answered by a scanner. `scripts/check_barcode.sh`
//! points a decoder at the rendered image and compares what it reads with the
//! texts under the codes.
//!
//! The head of the sheet is 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.
//!
//! Usage: `cargo run --example write_code_charsets -- tmp/code_charsets.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_code_charsets --
//! tmp/code_charsets_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::eci::Charset;
use hqf_pdf::pdf417::{ErrorLevel, ROW_ASPECT};
use hqf_pdf::qr::Correction;
use hqf_pdf::{
    Aztec, DataMatrix, Document, Error, Font, FontHandle, License, Page, Pdf417, 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")
}

/// The QR code's text, and the Latin-1 bytes it is handed over as.
const LATIN_1_TEXT: &str = "Grüße aus Köln";
/// See [`LATIN_1_TEXT`].
const LATIN_1_BYTES: &[u8] = b"Gr\xfc\xdfe aus K\xf6ln";

/// The Data Matrix's text, and the Greek bytes it is handed over as.
const GREEK_TEXT: &str = "Καλημέρα";
/// See [`GREEK_TEXT`].
const GREEK_BYTES: &[u8] = b"\xca\xe1\xeb\xe7\xec\xdd\xf1\xe1";

/// The Aztec code's text, and the Latin-9 bytes it is handed over as.
const LATIN_9_TEXT: &str = "Prix 12 €";
/// See [`LATIN_9_TEXT`].
const LATIN_9_BYTES: &[u8] = b"Prix 12 \xa4";

/// What the PDF417 codes carry, in the order they are set down the page.
const STACKED: [&str; 6] = [
    "Łódź",
    "Москва",
    "TOKYO 2026",
    "Café 3 €",
    "ASCII 2026",
    "BIN 7",
];

/// The side of one module of a square code, 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 width of one module of a PDF417 code, in points: six pixels to a module
/// at 288dpi.
const BAR_MODULE: f64 = 1.5;

/// Where the bottom of the row of square codes sits, in points up from the
/// bottom of the sheet.
const TOP: f64 = 640.0;

/// Where the head of the first PDF417 code sits, in points up from the bottom
/// of the sheet.
const STACK_TOP: f64 = 590.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 codes.
const MARGIN: f64 = 72.0;

/// Where the baseline of the heading sits, in points up from the bottom 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 that names its character set; `{number}` stands
    /// for the number the register gives the set.
    declared: &'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: "Codes that name their character set",
    lines: [
        "A code that names no character set is read in the one the scanner assumes.",
        "Each code here names its own, so Greek comes back as Greek, Cyrillic as Cyrillic.",
    ],
    declared: "character set {number}",
};

/// The head of the sheet in French.
const FRENCH: Words = Words {
    title: "Codes qui nomment leur jeu de caractères",
    lines: [
        "Un code qui ne nomme pas son jeu de caractères est lu dans celui du scanner.",
        "Ici, chaque code nomme le sien\u{a0}: le grec se relit en grec, le cyrillique aussi.",
    ],
    declared: "jeu de caractères {number}",
};

/// The head of the sheet in Dutch.
const DUTCH: Words = Words {
    title: "Codes die hun tekenset noemen",
    lines: [
        "Een code zonder tekenset wordt gelezen in de set die de scanner aanneemt.",
        "Elke code hier noemt de zijne: Grieks komt terug als Grieks, Cyrillisch als Cyrillisch.",
    ],
    declared: "tekenset {number}",
};

/// The head of the sheet in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Códigos que nomeiam o seu conjunto de caracteres",
    lines: [
        "Um código sem conjunto de caracteres declarado lê-se como o leitor presumir.",
        "Aqui cada código indica o seu: o grego lê-se como grego, o cirílico como cirílico.",
    ],
    declared: "conjunto de caracteres {number}",
};

/// The head of the sheet in Italian.
const ITALIAN: Words = Words {
    title: "Codici che nominano il loro set di caratteri",
    lines: [
        "Un codice senza set di caratteri dichiarato si legge in quello che suppone lo scanner.",
        "Ogni codice qui nomina il suo, così il greco torna greco, il cirillico cirillico.",
    ],
    declared: "set di caratteri {number}",
};

/// The head of the sheet in Spanish.
const SPANISH: Words = Words {
    title: "Códigos que nombran su juego de caracteres",
    lines: [
        "Un código que no nombra juego de caracteres se lee en el que supone el escáner.",
        "Aquí cada código nombra el suyo: el griego sale griego y el cirílico, cirílico.",
    ],
    declared: "juego de caracteres {number}",
};

/// The head of the sheet in German.
const GERMAN: Words = Words {
    title: "Codes, die ihren Zeichensatz nennen",
    lines: [
        "Ein Code ohne Zeichensatz wird in dem gelesen, den der Scanner annimmt.",
        "Jeder Code nennt seinen: Griechisch kommt griechisch zurück, Kyrillisch kyrillisch.",
    ],
    declared: "Zeichensatz {number}",
};

/// 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(())
}

/// Sets each of `lines` at `size` from `x`, its baseline the drop it comes with
/// under `y`.
fn caption(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    (x, y): (f64, f64),
    lines: [(&str, f64); 2],
) -> Result<(), Error> {
    for (line, drop) in lines {
        content.begin_text();
        content.set_font(font, size)?;
        content.text_origin(x, y - drop)?;
        content.show_glyphs(&font.glyphs(line));
        content.end_text();
    }
    Ok(())
}

/// The PDF417 codes, each handed its text as bytes in a set it names, at a
/// level of correction of its own.
fn stacked() -> Result<[(Pdf417, Charset); 6], Error> {
    let built = |bytes: &[u8], charset: Charset, level: ErrorLevel| {
        Pdf417::from_bytes_in(bytes, charset, level).map(|code| (code, charset))
    };
    Ok([
        built(b"\xa3\xf3d\xbc", Charset::LATIN_2, ErrorLevel::One)?,
        built(
            b"\xbc\xde\xe1\xda\xd2\xd0",
            Charset::CYRILLIC,
            ErrorLevel::Two,
        )?,
        built(STACKED[2].as_bytes(), Charset::SHIFT_JIS, ErrorLevel::Three)?,
        built(b"Caf\xe9 3 \x80", Charset::WINDOWS_1252, ErrorLevel::Four)?,
        built(STACKED[4].as_bytes(), Charset::ASCII, ErrorLevel::Six)?,
        built(STACKED[5].as_bytes(), Charset::BINARY, ErrorLevel::Seven)?,
    ])
}

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("code_charsets")));
    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)?;

    // The three square codes side by side, each drawn its own quiet zone in
    // from where it stands, and the next one standing clear of its caption as
    // well as of the code itself.
    let declared = |charset: Charset| {
        words
            .declared
            .replace("{number}", &charset.number().to_string())
    };
    let mut left = MARGIN;

    let qr = QrCode::from_bytes_in(LATIN_1_BYTES, Charset::LATIN_1, Correction::Medium)?;
    let quiet = f64::from(u32::try_from(hqf_pdf::qr::QUIET_ZONE)?) * MODULE;
    let side = f64::from(u32::try_from(qr.size())?) * MODULE;
    content.draw_qr(&qr, left + quiet, TOP, side)?;
    let named = declared(Charset::LATIN_1);
    caption(
        &mut content,
        &font,
        8.0,
        (left + quiet, TOP),
        [(LATIN_1_TEXT, 12.0), (&named, 22.0)],
    )?;
    let widest = font
        .measure(LATIN_1_TEXT, 8.0)
        .max(font.measure(&named, 8.0));
    left += side.max(widest) + quiet.mul_add(2.0, 24.0);

    let matrix = DataMatrix::from_bytes_in(GREEK_BYTES, Charset::GREEK)?;
    let quiet = f64::from(u32::try_from(hqf_pdf::datamatrix::QUIET_ZONE)?) * MODULE;
    let side = f64::from(u32::try_from(matrix.width())?) * MODULE;
    content.draw_data_matrix(&matrix, left + quiet, TOP, side)?;
    let named = declared(Charset::GREEK);
    caption(
        &mut content,
        &font,
        8.0,
        (left + quiet, TOP),
        [(GREEK_TEXT, 12.0), (&named, 22.0)],
    )?;
    let widest = font.measure(GREEK_TEXT, 8.0).max(font.measure(&named, 8.0));
    left += side.max(widest) + quiet.mul_add(2.0, 24.0);

    // An Aztec code asks for no quiet zone: the scanner finds the bullseye at
    // its centre.
    let aztec = Aztec::from_bytes_in(LATIN_9_BYTES, Charset::LATIN_9, DEFAULT_CORRECTION)?;
    let side = f64::from(u32::try_from(aztec.size())?) * MODULE;
    content.draw_aztec(&aztec, left, TOP, side)?;
    let named = declared(Charset::LATIN_9);
    caption(
        &mut content,
        &font,
        8.0,
        (left, TOP),
        [(LATIN_9_TEXT, 12.0), (&named, 22.0)],
    )?;

    // The PDF417 codes one above the other: a decoder reads codes set side by
    // side less surely than codes set one above the other.
    let quiet = f64::from(u32::try_from(hqf_pdf::pdf417::QUIET_ZONE)?) * BAR_MODULE;
    let aspect = f64::from(u32::try_from(ROW_ASPECT)?);
    let mut top = STACK_TOP;
    for ((code, charset), carried) in stacked()?.iter().zip(STACKED) {
        let width = f64::from(u32::try_from(code.width())?) * BAR_MODULE;
        let height = f64::from(u32::try_from(code.height())?) * BAR_MODULE * aspect;
        let bottom = top - height;
        content.draw_pdf417(code, MARGIN + quiet, bottom, width, height)?;
        let named = declared(*charset);
        caption(
            &mut content,
            &font,
            7.0,
            (MARGIN + quiet, bottom),
            [(carried, 10.0), (&named, 19.0)],
        )?;
        top = bottom - quiet.mul_add(2.0, 30.0);
    }

    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::eci::Charset;
    use hqf_pdf::pdf417::{QUIET_ZONE, ROW_ASPECT};
    use hqf_pdf::qr::Correction;
    use hqf_pdf::{Document, Font, QrCode};

    use super::{
        BAR_MODULE, BODY, HEAD_GAP, HEAD_TOP, HEADING, LATIN_1_BYTES, LINE_STEP, MARGIN, MODULE,
        STACK_TOP, TOP, WORDS, default_font, language, stacked,
    };

    /// 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,
    /// the lines under it and the caption that names a set 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;

    /// How far above the foot of the sheet the last caption may stand.
    const FOOT: f64 = 36.0;

    #[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 QR code is the tallest of the row, so it 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 qr = QrCode::from_bytes_in(LATIN_1_BYTES, Charset::LATIN_1, Correction::Medium)
            .expect("the Latin-1 text is a code a QR symbol holds");
        let side = f64::from(u32::try_from(qr.size()).expect("a symbol is a few dozen modules"));
        let codes = side.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()
            );
        }
    }

    /// The column of PDF417 codes starts under the captions of the row and ends
    /// above the foot of the sheet.
    #[test]
    fn the_column_of_stacked_codes_fits_the_sheet() {
        const {
            assert!(
                STACK_TOP < TOP - 22.0,
                "the column starts on the row's captions"
            );
        }

        let quiet = f64::from(u32::try_from(QUIET_ZONE).expect("a few modules")) * BAR_MODULE;
        let aspect = f64::from(u32::try_from(ROW_ASPECT).expect("a few modules"));
        let mut top = STACK_TOP;
        let mut last_caption = top;
        for (code, _) in stacked().expect("every stacked text is a code a PDF417 holds") {
            let rows = f64::from(u32::try_from(code.height()).expect("a few dozen rows"));
            let height = rows * BAR_MODULE * aspect;
            let bottom = top - height;
            last_caption = bottom - 19.0;
            top = bottom - quiet.mul_add(2.0, 30.0);
        }
        assert!(
            last_caption >= FOOT,
            "the last caption stands at {last_caption:.1} points, under {FOOT:.1}"
        );
    }
}