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