write_drawn_letters.rs

Le fichier Rust de l’exemple « Des lettres que vous dessinez vous-même ». Une coche, une croix et un tiret dessinés par le programme, ajoutés au document comme une police, et posés au milieu de mots ordinaires.

Rust 841 lignes

À quoi sert cet exemple

Un fichier de police contient des lettres dessinées par quelqu’un d’autre. Parfois, ce dont un document a besoin, c’est d’un signe que personne n’a dessiné pour vous : votre logo, la coche de vos fiches qualité, un symbole que votre métier connaît et qu’Unicode ignore. La réponse habituelle est de poser une image à chaque endroit, puis de calculer à la main de combien avancer avant le mot suivant — ce qui se défait le jour où le texte est traduit ou change de taille.

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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! Sets text in a font whose letters are drawings rather than outlines read
//! from a file.
//!
//! Two fonts are built here, both out of content operators. The first paints
//! its own colours: a green tick, a red cross and a grey dash, set inline among
//! ordinary words. The second states shapes and no colour, so each is painted
//! in whatever colour the text around it is in — the same square comes out red
//! on one line and blue on the next.
//!
//! A font file that paints its own signs in colour is then set beside them:
//! three of its signs inside a sentence, its star from each of the two palettes
//! the file holds, two signs a second file fills with gradients and one it
//! holds as a picture, three it composes each out of two paints — two squares
//! whose colours multiply where they overlap, a star keeping the colours of a
//! square laid over it, a square with a star cut out of it — and its flag,
//! whose pole takes the colour of the text around it while its cloth keeps its
//! own.
//!
//! The letters still copy out of the file as the characters they stand for,
//! because the font carries the map back to them.
//!
//! Under the note, each font says what it holds: how many glyphs, the box they
//! stand in, the matrix that scales them, and which glyph its first mark is and
//! how wide.
//!
//! Every word the page sets is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn.
//!
//! Usage: `cargo run --example write_drawn_letters -- tmp/drawn.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_drawn_letters`

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

use hqf_pdf::content::Content;
use hqf_pdf::{
    ColorFont, Document, Font, FontHandle, Page, Rect, Rgb, RichText, Style, TextFlow, Type3Font,
    Type3Glyph,
};

#[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 its words with 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")
}

/// The font file that paints its signs in colour: the one committed for the
/// tests.
fn color_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("HqfColor.ttf")
}

/// The font file that fills its signs with gradients: the one committed for the
/// tests.
fn gradient_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("HqfColorV1.ttf")
}

/// The words the page 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 heading over the letters that paint themselves.
    painted: &'static str,
    /// The line the coloured letters are set in, before each of them.
    checks: [&'static str; 3],
    /// The heading over the letters that take the colour around them.
    shaped: &'static str,
    /// What the two coloured lines say, before the square.
    tinted: [&'static str; 2],
    /// The closing note about copying the text out.
    note: &'static str,
    /// What the two fonts are called on the page, the painted one first.
    fonts: [&'static str; 2],
    /// What a font holds; `{font}`, `{count}`, `{box}`, `{matrix}`,
    /// `{character}`, `{index}` and `{width}` stand for them.
    holds: &'static str,
    /// The heading over the signs a font file paints in colour.
    colored: &'static str,
    /// The start of the sentence the three coloured signs are set in.
    steps_lead: &'static str,
    /// What follows each of the three coloured signs in that sentence.
    steps: [&'static str; 3],
    /// What follows the star from each palette, the first palette first.
    palettes: [&'static str; 2],
    /// What follows each of the two signs filled with gradients, the square
    /// first.
    gradients: [&'static str; 2],
    /// What follows the sign shown as a picture.
    picture: &'static str,
    /// What follows each of the three signs composed out of two paints: the two
    /// squares multiplied, the star kept inside, the square cut out.
    composed: [&'static str; 3],
    /// The note about the signs the font file paints.
    colored_note: &'static str,
}

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

/// The page in English.
const ENGLISH: Words = Words {
    title: "Letters you draw yourself",
    lead: "The three marks below are not in any font file. Each one is a \
           drawing this program made, added to the document as a font, and set \
           in a line of text like any other letter. Copy the line out of this \
           file and the marks come back as the characters they stand for.",
    painted: "Marks that paint themselves",
    checks: ["Invoice sent", "Payment received", "Delivery note"],
    shaped: "Marks that take the colour around them",
    tinted: ["Overdue", "Settled"],
    note: "A mark of the first kind carries its own colour. A mark of the second \
           kind states a shape and nothing else, so the colour of the words it \
           sits among is the colour it comes out in.",
    fonts: ["The painted font", "The shaped font"],
    holds: "{font}: glyphs, {count}; box, [{box}]; matrix, [{matrix}]; {character} is its \
            glyph {index}, {width} wide.",
    colored: "Signs a font file paints in colour",
    steps_lead: "Each step is marked: ",
    steps: ["approved,", "under review,", "awaiting signature."],
    palettes: [
        "The star from the font’s first palette;",
        "the same star from its second.",
    ],
    gradients: [
        "A square the font fills with colours running from one side to the other, half see-through;",
        "a diamond it fills with colours spreading from its centre.",
    ],
    picture: "A sign the font file holds as a picture, shown as it is rather than drawn from an outline.",
    composed: [
        "Two squares the font lays one over the other, their colours multiplied where they overlap;",
        "a star taking the colours of a square laid over it, kept only inside its own outline;",
        "a square the font cuts a star out of.",
    ],
    colored_note: "This program draws none of these signs: the font file paints each \
                   one in layers of colour, and the document sets them like any other \
                   letter. The flag’s pole takes the colour of the text around it; its \
                   cloth keeps its own.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Des lettres que vous dessinez vous-même",
    lead: "Les trois marques ci-dessous ne viennent d’aucun fichier de police. Chacune \
est un dessin créé par ce programme, ajouté au document comme une police et \
posé dans une ligne de texte comme n’importe quelle lettre. Copiez la ligne \
depuis ce fichier : les marques redeviennent les caractères qu’elles \
représentent.",
    painted: "Des marques qui ont leur propre couleur",
    checks: ["Facture envoyée", "Paiement reçu", "Bon de livraison"],
    shaped: "Des marques qui prennent la couleur qui les entoure",
    tinted: ["En retard", "Réglé"],
    note: "Une marque du premier type définit sa propre couleur. Une marque du second \
type ne définit qu’une forme : elle prend donc la couleur des mots qu’elle \
accompagne.",
    fonts: ["La police peinte", "La police de formes"],
    holds: "{font} : glyphes, {count} ; boîte, [{box}] ; matrice, [{matrix}] ; \
{character} est son glyphe {index}, large de {width}.",
    colored: "Des signes qu’un fichier de police peint en couleur",
    steps_lead: "Chaque étape est signalée : ",
    steps: [
        "approuvée,",
        "en cours de relecture,",
        "en attente de signature.",
    ],
    palettes: [
        "L’étoile tirée de la première palette de la police ;",
        "la même étoile tirée de la deuxième.",
    ],
    gradients: [
        "Un carré que la police remplit d’un dégradé de couleurs allant d’un côté à l’autre, à demi transparent ;",
        "un losange qu’elle remplit d’un dégradé partant de son centre.",
    ],
    picture: "Un signe que le fichier de police contient sous forme d’image, affiché tel quel au lieu d’être tracé à partir d’un contour.",
    composed: [
        "Deux carrés que la police superpose et dont les couleurs se multiplient là où ils se chevauchent ;",
        "une étoile qui prend les couleurs d’un carré posé par-dessus, sans qu’elles débordent de son contour ;",
        "un carré dans lequel la police découpe un trou en forme d’étoile.",
    ],
    colored_note: "Ce programme ne dessine aucun de ces signes : le fichier de \
police peint chacun d’eux en couches de couleur, et le document les pose comme \
n’importe quelle lettre. Le mât du drapeau prend la couleur du texte qui \
l’entoure ; le tissu garde la sienne.",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Letters die u zelf tekent",
    lead: "De drie tekens hieronder staan in geen enkel lettertypebestand. Elk is een tekening die dit programma heeft gemaakt, als lettertype aan het document toegevoegd en in een tekstregel gezet zoals elke andere letter. Kopieer de regel uit dit bestand en de tekens komen terug als de tekens waar ze voor staan.",
    painted: "Tekens die zichzelf kleuren",
    checks: ["Factuur verstuurd", "Betaling ontvangen", "Pakbon"],
    shaped: "Tekens die de kleur om zich heen aannemen",
    tinted: ["Achterstallig", "Voldaan"],
    note: "Een teken van de eerste soort heeft zijn eigen kleur. Een teken van de tweede soort geeft een vorm en verder niets, dus krijgt het de kleur van de woorden waartussen het staat.",
    fonts: ["Het geschilderde lettertype", "Het vormlettertype"],
    holds: "{font}: glyphs, {count}; kader, [{box}]; matrix, [{matrix}]; {character} is zijn glyph {index}, {width} breed.",
    colored: "Tekens die een lettertypebestand in kleur schildert",
    steps_lead: "Elke stap krijgt een teken: ",
    steps: ["goedgekeurd,", "in beoordeling,", "wacht op ondertekening."],
    palettes: [
        "De ster uit het eerste palet van het lettertype;",
        "dezelfde ster uit het tweede.",
    ],
    gradients: [
        "Een vierkant dat het lettertype vult met een half doorzichtig kleurverloop van de ene kant naar de andere;",
        "een ruit die het vult met een kleurverloop vanuit het midden.",
    ],
    picture: "Een teken dat in het lettertypebestand als afbeelding is opgeslagen en zo wordt weergegeven, niet getekend vanuit een contour.",
    composed: [
        "Twee vierkanten die het lettertype over elkaar legt, hun kleuren vermenigvuldigd waar ze elkaar bedekken;",
        "een ster die de kleuren aanneemt van een vierkant dat erop ligt, alleen binnen haar eigen omtrek;",
        "een vierkant waaruit het lettertype een ster snijdt.",
    ],
    colored_note: "Dit programma tekent geen van deze tekens: het lettertypebestand schildert elk teken in kleurlagen, en het document zet ze net als elke andere letter. De stok van de vlag neemt de kleur van de omringende tekst aan; het doek houdt zijn eigen kleur.",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Letras desenhadas por si",
    lead: "As três marcas abaixo não estão em nenhum ficheiro de tipo de letra. Cada uma é um desenho feito por este programa, acrescentado ao documento como tipo de letra e composto numa linha de texto como qualquer outra letra. Copie a linha deste ficheiro e as marcas voltam como os caracteres que representam.",
    painted: "Marcas que se pintam sozinhas",
    checks: ["Fatura enviada", "Pagamento recebido", "Guia de remessa"],
    shaped: "Marcas que tomam a cor à sua volta",
    tinted: ["Vencida", "Liquidada"],
    note: "Uma marca do primeiro tipo leva a sua própria cor. Uma marca do segundo tipo dá uma forma e nada mais, por isso sai da cor das palavras entre as quais está.",
    fonts: ["O tipo de letra pintado", "O tipo de letra de formas"],
    holds: "{font}: glifos, {count}; caixa, [{box}]; matriz, [{matrix}]; {character} é o seu glifo {index}, de largura {width}.",
    colored: "Sinais que um ficheiro de tipo de letra pinta a cores",
    steps_lead: "Cada etapa tem o seu sinal: ",
    steps: ["aprovada,", "em análise,", "por assinar."],
    palettes: [
        "A estrela na primeira paleta do tipo de letra;",
        "a mesma estrela na segunda.",
    ],
    gradients: [
        "Um quadrado que o tipo de letra preenche com um gradiente de cores de um lado ao outro, semitransparente;",
        "um losango que o tipo de letra preenche com cores que irradiam do centro.",
    ],
    picture: "Um sinal que o ficheiro do tipo de letra guarda como imagem, mostrado tal como está em vez de ser desenhado a partir de um contorno.",
    composed: [
        "Dois quadrados que o tipo de letra sobrepõe, com as cores multiplicadas onde se cobrem;",
        "uma estrela que toma as cores de um quadrado posto por cima, só dentro do seu próprio contorno;",
        "um quadrado do qual o tipo de letra recorta uma estrela.",
    ],
    colored_note: "Este programa não desenha nenhum destes sinais: o ficheiro de tipo de letra pinta cada um em camadas de cor e o documento compõe-nos como qualquer outra letra. O mastro da bandeira toma a cor do texto que o rodeia; o pano conserva a sua.",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Lettere disegnate da voi",
    lead: "I tre segni qui sotto non sono in nessun file di font. Ciascuno è un disegno fatto da questo programma, aggiunto al documento come font e composto in una riga di testo come ogni altra lettera. Copiate la riga da questo file e i segni tornano come i caratteri che rappresentano.",
    painted: "Segni che si dipingono da sé",
    checks: [
        "Fattura inviata",
        "Pagamento ricevuto",
        "Documento di trasporto",
    ],
    shaped: "Segni che prendono il colore intorno",
    tinted: ["Scaduta", "Saldata"],
    note: "Un segno del primo tipo porta il proprio colore. Un segno del secondo tipo dà una forma e nient’altro, così esce del colore delle parole tra cui si trova.",
    fonts: ["Il font dipinto", "Il font di forme"],
    holds: "{font}: glifi, {count}; riquadro, [{box}]; matrice, [{matrix}]; {character} è il suo glifo {index}, largo {width}.",
    colored: "Segni che un file di font dipinge a colori",
    steps_lead: "Ogni fase ha il suo segno: ",
    steps: ["approvata,", "in revisione,", "in attesa di firma."],
    palettes: [
        "La stella con la prima palette del font;",
        "la stessa stella con la seconda.",
    ],
    gradients: [
        "Un quadrato che il font riempie di colori sfumati da un lato all’altro, semitrasparenti;",
        "un rombo che il font riempie di colori che sfumano dal centro verso l’esterno.",
    ],
    picture: "Un segno che il file del font contiene come immagine, mostrato così com’è anziché tracciato a partire da un contorno.",
    composed: [
        "Due quadrati che il font sovrappone, con i colori moltiplicati dove si coprono;",
        "una stella che prende i colori di un quadrato posato sopra, solo dentro il proprio contorno;",
        "un quadrato da cui il font ritaglia una stella.",
    ],
    colored_note: "Questo programma non disegna nessuno di questi segni: è il file di font a dipingerli, ciascuno a strati di colore, e il documento li compone come qualsiasi altra lettera. L’asta della bandiera prende il colore del testo intorno; il drappo conserva il proprio.",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Letras que dibuja usted mismo",
    lead: "Las tres marcas de abajo no están en ningún archivo de fuente. Cada una es un dibujo hecho por este programa, añadido al documento como fuente y compuesto en una línea de texto como cualquier otra letra. Copie la línea de este archivo y las marcas vuelven como los caracteres que representan.",
    painted: "Marcas que se pintan solas",
    checks: ["Factura enviada", "Pago recibido", "Albarán"],
    shaped: "Marcas que toman el color de su entorno",
    tinted: ["Vencida", "Saldada"],
    note: "Una marca del primer tipo lleva su propio color. Una marca del segundo tipo da una forma y nada más, así que toma el color de las palabras entre las que está.",
    fonts: ["La fuente pintada", "La fuente de formas"],
    holds: "{font}: glifos, {count}; caja, [{box}]; matriz, [{matrix}]; {character} es su glifo {index}, de ancho {width}.",
    colored: "Signos que un archivo de fuente pinta en color",
    steps_lead: "Cada fase se indica con un signo: ",
    steps: ["aprobada,", "en revisión,", "pendiente de firma."],
    palettes: [
        "La estrella con la primera paleta de la fuente;",
        "la misma estrella con la segunda.",
    ],
    gradients: [
        "Un cuadrado que la fuente rellena con un degradado de colores de un lado a otro, semitransparente;",
        "un rombo que la fuente rellena con un degradado desde su centro hacia fuera.",
    ],
    picture: "Un signo que el archivo de la fuente guarda como imagen y que se muestra tal cual, en lugar de trazarse a partir de un contorno.",
    composed: [
        "Dos cuadrados que la fuente superpone, con sus colores multiplicados donde se cubren;",
        "una estrella que toma los colores de un cuadrado puesto encima, solo dentro de su propio contorno;",
        "un cuadrado del que la fuente recorta una estrella.",
    ],
    colored_note: "Este programa no dibuja ninguno de estos signos: el archivo de fuente pinta cada uno en capas de color, y el documento los compone como cualquier otra letra. El asta de la bandera toma el color del texto que la rodea; la tela conserva el suyo.",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Buchstaben, die Sie selbst zeichnen",
    lead: "Die drei Zeichen unten stehen in keiner Schriftdatei. Jedes ist eine Zeichnung, die dieses Programm angefertigt, dem Dokument als Schrift hinzugefügt und wie jeden anderen Buchstaben in eine Textzeile gesetzt hat. Kopieren Sie die Zeile aus dieser Datei, und die Zeichen kommen als die Schriftzeichen zurück, für die sie stehen.",
    painted: "Zeichen, die sich selbst färben",
    checks: ["Rechnung versandt", "Zahlung eingegangen", "Lieferschein"],
    shaped: "Zeichen, die die Farbe ihrer Umgebung annehmen",
    tinted: ["Überfällig", "Beglichen"],
    note: "Ein Zeichen der ersten Art trägt seine eigene Farbe. Ein Zeichen der zweiten Art gibt eine Form an und sonst nichts, also erscheint es in der Farbe der Wörter, zwischen denen es steht.",
    fonts: ["Die gefärbte Schrift", "Die geformte Schrift"],
    holds: "{font}: Glyphen, {count}; Rahmen, [{box}]; Matrix, [{matrix}]; {character} ist ihr Glyph {index}, {width} breit.",
    colored: "Zeichen, die eine Schriftdatei in Farbe malt",
    steps_lead: "Jeder Schritt ist gekennzeichnet: ",
    steps: ["freigegeben,", "in Prüfung,", "Unterschrift ausstehend."],
    palettes: [
        "Der Stern aus der ersten Palette der Schrift;",
        "derselbe Stern aus ihrer zweiten.",
    ],
    gradients: [
        "Ein Quadrat, das die Schrift mit einem halbtransparenten Farbverlauf von einer Seite zur anderen füllt;",
        "eine Raute, die sie mit einem Farbverlauf füllt, der von der Mitte aus nach außen verläuft.",
    ],
    picture: "Ein Zeichen, das in der Schriftdatei als Bild gespeichert ist und unverändert angezeigt wird, statt aus einem Umriss gezeichnet zu werden.",
    composed: [
        "Zwei von der Schrift übereinandergelegte Quadrate, deren Farben sich multiplizieren, wo sie sich überdecken;",
        "ein Stern, der die Farben eines darübergelegten Quadrats annimmt, aber nur innerhalb seines eigenen Umrisses;",
        "ein Quadrat, aus dem die Schrift einen Stern ausschneidet.",
    ],
    colored_note: "Keines dieser Zeichen zeichnet dieses Programm: Die Schriftdatei malt jedes in Farbschichten, und das Dokument setzt sie wie jeden anderen Buchstaben. Die Fahnenstange nimmt die Farbe des umgebenden Textes an; das Fahnentuch behält seine eigene.",
};

/// 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 matrix that puts a drawn font on the thousandth scale a font file uses,
/// so a width of 600 is six tenths of the size the text is set at.
const THOUSANDTH: [f64; 6] = [0.001, 0.0, 0.0, 0.001, 0.0, 0.0];

/// How wide every drawn glyph is, in glyph space: one em.
const GLYPH_WIDTH: f64 = 1000.0;

/// How thick a drawn stroke is, in glyph space.
const STROKE: f64 = 150.0;

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

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

/// The character the tick is set with.
const TICK: char = '\u{2713}';
/// The character the cross is set with.
const CROSS: char = '\u{2717}';
/// The character the dash is set with.
const DASH: char = '\u{2013}';
/// The character the square is set with.
const SQUARE: char = '\u{25A0}';

/// The star the colour font paints.
const STAR: char = '\u{2605}';
/// The target the colour font paints.
const TARGET: char = '\u{25C9}';
/// The triangle the colour font paints.
const TRIANGLE: char = '\u{25B2}';
/// The flag the colour font paints, its pole in the colour of the text.
const FLAG: char = '\u{2691}';

/// Every sign the page sets in the colour font.
const SIGNS: [char; 4] = [STAR, TARGET, TRIANGLE, FLAG];

/// The square the second colour font fills with a linear gradient.
const GRADIENT_SQUARE: char = '\u{25A0}';
/// The diamond the second colour font fills with a radial gradient.
const GRADIENT_DIAMOND: char = '\u{25C6}';
/// The sign the second colour font shows as a picture.
const PICTURE: char = '\u{25CB}';
/// Every sign the page sets in the second colour font.
const GRADIENT_SIGNS: [char; 3] = [GRADIENT_SQUARE, GRADIENT_DIAMOND, PICTURE];

/// The two squares the second colour font composes in the multiply mode.
const MULTIPLIED: char = '\u{29C9}';
/// The star the second colour font paints with the colours of a square laid
/// over it, kept only where the star paints.
const KEPT_INSIDE: char = '\u{2606}';
/// The square the second colour font paints only where a star laid over it does
/// not.
const CUT_OUT: char = '\u{25A3}';
/// Every sign the page sets composed out of two paints, in the order the page
/// sets them.
const COMPOSED_SIGNS: [char; 3] = [MULTIPLIED, KEPT_INSIDE, CUT_OUT];

/// The box every drawn glyph stands in, in glyph space.
const fn glyph_box() -> Rect {
    Rect::new(0.0, -200.0, GLYPH_WIDTH, 1000.0)
}

/// A tick, stroked in `ink`.
fn tick(ink: Rgb) -> Result<Content, Box<dyn std::error::Error>> {
    let mut pen = Content::new();
    pen.set_stroke(ink)?.set_line_width(STROKE)?;
    pen.move_to(140.0, 480.0)?
        .line_to(390.0, 230.0)?
        .line_to(870.0, 740.0)?;
    pen.stroke();
    Ok(pen)
}

/// A cross, stroked in `ink`.
fn cross(ink: Rgb) -> Result<Content, Box<dyn std::error::Error>> {
    let mut pen = Content::new();
    pen.set_stroke(ink)?.set_line_width(STROKE)?;
    pen.move_to(200.0, 230.0)?.line_to(810.0, 740.0)?;
    pen.move_to(810.0, 230.0)?.line_to(200.0, 740.0)?;
    pen.stroke();
    Ok(pen)
}

/// A dash, filled in `ink`.
fn dash(ink: Rgb) -> Result<Content, Box<dyn std::error::Error>> {
    let mut pen = Content::new();
    pen.set_fill(ink)?.rect(160.0, 400.0, 680.0, STROKE)?;
    pen.fill();
    Ok(pen)
}

/// A filled square, in no colour of its own.
fn square() -> Result<Content, Box<dyn std::error::Error>> {
    let mut pen = Content::new();
    pen.rect(200.0, 150.0, 600.0, 600.0)?;
    pen.fill();
    Ok(pen)
}

/// The tick glyph, green.
fn tick_glyph() -> Result<Type3Glyph, Box<dyn std::error::Error>> {
    Ok(Type3Glyph::painted(
        TICK,
        GLYPH_WIDTH,
        tick(Rgb::new(0.15, 0.55, 0.25))?,
    ))
}

/// The square glyph, in no colour of its own.
fn square_glyph() -> Result<Type3Glyph, Box<dyn std::error::Error>> {
    let bounds = Rect::new(200.0, 150.0, 600.0, 600.0);
    Ok(Type3Glyph::shaped(SQUARE, GLYPH_WIDTH, bounds, square()?))
}

/// The numbers of `values` as the page writes them, a space between each.
fn listed(values: &[f64]) -> String {
    values
        .iter()
        .map(f64::to_string)
        .collect::<Vec<_>>()
        .join(" ")
}

/// What `typeface`, called `called`, holds, its first mark being `first`.
fn holds(typeface: &Type3Font, first: &Type3Glyph, called: &str, words: &Words) -> String {
    let shape = typeface.box_();
    let position = typeface
        .glyph(first.character())
        .map_or_else(String::new, |glyph| glyph.index().to_string());
    words
        .holds
        .replace("{font}", called)
        .replace("{count}", &typeface.glyph_count().to_string())
        .replace(
            "{box}",
            &listed(&[shape.x(), shape.y(), shape.width(), shape.height()]),
        )
        .replace("{matrix}", &listed(&typeface.matrix()))
        .replace("{character}", &first.character().to_string())
        .replace("{index}", &position)
        .replace("{width}", &first.width().to_string())
}

/// The font whose three marks paint themselves.
fn painted_font() -> Result<Type3Font, Box<dyn std::error::Error>> {
    let glyphs = vec![
        tick_glyph()?,
        Type3Glyph::painted(CROSS, GLYPH_WIDTH, cross(Rgb::new(0.75, 0.15, 0.15))?),
        Type3Glyph::painted(DASH, GLYPH_WIDTH, dash(Rgb::gray(0.55))?),
    ];
    Ok(Type3Font::new(THOUSANDTH, glyph_box(), glyphs)?)
}

/// The font whose one mark takes the colour of the text around it.
fn shaped_font() -> Result<Type3Font, Box<dyn std::error::Error>> {
    let glyphs = vec![square_glyph()?];
    Ok(Type3Font::new(THOUSANDTH, glyph_box(), glyphs)?)
}

/// 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,
    handle: &FontHandle,
    size: f64,
    top: f64,
    text: &str,
) -> Result<f64, Box<dyn std::error::Error>> {
    let flow = TextFlow::new(handle, size);
    let lines = flow.break_lines(text, WIDTH);
    c.begin_text();
    flow.draw(c, &lines, LEFT, top, WIDTH)?;
    c.end_text();
    Ok(top - flow.height(&lines))
}

/// Sets `line` with its first baseline at `top`, and hands back the ordinate it
/// ends at.
fn set_line(c: &mut Content, line: &RichText, top: f64) -> Result<f64, Box<dyn std::error::Error>> {
    let lines = line.break_lines(WIDTH);
    line.draw(c, &lines, LEFT, top, WIDTH)?;
    Ok(top - RichText::height(&lines))
}

/// Sets the signs the colour fonts paint, its heading at `top`: three inside a
/// sentence, the star from each palette, the two signs filled with gradients,
/// the sign shown as a picture, the three signs composed out of two paints, the
/// flag in two text colours, then the note under them. `fonts` holds the colour
/// font from its first palette, then from its second, then the font filling its
/// signs with gradients and showing one as a picture, then the same font file
/// composing its three signs.
fn color_signs(
    c: &mut Content,
    words: &Words,
    text: &FontHandle,
    fonts: [&FontHandle; 4],
    top: f64,
) -> Result<f64, Box<dyn std::error::Error>> {
    let mut top = block(c, text, 12.0, top, words.colored)? - 10.0;
    let label = Style::new(text, 11.0);
    let sign = Style::new(fonts[0], 11.0);
    let mut sentence = RichText::new().span(words.steps_lead, &label);
    for (index, step) in words.steps.iter().enumerate() {
        if index > 0 {
            sentence = sentence.span(" ", &label);
        }
        sentence = sentence
            .span([STAR, TARGET, TRIANGLE][index].to_string(), &sign)
            .span(format!("\u{00A0}{step}"), &label);
    }
    top = set_line(c, &sentence, top)? - 8.0;

    let palettes = RichText::new()
        .span(STAR.to_string(), &sign)
        .span(format!("\u{00A0}{}", words.palettes[0]), &label)
        .span(" ", &label)
        .span(STAR.to_string(), &Style::new(fonts[1], 11.0))
        .span(format!("\u{00A0}{}", words.palettes[1]), &label);
    top = set_line(c, &palettes, top)? - 8.0;

    let shaded = Style::new(fonts[2], 11.0);
    let gradients = RichText::new()
        .span(GRADIENT_SQUARE.to_string(), &shaded)
        .span(format!("\u{00A0}{}", words.gradients[0]), &label)
        .span(" ", &label)
        .span(GRADIENT_DIAMOND.to_string(), &shaded)
        .span(format!("\u{00A0}{}", words.gradients[1]), &label);
    top = set_line(c, &gradients, top)? - 8.0;

    let picture = RichText::new()
        .span(PICTURE.to_string(), &shaded)
        .span(format!("\u{00A0}{}", words.picture), &label);
    top = set_line(c, &picture, top)? - 8.0;

    let composing = Style::new(fonts[3], 11.0);
    let mut composed = RichText::new();
    for (index, said) in words.composed.iter().enumerate() {
        if index > 0 {
            composed = composed.span(" ", &label);
        }
        composed = composed
            .span(COMPOSED_SIGNS[index].to_string(), &composing)
            .span(format!("\u{00A0}{said}"), &label);
    }
    top = set_line(c, &composed, top)? - 8.0;

    let mut flags = RichText::new();
    for (index, tinted) in words.tinted.iter().enumerate() {
        let ink = if index == 0 {
            Rgb::new(0.75, 0.15, 0.15)
        } else {
            Rgb::new(0.15, 0.35, 0.75)
        };
        if index > 0 {
            flags = flags.span("    ", &label);
        }
        flags = flags
            .span(FLAG.to_string(), &Style::new(fonts[0], 11.0).color(ink))
            .span(
                format!("\u{00A0}{tinted}"),
                &Style::new(text, 11.0).color(ink),
            );
    }
    top = set_line(c, &flags, top)? - 14.0;
    block(c, text, 10.0, top, words.colored_note)
}

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("drawn_letters")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let text = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    let (painting, shaping) = (painted_font()?, shaped_font()?);
    let said = [
        holds(&painting, &tick_glyph()?, words.fonts[0], words),
        holds(&shaping, &square_glyph()?, words.fonts[1], words),
    ];
    let marks = doc.add_type3_font(painting);
    let shapes = doc.add_type3_font(shaping);
    let colored = Font::parse(fs::read(color_font())?)?;
    let signs = doc.add_color_font(ColorFont::new(&colored, &SIGNS.iter().collect::<String>())?)?;
    let dark = doc.add_color_font(ColorFont::new(&colored, &STAR.to_string())?.with_palette(1)?)?;
    let filled = Font::parse(fs::read(gradient_font())?)?;
    let shaded = doc.add_color_font(ColorFont::new(
        &filled,
        &GRADIENT_SIGNS.iter().collect::<String>(),
    )?)?;
    let composing = doc.add_color_font(ColorFont::new(
        &filled,
        &COMPOSED_SIGNS.iter().collect::<String>(),
    )?)?;

    let mut c = Content::new();

    let mut top = 760.0;
    top = block(&mut c, &text, 18.0, top, words.title)? - 14.0;
    top = block(&mut c, &text, 10.0, top, words.lead)? - 26.0;

    top = block(&mut c, &text, 12.0, top, words.painted)? - 10.0;
    let label = Style::new(&text, 11.0);
    let mark = Style::new(&marks, 11.0);
    let mut line = RichText::new();
    for (index, check) in words.checks.iter().enumerate() {
        let drawn = [TICK, CROSS, DASH][index];
        // The gap after a mark is set in the words' own font: a font of
        // drawings holds the marks and nothing else, so a space in it would be
        // a space it cannot draw.
        line = line
            .span(drawn.to_string(), &mark)
            .span(format!("\u{00A0}{check}"), &label)
            .span(
                if index == words.checks.len() - 1 {
                    ""
                } else {
                    "    "
                },
                &label,
            );
    }
    let lines = line.break_lines(WIDTH);
    line.draw(&mut c, &lines, LEFT, top, WIDTH)?;
    top -= RichText::height(&lines) + 26.0;

    top = block(&mut c, &text, 12.0, top, words.shaped)? - 10.0;
    for (index, tinted) in words.tinted.iter().enumerate() {
        let ink = if index == 0 {
            Rgb::new(0.75, 0.15, 0.15)
        } else {
            Rgb::new(0.15, 0.35, 0.75)
        };
        let shape = Style::new(&shapes, 11.0).color(ink);
        let word = Style::new(&text, 11.0).color(ink);
        let row = RichText::new()
            .span(SQUARE.to_string(), &shape)
            .span(format!("\u{00A0}{tinted}"), &word);
        let drawn = row.break_lines(WIDTH);
        row.draw(&mut c, &drawn, LEFT, top, WIDTH)?;
        top -= RichText::height(&drawn) + 4.0;
    }

    top -= 22.0;
    top = block(&mut c, &text, 10.0, top, words.note)? - 14.0;
    for line in said {
        top = block(&mut c, &text, 9.0, top, &line)? - 6.0;
    }
    color_signs(
        &mut c,
        words,
        &text,
        [&signs, &dark, &shaded, &composing],
        top - 20.0,
    )?;

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

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;
    println!("wrote {out}: {} bytes", bytes.len());
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        COMPOSED_SIGNS, CROSS, DASH, GRADIENT_SIGNS, SIGNS, SQUARE, TICK, WORDS, color_font,
        gradient_font, language, painted_font, shaped_font,
    };
    use hqf_pdf::{ColorFont, Font, GlyphId};

    /// The lines two languages are allowed to write the same way, where two
    /// languages spell a word alike. Every word is a word of the language it is
    /// written in.
    const SPARED: [&str; 1] = [
        // Written the same way in Portuguese.
        r#""Vencida""#,
    ];

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

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

    #[test]
    fn the_painted_font_draws_the_three_marks_the_page_sets() {
        let font = painted_font().expect("the marks are drawn");

        assert_eq!(font.glyph_count(), 3);
        for mark in [TICK, CROSS, DASH] {
            assert!(font.glyph(mark).is_some(), "{mark} is drawn");
        }
    }

    #[test]
    fn the_shaped_font_draws_one_mark_and_gives_it_the_first_code() {
        let font = shaped_font().expect("the square is drawn");

        assert_eq!(font.glyph(SQUARE), Some(GlyphId::new(0)));
        assert_eq!(font.glyph_count(), 1);
    }

    #[test]
    fn the_color_font_paints_every_sign_the_page_sets_in_it() {
        let font = Font::parse(std::fs::read(color_font()).unwrap()).unwrap();
        let painted = ColorFont::new(&font, &SIGNS.iter().collect::<String>()).unwrap();
        let mut signs = SIGNS;
        signs.sort_unstable();

        assert_eq!(painted.colored().collect::<Vec<_>>(), signs);
        assert_eq!(painted.palettes().len(), 2);
    }

    #[test]
    fn the_gradient_font_paints_every_sign_the_page_sets_in_it() {
        let font = Font::parse(std::fs::read(gradient_font()).unwrap()).unwrap();
        let painted = ColorFont::new(&font, &GRADIENT_SIGNS.iter().collect::<String>()).unwrap();

        assert_eq!(painted.colored().collect::<Vec<_>>(), GRADIENT_SIGNS);
    }

    #[test]
    fn the_gradient_font_composes_every_sign_the_page_sets_out_of_two_paints() {
        let font = Font::parse(std::fs::read(gradient_font()).unwrap()).unwrap();
        let painted = ColorFont::new(&font, &COMPOSED_SIGNS.iter().collect::<String>()).unwrap();
        let mut signs = COMPOSED_SIGNS;
        signs.sort_unstable();

        assert_eq!(painted.colored().collect::<Vec<_>>(), signs);
    }
}