write_carried_facts.rs

The Rust program of A delivery note that knows its own order. Every line of the note carries the order it was picked for, the article code and the shelf it came off, and prints none of them. The place where the driver signs carries the round and the van, and a mark beside the fold tick carries nothing but its own place.

Rust 551 lines
  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
//! Draws a delivery note whose every line carries the order it came from, the
//! article code and the shelf it was picked from, without printing any of them.
//!
//! A warehouse prints a note for the driver and keeps a record for itself, and
//! the two have to be paired up again when the signed sheet comes back.
//! Printing the codes on the note would pair them, at the price of a column of
//! machine words on a sheet a customer reads.
//!
//! So the codes travel under the page instead. Each line of the note is drawn
//! inside a marked run, and the run points at a list of the caller's own facts
//! held once in the file; the point where the driver signs carries a list of
//! its own. Nothing of any list is drawn: a program reading the file afterwards
//! finds every code against the line it belongs to, and an eye reading the
//! sheet finds a delivery note.
//!
//! The library says nothing about what a list holds. The names and the values
//! here are the warehouse's own, and another trade would carry other ones.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The codes, the quantities and the shelves are the same
//! in both.
//!
//! Usage: `cargo run --example write_carried_facts -- [out.pdf] [face.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_carried_facts`

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

use hqf_pdf::content::Content;
use hqf_pdf::cos::{Dictionary, Name, Object};
use hqf_pdf::{Align, Document, Font, FontHandle, Page, PropertiesHandle, Rgb, TextFlow};

#[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 note is set in when none is given on the command line: the one
/// committed for the tests, so the example runs on any machine.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// How many lines the note delivers.
const LINE_COUNT: usize = 6;

/// What one line of the note carries under the page.
struct Carried {
    /// The order the line came from.
    order: &'static str,
    /// The article code the warehouse knows the goods by.
    article: &'static str,
    /// The shelf it was picked from.
    bin: &'static str,
    /// How many were picked, which is the one figure the page also prints.
    quantity: u32,
}

/// What each line carries, in the order the note delivers them.
///
/// A code is a code in every language, so these stay out of `Words`.
const CARRIED: [Carried; LINE_COUNT] = [
    Carried {
        order: "SO-88412",
        article: "TBL-OAK-180",
        bin: "A-14-3",
        quantity: 1,
    },
    Carried {
        order: "SO-88412",
        article: "CHR-WAL-04",
        bin: "A-09-1",
        quantity: 6,
    },
    Carried {
        order: "SO-88451",
        article: "SBD-3DR-120",
        bin: "B-02-7",
        quantity: 1,
    },
    Carried {
        order: "SO-88451",
        article: "SHF-WAL-090",
        bin: "C-31-2",
        quantity: 4,
    },
    Carried {
        order: "SO-88463",
        article: "CST-STD-01",
        bin: "C-08-5",
        quantity: 2,
    },
    Carried {
        order: "SO-88463",
        article: "LMP-FLR-BRS",
        bin: "D-17-9",
        quantity: 3,
    },
];

/// The round the driver is on, carried by the point where the note is signed.
const ROUND: &str = "RT-2026-224";

/// The van the round is driven in, carried by the same point.
const VAN: &str = "DRV-118";

/// How many lists of facts travel with the page: one for each line, and one for
/// the point where the note is signed.
const LISTS: usize = LINE_COUNT + 1;

/// The words the note is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The page's title.
    title: &'static str,
    /// What the page is about.
    lead: &'static str,
    /// The label over the note itself.
    note: &'static str,
    /// Who the goods are going to, and when.
    consignee: &'static str,
    /// The three column headings of the note.
    goods: &'static str,
    count: &'static str,
    picked: &'static str,
    /// What each line delivers, in the order `CARRIED` picks them.
    items: [&'static str; LINE_COUNT],
    /// What is written under the line the driver signs on.
    signature: &'static str,
    /// The label over what the page carries and does not show.
    beneath: &'static str,
    /// What the page carries and does not show.
    carried: &'static str,
    /// The label over the fold mark.
    fold: &'static str,
    /// What the fold mark is.
    folded: &'static str,
    /// What the page leaves the reader with.
    caveat: &'static str,
}

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

/// The note in English.
const ENGLISH: Words = Words {
    title: "A delivery note that knows which order it came from",
    lead: "Every line of the note below carries the order it was picked for, the \
           article code and the shelf it came off, and prints none of the three. \
           The line is drawn inside a marked run, and the run points at a list of \
           facts held once in the file under the warehouse's own names. The sheet \
           that comes back signed is therefore paired with the records it came \
           from by reading the file, not by reading the paper.",
    note: "The note the driver carries",
    consignee: "Meunier & Filles, 14 rue des Tanneurs, Tours — delivered 13 August 2026",
    goods: "Goods",
    count: "Qty",
    picked: "Picked by",
    items: [
        "Oak dining table, 180 cm",
        "Dining chair, walnut",
        "Sideboard, three doors",
        "Wall shelf, 90 cm",
        "Coat stand",
        "Floor lamp, brushed steel",
    ],
    signature: "Signed on delivery",
    beneath: "What travels under the page",
    carried: "Seven lists of facts travel with this sheet: one against each of the \
              six lines, and one at the point where the driver signs, which carries \
              the round and the van. Not one letter of any of them is drawn. A list \
              is written once in the file and pointed at from the page, so a list \
              that belongs to several places is held once and marked as often as \
              it is needed.",
    fold: "The mark that carries nothing",
    folded: "The short stroke in the left margin is where the sheet is folded for a \
             window envelope, and a mark of its own is put in the page beside it, \
             under a name and with no facts at all. A place is sometimes all there \
             is to say.",
    caveat: "What a list holds is the caller's business: an order number here, an \
             article code in a catalogue, a state against a box on a form. The \
             library neither reads these names nor acts on them — it writes them \
             down and ties them to what was drawn.",
};

/// The note in French.
const FRENCH: Words = Words {
    title: "Un bon de livraison qui sait de quelle commande il vient",
    lead: "Chaque ligne du bon ci-dessous porte la commande pour laquelle elle a \
           été préparée, le code de l'article et l'étagère d'où il sort, et \
           n'imprime aucun des trois. La ligne est dessinée dans un repère, et ce \
           repère désigne une liste de renseignements écrite une seule fois dans \
           le fichier, sous les noms de l'entrepôt. La feuille qui revient signée \
           se rapproche donc de ses enregistrements en lisant le fichier, et non \
           en lisant le papier.",
    note: "Le bon que le chauffeur emporte",
    consignee: "Meunier & Filles, 14 rue des Tanneurs, Tours — livré le 13 août 2026",
    goods: "Marchandise",
    count: "Qté",
    picked: "Préparé par",
    items: [
        "Table de salle à manger en chêne, 180 cm",
        "Chaise de salle à manger en noyer",
        "Buffet trois portes",
        "Étagère murale, 90 cm",
        "Portemanteau",
        "Lampadaire en acier brossé",
    ],
    signature: "Signature à la livraison",
    beneath: "Ce qui voyage sous la page",
    carried: "Sept listes de renseignements voyagent avec cette feuille : une \
              contre chacune des six lignes, et une au point où le chauffeur \
              signe, qui porte la tournée et le véhicule. Pas une lettre de \
              l'une d'elles n'est dessinée. Une liste est écrite une fois puis \
              désignée depuis la page : une liste qui vaut à plusieurs endroits \
              n'est donc écrite qu'une fois et posée autant de fois qu'il le \
              faut.",
    fold: "Le repère qui ne porte rien",
    folded: "Le petit trait de la marge gauche est l'endroit où la feuille se plie \
             pour une enveloppe à fenêtre, et un repère à lui est posé dans la page \
             juste à côté, sous un nom et sans le moindre renseignement. Un endroit \
             suffit parfois à tout dire.",
    caveat: "Ce qu'une liste porte appartient à l'appelant : un numéro de commande \
             ici, une référence d'article dans un catalogue, un état contre une case \
             d'un formulaire. La bibliothèque ne lit pas ces noms et n'en fait rien — \
             elle les écrit et les attache à ce qui a été dessiné.",
};

/// 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); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// The left edge of everything on the page.
const LEFT: f64 = 72.0;

/// How wide a block of text is.
const WIDTH: f64 = 451.0;

/// How wide the column of goods is.
const GOODS_WIDTH: f64 = 300.0;

/// Where the column of quantities begins, and how wide it is.
const COUNT_AT: f64 = LEFT + GOODS_WIDTH;
const COUNT_WIDTH: f64 = 50.0;

/// Where the column naming the picker begins.
const PICKED_AT: f64 = COUNT_AT + COUNT_WIDTH;

/// How far apart two lines of the note stand.
const PITCH: f64 = 18.0;

/// The size the note is set at.
const NOTE_SIZE: f64 = 9.5;

/// The grey the page draws its second-rank words in.
const GREY: Rgb = Rgb::gray(0.42);

/// The grey the rules of the note are drawn in.
const RULE: Rgb = Rgb::gray(0.72);

/// Who picked each line, which the note does print.
const PICKERS: [&str; LINE_COUNT] = ["MJ", "MJ", "PL", "PL", "SD", "SD"];

/// Sets a block of words with its first baseline at `top`, and hands back the
/// ordinate the block ends at.
fn block(
    c: &mut Content,
    flow: &TextFlow,
    x: f64,
    top: f64,
    width: f64,
    text: &str,
) -> Result<f64, Box<dyn std::error::Error>> {
    let lines = flow.break_lines(text, width);
    c.begin_text();
    flow.draw(c, &lines, x, top, width)?;
    c.end_text();
    Ok(top - flow.height(&lines))
}

/// The list of facts one line of the note carries.
fn facts_of(line: &Carried) -> Dictionary {
    let mut facts = Dictionary::new();
    facts.set(Name::new("Order"), Object::text_string(line.order));
    facts.set(Name::new("Article"), Object::text_string(line.article));
    facts.set(Name::new("Bin"), Object::text_string(line.bin));
    facts
}

/// The list of facts the point where the note is signed carries.
fn round_facts() -> Dictionary {
    let mut facts = Dictionary::new();
    facts.set(Name::new("Round"), Object::text_string(ROUND));
    facts.set(Name::new("Van"), Object::text_string(VAN));
    facts
}

/// Draws the six lines of the note, each inside the run that carries its facts,
/// and hands back the ordinate the last of them ends at.
fn lines_of_the_note(
    c: &mut Content,
    handle: &FontHandle,
    words: &Words,
    lists: &[PropertiesHandle],
    top: f64,
) -> Result<f64, Box<dyn std::error::Error>> {
    let goods = TextFlow::new(handle, NOTE_SIZE);
    let figure = TextFlow::new(handle, NOTE_SIZE).align(Align::Right);
    let picker = TextFlow::new(handle, NOTE_SIZE).align(Align::Right);

    let mut row = top;
    for (index, line) in CARRIED.iter().enumerate() {
        c.begin_marked_with(&Name::new("Line"), &lists[index]);
        block(c, &goods, LEFT, row, GOODS_WIDTH, words.items[index])?;
        block(
            c,
            &figure,
            COUNT_AT,
            row,
            COUNT_WIDTH,
            &line.quantity.to_string(),
        )?;
        block(
            c,
            &picker,
            PICKED_AT,
            row,
            LEFT + WIDTH - PICKED_AT,
            PICKERS[index],
        )?;
        c.end_marked();

        c.set_stroke(RULE)?;
        c.set_line_width(0.4)?;
        c.move_to(LEFT, row - PITCH + 4.0)?;
        c.line_to(LEFT + WIDTH, row - PITCH + 4.0)?;
        c.stroke();
        row -= PITCH;
    }
    Ok(row)
}

/// Draws the whole page.
fn build(words: &Words, font: Font) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let handle = doc.add_font(font);

    let mut lists = Vec::new();
    for line in &CARRIED {
        lists.push(doc.add_properties(facts_of(line))?);
    }
    let round = doc.add_properties(round_facts())?;

    let title = TextFlow::new(&handle, 18.0);
    let lead = TextFlow::new(&handle, 10.0);
    let label = TextFlow::new(&handle, 12.0);
    let small = TextFlow::new(&handle, 8.5).color(GREY);

    let mut c = Content::new();
    let mut top = 790.0;
    top = block(&mut c, &title, LEFT, top, WIDTH, words.title)? - 12.0;
    top = block(&mut c, &lead, LEFT, top, WIDTH, words.lead)? - 22.0;

    top = block(&mut c, &label, LEFT, top, WIDTH, words.note)? - 10.0;
    top = block(&mut c, &small, LEFT, top, WIDTH, words.consignee)? - 12.0;

    block(&mut c, &small, LEFT, top, GOODS_WIDTH, words.goods)?;
    block(
        &mut c,
        &small.clone().align(Align::Right),
        COUNT_AT,
        top,
        COUNT_WIDTH,
        words.count,
    )?;
    top = block(
        &mut c,
        &small.clone().align(Align::Right),
        PICKED_AT,
        top,
        LEFT + WIDTH - PICKED_AT,
        words.picked,
    )? - 4.0;

    c.set_stroke(Rgb::gray(0.3))?;
    c.set_line_width(0.6)?;
    c.move_to(LEFT, top)?;
    c.line_to(LEFT + WIDTH, top)?;
    c.stroke();

    top = lines_of_the_note(&mut c, &handle, words, &lists, top - 12.0)? - 16.0;

    // The point where the driver signs, and the list the round travels in.
    c.mark_point_with(&Name::new("Signature"), &round);
    c.set_stroke(Rgb::gray(0.3))?;
    c.set_line_width(0.5)?;
    c.move_to(LEFT + WIDTH - 200.0, top)?;
    c.line_to(LEFT + WIDTH, top)?;
    c.stroke();
    top = block(
        &mut c,
        &small.clone().align(Align::Right),
        LEFT + WIDTH - 200.0,
        top - 3.0,
        200.0,
        words.signature,
    )? - 26.0;

    // The fold tick, and the mark that carries nothing but its own place.
    c.set_stroke(RULE)?;
    c.set_line_width(0.4)?;
    c.move_to(LEFT - 18.0, 561.0)?;
    c.line_to(LEFT - 8.0, 561.0)?;
    c.stroke();
    c.mark_point(&Name::new("Fold"));

    top = block(&mut c, &label, LEFT, top, WIDTH, words.beneath)? - 10.0;
    top = block(&mut c, &lead, LEFT, top, WIDTH, words.carried)? - 18.0;
    top = block(&mut c, &label, LEFT, top, WIDTH, words.fold)? - 10.0;
    top = block(&mut c, &lead, LEFT, top, WIDTH, words.folded)? - 20.0;

    let closing = TextFlow::new(&handle, 9.0).color(GREY);
    block(&mut c, &closing, LEFT, top, WIDTH, words.caveat)?;

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

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 = env::args().skip(1);
    // 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 out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("carried_facts")));
    let face = args.next().map_or_else(default_font, PathBuf::from);

    let font = Font::parse(fs::read(&face)?)?;
    let drawn = build(words, font)?;

    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &drawn)?;
    println!(
        "wrote {out}: {} bytes, {LISTS} lists carried and none drawn",
        drawn.len()
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::cos::{Name, Object};

    use super::{CARRIED, LINE_COUNT, LISTS, ROUND, VAN, WORDS, facts_of, language, round_facts};

    /// The lines two languages are allowed to write the same way. There are
    /// none: even the consignee's line carries a date, which each language
    /// writes its own way.
    const SPARED: [&str; 0] = [];

    #[test]
    fn every_language_draws_the_note_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the note says these in more than one language: {untranslated:?}"
        );
    }

    /// The whole point of the page: what is carried is not what is printed. No
    /// word the note draws, in any language, holds a code the page carries.
    #[test]
    fn no_code_the_page_carries_is_drawn_on_it() {
        for (named, words) in WORDS {
            let drawn = format!("{words:#?}");
            for line in &CARRIED {
                for code in [line.order, line.article, line.bin] {
                    assert!(
                        !drawn.contains(code),
                        "the {} page draws {code}, which it is meant to carry",
                        named.code()
                    );
                }
            }
            for code in [ROUND, VAN] {
                assert!(
                    !drawn.contains(code),
                    "the {} page draws {code}, which it is meant to carry",
                    named.code()
                );
            }
        }
    }

    /// Every line carries the three facts under the same three names, so a
    /// program reading the file looks for one shape and not six.
    #[test]
    fn every_line_carries_the_same_three_names() {
        for line in &CARRIED {
            let facts = facts_of(line);
            for name in ["Order", "Article", "Bin"] {
                assert!(
                    facts.get(&Name::new(name)).is_some(),
                    "a line of the note carries no {name}"
                );
            }
        }
    }

    /// The page states how many lists travel with it, so the count has to be
    /// the count.
    #[test]
    fn the_page_carries_one_list_a_line_and_one_for_the_signature() {
        assert_eq!(LISTS, LINE_COUNT + 1);
        assert_eq!(
            round_facts().get(&Name::new("Round")),
            Some(&Object::text_string(ROUND))
        );
    }
}