f-office-docx 0.3.0

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
//! Sections: page size, margins, headers, footers and page numbers that change within a
//! body.

use crate::body::{Block, LineNumberRestart, Section, SectionStart};

use super::{Layout, PageInfo, SectionLayout};

/// The place of one section among the sections of a layout, from 0. Only [`Layout::adopt`]
/// makes one, after it found its section there, besides [`SectionIndex::FIRST`], and the
/// sections of a layout do not change, so that every index names one of them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct SectionIndex(usize);

impl SectionIndex {
    /// The first section, which every layout has.
    pub(super) const FIRST: Self = Self(0);
}

/// Whether a page number is odd or even. With different odd and even headers, the even
/// numbers take the even header and footer; mirrored margins swap the sides of an even page;
/// and a section that starts on an odd or even page starts on a page of that number.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Parity {
    /// An odd number, a right-hand page.
    Odd,
    /// An even number, a left-hand page.
    Even,
}

impl Parity {
    /// The parity of the page number `number`.
    pub(super) const fn of(number: i64) -> Self {
        if number % 2 == 0 {
            Self::Even
        } else {
            Self::Odd
        }
    }
}

impl Layout<'_> {
    /// Lays out the blocks of each section in turn.
    pub(super) fn sections_flow(&mut self, blocks: &[Block]) {
        let mut begin = 0;
        for index in 0..self.sections.count() {
            let Some((end, start)) = self.sections.get(index).map(|s| (s.end, s.start)) else {
                continue;
            };
            if index > 0 {
                self.start_section(index, start);
            }
            let end = end.clamp(begin, blocks.len());
            let part = blocks.get(begin..end).unwrap_or_default();
            self.section_end_paragraph = match part.last() {
                Some(Block::Paragraph(paragraph)) if index + 1 < self.sections.count() => {
                    Some(paragraph.id)
                }
                _ => None,
            };
            // Columns before a continuous section break on the same page share their text evenly.
            let continuous = self.continues_on_same_page(index + 1);
            if continuous && self.columns.len() > 1 {
                self.balanced_blocks(part);
            } else {
                self.blocks(part);
                self.section_top = super::columns::SectionTop::Placed;
                if continuous && matches!(blocks.get(end), Some(Block::Paragraph(_))) {
                    self.hidden_section_end(part);
                }
            }
            begin = end;
        }
    }

    /// The empty paragraph that ends a section of one column before a continuous section, when
    /// it shows nothing, stands between the paragraph before it and the next section's first
    /// paragraph without a line, as below balanced columns: the space after of the paragraph
    /// before it stays in the section, and the next paragraph has only the part of its space
    /// before beyond the empty paragraph's space after. The empty paragraph's space before has
    /// no effect.
    ///
    /// Where the target keeps those spaces ([`super::decisions::spaced_section_end`]).
    pub(super) fn hidden_section_end(&mut self, blocks: &[Block]) {
        let Some(blocks) = super::decisions::spaced_section_end(&self.context.quirks, blocks)
        else {
            return;
        };
        if let Some((after, props)) = self.hidden_end(blocks) {
            self.y += after;
            self.section_previous = Some(super::Previous::of(&props));
        }
    }

    /// Whether section `index` starts continuously on the current page (continuous break with the
    /// same page size and orientation as the current section).
    pub(super) fn continues_on_same_page(&self, index: usize) -> bool {
        self.sections.get(index).is_some_and(|next| {
            next.start == SectionStart::Continuous && self.section.same_page_size(&next.section)
        })
    }

    /// Starts a section on a new page, or on this page for a continuous section with the same page
    /// size and orientation.
    pub(super) fn start_section(&mut self, index: usize, start: SectionStart) {
        let from_break = self.page_from_break == Some(self.output.pages.len());
        if start == SectionStart::Continuous && self.continues_on_same_page(index) {
            // The section before ends on this page with its columns.
            self.paint_column_separators();
            if from_break && self.page_has_no_line() {
                // Nothing of the previous section has taken a line on the page that its page
                // break began, so the continuous section adopts this page directly.
                self.adopt(index);
                self.move_to_body_top(self.output.pages.len());
                self.column_top = self.y;
                self.section_top = super::columns::SectionTop::Placed;
                return;
            }
            // The margins, columns, and line numbering change at once; the page size and the
            // headers change on the next page.
            if let Some(next) = self.sections.get(index).map(|s| s.section) {
                self.take_side_margins(&next);
                self.section.columns = next.columns;
                self.adopt_continuous_line_numbers(&next);
                self.set_columns();
                self.section_top = if self.columns.len() > 1 {
                    super::columns::SectionTop::Pending
                } else {
                    super::columns::SectionTop::Placed
                };
            }
            self.pending = Some(index);
            return;
        }
        // A section after a page break starts on the page that the break began, when nothing
        // but empty paragraphs has come onto it. Their line numbers and fills go with them,
        // and the count of numbered lines goes on from the break.
        if from_break && self.items.count() == self.break_numbers.0 {
            self.items.cut(0);
            self.output.line_count = self.break_numbers.1;
            self.break_numbers.0 = 0;
        }
        if !(from_break && self.page_is_empty()) {
            self.new_page();
        }
        // The space after the last paragraph of the section stays on its page.
        self.section_previous = self.previous.take();
        self.adopt(index);
        let number = self.page_number(self.output.pages.len());
        // With different odd and even headers, a section that restarts its page numbers puts
        // an odd number on a right-hand page and an even number on a left-hand page.
        let restarts = self.sections.get(index).is_some_and(|s| s.restarts_numbers);
        let right_hand = self.right_hand_next();
        let other_side = self.settings.even_and_odd_headers
            && restarts
            && (Parity::of(number) == Parity::Odd) != right_hand;
        let wrong = other_side
            || match start {
                SectionStart::EvenPage => Parity::of(number) != Parity::Even,
                SectionStart::OddPage => Parity::of(number) != Parity::Odd,
                SectionStart::NextPage | SectionStart::Continuous => false,
            };
        if wrong {
            // Word leaves a blank page, without a header or a footer, to start the section on
            // the right side. The section starts on the page after it.
            self.output.blank_pages.push(self.output.pages.len());
            self.new_page();
            self.adopt(index);
        }
        self.move_to_body_top(self.output.pages.len());
        self.column_top = self.y;
        self.section_top = super::columns::SectionTop::Placed;
    }

    /// Updates line numbering when a continuous section begins mid-page: enables or disables line
    /// numbers immediately, restarts the counter for `newSection` (or when turning numbering on),
    /// and preserves the running page counter and start offset for `newPage` until the next page.
    fn adopt_continuous_line_numbers(&mut self, next: &Section) {
        match (self.section.line_numbers, next.line_numbers) {
            (_, None) => {
                self.section.line_numbers = None;
                self.output.line_count.0 = 0;
            }
            (None, Some(next)) => {
                if next.restart != LineNumberRestart::Continuous {
                    self.output.line_count.0 = 0;
                }
                self.section.line_numbers = Some(next);
            }
            (Some(_), Some(next)) if next.restart == LineNumberRestart::NewSection => {
                self.output.line_count.0 = 0;
                self.section.line_numbers = Some(next);
            }
            (Some(prev), Some(mut next)) if next.restart == LineNumberRestart::NewPage => {
                next.start = prev.start;
                self.section.line_numbers = Some(next);
            }
            (Some(_), Some(next)) => {
                self.section.line_numbers = Some(next);
            }
        }
    }

    /// Whether the page being filled is a right-hand page for a section that restarts its page
    /// numbers: by its place in the document, the odd places, or by the number of the page
    /// before it, after which it takes the other side; the first page is a right-hand page.
    fn right_hand_next(&self) -> bool {
        super::decisions::restart_side(
            &self.context.quirks,
            || self.output.pages.len().is_multiple_of(2),
            || {
                self.output
                    .page_infos
                    .last()
                    .is_none_or(|before| Parity::of(before.number) == Parity::Even)
            },
        )
    }

    /// Makes a section the current one from the page being filled on.
    pub(super) fn adopt(&mut self, index: usize) {
        let Some((section, restarts)) = self
            .sections
            .get(index)
            .map(|s| (s.section, s.restarts_numbers))
        else {
            return;
        };
        let next = self
            .output
            .page_infos
            .last()
            .map_or(section.first_page_number, |p| p.number.saturating_add(1));
        self.number_start = if restarts {
            section.first_page_number
        } else {
            next
        };
        let restart = section.line_numbers.map(|n| n.restart);
        if restart != Some(LineNumberRestart::Continuous) {
            self.output.line_count.0 = 0;
        }
        self.section = section;
        self.device = self.device.with_page(
            self.section.width,
            self.section.height,
            self.section.orientation,
        );
        self.section_index = SectionIndex(index);
        self.section_first_page = self.output.pages.len();
        self.section_title_page = Some(self.output.pages.len());
        self.take_side_margins(&section);
        self.set_columns();
        self.measure_body();
        self.start_wraps();
    }

    /// The section and the number of a page, finished or being filled.
    pub(super) fn page_info(&self, index: usize) -> PageInfo {
        if let Some(info) = self.output.page_infos.get(index) {
            return *info;
        }
        let offset = index.saturating_sub(self.section_first_page);
        PageInfo {
            section: self.section_index,
            number: self
                .number_start
                .saturating_add(f_office_units::count_factor(offset)),
            first: self.section_title_page == Some(index),
        }
    }

    /// The section `index` of the flow.
    pub(super) fn section_layout(&self, index: SectionIndex) -> &SectionLayout {
        // `get` finds every index that `adopt` made. A lookup by a number gives an `Option`,
        // and the workspace lints refuse `expect` and indexing, so a release build gives the
        // first section for the case that no index can reach; a debug build, as the tests
        // run, stops there.
        debug_assert!(
            index.0 < self.sections.count(),
            "a section index names a section of its layout"
        );
        self.sections
            .get(index.0)
            .unwrap_or_else(|| self.sections.first())
    }

    /// The page settings of a section, with its own side margins.
    pub(super) fn section_of(&self, index: SectionIndex) -> Section {
        self.section_layout(index).section
    }

    /// Whether the page currently being filled (or the page of the active header/footer story)
    /// has an even page number, used to flip `inside`/`outside` horizontal alignment.
    pub(super) fn current_page_is_even(&self) -> bool {
        let number = self.story_pages().map_or_else(
            || self.page_number(self.output.pages.len()),
            |(page, _)| page,
        );
        matches!(Parity::of(number), Parity::Even)
    }

    /// The section of the page `index`, with the side margins of its side.
    pub(super) fn page_section(&self, index: usize) -> Section {
        let info = self.page_info(index);
        let section = self.section_of(info.section);
        let even = matches!(Parity::of(info.number), Parity::Even);
        let (left, right) = section.side_margins(self.settings.side_margins, even);
        Section {
            right,
            left,
            ..section
        }
    }

    /// Gives the page being filled the side margins of `section` for its side.
    pub(super) fn take_side_margins(&mut self, section: &Section) {
        let number = self.page_number(self.output.pages.len());
        let even = matches!(Parity::of(number), Parity::Even);
        (self.section.left, self.section.right) =
            section.side_margins(self.settings.side_margins, even);
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::Write as _;

    use super::Parity;
    use crate::body::Body;
    use crate::layout::testing::{Fake, base_context, find, p, parse, sections_of};
    use crate::layout::{Context, Layout, Stories};
    use crate::ns::W;
    use crate::quirks::{BodyFieldResults, RestartSide};
    use crate::reader::PartReader;
    use crate::styles::{FontTable, Settings, Styles, Theme};
    use crate::text::{Shaper, ShaperSettings};

    /// The page, from 0, of the second section's first glyph in a body of two sections under
    /// different headers of odd and even pages: the first starts its page numbers at `first`
    /// and holds `pages` pages, and the second starts on the next page and restarts its
    /// numbers at `restart`, on the base target with the restart side `side`.
    fn second_section_page(side: RestartSide, first: u32, pages: usize, restart: u32) -> usize {
        let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
        let mut body = String::new();
        for _ in 1..pages {
            body.push_str(&p("A"));
            body.push_str(r#"<w:p><w:r><w:br w:type="page"/></w:r></w:p>"#);
        }
        write!(
            body,
            r#"<w:p><w:pPr><w:sectPr>{page}<w:pgNumType w:start="{first}"/></w:sectPr></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#
        )
        .unwrap();
        body.push_str(&p("B"));
        write!(
            body,
            r#"<w:sectPr>{page}<w:pgNumType w:start="{restart}"/></w:sectPr>"#
        )
        .unwrap();
        let doc = parse(&format!(r#"<w:body xmlns:w="{W}">{body}</w:body>"#));
        let quirks = crate::profile::Profile::base().with_variant(side).quirks();
        let settings = Settings {
            even_and_odd_headers: true,
            ..Settings::default()
        };
        let body = Body::read(
            &mut PartReader::new(&doc),
            doc.root().unwrap(),
            (
                crate::reader::settings::ReaderSettings::of(&quirks)
                    .with_body_results(BodyFieldResults::ComputesFields),
                settings.mode_rules,
            ),
        );
        let styles = Styles::default();
        let sections = sections_of(&body, &Stories::default());
        let context = Context {
            quirks,
            ..base_context(&styles, &settings)
        };
        let stories = context.for_stories();
        let (theme, fonts) = (Theme::default(), FontTable::default());
        let list = Layout::new(
            (&context, &stories),
            &sections,
            Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
        )
        .run_with_wraps(&body)
        .list;
        find(&list, 'B').0
    }

    #[test]
    fn a_restarted_section_takes_its_side_from_the_number_of_the_page_before_where_the_target_does()
    {
        // The first number, the pages and the restart of each case. After a first page
        // numbered 1, both variants make the second page a left-hand page: a restart at 1 leaves
        // a blank page, one at 2 none. After a first page numbered 2, the second page is a
        // left-hand page by its place and a right-hand page by the number before it. After
        // pages 42 and 43, the third page is a right-hand page by its place and a left-hand page
        // by the number before it.
        let cases = [(1, 1, 1), (1, 1, 2), (2, 1, 1), (2, 1, 2), (42, 2, 1)];
        let pages = |side| {
            cases.map(|(first, count, restart)| second_section_page(side, first, count, restart))
        };
        assert_eq!(pages(RestartSide::Place), [2, 1, 2, 1, 2]);
        assert_eq!(pages(RestartSide::PreviousNumber), [2, 1, 1, 2, 3]);
    }

    #[test]
    fn tells_odd_and_even_page_numbers_apart_also_below_one() {
        let parities = [-3, -2, 0, 1, 2, 7].map(Parity::of);
        assert_eq!(
            parities,
            [
                Parity::Odd,
                Parity::Even,
                Parity::Even,
                Parity::Odd,
                Parity::Even,
                Parity::Odd
            ]
        );
    }

    fn flow_body<R>(xml: &str, read: impl FnOnce(&Layout<'_>) -> R) -> R {
        let doc = parse(xml);
        let quirks = crate::profile::Profile::base().quirks();
        let settings = Settings::default();
        let body = Body::read(
            &mut PartReader::new(&doc),
            doc.root().unwrap(),
            (
                crate::reader::settings::ReaderSettings::of(&quirks),
                settings.mode_rules,
            ),
        );
        let styles = Styles::default();
        let sections = sections_of(&body, &Stories::default());
        let context = Context {
            quirks,
            ..base_context(&styles, &settings)
        };
        let stories = context.for_stories();
        let (theme, fonts) = (Theme::default(), FontTable::default());
        let mut layout = Layout::new(
            (&context, &stories),
            &sections,
            Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
        );
        layout.sections_flow(&body.blocks);
        read(&layout)
    }

    #[test]
    fn continuous_section_adopts_empty_page_started_by_page_break() {
        let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
        let run = |extra_empty: bool| {
            let empty = if extra_empty { "<w:p/>" } else { "" };
            let xml = format!(
                r#"<w:body xmlns:w="{W}">{p1}<w:p><w:r><w:br w:type="page"/></w:r></w:p>{empty}<w:p><w:pPr><w:sectPr>{page}</w:sectPr></w:pPr></w:p>{p2}<w:sectPr><w:type w:val="continuous"/>{page}</w:sectPr></w:body>"#,
                p1 = p("A"),
                p2 = p("B"),
            );
            flow_body(&xml, |layout| layout.page_info(1))
        };
        // No line of section 1 on page 2 -> continuous section 2 adopts page 2 immediately.
        let adopted = run(false);
        assert_eq!(adopted.section.0, 1);
        assert!(adopted.first);
        // An extra empty paragraph on page 2 keeps section 1 on page 2.
        let kept = run(true);
        assert_eq!(kept.section.0, 0);
    }

    #[test]
    fn continuous_section_with_different_page_size_starts_new_page() {
        let letter = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
        let a4 = r#"<w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
        let tall_margin = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="2880" w:right="1440" w:bottom="2880" w:left="1440"/>"#;
        let run = |s2_props: &str, s2_body: &str| {
            let xml = format!(
                r#"<w:body xmlns:w="{W}">{p1}<w:p><w:pPr><w:sectPr>{letter}</w:sectPr></w:pPr></w:p>{s2_body}<w:sectPr><w:type w:val="continuous"/>{s2_props}</w:sectPr></w:body>"#,
                p1 = p("A"),
            );
            flow_body(&xml, |layout| {
                (layout.output.pages.len() + 1, layout.section.width)
            })
        };
        // Letter -> A4 continuous section forces page 2 even with only empty paragraphs.
        let (pages_a4, width_a4) = run(a4, "<w:p/>");
        assert_eq!(pages_a4, 2);
        assert_eq!(width_a4, f_office_units::Length::from_twips(11906).unwrap());
        // Same page size with changed top/bottom margins stays on page 1.
        let (pages_mar, _) = run(tall_margin, &p("B"));
        assert_eq!(pages_mar, 1);
    }
}