f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! The clips of table cells: the rectangle outside which what a cell draws shows nothing, on a
//! target that cuts it there (quirk `CellClip`).

use std::cmp::Reverse;
use std::iter::Peekable;
use std::ops::Range;
use std::vec;

use f_office_paint::{Group, GroupClip, Item};
use f_office_units::{Edges, Length};

use super::borders::{CellSide, LineEdge, RowTop};
use super::merges::Open;
use super::{Shape, Slot};
use crate::layout::{Layout, decisions};

/// The clip of the rectangle `rect` of a cell on the page, as a group of the page's items
/// takes it. A rectangle without area gives a clip without area, which shows nothing.
fn group_clip(rect: Edges<Length>) -> GroupClip {
    let (left, right) = (rect.left.min(rect.right), rect.left.max(rect.right));
    let height = (rect.bottom - rect.top).max(Length::ZERO);
    GroupClip::rect(left, rect.top, right - left, height)
}

/// The clip of a merged region's first cell, before the row that ends the region gives its
/// bottom: the page that the region starts on, and the rectangle's other sides.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct RegionClip {
    page: usize,
    rect: Edges<Length>,
}

impl Layout<'_> {
    /// Adds the clip of each cell of row `index` whose row ends here, from the row's `top`,
    /// the top of its cells below their top lines `inner` and its `bottom`, with the items of
    /// each cell as `laid` gives them, on a target that cuts what a cell draws: the clip of
    /// each cell outside a merged region, and that of each region in `closed`, which the row
    /// ends, when the region started on this page. A cell of turned text and a cell of a table
    /// with cell spacing get none.
    pub(super) fn clip_row(
        &mut self,
        (shape, index): (&Shape, usize),
        (slots, laid): (&[Slot], &[(Range<usize>, Length)]),
        (top, inner, bottom): (RowTop, Length, Length),
        closed: &[Open],
    ) {
        let Some(slots) = decisions::clipped_cells(&self.context.quirks, slots) else {
            return;
        };
        for (slot, (items, _)) in slots.iter().zip(laid) {
            if !clipped(slot) || slot.merged_above() || slot.merged_below {
                continue;
            }
            let rect = Edges {
                bottom: self.clip_bottom((shape, index), slot, bottom),
                ..self.clip_sides(slot, (top, inner))
            };
            self.items.clip_cell(items.clone(), rect);
        }
        let page = self.output.pages.len();
        for open in closed {
            let Some(clip) = open.clip.filter(|clip| clip.page == page) else {
                continue;
            };
            let last = slots
                .iter()
                .find(|slot| slot.first == open.first && slot.merged_above());
            if let Some(slot) = last {
                let rect = Edges {
                    bottom: self.clip_bottom((shape, index), slot, bottom),
                    ..clip.rect
                };
                self.items.clip_cell(open.items.clone(), rect);
            }
        }
    }

    /// The clip of the merged region that `slot` starts in a row from `top`, whose cells' top
    /// lines end at `inner`, on a target that cuts what a cell draws.
    pub(super) fn region_clip(
        &self,
        slot: &Slot,
        (top, inner): (RowTop, Length),
    ) -> Option<RegionClip> {
        decisions::clipped_cells(&self.context.quirks, slot)
            .filter(|slot| clipped(slot))
            .map(|slot| RegionClip {
                page: self.output.pages.len(),
                rect: self.clip_sides(slot, (top, inner)),
            })
    }

    /// The sides of the clip of `slot`'s cell but its bottom, in a row from `top` whose cells'
    /// top lines end at `inner`: across, the inner edges of the cell's lines as they are
    /// drawn, or its grid lines where it has none; down, the top of its text area when it has
    /// a top margin, else the inner edge of its top line, or the row's top.
    fn clip_sides(&self, slot: &Slot, (top, inner): (RowTop, Length)) -> Edges<Length> {
        let left = slot.sides.edge(CellSide::Left, LineEdge::Inner);
        let right = slot.sides.edge(CellSide::Right, LineEdge::Inner);
        let line = (slot.borders.top).map_or(top.at, |border| self.top_line_end(border, top));
        Edges {
            left: left.unwrap_or(slot.left),
            top: if slot.margins.top > Length::ZERO {
                inner + slot.margins.top
            } else {
                line
            },
            right: right.unwrap_or(slot.right),
            bottom: line,
        }
    }

    /// The bottom of the clip of `slot`'s cell in row `index`, which ends at `bottom`: the top
    /// of the line that the cell draws below itself, in the last row and above no cell, as it
    /// is drawn; else, with a line below the cell, where the next row's top line starts, on the
    /// device grid; and without a line, the row's bottom itself, off the device grid, as Word's
    /// clips show.
    fn clip_bottom(&self, (shape, index): (&Shape, usize), slot: &Slot, bottom: Length) -> Length {
        let Some(border) = slot.borders.bottom else {
            return bottom;
        };
        let last = index + 1 == shape.grid.table.rows.len();
        let drawn = (last || shape.grid.open_below(index, slot)).then(|| {
            self.bottom_parts(border, bottom)
                .into_iter()
                .map(|part| part.start)
                .min()
        });
        drawn.flatten().unwrap_or_else(|| self.device.snap(bottom))
    }
}

/// Whether a cell's clip cuts what it draws: a cell of upright text in a table without cell
/// spacing.
fn clipped(slot: &Slot) -> bool {
    slot.upright() && slot.gaps.is_none()
}

/// A cell's clip: the items of its content among the items being filled, and its rectangle.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Cell {
    items: Range<usize>,
    rect: Edges<Length>,
}

/// The cell clip list: the clip of each cell laid out on the page being filled, with the items
/// of its content, and the items of the floating drawings anchored in cells, which no cell
/// clip cuts: a drawing in front of the text lies above all the page's items, as the page's
/// own drawings in front of the text do, on every target and in a cell with no clip too, and
/// one behind the text keeps its place. Like the border line list, it follows the items: a cut
/// of the items drops the clips and drawings that reach past the cut, and items that move down
/// move the clips that hold them. A row's trial takes back the clips that it added ([`super::super::columns::RowMark`]). When the page's items are taken, each
/// cell's items become one group of the page's items under its clip, the inner cells of a
/// nested table first ([`Self::apply`]). The part of a cell of a row that splits keeps the
/// page's list while it fills its own, and the clips of such a part are dropped: the parts on
/// later pages show uncut.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(in crate::layout) struct CellClips {
    cells: Vec<Cell>,
    /// The items of each floating drawing anchored in a cell.
    drawings: Vec<CellDrawing>,
}

/// A floating drawing anchored in a cell: its items, and whether it lies in front of the text.
#[derive(Clone, Debug, PartialEq, Eq)]
struct CellDrawing {
    items: Range<usize>,
    front: bool,
}

impl CellClips {
    /// An empty list.
    pub(in crate::layout) const fn new() -> Self {
        Self {
            cells: Vec::new(),
            drawings: Vec::new(),
        }
    }

    /// The count of the clips, which a row mark keeps.
    pub(in crate::layout) const fn count(&self) -> usize {
        self.cells.len()
    }

    /// Drops the clips added after the first `count`, when a row is laid out again.
    pub(in crate::layout) fn truncate(&mut self, count: usize) {
        self.cells.truncate(count);
    }

    /// Adds the clip `rect` of a cell whose content is `items`.
    pub(in crate::layout) fn push(&mut self, items: Range<usize>, rect: Edges<Length>) {
        if !items.is_empty() {
            self.cells.push(Cell { items, rect });
        }
    }

    /// Notes the items of a floating drawing anchored in a cell, which no cell clip cuts, and
    /// whether it lies in front of the text.
    pub(in crate::layout) fn drawing(&mut self, items: Range<usize>, front: bool) {
        if !items.is_empty() {
            self.drawings.push(CellDrawing { items, front });
        }
    }

    /// Drops the clips and drawings that reach past `len`, when the items are cut to `len`.
    pub(in crate::layout) fn cut(&mut self, len: usize) {
        self.cells.retain(|cell| cell.items.end <= len);
        self.drawings.retain(|drawing| drawing.items.end <= len);
    }

    /// Moves down by `dy` the clip of each cell whose items lie in `range`, when those items
    /// move down.
    pub(in crate::layout) fn moved(&mut self, range: &Range<usize>, dy: Length) {
        for cell in &mut self.cells {
            if range.start <= cell.items.start && cell.items.end <= range.end {
                cell.rect.top += dy;
                cell.rect.bottom += dy;
            }
        }
    }

    /// Puts the items of each cell into groups of the page's items under the cell's clip, in
    /// one walk of `items`, and empties the list. A cell inside another, in a nested table,
    /// makes its groups inside the groups of the cell around it. A floating drawing anchored in
    /// a cell and a picture stay out of every group: they close the groups of all the cells
    /// open around them, and the next item opens those groups again. The target's writer writes
    /// a picture's file again only outside a group, as it does for a text box's pictures. The
    /// list names places of entries, and `starts` gives the index in `items` of the first item
    /// of each entry, and last the count of the items.
    pub(in crate::layout) fn apply(&mut self, items: Vec<Item>, starts: &[usize]) -> Vec<Item> {
        let (cells, drawings) = self.walk_order(starts);
        let mut walk = Walk {
            out: Vec::with_capacity(items.len()),
            open: Vec::new(),
            cells: cells.into_iter().peekable(),
            drawings: drawings.into_iter().peekable(),
            alone_to: 0,
            lifted: false,
            front: Vec::new(),
        };
        for (at, item) in items.into_iter().enumerate() {
            walk.reach(at);
            walk.take(at, item);
        }
        while !walk.open.is_empty() {
            walk.close();
        }
        walk.out.append(&mut walk.front);
        walk.out
    }

    /// Empties the list, and gives its cells and drawings as ranges of the items that `starts`
    /// places, in the order in which a walk of the items meets them. The cells come by their
    /// start, the longer of two with one start first, and of two with one range the later one
    /// first, around the earlier one; a cell or a drawing without items is left out. The
    /// drawings come by their start.
    fn walk_order(&mut self, starts: &[usize]) -> (Vec<Cell>, Vec<CellDrawing>) {
        let among =
            |places: &Range<usize>| Some(*starts.get(places.start)?..*starts.get(places.end)?);
        let mut cells: Vec<(usize, Cell)> = std::mem::take(&mut self.cells)
            .into_iter()
            .enumerate()
            .filter_map(|(order, cell)| {
                let items = among(&cell.items).filter(|items| !items.is_empty())?;
                Some((
                    order,
                    Cell {
                        items,
                        rect: cell.rect,
                    },
                ))
            })
            .collect();
        cells.sort_by_key(|(order, cell)| {
            (cell.items.start, Reverse(cell.items.end), Reverse(*order))
        });
        let mut drawings: Vec<CellDrawing> = std::mem::take(&mut self.drawings)
            .into_iter()
            .filter_map(|drawing| {
                Some(CellDrawing {
                    items: among(&drawing.items).filter(|items| !items.is_empty())?,
                    front: drawing.front,
                })
            })
            .collect();
        drawings.sort_by_key(|drawing| drawing.items.start);
        (cells.into_iter().map(|(_, cell)| cell).collect(), drawings)
    }
}

/// A cell that the walk of [`CellClips::apply`] is in: the end of its items, its clip, and its
/// items since its group last opened.
struct OpenCell {
    end: usize,
    rect: Edges<Length>,
    run: Vec<Item>,
}

impl OpenCell {
    /// The group of the cell's items since its group last opened, if it has any, and opens the
    /// group again.
    fn group(&mut self) -> Option<Item> {
        (!self.run.is_empty()).then(|| {
            Item::Group(Group::of_cell(
                std::mem::take(&mut self.run),
                group_clip(self.rect),
            ))
        })
    }
}

/// The walk of [`CellClips::apply`]: the page's items so far, the cells open where it stands,
/// the innermost last, the cells and the floating drawings that it has not reached yet, the
/// end of the drawing whose items stand alone and whether they go in front, and the items of
/// the drawings in front of the text, which come after all the others.
struct Walk {
    out: Vec<Item>,
    open: Vec<OpenCell>,
    cells: Peekable<vec::IntoIter<Cell>>,
    drawings: Peekable<vec::IntoIter<CellDrawing>>,
    alone_to: usize,
    lifted: bool,
    front: Vec<Item>,
}

impl Walk {
    /// Comes to the item `at`: ends the cells that end before it, opens those that start at
    /// it, and passes the drawings that start before it.
    fn reach(&mut self, at: usize) {
        while self.open.last().is_some_and(|cell| cell.end <= at) {
            self.close();
        }
        while let Some(cell) = self.cells.next_if(|cell| cell.items.start <= at) {
            self.open.push(OpenCell {
                end: cell.items.end,
                rect: cell.rect,
                run: Vec::new(),
            });
        }
        while self
            .drawings
            .next_if(|drawing| drawing.items.start < at)
            .is_some()
        {}
    }

    /// Takes `item`, the item `at`: an item of a floating drawing in front of the text stands
    /// alone after all the page's items, whether a cell clip holds it or not; an item of a
    /// floating drawing behind the text in the innermost open cell and a picture stand alone
    /// in their place; and any other item joins the innermost open cell.
    fn take(&mut self, at: usize, item: Item) {
        if at >= self.alone_to {
            let innermost_end = self.open.last().map(|cell| cell.end);
            let drawing = self.drawings.next_if(|drawing| {
                drawing.items.start == at
                    && (drawing.front || innermost_end.is_some_and(|end| drawing.items.end <= end))
            });
            if let Some(drawing) = drawing {
                (self.alone_to, self.lifted) = (drawing.items.end, drawing.front);
            } else if matches!(item, Item::Image(_)) {
                self.lifted = false;
            } else {
                self.push(item);
                return;
            }
        }
        self.stand_alone(item);
    }

    /// Puts `item`, which stands alone, after the items of the page when it belongs to a
    /// drawing in front of the text, and otherwise after the groups of the open cells so far.
    fn stand_alone(&mut self, item: Item) {
        if self.lifted {
            self.front.push(item);
        } else {
            self.close_runs();
            self.out.push(item);
        }
    }

    /// Adds `item` to the group of the innermost open cell, or to the page's items.
    fn push(&mut self, item: Item) {
        match self.open.last_mut() {
            Some(cell) => cell.run.push(item),
            None => self.out.push(item),
        }
    }

    /// Ends the innermost open cell: its group joins the group of the cell around it.
    fn close(&mut self) {
        if let Some(group) = self.open.pop().and_then(|mut cell| cell.group()) {
            self.push(group);
        }
    }

    /// Closes the groups of all the open cells, the innermost first, each into the group of
    /// the cell around it, before an item that stands alone.
    fn close_runs(&mut self) {
        let mut inner = None;
        for cell in self.open.iter_mut().rev() {
            cell.run.extend(inner.take());
            inner = cell.group();
        }
        self.out.extend(inner);
    }
}

#[cfg(test)]
mod tests {
    use f_office_paint::{Group, Image, ImageItem, Item, Rect, Rgb};
    use f_office_units::{Edges, Length};

    use super::{CellClips, group_clip};

    fn fill(y: i64) -> Item {
        Item::Rect(Rect {
            x: Length::ZERO,
            y: Length::from_units(y),
            width: Length::from_units(1),
            height: Length::from_units(1),
            color: Rgb::BLACK,
        })
    }

    fn rect(top: i64) -> Edges<Length> {
        Edges {
            left: Length::ZERO,
            top: Length::from_units(top),
            right: Length::from_units(10),
            bottom: Length::from_units(top + 10),
        }
    }

    fn picture(y: i64) -> Item {
        Item::Image(ImageItem {
            x: Length::ZERO,
            y: Length::from_units(y),
            width: Length::from_units(1),
            height: Length::from_units(1),
            clip: None,
            turn: None,
            image: Image::new(Vec::new()),
        })
    }

    /// The items as a tree of their `y`, with a group as the list of its items' `y` and a
    /// picture as its `y` after `p`.
    fn shape(items: &[Item]) -> String {
        items
            .iter()
            .map(|item| match item {
                Item::Rect(r) => r.y.units().to_string(),
                Item::Image(i) => format!("p{}", i.y.units()),
                Item::Group(g) => format!("[{}]", shape(&g.items)),
                _ => "?".to_string(),
            })
            .collect::<Vec<_>>()
            .join(" ")
    }

    #[test]
    fn groups_each_cell_with_its_nested_cells_inside_and_leaves_its_drawings_out() {
        let items: Vec<Item> = (0..10).map(fill).collect();
        let mut clips = CellClips::new();
        // An outer cell 1..9 with a nested cell 3..5 and a floating drawing at 6, and a second
        // cell 9..10.
        clips.push(3..5, rect(3));
        clips.drawing(6..7, false);
        clips.push(1..9, rect(1));
        clips.push(9..10, rect(9));
        let starts: Vec<usize> = (0..=items.len()).collect();
        let items = clips.apply(items, &starts);
        assert_eq!(shape(&items), "0 [1 2 [3 4] 5] 6 [7 8] [9]");
        assert_eq!(clips, CellClips::new());
    }

    #[test]
    fn leaves_the_pictures_of_a_cell_out_of_its_group() {
        let items: Vec<Item> = vec![fill(0), fill(1), picture(2), fill(3), picture(4)];
        let mut clips = CellClips::new();
        // A nested cell 1..3 that holds a picture, in an outer cell 0..5 that ends with one.
        clips.push(1..3, rect(1));
        clips.push(0..5, rect(0));
        let starts: Vec<usize> = (0..=items.len()).collect();
        let items = clips.apply(items, &starts);
        assert_eq!(shape(&items), "[0 [1]] p2 [3] p4");
    }

    /// Two cells, the second with a floating drawing at its start.
    fn two_cells() -> CellClips {
        let mut clips = CellClips::new();
        clips.push(4..6, rect(0));
        clips.push(7..10, rect(0));
        clips.drawing(7..8, false);
        clips
    }

    #[test]
    fn moves_the_clip_of_a_cell_whose_items_move() {
        let mut clips = two_cells();
        clips.moved(&(0..6), Length::from_units(5));
        let rects: Vec<_> = clips.cells.iter().map(|cell| cell.rect).collect();
        assert_eq!(rects, [rect(5), rect(0)]);
    }

    #[test]
    fn groups_the_items_of_the_entries_at_a_cell_s_places() {
        // Four entries: an item, a fills entry of two items, an empty place and an item.
        let items: Vec<Item> = (0..4).map(fill).collect();
        let starts = [0, 1, 3, 3, 4];
        let mut clips = CellClips::new();
        clips.push(1..3, rect(1));
        clips.push(3..4, rect(3));
        let items = clips.apply(items, &starts);
        assert_eq!(shape(&items), "0 [1 2] [3]");
    }

    #[test]
    fn nests_the_earlier_of_two_cells_with_one_range_in_the_later() {
        let items: Vec<Item> = (0..2).map(fill).collect();
        let mut clips = CellClips::new();
        clips.push(0..2, rect(0));
        clips.push(0..2, rect(5));
        let starts: Vec<usize> = (0..=items.len()).collect();
        let inner = Item::Group(Group::of_cell(items.clone(), group_clip(rect(0))));
        let outer = Item::Group(Group::of_cell(vec![inner], group_clip(rect(5))));
        assert_eq!(clips.apply(items, &starts), [outer]);
    }

    #[test]
    fn leaves_a_drawing_at_a_cell_s_first_item_out_of_its_group() {
        let items: Vec<Item> = (0..4).map(fill).collect();
        let mut clips = CellClips::new();
        clips.push(1..4, rect(1));
        clips.drawing(1..3, false);
        let starts: Vec<usize> = (0..=items.len()).collect();
        assert_eq!(shape(&clips.apply(items, &starts)), "0 1 2 [3]");
    }

    #[test]
    fn puts_a_drawing_in_front_of_the_text_of_a_cell_after_all_the_page_s_items() {
        let items: Vec<Item> = (0..7).map(fill).collect();
        let mut clips = CellClips::new();
        // A drawing in front of the text at 2..4 in a cell 1..5, and a second cell 5..7 below
        // it: the drawing comes last, and the first cell's group stays whole.
        clips.push(1..5, rect(1));
        clips.drawing(2..4, true);
        clips.push(5..7, rect(5));
        let starts: Vec<usize> = (0..=items.len()).collect();
        assert_eq!(shape(&clips.apply(items, &starts)), "0 [1 4] [5 6] 2 3");
    }

    #[test]
    fn puts_a_drawing_in_front_of_the_text_last_without_a_cell_clip() {
        // A target that cuts no cell: a drawing in front of the text at 1..3 comes after the
        // page's items, and one behind the text at 4..5 keeps its place.
        let items: Vec<Item> = (0..6).map(fill).collect();
        let mut clips = CellClips::new();
        clips.drawing(1..3, true);
        clips.drawing(4..5, false);
        let starts: Vec<usize> = (0..=items.len()).collect();
        assert_eq!(shape(&clips.apply(items, &starts)), "0 3 4 5 1 2");
    }

    #[test]
    fn leaves_out_a_drawing_without_items() {
        // A drawing at the place 2, whose entry holds no item, makes the cell's third item, at
        // the next place, stand alone no more than any other item of the cell.
        let items: Vec<Item> = (0..4).map(fill).collect();
        let mut clips = CellClips::new();
        clips.push(0..5, rect(0));
        clips.drawing(2..3, false);
        let starts = [0, 1, 2, 2, 3, 4];
        assert_eq!(shape(&clips.apply(items, &starts)), "[0 1 2 3]");
    }

    #[test]
    fn follows_cuts_of_the_items_and_of_a_row_s_trial() {
        let mut clips = two_cells();
        clips.cut(9);
        assert_eq!((clips.count(), clips.drawings.len()), (1, 1));
        clips.truncate(0);
        assert_eq!(clips.count(), 0);
    }
}