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
//! Tables: grid lines, cell text areas, row heights, page breaks and borders.
mod borders;
mod clips;
mod floating;
mod keeps;
mod merges;
mod nested;
mod rows;
mod shape;
mod split;
mod turned;
use std::borrow::Cow;
use std::ops::Range;
use std::rc::Rc;
use f_office_paint::{Item, Point};
use f_office_units::Length;
use super::decisions::{self, CellGaps, CellParts, DeletedTableAtTop};
use super::{CellEdgeParts, Column, Layout, Rest, Within};
use crate::body::Block;
use crate::props::{Anchor, Border, Color};
use crate::quirks::Quirks;
use crate::styles::TableStyle;
use crate::table::{
Cell, HeightRule, Region, Row, Table, TableAlignment, TablePlacement, VerticalAlign,
};
pub(super) use clips::CellClips;
use keeps::Around;
use merges::Merges;
pub(super) use rows::CellFloor;
use shape::{Shape, TableGrid};
/// How the rows of a table break across pages.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Paging {
/// They do not: a table in a cell, or a floating table that stays whole.
Whole,
/// A row that does not end above the body's end goes on on the next page.
ByBottom,
/// A row that does not start above the body's end goes on on the next page: a floating
/// table that breaks, before the mode from which its rows fit by their bottom.
ByTop,
}
pub(super) use split::Fragment;
pub(super) use turned::{DOWN, UP, after, turn_item};
/// Four values, one for each side of a cell.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Sides<T> {
top: T,
left: T,
bottom: T,
right: T,
}
/// How a cell meets a merged region (`w:vMerge`) that comes down from the row above it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MergeAbove {
/// The cell continues no merged region from the row above.
Unmerged,
/// The cell continues a merged region from the row above at the top of a page, or below the
/// header rows that repeat there: it starts the region's part on that page and takes a top
/// line of its own.
PartStart,
/// The cell continues a merged region from the row above on the same page, below no
/// repeated header rows, and so has no top line of its own.
Joined,
}
impl MergeAbove {
/// How a cell meets the row above it: `merged` when it continues a merged region from that
/// row, and `joined` when it also meets that row on the same page, below no repeated header
/// rows.
const fn of(merged: bool, joined: bool) -> Self {
match (merged, joined) {
(false, _) => Self::Unmerged,
(true, false) => Self::PartStart,
(true, true) => Self::Joined,
}
}
}
/// A cell with its grid lines and its settings after the cascade.
#[derive(Clone)]
struct Slot<'t> {
cell: &'t Cell,
/// The previous cell of the same row in logical document stream order, if any.
prev_cell: Option<&'t Cell>,
/// The next cell of the same row in logical document stream order, if any.
next_cell: Option<&'t Cell>,
/// What the table style gives the paragraphs of the cell.
style: TableStyle,
/// The shading that the cell's fill draws (see `TableGrid::fill_shading`).
shading: Option<Color>,
/// The first grid column that the cell covers.
first: usize,
/// The index of its row in the table.
row: usize,
/// How the cell meets a merged region that comes down from the row above.
merge_above: MergeAbove,
/// Whether the cell in the row below continues this cell's merged region.
merged_below: bool,
/// The x of the grid line on its left.
left: Length,
/// The x of the grid line on its right.
right: Length,
/// The x of the table's leftmost grid line.
edge: Length,
/// How far the place that the table's lines are drawn from lies right of the device grid
/// (see `TableGrid::rounding`).
rounding: Option<Length>,
/// What the table's grid shift gains when it is rounded up to whole twips (see
/// `TableGrid::twip_rest`).
twip_rest: Length,
/// The dot that a line's center on exactly half a dot is rounded away from (see
/// `TableGrid::halves_away_from`).
halves_away_from: Option<Length>,
/// What the cell's upright text start loses to the half twip of the table's place (see
/// `TableGrid::text_rest`).
text_rest: Length,
/// The outer edge of the table in fixed-point points (see `TableGrid::outer_place`).
outer_place: Option<crate::grid::FixedPlace>,
margins: Sides<Length>,
/// Whether the cell, the table or its style sets the left margin, or the target gives a left
/// margin that none of them sets its default.
left_margin_set: bool,
borders: Sides<Option<Border>>,
/// The cell's own borders, from its properties, its table style's regions or the table's
/// borders, before they meet the lines of the cells beside it and above it.
own_borders: Sides<Option<Border>>,
/// The height that the cell's top border takes above its top margin: the cell's own top
/// line, or the part of the line drawn there (`borders.top`, the wider of the cell's own
/// line and the bottom line of the cell above) below the cell's top margin, whichever is
/// larger.
top_room: Length,
/// The height that the cell's bottom border takes below a row at the bottom of the table or
/// page: its width and space, or the space of a `none` bottom side with `w:space`.
bottom_room: Length,
/// The parts in which the cell's top line is drawn below the row before it on one page,
/// where each cell above draws its own bottom line along its width; empty where the top
/// line is drawn whole (`borders.top`), as below one cell that covers the whole cell.
top_parts: Vec<TopPart>,
/// Where the cell's own box lies, in a table with cell spacing.
gaps: Option<Gaps>,
/// The parts of the cell's left and right lines as they are drawn, made once with the
/// slot.
sides: borders::SideLines,
}
/// A part of a cell's top line, which a cell of the row above draws along its width: the line
/// `border` with the ends that a top line of a cell between the grid lines `left` and `right`
/// and with the vertical lines `sides` would have, within the ends of the cell's own top line.
/// Over grid columns that no cell above covers, `left` and `right` are the grid lines of those
/// columns and `sides` the lines of the cells above beside them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct TopPart {
left: Length,
right: Length,
sides: (Option<Border>, Option<Border>),
border: Border,
}
impl TopPart {
/// The part of a right-to-left table, whose grid is mirrored, as [`Slot::mirrored`] gives
/// its slot.
fn mirrored(self) -> Self {
Self {
left: self.right,
right: self.left,
sides: (self.sides.1, self.sides.0),
..self
}
}
}
/// In a table with cell spacing, each cell draws its own box. The gaps run from the grid lines
/// on the left and the right of the cell, and from the top and the bottom of its row, to the
/// outer edges of the box.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Gaps {
left: Length,
right: Length,
top: Length,
bottom: Length,
/// The width of the table's own line that closes the table right below the box, in its
/// last row: zero in the other rows and where the table has no bottom line.
closing: Length,
/// The table's cell spacing.
spacing: Length,
}
impl<T> Sides<T> {
/// The sides with left and right swapped.
fn mirrored(self) -> Self {
Self {
left: self.right,
right: self.left,
..self
}
}
}
impl Slot<'_> {
/// The vertical alignment of the cell's content: the cell's own `w:vAlign`, else the one
/// that its table style gives it, from the style or from a region that the cell is in.
fn align(&self) -> Option<VerticalAlign> {
self.cell.align.or(self.style.align)
}
/// The slot of a right-to-left table, whose grid is mirrored: its edges come from the
/// mirrored grid lines in the other order, and its leading border, margin and gap, which
/// the cell gives as left, are at the right.
fn mirrored(self) -> Self {
Self {
left: self.right,
right: self.left,
margins: self.margins.mirrored(),
borders: self.borders.mirrored(),
own_borders: self.own_borders.mirrored(),
top_parts: self.top_parts.into_iter().map(TopPart::mirrored).collect(),
gaps: self.gaps.map(|gaps| Gaps {
left: gaps.right,
right: gaps.left,
..gaps
}),
..self
}
}
/// Whether the slot's cell continues a merged region from the row above.
fn merged_above(&self) -> bool {
self.merge_above != MergeAbove::Unmerged
}
/// Whether the slot's cell continues a merged region from the row above on the same page,
/// with no top line of its own ([`MergeAbove::Joined`]).
fn joined_above(&self) -> bool {
self.merge_above == MergeAbove::Joined
}
/// Whether the slot lays its text out turned: a cell with a text direction that is no part
/// of a vertical merge. A turned cell that starts a merge keeps its text upright, since its
/// lines would break to the region's height, which this layout does not know yet.
fn turned(&self) -> bool {
!self.upright() && !self.merged_above() && !self.merged_below
}
/// Whether the slot's cell has upright text, without a text direction.
fn upright(&self) -> bool {
self.cell.direction == crate::table::TextDirection::Upright
}
/// The text column of the cell, in the room that [`decisions::cell_text_room`] gives it.
fn column(&self, quirks: &crate::quirks::Quirks) -> Column {
let parts = CellParts {
left: self.left,
right: self.right,
margins: (self.margins.left, self.margins.right),
left_margin_set: self.left_margin_set,
lines: (width(self.borders.left), width(self.borders.right)),
gaps: self.gaps.map(|gaps| CellGaps {
left: gaps.left,
right: gaps.right,
spacing: gaps.spacing,
}),
upright: self.upright(),
text_rest: self.text_rest,
};
let room = decisions::cell_text_room(quirks, &parts);
Column {
left: room.left,
within: Within::Cell(CellEdgeParts {
table: self.edge,
grid: self.left,
inner: room.inner,
outer: self.outer_place,
}),
origin: Length::ZERO,
width: room.width,
// The style's shading becomes the cell's own fill, which the text of the cell
// stands on.
cell: Some(Rc::new(TableStyle {
shading: self.cell.shading.or(self.style.shading),
..self.style.clone()
})),
}
}
/// The left and right x of the cell's fill: inside the lines of its own box with cell
/// spacing; else between the grid lines, or where the target's `quirks` fill inside the
/// lines ([`decisions::fill_inside_lines`]) on whole
/// dots, half the width of the cell's own border on each side inside the place from which
/// the line there is centered, and that place itself on a side without a border of its
/// own, also under the line that the cell beside it draws there
/// ([`borders::SideLines::fill`]).
fn fill(&self, quirks: &Quirks) -> (Length, Length) {
match self.gaps {
Some(gaps) => (
self.left + gaps.left + width(self.borders.left),
self.right - gaps.right - width(self.borders.right),
),
None => decisions::fill_inside_lines(quirks, || self.sides.fill())
.unwrap_or((self.left, self.right)),
}
}
}
/// A cell and the grid columns that it covers, from `first` up to `end`.
#[derive(Clone, Copy)]
struct Span<'t> {
cell: &'t Cell,
first: usize,
end: usize,
}
/// The width of a border, which is zero when there is no line.
fn width(border: Option<Border>) -> Length {
border.map_or(Length::ZERO, |b| b.width)
}
/// The room that a border keeps between its edge and the content: its width and its space, or
/// zero when there is no line.
fn line_room(border: Option<Border>) -> Length {
border.map_or(Length::ZERO, |b| b.width + b.space)
}
/// The first or the second kind of band, for a band index from 0.
fn band(index: usize, odd: Region, even: Region) -> Region {
if index.is_multiple_of(2) { odd } else { even }
}
/// Where two cells meet, the wider of their two lines is drawn. A line wins over no line.
fn heavier(own: Option<Border>, other: Option<Border>) -> Option<Border> {
match (own, other) {
(Some(a), Some(b)) if b.width > a.width => Some(b),
(None, other) => other,
(own, _) => own,
}
}
/// Whether a cell of `table` holds a table.
fn holds_tables(table: &Table) -> bool {
table.rows.iter().any(|row| {
row.cells.iter().any(|cell| {
cell.blocks
.iter()
.any(|block| matches!(block, Block::Table(_)))
})
})
}
impl Layout<'_> {
/// Warns of the features of a table that F-Office does not apply: the table's own (shading
/// and fitted cells) once for the table and each part that sets them
/// ([`Layout::warn_of_table_shading`]), and the rows' own ([`Layout::warn_of_row_features`])
/// once for each row.
fn warn_of_table_features(&mut self, grid: &TableGrid) {
self.warn_of_table_shading(grid);
if grid
.table
.rows
.iter()
.flat_map(|row| &row.cells)
.any(|cell| cell.fit_text)
{
self.warn_of_feature(crate::Feature::FitText, grid.table.part.as_str());
}
self.warn_of_row_features(grid);
}
/// Warns once for the table and each part that sets it of a shading of the whole table that
/// gives a fill or a pattern, of which F-Office draws only the shading of the cells: the
/// shading of the table after its style (`w:shd` of `w:tblPr`), or of a row's table
/// property exceptions (`w:tblPrEx`), which takes its place in the row.
fn warn_of_table_shading(&mut self, grid: &TableGrid) {
let mut parts: Vec<&str> = Vec::new();
for row in &grid.table.rows {
let shading = row
.exceptions
.shading
.as_ref()
.or(grid.props.shading.as_ref());
if let Some(set) = shading.filter(|set| set.value)
&& !parts.contains(&set.part.as_str())
{
parts.push(set.part.as_str());
}
}
for part in parts {
self.warn_of_feature(crate::Feature::TableShading, part);
}
}
/// Warns once for each row of a table whose own alignment or cell spacing F-Office does
/// not apply, where it would move the row's cells:
/// an alignment (`w:jc` of `w:trPr`)
/// other than the table's, in a table narrower than its column, and a cell spacing
/// (`w:tblCellSpacing` of `w:trPr` or of `w:tblPrEx`) other than the table's, which Word
/// applies to the row. F-Office lays out each row with the table's. The alignment of a
/// row's table property exceptions (`w:tblPrEx`) gives no warning: Word does not move such a
/// row either. The warnings name the part that
/// holds the table, which sets its rows' own properties.
fn warn_of_row_features(&mut self, grid: &TableGrid) {
let alignment = grid.props.alignment.unwrap_or(TableAlignment::Start);
let narrower = grid.width() < self.column.width;
let spacing = grid.spacing();
for row in &grid.table.rows {
let aligns = row.alignment.is_some_and(|own| own != alignment);
let spaces = [row.cell_spacing, row.exceptions.cell_spacing]
.into_iter()
.flatten()
.any(|own| Some(own) != spacing);
let features = [
(aligns && narrower, crate::Feature::RowAlignment),
(spaces, crate::Feature::RowCellSpacing),
];
for (_, feature) in features.into_iter().filter(|(acts, _)| *acts) {
self.warn_of_feature(feature, grid.table.part.as_str());
}
}
}
/// The least widths of the content of the cells of `table` ([`Self::least_cell_widths`]),
/// where the target lays the columns of a table out from its cells
/// ([`decisions::TableRules::fitting_cells`]) and the table may take them: a table of
/// automatic layout at the top level whose saved grid disagrees with its cells and whose
/// cells hold no table. Else none.
pub(super) fn least_widths_for(
&mut self,
table: &Table,
style: &TableStyle,
) -> Vec<Vec<Length>> {
let mut props = style.table.clone();
props.apply(&table.props);
let automatic = props.layout != Some(crate::table::TableLayout::Fixed);
if !automatic
|| self.column.cell.is_some()
|| !shape::cells_disagree(table)
|| holds_tables(table)
{
return Vec::new();
}
decisions::TableRules::of(&self.context.quirks)
.fitting_cells(|| Some(self.least_cell_widths(table)))
.unwrap_or_default()
}
/// The width that the content of each cell of `table` needs at the least, by row and cell:
/// the widest of its paragraphs' least widths ([`Layout::least_width`]). It measures the paragraphs on trial and takes back what that changed:
/// the list counters, the pictures and the drawings of the output, and the warnings.
fn least_cell_widths(&mut self, table: &Table) -> Vec<Vec<Length>> {
let numbering = self.numbering.clone();
let (pictures, drawings) = (self.output.pictures.len(), self.output.drawings.len());
let least = self.layout_without_warnings(|layout| {
table
.rows
.iter()
.map(|row| {
row.cells
.iter()
.map(|cell| {
cell.blocks
.iter()
.filter_map(|block| match block {
Block::Paragraph(paragraph) => {
let resolved = layout.resolve(paragraph);
Some(layout.least_width(paragraph, &resolved))
}
Block::Table(_) => None,
})
.max()
.unwrap_or(Length::ZERO)
})
.collect()
})
.collect()
});
self.output.pictures.truncate(pictures);
self.output.drawings.truncate(drawings);
self.numbering = numbering;
least
}
/// What a table's shape takes from the layout.
fn shape_context(&self) -> shape::Context {
shape::Context {
rules: self.settings.mode_rules,
device: self.device,
table_rules: decisions::TableRules::of(&self.context.quirks),
right_to_left: self.section.right_to_left,
}
}
/// Starts a page before a table of the body whose first paragraph has a page break before
/// it, as that paragraph would outside a table, unless the page holds no line yet.
fn break_page_before_table(&mut self, table: &Table) {
if self.column.cell.is_none() && self.breaks_before_table(table) && !self.page_has_no_line()
{
self.new_page();
self.previous = None;
}
}
/// Whether the table's first paragraph, in its first cell or in a table nested at the
/// start of that cell, has a page break before it (`w:pageBreakBefore`).
fn breaks_before_table(&self, table: &Table) -> bool {
let first = table
.rows
.first()
.and_then(|r| r.cells.first())
.and_then(|c| c.blocks.first());
match first {
Some(crate::body::Block::Paragraph(paragraph)) => {
self.styles
.paragraph_properties_without_list_level(¶graph.props, None)
.flags()
.page_break_before
}
Some(crate::body::Block::Table(nested)) => self.breaks_before_table(nested),
_ => false,
}
}
/// Lays out a table at the current position, with `rest` the blocks after it.
pub(super) fn table(&mut self, table: &Table, rest: Rest<'_>) {
let Some(shown) = self.shown_table(table) else {
return;
};
let table: &Table = &shown;
self.table_chain = super::TableChain::Ends;
let style = self.styles.table(table.props.style.as_deref());
// A floating table lies at its own place, and the text flows around it.
// In a table cell it floats when it hangs on the text both ways, or hangs on the text
// down with another anchor across and no negative offset down. A table that rises over
// the paragraph before it moves that paragraph below it, which is not laid out, so such
// a table and one with another anchor down stay in the flow of the cell.
let floats = |place: &TablePlacement| {
self.column.cell.is_none()
|| place.vertical == Anchor::Text
&& (place.horizontal == Anchor::Text || place.y >= Length::ZERO)
};
if let Some(placement) = table.props.placement.filter(floats) {
self.floating_table(table, style, placement);
return;
}
self.break_page_before_table(table);
self.after_break = false;
self.section_previous = None;
let kept_before = self.previous.as_ref().is_some_and(|previous| previous.kept);
// The space after the paragraph before the table stays above it, unless contextual
// spacing removes it before the first paragraph of the first cell.
let prev_before_table = self.previous.take();
if let Some(previous) = &prev_before_table {
let first = table
.rows
.first()
.and_then(|r| r.cells.first())
.and_then(|c| c.blocks.first());
let drops = match first {
Some(crate::body::Block::Paragraph(p)) => {
let props = self.styles.paragraph_properties_without_list_level(
&p.props,
self.column.cell.as_deref(),
);
previous.drops_after_before(props.style.as_deref())
}
_ => false,
};
if !drops {
self.advance_space(previous.after);
}
}
self.place_column_top();
let table_prev =
prev_before_table.map_or_else(|| self.cell_prev_style.clone(), |p| p.style);
let outer_table_prev = std::mem::replace(&mut self.table_prev_style, table_prev);
let outer = self.column.clone();
let least = self.least_widths_for(table, &style);
let mut table_column = outer.clone();
let mut shape = Shape::new(
table,
style.clone(),
&table_column,
&self.shape_context(),
&least,
);
if outer.cell.is_none()
&& self.page.is_none()
&& self.clear_table_wraps(&mut shape, &outer, &mut table_column)
{
shape = Shape::new(table, style, &table_column, &self.shape_context(), &least);
}
let around = Around {
column: &table_column,
kept_before,
rest,
};
let paginate = outer.cell.is_none();
let paging = if paginate {
Paging::ByBottom
} else {
Paging::Whole
};
let start_area = (self.output.pages.len(), self.column_index);
self.rows(&mut shape, (paging, paginate.then_some(around)));
self.table_prev_style = outer_table_prev;
self.column = outer;
if (self.output.pages.len(), self.column_index) != start_area
&& let Some(&(left, width)) = self.columns.get(self.column_index)
{
self.column.left = left;
self.column.origin = left;
self.column.width = width;
}
self.previous = None;
let kept_last = table
.rows
.len()
.checked_sub(1)
.is_some_and(|last| self.row_kept(&shape, last));
self.table_chain = if paginate && kept_last {
super::TableChain::GoesOn
} else {
super::TableChain::Ends
};
}
/// Moves a body inline table below overlapping `wrapTopAndBottom` bands or wrapped floating
/// boxes (`self.squares`) that intrude into `outer` and leave no clear horizontal band wide
/// enough for the table, or narrows `table_column` to the clear band beside intruding wraps
/// when the table fits there. Wraps wholly outside `outer` (such as margin or other-column
/// drawings) do not move the table. Returns `true` when `table_column` changed and the
/// table's [`Shape`] must be rebuilt.
fn clear_table_wraps(
&mut self,
shape: &mut Shape,
outer: &Column,
table_column: &mut Column,
) -> bool {
if self.bands.is_empty() && self.squares.is_empty() {
return false;
}
let Some((&grid_start, &grid_end)) = shape.grid.lines.first().zip(shape.grid.lines.last())
else {
return false;
};
let table_width = grid_end - grid_start;
let (col_left, col_right) = (outer.left, outer.left + outer.width);
let start_y = self.y;
// When a floating-table wrap starts below `self.y`, measure this inline table's height so
// it fits above the floating table only if its whole height clears `sq.top`.
let table_height = self.measure_table_for_floating_wraps(shape);
let limit = self.bands.len() + self.squares.len() + 1;
for _ in 0..limit {
if let Some(below) = self.intruding_band_below(col_left, col_right) {
if !self.advance_below_wrap(below, start_y) {
return false;
}
continue;
}
let band = (self.y, self.y + Length::from_units(1));
let intruding: Vec<_> = self
.squares
.iter()
.filter(|sq| {
let top_hit = if sq.table && table_height > Length::ZERO {
sq.top < self.y + table_height
} else {
sq.top <= self.y
};
top_hit && self.y < sq.bottom
})
.filter_map(|sq| {
let (left, right) = sq.across(band)?;
(right > col_left && left < col_right).then_some((sq, left, right))
})
.collect();
if intruding.is_empty() {
return false;
}
let gaps = clear_horizontal_gaps(col_left, col_right, &intruding);
let next_below = intruding
.iter()
.map(|&(sq, _, _)| sq.bottom)
.filter(|&b| b > self.y)
.min();
if let Some((gl, gr)) = gaps.iter().copied().find(|&(a, b)| b - a >= table_width) {
table_column.left = gl;
table_column.width = gr - gl;
return true;
}
let Some(below) = next_below else {
return false;
};
if !self.advance_below_wrap(below, start_y) {
return false;
}
}
false
}
/// Measures `shape`'s whole height when at least one floating-table wrap starts below
/// `self.y`; returns zero otherwise so ordinary inline tables do no extra work.
fn measure_table_for_floating_wraps(&mut self, shape: &mut Shape) -> Length {
if !self.squares.iter().any(|sq| sq.table && sq.top > self.y) {
return Length::ZERO;
}
let mark = self.mark();
let before = self.y;
self.rows(shape, (Paging::Whole, None));
let height = (self.y - before).max(Length::ZERO);
self.rewind(&mark);
height
}
/// Moves `self.y` to `below`, unless the table is the first thing on the page and moving
/// below the wrap would push it past the body's bottom (such as a full-page header wrap),
/// in which case `self.y` returns to `start_y` and `false` is returned.
fn advance_below_wrap(&mut self, below: Length, start_y: Length) -> bool {
if self.page_has_no_line() && below >= self.body_end() {
self.move_to(start_y);
return false;
}
self.move_to(below);
true
}
/// The lowest bottom of any `wrapTopAndBottom` or `notBeside` band that covers `self.y` and
/// intrudes horizontally into `[col_left, col_right]`.
fn intruding_band_below(&self, col_left: Length, col_right: Length) -> Option<Length> {
self.bands
.iter()
.filter(|b| b.top <= self.y && self.y < b.bottom)
.filter(|b| b.right > col_left && b.left < col_right)
.map(|b| b.bottom)
.max()
}
/// The table without its hidden rows that show nothing, or `None` when it has none: rows
/// that hide their row-end mark (`w:trPr/w:hidden`) and whose cells hold only paragraphs
/// that show nothing, each with its mark hidden and every run empty or hidden. The rows
/// around such a row meet as if it were not there, as in Word's pages.
/// The rows of `table` that Word's pages show, or `None` where the table is not there. A
/// row that hides its row-end mark and whose cells show nothing takes no room and draws no
/// line in Word's pages, and a table of such rows only is not there at all; nor is a table
/// whose rows all go at the top of a page where the target's decision says so
/// ([`Self::deleted_table_absent`]). A table that is not there still keeps its number in its
/// story, which the line records of later tables use.
fn shown_table<'t>(&mut self, table: &'t Table) -> Option<Cow<'t, Table>> {
let shown = match self.without_hidden_rows(table) {
Some(rest) if rest.rows.is_empty() => None,
Some(rest) => Some(Cow::Owned(rest)),
None if self.deleted_table_absent(table) => None,
None => Some(Cow::Borrowed(table)),
};
if shown.is_none() {
self.output.tables += 1;
}
shown
}
/// Whether `table`, a table in the flow of the body whose rows all go, at the top of a page,
/// is not there for the paragraph after it, as the target's decision for such a table says.
/// It then leaves that paragraph no space before where the decision says so, as a page
/// break does.
fn deleted_table_absent(&mut self, table: &Table) -> bool {
let in_flow = table.props.placement.is_none() && self.column.cell.is_none();
if !table.rows.is_empty() || !in_flow || self.y > self.page_top(self.output.pages.len()) {
return false;
}
match decisions::deleted_table_at_top(&self.context.quirks, self.settings.mode_rules) {
DeletedTableAtTop::Table => false,
DeletedTableAtTop::Absent => true,
DeletedTableAtTop::TakesSpace => {
self.after_break = true;
true
}
}
}
fn without_hidden_rows(&mut self, table: &Table) -> Option<Table> {
if !table.rows.iter().any(|row| row.hidden) {
return None;
}
// This look at the paragraphs keeps the list counters as they were.
let numbering = self.numbering.clone();
let shown: Vec<bool> = table
.rows
.iter()
.map(|row| !(row.hidden && self.row_shows_nothing(row)))
.collect();
self.numbering = numbering;
if shown.iter().all(|shown| *shown) {
return None;
}
let mut rest = table.clone();
rest.rows = table
.rows
.iter()
.zip(&shown)
.filter(|(_, shown)| **shown)
.map(|(row, _)| row.clone())
.collect();
Some(rest)
}
/// Whether every cell of `row` holds only paragraphs that show nothing. A cell that holds
/// a nested table shows something.
fn row_shows_nothing(&mut self, row: &Row) -> bool {
row.cells.iter().all(|cell| {
cell.blocks.iter().all(|block| match block {
Block::Paragraph(paragraph) => {
let resolved = self.resolve(paragraph);
self.shows_nothing(paragraph, &resolved)
}
Block::Table(_) => false,
})
})
}
/// Lays out the rows of a table from the current position down, breaking across pages as
/// `paging` says. `around` holds the blocks around a table in the flow of the body, whose
/// rows can be kept with the next row.
fn rows(&mut self, shape: &mut Shape, (paging, around): (Paging, Option<Around<'_>>)) {
let paginate = paging != Paging::Whole;
self.warn_of_table_features(&shape.grid);
// The table takes the next number of its story, which the line records of its cells
// keep.
self.output.tables += 1;
let outer = std::mem::replace(&mut self.table_number, self.output.tables);
self.output.table_columns.push(super::TableColumns {
table: self.output.tables,
widths: shape.grid.column_widths_drawn(),
});
let mut merges = Merges {
paginate,
fits_by_top: paging == Paging::ByTop,
..Merges::default()
};
// A table in a cell of a row that splits breaks between the parts of the cell as a
// table of the body breaks between pages.
let mut holder = if paginate { None } else { self.take_holder() };
for index in 0..shape.grid.table.rows.len() {
if let Some(fragment) = holder.as_mut() {
self.carried_row(shape, index, &mut merges, fragment);
continue;
}
// A chain of kept rows that does not fit starts the next page.
if let Some(around) = around
&& self.chain_moves(shape, index, around)
{
merges.cut_turned();
self.row_to_next_page(shape, (index, self.y), &mut merges);
}
self.row(shape, index, paginate, &mut merges);
}
self.advance_space(shape.bottom_border(shape.grid.table.rows.len().saturating_sub(1)));
if let Some(holder) = holder {
self.give_holder_back(holder);
}
self.table_number = outer;
}
/// Realigns an inline body table's shape to the current column after moving to a new column
/// or mirrored page, returning the horizontal shift of the table's left edge.
fn realign_table(&mut self, shape: &mut Shape) -> Length {
let Some(&(left, width)) = self.columns.get(self.column_index) else {
return Length::ZERO;
};
let column = Column {
left,
origin: left,
width,
cell: None,
..self.column.clone()
};
let context = self.shape_context();
let dx = shape.realign_to(&column, &context);
if shape.follows_column() {
self.column.origin = left;
}
dx
}
/// Moves items down, such as the content of a merged cell for its vertical alignment.
pub(super) fn shift(&mut self, range: Range<usize>, dy: Length) {
// Only the records of cell lines move with a table's items.
let page = self.output.pages.len();
for line in &mut self.output.placed {
if line.area == super::LineArea::TableCell
&& line.page == page
&& matches!(line.item, super::FirstItem::At(item) if range.contains(&item))
{
line.move_down(dy);
}
}
self.items.move_down(range, dy);
}
}
/// Moves `items` by `(dx, dy)`: every place of each item, in a group too.
pub(super) fn move_items_by(items: &mut [Item], dx: Length, dy: Length) {
if dx == Length::ZERO && dy == Length::ZERO {
return;
}
for item in items {
item.map_places(
|p| Point {
x: p.x + dx,
y: p.y + dy,
},
|v| v,
);
}
}
/// Moves `items` down by `dy`: every place of each item, in a group too.
pub(super) fn move_items(items: &mut [Item], dy: Length) {
move_items_by(items, Length::ZERO, dy);
}
/// How far the content of a cell moves down for its vertical alignment, given the free space
/// below it.
fn align(align: Option<VerticalAlign>, free: Length) -> Length {
match align {
Some(VerticalAlign::Center) => free.max(Length::ZERO).div_toward_zero(2),
Some(VerticalAlign::Bottom) => free.max(Length::ZERO),
Some(VerticalAlign::Top) | None => Length::ZERO,
}
}
/// The height of a row from the width of its top border, the height of each cell's content
/// with its top and bottom margins, and the row height rule. A minimum height leaves out the
/// top border and the cell margins ([`least_row_height`]). An exact height takes in the top
/// border, and the largest top or bottom cell margin, as the target's `quirks` say, comes on
/// top of it.
fn row_height(
border: Length,
cells: &[(Length, Sides<Length>)],
rule: Option<(Length, HeightRule)>,
quirks: &Quirks,
) -> Length {
match rule {
Some((height, HeightRule::Exact)) => height + exact_row_margin(cells, quirks),
Some((height, HeightRule::AtLeast)) => least_row_height(border, cells, height),
Some((_, HeightRule::Auto)) | None => {
border + cells.iter().map(|c| c.0).max().unwrap_or(Length::ZERO)
}
}
}
/// The cell margin that a row of an exact height adds to it: the largest top or bottom margin of
/// its cells, as the target's `quirks` say ([`decisions::exact_row_margin`]).
fn exact_row_margin(cells: &[(Length, Sides<Length>)], quirks: &Quirks) -> Length {
cells
.iter()
.map(|c| decisions::exact_row_margin(quirks, (c.1.top, c.1.bottom)))
.max()
.unwrap_or(Length::ZERO)
}
/// The height of a row of the minimum height `height`: its top border, and the larger of the
/// tallest cell's content with its margins and `height` with the largest pair of top and
/// bottom margins.
fn least_row_height(border: Length, cells: &[(Length, Sides<Length>)], height: Length) -> Length {
let content = cells.iter().map(|c| c.0).max().unwrap_or(Length::ZERO);
let margins = cells
.iter()
.map(|c| c.1.top + c.1.bottom)
.max()
.unwrap_or(Length::ZERO);
border + content.max(height + margins)
}
/// The clear horizontal bands within `[col_left, col_right]` left uncovered by `intruding` wrap
/// squares (each with its `(left, right)` span at the table's `y`), honoring each square's
/// [`crate::floating::WrapSides`].
fn clear_horizontal_gaps(
col_left: Length,
col_right: Length,
intruding: &[(&super::floating::Square, Length, Length)],
) -> Vec<(Length, Length)> {
let mut gaps = vec![(col_left, col_right)];
for &(sq, left, right) in intruding {
let (fl, fr) = forbidden_span(col_left, col_right, sq.sides, left, right);
gaps = subtract_span(&gaps, fl, fr);
}
gaps
}
/// The horizontal interval within `[col_left, col_right]` blocked by a wrap spanning `[left, right]`.
fn forbidden_span(
col_left: Length,
col_right: Length,
sides: Option<crate::floating::WrapSides>,
left: Length,
right: Length,
) -> (Length, Length) {
match sides {
Some(crate::floating::WrapSides::Left) => (left, col_right),
Some(crate::floating::WrapSides::Right) => (col_left, right),
Some(crate::floating::WrapSides::Largest) => {
if left - col_left >= col_right - right {
(left, col_right)
} else {
(col_left, right)
}
}
Some(crate::floating::WrapSides::Both) | None => (left, right),
}
}
/// Removes `[fl, fr]` from each interval in `gaps`, keeping non-empty remainders in order.
fn subtract_span(gaps: &[(Length, Length)], fl: Length, fr: Length) -> Vec<(Length, Length)> {
let mut next = Vec::with_capacity(gaps.len() + 1);
for &(a, b) in gaps {
if fr <= a || fl >= b {
next.push((a, b));
} else {
if a < fl {
next.push((a, fl));
}
if fr < b {
next.push((fr, b));
}
}
}
next
}
#[cfg(test)]
mod tests;