krilla 0.7.0

A high-level crate for creating PDF files.
Documentation
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
//! Exporting with a specific PDF conformance level.
//!
//! PDF defines a number of additional conformance levels that restrict the features of PDF that
//! can be used to a specific subset.
//!
//! You can use a [`Validator`] by creating a corresponding [`Configuration`]
//! you want to build the document with. There are three important aspects that play into this:
//! - krilla will internally write the file in a way that conforms to the given standard, i.e.
//!   by settings appropriate metadata. This happens under-the-hood and is completely abstracted
//!   away from the user.
//! - For aspects that are out of control of krilla and dependent on the input, krilla will perform
//!   a validation that the input is compatible with the standard. krilla will record all violations,
//!   and when calling `document.finish()`, in case there is at least one violation, krilla will
//!   return them as an error, instead of returning the finished document. See [`ValidationError`].
//! - Finally, some standards have requirements that cannot possibly be validated by krilla, as
//!   they are semantic in nature. It is upon you, as a user of that library, to ensure that those
//!   requirements are fulfilled. Therefore, while krilla tries to make it as easy as possible
//!   to generate compliant PDFs, it is still highly recommended that you familiarize yourself
//!   with the PDF specification as well as the specifications for the substandards. This is
//!   especially true for standards related to universal accessibility.
//!   
//!  You can find some requirements below **Requirements** for each [`Validator`].
//!
//! [`Configuration`]: crate::configure::Configuration

use std::collections::HashMap;
use std::fmt::Debug;

use pdf_writer::types::OutputIntentSubtype;
use pdf_writer::Finish;
use xmp_writer::XmpWriter;

use crate::color::separation::SeparationColorant;
use crate::color::separation::SeparationSpace;
use crate::color::RegularColor;
use crate::configure::PdfVersion;
use crate::interchange::embed::EmbedError;
use crate::surface::Location;
use crate::text::Font;
use crate::text::GlyphId;

/// An error that occurred during validation/
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ValidationError {
    /// There was a string that was longer than the maximum allowed length (32767).
    ///
    /// Can for example occur if you set a title or an author that is longer than
    /// the given length.
    TooLongString,
    /// There was a name that was longer than the maximum allowed length (127).
    ///
    /// Can for example occur if the font name is too long.
    TooLongName,
    /// There was an array that was longer than the maximum allowed length (8191).
    /// Can only occur for PDF 1.4.
    ///
    /// Can for example occur if a text too long was written.
    TooLongArray,
    /// There was a dictionary with more entries than the maximum allowed (4095).
    /// Can only occur for PDF 1.4.
    ///
    /// Can for example occur if too many annotations are added to a page.
    TooLongDictionary,
    /// There was a float that is higher than the maximum allowed (32767).
    /// Can only occur for PDF 1.4.
    TooLargeFloat,
    /// The PDF exceeds the upper limit for indirect objects (8388607).
    ///
    /// Occurs if the PDF is simply too long.
    TooManyIndirectObjects,
    /// The PDF contains a content stream that exceeds maximum allowed q/Q nesting level (28).
    ///
    /// Can only occur if the user stacks many clip paths.
    TooHighQNestingLevel,
    /// The PDF contains PostScript code, which is forbidden by some export formats.
    ///
    /// Occurs if a gradient with spread method `Repeat`/`Reflect` or a sweep gradient was used.
    ContainsPostScript(Option<Location>),
    /// No CMYK ICC profile was provided, even though one is necessary.
    ///
    /// Occurs if the export format requires a device-independent color representation,
    /// and a CMYK color was used in the document.
    MissingCMYKProfile,
    /// The same Separation colorant was used with multiple different fallback colors.
    ///
    /// Occurs if the user specified multiple Separation color spaces with the same colorant but a different fallback color.
    InconsistentSeparationFallback(SeparationColorant),
    /// The `.notdef` glyph was used, which is forbidden by some export formats.
    ///
    /// Can occur if a glyph could not be found in the font for a corresponding codepoint
    /// in the input text, or if it was explicitly mapped that way.
    ///
    /// The third argument contains the text range of the glyph.
    ContainsNotDefGlyph(Font, Option<Location>, String),
    /// A glyph was mapped to no codepoint at all, which is forbidden by some
    /// standards.
    NoCodepointMapping(Font, GlyphId, Option<Location>),
    /// A glyph was mapped either to the codepoint 0x0, 0xFEFF or 0xFFFE, which
    /// is forbidden by some standards.
    ///
    /// Can occur if those codepoints appeared in the input text, or were
    /// explicitly mapped to that glyph.
    InvalidCodepointMapping(Font, GlyphId, char, Option<Location>),
    /// A glyph was mapped to a codepoint in the Unicode private use area, which is forbidden
    /// by some standards, like for example PDF/A-2a.
    // Note that the standard doesn't explicitly forbid it, but instead requires an ActualText
    // attribute to be present. But we just completely forbid it, for simplicity.
    UnicodePrivateArea(Font, GlyphId, char, Option<Location>),
    /// A font has a license that requires explicit permission of the legal owner for embedding
    /// but the standard requires font programs to be legally embeddable for universal rendering.
    RestrictedLicense(Font),
    /// No document language was set via the metadata, even though it is required
    /// by the standard.
    NoDocumentLanguage,
    /// No title was provided for the document, even though it is required by
    /// the standard.
    NoDocumentTitle,
    /// A figure or formula is missing an alt text.
    MissingAltText(Option<Location>),
    /// A heading is missing a title.
    MissingHeadingTitle,
    /// The document does not contain an outline.
    MissingDocumentOutline,
    /// An annotation is missing an alt text.
    MissingAnnotationAltText(Option<Location>),
    /// The date of the document is missing.
    // We need this because for some standards we need to add the
    // xmp:History attribute.
    MissingDocumentDate,
    /// The PDF contains transparency, which is forbidden by some standards (e.g. PDF/A-1).
    Transparency(Option<Location>),
    /// The PDF contains an image with `interpolate` set to `true`.
    ImageInterpolation(Option<Location>),
    /// The PDF contains an embedded file.
    EmbeddedFile(EmbedError, Option<Location>),
    /// The PDF contains no tagging.
    MissingTagging,
    /// The PDF contains another embedded PDF.
    ///
    /// This is currently forbidden in validated export because we cannot manually verify
    /// whether the file actually fulfills all the criteria for the export mode.
    EmbeddedPDF(Option<Location>),
}

/// A validator for exporting PDF documents to a specific subset of PDF.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[allow(non_camel_case_types)]
pub enum Validator {
    /// A dummy validator, that does not perform any actual validation.
    ///
    /// **Requirements**: -
    #[default]
    None,
    /// The validator for the PDF/A-1a standard.
    ///
    /// **Requirements**:
    /// - All requirements of PDF/A-1b.
    /// - You need to follow all requirements outlined in the _Other Notes_ section of the
    ///   [`tagging`] module.
    /// - You need to follow all best practices when using [tags](`crate::interchange::tagging::Tag`), as outlined in the documentation
    ///   of each tag.
    /// - Artifacts such as page numbers, backgrounds, cut marks and color bars should be specified
    ///   correspondingly as artifacts.
    /// - Word boundaries need to be explicitly specified with a space. The same applies to words at
    ///   the end of a line that are not followed by punctuation.
    /// - To the fullest extent possible, the logical structure of the document should be encoded
    ///   correspondingly in the tag tree using appropriate grouping tags.
    /// - Language identifiers used must be valid according to RFC 3066.
    /// - You should provide an alternate text to span content tags, if applicable.
    /// - You should provide the expansion of abbreviations to span content tags, if applicable.
    ///
    /// [`tagging`]: crate::interchange::tagging
    A1_A,
    /// The validator for the PDF/A-1b standard.
    ///
    /// **Requirements**: -
    A1_B,
    /// The validator for the PDF/A-2a standard.
    ///
    /// **Requirements**:
    /// - All requirements of PDF/A-2b.
    /// - You need to follow all requirements outlined in the _Other Notes_ section of the
    ///   [`tagging`] module.
    /// - You need to follow all best practices when using [tags](`crate::interchange::tagging::Tag`), as outlined in the documentation
    ///   of each tag.
    /// - Artifacts such as page numbers, backgrounds, cut marks and color bars should be specified
    ///   correspondingly as artifacts.
    /// - Word boundaries need to be explicitly specified with a space. The same applies to words at
    ///   the end of a line that are not followed by punctuation.
    /// - To the fullest extent possible, the logical structure of the document should be encoded
    ///   correspondingly in the tag tree using appropriate grouping tags.
    /// - Language identifiers used must be valid according to RFC 3066.
    /// - You should provide an alternate text to span content tags, if applicable.
    /// - You should provide the expansion of abbreviations to span content tags, if applicable.
    ///
    /// [`tagging`]: crate::interchange::tagging
    A2_A,
    /// The validator for the PDF/A-2b standard.
    ///
    /// **Requirements**:
    /// - You should only use fonts that are legally embeddable in a file for unlimited,
    ///   universal rendering.
    A2_B,
    /// The validator for the PDF/A-2u standard.
    ///
    /// **Requirements**:
    /// - All requirements of PDF/A-2b
    A2_U,
    /// The validator for the PDF/A-3a standard.
    ///
    /// **Requirements**:
    /// - All requirements of PDF/A-2a
    A3_A,
    /// The validator for the PDF/A-3b standard.
    ///
    /// **Requirements**:
    /// - All requirements of PDF/A-2b
    A3_B,
    /// The validator for the PDF/A-3u standard.
    ///
    /// **Requirements**:
    /// - All requirements of PDF/A-2b
    A3_U,
    /// The validator for the PDF/UA-1 standard.
    ///
    /// **Requirements**:
    ///
    /// General:
    /// - All real content should be tagged accordingly.
    /// - All artifacts should be marked accordingly.
    /// - The tag tree should reflect the logical reading order of the
    ///   document.
    /// - Information should not be conveyed by contrast, color, format
    ///   or layout.
    /// - All "best practice" notes in [`TagKind`] need to be complied with.
    ///
    /// Text:
    /// - You should make use of the `Alt`, `ActualText`, `Lang` and `Expansion` attributes
    ///   whenever possible.
    /// - Usually, you can provide an empty string as `Lang` to indicate that a language is unknown.
    ///   You should not do that in PDF/UA.
    /// - Stretchable characters (such as brackets, which often consist of several glyphs)
    ///   should be marked accordingly with `ActualText`.
    ///
    ///  Graphics:
    /// - Graphics should be tagged as figures (unless they are an artifact).
    /// - Graphics need to be followed by a caption.
    /// - Graphics that possess semantic values only in combination with other graphics
    ///   should be tagged with a single Figure tag for each figure.
    /// - If a more accessible representation exists, it should be used over graphics.
    ///
    /// Headings:
    /// - Headings should be tagged as such.
    /// - For not strongly structured documents, H1 should be the first
    ///   heading.
    ///
    /// Tables:
    /// - Tables should include headers and be tagged accordingly.
    /// - Tables should only be used to represent content within logical row/column relationship.
    ///
    /// Lists:
    /// - List items should be tagged with Li tags, if necessary also with
    ///   Lbl and LBody tags.
    /// - Lists should only be used when the content is intended to be read
    ///   as a list.
    ///
    /// Mathematical expressions:
    /// - All mathematical expressions should be enclosed with
    ///   a `Formula` tag.
    ///
    /// Headers and footers:
    /// - Headers and footers should be marked as corresponding
    ///   artifacts.
    ///
    /// Notes and references:
    /// - Footnotes, endnotes, note labels and references should be
    ///   tagged accordingly and use tagged annotations.
    /// - Footnotes and end notes should use the `Note` tag.
    ///
    /// Navigation:
    /// - The document must contain an outline, and it should reflect
    ///   the reading order of the document.
    /// - Page labels should be semantically appropriate.
    ///
    /// Annotations:
    /// - Annotations should be present in the tag tree in the correct
    ///   reading order.
    ///
    /// Fonts:
    /// - You should only use fonts that are legally embeddable in a file for unlimited,
    ///   universal rendering.
    ///
    /// [`TagKind`]: crate::interchange::tagging::TagKind
    UA1,
    /// The validator for the PDF/A-4 standard.
    ///
    /// **Requirements**:
    /// - While not required, it's recommended to enable tagging.
    A4,
    /// The validator for the PDF/A-4f standard.
    ///
    /// **Requirements**:
    /// - All requirements of PDF/A-4
    A4F,
    /// The validator for the PDF/A-4e standard.
    ///
    /// **Requirements**:
    /// - All requirements of PDF/A-4
    A4E,
}

impl Validator {
    pub(crate) fn prohibits(&self, validation_error: &ValidationError) -> bool {
        match self {
            Validator::None => false,
            Validator::A1_A | Validator::A1_B => match validation_error {
                ValidationError::TooLongString => true,
                ValidationError::TooLongName => true,
                ValidationError::TooLongArray => true,
                ValidationError::TooLargeFloat => true,
                ValidationError::TooLongDictionary => true,
                ValidationError::TooManyIndirectObjects => true,
                ValidationError::TooHighQNestingLevel => true,
                ValidationError::ContainsPostScript(_) => true,
                ValidationError::MissingCMYKProfile => true,
                ValidationError::InconsistentSeparationFallback(_) => false,
                ValidationError::ContainsNotDefGlyph(_, _, _) => self.requires_codepoint_mappings(),
                ValidationError::NoCodepointMapping(_, _, _) => self.requires_codepoint_mappings(),
                ValidationError::InvalidCodepointMapping(_, _, _, _) => false,
                ValidationError::UnicodePrivateArea(_, _, _, _) => false,
                ValidationError::RestrictedLicense(_) => true,
                ValidationError::NoDocumentLanguage => *self == Validator::A1_A,
                ValidationError::NoDocumentTitle => false,
                ValidationError::MissingAltText(_) => *self == Validator::A1_A,
                ValidationError::MissingHeadingTitle => false,
                ValidationError::MissingDocumentOutline => false,
                ValidationError::MissingAnnotationAltText(_) => *self == Validator::A1_A,
                ValidationError::Transparency(_) => true,
                ValidationError::ImageInterpolation(_) => true,
                // PDF/A-1 doesn't strictly forbid, but it disallows the EF key,
                // which we always insert. So we just forbid it overall.
                ValidationError::EmbeddedFile(e, _) => match e {
                    EmbedError::Existence => true,
                    // Since existence is forbidden in the first place,
                    // we can just set the others to `false` to prevent unnecessary
                    // validation errors.
                    EmbedError::MissingDate => false,
                    EmbedError::MissingDescription => false,
                    EmbedError::MissingMimeType => false,
                },
                ValidationError::MissingTagging => *self == Validator::A1_A,
                ValidationError::MissingDocumentDate => true,
                ValidationError::EmbeddedPDF(_) => true,
            },
            Validator::A2_A | Validator::A2_B | Validator::A2_U => match validation_error {
                ValidationError::TooLongString => true,
                ValidationError::TooLongName => true,
                ValidationError::TooLargeFloat => false,
                ValidationError::TooLongArray => false,
                ValidationError::TooLongDictionary => false,
                ValidationError::TooManyIndirectObjects => true,
                ValidationError::TooHighQNestingLevel => true,
                ValidationError::ContainsPostScript(_) => true,
                ValidationError::MissingCMYKProfile => true,
                ValidationError::InconsistentSeparationFallback(_) => true,
                ValidationError::ContainsNotDefGlyph(_, _, _) => true,
                ValidationError::NoCodepointMapping(_, _, _)
                | ValidationError::InvalidCodepointMapping(_, _, _, _) => {
                    self.requires_codepoint_mappings()
                }
                ValidationError::UnicodePrivateArea(_, _, _, _) => *self == Validator::A2_A,
                ValidationError::RestrictedLicense(_) => true,
                ValidationError::NoDocumentLanguage => *self == Validator::A2_A,
                ValidationError::NoDocumentTitle => false,
                ValidationError::MissingAltText(_) => *self == Validator::A2_A,
                ValidationError::MissingHeadingTitle => false,
                ValidationError::MissingDocumentOutline => false,
                ValidationError::MissingAnnotationAltText(_) => *self == Validator::A2_A,
                ValidationError::Transparency(_) => false,
                ValidationError::ImageInterpolation(_) => true,
                // Also not strictly forbidden, but we can't ensure that it is PDF/A-2 compliant,
                // so we just forbid it completely.
                ValidationError::EmbeddedFile(e, _) => match e {
                    EmbedError::Existence => true,
                    // Since existence is forbidden in the first place,
                    // we can just set the others to `false` to prevent unnecessary
                    // validation errors.
                    EmbedError::MissingDate => false,
                    EmbedError::MissingDescription => false,
                    EmbedError::MissingMimeType => false,
                },
                ValidationError::MissingTagging => *self == Validator::A2_A,
                ValidationError::MissingDocumentDate => true,
                ValidationError::EmbeddedPDF(_) => true,
            },
            Validator::A3_A | Validator::A3_B | Validator::A3_U => match validation_error {
                ValidationError::TooLongString => true,
                ValidationError::TooLongName => true,
                ValidationError::TooLargeFloat => false,
                ValidationError::TooLongArray => false,
                ValidationError::TooLongDictionary => false,
                ValidationError::TooManyIndirectObjects => true,
                ValidationError::TooHighQNestingLevel => true,
                ValidationError::ContainsPostScript(_) => true,
                ValidationError::MissingCMYKProfile => true,
                ValidationError::InconsistentSeparationFallback(_) => true,
                ValidationError::ContainsNotDefGlyph(_, _, _) => true,
                ValidationError::NoCodepointMapping(_, _, _)
                | ValidationError::InvalidCodepointMapping(_, _, _, _) => {
                    self.requires_codepoint_mappings()
                }
                ValidationError::UnicodePrivateArea(_, _, _, _) => *self == Validator::A3_A,
                ValidationError::RestrictedLicense(_) => true,
                ValidationError::NoDocumentLanguage => *self == Validator::A3_A,
                ValidationError::NoDocumentTitle => false,
                ValidationError::MissingAltText(_) => *self == Validator::A3_A,
                ValidationError::MissingHeadingTitle => false,
                ValidationError::MissingDocumentOutline => false,
                ValidationError::MissingAnnotationAltText(_) => *self == Validator::A3_A,
                ValidationError::Transparency(_) => false,
                ValidationError::ImageInterpolation(_) => true,
                ValidationError::EmbeddedFile(er, _) => match er {
                    EmbedError::Existence => false,
                    EmbedError::MissingDate => true,
                    EmbedError::MissingDescription => true,
                    EmbedError::MissingMimeType => true,
                },
                ValidationError::MissingTagging => *self == Validator::A3_A,
                ValidationError::MissingDocumentDate => true,
                ValidationError::EmbeddedPDF(_) => true,
            },
            Validator::A4 | Validator::A4F | Validator::A4E => match validation_error {
                ValidationError::TooLongString => false,
                ValidationError::TooLongName => false,
                ValidationError::TooLongArray => false,
                ValidationError::TooLongDictionary => false,
                ValidationError::TooLargeFloat => false,
                ValidationError::TooManyIndirectObjects => false,
                ValidationError::TooHighQNestingLevel => false,
                ValidationError::ContainsPostScript(_) => false,
                ValidationError::MissingCMYKProfile => true,
                ValidationError::InconsistentSeparationFallback(_) => true,
                ValidationError::ContainsNotDefGlyph(_, _, _) => true,
                ValidationError::NoCodepointMapping(_, _, _)
                | ValidationError::InvalidCodepointMapping(_, _, _, _) => true,
                // Not strictly forbidden if we surround with actual text, but
                // easier to just forbid it.
                ValidationError::UnicodePrivateArea(_, _, _, _) => true,
                ValidationError::RestrictedLicense(_) => true,
                ValidationError::NoDocumentLanguage => false,
                ValidationError::NoDocumentTitle => false,
                ValidationError::MissingAltText(_) => false,
                ValidationError::MissingHeadingTitle => false,
                ValidationError::MissingDocumentOutline => false,
                ValidationError::MissingAnnotationAltText(_) => false,
                ValidationError::Transparency(_) => false,
                ValidationError::ImageInterpolation(_) => true,
                ValidationError::EmbeddedFile(e, _) => match e {
                    EmbedError::Existence => matches!(self, Validator::A4),
                    // Since existence is forbidden in the first place for A4,
                    // we can just set the others to `false` to prevent
                    // unnecessary validation errors.
                    EmbedError::MissingDate => false,
                    EmbedError::MissingDescription => {
                        matches!(self, Validator::A4E | Validator::A4F)
                    }
                    EmbedError::MissingMimeType => false,
                },
                // Only recommended, not required.
                ValidationError::MissingTagging => false,
                ValidationError::MissingDocumentDate => true,
                ValidationError::EmbeddedPDF(_) => true,
            },
            Validator::UA1 => match validation_error {
                ValidationError::TooLongString => false,
                ValidationError::TooLargeFloat => false,
                ValidationError::TooLongName => false,
                ValidationError::TooLongArray => false,
                ValidationError::TooLongDictionary => false,
                ValidationError::TooManyIndirectObjects => false,
                ValidationError::TooHighQNestingLevel => false,
                ValidationError::ContainsPostScript(_) => false,
                ValidationError::MissingCMYKProfile => false,
                ValidationError::InconsistentSeparationFallback(_) => false,
                ValidationError::ContainsNotDefGlyph(_, _, _) => true,
                ValidationError::NoCodepointMapping(_, _, _)
                | ValidationError::InvalidCodepointMapping(_, _, _, _) => {
                    self.requires_codepoint_mappings()
                }
                ValidationError::UnicodePrivateArea(_, _, _, _) => false,
                ValidationError::RestrictedLicense(_) => true,
                ValidationError::NoDocumentLanguage => false,
                ValidationError::NoDocumentTitle => true,
                ValidationError::MissingAltText(_) => true,
                ValidationError::MissingHeadingTitle => true,
                ValidationError::MissingDocumentOutline => true,
                ValidationError::MissingAnnotationAltText(_) => true,
                ValidationError::Transparency(_) => false,
                ValidationError::ImageInterpolation(_) => false,
                ValidationError::EmbeddedFile(er, _) => match er {
                    EmbedError::Existence => false,
                    EmbedError::MissingDate => false,
                    EmbedError::MissingDescription => true,
                    EmbedError::MissingMimeType => false,
                },
                ValidationError::MissingTagging => true,
                ValidationError::MissingDocumentDate => false,
                ValidationError::EmbeddedPDF(_) => true,
            },
        }
    }

    /// Check whether the validator is compatible with a specific pdf version.
    pub fn compatible_with_version(&self, pdf_version: PdfVersion) -> bool {
        match self {
            Validator::None => true,
            Validator::A1_A | Validator::A1_B => pdf_version <= PdfVersion::Pdf14,
            Validator::A2_A | Validator::A2_B | Validator::A2_U => pdf_version <= PdfVersion::Pdf17,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => pdf_version <= PdfVersion::Pdf17,
            // It can be any 2.x version, but we're not there yet.
            Validator::A4 | Validator::A4F | Validator::A4E => pdf_version == PdfVersion::Pdf20,
            Validator::UA1 => pdf_version <= PdfVersion::Pdf17,
        }
    }

    /// Get the recommended PDF version of a validator.
    pub fn recommended_version(&self) -> PdfVersion {
        match self {
            Validator::None => PdfVersion::Pdf17,
            Validator::A1_A | Validator::A1_B => PdfVersion::Pdf14,
            Validator::A2_A | Validator::A2_B | Validator::A2_U => PdfVersion::Pdf17,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => PdfVersion::Pdf17,
            Validator::A4 | Validator::A4F | Validator::A4E => PdfVersion::Pdf20,
            Validator::UA1 => PdfVersion::Pdf17,
        }
    }

    fn is_pdf_a(&self) -> bool {
        matches!(
            self,
            Validator::A1_A
                | Validator::A1_B
                | Validator::A2_A
                | Validator::A2_B
                | Validator::A2_U
                | Validator::A3_A
                | Validator::A3_B
                | Validator::A3_U
                | Validator::A4
                | Validator::A4F
                | Validator::A4E
        )
    }

    pub(crate) fn write_xmp(&self, xmp: &mut XmpWriter) {
        // TODO: Also needed for PDF/UA?
        if self.is_pdf_a() {
            let mut extension_schemas = xmp.extension_schemas();
            extension_schemas
                .xmp_media_management()
                .properties()
                .describe_instance_id();
            extension_schemas.pdf().properties().describe_all();
            extension_schemas.finish();
        }

        match self {
            Validator::None => {}
            Validator::A1_A => {
                xmp.pdfa_part(1);
                xmp.pdfa_conformance("A");
            }
            Validator::A1_B => {
                xmp.pdfa_part(1);
                xmp.pdfa_conformance("B");
            }
            Validator::A2_A => {
                xmp.pdfa_part(2);
                xmp.pdfa_conformance("A");
            }
            Validator::A2_B => {
                xmp.pdfa_part(2);
                xmp.pdfa_conformance("B");
            }
            Validator::A2_U => {
                xmp.pdfa_part(2);
                xmp.pdfa_conformance("U");
            }
            Validator::A3_A => {
                xmp.pdfa_part(3);
                xmp.pdfa_conformance("A");
            }
            Validator::A3_B => {
                xmp.pdfa_part(3);
                xmp.pdfa_conformance("B");
            }
            Validator::A3_U => {
                xmp.pdfa_part(3);
                xmp.pdfa_conformance("U");
            }
            Validator::A4 => {
                xmp.pdfa_part(4);
                xmp.pdfa_rev(2020);
            }
            Validator::A4F => {
                xmp.pdfa_part(4);
                xmp.pdfa_rev(2020);
                xmp.pdfa_conformance("F");
            }
            Validator::A4E => {
                xmp.pdfa_part(4);
                xmp.pdfa_rev(2020);
                xmp.pdfa_conformance("E");
            }
            Validator::UA1 => {
                xmp.pdfua_part(1);
            }
        }
    }

    pub(crate) fn requires_codepoint_mappings(&self) -> bool {
        match self {
            Validator::None => false,
            Validator::A1_A | Validator::A1_B => *self != Validator::A1_B,
            Validator::A2_A | Validator::A2_B | Validator::A2_U => *self != Validator::A2_B,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => *self != Validator::A3_B,
            Validator::A4 | Validator::A4F | Validator::A4E => true,
            Validator::UA1 => true,
        }
    }

    pub(crate) fn requires_display_doc_title(&self) -> bool {
        match self {
            Validator::None => false,
            Validator::A1_A | Validator::A1_B => false,
            Validator::A2_A | Validator::A2_B | Validator::A2_U => false,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => false,
            Validator::A4 | Validator::A4F | Validator::A4E => false,
            Validator::UA1 => true,
        }
    }

    pub(crate) fn requires_no_device_cs(&self) -> bool {
        match self {
            Validator::None => false,
            Validator::A1_A | Validator::A1_B => true,
            Validator::A2_A | Validator::A2_B | Validator::A2_U => true,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => true,
            Validator::A4 | Validator::A4F | Validator::A4E => true,
            Validator::UA1 => false,
        }
    }

    pub(crate) fn requires_annotation_flags(&self) -> bool {
        match self {
            Validator::None | Validator::UA1 => false,
            Validator::A1_A | Validator::A1_B => true,
            Validator::A2_A | Validator::A2_B | Validator::A2_U => true,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => true,
            Validator::A4 | Validator::A4F | Validator::A4E => true,
        }
    }

    pub(crate) fn requires_tagging(&self) -> bool {
        match self {
            Validator::None => false,
            Validator::A1_A => true,
            Validator::A1_B => false,
            Validator::A2_A => true,
            Validator::A2_B | Validator::A2_U => false,
            Validator::A3_A => true,
            Validator::A3_B | Validator::A3_U => false,
            Validator::A4 | Validator::A4F | Validator::A4E => false,
            Validator::UA1 => true,
        }
    }

    pub(crate) fn xmp_metadata(&self) -> bool {
        match self {
            Validator::None => false,
            Validator::A1_A | Validator::A1_B => true,
            Validator::A2_A | Validator::A2_B | Validator::A2_U => true,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => true,
            Validator::A4 | Validator::A4F | Validator::A4E => true,
            Validator::UA1 => true,
        }
    }

    pub(crate) fn requires_binary_header(&self) -> bool {
        match self {
            Validator::None => false,
            Validator::A1_A | Validator::A1_B => true,
            Validator::A2_A | Validator::A2_B | Validator::A2_U => true,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => true,
            Validator::A4 | Validator::A4F | Validator::A4E => true,
            Validator::UA1 => false,
        }
    }

    pub(crate) fn requires_file_provenance_information(&self) -> bool {
        match self {
            Validator::None => false,
            Validator::A1_A | Validator::A1_B => true,
            Validator::A2_A | Validator::A2_B | Validator::A2_U => true,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => true,
            Validator::A4 | Validator::A4F | Validator::A4E => true,
            Validator::UA1 => false,
        }
    }

    pub(crate) fn prohibits_instance_id_in_xmp_metadata(&self) -> bool {
        match self {
            Validator::None => false,
            Validator::A1_A | Validator::A1_B => true,
            Validator::A2_A | Validator::A2_B | Validator::A2_U => false,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => false,
            Validator::A4 | Validator::A4F | Validator::A4E => false,
            Validator::UA1 => false,
        }
    }

    pub(crate) fn output_intent(&self) -> Option<OutputIntentSubtype<'_>> {
        match self {
            Validator::None => None,
            Validator::A1_A | Validator::A1_B => Some(OutputIntentSubtype::PDFA),
            Validator::A2_A | Validator::A2_B | Validator::A2_U => Some(OutputIntentSubtype::PDFA),
            Validator::A3_A | Validator::A3_B | Validator::A3_U => Some(OutputIntentSubtype::PDFA),
            Validator::A4 | Validator::A4F | Validator::A4E => Some(OutputIntentSubtype::PDFA),
            Validator::UA1 => None,
        }
    }

    pub(crate) fn allows_info_dict(&self) -> bool {
        match self {
            Validator::None
            | Validator::A1_A
            | Validator::A1_B
            | Validator::A2_A
            | Validator::A2_B
            | Validator::A2_U
            | Validator::A3_A
            | Validator::A3_B
            | Validator::A3_U
            | Validator::UA1 => true,
            Validator::A4 | Validator::A4F | Validator::A4E => false,
        }
    }

    pub(crate) fn write_embedded_files(&self, is_empty: bool) -> bool {
        match self {
            Validator::None
            | Validator::A1_A
            | Validator::A1_B
            | Validator::A2_A
            | Validator::A2_B
            | Validator::A2_U
            | Validator::A3_A
            | Validator::A3_B
            | Validator::A3_U
            | Validator::A4
            | Validator::A4E
            | Validator::UA1 => !is_empty,
            // For this one we always need to write an `EmbeddedFiles` entry,
            // even if empty.
            Validator::A4F => true,
        }
    }

    pub(crate) fn allows_associated_files(&self) -> bool {
        match self {
            // PDF 2.0 _does_ support associated files. However, in this case the document has to
            // provide a modification date, since it's a required field. Therefore, it's easier to
            // just use the associated files feature, apart from PDF/A-3.
            Validator::None => false,
            Validator::A3_A | Validator::A3_B | Validator::A3_U => true,
            Validator::A4 | Validator::A4F | Validator::A4E => true,
            Validator::A1_A
            | Validator::A1_B
            | Validator::A2_A
            | Validator::A2_B
            | Validator::A2_U
            | Validator::UA1 => false,
        }
    }

    /// The string representation of the validator.
    pub fn as_str(self) -> &'static str {
        match self {
            Validator::None => "None",
            Validator::A1_A => "PDF/A-1a",
            Validator::A1_B => "PDF/A-1b",
            Validator::A2_A => "PDF/A-2a",
            Validator::A2_B => "PDF/A-2b",
            Validator::A2_U => "PDF/A-2u",
            Validator::A3_A => "PDF/A-3a",
            Validator::A3_B => "PDF/A-3b",
            Validator::A3_U => "PDF/A-3u",
            Validator::A4 => "PDF/A-4",
            Validator::A4F => "PDF/A-4f",
            Validator::A4E => "PDF/A-4e",
            Validator::UA1 => "PDF/UA-1",
        }
    }
}

#[derive(Debug, Default, Clone, PartialEq)]
pub(crate) struct ValidationStore {
    /// Maps from the name of a Separation colorant to a hash of its fallback
    /// color. Used to track that a name is only ever matched with a single
    /// fallback color. Since Krilla manages the `tintTransform` functions,
    /// those are always equivalent.
    separation_fallback_map: HashMap<SeparationColorant, RegularColor>,
}

impl ValidationStore {
    pub(crate) fn new() -> Self {
        Default::default()
    }

    /// Register a colorant and its fallback and raise an error if it already
    /// exists.
    pub(crate) fn validate_separation(
        &mut self,
        separation: &SeparationSpace,
    ) -> Result<(), ValidationError> {
        if self
            .separation_fallback_map
            .entry(separation.colorant.clone())
            .or_insert(separation.fallback)
            == &separation.fallback
        {
            Ok(())
        } else {
            Err(ValidationError::InconsistentSeparationFallback(
                separation.colorant.clone(),
            ))
        }
    }
}