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
//! The page items: the items of the page being filled, in the order of painting, with the table
//! border lines and the cell clips that name items by their places, and the fills entries of
//! the rows and merged regions of its tables and of its shaded paragraphs.

use std::ops::Range;
use std::sync::atomic::{AtomicU64, Ordering};

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

use super::table::{CellClips, move_items};
use crate::props::DashStyle;
use lines::BorderLines;

mod lines;

/// The key of the next fills entry. Each entry gets its own, so that a row whose page items
/// went aside while it was laid out, as those of a cell of a row that splits do, finds no
/// entry of its own among the page items that took their place.
static NEXT_FILLS_KEY: AtomicU64 = AtomicU64::new(0);

/// One place of the page items.
#[derive(Debug)]
enum Entry {
    /// An item.
    Item(Item),
    /// A fills entry, with its key and the fills that came to it, in the order of painting.
    Fills(u64, Vec<Item>),
    /// A place whose item was taken out.
    Empty,
}

impl Entry {
    /// The items that the entry paints, in their order.
    fn items(&self) -> &[Item] {
        match self {
            Self::Item(item) => std::slice::from_ref(item),
            Self::Fills(_, fills) => fills,
            Self::Empty => &[],
        }
    }

    /// The items that the entry paints, to change in place.
    fn items_mut(&mut self) -> &mut [Item] {
        match self {
            Self::Item(item) => std::slice::from_mut(item),
            Self::Fills(_, fills) => fills,
            Self::Empty => &mut [],
        }
    }

    /// The entry's item, when it is one.
    const fn item(&self) -> Option<&Item> {
        match self {
            Self::Item(item) => Some(item),
            Self::Fills(..) | Self::Empty => None,
        }
    }
}

/// A fills entry of the page items, which a table row, a merged region or a shaded paragraph
/// keeps to give it the fills that the layout knows only after its content.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct FillsEntry {
    at: usize,
    key: u64,
}

/// The page items: the entries of the page being filled, in the order of painting, with the
/// border line list and the cell clip list, which name entries by their places. An entry is an
/// item, a **fills entry**, which holds the fills of a table row, of a merged region or of a
/// shaded paragraph, or an empty place where an item was taken out. A place names an entry
/// that does not move while the page fills. The page's own fills come before all the
/// entries: the fill of the part of a shaded paragraph that goes on from an earlier page. A
/// cut drops the entries, lines and clips that reach past it. The undo list keeps the place of each fill that
/// went into the fills entry of a merged region, so that a row laid out again takes back the
/// fills that it gave earlier regions. The part of a cell of a row that splits fills page
/// items of its own while the page's wait.
#[derive(Debug, Default)]
pub(in crate::layout) struct PageItems {
    /// The page's own fills, which come before all the entries, the last first.
    page_fills: Vec<Item>,
    entries: Vec<Entry>,
    /// The count of the items that the entries paint.
    count: usize,
    /// The table border lines among the entries ([`BorderLines`]).
    lines: BorderLines,
    /// The clips of the table cells among the entries ([`CellClips`]).
    clips: CellClips,
    /// The places of the fills entries of merged regions, one for each fill that went in.
    undo: Vec<usize>,
}

impl PageItems {
    /// No items.
    pub(in crate::layout) const fn new() -> Self {
        Self {
            page_fills: Vec::new(),
            entries: Vec::new(),
            count: 0,
            lines: BorderLines::new(),
            clips: CellClips::new(),
            undo: Vec::new(),
        }
    }

    /// The count of the entries, which is the place of the next entry.
    pub(in crate::layout) const fn len(&self) -> usize {
        self.entries.len()
    }

    /// The count of the items that the entries paint.
    pub(in crate::layout) const fn count(&self) -> usize {
        self.count
    }

    /// Whether the entries paint no item.
    pub(in crate::layout) const fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// The count of the items that the entries before the place `at` paint.
    pub(in crate::layout) fn count_before(&self, at: usize) -> usize {
        let after: usize = (self.entries.get(at..).into_iter().flatten())
            .map(|entry| entry.items().len())
            .sum();
        self.count - after
    }

    /// The items, in the order of painting.
    #[cfg(test)]
    pub(in crate::layout) fn to_vec(&self) -> Vec<Item> {
        let entries = self.entries.iter().flat_map(Entry::items);
        self.page_fills.iter().chain(entries).cloned().collect()
    }

    /// The item at the place `at`, if an item stands there.
    pub(in crate::layout) fn item(&self, at: usize) -> Option<&Item> {
        self.entries.get(at)?.item()
    }

    /// The item at the place `at` to change in place, if an item stands there. A border line
    /// that changes no longer counts as the line that it was.
    pub(in crate::layout) fn item_mut(&mut self, at: usize) -> Option<&mut Item> {
        self.lines.stale();
        match self.entries.get_mut(at)? {
            Entry::Item(item) => Some(item),
            Entry::Fills(..) | Entry::Empty => None,
        }
    }

    /// The items of the entries at the places `places`, each with the place of its entry, in
    /// the order of painting.
    pub(in crate::layout) fn placed(
        &self,
        places: Range<usize>,
    ) -> impl Iterator<Item = (usize, &Item)> {
        let start = places.start;
        let entries = self.entries.get(places).unwrap_or_default();
        (start..)
            .zip(entries)
            .flat_map(|(at, entry)| entry.items().iter().map(move |item| (at, item)))
    }

    /// The items of the entries at the places `places`, copied, in the order of painting.
    pub(in crate::layout) fn cloned(&self, places: Range<usize>) -> Vec<Item> {
        self.placed(places).map(|(_, item)| item.clone()).collect()
    }

    /// The items of the entries from the place `from` on, to change in place.
    pub(in crate::layout) fn items_mut_from(
        &mut self,
        from: usize,
    ) -> impl Iterator<Item = &mut Item> {
        self.lines.stale();
        (self.entries.get_mut(from..).into_iter().flatten()).flat_map(Entry::items_mut)
    }

    /// Adds `item` after the others.
    pub(in crate::layout) fn push(&mut self, item: Item) {
        self.count += 1;
        self.entries.push(Entry::Item(item));
    }

    /// Adds `items` after the others.
    pub(in crate::layout) fn extend(&mut self, items: impl IntoIterator<Item = Item>) {
        for item in items {
            self.push(item);
        }
    }

    /// Moves all of `items` after the others, and leaves `items` empty.
    pub(in crate::layout) fn append(&mut self, items: &mut Vec<Item>) {
        self.extend(items.drain(..));
    }

    /// Cuts the entries to their first `len`, with the border lines, the cell clips and the
    /// fills of the undo list that reach past the cut.
    pub(in crate::layout) fn cut(&mut self, len: usize) {
        self.lines.cut(len, &self.entries);
        let cut: usize = (self.entries.get(len..).into_iter().flatten())
            .map(|entry| entry.items().len())
            .sum();
        self.count -= cut;
        self.entries.truncate(len);
        self.clips.cut(len);
        self.undo.retain(|&at| at < len);
    }

    /// Takes out the item at `at`, a border line or a piece of one, and leaves its place
    /// empty. Gives the item, or `None` when no item stands at `at`.
    pub(in crate::layout) fn take_out(&mut self, at: usize) -> Option<Item> {
        let entry = self.entries.get_mut(at)?;
        if !matches!(entry, Entry::Item(_)) {
            return None;
        }
        let Entry::Item(item) = std::mem::replace(entry, Entry::Empty) else {
            return None;
        };
        self.lines.stale();
        self.count -= 1;
        Some(item)
    }

    /// Moves the items of the entries at the places `range` down by `dy`, with the clip of each
    /// cell whose entries lie in `range`.
    pub(in crate::layout) fn move_down(&mut self, range: Range<usize>, dy: Length) {
        self.lines.stale();
        self.clips.moved(&range, dy);
        for entry in self.entries.get_mut(range).into_iter().flatten() {
            move_items(entry.items_mut(), dy);
        }
    }

    /// Takes the items of the page, each fills entry's fills at its place and the items of
    /// each cell grouped under its clip ([`CellClips::apply`]), and starts afresh.
    pub(in crate::layout) fn take(&mut self) -> Vec<Item> {
        let Self {
            page_fills,
            entries,
            mut clips,
            ..
        } = std::mem::take(self);
        let (items, starts) = flattened(page_fills, entries);
        clips.apply(items, &starts)
    }

    /// The items alone, without their clips: the part of a cell of a row that splits shows
    /// uncut on a later page.
    pub(in crate::layout) fn into_items(self) -> Vec<Item> {
        flattened(self.page_fills, self.entries).0
    }

    /// Adds an empty entry after the others, as [`Self::open_fills`] does, for the drawings
    /// behind the text that a shaded paragraph of a table cell anchors, which lie under the
    /// paragraph's fill. No cell clip cuts them.
    pub(in crate::layout) fn open_drawings(&mut self) -> FillsEntry {
        let entry = self.open_fills();
        self.clips.drawing(entry.at..entry.at + 1, false);
        entry
    }

    /// Adds an empty fills entry after the others, for the fills of a table row or of a merged
    /// region.
    pub(in crate::layout) fn open_fills(&mut self) -> FillsEntry {
        let entry = FillsEntry {
            at: self.entries.len(),
            key: NEXT_FILLS_KEY.fetch_add(1, Ordering::Relaxed),
        };
        self.entries.push(Entry::Fills(entry.key, Vec::new()));
        entry
    }

    /// The fills of the fills entry `entry`, to add to, if the entry is among these page items.
    fn fills_of(&mut self, entry: FillsEntry) -> Option<&mut Vec<Item>> {
        match self.entries.get_mut(entry.at)? {
            Entry::Fills(key, fills) if *key == entry.key => Some(fills),
            Entry::Fills(..) | Entry::Item(_) | Entry::Empty => None,
        }
    }

    /// Whether the fills entry `entry` is among these page items: not when the part of a cell
    /// of a row that splits went on to page items of its own after it.
    pub(in crate::layout) fn holds_fills(&self, entry: FillsEntry) -> bool {
        matches!(self.entries.get(entry.at), Some(Entry::Fills(key, _)) if *key == entry.key)
    }

    /// Adds the fills of a table row after those of its fills entry `entry`. A fills entry that
    /// the part of a cell of a row that splits took away gets none.
    pub(in crate::layout) fn put_fills(&mut self, entry: FillsEntry, mut fills: Vec<Item>) {
        let added = fills.len();
        if let Some(to) = self.fills_of(entry) {
            to.append(&mut fills);
            self.count += added;
        }
    }

    /// Adds the fill of a cell that goes on with a merged region after the fills of the
    /// region's fills entry `entry`, and notes it in the undo list.
    pub(in crate::layout) fn put_region_fill(&mut self, entry: FillsEntry, fill: Item) {
        if let Some(fills) = self.fills_of(entry) {
            fills.push(fill);
            self.count += 1;
            self.undo.push(entry.at);
        }
    }

    /// Adds the fill of the part of a shaded paragraph that goes on from an earlier page to
    /// the page's own fills, in front of those that came before it.
    pub(in crate::layout) fn put_page_fill(&mut self, fill: Item) {
        self.page_fills.insert(0, fill);
        self.count += 1;
    }

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

    /// Takes back the region fills of the undo list after its first `count`, the last first,
    /// when a row is laid out again.
    pub(in crate::layout) fn take_back_region_fills(&mut self, count: usize) {
        let later = self.undo.split_off(count.min(self.undo.len()));
        for at in later.into_iter().rev() {
            if let Some(Entry::Fills(_, fills)) = self.entries.get_mut(at)
                && fills.pop().is_some()
            {
                self.count -= 1;
            }
        }
    }

    /// The place of the border line that is the item `line`, if any.
    pub(in crate::layout) fn place_of_line(&mut self, line: &Item) -> Option<usize> {
        self.lines.place_of(&self.entries, line)
    }

    /// Whether one of the border lines is the item `line`.
    pub(in crate::layout) fn holds_line(&mut self, line: &Item) -> bool {
        self.lines.holds(&self.entries, line)
    }

    /// The dashes that the border line at the place `at` is to be drawn with, if any.
    pub(in crate::layout) fn line_dash(&self, at: usize) -> Option<DashStyle> {
        self.lines.dash(at)
    }

    /// Adds the border line `line` after the others, to be drawn with `dash`.
    pub(in crate::layout) fn push_line(&mut self, line: Item, dash: Option<DashStyle>) {
        self.lines.push(self.entries.len(), dash, &line);
        self.push(line);
    }

    /// Adds the border lines `lines` after the others, drawn as they are.
    pub(in crate::layout) fn extend_lines(&mut self, lines: impl IntoIterator<Item = Item>) {
        let at = self.entries.len();
        self.extend(lines);
        self.lines
            .extend(at, self.entries.get(at..).unwrap_or_default());
    }

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

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

    /// Adds the clip `rect` of a cell whose content is the entries at the places `items`.
    pub(in crate::layout) fn clip_cell(&mut self, items: Range<usize>, rect: Edges<Length>) {
        self.clips.push(items, rect);
    }

    /// Adds the items of a floating drawing anchored in a table cell, which no cell clip cuts,
    /// and which lies in front of the text when `front` is true.
    pub(in crate::layout) fn push_drawing(&mut self, items: Vec<Item>, front: bool) {
        let at = self.entries.len();
        self.extend(items);
        self.clips.drawing(at..self.entries.len(), front);
    }
}

/// The items of `page_fills` and then those of `entries`, in their order, with the index among
/// them of the first item of each entry and, last, their count.
fn flattened(page_fills: Vec<Item>, entries: Vec<Entry>) -> (Vec<Item>, Vec<usize>) {
    let mut items = page_fills;
    let mut starts = Vec::with_capacity(entries.len() + 1);
    for entry in entries {
        starts.push(items.len());
        match entry {
            Entry::Item(item) => items.push(item),
            Entry::Fills(_, mut fills) => items.append(&mut fills),
            Entry::Empty => {}
        }
    }
    starts.push(items.len());
    (items, starts)
}

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

    use super::PageItems;

    fn rect(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,
        })
    }

    #[test]
    fn puts_the_drawings_of_a_drawings_entry_at_its_place_and_lets_them_stand_alone() {
        let mut items = PageItems::new();
        let drawings = items.open_drawings();
        let fills = items.open_fills();
        items.push(rect(0));
        items.clip_cell(0..3, Edges::default());
        items.put_fills(drawings, vec![rect(1)]);
        items.put_fills(fills, vec![rect(2)]);
        assert_eq!(items.to_vec(), [1, 2, 0].map(rect));
        let taken = items.take();
        assert_eq!(taken.first(), Some(&rect(1)));
        assert!(matches!(taken.get(1), Some(Item::Group(_))));
    }

    #[test]
    fn keeps_its_border_lines_in_step_through_a_take_out_and_a_take() {
        let mut items = PageItems::new();
        items.push(rect(2));
        items.push(rect(0));
        items.push_line(rect(1), None);
        assert_eq!(items.place_of_line(&rect(1)), Some(2));
        assert_eq!(items.take_out(0), Some(rect(2)));
        assert_eq!(items.place_of_line(&rect(1)), Some(2));
        assert_eq!(items.take_out(0), None);
        assert_eq!(items.take(), [rect(0), rect(1)]);
        assert!(items.is_empty());
        items.push(rect(1));
        assert!(!items.holds_line(&rect(1)));
    }

    #[test]
    fn paints_the_fills_of_each_entry_at_its_place_in_the_order_they_came() {
        let mut items = PageItems::new();
        let row = items.open_fills();
        items.push(rect(0));
        let region = items.open_fills();
        items.push(rect(1));
        assert_eq!((items.len(), items.count()), (4, 2));
        items.put_region_fill(region, rect(5));
        let mark = items.region_fill_count();
        items.put_region_fill(region, rect(6));
        items.put_fills(row, vec![rect(3), rect(4)]);
        assert_eq!(items.to_vec(), [3, 4, 0, 5, 6, 1].map(rect));
        items.take_back_region_fills(mark);
        assert_eq!(items.to_vec(), [3, 4, 0, 5, 1].map(rect));
        assert_eq!(items.count(), 5);
        // A fills entry of other page items gets nothing here.
        let other = PageItems::new().open_fills();
        items.put_fills(other, vec![rect(7)]);
        assert_eq!(items.count(), 5);
        // The page's own fills come before all the entries, the last first.
        items.put_page_fill(rect(8));
        items.put_page_fill(rect(9));
        assert_eq!(items.count(), 7);
        assert_eq!(items.take(), [9, 8, 3, 4, 0, 5, 1].map(rect));
    }
}