f-office-docx 0.3.0

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! The part reader: the XML of one part and the warnings of the values in it that do not read.
//! Each reader of a part, and each reader of properties
//! that it calls, takes a part reader in place of the part's `Document`, and reads the value of
//! an attribute through it, so that a value that does not read gives an [invalid value]
//! warning beside the reading that the reader took, and a value that F-Office draws as another
//! value of its type gives a [value not supported] warning. The reader knows its part's name
//! from the start: [`PartReader::finish`] adds it to each warning, and each floating drawing that
//! the reader reads keeps it for the warnings of the layout. It gives each paragraph that its
//! part's readers read an ID from the document's source of paragraph IDs
//! ([`PartReader::paragraph_id`]).
//!
//! [invalid value]: crate::Warning::InvalidValue
//! [value not supported]: crate::Warning::ValueNotSupported

pub(crate) mod settings;

use std::cell::OnceCell;

use f_office_drawingml::color::SchemeColors;
use f_office_drawingml::shape::picture_fill;
use f_office_units::Length;
use f_office_warnings::{Name, Warnings};
use f_office_xml::{Document, NodeId};

use crate::body::{NoteId, NoteIds, ParagraphId, ParagraphIds};
use crate::ns::{V, W};
use crate::props::{ListRef, ParaProps};
use crate::reader::settings::{BorderStyles, ListLevels, NumberFormats, TurnedPictures, VmlSizes};
use crate::styles::Styles;
use crate::warnings::{
    Drawing, DrawingMlFeature, DrawingMlWarning, Feature, Limit, NoteKind, ReadAs, Reason,
    ValuePlace, Warning,
};

/// The value of an attribute, as a reader of its type reads it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Value<T> {
    /// The element has no such attribute.
    Missing,
    /// The attribute's value does not read as its type.
    Invalid,
    /// The value.
    Read(T),
}

impl<T> Value<T> {
    /// The value of the attribute `text`, read by `parse`.
    pub(crate) fn of(text: Option<&str>, parse: impl FnOnce(&str) -> Option<T>) -> Self {
        match text {
            None => Self::Missing,
            Some(text) => parse(text).map_or(Self::Invalid, Self::Read),
        }
    }
}

/// The text of the attribute `w:val` of `node`, which holds the value of most
/// WordprocessingML properties, as it stands: for the readers that take it as text, such as
/// a style's or a list level's name, and give no warning.
pub(crate) fn val(doc: &Document, node: NodeId) -> Option<&str> {
    doc.attribute(node, Some(W), "val")
}

/// The text of the attribute `w:val` of the child `w:name` of `node`, as [`val`] reads it,
/// such as the text of a list level (`w:lvlText`).
pub(crate) fn child_val<'d>(doc: &'d Document, node: NodeId, name: &str) -> Option<&'d str> {
    doc.child(node, W, name).and_then(|child| val(doc, child))
}

/// The place of the attribute `name`, which a reader builds only for a warning.
pub(crate) fn attribute(name: &str) -> ValuePlace {
    ValuePlace::Attribute(Name::new(name))
}

/// A value that does not read, as a part reader keeps it before the part's name is added: the
/// element's name, the value's place in the element, and the reading that the reader took.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct Invalid {
    element: Name,
    place: ValuePlace,
    read_as: ReadAs,
}

/// A value of an enumeration that F-Office draws as another value of its type, as a part
/// reader keeps it before the part's name is added: the element's name, the value's place in
/// the element, and the value, a name of the type.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct Unsupported {
    element: Name,
    place: ValuePlace,
    value: &'static str,
}

/// The XML of one part, with the warnings of the values in it that do not read.
pub(crate) struct PartReader<'d> {
    /// The part's XML.
    pub(crate) doc: &'d Document,
    /// The part's name in the package.
    part: &'d str,
    /// The document's source of paragraph IDs, which every part reader of the document shares.
    ids: &'d ParagraphIds,
    /// The values that do not read, each once with its count.
    invalid: Warnings<Invalid>,
    /// The values that F-Office draws as another value of their type, each once with its count.
    unsupported: Warnings<Unsupported>,
    /// The warnings of the readers of DrawingML that the part's reader calls.
    drawing: Warnings<DrawingMlWarning>,
    /// The drawings left out, each kind and reason once with its count, such as a drawing
    /// whose place or size lies beyond [`f_office_units::Length::FILE_LIMIT`].
    skipped: Warnings<(Drawing, Reason)>,
    /// The wrap polygons left out, each reason once with its count.
    polygons: Warnings<Reason>,
    /// The limits of F-Office's work that values of the part reached, each once with its count.
    limits: Warnings<Limit>,
    /// The features of VML, WordprocessingML and OMML that F-Office does not draw, each once
    /// with its count.
    features: Warnings<Feature>,
    /// The numbers of the normal notes that repeat the number of an earlier note, each once
    /// with its count.
    repeated_note_ids: Warnings<i64>,
    /// The IDs of the notes, against which the reader checks each note reference, or `None`
    /// for a reader of a part that is read before the notes or without them.
    notes: Option<&'d NoteIds>,
    /// The references to notes that no note has, each kind and number once with its count.
    missing_notes: Warnings<(NoteKind, i64)>,
    /// How the part reads a paragraph's list level: as the document's target reads it, for a
    /// part of a document ([`crate::parts::read_with`]), and as written for other readers.
    list_levels: ListLevels,
    /// How the part writes numbers in the formats of `ST_NumberFormat`: as the document's
    /// target does, for a part of a document ([`crate::parts::read_with`]), and in decimal
    /// digits for other readers.
    number_formats: NumberFormats,
    /// How the part sizes an inline VML shape: as the document's target does, for a part of a
    /// document ([`crate::parts::read_with`]), and as written for other readers.
    vml_sizes: VmlSizes,
    /// How the part reads the line style of a border side: as the document's target draws it,
    /// for a part of a document ([`crate::parts::read_with`]), and with a large gap style as
    /// one line for other readers.
    border_styles: BorderStyles,
    /// How the part draws a picture whose shape is rotated, and the box that it takes: as the
    /// document's target does, for a part of a document ([`crate::parts::read_with`]), and by
    /// whole quarter turns in the frame's room for other readers.
    turned_pictures: TurnedPictures,
    /// The date and time picture of a `SAVEDATE` or `PRINTDATE` field without its own: as the
    /// document's target gives it, for a part of a document ([`crate::parts::read_with`]), and
    /// none, so that such a field keeps its stored result, for other readers.
    saved_date_picture: Option<&'static str>,
    /// The VML shapes whose place across is the text column, which F-Office draws as the
    /// margins, noted for the body's reader ([`PartReader::note_text_column`]).
    text_columns: Vec<NodeId>,
    /// The colors of the document's theme, which a color that names a theme color takes;
    /// empty for a reader of a part read before the theme or without it.
    scheme: SchemeColors,
    /// The part's VML shape types (`v:shapetype`) by their `id`, found on the first call of
    /// [`PartReader::shape_type`].
    shape_types: OnceCell<Vec<(&'d str, NodeId)>>,
    /// The document's styles, for a part of a document read after them; `None` for the
    /// styles part itself, the parts before it and other readers.
    styles: Option<&'d Styles>,
    /// Whether display fractions step down in size (`m:mathPr/m:smallFrac`).
    small_frac: crate::props::SmallFractions,
}

impl<'d> PartReader<'d> {
    /// A reader of the part `part`, whose XML is `doc`, without warnings, which gives its
    /// paragraphs IDs from `ids`.
    pub(crate) fn of_part(doc: &'d Document, part: &'d str, ids: &'d ParagraphIds) -> Self {
        Self {
            doc,
            part,
            ids,
            invalid: Warnings::new(),
            unsupported: Warnings::new(),
            drawing: Warnings::new(),
            skipped: Warnings::new(),
            polygons: Warnings::new(),
            limits: Warnings::new(),
            features: Warnings::new(),
            repeated_note_ids: Warnings::new(),
            notes: None,
            missing_notes: Warnings::new(),
            list_levels: ListLevels::default(),
            number_formats: NumberFormats::default(),
            vml_sizes: VmlSizes::default(),
            border_styles: BorderStyles::default(),
            turned_pictures: TurnedPictures::default(),
            saved_date_picture: None,
            text_columns: Vec::new(),
            scheme: SchemeColors::default(),
            shape_types: OnceCell::new(),
            styles: None,
            small_frac: crate::props::SmallFractions::Off,
        }
    }

    /// Sets whether display fractions step down in size (`m:mathPr/m:smallFrac`).
    pub(crate) const fn with_small_frac(
        mut self,
        small_frac: crate::props::SmallFractions,
    ) -> Self {
        self.small_frac = small_frac;
        self
    }

    /// Whether display fractions step down in size (`m:mathPr/m:smallFrac`).
    pub(crate) const fn small_frac(&self) -> crate::props::SmallFractions {
        self.small_frac
    }

    /// The VML shape type (`v:shapetype`) of the part whose `id` is `id`, wherever in the part
    /// it lies, the first when several have it.
    pub(crate) fn shape_type(&self, id: &str) -> Option<NodeId> {
        let doc = self.doc;
        let types = self.shape_types.get_or_init(|| {
            let mut found = Vec::new();
            let mut stack: Vec<NodeId> = doc.root().into_iter().collect();
            while let Some(node) = stack.pop() {
                if doc.is(node, V, "shapetype")
                    && let Some(id) = doc.attribute(node, None, "id")
                {
                    found.push((id, node));
                }
                stack.extend(
                    doc.child_elements(node)
                        .collect::<Vec<_>>()
                        .into_iter()
                        .rev(),
                );
            }
            found
        });
        types
            .iter()
            .find(|(name, _)| *name == id)
            .map(|(_, node)| *node)
    }

    /// A reader of the part `doc` of a test, which is the main document part,
    /// [`crate::testing::DOCUMENT`], without warnings, with the tests' one source of paragraph
    /// IDs, [`crate::body::TEST_PARAGRAPH_IDS`].
    #[cfg(test)]
    pub(crate) fn new(doc: &'d Document) -> Self {
        Self::of_part(
            doc,
            crate::testing::DOCUMENT,
            &crate::body::TEST_PARAGRAPH_IDS,
        )
    }

    /// A reader of the same part with the same source of paragraph IDs and no warnings, for a
    /// value that the part's own reader reads too: that reader keeps the value's warnings, and
    /// this one drops them.
    pub(crate) fn again(&self) -> Self {
        Self::of_part(self.doc, self.part, self.ids)
            .with_scheme(self.scheme)
            .with_number_formats(self.number_formats)
            .with_vml_sizes(self.vml_sizes)
            .with_border_styles(self.border_styles)
            .with_turned_pictures(self.turned_pictures)
            .with_saved_date_picture(self.saved_date_picture)
    }

    /// The reader, whose colors that name a theme color take the colors of `scheme`.
    #[must_use]
    pub(crate) const fn with_scheme(mut self, scheme: SchemeColors) -> Self {
        self.scheme = scheme;
        self
    }

    /// The colors of the document's theme.
    pub(crate) const fn scheme(&self) -> &SchemeColors {
        &self.scheme
    }

    /// The ID of a paragraph that the reader reads, new in the document.
    pub(crate) fn paragraph_id(&self) -> ParagraphId {
        self.ids.next()
    }

    /// The part's name in the package, which a drawing that the reader reads keeps.
    pub(crate) const fn part(&self) -> &'d str {
        self.part
    }

    /// Notes the VML shape `shape`, whose place across is the text column that holds its anchor
    /// and which F-Office draws as the margins, so that the body's reader can warn where the two
    /// places can differ (`Body::read`).
    pub(crate) fn note_text_column(&mut self, shape: NodeId) {
        self.text_columns.push(shape);
    }

    /// The VML shapes noted since the last call ([`PartReader::note_text_column`]).
    pub(crate) fn take_text_columns(&mut self) -> Vec<NodeId> {
        std::mem::take(&mut self.text_columns)
    }

    /// Keeps the warning that a value of the part reached the limit `limit`, which the reader
    /// takes in its place.
    pub(crate) fn limit_reached(&mut self, limit: Limit) {
        self.limits.push(limit);
    }

    /// Keeps the warning that `count` values of the part reached the limit `limit`. A count of
    /// zero keeps nothing.
    pub(crate) fn limit_reached_times(&mut self, limit: Limit, count: u32) {
        self.limits.add(limit, count);
    }

    /// Keeps the warning that a drawing of the kind `drawing` in the part is left out, for
    /// `reason`, such as a place or a size that its values give beyond
    /// [`f_office_units::Length::FILE_LIMIT`] ([`Reason::OutOfRange`]).
    pub(crate) fn drawing_skipped(&mut self, drawing: Drawing, reason: Reason) {
        self.skipped.push((drawing, reason));
    }

    /// Keeps the warning that a wrap polygon of the part is left out, for `reason`.
    pub(crate) fn polygon_skipped(&mut self, reason: Reason) {
        self.polygons.push(reason);
    }

    /// The warnings of the readers of DrawingML that the part's reader calls, such as
    /// [`f_office_drawingml::shape::ShapeLook::read`], which [`PartReader::finish`] adds with
    /// the part's name.
    pub(crate) fn drawing_warnings(&mut self) -> &mut Warnings<DrawingMlWarning> {
        &mut self.drawing
    }

    /// Keeps the warning that a drawing of the part asks for `feature`, which F-Office does
    /// not draw, as a warning of DrawingML.
    pub(crate) fn drawingml_feature_not_supported(&mut self, feature: DrawingMlFeature) {
        self.drawing
            .push(DrawingMlWarning::FeatureNotSupported { feature });
    }

    /// Warns of the picture fill of the shape properties `props` of a drawing whose reader
    /// does not draw it ([`f_office_drawingml::shape::picture_fill`]).
    pub(crate) fn warn_of_picture_fill(&mut self, props: Option<NodeId>) {
        let warning = picture_fill_warning(self.doc, props);
        self.drawing.extend(warning, std::convert::identity);
    }

    /// Keeps the warning that the part asks for `feature` of VML, WordprocessingML or OMML,
    /// which F-Office does not draw.
    pub(crate) fn feature_not_supported(&mut self, feature: Feature) {
        self.features.push(feature);
    }

    /// Keeps the warning that a normal note of the part has the ID of the number `id` of an
    /// earlier normal note.
    pub(crate) fn note_id_repeated(&mut self, id: i64) {
        self.repeated_note_ids.push(id);
    }

    /// Keeps the warning that a reference names the note `id` of `kind`, which no note has,
    /// when the reader knows the notes' IDs.
    pub(crate) fn note_reference(&mut self, kind: NoteKind, id: NoteId) {
        if self
            .notes
            .is_some_and(|notes| !notes.get(kind).contains(&id))
        {
            self.missing_notes.push((kind, id.number()));
        }
    }

    /// The reader, which checks each note reference against `notes`, the notes' IDs, when it
    /// has them.
    pub(crate) fn with_note_ids(mut self, notes: Option<&'d NoteIds>) -> Self {
        self.notes = notes;
        self
    }

    /// The reader, which looks up the list of a paragraph's style in `styles`, when it has them.
    #[must_use]
    pub(crate) const fn with_styles(mut self, styles: Option<&'d Styles>) -> Self {
        self.styles = styles;
        self
    }

    /// The list of a paragraph with the properties `props`: its own (`w:numPr`), or else the
    /// one that its style gives it; `None` without either, and without the styles.
    pub(crate) fn list_of(&self, props: &ParaProps) -> Option<ListRef> {
        props.numbering.or_else(|| {
            self.styles
                .and_then(|styles| styles.list_of(props.style.as_deref()))
        })
    }

    /// The reader, which reads a paragraph's list level as `reading` says.
    #[must_use]
    pub(crate) fn with_list_levels(mut self, reading: ListLevels) -> Self {
        self.list_levels = reading;
        self
    }

    /// The reader, which writes numbers in the formats of `ST_NumberFormat` as `formats` says.
    #[must_use]
    pub(crate) const fn with_number_formats(mut self, formats: NumberFormats) -> Self {
        self.number_formats = formats;
        self
    }

    /// The reader, which sizes an inline VML shape as `sizes` says.
    #[must_use]
    pub(crate) const fn with_vml_sizes(mut self, sizes: VmlSizes) -> Self {
        self.vml_sizes = sizes;
        self
    }

    /// The reader, which reads the line style of a border side as `styles` says.
    #[must_use]
    pub(crate) const fn with_border_styles(mut self, styles: BorderStyles) -> Self {
        self.border_styles = styles;
        self
    }

    /// How the part reads the line style of a border side.
    pub(crate) const fn border_styles(&self) -> BorderStyles {
        self.border_styles
    }

    /// The reader, which draws a picture whose shape is rotated as `turns` says.
    #[must_use]
    pub(crate) const fn with_turned_pictures(mut self, turns: TurnedPictures) -> Self {
        self.turned_pictures = turns;
        self
    }

    /// How the part draws a picture whose shape is rotated, and the box that it takes.
    pub(crate) const fn turned_pictures(&self) -> TurnedPictures {
        self.turned_pictures
    }

    /// The reader, which gives a `SAVEDATE` or `PRINTDATE` field without its own date and time
    /// picture the picture `picture`, or keeps its stored result when `picture` is none.
    #[must_use]
    pub(crate) const fn with_saved_date_picture(mut self, picture: Option<&'static str>) -> Self {
        self.saved_date_picture = picture;
        self
    }

    /// The date and time picture of a `SAVEDATE` or `PRINTDATE` field without its own, or none
    /// where such a field keeps its stored result.
    pub(crate) const fn saved_date_picture(&self) -> Option<&'static str> {
        self.saved_date_picture
    }

    /// How the part sizes an inline VML shape.
    pub(crate) const fn vml_sizes(&self) -> VmlSizes {
        self.vml_sizes
    }

    /// How the part writes numbers in the formats of `ST_NumberFormat`.
    pub(crate) const fn number_formats(&self) -> NumberFormats {
        self.number_formats
    }

    /// How the part reads a paragraph's list level.
    pub(crate) fn list_levels(&self) -> ListLevels {
        self.list_levels
    }

    /// The value of the attribute `name` of `node` in the WordprocessingML namespace, read by
    /// `parse`: `None` when it is missing, and when it does not read, with a warning that it
    /// counts as missing.
    pub(crate) fn or_missing<T>(
        &mut self,
        node: NodeId,
        name: &str,
        parse: impl FnOnce(&str) -> Option<T>,
    ) -> Option<T> {
        self.or_missing_in(node, (Some(W), name), parse)
    }

    /// The value of the attribute `name` of `node` in the namespace `namespace`, or in none,
    /// read by `parse`, as [`PartReader::or_missing`] reads it.
    pub(crate) fn or_missing_in<T>(
        &mut self,
        node: NodeId,
        (namespace, name): (Option<&str>, &str),
        parse: impl FnOnce(&str) -> Option<T>,
    ) -> Option<T> {
        let value = Value::of(self.doc.attribute(node, namespace, name), parse);
        self.missing_if_invalid(node, || attribute(name), value)
    }

    /// The length in EMU of the attribute `name` of `node`, in no namespace, as
    /// [`f_office_drawingml::emus`] reads it, such as a drawing's extent. A value that does
    /// not read counts as missing: Word refuses a document with one.
    pub(crate) fn emus(&mut self, node: NodeId, name: &str) -> Option<i64> {
        self.or_missing_in(node, (None, name), f_office_drawingml::emus)
    }

    /// The attribute `name` of `node`, in no namespace, as a length, which
    /// [`f_office_drawingml::emu_length`] reads in one read with the bound of
    /// [`PartReader::emus`], such as a drawing's extent or a text box's inset.
    pub(crate) fn emu_length(&mut self, node: NodeId, name: &str) -> Option<Length> {
        self.or_missing_in(node, (None, name), f_office_drawingml::emu_length)
    }

    /// The text of `node` as a length in EMU, the offset of a floating drawing (`wp:posOffset`,
    /// `ST_PositionOffset`): a whole number only, without spaces around it. Text that does not
    /// read counts as missing: Word refuses a document with one. A number beyond
    /// [`f_office_drawingml::COORDINATE_LIMIT`] does not read either, as in
    /// [`PartReader::emus`], and no number within it lies beyond the range of a length.
    pub(crate) fn emu_length_text(&mut self, node: NodeId) -> Option<Length> {
        let limit = f_office_drawingml::COORDINATE_LIMIT;
        let value = Value::of(Some(&self.doc.text_content(node)), |text| {
            text.parse::<i64>()
                .ok()
                .filter(|emus| (-limit..=limit).contains(emus))
                .and_then(Length::from_emus)
        });
        self.missing_if_invalid(node, || ValuePlace::Text, value)
    }

    /// The text of `node`, read by `parse`: `None` when it does not read, with a warning that
    /// it counts as missing.
    pub(crate) fn text_or_missing<T>(
        &mut self,
        node: NodeId,
        parse: impl FnOnce(&str) -> Option<T>,
    ) -> Option<T> {
        let value = Value::of(Some(&self.doc.text_content(node)), parse);
        self.missing_if_invalid(node, || ValuePlace::Text, value)
    }

    /// The value that `value` holds, and `None` with a warning that the value at the place
    /// that `place` builds in `node` counts as missing when it does not read.
    pub(crate) fn missing_if_invalid<T>(
        &mut self,
        node: NodeId,
        place: impl FnOnce() -> ValuePlace,
        value: Value<T>,
    ) -> Option<T> {
        match value {
            Value::Missing => None,
            Value::Invalid => {
                self.invalid(node, place(), ReadAs::Missing);
                None
            }
            Value::Read(value) => Some(value),
        }
    }

    /// The value of the attribute `name` of `node` in the WordprocessingML namespace, read by
    /// `parse`: `None` when it is missing, and `zero` when it does not read, with a warning that
    /// it reads as zero.
    pub(crate) fn or_zero<T>(
        &mut self,
        node: NodeId,
        name: &str,
        (parse, zero): (impl FnOnce(&str) -> Option<T>, T),
    ) -> Option<T> {
        match Value::of(self.doc.attribute(node, Some(W), name), parse) {
            Value::Missing => None,
            Value::Invalid => {
                self.invalid(node, attribute(name), ReadAs::Zero);
                Some(zero)
            }
            Value::Read(value) => Some(value),
        }
    }

    /// Keeps the warning of the value at `place` in `node` that does not read, read as
    /// `read_as`.
    pub(crate) fn invalid(&mut self, node: NodeId, place: ValuePlace, read_as: ReadAs) {
        let element = self.element_name(node);
        self.invalid.push(Invalid {
            element,
            place,
            read_as,
        });
    }

    /// Keeps the warning that F-Office draws the value `value` at `place` in `node`, a name of
    /// its type, as another value of the type.
    pub(crate) fn not_supported(&mut self, node: NodeId, place: ValuePlace, value: &'static str) {
        let element = self.element_name(node);
        self.not_supported_named(element, place, value);
    }

    pub(crate) fn not_supported_named(
        &mut self,
        element: Name,
        place: ValuePlace,
        value: &'static str,
    ) {
        self.unsupported.push(Unsupported {
            element,
            place,
            value,
        });
    }

    /// The local name of the element `node`, or an empty name.
    fn element_name(&self, node: NodeId) -> Name {
        self.doc
            .element(node)
            .map_or_default(|element| Name::new(element.name.local))
    }

    /// Adds the warnings of the values that did not read to `warnings`, each with the name of
    /// the part.
    pub(crate) fn finish(self, warnings: &mut crate::Warnings) {
        let part = Name::new(self.part);
        warnings.extend(self.invalid, |invalid| Warning::InvalidValue {
            part: part.clone(),
            element: invalid.element,
            place: invalid.place,
            read_as: invalid.read_as,
        });
        warnings.extend(self.unsupported, |unsupported| Warning::ValueNotSupported {
            part: part.clone(),
            element: unsupported.element,
            place: unsupported.place,
            value: Name::new(unsupported.value),
        });
        warnings.extend(self.drawing, |warning| Warning::DrawingMl {
            part: part.clone(),
            warning,
        });
        warnings.extend(self.skipped, |(drawing, reason)| Warning::DrawingSkipped {
            drawing,
            part: part.clone(),
            reason,
        });
        warnings.extend(self.polygons, |reason| Warning::WrapPolygonSkipped {
            part: part.clone(),
            reason,
        });
        warnings.extend(self.limits, |limit| Warning::LimitReached {
            part: part.clone(),
            limit,
        });
        warnings.extend(self.features, |feature| Warning::FeatureNotSupported {
            part: part.clone(),
            feature,
        });
        warnings.extend(self.repeated_note_ids, |id| Warning::NoteIdRepeated {
            part: part.clone(),
            id,
        });
        warnings.extend(self.missing_notes, |(note, id)| Warning::NoteMissing {
            part: part.clone(),
            note,
            id,
        });
    }

    /// The warnings of the values that did not read, without the part's name, for a test.
    #[cfg(test)]
    pub(crate) fn invalid_values(&self) -> Vec<(String, Option<String>, ReadAs, u32)> {
        self.invalid
            .iter()
            .map(|(invalid, count)| {
                (
                    invalid.element.to_string(),
                    test_place(&invalid.place),
                    invalid.read_as,
                    count,
                )
            })
            .collect()
    }

    /// The limits that values of the part reached, with their counts, for a test.
    #[cfg(test)]
    pub(crate) fn limits_reached(&self) -> Vec<(Limit, u32)> {
        self.limits
            .iter()
            .map(|(limit, count)| (*limit, count))
            .collect()
    }

    /// The kinds of the drawings left out, with why and their counts, for a test.
    #[cfg(test)]
    pub(crate) fn skipped_drawings(&self) -> Vec<(Drawing, Reason, u32)> {
        self.skipped
            .iter()
            .map(|((drawing, reason), count)| (*drawing, *reason, count))
            .collect()
    }

    /// The warnings of the values that F-Office draws as another value, without the part's
    /// name, for a test: the element, the place ([`test_place`]), the value and the count.
    #[cfg(test)]
    pub(crate) fn unsupported_values(&self) -> Vec<(String, Option<String>, &'static str, u32)> {
        self.unsupported
            .iter()
            .map(|(unsupported, count)| {
                (
                    unsupported.element.to_string(),
                    test_place(&unsupported.place),
                    unsupported.value,
                    count,
                )
            })
            .collect()
    }
}

/// The warning of the picture fill of the shape properties `props` of a drawing whose reader
/// does not draw it ([`f_office_drawingml::shape::picture_fill`]), or no warning without one.
pub(crate) fn picture_fill_warning(
    doc: &Document,
    props: Option<NodeId>,
) -> Warnings<DrawingMlWarning> {
    let mut warnings = Warnings::new();
    if props.and_then(|p| picture_fill(doc, p)).is_some() {
        warnings.push(DrawingMlWarning::FeatureNotSupported {
            feature: DrawingMlFeature::PictureFill,
        });
    }
    warnings
}

/// The place of a value in the short form of the tests: the attribute's name, the attribute's
/// and the property's names with a space between them, or `None` for the text.
#[cfg(test)]
fn test_place(place: &ValuePlace) -> Option<String> {
    match place {
        ValuePlace::Text => None,
        ValuePlace::Attribute(attribute) => Some(attribute.to_string()),
        ValuePlace::Property {
            attribute,
            property,
        } => Some(format!("{attribute} {property}")),
    }
}