f-office-docx 0.2.4

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
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
//! The borders of the cells.

use std::collections::{HashMap, HashSet};

use f_office_paint::{Item, Point, Rect, Rgb};
use f_office_units::{Edges, Length};

use super::{Gaps, Shape, Sides, Slot, TopPart, width};
use crate::grid::{Device, Rounding};
use crate::layout::line::height::{BoxTop, SpaceBefore, row_line_dot};
use crate::layout::page_items::PageItems;
use crate::layout::{Layout, decisions};
use crate::params::MAX_DASHED_PAGE_ITEMS;
use crate::props::{Border, DashStyle};

/// Where the table's own outline ends below a row of a table with cell spacing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum OutlineEnd {
    /// The table goes on below the row on the same page.
    Row,
    /// The row is the table's last: the table's bottom line lies one more spacing below it.
    Table,
    /// A page's foot ends the table's part below the row, and the line that closes the part
    /// there, if any, lies right below it.
    Page(Option<Border>),
}

impl OutlineEnd {
    /// The end of the outline below the whole row `index`: the table's end below its last row.
    pub(super) fn of_row(shape: &Shape, index: usize) -> Self {
        if index + 1 == shape.grid.table.rows.len() {
            Self::Table
        } else {
            Self::Row
        }
    }
}

/// The top of a table row, `at`, with the cursor's twips rest there, `rest`, where the rows
/// carry one down the page from the table's top; a part of a row that a page break or a cell
/// starts has none.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct RowTop {
    pub(super) at: Length,
    pub(super) rest: Option<i64>,
}

impl RowTop {
    /// The top `at` of a row part without a twips rest.
    pub(super) fn without_rest(at: Length) -> Self {
        Self { at, rest: None }
    }
}

/// A join of two parts of the line over a cell, where the vertical line between two cells
/// above meets them.
#[derive(Clone, Copy, Debug)]
enum Join {
    /// The part before ends at the vertical line's near edge, and the part after starts there
    /// and covers it.
    Covered,
    /// The vertical line runs on through the band of the part `as_wide`, which is exactly as
    /// wide as it, and both parts end at its edges.
    Cut { vertical: Border, as_wide: Border },
}

/// The join after each part of the line over a cell, where a vertical line between two cells
/// above meets the next part inside the cell between `low` and `high`.
fn joins(parts: &[TopPart], (low, high): (Length, Length)) -> Vec<Option<Join>> {
    parts
        .iter()
        .zip(parts.iter().skip(1).map(Some).chain([None]))
        .map(|(part, next)| {
            let next = next?;
            let vertical = part
                .sides
                .1
                .filter(|_| low < part.right && part.right < high)?;
            let as_wide = [part.border, next.border]
                .into_iter()
                .find(|border| border.width == vertical.width);
            Some(as_wide.map_or(Join::Covered, |as_wide| Join::Cut { vertical, as_wide }))
        })
        .collect()
}

/// A part of the line over a cell as a cell of its own, with the vertical lines of the cells
/// above at its ends. At the cell's own edges, it takes the cell's own vertical line where no
/// cell above gives one.
fn part_slot<'t>(device: &Device, slot: &Slot<'t>, part: &TopPart) -> Slot<'t> {
    let side = |line: Option<Border>, edge: Length, own: Option<Border>| {
        line.or(own.filter(|_| edge == slot.left || edge == slot.right))
    };
    let mut cell = Slot {
        left: part.left,
        right: part.right,
        borders: Sides {
            left: side(part.sides.0, part.left, slot.borders.left),
            right: side(part.sides.1, part.right, slot.borders.right),
            ..slot.borders
        },
        top_parts: Vec::new(),
        ..slot.clone()
    };
    cell.sides = SideLines::of(device, &cell);
    cell
}

/// The ends of a part, from its `cell`, in increasing order. Before a join, the part ends at
/// the near edge of the vertical line after it, cut or not. After a cut, it starts at the far
/// edge of the vertical line before it; after a join that does not cut, at its near edge, so
/// that it covers it.
fn part_ends(cell: &Slot, join_after: bool, after_cut: bool, forward: bool) -> (Length, Length) {
    let (a, b) = Layout::line_ends(cell);
    let (mut from, mut to) = (a.min(b), a.max(b));
    let near = |side| cell.sides.parts(side).iter().map(|line| line.start).min();
    let far = |side| {
        cell.sides
            .parts(side)
            .iter()
            .copied()
            .map(LinePart::end)
            .max()
    };
    if join_after {
        if forward {
            to = near(CellSide::Right).unwrap_or(to);
        } else {
            from = far(CellSide::Right).unwrap_or(from);
        }
    }
    if after_cut {
        if forward {
            from = far(CellSide::Left).unwrap_or(from);
        } else {
            to = near(CellSide::Left).unwrap_or(to);
        }
    }
    (from.min(to), from.max(to))
}

impl Layout<'_> {
    /// Draws the line over a cell below several cells above in its parts, between `low` and
    /// `high`. Each end lies on the dot of its own place.
    fn top_parts_lines(&mut self, slot: &Slot, top: RowTop, (low, high): (Length, Length)) {
        let device = self.device;
        let joins = joins(&slot.top_parts, (low, high));
        let forward = slot.left <= slot.right;
        for (i, part) in slot.top_parts.iter().enumerate() {
            let cell = part_slot(&device, slot, part);
            let after = joins.get(i).copied().flatten();
            let after_cut = i
                .checked_sub(1)
                .and_then(|j| joins.get(j).copied().flatten())
                .is_some_and(|join| matches!(join, Join::Cut { .. }));
            if let Some(Join::Cut { vertical, as_wide }) = after {
                self.cut_vertical(&cell, (vertical, as_wide), top);
            }
            let (from, to) = part_ends(&cell, after.is_some(), after_cut, forward);
            let (from, to) = (from.max(low), to.min(high));
            if from < to {
                self.row_top_border(part.border, (device.snap(from), device.snap(to)), top);
            }
        }
    }

    /// Draws the vertical line on the right of a part's `cell` on through the band of the part
    /// `as_wide`, where the lines of the row meet it at a cut.
    fn cut_vertical(&mut self, cell: &Slot, (vertical, as_wide): (Border, Border), top: RowTop) {
        let line_top = self.top_line_dot(top, Length::ZERO);
        let height = self.top_line_end(as_wide, top) - line_top;
        for line in cell.sides.parts(CellSide::Right) {
            let at = Point {
                x: line.start,
                y: line_top,
            };
            self.push_line(vertical, line_rect(vertical, at, line.thick, height));
        }
    }

    /// Draws the borders of a cell. Each row draws its top border inside its own height, and
    /// the last row also draws its bottom border below it. The vertical lines are centered on
    /// the grid lines. The top border's lines and the vertical lines start at the dots of
    /// [`Self::top_line_dot`]; a vertical line ends at the nearest dot of the row's bottom, and
    /// a top line of the next row that starts a dot higher is drawn over its last dot.
    pub(super) fn cell_borders(
        &mut self,
        slot: &Slot,
        (top, bottom): (RowTop, Length),
        last: bool,
    ) {
        if let Some(gaps) = slot.gaps {
            self.cell_box(slot, gaps, (top.at, bottom));
            return;
        }
        let b = &slot.borders;
        let (x0, x1) = Self::line_ends(slot);
        if slot.top_parts.is_empty() {
            if let Some(border) = b.top {
                self.row_top_border(border, (x0, x1), top);
            }
        } else {
            self.top_parts_lines(slot, top, (x0.min(x1), x0.max(x1)));
        }
        if last {
            self.bottom_line(slot, bottom);
        }
        let device = self.device;
        // A vertical line ends where the next row's top line starts, and in the last row where
        // the row's bottom line ends.
        let end = match b.bottom.filter(|_| last) {
            Some(border) => self.bottom_end(border, bottom),
            None => device.snap(bottom),
        };
        let line_top = self.top_line_dot(top, Length::ZERO);
        let (y, height) = (line_top, end - line_top);
        for (border, side) in [(b.left, CellSide::Left), (b.right, CellSide::Right)] {
            let Some(border) = border else { continue };
            for part in slot.sides.parts(side) {
                let at = Point { x: part.start, y };
                self.push_line(border, line_rect(border, at, part.thick, height));
            }
        }
    }

    /// The start and the width of each line of a cell's bottom border, which lies below `y`, on
    /// the device grid, as the target's quirk `TableLines` says: under `RoundsStarts` each line
    /// starts at its place rounded, and under `RoundsCenters` it ends at the nearest dot of its
    /// place plus its exact width, and starts its width in whole dots above that end. An end
    /// that lies exactly half a dot past a whole dot takes the dot on the side of the twips
    /// rest of the row that ends at `y`, as a row's line does ([`row_line_dot`]), and without
    /// one the dot below. A border that the device places as one line
    /// ([`Device::whole_table_border`]) ends so as one line of all its parts, and its lines lie
    /// in it one after the other.
    pub(super) fn bottom_parts(&self, border: Border, y: Length) -> Vec<LinePart> {
        let device = self.device;
        let rest = self
            .table_twips
            .row_end
            .filter(|end| end.at == y)
            .map(|end| end.twips);
        if let Some(parts) = device.whole_table_border(&border) {
            let whole: Length = parts.iter().copied().sum();
            let start = device
                .centered_table_line(|| {
                    row_line_dot(&device, y + border.width, rest, BoxTop::Lower) - whole
                })
                .unwrap_or_else(|| device.snap(y));
            return whole_parts(start, &parts);
        }
        border
            .lines()
            .into_iter()
            .map(|(offset, thickness)| {
                let thick = device.table_line_thickness(thickness);
                let start = device
                    .centered_table_line(|| {
                        let end = y + offset + thickness;
                        row_line_dot(&device, end, rest, BoxTop::Lower) - thick
                    })
                    .unwrap_or_else(|| device.snap(y + offset));
                LinePart { start, thick }
            })
            .collect()
    }

    /// The dot of a line of the row from `top` that starts `offset` below it: the dot that a
    /// line's top takes at that place with the twips rest of the row's top
    /// ([`row_line_dot`]), as a line of text takes it, at the body's top on its page or
    /// below it.
    fn top_line_dot(&self, top: RowTop, offset: Length) -> Length {
        let box_top = self.box_top((top.at, SpaceBefore::Absent));
        row_line_dot(&self.device, top.at + offset, top.rest, box_top)
    }

    /// The lines of a row's top border `border` below `top` on the device: each starts at the
    /// dot of its own top ([`Self::top_line_dot`]), or, for a border that the device places as
    /// one line ([`Device::whole_table_border`]), they lie one after the other from the dot of
    /// the border's top.
    fn top_parts(&self, border: Border, top: RowTop) -> Vec<LinePart> {
        let device = self.device;
        if let Some(parts) = device.whole_table_border(&border) {
            return whole_parts(self.top_line_dot(top, Length::ZERO), &parts);
        }
        border
            .lines()
            .into_iter()
            .map(|(offset, thickness)| LinePart {
                start: self.top_line_dot(top, offset),
                thick: device.table_line_thickness(thickness),
            })
            .collect()
    }

    /// Draws a row's top border `border` from `x0` to `x1` below `top`, in its lines on the
    /// device ([`Self::top_parts`]).
    fn row_top_border(&mut self, border: Border, (x0, x1): (Length, Length), top: RowTop) {
        let device = self.device;
        for part in self.top_parts(border, top) {
            let at = Point {
                x: device.snap(x0),
                y: part.start,
            };
            self.push_line(
                border,
                line_rect(border, at, device.snap(x1 - x0), part.thick),
            );
        }
    }

    /// Where a row's top border `border` from `top` ends on the device, as
    /// [`Self::row_top_border`] draws its lines.
    pub(super) fn top_line_end(&self, border: Border, top: RowTop) -> Length {
        self.top_parts(border, top)
            .into_iter()
            .map(LinePart::end)
            .max()
            .unwrap_or_else(|| self.top_line_dot(top, Length::ZERO))
    }

    /// Where the vertical lines of the last row end on the device: where its bottom border
    /// `border` below `bottom` ends.
    fn bottom_end(&self, border: Border, bottom: Length) -> Length {
        let device = self.device;
        device
            .centered_table_line(|| {
                self.bottom_parts(border, bottom)
                    .into_iter()
                    .map(LinePart::end)
                    .max()
                    .unwrap_or_else(|| device.snap(bottom))
            })
            .unwrap_or_else(|| device.snap(bottom + border.width))
    }

    /// Paints the bands of the top margins of a row's filled cells, whose lines start at `top`
    /// and whose content starts at `inner`, after the row's borders, which start at
    /// `lines_from` in the items. Word paints each cell's right border over the band's height
    /// after the band, so the band lightens the edge of the cell's top and left borders but not
    /// of its right one.
    pub(super) fn top_bands(
        &mut self,
        slots: &[Slot],
        (top, inner): (RowTop, Length),
        lines_from: usize,
    ) {
        for slot in slots {
            let Some(band) = self.top_band(slot, (top, inner)) else {
                continue;
            };
            let rows = (band.y, band.y + band.height);
            self.items.push(Item::Rect(band));
            let right = slot.sides.parts(CellSide::Right);
            let lifted = lift(&mut self.items, lines_from, right, rows);
            self.items.extend_lines(lifted);
        }
    }

    /// The band of a filled cell's top margin, below its top border and between the inner
    /// edges of its side borders, in the cell's fill color, which Word paints again after the
    /// borders of the row: down from the content's top `inner` by the margin, or from the drawn
    /// lower edge of the cell's top line below `top`, also for a cell that continues a merged
    /// region at the top of a page ([`decisions::top_band_rows`]). A cell with cell spacing has
    /// none.
    fn top_band(&self, slot: &Slot, (top, inner): (RowTop, Length)) -> Option<Rect> {
        let color = super::rows::cell_fill_color(slot)?;
        if slot.gaps.is_some() {
            return None;
        }
        let margin = slot.margins.top;
        let device = self.device;
        let below_margin =
            || (margin > Length::ZERO).then(|| (device.snap(inner), device.snap(inner + margin)));
        let from_line = || {
            let borders: Vec<Border> = if slot.top_parts.is_empty() {
                slot.borders.top.into_iter().collect()
            } else {
                slot.top_parts.iter().map(|part| part.border).collect()
            };
            let end = borders
                .iter()
                .map(|&border| self.top_line_end(border, top))
                .max()?;
            let width = borders.iter().map(|border| border.width).max()?;
            let line_top = self.top_line_dot(top, Length::ZERO);
            Some((end, device.snap(line_top + width + margin)))
        };
        let (y0, y1) = decisions::top_band_rows(
            &self.context.quirks,
            (slot.merged_above(), slot.joined_above()),
            below_margin,
            from_line,
        )?;
        let sides = &slot.sides;
        let (x0, x1) = (
            sides
                .edge(CellSide::Left, LineEdge::Inner)
                .unwrap_or(slot.left),
            sides
                .edge(CellSide::Right, LineEdge::Inner)
                .unwrap_or(slot.right),
        );
        Some(Rect {
            x: x0,
            y: y0,
            width: x1 - x0,
            height: y1 - y0,
            color,
        })
    }

    /// The left and right ends of the horizontal lines of a cell: the outer edges of the
    /// vertical borders on its left and right.
    fn line_ends(slot: &Slot) -> (Length, Length) {
        let sides = &slot.sides;
        (
            sides
                .edge(CellSide::Left, LineEdge::Outer)
                .unwrap_or(slot.left),
            sides
                .edge(CellSide::Right, LineEdge::Outer)
                .unwrap_or(slot.right),
        )
    }

    /// Draws the own box of a cell in a table with cell spacing, for a row from `top` with its
    /// cells' content down to `bottom`. The lines lie inside the box, the bottom line below
    /// `bottom`, and each edge of the box goes to the device grid toward the inside of the box.
    fn cell_box(&mut self, slot: &Slot, gaps: Gaps, (top, bottom): (Length, Length)) {
        let b = &slot.borders;
        let device = self.device;
        let inward = |v: Length, up: bool| {
            let down = device.floor(v);
            if up && down < v { device.ceil(v) } else { down }
        };
        let (x0, x1) = (
            inward(slot.left + gaps.left, true),
            inward(slot.right - gaps.right, false),
        );
        let (y0, y1) = (
            inward(top + gaps.top, true),
            inward(bottom + width(b.bottom), false),
        );
        for (border, y) in [(b.top, y0), (b.bottom, y1 - width(b.bottom))] {
            if let Some(border) = border {
                self.border_rect(border, Point { x: x0, y }, x1 - x0, Direction::Across);
            }
        }
        for (border, x) in [(b.left, x0), (b.right, x1 - width(b.right))] {
            if let Some(border) = border {
                self.border_rect(border, Point { x, y: y0 }, y1 - y0, Direction::Down);
            }
        }
    }

    /// Draws the table's own lines beside row `index` of a table with cell spacing, whose slots
    /// on its page are `slots`, from `top` down to `bottom`, the spacing below the cells' boxes:
    /// the left and the right line, the line `opening` above the row, and the line below it
    /// where `end` closes the table or its part on the page.
    pub(super) fn table_outline(
        &mut self,
        shape: &Shape,
        (index, slots): (usize, &[Slot]),
        (top, bottom): (Length, Length),
        (opening, end): (Option<Border>, OutlineEnd),
    ) {
        let Some(spacing) = shape.grid.spacing() else {
            return;
        };
        let (Some(first), Some(last)) = (slots.first(), slots.last()) else {
            return;
        };
        let lines = shape.grid.outline(index);
        let x0 = first.left - width(lines.left).div_toward_zero(2);
        let x1 = last.right + width(lines.right).div_toward_zero(2);
        if let Some(border) = opening {
            self.border_rect(border, Point { x: x0, y: top }, x1 - x0, Direction::Across);
        }
        let closing = match end {
            OutlineEnd::Row => None,
            OutlineEnd::Table => Some((spacing, lines.bottom)),
            OutlineEnd::Page(line) => Some((Length::ZERO, line)),
        };
        let mut end = bottom;
        if let Some((gap, line)) = closing {
            end += gap;
            if let Some(border) = line {
                self.border_rect(border, Point { x: x0, y: end }, x1 - x0, Direction::Across);
            }
            end += width(line);
        }
        for (border, x) in [(lines.left, first.left), (lines.right, last.right)] {
            if let Some(border) = border {
                let start = x - border.width.div_toward_zero(2);
                self.border_rect(
                    border,
                    Point { x: start, y: top },
                    end - top,
                    Direction::Down,
                );
            }
        }
    }

    /// Draws the bottom border of a cell below `y`, from the left edge of the line on the left
    /// of the cell to the right edge of the line on its right.
    pub(super) fn bottom_line(&mut self, slot: &Slot, y: Length) {
        if let Some(border) = slot.borders.bottom {
            for line in self.bottom_rects(slot, border, y) {
                self.push_line(border, line);
            }
        }
    }

    /// Takes back the bottom border line that [`Self::bottom_line`] drew below `slot`'s cell
    /// at `y`, each of its rectangles that still stands among the border lines, so that the
    /// line of another border can stand there alone.
    pub(super) fn take_back_bottom_line(&mut self, slot: &Slot, y: Length) {
        if let Some(border) = slot.borders.bottom {
            for line in self.bottom_rects(slot, border, y) {
                if let Some(at) = self.items.place_of_line(&Item::Rect(line)) {
                    self.items.take_out(at);
                }
            }
        }
    }

    /// Each rectangle of the bottom border `border` of `slot`'s cell below `y`, on the
    /// device grid.
    fn bottom_rects(&self, slot: &Slot, border: Border, y: Length) -> Vec<Rect> {
        let (x0, x1) = Self::line_ends(slot);
        let (left, length) = (self.device.snap(x0), self.device.snap(x1 - x0));
        self.bottom_parts(border, y)
            .into_iter()
            .map(|part| {
                line_rect(
                    border,
                    Point {
                        x: left,
                        y: part.start,
                    },
                    length,
                    part.thick,
                )
            })
            .collect()
    }

    /// Adds a border line from `start` that runs in `direction` for a length on the device
    /// grid, as wide as the target's quirk `TableLines` says.
    fn border_rect(&mut self, border: Border, start: Point, length: Length, direction: Direction) {
        let device = self.device;
        for (offset, thickness) in border.lines() {
            let thick = device.table_line_thickness(thickness);
            let line = match direction {
                Direction::Down => {
                    let at = Point {
                        x: device.snap(start.x + offset),
                        y: device.snap(start.y),
                    };
                    line_rect(border, at, thick, device.snap(length))
                }
                Direction::Across => {
                    let at = Point {
                        x: device.snap(start.x),
                        y: device.snap(start.y + offset),
                    };
                    line_rect(border, at, device.snap(length), thick)
                }
            };
            self.push_line(border, line);
        }
    }

    /// Splits the lines that a row drew from item `from` on at their junctions, as Word draws
    /// them: each horizontal line runs between the junctions, each vertical line between them,
    /// and each junction is a square of its own, drawn once for every line that ends there and
    /// at least once. Two vertical lines that lie on each other are one line
    /// ([`drawn_once`]). A piece of a line that is to be drawn with dashes is drawn as its
    /// dashes from its left or top end ([`dashes`]); a square is drawn whole. `above` holds the
    /// left edge and bottom of the vertical lines of the row above, which run on into this
    /// row. Gives the same for this row. A piece whose dashes would take the page beyond
    /// [`MAX_DASHED_PAGE_ITEMS`] items is drawn whole, with the warning `limit-reached` for the
    /// table's part `part`, and so are all lines of a row whose edges a length does not reach
    /// ([`drawn_lines`]).
    pub(super) fn split_at_junctions(
        &mut self,
        from: usize,
        above: &[Point],
        part: &f_office_warnings::Name,
    ) -> Vec<Point> {
        let items = self.items.placed(from..self.items.len());
        let Some(lines) = drawn_lines(items, |at| self.items.line_dash(at)) else {
            self.output.warnings.push(crate::Warning::LimitReached {
                part: part.clone(),
                limit: crate::warnings::Limit::LineRange,
            });
            return Vec::new();
        };
        let (horizontal, vertical): (Vec<_>, Vec<_>) = lines
            .into_iter()
            .partition(|line| Direction::of(line.edges) == Direction::Across);
        let cell_cuts = decisions::cell_dash_cuts(&self.context.quirks, ())
            .map_or_else(Vec::new, |()| cell_cuts(&horizontal, &vertical));
        let horizontal = joined(horizontal);
        let drawn = drawn_once(&vertical);
        let squares = junctions(&horizontal, &drawn, above);
        let order = SquareOrder::of(&squares);
        let dashed_order = SquareOrder::of(&[squares.as_slice(), &cell_cuts].concat());
        // The items of the page before the row's lines, for the limit of the dashes.
        let held = self.items.count_before(from);
        let mut pieces: Vec<(Edges<Length>, Rgb)> = Vec::new();
        let mut whole = false;
        for (lines, direction) in [(&horizontal, Direction::Across), (&drawn, Direction::Down)] {
            for line in lines {
                let order = if line.dash.is_some() && direction == Direction::Across {
                    &dashed_order
                } else {
                    &order
                };
                for piece in cut(line.edges, order, direction) {
                    let (drawn, limited) =
                        drawn_piece(piece, line.dash, direction, held + pieces.len());
                    whole |= limited;
                    pieces.extend(drawn.into_iter().map(|b| (b, line.color)));
                }
            }
        }
        if whole {
            self.output.warnings.push(crate::Warning::LimitReached {
                part: part.clone(),
                limit: crate::warnings::Limit::TableDashes,
            });
        }
        for square in &squares {
            pieces.extend(std::iter::repeat_n(
                (square.edges, square.color),
                square.count,
            ));
        }
        self.items.cut(from);
        self.items
            .extend_lines(pieces.into_iter().map(|(b, color)| {
                Item::Rect(Rect {
                    x: b.left,
                    y: b.top,
                    width: b.width(),
                    height: b.height(),
                    color,
                })
            }));
        vertical
            .iter()
            .map(|v| Point {
                x: v.edges.left,
                y: v.edges.bottom,
            })
            .collect()
    }

    /// Adds one filled rectangle of a border, once: two cells side by side give the same line
    /// between them, and Word draws it once. Only the border lines on the items being filled
    /// count ([`PageItems`]). The line keeps the dashes of the border's style where the
    /// target draws a table's lines of a dash style as their dashes.
    fn push_line(&mut self, border: Border, line: Rect) {
        let line = Item::Rect(line);
        if !self.items.holds_line(&line) {
            let dash = decisions::table_dash(&self.context.quirks, border.dash);
            self.items.push_line(line, dash);
        }
    }
}

/// The filled rectangle of a border line from `at`, `width` across and `height` down, in the
/// border's color as drawn.
fn line_rect(border: Border, at: Point, width: Length, height: Length) -> Rect {
    Rect {
        x: at.x,
        y: at.y,
        width,
        height,
        color: border.color.drawn(),
    }
}

/// The start on the device of a line `thick` wide that is centered on `center`: the center
/// rounded to the nearest dot, less half the line, with the extra dot of an odd width before
/// the center.
fn centered(device: &Device, center: Length, thick: Length) -> Length {
    around(device, device.snap(center), thick)
}

/// The start of a line `thick` wide around the dot `dot`, the extra dot of an odd width on the
/// left.
fn around(device: &Device, dot: Length, thick: Length) -> Length {
    let dots = device.count(thick, Rounding::TowardZero);
    dot - device.dots((dots + 1) / 2)
}

/// One line of a border across its width, on the device grid: where it starts and how thick it
/// is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct LinePart {
    pub(super) start: Length,
    pub(super) thick: Length,
}

impl LinePart {
    /// Where the line ends: its start and its thickness.
    fn end(self) -> Length {
        self.start + self.thick
    }
}

/// A side of a cell: its left or its right.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum CellSide {
    Left,
    Right,
}

/// An edge of the line on a side of a cell: the one toward the cell's inside or the one toward
/// its outside.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum LineEdge {
    Inner,
    Outer,
}

/// The side lines of a cell: the parts of its left and right lines as they are drawn
/// ([`vertical_parts`]), made once with the cell's slot. A side without a line has no parts.
/// They also hold where the cell's fill starts and ends between them on the device grid
/// ([`SideLines::fill`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct SideLines {
    left: Vec<LinePart>,
    right: Vec<LinePart>,
    fill: (Length, Length),
}

impl SideLines {
    /// The side lines of `slot`'s cell on `device`, from its left and right borders on its
    /// grid lines, and the ends of its fill on the device grid: on each side, the place from
    /// which a line on that grid line is centered under `TableLines::RoundsCenters`
    /// ([`line_place`]), moved toward the cell's inside by half the width of the cell's own
    /// border on that side rounded down to whole twips (none without a border of its own), and
    /// rounded to the device grid as that line's center is ([`center_dot`]).
    pub(super) fn of(device: &Device, slot: &Slot) -> Self {
        let parts = |border: Option<Border>, x| {
            border.map_or_else(Vec::new, |border| vertical_parts(device, border, x, slot))
        };
        let inset = |border: Option<Border>| {
            width(border)
                .div_toward_zero(2)
                .down_to_whole(Length::UNITS_PER_TWIP)
        };
        let fill_end = |x, inset| center_dot(device, slot, line_place(slot, x) + inset);
        Self {
            left: parts(slot.borders.left, slot.left),
            right: parts(slot.borders.right, slot.right),
            fill: (
                fill_end(slot.left, inset(slot.own_borders.left)),
                fill_end(slot.right, -inset(slot.own_borders.right)),
            ),
        }
    }

    /// The left and right x of the cell's fill on the device grid, as [`SideLines::of`] makes
    /// them.
    pub(super) const fn fill(&self) -> (Length, Length) {
        self.fill
    }

    /// The parts of the line on `side`.
    pub(super) fn parts(&self, side: CellSide) -> &[LinePart] {
        match side {
            CellSide::Left => &self.left,
            CellSide::Right => &self.right,
        }
    }

    /// The edge `edge` of the line on `side`, or `None` when the side has no line: the right
    /// edge of the left line's rightmost part and the left edge of the right line's leftmost
    /// part inside, and the other two outside.
    pub(super) fn edge(&self, side: CellSide, edge: LineEdge) -> Option<Length> {
        let parts = self.parts(side).iter();
        match (side, edge) {
            (CellSide::Left, LineEdge::Inner) | (CellSide::Right, LineEdge::Outer) => {
                parts.map(|part| part.end()).max()
            }
            (CellSide::Left, LineEdge::Outer) | (CellSide::Right, LineEdge::Inner) => {
                parts.map(|part| part.start).min()
            }
        }
    }
}

/// The place from which a line whose middle lies at `middle` is centered under
/// `TableLines::RoundsCenters`: measured from the column edge rounded to the device grid
/// (`slot.rounding`), and moved right by what the table's grid shift gains in whole twips
/// (`slot.twip_rest`).
fn line_place(slot: &Slot, middle: Length) -> Length {
    middle + slot.twip_rest - slot.rounding.unwrap_or(Length::ZERO)
}

/// The dot of a line's center `center` under `TableLines::RoundsCenters`: the nearest dot, an
/// exact half up, or down for a center left of the dot `slot.halves_away_from`.
fn center_dot(device: &Device, slot: &Slot, center: Length) -> Length {
    match slot.halves_away_from {
        Some(edge) if center < edge => device.snap_half_down(center),
        _ => device.snap(center),
    }
}

/// The start and the width of each line of a vertical border on the grid line `x`, on the
/// device grid, as the target's quirk `TableLines` says. Under `RoundsStarts`, the border
/// at the table's left edge, and every border of a centered or right-aligned table, is
/// centered on its grid line, and each of its lines is then rounded to the device grid;
/// inside a left-aligned table, each line of a border is centered on its own place
/// measured from the text column's edge rounded to the device grid, and then rounded.
/// Under `RoundsCenters`, each line is centered on its own place, measured in a
/// left-aligned table from the text column's edge rounded to the device grid, a half down,
/// or in a centered table under `CenteredTableLines::FromOuterEdge` from the outer edge of
/// its left border rounded to the device grid, and moved right by what the table's grid
/// shift gains in whole twips, or before mode 15 under
/// `CenteredTableLinesBefore15::FromColumnEdge` from the text column's edge rounded to the
/// device grid, and moved left by the half twip of an odd free width; the
/// center is then rounded to the device grid, an exact half up, or down for a center left
/// of the column edge's dot. Of a line an odd number of device dots wide, the extra unit
/// lies on the left. A border that the device places as one line
/// ([`Device::whole_table_border`]) is placed so, as one line of all its parts on the
/// border's middle, and its lines lie in it one after the other.
fn vertical_parts(device: &Device, border: Border, x: Length, slot: &Slot) -> Vec<LinePart> {
    let left = x - border.width.div_toward_zero(2);
    // The start of a line `thick` wide whose middle lies at `middle` and whose exact start lies
    // at `exact`.
    let start_of = |middle: Length, exact: Length, thick: Length| {
        let around_center = || {
            around(
                device,
                center_dot(device, slot, line_place(slot, middle)),
                thick,
            )
        };
        device
            .centered_table_line(around_center)
            .unwrap_or_else(|| match slot.rounding {
                Some(rounding) if x != slot.edge => centered(device, middle - rounding, thick),
                _ => device.snap(exact),
            })
    };
    if let Some(parts) = device.whole_table_border(&border) {
        let middle = left + border.width.div_toward_zero(2);
        let whole: Length = parts.iter().copied().sum();
        return whole_parts(start_of(middle, left, whole), &parts);
    }
    border
        .lines()
        .into_iter()
        .map(|(offset, thickness)| {
            let thick = device.table_line_thickness(thickness);
            let middle = left + offset + thickness.div_toward_zero(2);
            LinePart {
                start: start_of(middle, left + offset, thick),
                thick,
            }
        })
        .collect()
}

/// The lines of a border that the device places as one line from `start`
/// ([`Device::whole_table_border`]), whose parts on the device are `parts`, a line, a gap, a
/// line and so on: the lines one after the other with their gaps between them.
fn whole_parts(start: Length, parts: &[Length]) -> Vec<LinePart> {
    parts
        .iter()
        .scan(start, |at, thick| {
            let line = LinePart {
                start: *at,
                thick: *thick,
            };
            *at += *thick;
            Some(line)
        })
        .step_by(2)
        .collect()
}

/// A drawn line: its edges, its color and the dashes that it is to be drawn with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct DrawnLine {
    edges: Edges<Length>,
    color: Rgb,
    dash: Option<DashStyle>,
}

/// A junction square: its edges, its color and how many times it is drawn.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Junction {
    edges: Edges<Length>,
    color: Rgb,
    count: usize,
}

/// The way that a line of a table runs: across the page, as a horizontal line does, or down
/// it, as a vertical line does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Direction {
    Across,
    Down,
}

impl Direction {
    /// The way that the line with the edges `b` runs: across when it is wider than high.
    fn of(b: Edges<Length>) -> Self {
        if b.width() > b.height() {
            Self::Across
        } else {
            Self::Down
        }
    }
}

/// The rectangles of `items`, each with the dashes that `dash` gives for its place, or `None`
/// when anything else is among them or a rectangle's edge lies beyond the range of a length.
/// The lines of a row are only rectangles ([`Layout::push_line`]), so only an edge beyond the
/// range gives `None`.
fn drawn_lines<'i>(
    items: impl Iterator<Item = (usize, &'i Item)>,
    dash: impl Fn(usize) -> Option<DashStyle>,
) -> Option<Vec<DrawnLine>> {
    items
        .map(|(at, item)| match item {
            Item::Rect(r) => Some(DrawnLine {
                edges: Edges::placed(r.x, r.y, r.width, r.height)?,
                color: r.color,
                dash: dash(at),
            }),
            _ => None,
        })
        .collect()
}

/// Joins the horizontal lines that continue each other, as the top lines of cells side by
/// side do, into one line.
fn joined(mut lines: Vec<DrawnLine>) -> Vec<DrawnLine> {
    lines.sort_by_key(|line| (line.edges.top, line.edges.bottom, line.edges.left));
    let mut out: Vec<DrawnLine> = Vec::new();
    for line in lines {
        let b = line.edges;
        match out.last_mut() {
            Some(last)
                if (last.color, last.dash) == (line.color, line.dash)
                    && (last.edges.top, last.edges.bottom) == (b.top, b.bottom)
                    && b.left <= last.edges.right =>
            {
                last.edges.right = last.edges.right.max(b.right);
            }
            _ => out.push(line),
        }
    }
    out
}

/// The vertical lines of a row with each line that lies on another one, at the same place, as
/// wide and in the same color, taken into the first as one line over both lengths, in the order
/// of the first lines. In a table's last row, the two cells beside a vertical line each give
/// it, and a cell with a bottom border ends it where its bottom line ends, a cell without one
/// at the row's bottom: the two lines differ in length, so [`Layout::push_line`] keeps both,
/// and Word draws one line.
fn drawn_once(lines: &[DrawnLine]) -> Vec<DrawnLine> {
    let mut out: Vec<DrawnLine> = Vec::new();
    // The places in `out` of the lines with each left and right edge, color and dashes.
    let mut alike: HashMap<_, Vec<usize>> = HashMap::new();
    for &line in lines {
        let b = line.edges;
        let places = alike
            .entry((b.left, b.right, line.color, line.dash))
            .or_default();
        let on = places
            .iter()
            .filter_map(|&at| out.get(at).map(|o| (at, o.edges)))
            .find(|(_, o)| b.top < o.bottom && o.top < b.bottom);
        if let Some(o) = on.and_then(|(at, _)| out.get_mut(at)) {
            o.edges.top = o.edges.top.min(b.top);
            o.edges.bottom = o.edges.bottom.max(b.bottom);
        } else {
            places.push(out.len());
            out.push(line);
        }
    }
    out
}

/// Takes out the pieces of the lines of a right border (its `parts`) that lie beside a band
/// from `y0` to `y1`, among the items from `from`, and returns them, cut at `y1`, for painting
/// after the band. The pieces below `y1` stay in place. A piece that goes out whole leaves its
/// place empty ([`PageItems::take_out`]).
fn lift(
    items: &mut PageItems,
    from: usize,
    parts: &[LinePart],
    (y0, y1): (Length, Length),
) -> Vec<Item> {
    let mut lifted = Vec::new();
    for index in from..items.len() {
        let Some(Item::Rect(r)) = items.item(index) else {
            continue;
        };
        let (top, bottom) = (r.y, r.y + r.height);
        if !parts.contains(&LinePart {
            start: r.x,
            thick: r.width,
        }) || top >= y1
            || bottom <= y0
        {
            continue;
        }
        let cut = bottom.min(y1);
        lifted.push(Item::Rect(Rect {
            height: cut - top,
            ..r.clone()
        }));
        if cut < bottom {
            if let Some(Item::Rect(r)) = items.item_mut(index) {
                r.y = cut;
                r.height = bottom - cut;
            }
        } else {
            items.take_out(index);
        }
    }
    lifted
}

/// The cuts of the dashed lines across `horizontal`, as the cells of a row draw them, where one
/// cell's line passes on into the next cell's with no line of `vertical` down between them:
/// for each such pass, a room that starts at the next cell's line and is as long as the line is
/// wide, drawn no times, which [`cut`] cuts the lines at. A pass is also where the next cell's
/// line starts after the line before it ends, by less than the line is wide, as the rounded
/// ends of two cells' lines can leave.
fn cell_cuts(horizontal: &[DrawnLine], vertical: &[DrawnLine]) -> Vec<Junction> {
    let mut lines: Vec<DrawnLine> = horizontal
        .iter()
        .copied()
        .filter(|line| line.dash.is_some())
        .collect();
    lines.sort_by_key(|line| (line.edges.top, line.edges.bottom, line.edges.left));
    lines
        .windows(2)
        .filter_map(|pair| {
            let [before, after] = pair else {
                return None;
            };
            let (a, b) = (before.edges, after.edges);
            let thick = b.height();
            let continues = (before.color, before.dash) == (after.color, after.dash)
                && (a.top, a.bottom) == (b.top, b.bottom)
                && a.left < b.left
                && b.left < a.right + thick;
            let room = Edges {
                right: b.left + thick,
                ..b
            };
            // A line down within a line's width of the pass meets the line there already.
            let crossed = vertical.iter().any(|v| {
                let v = v.edges;
                v.left < room.right
                    && v.right > room.left - thick
                    && v.top < room.bottom
                    && v.bottom > room.top
            });
            (continues && !crossed).then_some(Junction {
                edges: room,
                color: after.color,
                count: 0,
            })
        })
        .collect()
}

/// The squares where horizontal and vertical lines meet, each with the number of times Word
/// draws it: once for each line that ends there, and at least once. A vertical line whose left
/// edge and top are in `above` runs on from the row above.
fn junctions(horizontal: &[DrawnLine], vertical: &[DrawnLine], above: &[Point]) -> Vec<Junction> {
    let mut squares: Vec<Junction> = Vec::new();
    let mut seen = HashSet::new();
    for line in horizontal {
        let h = line.edges;
        for v in vertical.iter().map(|line| line.edges) {
            let j = Edges {
                left: h.left.max(v.left),
                top: h.top.max(v.top),
                right: h.right.min(v.right),
                bottom: h.bottom.min(v.bottom),
            };
            if j.right <= j.left
                || j.bottom <= j.top
                || !seen.insert((j.left, j.top, j.right, j.bottom))
            {
                continue;
            }
            let h_ends = j.left <= h.left || j.right >= h.right;
            let runs_on = above.contains(&Point {
                x: v.left,
                y: v.top,
            });
            let v_ends = (j.top <= v.top && !runs_on) || j.bottom >= v.bottom;
            let ends = usize::from(h_ends) + usize::from(v_ends);
            squares.push(Junction {
                edges: j,
                color: line.color,
                count: ends.max(1),
            });
        }
    }
    squares
}

/// The squares where the lines of a row meet, as [`cut`] reads them: down by their tops and
/// across by their left edges, with the height of the highest and the width of the widest.
struct SquareOrder {
    down: Vec<Edges<Length>>,
    across: Vec<Edges<Length>>,
    height: Length,
    width: Length,
}

impl SquareOrder {
    fn of(squares: &[Junction]) -> Self {
        let mut down: Vec<_> = squares.iter().map(|square| square.edges).collect();
        let mut across = down.clone();
        down.sort_unstable_by_key(|j| j.top);
        across.sort_unstable_by_key(|j| j.left);
        let most = |size: fn(Edges<Length>) -> Length| {
            down.iter().copied().map(size).max().unwrap_or(Length::ZERO)
        };
        let (height, width) = (most(Edges::height), most(Edges::width));
        Self {
            down,
            across,
            height,
            width,
        }
    }

    /// The squares that can lie on the line `b` that runs in `direction`: for a line across,
    /// those whose top is above its bottom and less than the highest square's height above
    /// its top, and for a line down the same across.
    fn near(&self, b: Edges<Length>, direction: Direction) -> &[Edges<Length>] {
        let (order, size, start, end, first): (_, _, _, _, fn(&Edges<Length>) -> Length) =
            match direction {
                Direction::Across => (&self.down, self.height, b.top, b.bottom, |j| j.top),
                Direction::Down => (&self.across, self.width, b.left, b.right, |j| j.left),
            };
        let from = order.partition_point(|j| first(j) + size <= start);
        let to = order.partition_point(|j| first(j) < end);
        order.get(from..to.max(from)).unwrap_or_default()
    }
}

/// The pieces of a line `b` that runs in `direction` between the squares on it, along its
/// length.
fn cut(b: Edges<Length>, squares: &SquareOrder, direction: Direction) -> Vec<Edges<Length>> {
    let mut gaps: Vec<(Length, Length)> = squares
        .near(b, direction)
        .iter()
        .copied()
        .filter(|j| j.left < b.right && j.right > b.left && j.top < b.bottom && j.bottom > b.top)
        .map(|j| span(j, direction))
        .collect();
    gaps.sort_unstable();
    let (start, end) = span(b, direction);
    let mut spans = Vec::new();
    let mut at = start;
    for (g0, g1) in gaps {
        if g0 > at {
            spans.push((at, g0.min(end)));
        }
        at = at.max(g1);
    }
    if at < end {
        spans.push((at, end));
    }
    spans
        .into_iter()
        .map(|span| along(b, span, direction))
        .collect()
}

/// The start and the end of the box `b` in `direction`: its left and right edges across, its
/// top and bottom down.
fn span(b: Edges<Length>, direction: Direction) -> (Length, Length) {
    match direction {
        Direction::Across => (b.left, b.right),
        Direction::Down => (b.top, b.bottom),
    }
}

/// The part of the line `b` that runs in `direction` from `a` to `z` along its length.
fn along(b: Edges<Length>, (a, z): (Length, Length), direction: Direction) -> Edges<Length> {
    match direction {
        Direction::Across => Edges {
            left: a,
            right: z,
            ..b
        },
        Direction::Down => Edges {
            top: a,
            bottom: z,
            ..b
        },
    }
}

/// The rectangles that draw the piece `b` of a line of the dash style `dash` that runs in
/// `direction`, on a page whose body holds `held` items before them: the piece's dashes, or the
/// piece whole when it has no dash style or when its dashes would take the page beyond
/// [`MAX_DASHED_PAGE_ITEMS`] items. Says whether the limit made the piece whole.
fn drawn_piece(
    b: Edges<Length>,
    dash: Option<DashStyle>,
    direction: Direction,
    held: usize,
) -> (Vec<Edges<Length>>, bool) {
    match dash {
        Some(dash)
            if held.saturating_add(dash_count(b, dash, direction)) <= MAX_DASHED_PAGE_ITEMS =>
        {
            (dashes(b, dash, direction), false)
        }
        Some(_) => (vec![b], true),
        None => (vec![b], false),
    }
}

/// The start and the end of the piece `b` along its line, which runs in `direction`, and the
/// line's width across it.
fn along_and_across(b: Edges<Length>, direction: Direction) -> (Length, Length, Length) {
    let (start, end) = span(b, direction);
    let width = match direction {
        Direction::Across => b.height(),
        Direction::Down => b.width(),
    };
    (start, end, width)
}

/// At least as many dashes as [`dashes`] gives the piece `b` of a line of the dash style
/// `dash`: the dashes of each repeat of the style's pattern that the piece reaches into.
fn dash_count(b: Edges<Length>, dash: DashStyle, direction: Direction) -> usize {
    let (start, end, width) = along_and_across(b, direction);
    let pattern = dash.pattern();
    let widths: i64 = pattern.iter().sum();
    let repeat = width.units().saturating_mul(widths);
    if repeat <= 0 {
        return 1;
    }
    let repeats = (end - start).units().max(0) / repeat + 1;
    usize::try_from(repeats)
        .unwrap_or(usize::MAX)
        .saturating_mul(pattern.len().div_ceil(2))
}

/// The dashes of the piece `b` of a line of the dash style `dash`: from a dash at the piece's
/// left end, or its top end for a piece that runs down, each dash and each gap the number of
/// the line's widths across that the style's pattern gives, and the last dash cut at the
/// piece's end. A piece without a width is drawn whole.
fn dashes(b: Edges<Length>, dash: DashStyle, direction: Direction) -> Vec<Edges<Length>> {
    let (start, end, width) = along_and_across(b, direction);
    if width <= Length::ZERO {
        return vec![b];
    }
    let mut out = Vec::new();
    let mut at = start;
    // The pattern alternates a dash and a gap, from a dash.
    for (index, widths) in dash.pattern().iter().cycle().enumerate() {
        if at >= end {
            break;
        }
        let next = at + width * *widths;
        if index % 2 == 0 {
            out.push(along(b, (at, next.min(end)), direction));
        }
        at = next;
    }
    out
}

#[cfg(test)]
mod tests;