write_output_intent.rs

Die Rust-Datei des Beispiels „Das Gerät, für das die Farben einer Datei bestimmt sind“. Das Gerät, für das die Farben einer Datei gewählt wurden, in klaren Worten auf der Seite genannt, für die es gilt, mit einem Verlauf und einem Feld pro Grundfarbe, durch das eigene Profil dieses Geräts gemalt. Die Beschreibung Ihrer Druckerei tut es ebenso.

Rust 854 Zeilen

Wofür dieses Beispiel da ist

Zwei Menschen können dieselbe Datei öffnen, sich über ihre Farbe uneinig sein, und beide haben recht, denn nichts darin sagt, wie die Zahlen aussehen sollten. Eine Druckerei geht dieses Risiko nicht ein: Bevor sie einen Auftrag druckt, will sie wissen, für welche Druckmaschine, welches Papier und welchen Druckfarbensatz die Farben gewählt wurden.

Was dieses Beispiel zeigt

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
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
842
843
844
845
846
847
848
849
850
851
852
853
854
//! The device a document's colours are meant for, stated in the file.
//!
//! A page that fills a rectangle with four numbers has said four numbers and
//! nothing about what colour they are. The output intent is the answer: the
//! profile of the device the job was prepared for, travelling inside the file,
//! together with the name of that device's condition. An archival claim makes
//! stating one compulsory, and a job separated for a press states the press's
//! own profile rather than the screen the library falls back to.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is written in. What the file states is not language: the
//! name of the condition and the name of the profile travel as they are given.
//!
//! Usage: `cargo run --example write_output_intent -- tmp/intent.pdf [font.ttf]
//! [press.icc]`
//!        `HQF_PDF_LANG=fr cargo run --example write_output_intent --
//! tmp/intention.pdf`

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

use hqf_pdf::color::icc::{self, DeviceClass};
use hqf_pdf::content::Content;
use hqf_pdf::metadata::xmp::{Metadata, PdfA};
use hqf_pdf::{
    Color, ColorSpaceHandle, Document, Error, Font, FontHandle, IccBased, OutputIntent, Page,
};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

#[path = "shared/failure.rs"]
mod failure;

use language::Language;

/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The left edge of everything.
const LEFT: f64 = 70.0;

/// How far in from `LEFT` the values of the intent's rows are set, which is the
/// room the labels beside them have.
const VALUE_IN: f64 = 100.0;

/// The date the document says it was made on, so that two runs of the example
/// produce the same bytes.
const MADE: &str = "2026-07-25T10:00:00+02:00";

/// The claim the file makes, which is a name the standard gives rather than
/// anything a language says.
const CLAIM: &str = "PDF/A-3B";

/// The tints the ramp runs through, all the profile's channels together.
const TINTS: &[f64] = &[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0];
/// The width of one cell of the ramp, the gap to the next, and its height.
const RAMP_CELL: f64 = 38.0;
/// See [`RAMP_CELL`].
const RAMP_GAP: f64 = 3.5;
/// See [`RAMP_CELL`].
const RAMP_HEIGHT: f64 = 86.0;
/// The bottom edge of the ramp.
const RAMP_Y: f64 = 440.0;

/// The size of one channel swatch, the gap to the next, and their bottom edge.
const CHANNEL_CELL: f64 = 90.0;
/// See [`CHANNEL_CELL`].
const CHANNEL_GAP: f64 = 15.0;
/// See [`CHANNEL_CELL`].
const CHANNEL_Y: f64 = 230.0;

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The title over the page, which is also the title the file states.
    title: &'static str,
    /// The two lines under the title.
    intro: [&'static str; 2],
    /// The heading over the panel that lists what the file carries.
    intent_panel: &'static str,
    /// The heading over the ramp, and the line under it.
    profile_panel: &'static str,
    /// See [`Words::profile_panel`].
    profile_note: &'static str,
    /// The heading over the channel swatches.
    channel_panel: &'static str,
    /// What the five rows of the intent panel are called.
    rows: [&'static str; 5],
    /// What stands between the size of the profile and what it describes, so
    /// that the row reads as one sentence in every language.
    profile_size: &'static str,
    /// What follows the name of the claim on its row.
    claim_note: &'static str,
    /// What a colour is made of, in words, in a grey, an RGB and a CMYK space.
    described: [&'static str; 3],
    /// The device a profile describes, one entry per kind of device a profile
    /// names in its header, then what is said of bytes that name none.
    classes: [&'static str; 8],
    /// The one channel of a grey space.
    gray_channels: [&'static str; 1],
    /// The three channels of an RGB space.
    rgb_channels: [&'static str; 3],
    /// The four channels of a CMYK space.
    cmyk_channels: [&'static str; 4],
    /// What the caller is told a profile of their own would do, under the
    /// swatches.
    closing: [&'static str; 2],
    /// What the condition is called when a profile is handed over on the
    /// command line, which is prose rather than a registered name.
    custom_info: &'static str,
}

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

    /// The channels a colour in `space` is made of, in the order their numbers
    /// are given.
    const fn channels(&self, space: hqf_pdf::DeviceSpace) -> &[&'static str] {
        match space {
            hqf_pdf::DeviceSpace::Gray => &self.gray_channels,
            hqf_pdf::DeviceSpace::Rgb => &self.rgb_channels,
            hqf_pdf::DeviceSpace::Cmyk => &self.cmyk_channels,
            _ => panic!("the profile names a space this page has no words for"),
        }
    }

    /// What a colour in `space` is made of, in words.
    const fn described(&self, space: hqf_pdf::DeviceSpace) -> &'static str {
        match space {
            hqf_pdf::DeviceSpace::Gray => self.described[0],
            hqf_pdf::DeviceSpace::Rgb => self.described[1],
            hqf_pdf::DeviceSpace::Cmyk => self.described[2],
            _ => panic!("the profile names a space this page has no words for"),
        }
    }

    /// The device the profile `bytes` describes, in words.
    fn device(&self, bytes: &[u8]) -> &'static str {
        match icc::device_class(bytes) {
            Some(DeviceClass::Input) => self.classes[0],
            Some(DeviceClass::Display) => self.classes[1],
            Some(DeviceClass::Output) => self.classes[2],
            Some(DeviceClass::DeviceLink) => self.classes[3],
            Some(DeviceClass::ColorSpace) => self.classes[4],
            Some(DeviceClass::Abstract) => self.classes[5],
            Some(DeviceClass::NamedColor) => self.classes[6],
            _ => self.classes[7],
        }
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    title: "What the numbers on this page mean",
    intro: [
        "A file states the device it was prepared for, and the profile of that device travels \
         inside it.",
        "Nothing else in the file says what its colours are: the numbers alone say none.",
    ],
    intent_panel: "The output intent this file carries",
    profile_panel: "The same profile, painted through",
    profile_note: "One profile does both jobs: it says what the file is for, and it is what these \
                   swatches are painted in. The file carries it once.",
    channel_panel: "One channel at a time, at full strength",
    rows: ["Condition", "Description", "Profile", "Device", "Claim"],
    profile_size: " bytes, describing ",
    claim_note: ", which makes stating one compulsory",
    described: ["grey", "red, green and blue", "the four printing inks"],
    classes: [
        "a scanner or a camera, which reads colour in",
        "a screen",
        "a press or a printer",
        "a link from one device to another",
        "a space colours are converted through",
        "an effect applied along the way",
        "a book of named colours",
        "nothing a profile names",
    ],
    gray_channels: ["Grey"],
    rgb_channels: ["Red", "Green", "Blue"],
    cmyk_channels: ["Cyan", "Magenta", "Yellow", "Black"],
    closing: [
        "Hand a press profile on the command line and the page is drawn in its inks instead, \
         under its own",
        "condition. A file that paints in CMYK and states a screen is a file a validator refuses.",
    ],
    custom_info: "A profile handed over on the command line",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Ce que veulent dire les nombres de cette page",
    intro: [
        "Un fichier indique l’appareil pour lequel il a été préparé, et il contient le \
profil de cet appareil.",
        "Rien d’autre dans le fichier ne dit ce que sont ses couleurs : les nombres \
seuls n’en disent rien.",
    ],
    intent_panel: "L’intention de sortie que déclare ce fichier",
    profile_panel: "Le même profil, utilisé pour peindre",
    profile_note: "Un seul profil fait les deux : il dit à quoi sert le fichier, et c’est lui qui \
peint ces pastilles. Le fichier ne le contient qu’une fois.",
    channel_panel: "Une composante à la fois, à pleine intensité",
    rows: [
        "Condition",
        "Description",
        "Profil",
        "Appareil",
        "Déclaration",
    ],
    profile_size: " octets, décrivant ",
    claim_note: ", qui oblige à en déclarer une",
    described: [
        "le gris",
        "le rouge, le vert et le bleu",
        "les quatre encres d’imprimerie",
    ],
    classes: [
        "un scanner ou un appareil photo, qui lit la couleur",
        "un écran",
        "une presse ou une imprimante",
        "un lien d’un appareil à un autre",
        "un espace par lequel passent les conversions",
        "un effet appliqué en chemin",
        "un nuancier de couleurs nommées",
        "rien qu’un profil nomme",
    ],
    gray_channels: ["Gris"],
    rgb_channels: ["Rouge", "Vert", "Bleu"],
    cmyk_channels: ["Cyan", "Magenta", "Jaune", "Noir"],
    closing: [
        "Passez un profil de presse en ligne de commande et la page est peinte avec ses \
encres, selon sa propre",
        "condition d’impression. Un fichier qui peint en CMJN en annonçant un écran est \
refusé par un validateur.",
    ],
    custom_info: "Un profil passé en ligne de commande",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Wat de getallen op deze pagina betekenen",
    intro: [
        "Een bestand zegt voor welk apparaat het is voorbereid, en het profiel van dat apparaat reist erin mee.",
        "Niets anders in het bestand zegt wat zijn kleuren zijn: de getallen alleen zeggen niets.",
    ],
    intent_panel: "De uitvoerintentie die dit bestand bevat",
    profile_panel: "Hetzelfde profiel, gebruikt om te schilderen",
    profile_note: "Eén profiel doet beide: het zegt waarvoor het bestand is, en deze stalen zijn ermee ingekleurd. Het bestand bevat het één keer.",
    channel_panel: "Eén kanaal tegelijk, op volle sterkte",
    rows: ["Conditie", "Omschrijving", "Profiel", "Apparaat", "Claim"],
    profile_size: " bytes, dat beschrijft:",
    claim_note: ", wat het noemen ervan verplicht maakt",
    described: ["grijs", "rood, groen en blauw", "de vier drukinkten"],
    classes: [
        "een scanner of camera, die kleur leest in",
        "een scherm",
        "een pers of printer",
        "een koppeling van het ene apparaat naar het andere",
        "een ruimte waarlangs kleuren worden omgezet",
        "een effect onderweg toegepast",
        "een boek met benoemde kleuren",
        "niets wat een profiel noemt",
    ],
    gray_channels: ["Grijs"],
    rgb_channels: ["Rood", "Groen", "Blauw"],
    cmyk_channels: ["Cyaan", "Magenta", "Geel", "Zwart"],
    closing: [
        "Geef op de opdrachtregel een persprofiel mee en de pagina wordt in zijn inkten getekend, onder zijn eigen",
        "conditie. Een bestand dat in CMYK schildert en een scherm opgeeft, is een bestand dat een validator weigert.",
    ],
    custom_info: "Een profiel meegegeven op de opdrachtregel",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "O que significam os números desta página",
    intro: [
        "Um ficheiro indica o dispositivo para que foi preparado, e o perfil desse dispositivo viaja dentro dele.",
        "Nada mais no ficheiro diz quais são as suas cores: os números sozinhos não dizem nenhuma.",
    ],
    intent_panel: "A intenção de saída que este ficheiro leva",
    profile_panel: "O mesmo perfil, usado para pintar",
    profile_note: "Um perfil faz os dois trabalhos: diz para que serve o ficheiro, e é nele que estas amostras são pintadas. O ficheiro leva-o uma vez.",
    channel_panel: "Um canal de cada vez, a plena intensidade",
    rows: [
        "Condição",
        "Descrição",
        "Perfil",
        "Dispositivo",
        "Declaração",
    ],
    profile_size: " bytes, que descrevem",
    claim_note: ", o que torna obrigatório indicar um",
    described: [
        "cinzento",
        "vermelho, verde e azul",
        "as quatro tintas de impressão",
    ],
    classes: [
        "um digitalizador ou uma câmara, que lê a cor em",
        "um ecrã",
        "uma máquina de impressão ou uma impressora",
        "uma ligação de um dispositivo a outro",
        "um espaço através do qual se convertem cores",
        "um efeito aplicado pelo caminho",
        "um catálogo de cores com nome",
        "nada que um perfil nomeie",
    ],
    gray_channels: ["Cinzento"],
    rgb_channels: ["Vermelho", "Verde", "Azul"],
    cmyk_channels: ["Ciano", "Magenta", "Amarelo", "Preto"],
    closing: [
        "Passe um perfil de impressão na linha de comandos e a página é desenhada nas suas tintas, sob a sua",
        "condição. Um ficheiro que pinta em CMYK e declara um ecrã é um ficheiro que um validador recusa.",
    ],
    custom_info: "Um perfil passado na linha de comandos",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Cosa significano i numeri di questa pagina",
    intro: [
        "Un file indica il dispositivo per cui è stato preparato, e il profilo di quel dispositivo viaggia al suo interno.",
        "Nient’altro nel file dice quali sono i suoi colori: i numeri da soli non ne dicono nessuno.",
    ],
    intent_panel: "L’intento di uscita che porta questo file",
    profile_panel: "Lo stesso profilo, usato per dipingere",
    profile_note: "Un profilo fa entrambi i lavori: dice a cosa serve il file, ed è con esso che sono dipinti questi campioni. Il file lo porta una volta.",
    channel_panel: "Un canale alla volta, a piena intensità",
    rows: [
        "Condizione",
        "Descrizione",
        "Profilo",
        "Dispositivo",
        "Dichiarazione",
    ],
    profile_size: " byte, che descrivono",
    claim_note: ", il che rende obbligatorio indicarne uno",
    described: [
        "grigio",
        "rosso, verde e blu",
        "i quattro inchiostri da stampa",
    ],
    classes: [
        "uno scanner o una fotocamera, che legge il colore in",
        "uno schermo",
        "una macchina da stampa o una stampante",
        "un collegamento da un dispositivo a un altro",
        "uno spazio attraverso cui si convertono i colori",
        "un effetto applicato lungo il percorso",
        "una mazzetta di colori con nome",
        "nulla che un profilo nomini",
    ],
    gray_channels: ["Grigio"],
    rgb_channels: ["Rosso", "Verde", "Blu"],
    cmyk_channels: ["Ciano", "Magenta", "Giallo", "Nero"],
    closing: [
        "Passate un profilo da stampa sulla riga di comando e la pagina è disegnata nei suoi inchiostri, sotto la sua",
        "condizione. Un file che dipinge in CMYK e dichiara uno schermo è un file che un validatore rifiuta.",
    ],
    custom_info: "Un profilo passato sulla riga di comando",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Lo que significan los números de esta página",
    intro: [
        "Un archivo indica el dispositivo para el que se preparó, y el perfil de ese dispositivo viaja dentro de él.",
        "Nada más en el archivo dice cuáles son sus colores: los números solos no dicen ninguno.",
    ],
    intent_panel: "La intención de salida que lleva este archivo",
    profile_panel: "El mismo perfil, usado para pintar",
    profile_note: "Un perfil hace los dos trabajos: dice para qué es el archivo, y con él se pintan estas muestras. El archivo lo lleva una vez.",
    channel_panel: "Un canal cada vez, a plena intensidad",
    rows: [
        "Condición",
        "Descripción",
        "Perfil",
        "Dispositivo",
        "Declaración",
    ],
    profile_size: " bytes, que describen ",
    claim_note: ", lo que obliga a indicar uno",
    described: [
        "gris",
        "rojo, verde y azul",
        "las cuatro tintas de imprenta",
    ],
    classes: [
        "un escáner o una cámara, que lee el color en",
        "una pantalla",
        "una prensa o una impresora",
        "un enlace de un dispositivo a otro",
        "un espacio por el que se convierten los colores",
        "un efecto aplicado por el camino",
        "un muestrario de colores con nombre",
        "nada que nombre un perfil",
    ],
    gray_channels: ["Gris"],
    rgb_channels: ["Rojo", "Verde", "Azul"],
    cmyk_channels: ["Cian", "Magenta", "Amarillo", "Negro"],
    closing: [
        "Pase un perfil de imprenta en la línea de órdenes y la página se dibuja en sus tintas, bajo su propia",
        "condición. Un archivo que pinta en CMYK y declara una pantalla es un archivo que un validador rechaza.",
    ],
    custom_info: "Un perfil pasado en la línea de órdenes",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Was die Zahlen auf dieser Seite bedeuten",
    intro: [
        "Eine Datei nennt das Gerät, für das sie gemacht ist, und dessen Profil reist mit.",
        "Nichts sonst in der Datei sagt, was ihre Farben sind: Die Zahlen allein sagen es nicht.",
    ],
    intent_panel: "Die Ausgabebedingung, die diese Datei trägt",
    profile_panel: "Dasselbe Profil, zum Malen verwendet",
    profile_note: "Ein Profil für beide Aufgaben: Es sagt, wofür die Datei ist, und diese Felder sind darin gemalt. Die Datei trägt es einmal.",
    channel_panel: "Ein Kanal nach dem anderen, in voller Stärke",
    rows: ["Bedingung", "Beschreibung", "Profil", "Gerät", "Anspruch"],
    profile_size: " Bytes, beschreibt ",
    claim_note: ", was die Angabe einer solchen Bedingung zur Pflicht macht",
    described: ["Grau", "Rot, Grün und Blau", "die vier Druckfarben"],
    classes: [
        "einen Scanner oder eine Kamera, die Farbe einliest",
        "einen Bildschirm",
        "eine Druckmaschine oder einen Drucker",
        "eine Verbindung von einem Gerät zu einem anderen",
        "einen Farbraum, über den Farben umgerechnet werden",
        "einen unterwegs angewandten Effekt",
        "ein Buch benannter Farben",
        "nichts, was ein Profil benennt",
    ],
    gray_channels: ["Grau"],
    rgb_channels: ["Rot", "Grün", "Blau"],
    cmyk_channels: ["Cyan", "Magenta", "Gelb", "Schwarz"],
    closing: [
        "Mit einem Druckprofil auf der Befehlszeile wird die Seite in dessen Farben gezeichnet,",
        "unter seiner Bedingung. Eine CMYK-Datei, die einen Bildschirm nennt, lehnt ein Validator ab.",
    ],
    custom_info: "Ein auf der Befehlszeile übergebenes Profil",
};

/// 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),
];

/// What the caller says the condition is called when a profile is handed over
/// on the command line.
///
/// ISO 32000-1 table 365 asks for `Custom` where the condition is not one of
/// the registered characterizations, which a profile read off a disk is not.
const CUSTOM: &str = "Custom";
/// What the condition is called when the library's own profile is used, and the
/// name that profile is registered under.
const BUILT_IN: (&str, &str) = ("sRGB", "sRGB IEC61966-2.1");

/// A profile and what the condition it describes is called.
struct Stated {
    profile: Vec<u8>,
    identifier: &'static str,
    info: String,
}

/// Draws one line of text with its baseline at `(x, y)`.
fn text(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    x: f64,
    y: f64,
    line: &str,
) -> Result<(), Error> {
    content.begin_text();
    content.set_font(font, size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(line));
    content.end_text();
    Ok(())
}

/// Draws the title and the two lines saying what the page is showing.
fn heading(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    text(content, font, 15.0, LEFT, 780.0, words.title)?;
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    text(content, font, 10.0, LEFT, 762.0, words.intro[0])?;
    text(content, font, 10.0, LEFT, 748.0, words.intro[1])?;
    content.restore_state();
    Ok(())
}

/// Draws one panel's heading, with the line under it that a panel may have.
fn panel_heading(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    title: &str,
    under: Option<&str>,
) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.2))?;
    text(content, font, 11.0, LEFT, y, title)?;
    if let Some(line) = under {
        content.set_fill(Color::Gray(0.45))?;
        text(content, font, 8.0, LEFT, y - 16.0, line)?;
    }
    content.restore_state();
    Ok(())
}

/// Draws the intent's parts, one to a line, as the file carries them.
fn intent_panel(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    intent: &OutputIntent,
    profile: &[u8],
) -> Result<(), Error> {
    let described = words.described(intent.profile().space());
    let values = [
        intent.identifier().to_owned(),
        intent.info().to_owned(),
        format!("{}{}{described}", profile.len(), words.profile_size),
        words.device(profile).to_owned(),
        format!("{CLAIM}{}", words.claim_note),
    ];

    let mut y = 672.0;
    for (label, value) in words.rows.iter().zip(&values) {
        content.save_state();
        content.set_fill(Color::Gray(0.45))?;
        text(content, font, 9.0, LEFT, y, label)?;
        content.set_fill(Color::Gray(0.15))?;
        text(content, font, 9.0, LEFT + VALUE_IN, y, value)?;
        content.restore_state();
        y -= 18.0;
    }
    Ok(())
}

/// Frames a swatch, so that one painted white is a swatch rather than a hole.
fn frame(content: &mut Content, x: f64, y: f64, width: f64, height: f64) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.75))?;
    content
        .rect(x - 1.0, y - 1.0, width + 2.0, height + 2.0)?
        .fill();
    content.restore_state();
    Ok(())
}

/// Draws the ramp: every channel of the profile at the same tint, from none of
/// it to all of it.
fn ramp(
    content: &mut Content,
    font: &FontHandle,
    space: &ColorSpaceHandle,
    width: usize,
) -> Result<(), Error> {
    let mut x = LEFT;
    for tint in TINTS {
        frame(content, x, RAMP_Y, RAMP_CELL, RAMP_HEIGHT)?;
        content.save_state();
        content.set_fill_space(space);
        content.set_fill_components(&vec![*tint; width])?;
        content.rect(x, RAMP_Y, RAMP_CELL, RAMP_HEIGHT)?.fill();
        content.restore_state();

        content.save_state();
        content.set_fill(Color::Gray(0.45))?;
        text(
            content,
            font,
            7.0,
            x,
            RAMP_Y - 12.0,
            &format!("{:.0}%", tint * 100.0),
        )?;
        content.restore_state();
        x += RAMP_CELL + RAMP_GAP;
    }
    Ok(())
}

/// Draws one swatch per channel, each at full strength with the others empty.
fn channel_swatches(
    content: &mut Content,
    font: &FontHandle,
    space: &ColorSpaceHandle,
    names: &[&str],
) -> Result<(), Error> {
    let mut x = LEFT;
    for (channel, name) in names.iter().enumerate() {
        let mut components = vec![0.0; names.len()];
        components[channel] = 1.0;

        frame(content, x, CHANNEL_Y, CHANNEL_CELL, CHANNEL_CELL)?;
        content.save_state();
        content.set_fill_space(space);
        content.set_fill_components(&components)?;
        content
            .rect(x, CHANNEL_Y, CHANNEL_CELL, CHANNEL_CELL)?
            .fill();
        content.restore_state();

        content.save_state();
        content.set_fill(Color::Gray(0.45))?;
        text(content, font, 8.0, x, CHANNEL_Y - 12.0, name)?;
        content.restore_state();
        x += CHANNEL_CELL + CHANNEL_GAP;
    }
    Ok(())
}

/// Draws the closing note under the swatches.
fn closing(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    text(content, font, 9.0, LEFT, 160.0, words.closing[0])?;
    text(content, font, 9.0, LEFT, 146.0, words.closing[1])?;
    content.restore_state();
    Ok(())
}

/// The profile the document is stated for, and what its condition is called:
/// the file named on the command line, or the one the library builds.
fn stated_for(path: Option<String>, words: &Words) -> Result<Stated, Box<dyn std::error::Error>> {
    match path {
        Some(path) => Ok(Stated {
            profile: fs::read(path)?,
            identifier: CUSTOM,
            info: words.custom_info.to_owned(),
        }),
        None => Ok(Stated {
            profile: icc::srgb(),
            identifier: BUILT_IN.0,
            info: BUILT_IN.1.to_owned(),
        }),
    }
}

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("intent")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);
    let stated = stated_for(args.next(), words)?;
    let bytes = &stated.profile;

    let described =
        icc::space(bytes).ok_or("the profile must describe a grey, RGB or CMYK space")?;
    let intent = OutputIntent::new(
        IccBased::new(bytes, described)?,
        stated.identifier,
        &stated.info,
    )?;
    let names = words.channels(described);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_conformance(PdfA::A3B);
    let mut facts = Metadata::default();
    facts.title = Some(words.title.to_owned());
    facts.producer = Some("hqf-pdf".to_owned());
    facts.created = Some(MADE.to_owned());
    doc.set_metadata(facts);
    doc.set_output_intent(intent.clone());

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    let space = doc.add_color_space(IccBased::new(bytes, described)?);

    let mut content = Content::new();
    heading(&mut content, &font, words)?;
    panel_heading(&mut content, &font, 700.0, words.intent_panel, None)?;
    intent_panel(&mut content, &font, words, &intent, bytes)?;

    panel_heading(
        &mut content,
        &font,
        566.0,
        words.profile_panel,
        Some(words.profile_note),
    )?;
    ramp(&mut content, &font, &space, names.len())?;

    panel_heading(&mut content, &font, 360.0, words.channel_panel, None)?;
    channel_swatches(&mut content, &font, &space, names)?;
    closing(&mut content, &font, words)?;

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

    let written = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &written)?;
    println!(
        "wrote {out}: {} bytes, stated for {} through a profile of {} bytes",
        written.len(),
        stated.identifier,
        bytes.len()
    );
    Ok(())
}

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

    use super::{CHANNEL_CELL, CHANNEL_GAP, CLAIM, LEFT, VALUE_IN, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way. Some row
    /// labels and ink names are the same word in two languages; the rest of the
    /// page is prose, and no two languages write one line of it alike.
    const SPARED: [&str; 12] = [
        "\"Condition\"",
        "\"Description\"",
        "\"Cyan\"",
        "\"Magenta\"",
        // Written the same way in German.
        r#""Profil""#,
        // Written the same way in Spanish.
        r#""Gris""#,
        // Written the same way in Italian.
        r#""Dispositivo""#,
        r#""Verde""#,
        // Written the same way in Portuguese.
        r#""Azul""#,
        r#""Ciano""#,
        r#""Perfil""#,
        // Written the same way in Dutch.
        r#""Claim""#,
    ];

    /// A4's width, and the room a line that stands over nothing has: it only
    /// has to stay on the paper.
    const PAGE_WIDTH: f64 = 595.276;
    /// See [`PAGE_WIDTH`].
    const PAPER: f64 = PAGE_WIDTH - LEFT;

    /// The longest a value of the intent panel may run: the paper, less the
    /// room the labels are given in front of it.
    const VALUE_ROOM: f64 = PAPER - VALUE_IN;

    /// The room a channel's name has under its swatch, which is the swatch and
    /// the gap to the one beside it.
    const CHANNEL_ROOM: f64 = CHANNEL_CELL + CHANNEL_GAP;

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

    /// Nothing on the page is broken to a width: a line longer than the room it
    /// is given runs over the swatch beside it, or off the sheet.
    #[test]
    fn every_language_writes_lines_no_wider_than_the_room_they_are_given() {
        let mut doc = Document::new();
        let font = Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
            .expect("the committed font parses");
        let text = doc.add_font(font);

        for (named, words) in WORDS {
            let code = named.code();
            // The size of the profile is a number the page reads off the file,
            // and the widest it can be is the widest profile a caller hands
            // over; what is measured here is the words around it.
            let rows = [
                format!("{}{}", words.profile_size, words.described[2]),
                format!("{CLAIM}{}", words.claim_note),
                words.custom_info.to_owned(),
            ];

            let lines = std::iter::once((15.0, words.title.to_owned(), PAPER))
                .chain(words.intro.map(|line| (10.0, line.to_owned(), PAPER)))
                .chain([
                    (11.0, words.intent_panel.to_owned(), PAPER),
                    (11.0, words.profile_panel.to_owned(), PAPER),
                    (8.0, words.profile_note.to_owned(), PAPER),
                    (11.0, words.channel_panel.to_owned(), PAPER),
                ])
                .chain(words.rows.map(|label| (9.0, label.to_owned(), VALUE_IN)))
                .chain(rows.map(|value| (9.0, value, VALUE_ROOM)))
                .chain(
                    words
                        .cmyk_channels
                        .map(|name| (8.0, name.to_owned(), CHANNEL_ROOM)),
                )
                .chain(
                    words
                        .rgb_channels
                        .map(|name| (8.0, name.to_owned(), CHANNEL_ROOM)),
                )
                .chain(
                    words
                        .gray_channels
                        .map(|name| (8.0, name.to_owned(), CHANNEL_ROOM)),
                )
                .chain(words.closing.map(|line| (9.0, line.to_owned(), PAPER)));

            for (size, line, room) in lines {
                let measured = text.measure(&line, size);
                assert!(
                    measured <= room,
                    "the {code} page draws {line:?} over {measured:.1} points, \
                     and it is given {room:.1}"
                );
            }
        }
    }
}