f-office-docx 0.2.2

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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
//! Paragraph borders: the sides of `w:pBdr` and the lines and gaps of each side.

use f_office_paint::Rgb;
use f_office_units::Length;
use f_office_xml::enumeration::{Case, Values, own};
use f_office_xml::{Document, NodeId};

use super::Color;
use super::color::parse_color;
use crate::ns::W;
use crate::params;
use crate::reader::{PartReader, attribute};
use crate::warnings::Feature;

/// One side of a paragraph border.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Border {
    /// The width of the border: of all its lines and the gaps between them.
    pub width: Length,
    /// The space between the text and the line.
    pub space: Length,
    /// The line color.
    pub color: Color,
    /// The lines and the gaps across the width.
    pub parts: BorderParts,
    /// The dashes of the side's style, which a target may draw the line with: `None` for a
    /// solid style, and for a side that is read without its dashes, such as a paragraph's.
    pub dash: Option<DashStyle>,
}

/// The lines of a border and the gaps between them across its width, from its top or left
/// edge: a line, a gap, a line and so on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BorderParts {
    /// The size of each part: at most three lines and the two gaps between them.
    sizes: [Length; 5],
    /// The number of parts.
    count: usize,
    /// The line style that the parts come from.
    style: LineStyle,
    /// The width of the side's line, `w:sz`: the thick line of a compound style.
    line: Length,
}

impl BorderParts {
    /// One line of `width`.
    #[must_use]
    pub const fn single(width: Length) -> Self {
        Self {
            sizes: [
                width,
                Length::ZERO,
                Length::ZERO,
                Length::ZERO,
                Length::ZERO,
            ],
            count: 1,
            style: LineStyle::Single,
            line: width,
        }
    }

    /// The parts of `sizes` of the style `style` with the line `line`, of which at most the
    /// first five count.
    fn new(style: LineStyle, line: Length, sizes: &[Length]) -> Self {
        let mut parts = Self::single(Length::ZERO);
        parts.count = sizes.len().min(parts.sizes.len());
        for (slot, size) in parts.sizes.iter_mut().zip(sizes) {
            *slot = *size;
        }
        Self {
            style,
            line,
            ..parts
        }
    }

    /// The sizes of the parts in order.
    pub(crate) fn sizes(&self) -> &[Length] {
        self.sizes.get(..self.count).unwrap_or(&self.sizes)
    }

    /// The parts of the same style whose line is cut to whole twips, toward zero, before the
    /// thin lines and the gaps of a compound style are taken from it. The parts of a [none
    /// border](Border::none) stay as they are.
    #[must_use]
    fn in_whole_twips(self) -> Self {
        if self.count == 0 {
            return self;
        }
        let line = self.line.toward_zero_whole(Length::UNITS_PER_TWIP);
        border_parts(self.style, line)
    }
}

impl Border {
    /// A border of `parts`, as wide as all of them, `space` from the text.
    #[must_use]
    pub fn new(parts: BorderParts, space: Length, color: Color) -> Self {
        Self {
            width: parts.sizes().iter().copied().sum(),
            space,
            color,
            parts,
            dash: None,
        }
    }

    /// A side of `w:val="none"` with `space` between the text and where a line would stand: it
    /// draws no line and has no width (a **none border**).
    #[must_use]
    pub fn none(space: Length) -> Self {
        Self::new(
            BorderParts::new(LineStyle::None, Length::ZERO, &[]),
            space,
            Color::Auto,
        )
    }

    /// The side with its line, `w:sz`, cut to whole twips before its lines and gaps are taken
    /// from it, for a target that holds the width of a paragraph's border in whole twips
    /// (`BorderWidthUnit::WholeTwips`).
    #[must_use]
    pub fn in_whole_twips(self) -> Self {
        Self {
            dash: self.dash,
            ..Self::new(self.parts.in_whole_twips(), self.space, self.color)
        }
    }

    /// Whether the border draws no line: a [`Border::none`].
    #[must_use]
    pub fn is_none(&self) -> bool {
        self.parts.count == 0
    }

    /// The lines that draw the border, as their offset from its top or left edge and their
    /// thickness.
    #[must_use]
    pub fn lines(&self) -> Vec<(Length, Length)> {
        self.parts
            .sizes()
            .iter()
            .scan(Length::ZERO, |offset, size| {
                let start = *offset;
                *offset += *size;
                Some((start, *size))
            })
            .step_by(2)
            .collect()
    }

    /// The lines that draw the border, as their offset from its bottom or right edge and their
    /// thickness.
    #[must_use]
    pub fn lines_from_end(&self) -> Vec<(Length, Length)> {
        let width = self.width;
        self.lines()
            .into_iter()
            .map(|(offset, thickness)| (width - offset - thickness, thickness))
            .collect()
    }

    /// Whether the border's lines touch, as the bands of a 3-D style do: each line then lies
    /// where the line before it ends as drawn ([`Border::touching_lines`]).
    #[must_use]
    pub(crate) const fn touches(&self) -> bool {
        matches!(self.parts.style, LineStyle::ThreeD(_))
    }

    /// The lines of a border whose lines touch, from its top or left edge, each `thick(t)` thick
    /// for its thickness `t` and starting where the one before it ends.
    pub(crate) fn touching_lines(&self, thick: impl Fn(Length) -> Length) -> Vec<(Length, Length)> {
        self.lines()
            .into_iter()
            .scan(Length::ZERO, |offset, (_, thickness)| {
                let (start, drawn) = (*offset, thick(thickness));
                *offset += drawn;
                Some((start, drawn))
            })
            .collect()
    }

    /// The color of each line of [`Border::lines`] as drawn, from the top or left: the shades
    /// of a 3-D style in its order on the page, and the border's color for every other line.
    #[must_use]
    pub(crate) fn line_colors(&self) -> Vec<Rgb> {
        match self.parts.style {
            LineStyle::ThreeD(relief) => {
                let [light, middle, dark] = relief_shades(self.color);
                match relief {
                    Relief::Emboss => vec![light, middle, dark],
                    Relief::Engrave => vec![dark, middle, light],
                }
            }
            _ => vec![self.color.drawn(); self.lines().len()],
        }
    }

    /// The side with a 3-D style drawn as one line of its width, as a `single` line, for a
    /// target that draws it so (`ThreeDBorders::OneLine`); every other side as it is.
    #[must_use]
    pub(crate) fn as_one_line(self) -> Self {
        if self.touches() {
            Self {
                dash: self.dash,
                ..Self::new(BorderParts::single(self.parts.line), self.space, self.color)
            }
        } else {
            self
        }
    }
}

/// The gaps of a compound border style: 0.75 pt for a small gap, half the line for a medium
/// one, and the line itself for a large one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Gap {
    /// `SmallGap`.
    Small,
    /// `MediumGap`.
    Medium,
    /// `LargeGap`.
    Large,
}

/// The lines of a border style as F-Office draws it (ECMA-376 Part 1, 17.18.2).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum LineStyle {
    /// No line (`nil`, `none`).
    None,
    /// One line.
    Single,
    /// Two lines of the line's width, a line apart (`double`).
    Double,
    /// Three lines of the line's width, a line apart (`triple`).
    Triple,
    /// A thin line and a thick one (`thinThickSmallGap`, `thinThickMediumGap`,
    /// `thinThickLargeGap`).
    ThinThick(Gap),
    /// A thick line and a thin one (`thickThinSmallGap`, `thickThinMediumGap`,
    /// `thickThinLargeGap`).
    ThickThin(Gap),
    /// A thick line between two thin ones (`thinThickThinSmallGap`, `thinThickThinMediumGap`,
    /// `thinThickThinLargeGap`).
    ThinThickThin(Gap),
    /// Three bands that touch, the line between two narrower bands, in three shades of the
    /// line's color (`threeDEmboss`, `threeDEngrave`).
    ThreeD(Relief),
}

/// Which shade of a 3-D border style comes first on the page, read left to right or top to
/// bottom, on every side.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Relief {
    /// `threeDEmboss`: the light band first, then the middle and the dark one.
    Emboss,
    /// `threeDEngrave`: the dark band first, then the middle and the light one.
    Engrave,
}

/// A dash style of `ST_Border` that a target can stroke as a dashed line (ECMA-376 Part 1,
/// 17.18.2): its dashes and gaps along the line, from a dash at the line's start.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DashStyle {
    /// `dotted`: dots as long as the line is wide, with gaps as long.
    Dotted,
    /// `dashed`: dashes three widths long, with gaps of one width.
    Dashed,
    /// `dotDash`: a dash and a dot, each followed by a gap.
    DotDash,
    /// `dotDotDash`: a dash and two dots, each followed by a gap.
    DotDotDash,
}

impl DashStyle {
    /// The lengths of the dashes and the gaps of the pattern, in order from its first dash, in
    /// widths of the line; the pattern repeats along the line.
    #[must_use]
    pub const fn pattern(self) -> &'static [i64] {
        match self {
            Self::Dotted => &params::DOTTED_BORDER_DASHES,
            Self::Dashed => &params::DASHED_BORDER_DASHES,
            Self::DotDash => &params::DOT_DASH_BORDER_DASHES,
            Self::DotDotDash => &params::DOT_DOT_DASH_BORDER_DASHES,
        }
    }
}

/// The dash styles of `ST_Border`, by name; every other style has no dashes.
const DASHED_LINES: [Case<DashStyle>; 4] = [
    own("dotted", DashStyle::Dotted),
    own("dashed", DashStyle::Dashed),
    own("dotDash", DashStyle::DotDash),
    own("dotDotDash", DashStyle::DotDotDash),
];

/// The dashes of the styles of `ST_Border` that have them.
const BORDER_DASH: &Values<DashStyle> = &Values::new(&DASHED_LINES);

/// The names of `ST_Border`: the 27 line styles and the 164 art borders.
pub(crate) const BORDER_NAMES: &[&str] = &[
    "nil",
    "none",
    "single",
    "thick",
    "double",
    "dotted",
    "dashed",
    "dotDash",
    "dotDotDash",
    "triple",
    "thinThickSmallGap",
    "thickThinSmallGap",
    "thinThickThinSmallGap",
    "thinThickMediumGap",
    "thickThinMediumGap",
    "thinThickThinMediumGap",
    "thinThickLargeGap",
    "thickThinLargeGap",
    "thinThickThinLargeGap",
    "wave",
    "doubleWave",
    "dashSmallGap",
    "dashDotStroked",
    "threeDEmboss",
    "threeDEngrave",
    "outset",
    "inset",
    "apples",
    "archedScallops",
    "babyPacifier",
    "babyRattle",
    "balloons3Colors",
    "balloonsHotAir",
    "basicBlackDashes",
    "basicBlackDots",
    "basicBlackSquares",
    "basicThinLines",
    "basicWhiteDashes",
    "basicWhiteDots",
    "basicWhiteSquares",
    "basicWideInline",
    "basicWideMidline",
    "basicWideOutline",
    "bats",
    "birds",
    "birdsFlight",
    "cabins",
    "cakeSlice",
    "candyCorn",
    "celticKnotwork",
    "certificateBanner",
    "chainLink",
    "champagneBottle",
    "checkedBarBlack",
    "checkedBarColor",
    "checkered",
    "christmasTree",
    "circlesLines",
    "circlesRectangles",
    "classicalWave",
    "clocks",
    "compass",
    "confetti",
    "confettiGrays",
    "confettiOutline",
    "confettiStreamers",
    "confettiWhite",
    "cornerTriangles",
    "couponCutoutDashes",
    "couponCutoutDots",
    "crazyMaze",
    "creaturesButterfly",
    "creaturesFish",
    "creaturesInsects",
    "creaturesLadyBug",
    "crossStitch",
    "cup",
    "decoArch",
    "decoArchColor",
    "decoBlocks",
    "diamondsGray",
    "doubleD",
    "doubleDiamonds",
    "earth1",
    "earth2",
    "eclipsingSquares1",
    "eclipsingSquares2",
    "eggsBlack",
    "fans",
    "film",
    "firecrackers",
    "flowersBlockPrint",
    "flowersDaisies",
    "flowersModern1",
    "flowersModern2",
    "flowersPansy",
    "flowersRedRose",
    "flowersRoses",
    "flowersTeacup",
    "flowersTiny",
    "gems",
    "gingerbreadMan",
    "gradient",
    "handmade1",
    "handmade2",
    "heartBalloon",
    "heartGray",
    "hearts",
    "heebieJeebies",
    "holly",
    "houseFunky",
    "hypnotic",
    "iceCreamCones",
    "lightBulb",
    "lightning1",
    "lightning2",
    "mapPins",
    "mapleLeaf",
    "mapleMuffins",
    "marquee",
    "marqueeToothed",
    "moons",
    "mosaic",
    "musicNotes",
    "northwest",
    "ovals",
    "packages",
    "palmsBlack",
    "palmsColor",
    "paperClips",
    "papyrus",
    "partyFavor",
    "partyGlass",
    "pencils",
    "people",
    "peopleWaving",
    "peopleHats",
    "poinsettias",
    "postageStamp",
    "pumpkin1",
    "pushPinNote2",
    "pushPinNote1",
    "pyramids",
    "pyramidsAbove",
    "quadrants",
    "rings",
    "safari",
    "sawtooth",
    "sawtoothGray",
    "scaredCat",
    "seattle",
    "shadowedSquares",
    "sharksTeeth",
    "shorebirdTracks",
    "skyrocket",
    "snowflakeFancy",
    "snowflakes",
    "sombrero",
    "southwest",
    "stars",
    "starsTop",
    "stars3d",
    "starsBlack",
    "starsShadowed",
    "sun",
    "swirligig",
    "tornPaper",
    "tornPaperBlack",
    "trees",
    "triangleParty",
    "triangles",
    "tribal1",
    "tribal2",
    "tribal3",
    "tribal4",
    "tribal5",
    "tribal6",
    "twistedLines1",
    "twistedLines2",
    "vine",
    "waveline",
    "weavingAngles",
    "weavingBraid",
    "weavingRibbon",
    "weavingStrips",
    "whiteFlowers",
    "woodwork",
    "xIllusions",
    "zanyTriangles",
    "zigZag",
    "zigZagStitch",
];

/// An art style of `ST_Border`, such as `apples`: one of the names after the line styles, whose
/// side of a page border Word draws as pictures, and whose `w:sz` counts in points.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ArtStyle(u8);

impl ArtStyle {
    /// The art style of the name `name`, as the schema spells it, or `None` for a line style and
    /// for any other text.
    #[must_use]
    pub fn of_name(name: &str) -> Option<Self> {
        let index = BORDER_NAMES
            .get(params::LINE_STYLE_NAMES..)?
            .iter()
            .position(|art| *art == name)?;
        u8::try_from(index).ok().map(Self)
    }

    /// The name of the art style, as the schema spells it.
    #[must_use]
    pub fn name(self) -> &'static str {
        BORDER_NAMES
            .get(params::LINE_STYLE_NAMES + usize::from(self.0))
            .copied()
            .unwrap_or_default()
    }
}

/// The line styles of `ST_Border` that F-Office draws as their own lines. A target may draw
/// the large gap styles as one line
/// ([`BorderStyles::drawn`](crate::reader::settings::BorderStyles::drawn)).
const DRAWN_LINES: [Case<LineStyle>; 18] = [
    own("threeDEmboss", LineStyle::ThreeD(Relief::Emboss)),
    own("threeDEngrave", LineStyle::ThreeD(Relief::Engrave)),
    own("inset", LineStyle::Single),
    own("outset", LineStyle::Single),
    own("nil", LineStyle::None),
    own("none", LineStyle::None),
    own("single", LineStyle::Single),
    own("double", LineStyle::Double),
    own("triple", LineStyle::Triple),
    own("thinThickSmallGap", LineStyle::ThinThick(Gap::Small)),
    own("thickThinSmallGap", LineStyle::ThickThin(Gap::Small)),
    own(
        "thinThickThinSmallGap",
        LineStyle::ThinThickThin(Gap::Small),
    ),
    own("thinThickMediumGap", LineStyle::ThinThick(Gap::Medium)),
    own("thickThinMediumGap", LineStyle::ThickThin(Gap::Medium)),
    own(
        "thinThickThinMediumGap",
        LineStyle::ThinThickThin(Gap::Medium),
    ),
    own("thinThickLargeGap", LineStyle::ThinThick(Gap::Large)),
    own("thickThinLargeGap", LineStyle::ThickThin(Gap::Large)),
    own(
        "thinThickThinLargeGap",
        LineStyle::ThinThickThin(Gap::Large),
    ),
];

/// `ST_Border` of a side of a paragraph, table or cell border: each style that F-Office
/// does not draw as its own lines, such as `dotted`, `wave` and an art border, is drawn as one
/// line. A side without a style, or whose style is text outside the type, has no
/// line, where F-Office drew text as one line before.
pub(crate) const BORDER_LINE: &Values<LineStyle> =
    &Values::with_others(&DRAWN_LINES, BORDER_NAMES, LineStyle::Single);

/// The parts of a border of the line style `style` whose line is `line` wide: one line, three
/// of a double border, five of a triple border, and the lines and gaps of a gap style such as
/// `thinThickSmallGap`. A small or medium gap style's thick line is the line, and its thin lines
/// and gaps are 0.75 pt for a small gap and half the line for a medium gap; a large gap style's
/// lines are 1.5 pt and 0.75 pt and its gaps the line. From the top or the left, the lines of a
/// compound style are in the reverse order of its name: the thick line of `thinThickSmallGap`
/// is on top.
fn border_parts(style: LineStyle, line: Length) -> BorderParts {
    // The thin line, the thick line and the gap of a gap style.
    let gap = |gap: Gap| match gap {
        Gap::Small => {
            let small = eighth_points(params::SMALL_GAP_EIGHTHS);
            (small, line, small)
        }
        Gap::Medium => {
            let medium = line.div_toward_zero(params::MEDIUM_GAP_PARTS);
            (medium, line, medium)
        }
        Gap::Large => (
            eighth_points(params::LARGE_GAP_THIN_EIGHTHS),
            eighth_points(params::LARGE_GAP_THICK_EIGHTHS),
            line,
        ),
    };
    // The lines of a compound style in the order of its name, each with the gap after it.
    let compound = |lines: &[Length], gap: Length| {
        let sizes: Vec<Length> = lines
            .iter()
            .rev()
            .flat_map(|size| [gap, *size])
            .skip(1)
            .collect();
        BorderParts::new(style, line, &sizes)
    };
    let repeated = |count: i64| {
        BorderParts::new(
            style,
            line,
            &vec![line; usize::try_from(count).unwrap_or(1)],
        )
    };
    match style {
        LineStyle::None | LineStyle::Single => BorderParts::new(style, line, &[line]),
        LineStyle::Double => repeated(params::DOUBLE_BORDER_PARTS),
        LineStyle::Triple => repeated(params::TRIPLE_BORDER_PARTS),
        LineStyle::ThinThick(size) => {
            let (thin, thick, space) = gap(size);
            compound(&[thin, thick], space)
        }
        LineStyle::ThickThin(size) => {
            let (thin, thick, space) = gap(size);
            compound(&[thick, thin], space)
        }
        LineStyle::ThinThickThin(size) => {
            let (thin, thick, space) = gap(size);
            compound(&[thin, thick, thin], space)
        }
        LineStyle::ThreeD(_) => {
            let [narrow, wide] = params::THREE_D_BAND_EIGHTHS;
            let eighths = if line < eighth_points(params::THREE_D_WIDE_LINE_EIGHTHS) {
                narrow
            } else {
                wide
            };
            let band = eighth_points(eighths);
            BorderParts::new(style, line, &[band, Length::ZERO, line, Length::ZERO, band])
        }
    }
}

/// `eighths` eighths of a point.
fn eighth_points(eighths: i64) -> Length {
    Length::from_eighth_points(eighths).unwrap_or(Length::ZERO)
}

/// The light, middle and dark shades of the bands of a 3-D border style of the color `color`.
/// Black and the automatic color, and white, take shades of their own. Any other color's light
/// band is the color made lighter once for each lightness of `THREE_D_LIGHTER_BELOW` that it
/// lies below, and the middle and dark bands are darker than the light band, each with the
/// color's hue and saturation.
fn relief_shades(color: Color) -> [Rgb; 3] {
    let rgb = |[r, g, b]: [u8; 3]| Rgb { r, g, b };
    let channels = match color {
        Color::Auto => return params::THREE_D_BLACK_BANDS.map(rgb),
        Color::Rgb(channels) => channels,
    };
    if channels == [0; 3] {
        return params::THREE_D_BLACK_BANDS.map(rgb);
    }
    if channels == super::color::WHITE {
        return params::THREE_D_WHITE_BANDS.map(rgb);
    }
    let steps = params::THREE_D_LIGHTNESS_STEPS;
    let light = lightness(channels);
    let light = light
        + params::THREE_D_LIGHTER_STEP
            * params::THREE_D_LIGHTER_BELOW
                .iter()
                .fold(0, |count, &below| count + i64::from(light < below));
    let [middle, dark] = params::THREE_D_DARKER.map(|darker| (light - darker).max(0));
    [light.min(steps), middle, dark].map(|lightness| rgb(with_lightness(channels, lightness)))
}

/// The lightness of `channels` in steps of `THREE_D_LIGHTNESS_STEPS`, to the nearest step: the
/// mean of the largest and the smallest channel.
fn lightness(channels: [u8; 3]) -> i64 {
    let (high, low) = extremes(channels);
    f_office_units::div_round(
        (high + low) * params::THREE_D_LIGHTNESS_STEPS,
        2 * i64::from(u8::MAX),
    )
}

/// The largest and the smallest of `channels`.
fn extremes(channels: [u8; 3]) -> (i64, i64) {
    let wide = channels.map(i64::from);
    let high = wide.iter().copied().max().unwrap_or(0);
    let low = wide.iter().copied().min().unwrap_or(0);
    (high, low)
}

/// `channels` with the lightness `lightness`, in steps of `THREE_D_LIGHTNESS_STEPS`, and their
/// hue and saturation kept, each channel rounded to the nearest whole step.
fn with_lightness(channels: [u8; 3], lightness: i64) -> [u8; 3] {
    let steps = params::THREE_D_LIGHTNESS_STEPS;
    let whole = i64::from(u8::MAX);
    let (high, low) = extremes(channels);
    // Sums of the largest and the smallest channel, in steps times whole channels: white is
    // `full`, and a sum of chroma `c` keeps its saturation where the room around it is wider.
    let full = 2 * whole * steps;
    let room = |sum: i64| sum.min(full - sum);
    let (old, new) = ((high + low) * steps, lightness * 2 * whole);
    let chroma = (high - low) * steps;
    let new_chroma = if room(old) == 0 {
        0
    } else {
        chroma * room(new) / room(old)
    };
    channels.map(|channel| {
        let share = if high == low {
            0
        } else {
            (i64::from(channel) - low) * new_chroma / (high - low)
        };
        let value = f_office_units::div_round(new - new_chroma + 2 * share, 2 * steps);
        u8::try_from(value.clamp(0, whole)).unwrap_or(u8::MAX)
    })
}

/// The borders of a paragraph.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Borders {
    /// The line above the paragraph.
    pub top: Option<Border>,
    /// The line below the paragraph.
    pub bottom: Option<Border>,
    /// The line at the paragraph's left side.
    pub left: Option<Border>,
    /// The line at the paragraph's right side.
    pub right: Option<Border>,
    /// The line between two paragraphs of a group with equal borders (`w:between`).
    pub between: Option<Border>,
}

impl Borders {
    /// The borders with the line of each side cut to whole twips ([`Border::in_whole_twips`]),
    /// for a target that holds the width of a paragraph's border in whole twips
    /// (`BorderWidthUnit::WholeTwips`).
    #[must_use]
    pub fn in_whole_twips(self) -> Self {
        let cut = |side: Option<Border>| side.map(Border::in_whole_twips);
        Self {
            top: cut(self.top),
            bottom: cut(self.bottom),
            left: cut(self.left),
            right: cut(self.right),
            between: cut(self.between),
        }
    }

    /// The borders with each side of a 3-D style drawn as one line ([`Border::as_one_line`]),
    /// for a target that draws them so (`ThreeDBorders::OneLine`).
    #[must_use]
    pub fn as_one_line(self) -> Self {
        let one = |side: Option<Border>| side.map(Border::as_one_line);
        Self {
            top: one(self.top),
            bottom: one(self.bottom),
            left: one(self.left),
            right: one(self.right),
            between: one(self.between),
        }
    }

    /// The borders without their top and bottom [none borders](Border::none), for a target
    /// whose paragraphs drop them (`NoneBorders::Dropped`).
    #[must_use]
    pub fn without_none(self) -> Self {
        let line = |side: Option<Border>| side.filter(|border| !border.is_none());
        Self {
            top: line(self.top),
            bottom: line(self.bottom),
            ..self
        }
    }
}

/// A side of a paragraph's border that one level of the cascade names in its `w:pBdr`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NamedSide {
    /// The side with its line, or a top or bottom [none border](Border::none).
    Line(Border),
    /// The side without a line, such as one of `nil`: it draws none and hides the side that a
    /// level below names.
    Hidden,
}

impl NamedSide {
    /// The border that the side draws, if any.
    #[must_use]
    pub fn line(side: Option<Self>) -> Option<Border> {
        match side {
            Some(Self::Line(border)) => Some(border),
            Some(Self::Hidden) | None => None,
        }
    }
}

/// The sides of a paragraph's border by name, `w:top`, `w:bottom`, `w:left`, `w:right` and
/// `w:between` of `w:pBdr`, each taken from the nearest level of the cascade that names it; `None` for a side
/// that no level names. `w:start` and `w:end` name no side here.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NamedSides {
    /// The side above the paragraph.
    pub top: Option<NamedSide>,
    /// The side below the paragraph.
    pub bottom: Option<NamedSide>,
    /// The side at the paragraph's left.
    pub left: Option<NamedSide>,
    /// The side at the paragraph's right.
    pub right: Option<NamedSide>,
    /// The side between two paragraphs of a group.
    pub between: Option<NamedSide>,
}

impl NamedSides {
    /// Overlays the sides that `other` names on these: each of them wins, and the others stay.
    pub fn apply(&mut self, other: &Self) {
        for (side, named) in [
            (&mut self.top, other.top),
            (&mut self.bottom, other.bottom),
            (&mut self.left, other.left),
            (&mut self.right, other.right),
            (&mut self.between, other.between),
        ] {
            if named.is_some() {
                *side = named;
            }
        }
    }

    /// Overlays the sides that `other` names on the sides of `sides`, which start empty when
    /// no level before named one; `None` in `other` leaves `sides` as it is.
    pub fn overlay(sides: &mut Option<Box<Self>>, other: Option<&Self>) {
        if let Some(other) = other {
            sides.get_or_insert_with(Box::default).apply(other);
        }
    }

    /// The borders that the sides draw: a hidden side, and a side that no level names, draws
    /// none.
    #[must_use]
    pub fn borders(self) -> Borders {
        Borders {
            top: NamedSide::line(self.top),
            bottom: NamedSide::line(self.bottom),
            left: NamedSide::line(self.left),
            right: NamedSide::line(self.right),
            between: NamedSide::line(self.between),
        }
    }
}

/// Reads the top, bottom, left and right sides of `w:pBdr`, as the borders of the level
/// ([`Borders`]) and as the sides that it names ([`NamedSides`]). A top or bottom side of
/// `w:val="none"` with a space above 0 reads as a [none border](Border::none), which the layout
/// keeps or drops by its target; one of `nil`, or without a space, is no border. The borders
/// take `w:start` and `w:end` for a left and a right side without a line; the named sides do
/// not. It reads the side between the paragraphs of a group (`w:between`), which the layout
/// draws or drops by its target. A bar border (`w:bar`) is not drawn, with a warning when it has
/// a line ([`has_line`]).
pub(super) fn read_borders(reader: &mut PartReader, node: NodeId) -> (Borders, NamedSides) {
    let doc = reader.doc;
    if doc
        .child(node, W, "bar")
        .is_some_and(|side| has_line(doc, side))
    {
        reader.feature_not_supported(Feature::BarBorder);
    }
    let mut named = |name, edge: bool| {
        let side = doc.child(node, W, name)?;
        let line = read_border(reader, side).or_else(|| edge.then(|| read_none(reader, side))?);
        Some(line.map_or(NamedSide::Hidden, NamedSide::Line))
    };
    let left = named("left", false);
    let left_start = NamedSide::line(left).or_else(|| NamedSide::line(named("start", false)));
    let right = named("right", false);
    let right_end = NamedSide::line(right).or_else(|| NamedSide::line(named("end", false)));
    let sides = NamedSides {
        top: named("top", true),
        bottom: named("bottom", true),
        left,
        right,
        between: named("between", false),
    };
    let borders = Borders {
        left: left_start,
        right: right_end,
        ..sides.borders()
    };
    (borders, sides)
}

/// Whether the border side `side` has a line: a style of `ST_Border` other than `none` and
/// `nil`, an art border too, which [`BORDER_LINE`] draws as one line. A side without a style,
/// or whose style is text outside the type, has none. It reads the style without the warnings
/// of a side that F-Office draws.
fn has_line(doc: &Document, side: NodeId) -> bool {
    doc.attribute(side, Some(W), "val")
        .and_then(|name| BORDER_LINE.find(name))
        .is_some_and(|(style, _, _)| !matches!(style, LineStyle::None))
}

/// Reads a side of `w:val="none"` whose space is above 0 as a [none border](Border::none).
/// A missing or unreadable space is 0.
fn read_none(reader: &mut PartReader, side: NodeId) -> Option<Border> {
    let named = reader.doc.attribute(side, Some(W), "val") == Some("none");
    let space = Length::from_points(reader.whole_number(side, "space").unwrap_or(0))?;
    (named && space > Length::ZERO).then(|| Border::none(space))
}

/// Reads one border side, such as `w:top`, whose style reads through [`BORDER_LINE`]. A side
/// without a style, or a `none` or `nil` side, has no line.
pub(crate) fn read_border(reader: &mut PartReader, side: NodeId) -> Option<Border> {
    let style = read_line_style(reader, side, BORDER_LINE)?;
    read_border_as(reader, side, style)
}

/// The line style of the border side `side` as `table` reads it and as the part's target draws
/// it ([`BorderStyles::drawn`](crate::reader::settings::BorderStyles::drawn)). A style that the
/// target draws as another, such as a large gap style that it draws as one line, gives the
/// warning `value-not-supported`.
pub(crate) fn read_line_style(
    reader: &mut PartReader,
    side: NodeId,
    table: &'static Values<LineStyle>,
) -> Option<LineStyle> {
    let style = reader.enumeration(side, "val", table)?;
    let drawn = reader.border_styles().drawn(style);
    if drawn != style {
        let doc = reader.doc;
        if let Some((_, spelling, _)) = doc
            .attribute(side, Some(W), "val")
            .and_then(|name| table.find(name))
        {
            reader.not_supported(side, attribute("val"), spelling);
        }
    }
    Some(drawn)
}

/// Reads one side of a table's or a cell's borders, as [`read_border`] does, with the dashes
/// of its style. A side of a 3-D style is one line ([`Border::as_one_line`]).
pub(crate) fn read_table_border(reader: &mut PartReader, side: NodeId) -> Option<Border> {
    let dash = reader
        .doc
        .attribute(side, Some(W), "val")
        .and_then(|name| BORDER_DASH.find(name))
        .map(|(dash, _, _)| *dash);
    read_border(reader, side).map(|border| Border {
        dash,
        ..border.as_one_line()
    })
}

/// Reads one border side, such as `w:top`, of the line style `style`. A missing width or space
/// is 0, and so is one that does not read.
pub(crate) fn read_border_as(
    reader: &mut PartReader,
    side: NodeId,
    style: LineStyle,
) -> Option<Border> {
    if style == LineStyle::None {
        return None;
    }
    let doc = reader.doc;
    let line = Length::from_eighth_points(reader.whole_number(side, "sz").unwrap_or(0))?;
    let space = Length::from_points(reader.whole_number(side, "space").unwrap_or(0))?;
    Some(Border::new(
        border_parts(style, line),
        space,
        doc.attribute(side, Some(W), "color")
            .map_or(Color::Auto, parse_color),
    ))
}

#[cfg(test)]
mod tests {
    use super::{
        Border, BorderParts, Borders, Color, LineStyle, NamedSide, NamedSides, Relief, border_parts,
    };
    use f_office_paint::Rgb;
    use f_office_units::Length;

    /// A side of the 3-D style `relief` of the line `eighths` eighths of a point wide in
    /// `color`.
    fn relief(relief: Relief, eighths: i64, color: Color) -> Border {
        let line = Length::from_eighth_points(eighths).unwrap();
        Border::new(
            border_parts(LineStyle::ThreeD(relief), line),
            Length::ZERO,
            color,
        )
    }

    #[test]
    fn draws_a_three_d_side_as_a_line_between_two_touching_bands() {
        let eighths = |sizes: Vec<(Length, Length)>| -> Vec<(i64, i64)> {
            let eighth = Length::from_eighth_points(1).unwrap().units();
            sizes
                .into_iter()
                .map(|(offset, size)| (offset.units() / eighth, size.units() / eighth))
                .collect()
        };
        // The bands are 0.75 pt up to a line of 3 pt, and 1.5 pt from it.
        let narrow = relief(Relief::Emboss, 18, Color::Auto);
        assert_eq!(eighths(narrow.lines()), [(0, 6), (6, 18), (24, 6)]);
        assert_eq!(narrow.width, Length::from_eighth_points(30).unwrap());
        assert_eq!(
            eighths(relief(Relief::Engrave, 24, Color::Auto).lines()),
            [(0, 12), (12, 24), (36, 12)]
        );
        assert!(narrow.touches());
        assert_eq!(
            narrow.as_one_line(),
            Border::new(
                BorderParts::single(Length::from_eighth_points(18).unwrap()),
                Length::ZERO,
                Color::Auto
            )
        );
    }

    #[test]
    fn shades_the_bands_of_a_three_d_side_in_their_order_on_the_page() {
        let gray = |v: u8| Rgb { r: v, g: v, b: v };
        let colors = |relief_of: Relief, color: Color| relief(relief_of, 18, color).line_colors();
        // Black and the automatic color take shades of their own, and so does white.
        for black in [Color::Auto, Color::Rgb([0; 3])] {
            assert_eq!(
                colors(Relief::Emboss, black),
                [gray(192), gray(96), gray(0)]
            );
            assert_eq!(
                colors(Relief::Engrave, black),
                [gray(0), gray(96), gray(192)]
            );
        }
        assert_eq!(
            colors(Relief::Emboss, Color::Rgb([255; 3])),
            [gray(255), gray(160), gray(128)]
        );
        // A red of the lightness 119 lies below the half lightness 120 and takes a light band
        // 40 lighter; one of 59 lies below a quarter too and takes one 80 lighter.
        let red = |r, g| Rgb { r, g, b: g };
        assert_eq!(
            colors(Relief::Emboss, Color::Rgb([0xFD, 0, 0])),
            [red(255, 83), red(189, 0), red(168, 0)]
        );
        assert_eq!(
            colors(Relief::Emboss, Color::Rgb([0x7D, 0, 0])),
            [red(255, 40), red(147, 0), red(125, 0)]
        );
    }

    #[test]
    fn named_sides_overlay_side_by_side_and_a_hidden_side_hides_the_one_below() {
        let line = |eighths| {
            Border::new(
                border_parts(
                    LineStyle::Single,
                    Length::from_eighth_points(eighths).unwrap(),
                ),
                Length::from_points(1).unwrap(),
                Color::Auto,
            )
        };
        let style = NamedSides {
            top: Some(NamedSide::Line(line(12))),
            bottom: Some(NamedSide::Line(line(12))),
            left: Some(NamedSide::Line(line(12))),
            right: Some(NamedSide::Line(line(12))),
            between: None,
        };
        let own = NamedSides {
            right: Some(NamedSide::Line(line(24))),
            bottom: Some(NamedSide::Hidden),
            ..NamedSides::default()
        };
        let mut sides = style;
        sides.apply(&own);
        assert_eq!(
            sides.borders(),
            Borders {
                top: Some(line(12)),
                bottom: None,
                left: Some(line(12)),
                right: Some(line(24)),
                between: None,
            }
        );
        // A level that names no side leaves every side as it was.
        sides.apply(&NamedSides::default());
        assert_eq!(sides.borders().right, Some(line(24)));
    }
}