Skip to main content

f_office_docx/
warnings.rs

1//! The warnings of a DOCX layout: what it left out of the file, or drew in another way than
2//! the file asks, while it went on with the rest. A warning holds no content of the document,
3//! only the names that the file uses to point at a part or a font, as `f_office_warnings::Name`
4//! keeps them.
5
6use std::fmt;
7
8use f_office_emf::Frame;
9use f_office_fonts::{NotReadCause, OutlineError, ShapeFailure};
10use f_office_paint::{Image, ImageFormat};
11use f_office_units::Length;
12use f_office_warnings::Name;
13
14use crate::Fonts;
15use crate::text::FontNotes;
16
17/// What the player of an EMF or WMF picture left out of it, or drew in another way than it
18/// asks, which [`Warning::Metafile`] holds.
19pub use f_office_emf::Warning as MetafileWarning;
20
21/// The type of a record of an EMF or WMF picture in the numbering of its format, which a
22/// [`MetafileWarning`] of a record names.
23pub use f_office_emf::RecordType as MetafileRecordType;
24
25/// What a reader of DrawingML read in another way than the file asks, which
26/// [`Warning::DrawingMl`] holds.
27pub use f_office_drawingml::Warning as DrawingMlWarning;
28
29/// A feature of DrawingML that F-Office does not draw, which a [`DrawingMlWarning`] names. The
30/// features of VML, WordprocessingML and OMML are [`Feature`]: one set of features for each
31/// crate, as each crate has its own warnings.
32pub use f_office_drawingml::Feature as DrawingMlFeature;
33
34/// What a DOCX layout left out or drew in another way, and went on.
35#[derive(Clone, Debug, PartialEq, Eq, Hash)]
36#[non_exhaustive]
37pub enum Warning {
38    /// A part that the layout does without: its name in the package, and why.
39    PartSkipped {
40        /// The part.
41        part: Name,
42        /// Why.
43        reason: Reason,
44    },
45    /// A part whose relationships do not read, so that the layout draws it without what they
46    /// name, such as its pictures: the part's name, or `/` for the package's own relationships.
47    RelationshipsSkipped {
48        /// The part.
49        part: Name,
50    },
51    /// A drawing that the layout leaves out: its kind, the part that holds it (or, when its
52    /// relationship ID names no part, the part that names it, and for a drawing that the reader
53    /// of a part leaves out, that part), and why.
54    DrawingSkipped {
55        /// The kind of drawing.
56        drawing: Drawing,
57        /// The part.
58        part: Name,
59        /// Why.
60        reason: Reason,
61    },
62    /// The polygon of a floating drawing's tight or through wrap (`wp:wrapPolygon`) that the
63    /// layout leaves out, so that the text keeps out of the drawing's box, as for a wrap
64    /// without a polygon: the part that holds the drawing, and why.
65    WrapPolygonSkipped {
66        /// The part.
67        part: Name,
68        /// Why.
69        reason: Reason,
70    },
71    /// A page border's side of an art style, such as `apples`, that the layout leaves out
72    /// because the caller gave no picture of the style at the side's size
73    /// ([`crate::ArtPictures`]): the style and the size.
74    ArtBorderNotDrawn {
75        /// The art style, as the schema spells it.
76        style: &'static str,
77        /// The side's size, in points (`w:sz`).
78        size: u32,
79    },
80    /// A font family that the document asks for and that a face of another family draws: the
81    /// family asked for, and the family and version of the face that draws it, when the caller
82    /// knows them, with how its layout stands to the family's.
83    FontSubstituted {
84        /// The family that the document asks for.
85        asked: Name,
86        /// The family of the face that draws it, `None` when the caller does not know it
87        /// ([`crate::Fonts::family_name`]).
88        used: Option<Name>,
89        /// The version of the face that draws it, such as "7.06.1", `None` when the caller does
90        /// not know it ([`crate::Fonts::face_version`]).
91        version: Option<Name>,
92        /// How the layout of the face that draws it stands to the family's.
93        layout: SubstituteLayout,
94    },
95    /// Text that the layout leaves out because the caller has no face for it: none of the
96    /// family that it asks for, nor of the names that stand for that family, nor of a family
97    /// that Word draws in its place.
98    TextNotDrawn {
99        /// The family that the text asks for, `None` for text that names no font.
100        asked: Option<Name>,
101        /// The families that were tried, in order, each with the faces that stand in for it.
102        tried: Vec<Name>,
103    },
104    /// A font that the layout looks for, other than for text that it leaves out, when the
105    /// caller has no face of it, nor of the names that stand for it, nor of a family that Word
106    /// draws in its place: for a paragraph mark, a tab or a line break, which then takes no
107    /// face, so that its height is not part of its line's, or for a character that its run's
108    /// font lacks, which then does not take the family. A font whose text the layout leaves
109    /// out gives [`Warning::TextNotDrawn`] only.
110    FontNotFound {
111        /// The family looked for, `None` for a piece that names no font.
112        asked: Option<Name>,
113        /// The families that were tried, in order, each with the faces that stand in for it.
114        tried: Vec<Name>,
115    },
116    /// A font whose text of a shaped script, such as Arabic, the caller could not shape, so
117    /// that each of its characters has the glyph of the font's character map.
118    ScriptNotShaped {
119        /// The family of the font, `None` when the caller does not know it
120        /// ([`crate::Fonts::family_name`]).
121        font: Option<Name>,
122        /// Why the caller could not shape it.
123        cause: ShapeFailure,
124    },
125    /// A font file whose bytes did not load when the caller chose one of its faces, so that
126    /// the face counted as missing: the file's path in its font folder, and why.
127    FontFileNotRead {
128        /// The file's path in its font folder.
129        file: Name,
130        /// Why the file did not load.
131        cause: NotReadCause,
132    },
133    /// A font with a glyph whose ink the layout asked for, as for an equation, and that the
134    /// caller could not measure, so that the layout places the glyph as one without ink.
135    InkNotMeasured {
136        /// The family of the font, `None` when the caller does not know it
137        /// ([`crate::Fonts::family_name`]).
138        font: Option<Name>,
139        /// Why the caller could not measure it.
140        cause: OutlineError,
141    },
142    /// A value that does not read as its type, such as a length written as text: the part, the
143    /// element and the place in the element that hold it, and the reading that the layout took
144    /// in its place.
145    InvalidValue {
146        /// The part.
147        part: Name,
148        /// The element that holds the value.
149        element: Name,
150        /// Where the value lies in the element.
151        place: ValuePlace,
152        /// The reading that the layout took.
153        read_as: ReadAs,
154    },
155    /// A value that is a value of its type and that the layout draws as another value of the
156    /// type, such as a striped shading that it draws as its fill alone: the part, the element
157    /// and the place in the element that hold it, and the value, a name of the type.
158    ValueNotSupported {
159        /// The part.
160        part: Name,
161        /// The element that holds the value.
162        element: Name,
163        /// Where the value lies in the element.
164        place: ValuePlace,
165        /// The value, a name of its type.
166        value: Name,
167    },
168    /// A normal footnote or endnote whose ID has the number of an earlier normal note of its
169    /// part: the part, and the number. The layout keeps one of the two, as the target's quirk
170    /// `RepeatedNoteId` says, and a reference of the number finds it. The
171    /// warning comes once for each note that repeats a number.
172    NoteIdRepeated {
173        /// The part.
174        part: Name,
175        /// The number of the ID.
176        id: i64,
177    },
178    /// A reference to a footnote or an endnote (`w:footnoteReference`, `w:endnoteReference`)
179    /// whose ID no normal note of the footnotes or the endnotes part has: the part of the
180    /// reference, the kind of note, and the number of the ID. The reference's number is drawn,
181    /// and no note. The warning comes once for each such reference.
182    NoteMissing {
183        /// The part of the reference.
184        part: Name,
185        /// Whether it refers to a footnote or an endnote.
186        note: NoteKind,
187        /// The number of the ID.
188        id: i64,
189    },
190    /// A namespace prefix that a part, or a relationships part, uses on an element or an
191    /// attribute without a declaration, which XML's namespaces forbid: the part, and the
192    /// prefix. The reader goes on, once for each prefix of a part: an element of the prefix,
193    /// with what it holds, is none that a reader takes, and an attribute of it reads as an
194    /// attribute without a prefix ([`f_office_xml::Document::undeclared_prefixes`]).
195    UndeclaredPrefix {
196        /// The part.
197        part: Name,
198        /// The prefix.
199        prefix: Name,
200    },
201    /// A value of the file beyond a limit of F-Office's work, which the reader takes as the
202    /// limit before it goes on, such as a table of more grid columns than the layout takes: the
203    /// part, and the limit.
204    LimitReached {
205        /// The part.
206        part: Name,
207        /// The limit.
208        limit: Limit,
209    },
210    /// A record of an EMF or WMF picture that the layout leaves out or draws in another way:
211    /// the picture's part, and what its player warns of.
212    Metafile {
213        /// The part of the picture.
214        part: Name,
215        /// What the player warns of.
216        warning: MetafileWarning,
217    },
218    /// A value of DrawingML that a reader of DrawingML read in another way than the file asks,
219    /// such as a line width that does not read: the part, and what the reader warns of.
220    DrawingMl {
221        /// The part.
222        part: Name,
223        /// What the reader of DrawingML warns of.
224        warning: DrawingMlWarning,
225    },
226    /// A feature of VML, WordprocessingML or OMML that F-Office does not draw, which it draws
227    /// in another way or leaves out, such as the rotation of a VML shape: the part, and the
228    /// feature.
229    FeatureNotSupported {
230        /// The part.
231        part: Name,
232        /// The feature.
233        feature: Feature,
234    },
235}
236
237/// A feature of VML, WordprocessingML or OMML that F-Office does not draw, which
238/// [`Warning::FeatureNotSupported`] names. Each says what F-Office draws in its place. The
239/// features of DrawingML are [`DrawingMlFeature`].
240///
241/// The warning names the part that sets the feature: the part of the layer of the cascade that
242/// sets the property that shows it, such as the styles part for a style or the numbering part
243/// for a list level; the main document's for a setting that acts by default where no layer
244/// sets it, such as hanging punctuation; and the part that holds a table for the own properties
245/// of its rows and cells. The readers of the parts give the features that act where they are
246/// read, such as a rotation of a VML shape or a section's text direction. The layout gives the
247/// features of text, paragraphs, frames and tables where it lays them out: a feature of runs
248/// once for each paragraph whose text draws it and each part that sets it, with the list label
249/// as a run of its paragraph, so that a style, a list level or a paragraph mark that draws no
250/// text gives none; and a feature of a table once for each table and part.
251#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
252#[non_exhaustive]
253pub enum Feature {
254    /// A VML shape whose outline is other than a rectangle, a rounded rectangle, an ellipse or
255    /// a line: a `v:shape` of a type (`type`) other than the text box, the rectangle and the
256    /// straight connector, whose outline, fill and line are not drawn, or a `v:shape` with its
257    /// own path (`path`), which is drawn as a rectangle. Its text box is laid out.
258    VmlGeometry,
259    /// A rotation of a VML shape or picture other than a whole number of quarter turns
260    /// (`rotation` in its CSS `style`): the shape or the picture is drawn upright.
261    VmlRotation,
262    /// A color change of a VML picture in its text line (`gain`, `blacklevel`, `grayscale` or
263    /// `bilevel` of `v:imagedata`): the picture keeps its own colors.
264    VmlPictureColors,
265    /// A text box of a VML picture in its text line (a `v:textbox` with `w:txbxContent` of a
266    /// `v:shape` whose `v:imagedata` names an image): the picture is drawn without its text
267    /// box. One warning for each such shape.
268    VmlPictureTextBox,
269    /// A fill of a run's text other than a solid opaque one (`w14:textFill`): an empty fill, a
270    /// gradient, or a solid fill of a color that is not opaque. The text is drawn in its color
271    /// (`w:color`). One warning for each paragraph whose text shows it, for each part that sets it.
272    TextFill,
273    /// A glow, shadow, reflection or 3-D look of a run's text that draws something
274    /// (`w14:glow`, `w14:shadow`, `w14:reflection`, `w14:scene3d`, `w14:props3d`), or an
275    /// outline, shadow, emboss or imprint of a run's text that is on (`w:outline`, `w:shadow`,
276    /// `w:emboss`, `w:imprint`): the text is drawn without it. One warning for each paragraph whose text shows it, for each part that sets it.
277    TextEffect,
278    /// A fill of the line along the outline of a run's glyphs (`w14:textOutline`) other than a
279    /// solid opaque one: a gradient (`w14:gradFill`), which is not drawn, or a solid fill of a
280    /// color that is not opaque, which is drawn opaque. One warning for each paragraph whose text shows it, for each part that sets it.
281    TextOutlineFill,
282    /// A structure of an equation that F-Office does not lay out as a structure: a box that acts
283    /// as an operator or holds a break (`m:box` with `m:opEmu` or `m:brk`). Its content is laid
284    /// out in a row, without the structure's marks and places.
285    MathStructure,
286    /// A double strike through a run's text that is on (`w:dstrike`): a target whose quirk
287    /// `UnderlineForms` is `AllSingle` draws it as a single strike. One warning for each
288    /// paragraph whose text shows it, for each part that sets it.
289    DoubleStrike,
290    /// A border around a run's text of a line style other than none (`w:bdr`): the text is
291    /// drawn without it. One warning for each paragraph whose text shows it, for each part that sets it.
292    TextBorder,
293    /// A width that a run's text or a cell's text is fitted into (`w:fitText` above 0,
294    /// `w:tcFitText` on): the text keeps its own spacing. One warning for each paragraph whose
295    /// text shows it, and one for each table with such cells, for each part that sets it.
296    FitText,
297    /// An emphasis mark of a run's text (`w:em` other than `none`), or two lines in one or text
298    /// turned in its line (`w:eastAsianLayout` with `w:combine` or `w:vert` on): the text is
299    /// laid out in its line without them. One warning for each paragraph whose text shows it, for each part that sets it.
300    EastAsianLayout,
301    /// Automatic hyphenation of the document (`w:autoHyphenation` on in the settings) on a
302    /// target whose configuration hyphenates no language: no word is hyphenated at the end of a
303    /// line.
304    AutoHyphenation,
305    /// A shading of a whole table that gives a fill or a pattern (`w:shd` of `w:tblPr`, also in a
306    /// table style, or of a row's `w:tblPrEx`, which takes the table's place in the row): only
307    /// the shading of the cells is drawn. One warning for each table, for each part that sets
308    /// the shading of one of its rows; a table style that no table uses gives none.
309    TableShading,
310    /// A section's text direction other than upright from left to right (`w:textDirection` of
311    /// `w:sectPr` other than `lrTb` and `tb`): the section's text is laid out upright.
312    SectionTextDirection,
313    /// A place of a section's footnotes other than the bottom of the page (`w:pos` of
314    /// `w:footnotePr` of the section or the settings other than `pageBottom`), in a document
315    /// that holds footnotes: they stand at the bottom of the page.
316    FootnotePosition,
317    /// A place of a section's endnotes at the end of the section (`w:pos` of `w:endnotePr` of
318    /// the section or the settings `sectEnd`), in a document that holds endnotes: they follow
319    /// the text at the end of the document.
320    EndnotePosition,
321    /// A paragraph's text alignment at the top, the middle or the bottom of its lines
322    /// (`w:textAlignment` of `top`, `center` or `bottom`), on a line whose pieces have two
323    /// heights, such as runs of two font sizes or a picture beside text: every piece of the
324    /// line stands on one baseline. One warning for each paragraph that holds such a line; a
325    /// line of one height gives none.
326    TextAlignment,
327    /// Hanging punctuation (`w:overflowPunct`, on by default): a punctuation mark of East
328    /// Asian text, of its language's list in [MS-OI29500] 2.1.52, that does not fit at the end
329    /// of a line goes to the next line with the text before it, where Word lets it stand past
330    /// the end of the line. One warning for each paragraph that holds such a line, with the part
331    /// that sets `w:overflowPunct`, or the main document's where no layer sets it.
332    HangingPunctuation,
333    /// A paragraph's text direction that turns its text (`w:textDirection` of `w:pPr` other
334    /// than `lrTb` and `tb`), in a frame, where Word turns the paragraph ([MS-OI29500] 2.1.63):
335    /// the paragraph is laid out upright. One warning for each such paragraph, a paragraph of a
336    /// header or a footer once whatever the number of its pages. Outside frames Word lays the
337    /// paragraph out upright too, and it gives none.
338    ParagraphTextDirection,
339    /// A text box whose text is turned (`vert` of `wps:bodyPr` other than `horz`, `layout-flow`
340    /// of the style of `v:textbox` other than `horizontal`, or a VML or DrawingML shape turned
341    /// by whole quarter turns other than none, unless `upright` of `wps:bodyPr` keeps the text
342    /// upright): its text is laid out upright. One warning for each such box.
343    TurnedTextBox,
344    /// Mirrored indents (`w:mirrorIndents` on) of a paragraph whose left and right indents
345    /// differ, which make them the inside and outside indents of mirrored pages: the left
346    /// indent stays on the left of every page. One warning for each such paragraph.
347    MirrorIndents,
348    /// A right indent that moves to the section's grid of characters (`w:adjustRightInd`, on by
349    /// default, in a paragraph on the grid of a section whose `w:docGrid` is of the type
350    /// `linesAndChars`): the right indent stays as set. One warning for each such paragraph,
351    /// with the part that sets `w:adjustRightInd`, or the main document's where no layer sets
352    /// it.
353    GridRightIndent,
354    /// A frame of the body that overlaps an earlier frame of its page in the layout, where one
355    /// of the two must not overlap other frames (`w:suppressOverlap` on): Word moves it, and it
356    /// stays at its own place. One warning for each such frame, with the part that sets
357    /// `w:suppressOverlap` for it, or else for the earlier frame.
358    FrameOverlap,
359    /// A paragraph of a text box whose lines take part in the box's tight wrap
360    /// (`w:textboxTightWrap` other than `none`): the text around the box wraps around its
361    /// rectangle. One warning for each such paragraph.
362    TextBoxTightWrap,
363    /// A row's own alignment (`w:jc` of `w:trPr` or of `w:tblPrEx`) other than its table's,
364    /// in a table narrower than its column: the row stands where the table's alignment puts
365    /// the table. One warning for each such row, with the part that holds the table.
366    RowAlignment,
367    /// A row's own cell spacing (`w:tblCellSpacing` of `w:trPr` or of `w:tblPrEx`) other than
368    /// its table's: the row's cells keep the table's spacing. One warning for each such row, with
369    /// the part that holds the table.
370    RowCellSpacing,
371    /// A paragraph of an HTML div (`w:divId`) that has, or lies in a div that has, a margin
372    /// other than 0 or a border line (`w:div` of the web settings part): the paragraph is laid
373    /// out without them. One warning for each such paragraph.
374    HtmlDiv,
375    /// A drawing group's own turn or flip (its **group transform**: `rot`, `flipH` and `flipV` of
376    /// the `a:xfrm` of `wpg:grpSpPr`), which says what is not drawn: the group's parts and their
377    /// text are drawn upright and unflipped, at their places before the turn. One warning for
378    /// each such group, an inner group too.
379    GroupTransform(GroupTransform),
380    /// A character of Word's symbol extension (`w16se:symEx`), a character in a font of its
381    /// own, such as an emoji, in a choice of alternate content that F-Office takes: nothing is
382    /// drawn in its place. One warning for each such character.
383    SymbolExtension,
384    /// A choice of alternate content (`mc:Choice`) that F-Office passes over because it does not
385    /// read a namespace that the choice requires, and that holds no drawing: a later choice or
386    /// the fallback is drawn in its place, or nothing. One warning for each such choice.
387    AlternateChoice,
388    /// Text in a bidirectional embedding or override of a paragraph (`w:dir`, `w:bdo`): its
389    /// runs are left out. One warning for each such element.
390    BidirectionalEmbedding,
391    /// A phonetic guide over a run's text (`w:ruby`): its guide text and its base text are left
392    /// out. One warning for each such guide.
393    Ruby,
394    /// A page number written as an element of a run (`w:pgNum`), not as a field: no number is
395    /// drawn in its place. One warning for each such element.
396    PageNumberElement,
397    /// A part of the current date written as an element of a run (`w:dayShort`, `w:dayLong`,
398    /// `w:monthShort`, `w:monthLong`, `w:yearShort`, `w:yearLong`): nothing is drawn in its
399    /// place. One warning for each such element.
400    DateBlock,
401    /// A border between the paragraphs of a group of the same borders (`w:between` of
402    /// `w:pBdr`) with a line: it is not drawn. One warning for each paragraph or style whose
403    /// own borders hold it.
404    BetweenBorder,
405    /// A bar border beside a paragraph (`w:bar` of `w:pBdr`) with a line: it is not drawn. One
406    /// warning for each paragraph or style whose own borders hold it.
407    BarBorder,
408    /// An element in an equation outside Office Math that F-Office does not read: not a
409    /// tracked change, a hyperlink, a smart tag, custom XML, a content control or a mark that
410    /// draws nothing. What it holds is left out. One warning for each such element.
411    MathElement,
412    /// The title, the legend or labels of the axes of a chart that F-Office draws (`c:title`,
413    /// `c:legend`, the labels of `c:catAx` and `c:valAx`), which F-Office does not draw: the
414    /// chart is drawn without them. One warning for each chart drawn without a part of its text.
415    ChartLabels,
416    /// The picture bullet of a list label (`w:lvlPicBulletId`), which F-Office does not draw:
417    /// the label takes no room and nothing is drawn in its place. One warning for each
418    /// paragraph with such a label.
419    PictureBullet,
420    /// The mark of a footnote or an endnote (`w:footnoteRef`, `w:endnoteRef`) in a text box of
421    /// its note, or the mark of an endnote in a frame of its note, which F-Office does not number
422    /// from the note: the mark shows 1. One warning for each such text box or frame.
423    NoteMarkInBox,
424    /// The data labels of a chart that F-Office draws (`c:dLbls`, `c:dLbl`), which F-Office
425    /// does not draw: the chart is drawn without them. One warning for each chart whose series
426    /// show data labels.
427    DataLabels,
428}
429
430/// What F-Office does not draw of a drawing group's own **group transform**.
431#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
432#[non_exhaustive]
433pub enum GroupTransform {
434    /// A turn other than none, at any angle (`rot`).
435    Turn,
436    /// A flip across, down or both (`flipH`, `flipV`).
437    Flip,
438    /// A turn and a flip.
439    TurnAndFlip,
440}
441
442impl GroupTransform {
443    /// Every value, in the order of their declaration.
444    pub const ALL: [Self; 3] = [Self::Turn, Self::Flip, Self::TurnAndFlip];
445}
446
447impl Feature {
448    /// Every feature, in the order of their declaration, each kind once: a feature that says
449    /// what is not drawn takes its first value, such as [`GroupTransform::Turn`].
450    pub const ALL: [Self; 42] = [
451        Self::VmlGeometry,
452        Self::VmlRotation,
453        Self::VmlPictureColors,
454        Self::VmlPictureTextBox,
455        Self::TextFill,
456        Self::TextEffect,
457        Self::TextOutlineFill,
458        Self::MathStructure,
459        Self::DoubleStrike,
460        Self::TextBorder,
461        Self::FitText,
462        Self::EastAsianLayout,
463        Self::AutoHyphenation,
464        Self::TableShading,
465        Self::SectionTextDirection,
466        Self::FootnotePosition,
467        Self::EndnotePosition,
468        Self::TextAlignment,
469        Self::HangingPunctuation,
470        Self::ParagraphTextDirection,
471        Self::TurnedTextBox,
472        Self::MirrorIndents,
473        Self::GridRightIndent,
474        Self::FrameOverlap,
475        Self::TextBoxTightWrap,
476        Self::RowAlignment,
477        Self::RowCellSpacing,
478        Self::HtmlDiv,
479        Self::GroupTransform(GroupTransform::Turn),
480        Self::SymbolExtension,
481        Self::AlternateChoice,
482        Self::BidirectionalEmbedding,
483        Self::Ruby,
484        Self::PageNumberElement,
485        Self::DateBlock,
486        Self::BetweenBorder,
487        Self::BarBorder,
488        Self::MathElement,
489        Self::ChartLabels,
490        Self::PictureBullet,
491        Self::NoteMarkInBox,
492        Self::DataLabels,
493    ];
494
495    /// The kind of the warning of the feature, as [`Warning::kind`] gives it.
496    #[must_use]
497    pub fn kind(self) -> &'static str {
498        match self {
499            Self::VmlGeometry => "vml-geometry-not-supported",
500            Self::VmlRotation => "vml-rotation-not-supported",
501            Self::VmlPictureColors => "vml-picture-colors-not-supported",
502            Self::VmlPictureTextBox => "vml-picture-text-box-not-supported",
503            Self::TextFill => "text-fill-not-supported",
504            Self::TextEffect => "text-effect-not-supported",
505            Self::TextOutlineFill => "text-outline-fill-not-supported",
506            Self::MathStructure => "math-structure-not-supported",
507            Self::DoubleStrike => "double-strike-not-supported",
508            Self::TextBorder => "text-border-not-supported",
509            Self::FitText => "fit-text-not-supported",
510            Self::EastAsianLayout => "east-asian-layout-not-supported",
511            Self::AutoHyphenation => "auto-hyphenation-not-supported",
512            Self::TableShading => "table-shading-not-supported",
513            Self::SectionTextDirection => "section-text-direction-not-supported",
514            Self::FootnotePosition => "footnote-position-not-supported",
515            Self::EndnotePosition => "endnote-position-not-supported",
516            Self::TextAlignment => "text-alignment-not-supported",
517            Self::HangingPunctuation => "hanging-punctuation-not-supported",
518            Self::ParagraphTextDirection => "paragraph-text-direction-not-supported",
519            Self::TurnedTextBox => "turned-text-box-not-supported",
520            Self::MirrorIndents => "mirror-indents-not-supported",
521            Self::GridRightIndent => "grid-right-indent-not-supported",
522            Self::FrameOverlap => "frame-overlap-not-supported",
523            Self::TextBoxTightWrap => "text-box-tight-wrap-not-supported",
524            Self::RowAlignment => "row-alignment-not-supported",
525            Self::RowCellSpacing => "row-cell-spacing-not-supported",
526            Self::HtmlDiv => "html-div-not-supported",
527            Self::GroupTransform(_) => "group-transform-not-supported",
528            Self::SymbolExtension => "symbol-extension-not-supported",
529            Self::AlternateChoice => "alternate-choice-not-supported",
530            Self::BidirectionalEmbedding => "bidirectional-embedding-not-supported",
531            Self::Ruby => "ruby-not-supported",
532            Self::PageNumberElement => "page-number-element-not-supported",
533            Self::DateBlock => "date-block-not-supported",
534            Self::BetweenBorder => "between-border-not-supported",
535            Self::BarBorder => "bar-border-not-supported",
536            Self::MathElement => "math-element-not-supported",
537            Self::ChartLabels => "chart-labels-not-supported",
538            Self::PictureBullet => "picture-bullet-not-supported",
539            Self::NoteMarkInBox => "note-mark-in-box-not-supported",
540            Self::DataLabels => "data-labels-not-supported",
541        }
542    }
543}
544
545impl fmt::Display for Feature {
546    #[expect(
547        clippy::too_many_lines,
548        reason = "one arm for each feature of the closed set, which says what is drawn in its place"
549    )]
550    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551        f.write_str(match self {
552            Self::VmlGeometry => {
553                "a VML shape of an outline other than a rectangle, a rounded rectangle, an \
554                 ellipse or a line is not supported, and the shape is drawn as a rectangle or \
555                 not at all"
556            }
557            Self::VmlRotation => {
558                "a rotation of a VML shape or picture other than a whole number of quarter turns \
559                 is not supported, and it is drawn upright"
560            }
561            Self::VmlPictureColors => {
562                "a color change of a VML picture in its text line is not supported, and the \
563                 picture keeps its own colors"
564            }
565            Self::VmlPictureTextBox => {
566                "a text box of a VML picture in its text line is not supported, and the picture \
567                 is drawn without it"
568            }
569            Self::TextFill => {
570                "a fill of text other than a solid opaque one is not supported, and the text is \
571                 drawn in its color"
572            }
573            Self::TextEffect => {
574                "a glow, shadow, reflection, 3-D look, outline, emboss or imprint of text is not \
575                 supported, and the text is drawn without it"
576            }
577            Self::TextOutlineFill => {
578                "an outline of text whose fill is other than a solid opaque one is not supported, \
579                 and a gradient outline is not drawn and a transparent one is drawn opaque"
580            }
581            Self::MathStructure => {
582                "a structure of an equation such as a radical, an accent or a matrix is not \
583                 supported, and its content is laid out in a row"
584            }
585            Self::DoubleStrike => {
586                "a double strike through text is not supported on a target that does not draw \
587                 its own form, and it is drawn as a single strike"
588            }
589            Self::TextBorder => {
590                "a border around text is not supported, and the text is drawn without it"
591            }
592            Self::FitText => {
593                "text fitted into a width is not supported, and the text keeps its own spacing"
594            }
595            Self::EastAsianLayout => {
596                "an emphasis mark, two lines in one or text turned in its line is not supported, \
597                 and the text is laid out in its line without them"
598            }
599            Self::AutoHyphenation => {
600                "automatic hyphenation is not supported, and no word is hyphenated at the end of a \
601                 line"
602            }
603            Self::TableShading => {
604                "the shading of a whole table is not supported, and only the shading of its cells \
605                 is drawn"
606            }
607            Self::SectionTextDirection => {
608                "a section's vertical text direction is not supported, and its text is laid out \
609                 upright"
610            }
611            Self::FootnotePosition => {
612                "a place of a section's footnotes other than the bottom of the page is not \
613                 supported, and they stand at the bottom of the page"
614            }
615            Self::EndnotePosition => {
616                "a place of a section's endnotes at the end of the section is not supported, and \
617                 they follow the text at the end of the document"
618            }
619            Self::TextAlignment => {
620                "a paragraph's text alignment at the top, the middle or the bottom of its lines is \
621                 not supported, and the pieces of a line of two heights stand on one baseline"
622            }
623            Self::HangingPunctuation => {
624                "hanging punctuation is not supported, and a mark that does not fit at the end of \
625                 a line goes to the next line with the text before it"
626            }
627            Self::ParagraphTextDirection => {
628                "a vertical text direction of a paragraph in a frame is not supported, and the \
629                 paragraph is laid out upright"
630            }
631            Self::TurnedTextBox => {
632                "turned text in a text box is not supported, and the text is laid out upright"
633            }
634            Self::MirrorIndents => {
635                "mirroring indents is not supported, and the left indent stays on the left"
636            }
637            Self::GridRightIndent => {
638                "moving a right indent to the grid is not supported, and it stays as set"
639            }
640            Self::FrameOverlap => {
641                "keeping frames apart is not supported, and a frame stays over the other"
642            }
643            Self::TextBoxTightWrap => {
644                "a tight wrap of a text box is not supported, and text wraps around its box"
645            }
646            Self::RowAlignment => {
647                "a row's own alignment is not supported, and it takes its table's"
648            }
649            Self::RowCellSpacing => {
650                "a row's own cell spacing is not supported, and it takes its table's"
651            }
652            Self::HtmlDiv => {
653                "an HTML div with margins or borders is not supported, and they are left out"
654            }
655            Self::GroupTransform(GroupTransform::Turn) => {
656                "a turn of a drawing group is not supported, and its parts are drawn upright"
657            }
658            Self::GroupTransform(GroupTransform::Flip) => {
659                "a flip of a drawing group is not supported, and its parts are drawn unflipped"
660            }
661            Self::GroupTransform(GroupTransform::TurnAndFlip) => {
662                "a turn and flip of a drawing group is not supported, and its parts are drawn \
663                 upright and unflipped"
664            }
665            Self::SymbolExtension => {
666                "a character of the symbol extension is not supported, and nothing is drawn in \
667                 its place"
668            }
669            Self::AlternateChoice => {
670                "a choice of alternate content in a namespace that F-Office does not read is \
671                 not supported, and a later choice, the fallback or nothing is drawn in its place"
672            }
673            Self::BidirectionalEmbedding => {
674                "a bidirectional embedding or override is not supported, and its text is left \
675                 out"
676            }
677            Self::Ruby => {
678                "a phonetic guide is not supported, and its guide text and its base text are \
679                 left out"
680            }
681            Self::PageNumberElement => {
682                "a page number element is not supported, and no number is drawn in its place"
683            }
684            Self::DateBlock => "a date element is not supported, and nothing is drawn in its place",
685            Self::BetweenBorder => {
686                "a border between paragraphs is not supported, and it is not drawn"
687            }
688            Self::BarBorder => "a bar border of a paragraph is not supported, and it is not drawn",
689            Self::MathElement => {
690                "an element of an equation outside Office Math is not supported, and what it \
691                 holds is left out"
692            }
693            Self::ChartLabels => {
694                "the text of a chart's title, legend or axis labels is not supported, and the \
695                 chart is drawn without it"
696            }
697            Self::PictureBullet => {
698                "a picture bullet of a list label is not supported, and nothing is drawn in its \
699                 place"
700            }
701            Self::NoteMarkInBox => {
702                "a note mark in a text box or a frame of its note is not supported, and it \
703                 shows 1"
704            }
705            Self::DataLabels => {
706                "a data label of a chart is not supported, and the chart is drawn without its \
707                 data labels"
708            }
709        })
710    }
711}
712
713/// The kinds of drawing that a layout can leave out.
714#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
715#[non_exhaustive]
716pub enum Drawing {
717    /// A picture, whose image file is a part of the package.
718    Picture,
719    /// A chart.
720    Chart,
721    /// A SmartArt graphic.
722    SmartArt,
723    /// A shape, such as one of custom geometry.
724    Shape,
725}
726
727/// Where a value lies in its element, which [`Warning::InvalidValue`] and
728/// [`Warning::ValueNotSupported`] name.
729#[derive(Clone, Debug, PartialEq, Eq, Hash)]
730#[non_exhaustive]
731pub enum ValuePlace {
732    /// The text of the element, such as the offset of `wp:posOffset`.
733    Text,
734    /// An attribute of the element.
735    Attribute(Name),
736    /// A property of the CSS declarations that an attribute of the element holds, such as
737    /// `mso-position-horizontal-relative` in the `style` of a VML shape.
738    Property {
739        /// The attribute, such as `style`.
740        attribute: Name,
741        /// The property.
742        property: Name,
743    },
744}
745
746impl fmt::Display for ValuePlace {
747    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
748        match self {
749            Self::Text => f.write_str("the text"),
750            Self::Attribute(attribute) => write!(f, "attribute {attribute}"),
751            Self::Property {
752                attribute,
753                property,
754            } => write!(f, "property {property} of attribute {attribute}"),
755        }
756    }
757}
758
759/// The reading that the layout takes for a value that does not read.
760#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
761#[non_exhaustive]
762pub enum ReadAs {
763    /// The value is 0, as Word for Windows reads a value of half points that does not read.
764    Zero,
765    /// The value counts as missing, as if the element had no such attribute.
766    Missing,
767    /// The value reads as the value of its type with this name, as the schema spells it, when
768    /// unrecognized text uses a different fallback from a missing value, such as `subSup` for
769    /// the place of an n-ary operator's limits (`m:limLoc`).
770    Value(&'static str),
771}
772
773/// Why a part or a drawing is left out.
774#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
775#[non_exhaustive]
776pub enum Reason {
777    /// The package has no part of that name.
778    Missing,
779    /// The part is not XML that the reader takes, or has no root element.
780    NotXml,
781    /// The drawing names no part of the package: its relationship ID names no relationship of
782    /// its part, or one to a file outside the package, or it links a file outside the package
783    /// in place of a part, such as a linked image (`r:link` of `a:blip`, `o:href` of
784    /// `v:imagedata`).
785    Unlinked,
786    /// The layout does not draw what the part holds, other than a chart part, which gives its
787    /// own reason ([`Reason::Chart`]), or the drawing, such as a drawing canvas, ink, a VML group, polyline, arc,
788    /// curve or image element, a floating VML picture whose colors change, a VML shape or
789    /// picture without a CSS width or height, other than a floating line, a VML picture in its
790    /// text line in another element than `v:shape`, or a VML shape after the first of its
791    /// `w:pict` or `w:object`, or a VML text path with a letter whose outline the caller
792    /// cannot give.
793    Unsupported,
794    /// An earlier entry of the package has a name that differs from this one only in ASCII
795    /// case, which the package format forbids, and the reader keeps the earlier one.
796    Equivalent,
797    /// A place or a size that the values of a drawing or of its wrap polygon give lies beyond
798    /// [`Length::FILE_LIMIT`], such as a point of a custom path with a tiny size and a far
799    /// point.
800    OutOfRange,
801    /// The reader takes the drawing, but a step of its layout gives no place for what it
802    /// holds, such as the value axis of a chart whose numbers leave the digits of a decimal,
803    /// or a plot area without room in the chart's frame.
804    NotPlaced,
805    /// F-Office does not draw the chart that the part holds, for this reason.
806    Chart(ChartReason),
807}
808
809/// Why F-Office does not draw a chart, which [`Reason::Chart`] names: the first condition of
810/// its drawn case that the chart does not meet, in the order in which the readers test them.
811/// The reader of the part that holds the chart tests its drawing first (a chart of Office 2016
812/// and later, a floating chart, a chart in a drawing group), before its chart part is read;
813/// then the model of the chart part, the drawn case (one clustered column chart with both axes
814/// shown, its labels, legend, title and series), and the scope of the target's rule of the plot
815/// area (quirk `ChartPlotArea`).
816#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
817#[non_exhaustive]
818pub enum ChartReason {
819    /// The chart is one of Office 2016 and later (`cx:chart`), such as a waterfall chart.
820    ChartEx,
821    /// The chart is a part of a drawing group (`wpg:graphicFrame` of `wpg:wgp`).
822    InGroup,
823    /// The part has no chart (`c:chart`) or no plot area (`c:plotArea`).
824    NoPlotArea,
825    /// The plot area holds a chart group other than bars, lines and scatter points, such as a
826    /// pie, an area or a 3-D chart.
827    OtherGroup,
828    /// A bar group has no direction that reads (`c:barDir`, which the schema requires).
829    NoBarDirection,
830    /// The plot area holds no chart group, or more than one, such as bars with a line.
831    NotOneGroup,
832    /// The one chart group is lines (`c:lineChart`), which the rule of
833    /// `ChartPlotArea::DefaultChart` does not draw.
834    Lines,
835    /// The lines are stacked or stacked to 100 % (`c:grouping` of `c:lineChart`).
836    StackedLines,
837    /// The line group adds drop lines, high-low lines or up-down bars.
838    LineExtras,
839    /// A series of the line group shows markers at its points (`c:marker`) that F-Office does
840    /// not draw: a symbol other than a circle, a diamond, a square, a triangle, an x and a star,
841    /// a look other than a solid fill and a solid outline of a set width, or a look of the
842    /// chart's style on a series that sets its own line.
843    LineMarkers,
844    /// A series of the line group takes the colors of the chart's style (no `c:spPr`) in a
845    /// group of more than six series.
846    StyleColors,
847    /// A series of the line group has no properties (`c:spPr`) in a chart that names a chart
848    /// style (`c:style`), which is not supported.
849    ChartStyle,
850    /// A series of the line or scatter group is smoothed (`c:smooth`), which the target does not
851    /// draw (`ChartSmoothLines::Unknown`).
852    SmoothLines,
853    /// A series' line has a stroke that the target does not draw: under
854    /// `ChartLineStrokes::Unknown` no width that reads, caps or joins that are not written round,
855    /// or a dash; under `StyleRound` a flat or square cap, a miter or bevel join, or a dash of
856    /// its own (`a:custDash`).
857    LineLook,
858    /// The one chart group is scatter points (`c:scatterChart`), which the target does not draw
859    /// (`ChartScatter::Unknown`).
860    Scatter,
861    /// The scatter group's style is other than straight lines and markers (`c:scatterStyle`
862    /// other than `lineMarker`), or than smooth lines and markers (`smoothMarker`) on a target
863    /// that draws smooth lines, which is not supported.
864    ScatterStyle,
865    /// The scatter group lets the colors of its points vary (`c:varyColors` not off).
866    VariedColors,
867    /// A series of the scatter group adds a trendline or error bars (`c:trendline`,
868    /// `c:errBars`).
869    SeriesExtras,
870    /// The scatter chart has not one value axis at the bottom (`c:axPos val="b"`), its x axis,
871    /// and one at the left (`l`).
872    ScatterAxes,
873    /// The scatter chart's x axis draws gridlines (`c:majorGridlines` or `c:minorGridlines`).
874    XGridlines,
875    /// The scatter chart has a legend, which is not supported.
876    ScatterLegend,
877    /// The bars are horizontal (`c:barDir val="bar"`), on a target that does not draw them
878    /// (`ChartHorizontalBars::Unknown`) or in the scope of Word's default chart.
879    HorizontalBars,
880    /// The bars are stacked, stacked to 100 % or one behind the other, not clustered
881    /// (`c:grouping`).
882    NotClustered,
883    /// The plot area has not one category axis and one value axis, such as a date axis in
884    /// place of the category axis.
885    Axes,
886    /// An axis is deleted (`c:delete`) or shows its labels other than next to it
887    /// (`c:tickLblPos`).
888    AxisNotShown,
889    /// The value axis has a logarithm, runs from its highest value, or sets a major unit not
890    /// above zero or a minimum not below its maximum.
891    ValueScale,
892    /// The legend stands at the top right corner (`c:legendPos val="tr"`).
893    LegendTopRight,
894    /// The title is one that F-Office does not know: an automatic one that is not deleted and
895    /// that the target does not hide, a title of its own whose automatic title is deleted, or
896    /// one whose size does not read.
897    UnknownTitle,
898    /// A series has no solid fill that reads.
899    SeriesFill,
900    /// A series has no cached value for each of its points.
901    SeriesValues,
902    /// The bar group has no series.
903    NoSeries,
904    /// The series have different numbers of values.
905    SeriesLengths,
906    /// Every value is zero.
907    AllZero,
908    /// The chart shows no title, which the rule of `ChartPlotArea::DefaultChart` needs.
909    Untitled,
910    /// The legend does not stand at the bottom, or the chart has none, which the rule of
911    /// `ChartPlotArea::DefaultChart` needs.
912    LegendNotAtBottom,
913    /// The value axis sets its minimum, maximum or major unit, outside the scope of the rule
914    /// of `ChartPlotArea::DefaultChart`.
915    SetScale,
916    /// A value is below zero, outside the scope of the rule of `ChartPlotArea::DefaultChart`.
917    NegativeValue,
918    /// An axis crosses the other elsewhere than at the automatic zero, outside the scope of
919    /// the rule of `ChartPlotArea::FontLines`.
920    SetCrossing,
921    /// The plot area has a manual layout other than one in the edge mode, outside the scope
922    /// of the rule of `ChartPlotArea::FontLines`.
923    OtherPlotPlace,
924    /// A series has no name while the legend stands at the left or the right, outside the
925    /// scope of the rule of `ChartPlotArea::FontLines`.
926    UnnamedSeriesBesideLegend,
927    /// An axis shows a title, outside the scope of the rule of `ChartPlotArea::FontLines`.
928    AxisTitle,
929    /// The value labels have a number format other than General, outside the scope of the
930    /// rule of `ChartPlotArea::FontLines`.
931    OtherNumberFormat,
932    /// The plot area shows a data table (`c:dTable`), the series' values in a table below the
933    /// plot, which F-Office does not draw.
934    DataTable,
935    /// A pie's series or one of its points is pulled out of the circle (`c:explosion` above 0),
936    /// which F-Office does not draw.
937    PieExplosion,
938    /// A pie shows data labels at a position whose room F-Office does not know: one other than
939    /// the center, the inner end, the outer end, the best fit and the default, or one that its
940    /// points do not share.
941    PieLabels,
942}
943
944/// A limit of F-Office's work that a value of the file can reach, which
945/// [`Warning::LimitReached`] names. It bounds the work, and is not a measure of Word.
946#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
947#[non_exhaustive]
948pub enum Limit {
949    /// The largest multiple of automatic line spacing (`MAX_LINE_MULTIPLE`): a `w:line` of the
950    /// rule `auto`, or a DrawingML share of a line, beyond it or below its negative.
951    LineMultiple,
952    /// The most grid columns of a table (`MAX_GRID_COLUMNS`): a `w:gridSpan` or a
953    /// `w:gridBefore` above it, a `w:tblGrid` of more columns, or a row that would widen the
954    /// grid beyond it.
955    GridColumns,
956    /// The most trials of balanced columns (`MAX_BALANCE_TRIALS`): a section whose columns
957    /// end at a continuous section break and fit within no trial, which keeps its columns as
958    /// they fill.
959    BalanceTrials,
960    /// The most items of a page with the dashes of table lines (`MAX_DASHED_PAGE_ITEMS`): a
961    /// piece of a dashed table line whose dashes would take its page beyond them, which is
962    /// drawn whole.
963    TableDashes,
964    /// The range of a length: a line of a table row whose edges lie beyond it, which no file
965    /// gives, since every length that a reader takes lies within `Length::FILE_LIMIT`, and
966    /// which leaves the row's lines whole, not cut at their junctions.
967    LineRange,
968    /// The largest font size of a run (`MAX_FONT_SIZE`): a `w:sz` or a `w:szCs` above it.
969    FontSize,
970    /// The most fields open at one place of a story (`MAX_FIELD_DEPTH`): a field that begins
971    /// while that many are open, which is read as content of the field around it.
972    FieldDepth,
973}
974
975impl Warning {
976    /// The warning's kind, a short name that stays the same across versions and holds no name
977    /// of the file, for a caller that counts warnings or writes them where the names of the
978    /// file may not go.
979    #[must_use]
980    pub fn kind(&self) -> &'static str {
981        match self {
982            Self::PartSkipped { .. } => "part-skipped",
983            Self::RelationshipsSkipped { .. } => "relationships-skipped",
984            Self::DrawingSkipped { drawing, .. } => match drawing {
985                Drawing::Picture => "picture-skipped",
986                Drawing::Chart => "chart-skipped",
987                Drawing::SmartArt => "smartart-skipped",
988                Drawing::Shape => "shape-skipped",
989            },
990            Self::WrapPolygonSkipped { .. } => "wrap-polygon-skipped",
991            Self::ArtBorderNotDrawn { .. } => "art-border-not-drawn",
992            Self::FontSubstituted { .. } => "font-substituted",
993            Self::TextNotDrawn { .. } => "text-not-drawn",
994            Self::FontNotFound { .. } => "font-not-found",
995            Self::ScriptNotShaped { .. } => "script-not-shaped",
996            Self::FontFileNotRead { .. } => "font-file-not-read",
997            Self::InkNotMeasured { .. } => "ink-not-measured",
998            Self::InvalidValue { .. } => "invalid-value",
999            Self::ValueNotSupported { .. } => "value-not-supported",
1000            Self::NoteIdRepeated { .. } => "note-id-repeated",
1001            Self::NoteMissing { .. } => "note-missing",
1002            Self::UndeclaredPrefix { .. } => "undeclared-prefix",
1003            Self::LimitReached { .. } => "limit-reached",
1004            Self::Metafile { warning, .. } => warning.kind(),
1005            Self::DrawingMl { warning, .. } => warning.kind(),
1006            Self::FeatureNotSupported { feature, .. } => feature.kind(),
1007        }
1008    }
1009}
1010
1011/// The text of [`Warning::TextNotDrawn`].
1012fn not_drawn(f: &mut fmt::Formatter<'_>, asked: Option<&Name>, tried: &[Name]) -> fmt::Result {
1013    match asked {
1014        Some(asked) => write!(f, "text in font {asked} is not drawn")?,
1015        None => f.write_str("text that names no font is not drawn")?,
1016    }
1017    no_face(f, tried)
1018}
1019
1020/// The text of [`Warning::FontNotFound`].
1021fn not_found(f: &mut fmt::Formatter<'_>, asked: Option<&Name>, tried: &[Name]) -> fmt::Result {
1022    match asked {
1023        Some(asked) => write!(f, "font {asked} is not found")?,
1024        None => f.write_str("the font of a mark, tab or break that names no font is not found")?,
1025    }
1026    no_face(f, tried)
1027}
1028
1029/// The text of [`Warning::ScriptNotShaped`].
1030fn not_shaped(f: &mut fmt::Formatter<'_>, font: Option<&Name>, cause: ShapeFailure) -> fmt::Result {
1031    match font {
1032        Some(font) => write!(
1033            f,
1034            "text of a shaped script in {font} is not shaped: {cause}"
1035        ),
1036        None => write!(
1037            f,
1038            "text of a shaped script in a font of an unknown family is not shaped: {cause}"
1039        ),
1040    }
1041}
1042
1043/// The end of the text of a warning of a font that no face draws: the families `tried`.
1044fn no_face(f: &mut fmt::Formatter<'_>, tried: &[Name]) -> fmt::Result {
1045    f.write_str(": the fonts have no face of ")?;
1046    for (index, family) in tried.iter().enumerate() {
1047        if index > 0 {
1048            f.write_str(", ")?;
1049        }
1050        write!(f, "{family}")?;
1051    }
1052    f.write_str(", nor one that stands in for them")
1053}
1054
1055/// How the layout of a face that draws another family stands to that family's layout.
1056#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
1057#[non_exhaustive]
1058pub enum SubstituteLayout {
1059    /// A face with the family's glyph widths at most, such as Liberation Sans for Arial, so
1060    /// that lines can break where the family's do not.
1061    #[default]
1062    Widths,
1063    /// An open font made from the target's own face of the family, which has its layout.
1064    Exact,
1065    /// An open font made for another version of a family than the target's own face of it.
1066    OtherVersion {
1067        /// The family that the open font stands in for.
1068        family: Name,
1069        /// The version of the family that it was made for, such as "7.06".
1070        made_for: Name,
1071        /// The version of the target's own face of the family, such as "5.01.2x".
1072        target: Name,
1073    },
1074}
1075
1076/// The text of the warning of a substituted font.
1077fn substituted(
1078    f: &mut fmt::Formatter<'_>,
1079    asked: &Name,
1080    used: Option<&Name>,
1081    version: Option<&Name>,
1082    layout: &SubstituteLayout,
1083) -> fmt::Result {
1084    let Some(used) = used else {
1085        return write!(f, "font {asked} is drawn with another font");
1086    };
1087    write!(f, "font {asked} is drawn with {used}")?;
1088    let Some(version) = version else {
1089        return Ok(());
1090    };
1091    match layout {
1092        SubstituteLayout::Widths => Ok(()),
1093        SubstituteLayout::Exact => write!(f, " {version}, which has its layout"),
1094        SubstituteLayout::OtherVersion {
1095            family,
1096            made_for,
1097            target,
1098        } => write!(
1099            f,
1100            " {version}, made for {family} {made_for}; this target has {family} {target}, so \
1101             lines can break in other places"
1102        ),
1103    }
1104}
1105
1106impl fmt::Display for Warning {
1107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1108        match self {
1109            Self::PartSkipped { part, reason } => write!(f, "part {part} is skipped: {reason}"),
1110            Self::RelationshipsSkipped { part } => write!(
1111                f,
1112                "the relationships of part {part} do not read, and what they name is left out"
1113            ),
1114            Self::DrawingSkipped {
1115                drawing,
1116                part,
1117                reason,
1118            } => write!(f, "a {drawing} of part {part} is left out: {reason}"),
1119            Self::WrapPolygonSkipped { part, reason } => write!(
1120                f,
1121                "a wrap polygon of part {part} is left out, and the text keeps out of its \
1122                 drawing's box: {reason}"
1123            ),
1124            Self::ArtBorderNotDrawn { style, size } => write!(
1125                f,
1126                "a page border side of the art style {style} at {size} pt is not drawn: the \
1127                 caller gave no picture of it"
1128            ),
1129            Self::FontSubstituted {
1130                asked,
1131                used,
1132                version,
1133                layout,
1134            } => substituted(f, asked, used.as_ref(), version.as_ref(), layout),
1135            Self::TextNotDrawn { asked, tried } => not_drawn(f, asked.as_ref(), tried),
1136            Self::FontNotFound { asked, tried } => not_found(f, asked.as_ref(), tried),
1137            Self::ScriptNotShaped { font, cause } => not_shaped(f, font.as_ref(), *cause),
1138            Self::FontFileNotRead { file, cause } => write!(
1139                f,
1140                "font file {file} did not load, and its face counts as missing: {cause}"
1141            ),
1142            Self::InkNotMeasured {
1143                font: Some(font),
1144                cause,
1145            } => write!(
1146                f,
1147                "the ink of a glyph of {font} is not measured, and the glyph is placed as one \
1148                 without ink: {cause}"
1149            ),
1150            Self::InkNotMeasured { font: None, cause } => write!(
1151                f,
1152                "the ink of a glyph of a font of an unknown family is not measured, and the \
1153                 glyph is placed as one without ink: {cause}"
1154            ),
1155            Self::InvalidValue {
1156                part,
1157                element,
1158                place,
1159                read_as,
1160            } => {
1161                match place {
1162                    ValuePlace::Text => f.write_str("the text")?,
1163                    _ => write!(f, "the value of {place}")?,
1164                }
1165                write!(
1166                    f,
1167                    " of element {element} in part {part} does not read and {read_as}"
1168                )
1169            }
1170            Self::ValueNotSupported {
1171                part,
1172                element,
1173                place,
1174                value,
1175            } => write!(
1176                f,
1177                "the value {value} of {place} of element {element} in part {part} is drawn as \
1178                 another value"
1179            ),
1180            Self::NoteIdRepeated { part, id } => write!(
1181                f,
1182                "a note of part {part} has the ID {id} of an earlier note, and one of the two is kept"
1183            ),
1184            Self::NoteMissing { part, note, id } => write!(
1185                f,
1186                "a reference of part {part} names the {note} {id}, which no note has, and its \
1187                 number is drawn without a note"
1188            ),
1189            Self::UndeclaredPrefix { part, prefix } => write!(
1190                f,
1191                "part {part} uses the namespace prefix {prefix} without a declaration, and \
1192                 no reader takes an element of it"
1193            ),
1194            Self::LimitReached { part, limit } => write!(f, "in part {part}, {limit}"),
1195            Self::Metafile { part, warning } => write!(f, "in the picture {part}, {warning}"),
1196            Self::DrawingMl { part, warning } => write!(f, "in part {part}, {warning}"),
1197            Self::FeatureNotSupported { part, feature } => write!(f, "in part {part}, {feature}"),
1198        }
1199    }
1200}
1201
1202impl fmt::Display for ReadAs {
1203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1204        match self {
1205            Self::Zero => f.write_str("reads as 0"),
1206            Self::Missing => f.write_str("counts as missing"),
1207            Self::Value(name) => write!(f, "reads as {name}"),
1208        }
1209    }
1210}
1211
1212impl fmt::Display for Drawing {
1213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1214        f.write_str(match self {
1215            Self::Picture => "picture",
1216            Self::Chart => "chart",
1217            Self::SmartArt => "SmartArt graphic",
1218            Self::Shape => "shape",
1219        })
1220    }
1221}
1222
1223impl fmt::Display for Limit {
1224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1225        f.write_str(match self {
1226            Self::LineMultiple => {
1227                "a paragraph asks for a larger multiple of automatic line spacing than F-Office \
1228                 takes, and its spacing stops at the limit"
1229            }
1230            Self::GridColumns => {
1231                "a table asks for more grid columns than F-Office takes, and its grid stops at \
1232                 the limit"
1233            }
1234            Self::BalanceTrials => {
1235                "a section's balanced columns fit within no trial that F-Office makes, and they \
1236                 stay as they fill"
1237            }
1238            Self::TableDashes => {
1239                "a page's table lines have more dashes than F-Office draws, and a line past the \
1240                 limit is drawn whole"
1241            }
1242            Self::LineRange => {
1243                "a table line lies beyond the range of a length, and the lines of its row are \
1244                 drawn whole"
1245            }
1246            Self::FontSize => {
1247                "a run asks for a larger font size than F-Office takes, and its size stops at the \
1248                 limit"
1249            }
1250            Self::FieldDepth => {
1251                "a field begins inside more fields than F-Office keeps open, and it is read as \
1252                 the content of the field around it"
1253            }
1254        })
1255    }
1256}
1257
1258/// Whether a note reference names a footnote or an endnote, which [`Warning::NoteMissing`] says.
1259#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1260pub enum NoteKind {
1261    /// A footnote (`w:footnoteReference`).
1262    Footnote,
1263    /// An endnote (`w:endnoteReference`).
1264    Endnote,
1265}
1266
1267impl fmt::Display for NoteKind {
1268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1269        f.write_str(match self {
1270            Self::Footnote => "footnote",
1271            Self::Endnote => "endnote",
1272        })
1273    }
1274}
1275
1276impl fmt::Display for Reason {
1277    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1278        f.write_str(match self {
1279            Self::Missing => "the package has no such part",
1280            Self::NotXml => "the part is not XML that reads",
1281            Self::Unlinked => "it names no part of the package",
1282            Self::Unsupported => "F-Office does not draw what it holds",
1283            Self::Equivalent => "an earlier entry has a name that differs only in case",
1284            Self::OutOfRange => {
1285                "a place or a size that its values give lies beyond the range of a length"
1286            }
1287            Self::NotPlaced => "its layout gives no place for what it holds",
1288            Self::Chart(reason) => return write!(f, "F-Office does not draw a chart {reason}"),
1289        })
1290    }
1291}
1292
1293impl fmt::Display for ChartReason {
1294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1295        f.write_str(match self {
1296            Self::ChartEx => "of Office 2016 and later",
1297            Self::InGroup => "in a drawing group",
1298            Self::NoPlotArea => "without a plot area",
1299            Self::OtherGroup => {
1300                "whose plot area holds a chart group other than bars, lines and scatter points"
1301            }
1302            Self::NoBarDirection => "with a bar group whose direction does not read",
1303            Self::NotOneGroup => "whose plot area holds no chart group or more than one",
1304            Self::Lines => "of lines on this target",
1305            Self::StackedLines => "of stacked lines",
1306            Self::LineExtras => "of lines with drop lines, high-low lines or up-down bars",
1307            Self::LineMarkers => "of lines with markers of another kind",
1308            Self::StyleColors => "of more than six lines in the colors of the chart's style",
1309            Self::ChartStyle => {
1310                "of lines in the look of a chart style other than style 2 that it names"
1311            }
1312            Self::SmoothLines => "of smoothed lines",
1313            Self::LineLook => "of lines without a width, round caps and round joins",
1314            Self::Scatter => "of scatter points on this target",
1315            Self::ScatterStyle => "of scatter points in a style other than lines and markers",
1316            Self::VariedColors => "of scatter points whose colors vary",
1317            Self::SeriesExtras => "with a trendline or error bars",
1318            Self::ScatterAxes => {
1319                "of scatter points without one value axis below and one at the left"
1320            }
1321            Self::XGridlines => "of scatter points with gridlines of the x axis",
1322            Self::ScatterLegend => "of scatter points with a legend",
1323            Self::HorizontalBars => "of horizontal bars",
1324            Self::NotClustered => "whose bars are not clustered",
1325            Self::Axes => "without one category axis and one value axis",
1326            Self::AxisNotShown => "with an axis that is deleted or whose labels are not next to it",
1327            Self::ValueScale => "whose value axis has a scale that it does not draw",
1328            Self::LegendTopRight => "whose legend stands at the top right corner",
1329            Self::UnknownTitle => "whose title it does not know",
1330            Self::SeriesFill => "with a series without a solid fill",
1331            Self::SeriesValues => "with a series without a cached value for each point",
1332            Self::NoSeries => "without a series",
1333            Self::SeriesLengths => "whose series differ in their numbers of values",
1334            Self::AllZero => "whose values are all zero",
1335            Self::Untitled => "without a title on this target",
1336            Self::LegendNotAtBottom => "whose legend is not at the bottom on this target",
1337            Self::SetScale => "whose value axis sets its scale on this target",
1338            Self::NegativeValue => "with a value below zero on this target",
1339            Self::SetCrossing => "whose axes cross elsewhere than at zero on this target",
1340            Self::OtherPlotPlace => "whose plot area has another manual layout on this target",
1341            Self::UnnamedSeriesBesideLegend => {
1342                "with a series without a name beside its legend on this target"
1343            }
1344            Self::AxisTitle => "with an axis title on this target",
1345            Self::OtherNumberFormat => {
1346                "whose value labels have a number format other than General on this target"
1347            }
1348            Self::DataTable => "whose plot area shows a data table",
1349            Self::PieExplosion => "of a pie whose slices are pulled out",
1350            Self::PieLabels => "of a pie with data labels at another position",
1351        })
1352    }
1353}
1354
1355/// The warnings of a layout.
1356pub type Warnings = f_office_warnings::Warnings<Warning>;
1357
1358/// A value of a layout with its warnings.
1359pub type Warned<T> = f_office_warnings::Warned<T, Warning>;
1360
1361/// The warning of a drawing that the layout leaves out.
1362pub(crate) fn skipped(drawing: Drawing, part: &str, reason: Reason) -> Warning {
1363    Warning::DrawingSkipped {
1364        drawing,
1365        part: Name::new(part),
1366        reason,
1367    }
1368}
1369
1370/// The warnings of the records of an EMF or WMF picture of `part`, from one play into a frame
1371/// of one inch. Which records its player leaves out depends on the file only, so one play for
1372/// each story part that shows it gives them, however many times and at whatever size the layout
1373/// draws it.
1374pub(crate) fn of_metafile(image: &Image, part: &str, warnings: &mut Warnings) {
1375    let inch = Length::from_units(Length::UNITS_PER_INCH);
1376    let frame = Frame {
1377        x: Length::ZERO,
1378        y: Length::ZERO,
1379        width: inch,
1380        height: inch,
1381    };
1382    let Some(bytes) = image.load_bytes() else {
1383        return;
1384    };
1385    let played = match image.format {
1386        ImageFormat::Emf => f_office_emf::play(&bytes, frame),
1387        ImageFormat::Wmf => f_office_emf::play_wmf(&bytes, frame),
1388        _ => return,
1389    };
1390    if let Some(played) = played {
1391        let part = Name::new(part);
1392        warnings.extend(played.warnings, |warning| Warning::Metafile {
1393            part: part.clone(),
1394            warning,
1395        });
1396    }
1397}
1398
1399/// The warnings of the faces that the shapers chose: each family that a face of another
1400/// family drew, each family whose text no face drew, each other family that it found no face of,
1401/// each font whose text of a shaped script
1402/// the caller could not shape, and each font with a glyph whose ink the caller could not
1403/// measure, once for each cause; and each font file that did not load when the caller chose
1404/// one of its faces.
1405pub(crate) fn of_fonts(notes: &FontNotes, fonts: &dyn Fonts, warnings: &mut Warnings) {
1406    // A family that the caller does not know, or that keeps no character as a name, such as
1407    // an empty one, is `None`, so that no warning holds an empty name.
1408    let family = |font| {
1409        fonts
1410            .family_name(font)
1411            .map(|family| Name::new(&family))
1412            .filter(|family| !family.as_str().is_empty())
1413    };
1414    for (asked, font) in &notes.substituted {
1415        warnings.push(Warning::FontSubstituted {
1416            asked: Name::new(asked),
1417            used: family(*font),
1418            version: fonts.face_version(*font).map(|version| Name::new(&version)),
1419            layout: fonts.substitute_layout(*font),
1420        });
1421    }
1422    for (asked, tried) in &notes.not_drawn {
1423        warnings.push(Warning::TextNotDrawn {
1424            asked: asked.as_deref().map(Name::new),
1425            tried: tried.iter().map(|family| Name::new(family)).collect(),
1426        });
1427    }
1428    // A family whose text is left out warns of that only, though its marks take no face too.
1429    for (asked, tried) in notes.faceless.difference(&notes.not_drawn) {
1430        warnings.push(Warning::FontNotFound {
1431            asked: asked.as_deref().map(Name::new),
1432            tried: tried.iter().map(|family| Name::new(family)).collect(),
1433        });
1434    }
1435    for &(font, cause) in &notes.unshaped {
1436        warnings.push(Warning::ScriptNotShaped {
1437            font: family(font),
1438            cause,
1439        });
1440    }
1441    for &(font, cause) in &notes.ink_not_measured {
1442        warnings.push(Warning::InkNotMeasured {
1443            font: family(font),
1444            cause,
1445        });
1446    }
1447    for not_read in fonts.files_not_read() {
1448        warnings.push(Warning::FontFileNotRead {
1449            file: Name::new(&not_read.file),
1450            cause: not_read.cause,
1451        });
1452    }
1453}
1454
1455#[cfg(test)]
1456mod tests;