write_carried_facts.rs

Le fichier Rust de l’exemple « Un bon de livraison qui connaît sa commande ». Chaque ligne du bon contient la commande pour laquelle elle a été prélevée, le code article et l’étagère d’où elle vient, et n’imprime rien de tout cela. L’endroit où le chauffeur signe contient la tournée et la camionnette, et un autre, à côté du repère de pliage, ne contient rien que son propre emplacement.

Rust 685 lignes

À quoi sert cet exemple

Un entrepôt imprime un bon pour le chauffeur et garde un enregistrement pour lui. Trois jours plus tard, la feuille signée revient et quelqu’un doit la remettre à côté de l’enregistrement auquel elle se rapporte. Imprimer les codes sur le bon réglerait la question en un instant, au prix d’une colonne de codes faits pour les machines sur une feuille qu’un client lit et signe.

Ce que montre cet exemple

  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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! Writes 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 contient trois informations qu’elle n’imprime \
pas : la commande pour laquelle l’article a été préparé, son code article et \
l’étagère d’où il a été sorti. Chaque ligne est entourée d’une balise, et \
cette balise renvoie à une liste de renseignements écrite une seule fois dans \
le fichier, sous les noms qu’emploie l’entrepôt. Pour rapprocher la feuille \
qui revient signée des enregistrements dont elle est issue, on lit donc le \
fichier, et non le papier.",
    note: "Le bon que le chauffeur emporte",
    consignee: "Meunier & Filles, 14 rue des Tanneurs, Tours — livraison du 13 août 2026",
    goods: "Désignation",
    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 pour chacune \
des six lignes, et une septième, posée à l’endroit où signe le chauffeur, qui \
indique la tournée et le véhicule. Aucune n’apparaît sur la page, pas même une \
lettre. Chaque liste est écrite une seule fois dans le fichier, et la page y \
renvoie : une liste qui sert à plusieurs endroits n’est donc écrite qu’une \
fois, et l’on y renvoie autant de fois qu’il le faut.",
    fold: "La balise qui ne contient rien",
    folded: "Le petit trait de la marge gauche indique où plier la feuille pour une \
enveloppe à fenêtre ; juste à côté, une balise qui lui est propre est posée \
sur la page : elle ne contient qu’un nom, et aucun renseignement. Il arrive \
qu’un emplacement soit tout ce qu’il y a à dire.",
    caveat: "Le contenu d’une liste relève du programme appelant : un numéro de commande \
ici, un code article dans un catalogue, l’état d’une case dans un formulaire. \
La bibliothèque ne lit pas ces noms et n’en tire aucune conséquence : elle les \
inscrit dans le fichier et les rattache à ce qui figure sur la page.",
};

/// The note in Dutch.
const DUTCH: Words = Words {
    title: "Een pakbon die weet van welke bestelling hij komt",
    lead: "Elke regel van de pakbon hieronder bevat de bestelling waarvoor hij is verzameld, de artikelcode en het schap waar hij vandaan kwam, en drukt geen van de drie af. De regel wordt getekend binnen een gemarkeerd stuk, en dat stuk wijst naar een lijst gegevens die één keer in het bestand staat onder de eigen namen van het magazijn. Het blad dat getekend terugkomt wordt dus aan de gegevens gekoppeld door het bestand te lezen, niet het papier.",
    note: "De pakbon die de chauffeur meeneemt",
    consignee: "Meunier & Filles, 14 rue des Tanneurs, Tours — geleverd op 13 augustus 2026",
    goods: "Goederen",
    count: "Aantal",
    picked: "Verzameld door",
    items: [
        "Eiken eettafel, 180 cm",
        "Eetkamerstoel, notenhout",
        "Dressoir, drie deuren",
        "Wandplank, 90 cm",
        "Kapstok",
        "Staande lamp, geborsteld staal",
    ],
    signature: "Getekend bij levering",
    beneath: "Wat onder de pagina meereist",
    carried: "Zeven lijsten gegevens reizen met dit blad mee: één bij elk van de zes regels, en één op de plek waar de chauffeur tekent, met de route en de bestelwagen. Geen letter ervan wordt getekend. Een lijst wordt één keer in het bestand geschreven en vanaf de pagina aangewezen, dus een lijst die bij meerdere plekken hoort, staat er één keer en wordt zo vaak gemarkeerd als nodig.",
    fold: "Het teken dat niets draagt",
    folded: "Het korte streepje in de linkermarge is waar het blad wordt gevouwen voor een vensterenvelop, en ernaast wordt een eigen markering in de pagina gezet, met een naam en zonder gegevens. Soms is een plek alles wat er te zeggen valt.",
    caveat: "Wat een lijst bevat is de zaak van de aanroeper: hier een bestelnummer, een artikelcode in een catalogus, een status naast een vakje op een formulier. De bibliotheek leest deze namen niet en doet er niets mee: ze schrijft ze op en koppelt ze aan wat getekend is.",
};

/// The note in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Uma guia de remessa que sabe de que encomenda vem",
    lead: "Cada linha da guia abaixo leva a encomenda para que foi preparada, o código do artigo e a prateleira de onde saiu, e não imprime nenhum dos três. A linha é desenhada dentro de um troço marcado, e o troço aponta para uma lista de dados guardada uma vez no ficheiro com os nomes que o próprio armazém usa. A folha que volta assinada emparelha-se assim com os registos de onde veio lendo o ficheiro, não o papel.",
    note: "A guia que o motorista leva",
    consignee: "Meunier & Filles, 14 rue des Tanneurs, Tours — entregue a 13 de agosto de 2026",
    goods: "Mercadoria",
    count: "Qtd.",
    picked: "Preparado por",
    items: [
        "Mesa de jantar em carvalho, 180 cm",
        "Cadeira de jantar, nogueira",
        "Aparador, três portas",
        "Prateleira de parede, 90 cm",
        "Bengaleiro",
        "Candeeiro de pé, aço escovado",
    ],
    signature: "Assinado na entrega",
    beneath: "O que viaja por baixo da página",
    carried: "Sete listas de dados viajam com esta folha: uma por cada uma das seis linhas e uma no ponto onde o motorista assina, que leva a volta e a carrinha. Nem uma letra de nenhuma é desenhada. Uma lista escreve-se uma vez no ficheiro e é apontada a partir da página, por isso uma lista que pertence a vários sítios é guardada uma vez e marcada tantas vezes quantas forem precisas.",
    fold: "A marca que não leva nada",
    folded: "O traço curto na margem esquerda é onde a folha se dobra para um envelope de janela, e ao lado põe-se na página uma marca própria, com um nome e sem dado nenhum. Às vezes um lugar é tudo o que há a dizer.",
    caveat: "O que uma lista contém é assunto do programa que chama a biblioteca: aqui um número de encomenda, um código de artigo num catálogo, um estado junto a uma caixa de um formulário. A biblioteca não lê estes nomes nem age sobre eles: escreve-os e liga-os ao que foi desenhado.",
};

/// The note in Italian.
const ITALIAN: Words = Words {
    title: "Un documento di trasporto che sa da quale ordine viene",
    lead: "Ogni riga del documento qui sotto porta l’ordine per cui è stata preparata, il codice articolo e lo scaffale da cui è uscita, e non ne stampa nessuno dei tre. La riga è disegnata dentro un tratto marcato, e il tratto rimanda a un elenco di dati tenuto una volta nel file con i nomi propri del magazzino. Il foglio che torna firmato si abbina così ai registri da cui proviene leggendo il file, non la carta.",
    note: "Il documento che porta l’autista",
    consignee: "Meunier & Filles, 14 rue des Tanneurs, Tours — consegnato il 13 agosto 2026",
    goods: "Merce",
    count: "Qtà",
    picked: "Preparato da",
    items: [
        "Tavolo da pranzo in rovere, 180 cm",
        "Sedia da pranzo, noce",
        "Credenza, tre ante",
        "Mensola, 90 cm",
        "Appendiabiti",
        "Lampada da terra, acciaio spazzolato",
    ],
    signature: "Firmato alla consegna",
    beneath: "Ciò che viaggia sotto la pagina",
    carried: "Sette elenchi di dati viaggiano con questo foglio: uno per ciascuna delle sei righe e uno nel punto in cui firma l’autista, che porta il giro e il furgone. Non ne è disegnata nemmeno una lettera. Un elenco si scrive una volta nel file e si richiama dalla pagina, così un elenco che appartiene a più punti è tenuto una volta e marcato tutte le volte che serve.",
    fold: "Il segno che non porta nulla",
    folded: "Il tratto corto nel margine sinistro è dove il foglio si piega per una busta a finestra, e la pagina vi pone accanto un segno proprio, con un nome e senza alcun dato. A volte un luogo è tutto ciò che c’è da dire.",
    caveat: "Ciò che un elenco contiene è affare di chi chiama: qui un numero d’ordine, un codice articolo in un catalogo, uno stato accanto a una casella di un modulo. La libreria non legge questi nomi né agisce su di essi: li scrive e li lega a ciò che è stato disegnato.",
};

/// The note in Spanish.
const SPANISH: Words = Words {
    title: "Un albarán que sabe de qué pedido viene",
    lead: "Cada línea del albarán de abajo lleva el pedido para el que se preparó, el código del artículo y la estantería de la que salió, y no imprime ninguno de los tres. La línea se dibuja dentro de un tramo marcado, y el tramo apunta a una lista de datos guardada una vez en el archivo con los nombres propios del almacén. La hoja que vuelve firmada se empareja así con los registros de los que salió leyendo el archivo, no el papel.",
    note: "El albarán que lleva el conductor",
    consignee: "Meunier & Filles, 14 rue des Tanneurs, Tours — entregado el 13 de agosto de 2026",
    goods: "Mercancía",
    count: "Cant.",
    picked: "Preparado por",
    items: [
        "Mesa de comedor de roble, 180 cm",
        "Silla de comedor, nogal",
        "Aparador, tres puertas",
        "Estante de pared, 90 cm",
        "Perchero",
        "Lámpara de pie, acero cepillado",
    ],
    signature: "Firmado a la entrega",
    beneath: "Lo que viaja bajo la página",
    carried: "Siete listas de datos viajan con esta hoja: una por cada una de las seis líneas y una en el punto donde firma el conductor, que lleva la ruta y la furgoneta. No se dibuja ni una letra de ninguna. Una lista se escribe una vez en el archivo y se señala desde la página, así que una lista que pertenece a varios sitios se guarda una vez y se marca tantas veces como haga falta.",
    fold: "La marca que no lleva nada",
    folded: "El trazo corto del margen izquierdo es donde se dobla la hoja para un sobre de ventana, y a su lado se pone en la página una marca propia, con un nombre y sin ningún dato. A veces un lugar es todo lo que hay que decir.",
    caveat: "Lo que contiene una lista es cosa del programa que la usa: aquí un número de pedido, un código de artículo en un catálogo, un estado frente a una casilla de un formulario. La biblioteca ni lee estos nombres ni actúa sobre ellos: los escribe y los ata a lo que se dibujó.",
};

/// The note in German.
const GERMAN: Words = Words {
    title: "Ein Lieferschein, der weiß, aus welchem Auftrag er stammt",
    lead: "Jede Zeile des Lieferscheins unten trägt den Auftrag, für den sie kommissioniert wurde, die Artikelnummer und das Regal, aus dem sie kam, und druckt keines der drei. Die Zeile wird in einem markierten Abschnitt gezeichnet, und dieser Abschnitt verweist auf eine Liste von Angaben, die einmal in der Datei steht, unter den eigenen Namen des Lagers. Das unterschrieben zurückkommende Blatt wird also seinen Datensätzen zugeordnet, indem man die Datei liest, nicht das Papier.",
    note: "Der Lieferschein, den der Fahrer mitnimmt",
    consignee: "Meunier & Filles, 14 rue des Tanneurs, Tours — geliefert am 13. August 2026",
    goods: "Ware",
    count: "Menge",
    picked: "Kommissioniert von",
    items: [
        "Esstisch aus Eiche, 180 cm",
        "Esszimmerstuhl, Nussbaum",
        "Anrichte, drei Türen",
        "Wandregal, 90 cm",
        "Garderobenständer",
        "Stehleuchte, gebürsteter Stahl",
    ],
    signature: "Bei Lieferung unterschrieben",
    beneath: "Was unter der Seite mitreist",
    carried: "Sieben Listen von Angaben reisen mit diesem Blatt: eine zu jeder der sechs Zeilen und eine an der Stelle, an der der Fahrer unterschreibt, mit Tour und Lieferwagen. Kein einziger Buchstabe davon wird gezeichnet. Eine Liste steht einmal in der Datei, und die Seite verweist auf sie; eine Liste, die zu mehreren Stellen gehört, steht also einmal da und wird so oft markiert, wie es nötig ist.",
    fold: "Die Markierung, die nichts trägt",
    folded: "Der kurze Strich am linken Rand zeigt, wo das Blatt für einen Fensterumschlag gefaltet wird, und daneben steht auf der Seite eine eigene Markierung, mit einem Namen und ganz ohne Angaben. Manchmal ist ein Ort alles, was es zu sagen gibt.",
    caveat: "Was eine Liste enthält, ist Sache des Aufrufers: hier eine Auftragsnummer, eine Artikelnummer in einem Katalog, der Zustand eines Kästchens in einem Formular. Die Bibliothek liest diese Namen nicht und richtet sich nicht nach ihnen — sie schreibt sie auf und bindet sie an das Gezeichnete.",
};

/// 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 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, where two
    /// languages spell a word alike. Even the consignee's line carries a date,
    /// which each language writes its own way.
    const SPARED: [&str; 1] = [
        // Written the same way in Portuguese.
        r#"picked: "Preparado por""#,
    ];

    #[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))
        );
    }
}