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
//! Paragraphs in frames (`w:framePr`), which stand outside the text flow.

use f_office_units::{Edges, Length};

use crate::body::{Block, Paragraph, Section};
use crate::floating::WrapSides;
use crate::lines::Line;
use crate::params::{FRAME_NARROWEST_PIECE, NARROWEST_WRAP};
use crate::props::{Align, Anchor, FramePr, FrameWrap};

use super::floating::{Square, StartPastWrap};
use super::{Layout, Previous, Resolved, decisions};

/// A frame's content and its place across: the section of one column whose margins are the
/// frame's sides, the frame's paragraphs as a story, the frame's left edge and width, and how
/// far left of the frame's box at its offset across its left edge lies
/// ([`decisions::frame_shift_left`]).
type Framed = (Section, Vec<Block>, (Length, Length), Length);

/// The box of a frame of the body on the page being filled, which the layout keeps to warn of
/// an overlap that Word would move apart.
#[derive(Clone, Debug)]
pub(super) struct FrameBox {
    /// The frame's edges on the page.
    edges: Edges<Length>,
    /// When the frame must not overlap other frames (`w:suppressOverlap`), the name of the part
    /// that sets it for its first paragraph that does.
    keeps_apart: Option<std::rc::Rc<f_office_warnings::Name>>,
    /// Whether the frame is a drop cap in the text.
    drop_cap: bool,
}

impl FrameBox {
    /// Whether the frame is a drop cap in the text that reaches down past `top`, the top of a
    /// line beside it.
    pub(super) fn drop_cap_beside(&self, top: Length) -> bool {
        self.drop_cap && self.edges.top <= top && top < self.edges.bottom
    }
}

/// The bottom of a frame whose content runs from `top` to `end`: the frame is as tall as `w:h`
/// when the height is exact, at least `w:h` otherwise, and else as its content.
fn frame_bottom(frame: FramePr, top: Length, end: Length) -> Length {
    match frame.height {
        Some((h, true)) => top + h,
        Some((h, false)) => end.max(top + h),
        None => end,
    }
}

/// The space between the lines of the paragraph before a frame at the text and the frame: the
/// whole space after that paragraph.
pub(super) fn frame_lead(previous: Option<&Previous>) -> Length {
    previous.map_or(Length::ZERO, |previous| previous.after)
}

impl Layout<'_> {
    /// Lays out neighbor paragraphs with equal frame properties in one frame at its own
    /// place, without moving the flow. The paragraphs stack in the frame, which is as wide
    /// as `w:w` or as its widest paragraph.
    pub(super) fn frame_paragraphs(
        &mut self,
        (paragraphs, resolved): (&[&Paragraph], &[Resolved]),
        frame: FramePr,
        place: Option<Length>,
    ) {
        let (section, story, (left, width), shift) = self.framed(paragraphs, resolved, frame);
        let inner = self.frame_story(None);
        let part = std::rc::Rc::clone(&self.context.endnotes.part);
        self.warn_of_box_note_marks(paragraphs.iter().copied(), true, part.as_str());
        let height = |layout: &mut Self| {
            layout.layout_without_warnings(|layout| {
                layout
                    .story_in(&section, &story, Length::ZERO, inner.clone())
                    .1
            })
        };
        let top = self.frame_top(frame, place, height);
        // The frame's box, for the target that cuts its inline pictures there: at its offset
        // across, and from its top to its exact height, or else as low as its content.
        let quirks = self.context.quirks;
        let inside = decisions::inline_picture_cut(&quirks, || {
            let bottom = match frame.height {
                Some((h, true)) => top + h,
                _ => frame_bottom(frame, top, top + height(self)),
            };
            Some(Edges {
                left: left + shift,
                top,
                right: left + shift + width,
                bottom,
            })
        });
        let inner = self.frame_story(inside);
        let (items, end, lines) = self.placed_story(&section, &story, top, inner);
        self.items.extend(items);
        // The records of the frame's lines join the records of the story that holds the frame.
        self.output.placed.extend(lines);
        self.wrap_frame(frame, (left, width), (top, end));
        let frame_box = FrameBox {
            edges: Edges {
                left,
                top,
                right: left + width,
                bottom: frame_bottom(frame, top, end),
            },
            keeps_apart: resolved.iter().find_map(|resolved| {
                resolved
                    .props
                    .suppress_overlap
                    .as_ref()
                    .filter(|set| set.value)
                    .map(|set| set.part.clone())
            }),
            drop_cap: frame.drop_cap,
        };
        self.keep_frame_box(frame_box);
    }

    /// Keeps the box of a frame of the body's page, and warns once for the frame when it
    /// overlaps an earlier frame of the page and one of the two must not overlap other frames
    /// (`w:suppressOverlap`, ECMA-376 Part 1, 17.3.1.36): Word moves such a frame, and F-Office
    /// leaves it at its own place. The
    /// warning names the part that sets the setting for the frame, or else for the earlier
    /// frame. The frames of a story and of a table cell are not kept, as their wraps are not.
    fn keep_frame_box(&mut self, frame_box: FrameBox) {
        if self.column.cell.is_some() || self.story.is_some() {
            return;
        }
        let edges = frame_box.edges;
        let overlaps = |earlier: &Edges<Length>| {
            earlier.left < edges.right
                && edges.left < earlier.right
                && earlier.top < edges.bottom
                && edges.top < earlier.bottom
        };
        let part = self.frame_boxes.iter().find_map(|earlier| {
            overlaps(&earlier.edges)
                .then(|| {
                    frame_box
                        .keeps_apart
                        .as_ref()
                        .or(earlier.keeps_apart.as_ref())
                })
                .flatten()
                .cloned()
        });
        if let Some(part) = part {
            self.warn_of_feature(crate::Feature::FrameOverlap, part.as_str());
        }
        self.frame_boxes.push(frame_box);
    }

    /// How far below the flow the frame of `paragraphs` reaches when it stands at its place in
    /// the text: its height. `None` for a frame that hangs on the page or the margins, and for
    /// one with a distance down from its place (`w:y`), which stays on its page in Word.
    pub(super) fn frame_reach(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
        frame: FramePr,
    ) -> Option<Length> {
        let moved = frame.y.is_some_and(|y| y != Length::ZERO);
        if moved || self.v_anchor(frame) != Anchor::Text {
            return None;
        }
        let (section, story, ..) = self.framed(paragraphs, resolved, frame);
        let inner = self.frame_story(None);
        let end = self.layout_without_warnings(|layout| {
            layout.story_in(&section, &story, Length::ZERO, inner).1
        });
        Some(frame_bottom(frame, Length::ZERO, end))
    }

    /// The story of a frame in this layout, whose box on the page is `inside` where it is
    /// known: the page numbers of a story inside it ([`Self::inner_numbers`]), with the number
    /// of the footnote that holds the frame. It copies the behavior from before the story
    /// kinds: the endnote number does not pass on, so an endnote mark in a frame of an endnote
    /// shows 1, an open case.
    fn frame_story(&self, inside: Option<Edges<Length>>) -> super::Story {
        super::Story {
            kind: super::StoryKind::Frame { inside },
            numbers: super::StoryNumbers {
                note: self.footnote_label(),
                ..self.inner_numbers()
            },
        }
    }

    /// The content of the frame of `paragraphs` and its place across.
    fn framed(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
        frame: FramePr,
    ) -> Framed {
        let (content, lines) = self.frame_content(paragraphs, resolved);
        let page = self.section.width;
        // A frame at the text lies across in the text column of its paragraph, in a section
        // of more than one column.
        let column = self
            .columns
            .get(self.column_index)
            .filter(|_| self.columns.len() > 1);
        let (area_left, area_right) = match (frame.h_anchor, column) {
            (Anchor::Page, _) => (Length::ZERO, page),
            (Anchor::Text, Some(&(left, width))) => (left, left + width),
            (Anchor::Margin | Anchor::Text, _) => (self.section.left, page - self.section.right),
        };
        // A frame without a width that holds more than one line is as wide as the text column
        // that it lies in in a section of more than one column, and else as its area.
        let fitted = if lines > 1 {
            match self.columns.get(self.column_index) {
                Some(&(_, column)) if self.columns.len() > 1 => column,
                _ => area_right - area_left,
            }
        } else {
            content + decisions::frame_fitted_room(&self.context.quirks)
        };
        let width = frame.width.unwrap_or(fitted);
        let x_align = frame
            .x_align
            .map(|align| align.on_page(self.current_page_is_even()));
        let (left, shift) = match (x_align, frame.x) {
            (Some(Align::Center), _) => (
                area_left + (area_right - area_left - width).div_toward_zero(2),
                Length::ZERO,
            ),
            (Some(Align::End | Align::Outside), _) => (area_right - width, Length::ZERO),
            (Some(Align::Start | Align::Inside), _) | (None, None) => (area_left, Length::ZERO),
            (None, Some(x)) => {
                let shift = decisions::frame_shift_left(&self.context.quirks);
                (area_left + x - shift, shift)
            }
        };
        // A frame's text lies in one column as wide as the frame, whatever columns the
        // section has.
        let mut section = self.section;
        section.left = left;
        section.right = page - left - width;
        section.columns = crate::body::Columns::default();
        let story: Vec<Block> = paragraphs
            .iter()
            .map(|paragraph| Block::Paragraph((*paragraph).clone()))
            .collect();
        (section, story, (left, width), shift)
    }

    /// The width that the content of a frame's paragraphs needs, and the number of their lines.
    /// The frame holds each line at the line's own place, so the indent of the first line,
    /// which is negative for a hanging indent, counts for the first line.
    fn frame_content(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
    ) -> (Length, usize) {
        let mut widest_paragraph = Length::ZERO;
        let mut count = 0;
        for (paragraph, resolved) in paragraphs.iter().zip(resolved) {
            let (lines, ..) = self.prepare(paragraph, resolved);
            let first = resolved.props.indent_first.unwrap_or(Length::ZERO);
            let starts = std::iter::once(first).chain(std::iter::repeat(Length::ZERO));
            let widest = lines
                .iter()
                .zip(starts)
                .map(|(line, start)| start + line.width())
                .max()
                .unwrap_or(Length::ZERO);
            let indents = resolved.props.indent_left.unwrap_or(Length::ZERO)
                + resolved.props.indent_right.unwrap_or(Length::ZERO);
            widest_paragraph = widest_paragraph.max(widest + indents);
            count += lines.len();
        }
        (widest_paragraph, count)
    }

    /// Keeps the text of the page out of a frame that it flows around, by the frame's
    /// distances: beside it for `around`, and below it for `notBeside`. The frame is as tall as
    /// `w:h` when the height is exact, at least `w:h` otherwise, and else as its content.
    fn wrap_frame(
        &mut self,
        frame: FramePr,
        (left, width): (Length, Length),
        (top, end): (Length, Length),
    ) {
        // Only frames of the body move its text: a story such as a footer keeps its frames to
        // itself.
        if self.column.cell.is_some() || self.story.is_some() {
            return;
        }
        let bottom = frame_bottom(frame, top, end);
        let (h_space, v_space) = frame.spacing;
        let narrowest = if self.settings.mode_rules.frames_take_narrow_pieces() {
            NARROWEST_WRAP
        } else {
            FRAME_NARROWEST_PIECE
        };
        match frame.wrap {
            // The text flows on both sides of a frame where there is room.
            FrameWrap::Around => self.squares.push(Square {
                top: top - v_space,
                bottom: bottom + v_space,
                left: left - h_space,
                right: left + width + h_space,
                below: bottom + v_space,
                sides: Some(WrapSides::Both),
                line_steps: false,
                polygon: false,
                outline: None,
                narrowest,
                start_past: StartPastWrap::Whole,
                table: false,
            }),
            FrameWrap::NotBeside => self.bands.push(super::Band {
                top: top - v_space,
                bottom: bottom + v_space,
                left: left - h_space,
                right: left + width + h_space,
            }),
            FrameWrap::None => {}
        }
    }

    /// Whether `line`, which a wrap has `narrowed` or not, stands beside a drop cap in the text.
    /// Word counts the pieces of the paragraph's text again from the first glyph of the first
    /// line under a drop cap, where the line before stood `beside` it and `line` is not narrowed.
    pub(super) fn lines_under_drop_cap(
        &mut self,
        line: &Line,
        narrowed: bool,
        beside: bool,
    ) -> bool {
        if beside && !narrowed {
            let area = (self.output.pages.len(), self.column_index);
            self.text_part = (area, super::line::first_text_place(line));
        }
        narrowed && self.frame_boxes.iter().any(|f| f.drop_cap_beside(self.y))
    }

    /// The top of a frame: `w:yAlign` puts it at the top, in the middle or at the bottom of
    /// its anchor area, the page or the margins, and otherwise `w:y` gives its distance from
    /// the anchor's top, for a frame at the text from `place` when the paragraph before it
    /// held one.
    fn frame_top(
        &mut self,
        frame: FramePr,
        place: Option<Length>,
        height: impl FnOnce(&mut Self) -> Length,
    ) -> Length {
        let page = self.section.height;
        let v_anchor = self.v_anchor(frame);
        let area = match v_anchor {
            Anchor::Page => Some((Length::ZERO, page)),
            Anchor::Margin => Some((self.section.top, page - self.section.bottom)),
            Anchor::Text => None,
        };
        if let (Some(align), Some((top, bottom))) = (frame.y_align, area) {
            return match align {
                Align::Start | Align::Inside => top,
                Align::Center => top + (bottom - top - height(self)).div_toward_zero(2),
                Align::End | Align::Outside => bottom - height(self),
            };
        }
        let offset = frame.y.unwrap_or(Length::ZERO);
        match v_anchor {
            Anchor::Page => offset,
            Anchor::Margin => self.section.top + offset,
            // A frame at the text starts below the space after the paragraph before it, or at
            // the place that it held before that paragraph went below its band.
            Anchor::Text => place.unwrap_or_else(|| self.frame_text_place()) + offset,
        }
    }

    /// The place in the text of a frame after the paragraph laid out last: below its whole
    /// space after.
    pub(super) fn frame_text_place(&self) -> Length {
        self.y + frame_lead(self.previous.as_ref())
    }

    /// Lays out the paragraph at `index` of `paragraphs` with `lay`, and the paragraph again
    /// when the frames at the text right after it move its lines. Each such frame that keeps
    /// the text below it and has a distance above it has a band, from its top less that
    /// distance; when the band reaches above the paragraph's last line on the same page and
    /// column, the paragraph is laid out again with the bands so far: its lines that reach
    /// into a band go below it. Each frame whose band moves the lines keeps the place that the
    /// paragraph gave it before that band, and a later frame counts from the paragraph's lines
    /// below the bands before it. A frame whose band moves none keeps its place too, and its
    /// band takes the lines that a later band moves into it; or, from the compatibility mode
    /// that `ModeRules::frame_without_band_follows_the_lines` names, it counts from the lines
    /// as all the bands leave them. Before the compatibility mode that
    /// `ModeRules::frame_band_reaches_from_frame_top` names, the paragraph's last line reaches
    /// into a band with its space after.
    pub(super) fn before_frame_band(
        &mut self,
        (paragraphs, resolved): (&[&Paragraph], &[Resolved]),
        index: usize,
        mut lay: impl FnMut(&mut Self),
    ) {
        self.frame_places.clear();
        let in_body = self.column.cell.is_none() && self.story.is_none();
        if !in_body || self.frame_run(resolved, index + 1).is_none() {
            lay(self);
            return;
        }
        let mark = self.mark();
        let area = (self.output.pages.len(), self.column_index);
        lay(self);
        let mut bands = Vec::new();
        let mut waiting = Vec::new();
        let mut places = Vec::new();
        let follows = self
            .settings
            .mode_rules
            .frame_without_band_follows_the_lines();
        let mut start = index + 1;
        while let Some((frame, end)) = self.frame_run(resolved, start) {
            if (self.output.pages.len(), self.column_index) != area {
                return;
            }
            let place = self.frame_text_place();
            let run = (
                paragraphs.get(start..end).unwrap_or_default(),
                resolved.get(start..end).unwrap_or_default(),
            );
            let band = self.band_before(run, frame, place);
            let reaches = band.filter(|band| band.top < self.y);
            if reaches.is_some() || !follows {
                places.push((start, place));
            }
            match (reaches, band) {
                (Some(band), _) => {
                    bands.push(band);
                    // The frames before that kept their places take the moved lines with their
                    // bands too.
                    loop {
                        self.rewind(&mark);
                        self.bands.extend_from_slice(&bands);
                        lay(self);
                        let Some(at) = waiting
                            .iter()
                            .position(|band: &super::Band| band.top < self.y)
                        else {
                            break;
                        };
                        bands.push(waiting.swap_remove(at));
                    }
                }
                (None, Some(band)) if !follows => waiting.push(band),
                _ => {}
            }
            start = end;
        }
        if !bands.is_empty() {
            self.frame_places = places;
        }
    }

    /// The band of the frame of the paragraphs `run`, at `place` in the text, when it keeps the
    /// text below it and has a distance above it.
    fn band_before(
        &mut self,
        (paragraphs, resolved): (&[&Paragraph], &[Resolved]),
        frame: FramePr,
        place: Length,
    ) -> Option<super::Band> {
        let keeps_below = frame.wrap == FrameWrap::NotBeside
            && frame.spacing.1 > Length::ZERO
            && frame.y_align.is_none()
            && self.v_anchor(frame) == Anchor::Text;
        if !keeps_below {
            return None;
        }
        let (section, story, (left, _), width) = self.framed(paragraphs, resolved, frame);
        let inner = self.frame_story(None);
        let height = self.layout_without_warnings(|layout| {
            layout.story_in(&section, &story, Length::ZERO, inner).1
        });
        let top = place + frame.y.unwrap_or(Length::ZERO);
        let (h_space, v_space) = frame.spacing;
        let reach = top - v_space;
        // Before the mode, the last line counts with the space after below it, which the frame
        // starts below: a band from the middle of that line takes that line alone.
        let last_line_middle = self
            .output
            .placed
            .last()
            .filter(|_| !self.settings.mode_rules.frame_band_reaches_from_frame_top())
            .filter(|_| place > reach)
            .map(|line| line.top + line.height.div_toward_zero(2));
        let band_top = last_line_middle.map_or(reach, |middle| reach.min(middle));
        Some(super::Band {
            top: band_top,
            bottom: frame_bottom(frame, top, top + height) + v_space,
            left: left - h_space,
            right: left + width + h_space,
        })
    }

    /// What a frame's place down is measured from. Without `w:vAnchor`, a frame of the body
    /// aligns in the margins and counts `w:y` from the top of the page, while a frame of a
    /// story, such as a header or footer, counts from its paragraph.
    fn v_anchor(&self, frame: FramePr) -> Anchor {
        match (frame.v_anchor_named, self.story.is_some(), frame.y_align) {
            (true, _, _) | (false, true, _) => frame.v_anchor,
            (false, false, Some(_)) => Anchor::Margin,
            (false, false, None) => Anchor::Page,
        }
    }
}

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

    use super::FrameBox;

    #[test]
    fn a_drop_cap_stands_beside_the_lines_whose_tops_it_reaches() {
        let pt = |points: i64| Length::from_points(points).expect("a length");
        let frame = |drop_cap| FrameBox {
            edges: Edges {
                left: pt(72),
                top: pt(100),
                right: pt(110),
                bottom: pt(140),
            },
            keeps_apart: None,
            drop_cap,
        };
        assert!(frame(true).drop_cap_beside(pt(100)));
        assert!(frame(true).drop_cap_beside(pt(127)));
        assert!(!frame(true).drop_cap_beside(pt(140)));
        assert!(!frame(true).drop_cap_beside(pt(90)));
        assert!(!frame(false).drop_cap_beside(pt(127)));
    }
}