Skip to main content

laminapdf_syntax/generated/
codes.rs

1// @generated by cargo xtask gen codes. DO NOT EDIT.
2//! Every error and warning code the Rust crates and the WASM bindings raise, from
3//! `fixtures/codes.json` (ADR 0026 §3): kind, summary, hint and `docsUrl` per code.
4//! `cargo xtask check docs` fails when this file is stale.
5#![allow(
6    clippy::too_many_lines,
7    clippy::match_same_arms,
8    clippy::doc_markdown,
9    reason = "generated: one match arm per code; summaries are codes.json text"
10)]
11
12use crate::ErrorKind;
13
14/// The base of every `docsUrl` (ADR 0026 §6): `DOCS_URL_BASE` + code + `DOCS_URL_SUFFIX`.
15///
16/// Added in 0.2.0.
17pub const DOCS_URL_BASE: &str = "https://docs.laminapdf.com/reference/codes/";
18
19/// The suffix of every `docsUrl` (ADR 0026 §6).
20///
21/// Added in 0.2.0.
22pub const DOCS_URL_SUFFIX: &str = "/";
23
24/// Whether two byte strings are equal, in a `const fn`.
25const fn bytes_eq(a: &[u8], b: &[u8]) -> bool {
26    if a.len() != b.len() {
27        return false;
28    }
29    let (mut a, mut b) = (a, b);
30    while let ([x, a_rest @ ..], [y, b_rest @ ..]) = (a, b) {
31        if *x != *y {
32            return false;
33        }
34        a = a_rest;
35        b = b_rest;
36    }
37    true
38}
39
40/// Every error code lamina's Rust crates and its WASM binding raise (the codes only
41/// `@laminapdf/sdk` raises are not here), in `codes.json` order.
42///
43/// Added in 0.2.0.
44#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
45#[non_exhaustive]
46pub enum ErrorCode {
47    /// `not-pdf`: the input does not look like a PDF at all.
48    NotPdf,
49    /// `missing-root`: no document catalog (/Root) was found, even after repair.
50    MissingRoot,
51    /// `reference-cycle`: a reference chain or the page tree loops back on itself.
52    ReferenceCycle,
53    /// `limit-exceeded`: a hard Limits value was exceeded.
54    LimitExceeded,
55    /// `strict`: strict mode refused something the tolerant reader would have repaired.
56    Strict,
57    /// `data-pending`: the ByteSource has not fetched the byte ranges the call needs yet.
58    DataPending,
59    /// `source`: the ByteSource failed to read.
60    Source,
61    /// `type`: an object had a different type than the structure requires.
62    Type,
63    /// `invalid-structure`: an object stream, xref section or filter parameter was malformed.
64    InvalidStructure,
65    /// `unset-object`: a writer object number was reserved but never given a value.
66    UnsetObject,
67    /// `repaired-base`: an incremental update was requested for a document whose xref needed repair.
68    RepairedBase,
69    /// `encrypted-base`: a save of an encrypted document was requested.
70    EncryptedBase,
71    /// `password-required`: the document is encrypted with a user password and none was given.
72    PasswordRequired,
73    /// `wrong-password`: the given password is neither the user nor the owner password.
74    WrongPassword,
75    /// `unsupported-security-handler`: the document uses a security handler Lamina PDF cannot decrypt.
76    UnsupportedSecurityHandler,
77    /// `unexpected-eof`: the input ended before a complete token or object was read.
78    UnexpectedEof,
79    /// `syntax`: a token or structure did not match the PDF grammar.
80    Syntax,
81    /// `unsupported-filter`: a stream uses a filter Lamina PDF does not implement.
82    UnsupportedFilter,
83    /// `decompress`: compressed stream data was corrupt.
84    Decompress,
85    /// `nested-transaction`: a transaction was started, or undo or redo called, while one is open.
86    NestedTransaction,
87    /// `no-transaction`: apply, commit or rollback was called without an open transaction.
88    NoTransaction,
89    /// `unknown-page`: an op names a page the document does not have.
90    UnknownPage,
91    /// `direct-page`: the page is a direct dictionary, which ops cannot edit yet.
92    DirectPage,
93    /// `unsupported-version`: an op log has a schema version this reader does not know.
94    UnsupportedVersion,
95    /// `invalid-op-log`: an op log does not parse: an unknown op or field, a bad value, or not JSON.
96    InvalidOpLog,
97    /// `saved-not-rebased`: the document was saved to a sink Lamina PDF cannot read back and waits for rebase.
98    SavedNotRebased,
99    /// `no-pending-save`: rebase was called without a save waiting for it.
100    NoPendingSave,
101    /// `malformed-xmp`: a metadata edit would replace the document's XMP packet, which can't be read, losing what it holds.
102    MalformedXmp,
103    /// `unknown-source`: an op or a call names a source document that was not added to the session.
104    UnknownSource,
105    /// `sink`: the sink failed to take the bytes or could not give them back.
106    Sink,
107    /// `not-rebased`: the output was written, but rebasing the document onto it failed.
108    NotRebased,
109    /// `sink-not-empty`: the sink already held bytes before the save started.
110    SinkNotEmpty,
111    /// `would-invalidate-signatures`: the save would break one or more signatures.
112    WouldInvalidateSignatures,
113    /// `requires-rewrite`: an incremental save was requested but only a full rewrite is safe.
114    RequiresRewrite,
115    /// `invalid-font`: font bytes could not be read as a font.
116    InvalidFont,
117    /// `collection-index`: a font collection member past the end of the collection was asked for.
118    CollectionIndex,
119    /// `unknown-axis`: an instance was asked for on a variation axis the font does not have.
120    UnknownAxis,
121    /// `font-not-embeddable`: the font's OS/2 fsType forbids embedding.
122    FontNotEmbeddable,
123    /// `missing-glyph`: the font has no glyph for a character of the text.
124    MissingGlyph,
125    /// `glyph-out-of-range`: a glyph ID at or past the font's glyph count was used.
126    GlyphOutOfRange,
127    /// `unknown-font`: a FontKey was used with a registry that did not hand it out.
128    UnknownFont,
129    /// `subset-failed`: subsetting a font failed.
130    SubsetFailed,
131    /// `invalid-axis-value`: a variation axis value was NaN or infinite.
132    InvalidAxisValue,
133    /// `wrong-document`: finish_fonts was given a document the registry did not reserve its fonts in.
134    WrongDocument,
135    /// `invalid-feature`: an OpenType feature setting did not parse.
136    InvalidFeature,
137    /// `invalid-text-range`: a byte range was out of bounds or not on character boundaries of the text.
138    InvalidTextRange,
139    /// `invalid-spans`: the styled spans given for a paragraph do not cover its text once, in order.
140    InvalidSpans,
141    /// `unsupported-layout-option`: a layout option that is not implemented yet was asked for.
142    UnsupportedLayoutOption,
143    /// `font-mismatch`: a shaped run was given with a font key for a different font than it was shaped with.
144    FontMismatch,
145    /// `encoding-full`: a standard 14 font has no free one-byte code left for another glyph.
146    EncodingFull,
147    /// `font-not-shapable`: a standard 14 font was given to shaping or layout, which need a font program.
148    FontNotShapable,
149    /// `invalid-image`: image bytes are not a readable image of the format they were given as.
150    InvalidImage,
151    /// `unsupported-image`: the image uses a feature that PDF or Lamina PDF does not support.
152    UnsupportedImage,
153    /// `image-too-large`: the image needs more memory than the builder allows (a decoded PNG over 256 MiB, or raw dimensions whose size overflows).
154    ImageTooLarge,
155    /// `image-data-length`: raw image samples are not width x height x channels bytes long.
156    ImageDataLength,
157    /// `invalid-icc-profile`: the bytes are not a usable ICC profile.
158    InvalidIccProfile,
159    /// `color-components`: a colour has the wrong number of components for its colour space.
160    ColorComponents,
161    /// `invalid-color`: a colour string is not of the form #rgb or #rrggbb.
162    InvalidColor,
163    /// `invalid-geometry`: a page size, box, /UserUnit, drawing value (coordinate, matrix, line width, dash, miter limit) or image size is not usable.
164    InvalidGeometry,
165    /// `text-overflow`: a text box's lines don't all fit its height and its options asked for an error.
166    TextOverflow,
167    /// `page-index-out-of-range`: a link, outline item or destination names a page index the document doesn't have.
168    PageIndexOutOfRange,
169    /// `unknown-destination`: a link or outline item names a destination that was never defined.
170    UnknownDestination,
171    /// `invalid-page-labels`: page label ranges that don't start at page 0, don't increase, start past the last page or number from 0.
172    InvalidPageLabels,
173    /// `tag-element-not-open`: a structure element resumed or closed isn't open.
174    TagElementNotOpen,
175    /// `tag-element-unclosed`: structure elements opened across pages were never closed.
176    TagElementUnclosed,
177    /// `profile-version-conflict`: the PDF version asked for is one the profile doesn't allow (PDF/UA-1, PDF/A-2 and PDF/A-3 are based on PDF 1.7).
178    ProfileVersionConflict,
179    /// `missing-title`: PDF/UA-1 needs a document title, and the metadata gives none.
180    MissingTitle,
181    /// `missing-lang`: PDF/UA-1 needs the document's natural language, and none was set.
182    MissingLang,
183    /// `missing-alt-text`: a Figure or Formula has no alternate text (/Alt or /ActualText), which PDF/UA-1 requires.
184    MissingAltText,
185    /// `untagged-content`: content was drawn outside every structure element and artifact, which PDF/UA-1 forbids.
186    UntaggedContent,
187    /// `heading-level-skipped`: a heading skips a level (the first is not H1, or an H3 follows an H1), which PDF/UA-1 forbids.
188    HeadingLevelSkipped,
189    /// `unnumbered-heading-misused`: an unnumbered H heading shares its parent with another H, or the document also uses H1-H6, which PDF/UA-1 forbids.
190    UnnumberedHeadingMisused,
191    /// `invalid-structure-nesting`: a table or list element sits in a parent its type doesn't allow (a TD outside a TR, a P directly in a Table).
192    InvalidStructureNesting,
193    /// `link-without-structure`: a link annotation has no Link structure element (it was drawn inside an artifact), which PDF/UA-1 forbids.
194    LinkWithoutStructure,
195    /// `link-without-contents`: a link annotation has no description (/Contents), which PDF/UA-1 requires.
196    LinkWithoutContents,
197    /// `font-not-embedded`: a standard 14 font, which is never embedded, was used under a profile that needs every font embedded.
198    FontNotEmbedded,
199    /// `glyph-without-unicode`: a glyph was drawn without a Unicode value, which PDF/A-2u and PDF/UA-1 forbid.
200    GlyphWithoutUnicode,
201    /// `device-color-without-output-intent`: a DeviceCMYK colour or image was used, but the PDF/A output intent is sRGB.
202    DeviceColorWithoutOutputIntent,
203    /// `embedded-file-forbidden`: PDF/A-2 doesn't allow attached files that aren't PDF/A themselves.
204    EmbeddedFileForbidden,
205    /// `embedded-file-without-mime-type`: an attached file has no MIME type, which every PDF/A profile requires.
206    EmbeddedFileWithoutMimeType,
207    /// `flow-content-too-large`: a line or a figure of a flow is taller than the page's body, so no page can hold it.
208    FlowContentTooLarge,
209    /// `flow-layout-unstable`: a flow's contents page kept changing its page numbers after four layouts.
210    FlowLayoutUnstable,
211    /// `invalid-document`: a laminapdf.document/1 document has an unknown key, a missing one or a value of the wrong kind.
212    InvalidDocument,
213    /// `template-data-missing`: a template's $data, $each or $item points to a value the data doesn't have.
214    TemplateDataMissing,
215    /// `template-data-type`: a template's placeholder found data of the wrong kind: $each over something that isn't a list, or text from an object.
216    TemplateDataType,
217    /// `template-too-large`: a template would fill in more values, or nest deeper, than a document may hold.
218    TemplateTooLarge,
219    /// `render-too-large`: the requested tile is larger than the render limits allow; nothing was allocated.
220    RenderTooLarge,
221    /// `render-failed`: the render engine could not open the document or draw the page.
222    RenderFailed,
223    /// `render-backend-unavailable`: the render engine is not available: its library or module could not be loaded.
224    RenderBackendUnavailable,
225    /// `export-failed`: an export's PNG, JPEG or TIFF encoder failed on a page that was drawn.
226    ExportFailed,
227    /// `model-failed`: a layout model, OCR engine or page renderer plugged into an extraction failed; the extraction stops with no partial result.
228    ModelFailed,
229    /// `model-result-unexpected`: a model result was handed to an extraction job that hadn't asked for it, or was the other model's result.
230    ModelResultUnexpected,
231    /// `model-needs-host`: an extraction in one call was given a model whose results only the host can give: a host model, or a plug-in model without a page renderer.
232    ModelNeedsHost,
233    /// `cancelled`: a CancelToken stopped the work; the job is finished and returned no partial result.
234    Cancelled,
235    /// `job-finished`: a job was stepped after it had finished, failed or been cancelled.
236    JobFinished,
237    /// `document-changed`: the document a job was created for changed (an edit, undo, redo, save or rebase) or a different document was passed to step.
238    DocumentChanged,
239    /// `revision-index-out-of-range`: an earlier revision was asked for by an index past the file's last revision.
240    RevisionIndexOutOfRange,
241    /// `builder-finished`: a builder or one of its pages was used after it finished.
242    BuilderFinished,
243    /// `disposed`: a document, builder or other handle was used after free(), or after the using block that held it ended.
244    Disposed,
245    /// `invalid-argument`: a value passed to a binding does not have the shape its type declares.
246    InvalidArgument,
247    /// `source-budget-exceeded`: a sparse source was given more bytes than its byte budget allows.
248    SourceBudgetExceeded,
249    /// `unknown-option`: an options record passed to a binding has a key Lamina PDF does not know.
250    UnknownOption,
251    /// `invalid-command-line`: the command line doesn't parse: an unknown command or flag, a missing argument, a bad value, or stdin named twice.
252    InvalidCommandLine,
253    /// `invalid-page-range`: a page range doesn't fit the grammar, or names a page the document lacks.
254    InvalidPageRange,
255    /// `binary-output-to-terminal`: the command would write a PDF to standard output, and standard output is a terminal.
256    BinaryOutputToTerminal,
257    /// `unknown-code`: explain was given a code that isn't a Lamina PDF error or warning code.
258    UnknownCode,
259    /// `overwrite-refused`: the output file exists, or the command would modify its input in place, and --force wasn't given.
260    OverwriteRefused,
261    /// `input-unreadable`: an input file, standard input or the password file couldn't be read.
262    InputUnreadable,
263    /// `output-unwritable`: the output couldn't be written: its folder is missing or read-only, the disk is full, or standard output closed.
264    OutputUnwritable,
265    /// `path-outside-roots`: laminapdf mcp was given a path outside its --root folders, or a link that leads out of them.
266    PathOutsideRoots,
267}
268
269impl ErrorCode {
270    /// Every variant, in `codes.json` order.
271    ///
272    /// Added in 0.2.0.
273    pub const ALL: &'static [Self] = &[
274        Self::NotPdf,
275        Self::MissingRoot,
276        Self::ReferenceCycle,
277        Self::LimitExceeded,
278        Self::Strict,
279        Self::DataPending,
280        Self::Source,
281        Self::Type,
282        Self::InvalidStructure,
283        Self::UnsetObject,
284        Self::RepairedBase,
285        Self::EncryptedBase,
286        Self::PasswordRequired,
287        Self::WrongPassword,
288        Self::UnsupportedSecurityHandler,
289        Self::UnexpectedEof,
290        Self::Syntax,
291        Self::UnsupportedFilter,
292        Self::Decompress,
293        Self::NestedTransaction,
294        Self::NoTransaction,
295        Self::UnknownPage,
296        Self::DirectPage,
297        Self::UnsupportedVersion,
298        Self::InvalidOpLog,
299        Self::SavedNotRebased,
300        Self::NoPendingSave,
301        Self::MalformedXmp,
302        Self::UnknownSource,
303        Self::Sink,
304        Self::NotRebased,
305        Self::SinkNotEmpty,
306        Self::WouldInvalidateSignatures,
307        Self::RequiresRewrite,
308        Self::InvalidFont,
309        Self::CollectionIndex,
310        Self::UnknownAxis,
311        Self::FontNotEmbeddable,
312        Self::MissingGlyph,
313        Self::GlyphOutOfRange,
314        Self::UnknownFont,
315        Self::SubsetFailed,
316        Self::InvalidAxisValue,
317        Self::WrongDocument,
318        Self::InvalidFeature,
319        Self::InvalidTextRange,
320        Self::InvalidSpans,
321        Self::UnsupportedLayoutOption,
322        Self::FontMismatch,
323        Self::EncodingFull,
324        Self::FontNotShapable,
325        Self::InvalidImage,
326        Self::UnsupportedImage,
327        Self::ImageTooLarge,
328        Self::ImageDataLength,
329        Self::InvalidIccProfile,
330        Self::ColorComponents,
331        Self::InvalidColor,
332        Self::InvalidGeometry,
333        Self::TextOverflow,
334        Self::PageIndexOutOfRange,
335        Self::UnknownDestination,
336        Self::InvalidPageLabels,
337        Self::TagElementNotOpen,
338        Self::TagElementUnclosed,
339        Self::ProfileVersionConflict,
340        Self::MissingTitle,
341        Self::MissingLang,
342        Self::MissingAltText,
343        Self::UntaggedContent,
344        Self::HeadingLevelSkipped,
345        Self::UnnumberedHeadingMisused,
346        Self::InvalidStructureNesting,
347        Self::LinkWithoutStructure,
348        Self::LinkWithoutContents,
349        Self::FontNotEmbedded,
350        Self::GlyphWithoutUnicode,
351        Self::DeviceColorWithoutOutputIntent,
352        Self::EmbeddedFileForbidden,
353        Self::EmbeddedFileWithoutMimeType,
354        Self::FlowContentTooLarge,
355        Self::FlowLayoutUnstable,
356        Self::InvalidDocument,
357        Self::TemplateDataMissing,
358        Self::TemplateDataType,
359        Self::TemplateTooLarge,
360        Self::RenderTooLarge,
361        Self::RenderFailed,
362        Self::RenderBackendUnavailable,
363        Self::ExportFailed,
364        Self::ModelFailed,
365        Self::ModelResultUnexpected,
366        Self::ModelNeedsHost,
367        Self::Cancelled,
368        Self::JobFinished,
369        Self::DocumentChanged,
370        Self::RevisionIndexOutOfRange,
371        Self::BuilderFinished,
372        Self::Disposed,
373        Self::InvalidArgument,
374        Self::SourceBudgetExceeded,
375        Self::UnknownOption,
376        Self::InvalidCommandLine,
377        Self::InvalidPageRange,
378        Self::BinaryOutputToTerminal,
379        Self::UnknownCode,
380        Self::OverwriteRefused,
381        Self::InputUnreadable,
382        Self::OutputUnwritable,
383        Self::PathOutsideRoots,
384    ];
385
386    /// The code with this name, if there is one.
387    ///
388    /// Added in 0.2.0.
389    #[must_use]
390    pub const fn from_code(code: &str) -> Option<Self> {
391        let mut rest = Self::ALL;
392        while let [first, tail @ ..] = rest {
393            if bytes_eq(first.as_str().as_bytes(), code.as_bytes()) {
394                return Some(*first);
395            }
396            rest = tail;
397        }
398        None
399    }
400
401    /// The kebab-case code.
402    ///
403    /// Added in 0.2.0.
404    #[must_use]
405    pub const fn as_str(self) -> &'static str {
406        match self {
407            Self::NotPdf => "not-pdf",
408            Self::MissingRoot => "missing-root",
409            Self::ReferenceCycle => "reference-cycle",
410            Self::LimitExceeded => "limit-exceeded",
411            Self::Strict => "strict",
412            Self::DataPending => "data-pending",
413            Self::Source => "source",
414            Self::Type => "type",
415            Self::InvalidStructure => "invalid-structure",
416            Self::UnsetObject => "unset-object",
417            Self::RepairedBase => "repaired-base",
418            Self::EncryptedBase => "encrypted-base",
419            Self::PasswordRequired => "password-required",
420            Self::WrongPassword => "wrong-password",
421            Self::UnsupportedSecurityHandler => "unsupported-security-handler",
422            Self::UnexpectedEof => "unexpected-eof",
423            Self::Syntax => "syntax",
424            Self::UnsupportedFilter => "unsupported-filter",
425            Self::Decompress => "decompress",
426            Self::NestedTransaction => "nested-transaction",
427            Self::NoTransaction => "no-transaction",
428            Self::UnknownPage => "unknown-page",
429            Self::DirectPage => "direct-page",
430            Self::UnsupportedVersion => "unsupported-version",
431            Self::InvalidOpLog => "invalid-op-log",
432            Self::SavedNotRebased => "saved-not-rebased",
433            Self::NoPendingSave => "no-pending-save",
434            Self::MalformedXmp => "malformed-xmp",
435            Self::UnknownSource => "unknown-source",
436            Self::Sink => "sink",
437            Self::NotRebased => "not-rebased",
438            Self::SinkNotEmpty => "sink-not-empty",
439            Self::WouldInvalidateSignatures => "would-invalidate-signatures",
440            Self::RequiresRewrite => "requires-rewrite",
441            Self::InvalidFont => "invalid-font",
442            Self::CollectionIndex => "collection-index",
443            Self::UnknownAxis => "unknown-axis",
444            Self::FontNotEmbeddable => "font-not-embeddable",
445            Self::MissingGlyph => "missing-glyph",
446            Self::GlyphOutOfRange => "glyph-out-of-range",
447            Self::UnknownFont => "unknown-font",
448            Self::SubsetFailed => "subset-failed",
449            Self::InvalidAxisValue => "invalid-axis-value",
450            Self::WrongDocument => "wrong-document",
451            Self::InvalidFeature => "invalid-feature",
452            Self::InvalidTextRange => "invalid-text-range",
453            Self::InvalidSpans => "invalid-spans",
454            Self::UnsupportedLayoutOption => "unsupported-layout-option",
455            Self::FontMismatch => "font-mismatch",
456            Self::EncodingFull => "encoding-full",
457            Self::FontNotShapable => "font-not-shapable",
458            Self::InvalidImage => "invalid-image",
459            Self::UnsupportedImage => "unsupported-image",
460            Self::ImageTooLarge => "image-too-large",
461            Self::ImageDataLength => "image-data-length",
462            Self::InvalidIccProfile => "invalid-icc-profile",
463            Self::ColorComponents => "color-components",
464            Self::InvalidColor => "invalid-color",
465            Self::InvalidGeometry => "invalid-geometry",
466            Self::TextOverflow => "text-overflow",
467            Self::PageIndexOutOfRange => "page-index-out-of-range",
468            Self::UnknownDestination => "unknown-destination",
469            Self::InvalidPageLabels => "invalid-page-labels",
470            Self::TagElementNotOpen => "tag-element-not-open",
471            Self::TagElementUnclosed => "tag-element-unclosed",
472            Self::ProfileVersionConflict => "profile-version-conflict",
473            Self::MissingTitle => "missing-title",
474            Self::MissingLang => "missing-lang",
475            Self::MissingAltText => "missing-alt-text",
476            Self::UntaggedContent => "untagged-content",
477            Self::HeadingLevelSkipped => "heading-level-skipped",
478            Self::UnnumberedHeadingMisused => "unnumbered-heading-misused",
479            Self::InvalidStructureNesting => "invalid-structure-nesting",
480            Self::LinkWithoutStructure => "link-without-structure",
481            Self::LinkWithoutContents => "link-without-contents",
482            Self::FontNotEmbedded => "font-not-embedded",
483            Self::GlyphWithoutUnicode => "glyph-without-unicode",
484            Self::DeviceColorWithoutOutputIntent => "device-color-without-output-intent",
485            Self::EmbeddedFileForbidden => "embedded-file-forbidden",
486            Self::EmbeddedFileWithoutMimeType => "embedded-file-without-mime-type",
487            Self::FlowContentTooLarge => "flow-content-too-large",
488            Self::FlowLayoutUnstable => "flow-layout-unstable",
489            Self::InvalidDocument => "invalid-document",
490            Self::TemplateDataMissing => "template-data-missing",
491            Self::TemplateDataType => "template-data-type",
492            Self::TemplateTooLarge => "template-too-large",
493            Self::RenderTooLarge => "render-too-large",
494            Self::RenderFailed => "render-failed",
495            Self::RenderBackendUnavailable => "render-backend-unavailable",
496            Self::ExportFailed => "export-failed",
497            Self::ModelFailed => "model-failed",
498            Self::ModelResultUnexpected => "model-result-unexpected",
499            Self::ModelNeedsHost => "model-needs-host",
500            Self::Cancelled => "cancelled",
501            Self::JobFinished => "job-finished",
502            Self::DocumentChanged => "document-changed",
503            Self::RevisionIndexOutOfRange => "revision-index-out-of-range",
504            Self::BuilderFinished => "builder-finished",
505            Self::Disposed => "disposed",
506            Self::InvalidArgument => "invalid-argument",
507            Self::SourceBudgetExceeded => "source-budget-exceeded",
508            Self::UnknownOption => "unknown-option",
509            Self::InvalidCommandLine => "invalid-command-line",
510            Self::InvalidPageRange => "invalid-page-range",
511            Self::BinaryOutputToTerminal => "binary-output-to-terminal",
512            Self::UnknownCode => "unknown-code",
513            Self::OverwriteRefused => "overwrite-refused",
514            Self::InputUnreadable => "input-unreadable",
515            Self::OutputUnwritable => "output-unwritable",
516            Self::PathOutsideRoots => "path-outside-roots",
517        }
518    }
519
520    /// The kind (ADR 0026 §2).
521    ///
522    /// Added in 0.2.0.
523    #[must_use]
524    pub const fn kind(self) -> ErrorKind {
525        match self {
526            Self::NotPdf => ErrorKind::Input,
527            Self::MissingRoot => ErrorKind::Input,
528            Self::ReferenceCycle => ErrorKind::Input,
529            Self::LimitExceeded => ErrorKind::Limit,
530            Self::Strict => ErrorKind::Input,
531            Self::DataPending => ErrorKind::State,
532            Self::Source => ErrorKind::Io,
533            Self::Type => ErrorKind::Input,
534            Self::InvalidStructure => ErrorKind::Input,
535            Self::UnsetObject => ErrorKind::Internal,
536            Self::RepairedBase => ErrorKind::State,
537            Self::EncryptedBase => ErrorKind::Unsupported,
538            Self::PasswordRequired => ErrorKind::Security,
539            Self::WrongPassword => ErrorKind::Security,
540            Self::UnsupportedSecurityHandler => ErrorKind::Unsupported,
541            Self::UnexpectedEof => ErrorKind::Input,
542            Self::Syntax => ErrorKind::Input,
543            Self::UnsupportedFilter => ErrorKind::Unsupported,
544            Self::Decompress => ErrorKind::Input,
545            Self::NestedTransaction => ErrorKind::State,
546            Self::NoTransaction => ErrorKind::State,
547            Self::UnknownPage => ErrorKind::Usage,
548            Self::DirectPage => ErrorKind::Unsupported,
549            Self::UnsupportedVersion => ErrorKind::Unsupported,
550            Self::InvalidOpLog => ErrorKind::Input,
551            Self::SavedNotRebased => ErrorKind::State,
552            Self::NoPendingSave => ErrorKind::State,
553            Self::MalformedXmp => ErrorKind::Input,
554            Self::UnknownSource => ErrorKind::Usage,
555            Self::Sink => ErrorKind::Io,
556            Self::NotRebased => ErrorKind::State,
557            Self::SinkNotEmpty => ErrorKind::Usage,
558            Self::WouldInvalidateSignatures => ErrorKind::Security,
559            Self::RequiresRewrite => ErrorKind::State,
560            Self::InvalidFont => ErrorKind::Input,
561            Self::CollectionIndex => ErrorKind::Usage,
562            Self::UnknownAxis => ErrorKind::Usage,
563            Self::FontNotEmbeddable => ErrorKind::Usage,
564            Self::MissingGlyph => ErrorKind::Input,
565            Self::GlyphOutOfRange => ErrorKind::Usage,
566            Self::UnknownFont => ErrorKind::Usage,
567            Self::SubsetFailed => ErrorKind::Unsupported,
568            Self::InvalidAxisValue => ErrorKind::Usage,
569            Self::WrongDocument => ErrorKind::Usage,
570            Self::InvalidFeature => ErrorKind::Usage,
571            Self::InvalidTextRange => ErrorKind::Usage,
572            Self::InvalidSpans => ErrorKind::Usage,
573            Self::UnsupportedLayoutOption => ErrorKind::Unsupported,
574            Self::FontMismatch => ErrorKind::Usage,
575            Self::EncodingFull => ErrorKind::Limit,
576            Self::FontNotShapable => ErrorKind::Unsupported,
577            Self::InvalidImage => ErrorKind::Input,
578            Self::UnsupportedImage => ErrorKind::Unsupported,
579            Self::ImageTooLarge => ErrorKind::Limit,
580            Self::ImageDataLength => ErrorKind::Usage,
581            Self::InvalidIccProfile => ErrorKind::Input,
582            Self::ColorComponents => ErrorKind::Usage,
583            Self::InvalidColor => ErrorKind::Usage,
584            Self::InvalidGeometry => ErrorKind::Usage,
585            Self::TextOverflow => ErrorKind::Usage,
586            Self::PageIndexOutOfRange => ErrorKind::Usage,
587            Self::UnknownDestination => ErrorKind::Usage,
588            Self::InvalidPageLabels => ErrorKind::Usage,
589            Self::TagElementNotOpen => ErrorKind::Usage,
590            Self::TagElementUnclosed => ErrorKind::Usage,
591            Self::ProfileVersionConflict => ErrorKind::Usage,
592            Self::MissingTitle => ErrorKind::Usage,
593            Self::MissingLang => ErrorKind::Usage,
594            Self::MissingAltText => ErrorKind::Usage,
595            Self::UntaggedContent => ErrorKind::Usage,
596            Self::HeadingLevelSkipped => ErrorKind::Usage,
597            Self::UnnumberedHeadingMisused => ErrorKind::Usage,
598            Self::InvalidStructureNesting => ErrorKind::Usage,
599            Self::LinkWithoutStructure => ErrorKind::Usage,
600            Self::LinkWithoutContents => ErrorKind::Usage,
601            Self::FontNotEmbedded => ErrorKind::Usage,
602            Self::GlyphWithoutUnicode => ErrorKind::Usage,
603            Self::DeviceColorWithoutOutputIntent => ErrorKind::Usage,
604            Self::EmbeddedFileForbidden => ErrorKind::Usage,
605            Self::EmbeddedFileWithoutMimeType => ErrorKind::Usage,
606            Self::FlowContentTooLarge => ErrorKind::Usage,
607            Self::FlowLayoutUnstable => ErrorKind::Internal,
608            Self::InvalidDocument => ErrorKind::Usage,
609            Self::TemplateDataMissing => ErrorKind::Usage,
610            Self::TemplateDataType => ErrorKind::Usage,
611            Self::TemplateTooLarge => ErrorKind::Usage,
612            Self::RenderTooLarge => ErrorKind::Limit,
613            Self::RenderFailed => ErrorKind::Input,
614            Self::RenderBackendUnavailable => ErrorKind::Io,
615            Self::ExportFailed => ErrorKind::Internal,
616            Self::ModelFailed => ErrorKind::Internal,
617            Self::ModelResultUnexpected => ErrorKind::Usage,
618            Self::ModelNeedsHost => ErrorKind::Usage,
619            Self::Cancelled => ErrorKind::Cancelled,
620            Self::JobFinished => ErrorKind::State,
621            Self::DocumentChanged => ErrorKind::State,
622            Self::RevisionIndexOutOfRange => ErrorKind::Usage,
623            Self::BuilderFinished => ErrorKind::State,
624            Self::Disposed => ErrorKind::State,
625            Self::InvalidArgument => ErrorKind::Usage,
626            Self::SourceBudgetExceeded => ErrorKind::Limit,
627            Self::UnknownOption => ErrorKind::Usage,
628            Self::InvalidCommandLine => ErrorKind::Usage,
629            Self::InvalidPageRange => ErrorKind::Usage,
630            Self::BinaryOutputToTerminal => ErrorKind::Usage,
631            Self::UnknownCode => ErrorKind::Usage,
632            Self::OverwriteRefused => ErrorKind::State,
633            Self::InputUnreadable => ErrorKind::Io,
634            Self::OutputUnwritable => ErrorKind::Io,
635            Self::PathOutsideRoots => ErrorKind::Security,
636        }
637    }
638
639    /// One lowercase sentence: what happened.
640    ///
641    /// Added in 0.2.0.
642    #[must_use]
643    pub const fn summary(self) -> &'static str {
644        match self {
645            Self::NotPdf => "the input does not look like a PDF at all",
646            Self::MissingRoot => "no document catalog (/Root) was found, even after repair",
647            Self::ReferenceCycle => "a reference chain or the page tree loops back on itself",
648            Self::LimitExceeded => "a hard Limits value was exceeded",
649            Self::Strict => "strict mode refused something the tolerant reader would have repaired",
650            Self::DataPending => "the ByteSource has not fetched the byte ranges the call needs yet",
651            Self::Source => "the ByteSource failed to read",
652            Self::Type => "an object had a different type than the structure requires",
653            Self::InvalidStructure => "an object stream, xref section or filter parameter was malformed",
654            Self::UnsetObject => "a writer object number was reserved but never given a value",
655            Self::RepairedBase => "an incremental update was requested for a document whose xref needed repair",
656            Self::EncryptedBase => "a save of an encrypted document was requested",
657            Self::PasswordRequired => "the document is encrypted with a user password and none was given",
658            Self::WrongPassword => "the given password is neither the user nor the owner password",
659            Self::UnsupportedSecurityHandler => "the document uses a security handler Lamina PDF cannot decrypt",
660            Self::UnexpectedEof => "the input ended before a complete token or object was read",
661            Self::Syntax => "a token or structure did not match the PDF grammar",
662            Self::UnsupportedFilter => "a stream uses a filter Lamina PDF does not implement",
663            Self::Decompress => "compressed stream data was corrupt",
664            Self::NestedTransaction => "a transaction was started, or undo or redo called, while one is open",
665            Self::NoTransaction => "apply, commit or rollback was called without an open transaction",
666            Self::UnknownPage => "an op names a page the document does not have",
667            Self::DirectPage => "the page is a direct dictionary, which ops cannot edit yet",
668            Self::UnsupportedVersion => "an op log has a schema version this reader does not know",
669            Self::InvalidOpLog => "an op log does not parse: an unknown op or field, a bad value, or not JSON",
670            Self::SavedNotRebased => "the document was saved to a sink Lamina PDF cannot read back and waits for rebase",
671            Self::NoPendingSave => "rebase was called without a save waiting for it",
672            Self::MalformedXmp => "a metadata edit would replace the document's XMP packet, which can't be read, losing what it holds",
673            Self::UnknownSource => "an op or a call names a source document that was not added to the session",
674            Self::Sink => "the sink failed to take the bytes or could not give them back",
675            Self::NotRebased => "the output was written, but rebasing the document onto it failed",
676            Self::SinkNotEmpty => "the sink already held bytes before the save started",
677            Self::WouldInvalidateSignatures => "the save would break one or more signatures",
678            Self::RequiresRewrite => "an incremental save was requested but only a full rewrite is safe",
679            Self::InvalidFont => "font bytes could not be read as a font",
680            Self::CollectionIndex => "a font collection member past the end of the collection was asked for",
681            Self::UnknownAxis => "an instance was asked for on a variation axis the font does not have",
682            Self::FontNotEmbeddable => "the font's OS/2 fsType forbids embedding",
683            Self::MissingGlyph => "the font has no glyph for a character of the text",
684            Self::GlyphOutOfRange => "a glyph ID at or past the font's glyph count was used",
685            Self::UnknownFont => "a FontKey was used with a registry that did not hand it out",
686            Self::SubsetFailed => "subsetting a font failed",
687            Self::InvalidAxisValue => "a variation axis value was NaN or infinite",
688            Self::WrongDocument => "finish_fonts was given a document the registry did not reserve its fonts in",
689            Self::InvalidFeature => "an OpenType feature setting did not parse",
690            Self::InvalidTextRange => "a byte range was out of bounds or not on character boundaries of the text",
691            Self::InvalidSpans => "the styled spans given for a paragraph do not cover its text once, in order",
692            Self::UnsupportedLayoutOption => "a layout option that is not implemented yet was asked for",
693            Self::FontMismatch => "a shaped run was given with a font key for a different font than it was shaped with",
694            Self::EncodingFull => "a standard 14 font has no free one-byte code left for another glyph",
695            Self::FontNotShapable => "a standard 14 font was given to shaping or layout, which need a font program",
696            Self::InvalidImage => "image bytes are not a readable image of the format they were given as",
697            Self::UnsupportedImage => "the image uses a feature that PDF or Lamina PDF does not support",
698            Self::ImageTooLarge => "the image needs more memory than the builder allows (a decoded PNG over 256 MiB, or raw dimensions whose size overflows)",
699            Self::ImageDataLength => "raw image samples are not width x height x channels bytes long",
700            Self::InvalidIccProfile => "the bytes are not a usable ICC profile",
701            Self::ColorComponents => "a colour has the wrong number of components for its colour space",
702            Self::InvalidColor => "a colour string is not of the form #rgb or #rrggbb",
703            Self::InvalidGeometry => "a page size, box, /UserUnit, drawing value (coordinate, matrix, line width, dash, miter limit) or image size is not usable",
704            Self::TextOverflow => "a text box's lines don't all fit its height and its options asked for an error",
705            Self::PageIndexOutOfRange => "a link, outline item or destination names a page index the document doesn't have",
706            Self::UnknownDestination => "a link or outline item names a destination that was never defined",
707            Self::InvalidPageLabels => "page label ranges that don't start at page 0, don't increase, start past the last page or number from 0",
708            Self::TagElementNotOpen => "a structure element resumed or closed isn't open",
709            Self::TagElementUnclosed => "structure elements opened across pages were never closed",
710            Self::ProfileVersionConflict => "the PDF version asked for is one the profile doesn't allow (PDF/UA-1, PDF/A-2 and PDF/A-3 are based on PDF 1.7)",
711            Self::MissingTitle => "PDF/UA-1 needs a document title, and the metadata gives none",
712            Self::MissingLang => "PDF/UA-1 needs the document's natural language, and none was set",
713            Self::MissingAltText => "a Figure or Formula has no alternate text (/Alt or /ActualText), which PDF/UA-1 requires",
714            Self::UntaggedContent => "content was drawn outside every structure element and artifact, which PDF/UA-1 forbids",
715            Self::HeadingLevelSkipped => "a heading skips a level (the first is not H1, or an H3 follows an H1), which PDF/UA-1 forbids",
716            Self::UnnumberedHeadingMisused => "an unnumbered H heading shares its parent with another H, or the document also uses H1-H6, which PDF/UA-1 forbids",
717            Self::InvalidStructureNesting => "a table or list element sits in a parent its type doesn't allow (a TD outside a TR, a P directly in a Table)",
718            Self::LinkWithoutStructure => "a link annotation has no Link structure element (it was drawn inside an artifact), which PDF/UA-1 forbids",
719            Self::LinkWithoutContents => "a link annotation has no description (/Contents), which PDF/UA-1 requires",
720            Self::FontNotEmbedded => "a standard 14 font, which is never embedded, was used under a profile that needs every font embedded",
721            Self::GlyphWithoutUnicode => "a glyph was drawn without a Unicode value, which PDF/A-2u and PDF/UA-1 forbid",
722            Self::DeviceColorWithoutOutputIntent => "a DeviceCMYK colour or image was used, but the PDF/A output intent is sRGB",
723            Self::EmbeddedFileForbidden => "PDF/A-2 doesn't allow attached files that aren't PDF/A themselves",
724            Self::EmbeddedFileWithoutMimeType => "an attached file has no MIME type, which every PDF/A profile requires",
725            Self::FlowContentTooLarge => "a line or a figure of a flow is taller than the page's body, so no page can hold it",
726            Self::FlowLayoutUnstable => "a flow's contents page kept changing its page numbers after four layouts",
727            Self::InvalidDocument => "a laminapdf.document/1 document has an unknown key, a missing one or a value of the wrong kind",
728            Self::TemplateDataMissing => "a template's $data, $each or $item points to a value the data doesn't have",
729            Self::TemplateDataType => "a template's placeholder found data of the wrong kind: $each over something that isn't a list, or text from an object",
730            Self::TemplateTooLarge => "a template would fill in more values, or nest deeper, than a document may hold",
731            Self::RenderTooLarge => "the requested tile is larger than the render limits allow; nothing was allocated",
732            Self::RenderFailed => "the render engine could not open the document or draw the page",
733            Self::RenderBackendUnavailable => "the render engine is not available: its library or module could not be loaded",
734            Self::ExportFailed => "an export's PNG, JPEG or TIFF encoder failed on a page that was drawn",
735            Self::ModelFailed => "a layout model, OCR engine or page renderer plugged into an extraction failed; the extraction stops with no partial result",
736            Self::ModelResultUnexpected => "a model result was handed to an extraction job that hadn't asked for it, or was the other model's result",
737            Self::ModelNeedsHost => "an extraction in one call was given a model whose results only the host can give: a host model, or a plug-in model without a page renderer",
738            Self::Cancelled => "a CancelToken stopped the work; the job is finished and returned no partial result",
739            Self::JobFinished => "a job was stepped after it had finished, failed or been cancelled",
740            Self::DocumentChanged => "the document a job was created for changed (an edit, undo, redo, save or rebase) or a different document was passed to step",
741            Self::RevisionIndexOutOfRange => "an earlier revision was asked for by an index past the file's last revision",
742            Self::BuilderFinished => "a builder or one of its pages was used after it finished",
743            Self::Disposed => "a document, builder or other handle was used after free(), or after the using block that held it ended",
744            Self::InvalidArgument => "a value passed to a binding does not have the shape its type declares",
745            Self::SourceBudgetExceeded => "a sparse source was given more bytes than its byte budget allows",
746            Self::UnknownOption => "an options record passed to a binding has a key Lamina PDF does not know",
747            Self::InvalidCommandLine => "the command line doesn't parse: an unknown command or flag, a missing argument, a bad value, or stdin named twice",
748            Self::InvalidPageRange => "a page range doesn't fit the grammar, or names a page the document lacks",
749            Self::BinaryOutputToTerminal => "the command would write a PDF to standard output, and standard output is a terminal",
750            Self::UnknownCode => "explain was given a code that isn't a Lamina PDF error or warning code",
751            Self::OverwriteRefused => "the output file exists, or the command would modify its input in place, and --force wasn't given",
752            Self::InputUnreadable => "an input file, standard input or the password file couldn't be read",
753            Self::OutputUnwritable => "the output couldn't be written: its folder is missing or read-only, the disk is full, or standard output closed",
754            Self::PathOutsideRoots => "laminapdf mcp was given a path outside its --root folders, or a link that leads out of them",
755        }
756    }
757
758    /// The hint (ADR 0026 §5), with its `{limit}`/`{option}` parameters unfilled.
759    ///
760    /// Added in 0.2.0.
761    #[must_use]
762    pub const fn hint(self) -> &'static str {
763        match self {
764            Self::NotPdf => "check that the bytes passed to open are a PDF file",
765            Self::MissingRoot => "use another copy of the file: this one has no usable catalog",
766            Self::ReferenceCycle => "use another copy of the file, or repair it with another tool",
767            Self::LimitExceeded => "the input exceeds a safety limit; raise {limit} in Limits only if you trust the input",
768            Self::Strict => "open without strict mode to read the file with repairs, or fix the file",
769            Self::DataPending => "fetch the listed ranges into the source and retry the call",
770            Self::Source => "retry the call, or check the source; the document stays usable",
771            Self::Type => "use another copy of the file, or repair it with another tool",
772            Self::InvalidStructure => "use another copy of the file, or repair it with another tool",
773            Self::UnsetObject => "this is a bug in Lamina PDF: report it with the steps that led to it",
774            Self::RepairedBase => "save with a full rewrite instead of an incremental update",
775            Self::EncryptedBase => "saving encrypted documents is not supported yet; use another tool to decrypt or re-encrypt",
776            Self::PasswordRequired => "pass the document's password in OpenOptions",
777            Self::WrongPassword => "ask for the password again and retry with the correct one",
778            Self::UnsupportedSecurityHandler => "use a tool that supports this encryption to decrypt the file first",
779            Self::UnexpectedEof => "use a complete copy of the file: this one looks truncated",
780            Self::Syntax => "use another copy of the file, or repair it with another tool",
781            Self::UnsupportedFilter => "use a tool that supports the filter to read this stream",
782            Self::Decompress => "use another copy of the file: this stream's data is damaged",
783            Self::NestedTransaction => "commit or roll back the open transaction first, or use a savepoint inside it",
784            Self::NoTransaction => "call begin first, or use transact",
785            Self::UnknownPage => "use a PageId from this document's pages()",
786            Self::DirectPage => "rewrite the file so that every page is an indirect object, or wait for page-structure ops",
787            Self::UnsupportedVersion => "upgrade Lamina PDF to a version that reads this op log version",
788            Self::InvalidOpLog => "validate the op log against the op schema; the samples in fixtures/ops show the format",
789            Self::SavedNotRebased => "call rebase with the saved bytes before applying ops or saving again",
790            Self::NoPendingSave => "call rebase only after a save that returned SavedNotRebased",
791            Self::MalformedXmp => "set replaceMalformed on the edit to replace the packet with a new one, or leave the metadata as it is",
792            Self::UnknownSource => "add the source document's bytes with addSource before applying ops that name it",
793            Self::Sink => "check the destination and retry the save; the document is unchanged",
794            Self::NotRebased => "retry rebase with the saved output carried by the error",
795            Self::SinkNotEmpty => "pass an empty sink: output offsets count from the sink's first byte",
796            Self::WouldInvalidateSignatures => "save with SaveMode::Auto, or ask the user and retry with SaveOptions::with_invalidate_signatures",
797            Self::RequiresRewrite => "save with SaveMode::Auto or SaveMode::FullRewrite",
798            Self::InvalidFont => "pass the complete bytes of a .ttf, .otf, .ttc or .otc file",
799            Self::CollectionIndex => "use an index below Font::collection_len",
800            Self::UnknownAxis => "check the font's axes before choosing coordinates, or use a variable font",
801            Self::FontNotEmbeddable => "use another font, or register it with EmbedPolicy::Override if your licence allows embedding",
802            Self::MissingGlyph => "use a font that covers the character, or split the text across fonts",
803            Self::GlyphOutOfRange => "pass glyph IDs from the font you registered",
804            Self::UnknownFont => "use the key returned by this registry's add",
805            Self::SubsetFailed => "try another version or format of the font, and report the font if it is a common one",
806            Self::InvalidAxisValue => "pass finite axis values; values outside the axis range are clamped",
807            Self::WrongDocument => "use one FontRegistry per document and finish it with that document",
808            Self::InvalidFeature => "write it as liga=0, -liga, smcp or aalt=2 (HarfBuzz syntax without ranges)",
809            Self::InvalidTextRange => "take ranges from Lamina PDF's results (line_breaks, itemize, break_lines) and pass the same text",
810            Self::InvalidSpans => "give spans in text order, each starting where the one before ends, from byte 0 to the end of the text, between grapheme clusters, each with at least one font from the list",
811            Self::UnsupportedLayoutOption => "leave the option at its default; justification comes with a later release",
812            Self::FontMismatch => "pass the key of the font the run was shaped with (the font index of each line run maps to your keys)",
813            Self::EncodingFull => "embed a font with Font::from_bytes, or split the text across two registrations of the standard font",
814            Self::FontNotShapable => "draw standard 14 fonts with FontRegistry::encode, or shape with an embedded font",
815            Self::InvalidImage => "pass the complete bytes of a JPEG or PNG file to Image::jpeg or Image::png",
816            Self::UnsupportedImage => "convert it to a baseline or progressive 8-bit JPEG, or to PNG",
817            Self::ImageTooLarge => "scale the image down before adding it",
818            Self::ImageDataLength => "pass exactly 4 bytes (RGBA) per pixel, row by row",
819            Self::InvalidIccProfile => "pass a complete ICC profile with a Gray, RGB or CMYK data colour space",
820            Self::ColorComponents => "give one component per channel of the colour space (/N of the ICC profile)",
821            Self::InvalidColor => "write the colour as # followed by 3 or 6 hexadecimal digits",
822            Self::InvalidGeometry => "use finite coordinates, positive page sizes and /UserUnit, non-negative line widths and dashes, a miter limit of at least 1, and images of at least one pixel",
823            Self::TextOverflow => "make the box taller or the text shorter, or use Overflow::Clip and read TextLayout::overflow",
824            Self::PageIndexOutOfRange => "use a 0-based index below the document's page count",
825            Self::UnknownDestination => "define it with Builder::destination before the build finishes, or link to a page",
826            Self::InvalidPageLabels => "give ranges sorted by first page, the first at page 0, numbered from 1",
827            Self::TagElementNotOpen => "resume and close only elements this builder's pages opened with open_element, and close each once",
828            Self::TagElementUnclosed => "close each element from open_element with Builder::close_element once its last page is finished",
829            Self::ProfileVersionConflict => "leave the version at 1.7 (the default) or lower; PDF 2.0 needs PDF/A-4 or PDF/UA-2, which Lamina PDF doesn't write yet",
830            Self::MissingTitle => "set a title with Builder::metadata (Metadata::with_title)",
831            Self::MissingLang => "set the language with Builder::lang, such as \"en-GB\"",
832            Self::MissingAltText => "give the figure or formula a description with Tag::with_alt or Surface::figure's alt, or draw decoration as an artifact",
833            Self::UntaggedContent => "draw it inside Surface::tag (real content) or Surface::artifact (decoration)",
834            Self::HeadingLevelSkipped => "start with H1 and go down one level at a time",
835            Self::UnnumberedHeadingMisused => "use numbered headings (H1, H2, ...) throughout, or one H per section",
836            Self::InvalidStructureNesting => "nest tables as Table > TR > TH/TD and lists as L > LI > Lbl/LBody",
837            Self::LinkWithoutStructure => "draw links outside artifacts, so the builder gives each one a Link element",
838            Self::LinkWithoutContents => "pass a description as the link's contents",
839            Self::FontNotEmbedded => "load a font file with Builder::font instead of Builder::standard_font",
840            Self::GlyphWithoutUnicode => "remove NUL characters (U+0000) from the text, or choose PDF/A-2b, which doesn't need Unicode",
841            Self::DeviceColorWithoutOutputIntent => "use RGB or gray colours, or a CMYK colour with an ICC profile (Color::icc)",
842            Self::EmbeddedFileForbidden => "choose PDF/A-3b, which allows attached files of any kind",
843            Self::EmbeddedFileWithoutMimeType => "pass the file's MIME type, such as text/xml or application/octet-stream",
844            Self::FlowContentTooLarge => "make the figure smaller, the text size smaller or the page's margins narrower",
845            Self::FlowLayoutUnstable => "report the flow that fails; a page break after the contents block may avoid it until it is fixed",
846            Self::InvalidDocument => "data.pointer names the value; correct it against the document schema, and didYouMean lists the closest known keys",
847            Self::TemplateDataMissing => "data.pointer names the value the template asked for; add it to the data or correct the pointer",
848            Self::TemplateDataType => "data.pointer names the value and data.expected the kind the template needs there",
849            Self::TemplateTooLarge => "data.limit is the limit it passed; repeat fewer items, or split the document",
850            Self::RenderTooLarge => "request smaller tiles (256 to 512 pixels at high zoom) or raise RenderLimits if the larger bitmap is intended",
851            Self::RenderFailed => "the file may be damaged or use a feature this engine can't draw; try the other backend, or report the file",
852            Self::RenderBackendUnavailable => "run cargo xtask fetch-pdfium or set LAMINA_PDF_PDFIUM_DIR to the folder holding the PDFium library",
853            Self::ExportFailed => "report it with the format and the page: the encoder writes into memory, so this is a bug in Lamina PDF",
854            Self::ModelFailed => "check the plug-in's own logs; extract without the model to get the rules-only result",
855            Self::ModelResultUnexpected => "call provide only while request() returns a request, with the result its kind asks for",
856            Self::ModelNeedsHost => "step an extraction job and hand it each result with provide, or give the plug-in a page renderer",
857            Self::Cancelled => "nothing to do: this is the outcome the caller asked for; start a new job to try again",
858            Self::JobFinished => "stop stepping a job once a step returned its result or an error; create a new job",
859            Self::DocumentChanged => "pass the document the job was created from, and don't change it while the job runs; create a new job",
860            Self::RevisionIndexOutOfRange => "ask for an index below the document's revision count",
861            Self::BuilderFinished => "create a new builder or page: a finished one takes no more drawing, pages, fonts or settings",
862            Self::Disposed => "free a handle only after its last use; to keep working, open the document again or create a new builder",
863            Self::InvalidArgument => "pass the value the type declarations describe; the data field says what was wrong",
864            Self::SourceBudgetExceeded => "raise the source's budget, or open the file with fewer bytes fetched (smaller blocks, no readahead)",
865            Self::UnknownOption => "remove the key or correct its spelling; didYouMean lists the closest known names",
866            Self::InvalidCommandLine => "run the command with --help to see its arguments",
867            Self::InvalidPageRange => "write pages as 1-5, z for the last page, r2 for the second from the end, or x3 to leave page 3 out; data.position is the character where the range went wrong",
868            Self::BinaryOutputToTerminal => "redirect standard output to a file or a pipe, or write to a file with -o",
869            Self::UnknownCode => "check the spelling against didYouMean, or list every code at the docs URL",
870            Self::OverwriteRefused => "pass --force, or write to a new file with -o",
871            Self::InputUnreadable => "check that the file exists and that you can read it; data.input names it",
872            Self::OutputUnwritable => "check that the output's folder exists, that you can write to it and that the disk has room",
873            Self::PathOutsideRoots => "use a path inside one of the server's --root folders, or start the server with another --root",
874        }
875    }
876
877    /// The code's explain page (`docsUrl`, ADR 0026 §6).
878    ///
879    /// Added in 0.2.0.
880    #[must_use]
881    pub fn docs_url(self) -> String {
882        format!("{DOCS_URL_BASE}{}{DOCS_URL_SUFFIX}", self.as_str())
883    }
884}
885
886/// Every warning code, in `codes.json` order.
887///
888/// Added in 0.2.0.
889#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
890#[non_exhaustive]
891pub enum WarningCode {
892    /// `missing-header`: no %PDF-x.y header in the first 1,024 bytes; parsing went ahead.
893    MissingHeader,
894    /// `xref-repaired`: the stored cross-reference data was unusable and was rebuilt by scanning.
895    XrefRepaired,
896    /// `xrefstm-ignored`: a hybrid file's /XRefStm could not be read and was ignored.
897    XrefstmIgnored,
898    /// `stream-length-recovered`: a stream's /Length was wrong, so its end was found by scanning for endstream.
899    StreamLengthRecovered,
900    /// `stale-generation`: a reference's generation did not match its xref entry, so it resolved to null.
901    StaleGeneration,
902    /// `page-tree-node-skipped`: a page-tree node was missing, malformed or too deep, and was skipped.
903    PageTreeNodeSkipped,
904    /// `page-count-mismatch`: the page tree's /Count differs from the number of pages walked.
905    PageCountMismatch,
906    /// `flate-truncated`: Flate data was truncated or had a bad checksum; the partial output was kept.
907    FlateTruncated,
908    /// `objstm-index-mismatch`: an object stream's index was stale and the object was found by searching.
909    ObjstmIndexMismatch,
910    /// `object-number-out-of-range`: an xref entry above max_object_number was dropped.
911    ObjectNumberOutOfRange,
912    /// `aes-padding-invalid`: AES-encrypted data had a bad length or padding and was kept as stored.
913    AesPaddingInvalid,
914    /// `perms-mismatch`: an R5/R6 document's /Perms does not match its /P and /EncryptMetadata.
915    PermsMismatch,
916    /// `warnings-truncated`: more than max_warnings warnings were raised and the rest were dropped.
917    WarningsTruncated,
918    /// `invalid-box`: a page boundary box is not four numbers and reads as absent.
919    InvalidBox,
920    /// `invalid-rotate`: a page's /Rotate is not a multiple of 90 and reads as 0.
921    InvalidRotate,
922    /// `name-tree-node-skipped`: a name- or number-tree node was malformed, repeated or too deep, and was skipped.
923    NameTreeNodeSkipped,
924    /// `outline-cycle`: an outline item was reached twice; that branch of the walk stopped.
925    OutlineCycle,
926    /// `outline-item-skipped`: an outline item was missing, not a dictionary or too deep, and was skipped with its subtree.
927    OutlineItemSkipped,
928    /// `invalid-date`: an Info date is not a valid PDF date; the raw string is kept.
929    InvalidDate,
930    /// `xmp-invalid`: the XMP metadata packet is not readable XMP and reads as absent.
931    XmpInvalid,
932    /// `xmp-repaired`: the XMP metadata packet had damage other readers read past, and was read the same way.
933    XmpRepaired,
934    /// `invalid-page-label`: a /PageLabels entry is malformed; the malformed part is dropped.
935    InvalidPageLabel,
936    /// `invalid-entry`: an entry a view reads is unreadable or of the wrong type and reads as absent.
937    InvalidEntry,
938    /// `content-unknown-operator`: an operator the spec does not define was skipped outside a BX/EX section.
939    ContentUnknownOperator,
940    /// `content-bad-operands`: an operator had too few operands or operands of the wrong type, or extra ones.
941    ContentBadOperands,
942    /// `content-unbalanced-q`: a Q without a matching q was ignored, or saved graphics states were left open.
943    ContentUnbalancedQ,
944    /// `content-unbalanced-bt`: a text object was opened twice, closed outside one, or left open.
945    ContentUnbalancedBt,
946    /// `content-unbalanced-marked`: an EMC without a matching BMC or BDC was ignored, or marked content was left open.
947    ContentUnbalancedMarked,
948    /// `content-syntax`: content-stream bytes that are not a token were skipped.
949    ContentSyntax,
950    /// `content-resource-missing`: an operator named a resource that is missing, of the wrong type or unreadable.
951    ContentResourceMissing,
952    /// `inline-image-unterminated`: no EI ends an inline image; the rest of the content was skipped.
953    InlineImageUnterminated,
954    /// `xobject-cycle`: a Form XObject draws itself, directly or through other forms.
955    XobjectCycle,
956    /// `content-path-unpainted`: a content stream ended with a path no painting operator ended.
957    ContentPathUnpainted,
958    /// `font-invalid`: a font dictionary has a missing or malformed entry, so its text was decoded with defaults.
959    FontInvalid,
960    /// `cmap-invalid`: a font's CMap or ToUnicode CMap is malformed or names a predefined CMap Lamina PDF has no table for.
961    CmapInvalid,
962    /// `unmapped-glyph`: a font shows glyphs that nothing maps to text.
963    UnmappedGlyph,
964    /// `extract-limit-blocks`: a page had more runs of text than the extraction block limit; the runs past it were left out.
965    ExtractLimitBlocks,
966    /// `extract-reading-order-ambiguous`: a page mixes horizontal and vertical writing, so the order of its blocks is a guess.
967    ExtractReadingOrderAmbiguous,
968    /// `extract-table-ambiguous`: a table's rules marked out merged cells that aren't rectangles, so its cells were kept unmerged.
969    ExtractTableAmbiguous,
970    /// `extract-table-limit`: a page's ruling lines would make a table bigger than the extraction's cell limit; those lines gave no table.
971    ExtractTableLimit,
972    /// `extract-struct-tree-ignored`: a tagged page's structure tree covered too little of its text, or its order jumped back across columns too often, so the layout gave the reading order.
973    ExtractStructTreeIgnored,
974    /// `extract-untagged-content`: a page read in structure-tree order has visible text that is neither in the tree nor an artifact; it follows the tree's blocks, in layout order.
975    ExtractUntaggedContent,
976    /// `extract-needs-ocr`: a page has no usable text layer: it is an image (with or without an invisible OCR layer), outlined glyphs, or glyphs without Unicode, so its extracted text is empty or unreliable.
977    ExtractNeedsOcr,
978    /// `extract-column-order-uncertain`: the layout rules had to guess how a page's columns are read, so its blocks may be in the wrong order; the blocks concerned have a lower confidence.
979    ExtractColumnOrderUncertain,
980    /// `pdfa-one-author`: the file claims PDF/A-1, which allows one author, and its metadata lists more.
981    PdfaOneAuthor,
982    /// `pdfua-title-missing`: the file claims PDF/UA-1, which requires a title in its metadata, and it has none.
983    PdfuaTitleMissing,
984    /// `pdfa-info-mismatch`: the file claims PDF/A, which requires the Info dictionary and the XMP packet to agree, and they differ.
985    PdfaInfoMismatch,
986    /// `tounicode-conflict`: one glyph was used for two different texts; ToUnicode keeps the first.
987    TounicodeConflict,
988    /// `whole-font-rebuilt`: a font that forbids subsetting was rebuilt with every glyph kept.
989    WholeFontRebuilt,
990    /// `flow-keep-broken`: blocks kept together are taller than a page, so the flow split them.
991    FlowKeepBroken,
992    /// `markdown-html-ignored`: the Markdown holds raw HTML, which the PDF leaves out.
993    MarkdownHtmlIgnored,
994    /// `markdown-image-missing`: the Markdown names an image that wasn't supplied, so the PDF leaves it out.
995    MarkdownImageMissing,
996    /// `covered-text`: a page draws text and then paints a shape, an image or an annotation over it, so the text is hidden but still in the file.
997    CoveredText,
998    /// `redaction-not-applied`: a page has redaction marks that were never applied, so the text under them is still in the file.
999    RedactionNotApplied,
1000    /// `text-in-earlier-revision`: an earlier revision of the file holds text that the latest revision no longer has.
1001    TextInEarlierRevision,
1002}
1003
1004impl WarningCode {
1005    /// Every variant, in `codes.json` order.
1006    ///
1007    /// Added in 0.2.0.
1008    pub const ALL: &'static [Self] = &[
1009        Self::MissingHeader,
1010        Self::XrefRepaired,
1011        Self::XrefstmIgnored,
1012        Self::StreamLengthRecovered,
1013        Self::StaleGeneration,
1014        Self::PageTreeNodeSkipped,
1015        Self::PageCountMismatch,
1016        Self::FlateTruncated,
1017        Self::ObjstmIndexMismatch,
1018        Self::ObjectNumberOutOfRange,
1019        Self::AesPaddingInvalid,
1020        Self::PermsMismatch,
1021        Self::WarningsTruncated,
1022        Self::InvalidBox,
1023        Self::InvalidRotate,
1024        Self::NameTreeNodeSkipped,
1025        Self::OutlineCycle,
1026        Self::OutlineItemSkipped,
1027        Self::InvalidDate,
1028        Self::XmpInvalid,
1029        Self::XmpRepaired,
1030        Self::InvalidPageLabel,
1031        Self::InvalidEntry,
1032        Self::ContentUnknownOperator,
1033        Self::ContentBadOperands,
1034        Self::ContentUnbalancedQ,
1035        Self::ContentUnbalancedBt,
1036        Self::ContentUnbalancedMarked,
1037        Self::ContentSyntax,
1038        Self::ContentResourceMissing,
1039        Self::InlineImageUnterminated,
1040        Self::XobjectCycle,
1041        Self::ContentPathUnpainted,
1042        Self::FontInvalid,
1043        Self::CmapInvalid,
1044        Self::UnmappedGlyph,
1045        Self::ExtractLimitBlocks,
1046        Self::ExtractReadingOrderAmbiguous,
1047        Self::ExtractTableAmbiguous,
1048        Self::ExtractTableLimit,
1049        Self::ExtractStructTreeIgnored,
1050        Self::ExtractUntaggedContent,
1051        Self::ExtractNeedsOcr,
1052        Self::ExtractColumnOrderUncertain,
1053        Self::PdfaOneAuthor,
1054        Self::PdfuaTitleMissing,
1055        Self::PdfaInfoMismatch,
1056        Self::TounicodeConflict,
1057        Self::WholeFontRebuilt,
1058        Self::FlowKeepBroken,
1059        Self::MarkdownHtmlIgnored,
1060        Self::MarkdownImageMissing,
1061        Self::CoveredText,
1062        Self::RedactionNotApplied,
1063        Self::TextInEarlierRevision,
1064    ];
1065
1066    /// The code with this name, if there is one.
1067    ///
1068    /// Added in 0.2.0.
1069    #[must_use]
1070    pub const fn from_code(code: &str) -> Option<Self> {
1071        let mut rest = Self::ALL;
1072        while let [first, tail @ ..] = rest {
1073            if bytes_eq(first.as_str().as_bytes(), code.as_bytes()) {
1074                return Some(*first);
1075            }
1076            rest = tail;
1077        }
1078        None
1079    }
1080
1081    /// The kebab-case code.
1082    ///
1083    /// Added in 0.2.0.
1084    #[must_use]
1085    pub const fn as_str(self) -> &'static str {
1086        match self {
1087            Self::MissingHeader => "missing-header",
1088            Self::XrefRepaired => "xref-repaired",
1089            Self::XrefstmIgnored => "xrefstm-ignored",
1090            Self::StreamLengthRecovered => "stream-length-recovered",
1091            Self::StaleGeneration => "stale-generation",
1092            Self::PageTreeNodeSkipped => "page-tree-node-skipped",
1093            Self::PageCountMismatch => "page-count-mismatch",
1094            Self::FlateTruncated => "flate-truncated",
1095            Self::ObjstmIndexMismatch => "objstm-index-mismatch",
1096            Self::ObjectNumberOutOfRange => "object-number-out-of-range",
1097            Self::AesPaddingInvalid => "aes-padding-invalid",
1098            Self::PermsMismatch => "perms-mismatch",
1099            Self::WarningsTruncated => "warnings-truncated",
1100            Self::InvalidBox => "invalid-box",
1101            Self::InvalidRotate => "invalid-rotate",
1102            Self::NameTreeNodeSkipped => "name-tree-node-skipped",
1103            Self::OutlineCycle => "outline-cycle",
1104            Self::OutlineItemSkipped => "outline-item-skipped",
1105            Self::InvalidDate => "invalid-date",
1106            Self::XmpInvalid => "xmp-invalid",
1107            Self::XmpRepaired => "xmp-repaired",
1108            Self::InvalidPageLabel => "invalid-page-label",
1109            Self::InvalidEntry => "invalid-entry",
1110            Self::ContentUnknownOperator => "content-unknown-operator",
1111            Self::ContentBadOperands => "content-bad-operands",
1112            Self::ContentUnbalancedQ => "content-unbalanced-q",
1113            Self::ContentUnbalancedBt => "content-unbalanced-bt",
1114            Self::ContentUnbalancedMarked => "content-unbalanced-marked",
1115            Self::ContentSyntax => "content-syntax",
1116            Self::ContentResourceMissing => "content-resource-missing",
1117            Self::InlineImageUnterminated => "inline-image-unterminated",
1118            Self::XobjectCycle => "xobject-cycle",
1119            Self::ContentPathUnpainted => "content-path-unpainted",
1120            Self::FontInvalid => "font-invalid",
1121            Self::CmapInvalid => "cmap-invalid",
1122            Self::UnmappedGlyph => "unmapped-glyph",
1123            Self::ExtractLimitBlocks => "extract-limit-blocks",
1124            Self::ExtractReadingOrderAmbiguous => "extract-reading-order-ambiguous",
1125            Self::ExtractTableAmbiguous => "extract-table-ambiguous",
1126            Self::ExtractTableLimit => "extract-table-limit",
1127            Self::ExtractStructTreeIgnored => "extract-struct-tree-ignored",
1128            Self::ExtractUntaggedContent => "extract-untagged-content",
1129            Self::ExtractNeedsOcr => "extract-needs-ocr",
1130            Self::ExtractColumnOrderUncertain => "extract-column-order-uncertain",
1131            Self::PdfaOneAuthor => "pdfa-one-author",
1132            Self::PdfuaTitleMissing => "pdfua-title-missing",
1133            Self::PdfaInfoMismatch => "pdfa-info-mismatch",
1134            Self::TounicodeConflict => "tounicode-conflict",
1135            Self::WholeFontRebuilt => "whole-font-rebuilt",
1136            Self::FlowKeepBroken => "flow-keep-broken",
1137            Self::MarkdownHtmlIgnored => "markdown-html-ignored",
1138            Self::MarkdownImageMissing => "markdown-image-missing",
1139            Self::CoveredText => "covered-text",
1140            Self::RedactionNotApplied => "redaction-not-applied",
1141            Self::TextInEarlierRevision => "text-in-earlier-revision",
1142        }
1143    }
1144
1145    /// The kind (ADR 0026 §2).
1146    ///
1147    /// Added in 0.2.0.
1148    #[must_use]
1149    pub const fn kind(self) -> ErrorKind {
1150        match self {
1151            Self::MissingHeader => ErrorKind::Input,
1152            Self::XrefRepaired => ErrorKind::Input,
1153            Self::XrefstmIgnored => ErrorKind::Input,
1154            Self::StreamLengthRecovered => ErrorKind::Input,
1155            Self::StaleGeneration => ErrorKind::Input,
1156            Self::PageTreeNodeSkipped => ErrorKind::Input,
1157            Self::PageCountMismatch => ErrorKind::Input,
1158            Self::FlateTruncated => ErrorKind::Input,
1159            Self::ObjstmIndexMismatch => ErrorKind::Input,
1160            Self::ObjectNumberOutOfRange => ErrorKind::Limit,
1161            Self::AesPaddingInvalid => ErrorKind::Security,
1162            Self::PermsMismatch => ErrorKind::Security,
1163            Self::WarningsTruncated => ErrorKind::Limit,
1164            Self::InvalidBox => ErrorKind::Input,
1165            Self::InvalidRotate => ErrorKind::Input,
1166            Self::NameTreeNodeSkipped => ErrorKind::Input,
1167            Self::OutlineCycle => ErrorKind::Input,
1168            Self::OutlineItemSkipped => ErrorKind::Input,
1169            Self::InvalidDate => ErrorKind::Input,
1170            Self::XmpInvalid => ErrorKind::Input,
1171            Self::XmpRepaired => ErrorKind::Input,
1172            Self::InvalidPageLabel => ErrorKind::Input,
1173            Self::InvalidEntry => ErrorKind::Input,
1174            Self::ContentUnknownOperator => ErrorKind::Input,
1175            Self::ContentBadOperands => ErrorKind::Input,
1176            Self::ContentUnbalancedQ => ErrorKind::Input,
1177            Self::ContentUnbalancedBt => ErrorKind::Input,
1178            Self::ContentUnbalancedMarked => ErrorKind::Input,
1179            Self::ContentSyntax => ErrorKind::Input,
1180            Self::ContentResourceMissing => ErrorKind::Input,
1181            Self::InlineImageUnterminated => ErrorKind::Input,
1182            Self::XobjectCycle => ErrorKind::Input,
1183            Self::ContentPathUnpainted => ErrorKind::Input,
1184            Self::FontInvalid => ErrorKind::Input,
1185            Self::CmapInvalid => ErrorKind::Input,
1186            Self::UnmappedGlyph => ErrorKind::Input,
1187            Self::ExtractLimitBlocks => ErrorKind::Limit,
1188            Self::ExtractReadingOrderAmbiguous => ErrorKind::Unsupported,
1189            Self::ExtractTableAmbiguous => ErrorKind::Unsupported,
1190            Self::ExtractTableLimit => ErrorKind::Limit,
1191            Self::ExtractStructTreeIgnored => ErrorKind::Input,
1192            Self::ExtractUntaggedContent => ErrorKind::Input,
1193            Self::ExtractNeedsOcr => ErrorKind::Unsupported,
1194            Self::ExtractColumnOrderUncertain => ErrorKind::Unsupported,
1195            Self::PdfaOneAuthor => ErrorKind::Usage,
1196            Self::PdfuaTitleMissing => ErrorKind::Usage,
1197            Self::PdfaInfoMismatch => ErrorKind::Input,
1198            Self::TounicodeConflict => ErrorKind::Usage,
1199            Self::WholeFontRebuilt => ErrorKind::Usage,
1200            Self::FlowKeepBroken => ErrorKind::Usage,
1201            Self::MarkdownHtmlIgnored => ErrorKind::Unsupported,
1202            Self::MarkdownImageMissing => ErrorKind::Usage,
1203            Self::CoveredText => ErrorKind::Security,
1204            Self::RedactionNotApplied => ErrorKind::Security,
1205            Self::TextInEarlierRevision => ErrorKind::Security,
1206        }
1207    }
1208
1209    /// One lowercase sentence: what happened.
1210    ///
1211    /// Added in 0.2.0.
1212    #[must_use]
1213    pub const fn summary(self) -> &'static str {
1214        match self {
1215            Self::MissingHeader => "no %PDF-x.y header in the first 1,024 bytes; parsing went ahead",
1216            Self::XrefRepaired => "the stored cross-reference data was unusable and was rebuilt by scanning",
1217            Self::XrefstmIgnored => "a hybrid file's /XRefStm could not be read and was ignored",
1218            Self::StreamLengthRecovered => "a stream's /Length was wrong, so its end was found by scanning for endstream",
1219            Self::StaleGeneration => "a reference's generation did not match its xref entry, so it resolved to null",
1220            Self::PageTreeNodeSkipped => "a page-tree node was missing, malformed or too deep, and was skipped",
1221            Self::PageCountMismatch => "the page tree's /Count differs from the number of pages walked",
1222            Self::FlateTruncated => "Flate data was truncated or had a bad checksum; the partial output was kept",
1223            Self::ObjstmIndexMismatch => "an object stream's index was stale and the object was found by searching",
1224            Self::ObjectNumberOutOfRange => "an xref entry above max_object_number was dropped",
1225            Self::AesPaddingInvalid => "AES-encrypted data had a bad length or padding and was kept as stored",
1226            Self::PermsMismatch => "an R5/R6 document's /Perms does not match its /P and /EncryptMetadata",
1227            Self::WarningsTruncated => "more than max_warnings warnings were raised and the rest were dropped",
1228            Self::InvalidBox => "a page boundary box is not four numbers and reads as absent",
1229            Self::InvalidRotate => "a page's /Rotate is not a multiple of 90 and reads as 0",
1230            Self::NameTreeNodeSkipped => "a name- or number-tree node was malformed, repeated or too deep, and was skipped",
1231            Self::OutlineCycle => "an outline item was reached twice; that branch of the walk stopped",
1232            Self::OutlineItemSkipped => "an outline item was missing, not a dictionary or too deep, and was skipped with its subtree",
1233            Self::InvalidDate => "an Info date is not a valid PDF date; the raw string is kept",
1234            Self::XmpInvalid => "the XMP metadata packet is not readable XMP and reads as absent",
1235            Self::XmpRepaired => "the XMP metadata packet had damage other readers read past, and was read the same way",
1236            Self::InvalidPageLabel => "a /PageLabels entry is malformed; the malformed part is dropped",
1237            Self::InvalidEntry => "an entry a view reads is unreadable or of the wrong type and reads as absent",
1238            Self::ContentUnknownOperator => "an operator the spec does not define was skipped outside a BX/EX section",
1239            Self::ContentBadOperands => "an operator had too few operands or operands of the wrong type, or extra ones",
1240            Self::ContentUnbalancedQ => "a Q without a matching q was ignored, or saved graphics states were left open",
1241            Self::ContentUnbalancedBt => "a text object was opened twice, closed outside one, or left open",
1242            Self::ContentUnbalancedMarked => "an EMC without a matching BMC or BDC was ignored, or marked content was left open",
1243            Self::ContentSyntax => "content-stream bytes that are not a token were skipped",
1244            Self::ContentResourceMissing => "an operator named a resource that is missing, of the wrong type or unreadable",
1245            Self::InlineImageUnterminated => "no EI ends an inline image; the rest of the content was skipped",
1246            Self::XobjectCycle => "a Form XObject draws itself, directly or through other forms",
1247            Self::ContentPathUnpainted => "a content stream ended with a path no painting operator ended",
1248            Self::FontInvalid => "a font dictionary has a missing or malformed entry, so its text was decoded with defaults",
1249            Self::CmapInvalid => "a font's CMap or ToUnicode CMap is malformed or names a predefined CMap Lamina PDF has no table for",
1250            Self::UnmappedGlyph => "a font shows glyphs that nothing maps to text",
1251            Self::ExtractLimitBlocks => "a page had more runs of text than the extraction block limit; the runs past it were left out",
1252            Self::ExtractReadingOrderAmbiguous => "a page mixes horizontal and vertical writing, so the order of its blocks is a guess",
1253            Self::ExtractTableAmbiguous => "a table's rules marked out merged cells that aren't rectangles, so its cells were kept unmerged",
1254            Self::ExtractTableLimit => "a page's ruling lines would make a table bigger than the extraction's cell limit; those lines gave no table",
1255            Self::ExtractStructTreeIgnored => "a tagged page's structure tree covered too little of its text, or its order jumped back across columns too often, so the layout gave the reading order",
1256            Self::ExtractUntaggedContent => "a page read in structure-tree order has visible text that is neither in the tree nor an artifact; it follows the tree's blocks, in layout order",
1257            Self::ExtractNeedsOcr => "a page has no usable text layer: it is an image (with or without an invisible OCR layer), outlined glyphs, or glyphs without Unicode, so its extracted text is empty or unreliable",
1258            Self::ExtractColumnOrderUncertain => "the layout rules had to guess how a page's columns are read, so its blocks may be in the wrong order; the blocks concerned have a lower confidence",
1259            Self::PdfaOneAuthor => "the file claims PDF/A-1, which allows one author, and its metadata lists more",
1260            Self::PdfuaTitleMissing => "the file claims PDF/UA-1, which requires a title in its metadata, and it has none",
1261            Self::PdfaInfoMismatch => "the file claims PDF/A, which requires the Info dictionary and the XMP packet to agree, and they differ",
1262            Self::TounicodeConflict => "one glyph was used for two different texts; ToUnicode keeps the first",
1263            Self::WholeFontRebuilt => "a font that forbids subsetting was rebuilt with every glyph kept",
1264            Self::FlowKeepBroken => "blocks kept together are taller than a page, so the flow split them",
1265            Self::MarkdownHtmlIgnored => "the Markdown holds raw HTML, which the PDF leaves out",
1266            Self::MarkdownImageMissing => "the Markdown names an image that wasn't supplied, so the PDF leaves it out",
1267            Self::CoveredText => "a page draws text and then paints a shape, an image or an annotation over it, so the text is hidden but still in the file",
1268            Self::RedactionNotApplied => "a page has redaction marks that were never applied, so the text under them is still in the file",
1269            Self::TextInEarlierRevision => "an earlier revision of the file holds text that the latest revision no longer has",
1270        }
1271    }
1272
1273    /// The hint (ADR 0026 §5), with its `{limit}`/`{option}` parameters unfilled.
1274    ///
1275    /// Added in 0.2.0.
1276    #[must_use]
1277    pub const fn hint(self) -> &'static str {
1278        match self {
1279            Self::MissingHeader => "nothing to do if the document reads correctly; open in strict mode to refuse such files",
1280            Self::XrefRepaired => "check the result; save with a full rewrite, since an incremental update refuses a repaired base",
1281            Self::XrefstmIgnored => "nothing to do; the classic xref table is used instead",
1282            Self::StreamLengthRecovered => "nothing to do; a full rewrite writes the correct length",
1283            Self::StaleGeneration => "nothing to do; the reference is treated as missing",
1284            Self::PageTreeNodeSkipped => "check the page count: pages under the skipped node are missing",
1285            Self::PageCountMismatch => "nothing to do; Lamina PDF uses the walked page count",
1286            Self::FlateTruncated => "check the affected content: the end of the stream may be missing",
1287            Self::ObjstmIndexMismatch => "nothing to do; a full rewrite writes a correct index",
1288            Self::ObjectNumberOutOfRange => "raise max_object_number in Limits only if you trust the input",
1289            Self::AesPaddingInvalid => "treat the affected strings and streams as suspect: they may have been tampered with",
1290            Self::PermsMismatch => "treat the document's permissions as untrusted",
1291            Self::WarningsTruncated => "raise max_warnings in Limits if you need the full list",
1292            Self::InvalidBox => "nothing to do; the page uses the next box in the fallback chain",
1293            Self::InvalidRotate => "set the page rotation explicitly if 0 is wrong",
1294            Self::NameTreeNodeSkipped => "check the tree's entries: those under the skipped node are missing",
1295            Self::OutlineCycle => "nothing to do; the outline is read without the loop",
1296            Self::OutlineItemSkipped => "check the outline: the skipped item and its children are missing",
1297            Self::InvalidDate => "read the raw value from the Info view if you need it",
1298            Self::XmpInvalid => "nothing to do; a metadata edit asks before replacing it",
1299            Self::XmpRepaired => "nothing to do; a metadata edit writes the declarations the packet left out",
1300            Self::InvalidPageLabel => "nothing to do; affected pages fall back to decimal labels",
1301            Self::InvalidEntry => "nothing to do; the view uses the entry's default",
1302            Self::ContentUnknownOperator => "nothing to do; check the page's rendering if the operator mattered",
1303            Self::ContentBadOperands => "nothing to do; the operator was skipped or used its last operands",
1304            Self::ContentUnbalancedQ => "nothing to do; the graphics state was restored as the spec intends",
1305            Self::ContentUnbalancedBt => "nothing to do; text operators outside a text object were handled tolerantly",
1306            Self::ContentUnbalancedMarked => "check tagged-content results: marked-content sequences were closed for you",
1307            Self::ContentSyntax => "check the page's content: the bytes around the reported offset were skipped",
1308            Self::ContentResourceMissing => "check the page's resources: the operator ran without the resource or was skipped",
1309            Self::InlineImageUnterminated => "check the page's content: everything after the inline image is missing",
1310            Self::XobjectCycle => "nothing to do; the inner Do was skipped",
1311            Self::ContentPathUnpainted => "nothing to do; the unpainted path was dropped as the spec intends",
1312            Self::FontInvalid => "nothing to do; extracted text or positions for that font may be off",
1313            Self::CmapInvalid => "nothing to do; the bad entries were skipped and the rest of the CMap is used",
1314            Self::UnmappedGlyph => "nothing to do; those glyphs extract as U+FFFD (the file needs a ToUnicode CMap)",
1315            Self::ExtractLimitBlocks => "raise ExtractLimits::max_blocks_per_page if the page really has that many blocks",
1316            Self::ExtractReadingOrderAmbiguous => "nothing to do; check the order of that page's blocks, or ask for content order",
1317            Self::ExtractTableAmbiguous => "nothing to do; check that table's cells, whose text may be split across neighbours",
1318            Self::ExtractTableLimit => "raise ExtractLimits::max_table_cells if the page really has a table that big",
1319            Self::ExtractStructTreeIgnored => "nothing to do; ReadingOrder::Tagged uses the tree anyway",
1320            Self::ExtractUntaggedContent => "nothing to do; tag that text in the file to give it a place in the reading order",
1321            Self::ExtractNeedsOcr => "run OCR or a vision model on this page; the page's textLayer in the JSON says which case it is",
1322            Self::ExtractColumnOrderUncertain => "check the page, or send it to a layout model; the warning's reason says which guess was made",
1323            Self::PdfaOneAuthor => "keep one author (join the names into one), or save knowing the file no longer meets PDF/A-1",
1324            Self::PdfuaTitleMissing => "give the document a title before saving, or save knowing the file no longer meets PDF/UA-1",
1325            Self::PdfaInfoMismatch => "edit the metadata with setMetadata, which writes both, or remove the Info entries that differ",
1326            Self::TounicodeConflict => "mark the second occurrence with /ActualText so extraction gets its text",
1327            Self::WholeFontRebuilt => "check that the font's licence allows this, or use a static TrueType or CFF version",
1328            Self::FlowKeepBroken => "split the keep group or drop keep-with-next on a heading chain, or use a taller page",
1329            Self::MarkdownHtmlIgnored => "write the content in Markdown instead of HTML, or remove the HTML",
1330            Self::MarkdownImageMissing => "pass the image's bytes with MarkdownBuildOptions::with_image under the path the Markdown uses",
1331            Self::CoveredText => "remove the text itself with a tool that deletes what a redaction covers, then save a full rewrite",
1332            Self::RedactionNotApplied => "apply the redactions in a tool that removes what they cover, then save a full rewrite",
1333            Self::TextInEarlierRevision => "save the file as a full rewrite, which keeps only the latest revision",
1334        }
1335    }
1336
1337    /// The code's explain page (`docsUrl`, ADR 0026 §6).
1338    ///
1339    /// Added in 0.2.0.
1340    #[must_use]
1341    pub fn docs_url(self) -> String {
1342        format!("{DOCS_URL_BASE}{}{DOCS_URL_SUFFIX}", self.as_str())
1343    }
1344}