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
//! Where a line moves across its column: the alignment of the line, and how a justified line
//! spreads its free space over its spaces, or over its punctuation and gaps.

use f_office_units::Length;

use super::LinePlace;
use crate::character_class::CharacterClass;
use crate::layout::measure::JUSTIFIED_SHRINK;
use crate::layout::{Layout, decisions};
use crate::lines::{Line, LineEnd, Piece, stretches};
use crate::mode::ShareRounding;
use crate::params;
use crate::props::{Alignment, ParaProps};
use crate::quirks::Quirks;
use crate::styles::{Settings, SoftBreakLines};

/// Where a line moves across its column: the offset of a centered or right-aligned line, and
/// the free space that a justified line spreads over its spaces.
pub(in crate::layout) struct Shift {
    pub(in crate::layout) offset: Length,
    pub(in crate::layout) spread: Length,
}

/// How a justified line splits its free space over its stretched spaces.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(in crate::layout) struct SpaceShares {
    /// What each stretched space takes: an equal share, toward zero to a whole half-EMU.
    pub(in crate::layout) per_space: Length,
    /// The part of the free space that the equal shares leave: how far the line's right edge
    /// lies past the exact right edge of its text.
    pub(in crate::layout) rest: Length,
}

impl Shift {
    /// How `line` splits its free space over its stretched spaces, or no share at all when the
    /// inner blank halves of its punctuation marks shrink instead (`mark_shrink` not zero).
    pub(in crate::layout) fn space_shares(&self, line: &Line, mark_shrink: Length) -> SpaceShares {
        match stretched_spaces(line) {
            Some(n) if mark_shrink == Length::ZERO => {
                let per_space = self.spread.div_toward_zero(n);
                SpaceShares {
                    per_space,
                    rest: self.spread - per_space * n,
                }
            }
            _ => SpaceShares::default(),
        }
    }
}

impl Shift {
    /// The shares of `line`'s free space that the edge check of right-edge steps counts under
    /// `EdgeShares::ExactFree`, where the line spreads its free space over its stretched spaces
    /// with `shares`, rounding took `lost` from the advances of its glyphs (a numerator over a
    /// positive denominator in half-EMUs, [`Layout::free_rounding`]) and the compatibility mode
    /// rounds the shares with `rounding`. Nothing for a line that spreads no free space over its
    /// spaces.
    pub(in crate::layout) fn counted_shares(
        &self,
        line: &Line,
        (shares, mark_shrink): (SpaceShares, Length),
        lost: (i128, i128),
        rounding: ShareRounding,
    ) -> Option<CountedShares> {
        let spaces = stretched_spaces(line)?;
        let (lost, per) = lost;
        (self.spread != Length::ZERO && mark_shrink == Length::ZERO && per > 0).then(|| {
            CountedShares {
                free: (i128::from(self.spread.units()) * per - lost, per),
                spaces,
                per_space: shares.per_space,
                rounding,
            }
        })
    }
}

/// The shares of a justified line's free space that the edge check of right-edge steps counts
/// under `EdgeShares::ExactFree` ([`Shift::counted_shares`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct CountedShares {
    /// The free space that the exact advances of the line's glyphs leave, in half-EMUs: a
    /// numerator over a positive denominator.
    free: (i128, i128),
    /// How many spaces the line stretches.
    spaces: i64,
    /// What each stretched space takes on the line ([`SpaceShares::per_space`]).
    per_space: Length,
    /// How the shares round to whole parts of a point.
    rounding: ShareRounding,
}

impl CountedShares {
    /// The sum of the shares of the line's first `k` stretched spaces, in whole parts of
    /// `params::SHARE_PARTS_PER_POINT`.
    fn summed_parts(&self, k: i64) -> i128 {
        let (free, per) = self.free;
        let parts = i128::from(params::SHARE_PARTS_PER_POINT);
        let denominator = per * i128::from(self.spaces) * i128::from(Length::UNITS_PER_POINT);
        match self.rounding {
            // Division of integers rounds toward zero.
            ShareRounding::SumTowardZero => i128::from(k) * free * parts / denominator,
            ShareRounding::RemainderFirst => {
                let spaces = i128::from(self.spaces);
                // The line's free space in whole parts, to the nearest, a half away from zero.
                let (numerator, whole) = (free * parts, per * i128::from(Length::UNITS_PER_POINT));
                let total = (2 * numerator + numerator.signum() * whole) / (2 * whole);
                let (each, left) = (total / spaces, total % spaces);
                i128::from(k) * each + left.signum() * i128::from(k).min(left.abs())
            }
        }
    }

    /// What the edge check counts in the advance of the line's `k`-th stretched space, from 1,
    /// beside the share that the line gives it: the sum of the shares up to it less the sum up to
    /// the space before, less that share, in half-EMUs as a numerator over a positive
    /// denominator.
    pub(in crate::layout) fn excess(&self, k: i64) -> (i128, i128) {
        let parts = i128::from(params::SHARE_PARTS_PER_POINT);
        let own = self.summed_parts(k) - self.summed_parts(k - 1);
        (
            own * i128::from(Length::UNITS_PER_POINT) - i128::from(self.per_space.units()) * parts,
            parts,
        )
    }
}

/// How many spaces `line` stretches, from its first stretched piece up to its last visible
/// one, or `None` when it stretches none.
pub(super) fn stretched_spaces(line: &Line) -> Option<i64> {
    let spaces = line
        .placed
        .iter()
        .take(line.written())
        .skip(line.first_stretched())
        .filter(|p| stretches(&p.piece))
        .count();
    i64::try_from(spaces).ok().filter(|n| *n > 0)
}

/// Whether `line` is aligned as its paragraph's last line: it is the last one (`last`), or it
/// ends in a soft line break where the document's `settings` keep such lines from being
/// justified (the compatibility option `w:doNotExpandShiftReturn`, ECMA-376 Part 1, 17.15.3.5)
/// and the target's `quirks` follow them.
pub(in crate::layout) fn aligned_as_last(
    line: &Line,
    last: bool,
    settings: &Settings,
    quirks: &Quirks,
) -> bool {
    last || (matches!(line.end, LineEnd::Break(_))
        && decisions::followed_soft_break_lines(quirks, settings.soft_break_lines)
            == Some(SoftBreakLines::AsLastLine))
}

impl Layout<'_> {
    /// The alignment of `line` at `place` in a paragraph of the properties `props`, and where
    /// the line moves across its column. A line that ends in a soft line break is aligned as
    /// the last line where [`aligned_as_last`] says so. A justified last line whose free space
    /// is negative (held on the line by shrinking its spaces) keeps its justified alignment so
    /// right-to-left last lines shrink their spaces just as left-to-right ones do.
    pub(super) fn alignment_and_shift(
        &self,
        line: &Line,
        props: &ParaProps,
        place: LinePlace,
    ) -> (Alignment, Shift) {
        let last = aligned_as_last(line, place.last, self.settings, &self.context.quirks);
        let free = place.width - line.width();
        let alignment = line_alignment(props, last && free >= Length::ZERO);
        (alignment, shift(alignment, free, last))
    }
}

/// The alignment of a line. A right-to-left paragraph starts at the right edge, and so does
/// the last line of its justified text.
pub(super) fn line_alignment(props: &ParaProps, last: bool) -> Alignment {
    let rtl = props.flags().bidi;
    match (props.alignment.unwrap_or(Alignment::Start), rtl) {
        (Alignment::Start, true) => Alignment::End,
        (Alignment::Both | Alignment::ThaiDistribute, true) if last => Alignment::End,
        (Alignment::End, true) => Alignment::Start,
        (alignment, _) => alignment,
    }
}

/// The blank halves of punctuation right before the piece at `index` of `line`: that of a
/// closing mark (or a Japanese middle dot) before it and that of an opening mark at it. The blank
/// half of a closing mark is its right half, that of an opening mark its left half, and that of a
/// centered mark its two blank quarters.
fn blank_halves_before(line: &Line, index: usize, sides: MarkSides) -> i64 {
    let glyph = |i: usize| match line.placed.get(i).map(|p| p.piece) {
        Some(Piece::Glyph(g)) => Some(g.ch),
        _ => None,
    };
    let closing = index > 0 && glyph(index - 1).is_some_and(|ch| sides.has_trailing_half(ch));
    let opening = glyph(index).is_some_and(crate::lines::opening_mark);
    i64::from(closing) + i64::from(opening)
}

/// [`blank_halves_before`] the piece at `index` when it lies after the first stretched piece of
/// `line` and not after its last visible one, and else 0: the halves that shrink when the line
/// compresses its punctuation.
pub(super) fn inner_blank_halves_before(line: &Line, index: usize, sides: MarkSides) -> i64 {
    if inner_piece(line, index) {
        blank_halves_before(line, index, sides)
    } else {
        0
    }
}

/// Which sides of a compressed punctuation mark give up its share.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum MarkSides {
    /// Every mark gives up its share on its blank half.
    BlankHalf,
    /// Colon, semicolon and middle dot (`:`, `;`, `・`) give up half of their share on each
    /// side (Japanese); the other marks give it up on their blank half.
    Japanese,
    /// A mark that stands in the middle of its em ([`crate::lines::centered_mark`]) gives up
    /// half of its share on each side (Traditional Chinese); the other marks give it up on their
    /// blank half.
    Centered,
}

impl MarkSides {
    /// Whether `ch` splits its compression shrink equally on its left and right sides.
    const fn splits(self, ch: char) -> bool {
        match self {
            Self::BlankHalf => false,
            Self::Japanese => crate::lines::japanese_centered_mark(ch),
            Self::Centered => crate::lines::centered_mark(ch),
        }
    }

    /// Whether `ch` carries a compressible blank half counted after it (closing marks, plus the
    /// middle dot in Japanese).
    fn has_trailing_half(self, ch: char) -> bool {
        crate::lines::closing_mark(ch) || (self == Self::Japanese && crate::lines::middle_dot(ch))
    }
}

/// What the inner blank halves of punctuation right before the piece at `index` of `line` give
/// up when each gives up `shrink` ([`inner_blank_halves_before`]). With `Japanese` or `Centered`
/// sides, a mark that stands in the middle of its em for that script between two inner pieces
/// gives up half of its share before itself and the rest after itself, so that the line's total
/// stays the same.
pub(in crate::layout) fn inner_mark_shrink_before(
    line: &Line,
    index: usize,
    shrink: Length,
    sides: MarkSides,
) -> Length {
    if !inner_piece(line, index) {
        return Length::ZERO;
    }
    let glyph = |i: usize| match line.placed.get(i).map(|p| p.piece) {
        Some(Piece::Glyph(g)) => Some(g.ch),
        _ => None,
    };
    let split = |i: usize| {
        inner_piece(line, i)
            && inner_piece(line, i + 1)
            && glyph(i).is_some_and(|ch| sides.splits(ch))
    };
    let before = shrink.div_toward_zero(2);
    let own = if split(index) {
        before
    } else if glyph(index).is_some_and(crate::lines::opening_mark) {
        shrink
    } else {
        Length::ZERO
    };
    let after_mark = match index.checked_sub(1) {
        Some(previous) if split(previous) => shrink - before,
        Some(previous) if glyph(previous).is_some_and(|ch| sides.has_trailing_half(ch)) => shrink,
        _ => Length::ZERO,
    };
    own + after_mark
}

/// Whether the piece at `index` of `line` lies after its first stretched piece and not after
/// its last visible one, so that a gap or a blank half before it moves it.
pub(super) fn inner_piece(line: &Line, index: usize) -> bool {
    index > line.first_stretched() && line.last_visible().is_some_and(|v| index <= v)
}

/// Whether the gap before the piece at `index` of `line` takes a share of the room of a
/// justified line without spaces: it is an inner gap ([`inner_piece`]) and the glyph before or
/// after it is full-width. A gap between two other pieces keeps its width.
pub(in crate::layout) fn spread_gap(line: &Line, index: usize) -> bool {
    let full_width = |i: usize| matches!(line.placed.get(i).map(|p| p.piece), Some(Piece::Glyph(g)) if CharacterClass::FullWidthCell.contains(g.ch));
    inner_piece(line, index) && (full_width(index - 1) || full_width(index))
}

/// How a justified line with the justification of `WordPerfect` that runs past its width
/// narrows its pieces beyond what its stretched spaces give up: every piece from its first
/// stretched one to its last visible one by `each`, and those from `from` on by one dot of the
/// device more.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct Narrowing {
    first: usize,
    last: usize,
    each: Length,
    from: usize,
    dot: Length,
}

impl Narrowing {
    /// How a line that runs `over` past its width narrows, on a device whose dot is `dot`:
    /// what its stretched spaces give up in all, which they share as they share a justified
    /// line's free space, and how its pieces narrow beyond that. Where all the pieces from the
    /// line's first stretched one to its last visible one have one advance, the spaces give up
    /// nothing; else each gives up the overrun's share of a space, but no more than
    /// `JUSTIFIED_SPACE_SHRINK` of its width. The rest of the overrun counts in whole dots, to
    /// the nearest: each piece takes the same whole number, and the last pieces one more each.
    /// `None` for a line that does not run past its width.
    pub(in crate::layout) fn of(line: &Line, over: Length, dot: Length) -> Option<(Length, Self)> {
        let first = line.first_stretched();
        let last = line.last_visible().filter(|&last| last >= first)?;
        let pieces = line.placed.get(first..=last)?;
        if over <= Length::ZERO || dot <= Length::ZERO {
            return None;
        }
        let count = i64::try_from(pieces.len()).ok()?;
        let advance = pieces.first()?.advance;
        let spaces: Vec<Length> = pieces
            .iter()
            .filter(|p| stretches(&p.piece))
            .map(|p| p.advance)
            .collect();
        let taken = match i64::try_from(spaces.len()).ok()? {
            0 => Length::ZERO,
            _ if pieces.iter().all(|p| p.advance == advance) => Length::ZERO,
            n => {
                let share = over.div_toward_zero(n);
                spaces
                    .iter()
                    .map(|&space| share.min(JUSTIFIED_SHRINK.of(space)))
                    .sum()
            }
        };
        let dots = (over - taken).div_round(dot.units()).units();
        let from = last + 1 - usize::try_from(dots.rem_euclid(count)).ok()?;
        let narrowing = Self {
            first,
            last,
            each: dot * dots.div_euclid(count),
            from,
            dot,
        };
        Some((taken, narrowing))
    }

    /// How much the piece at `index` of `line` narrows beyond what it gives up as a stretched
    /// space, zero or below.
    pub(in crate::layout) fn at(self, index: usize) -> Length {
        if !(self.first..=self.last).contains(&index) {
            return Length::ZERO;
        }
        let extra = if index >= self.from {
            self.dot
        } else {
            Length::ZERO
        };
        -(self.each + extra)
    }
}

/// How much each gap of a justified line that touches a full-width character takes when the
/// line has `spread` room left and no space to stretch: an equal share of the room.
pub(in crate::layout) fn spread_over_gaps(line: &Line, spread: Length) -> Length {
    let has_space = line.placed.iter().any(|p| stretches(&p.piece));
    let gaps: i64 = (0..line.placed.len())
        .map(|index| i64::from(spread_gap(line, index)))
        .sum();
    if spread > Length::ZERO && gaps > 0 && !has_space {
        spread.div_toward_zero(gaps)
    } else {
        Length::ZERO
    }
}

/// How much each inner blank half of a justified line with compressed punctuation shrinks:
/// when the line runs `free` (below zero) past its width, the blank halves between its first
/// and its last visible glyph give up the overrun in equal shares, rounded toward the larger
/// shrink so that the line fits. The blank half of a closing mark at the end of the line keeps
/// its width. `None` when the line does not run past its width or has no inner blank half.
pub(in crate::layout) fn compressed_marks(
    line: &Line,
    free: Length,
    sides: MarkSides,
) -> Option<Length> {
    let halves: i64 = (0..line.placed.len())
        .map(|index| inner_blank_halves_before(line, index, sides))
        .sum();
    // The share of the overrun below zero rounds down, away from zero, in half-EMUs.
    (free < Length::ZERO && halves > 0)
        .then(|| Length::from_units((free.units() - halves + 1) / halves))
}

/// A justified line spreads its free space over its spaces. The free space is negative when the
/// line holds a word that fits only because its spaces shrink, and then even the last line
/// shrinks.
pub(in crate::layout) fn shift(alignment: Alignment, free: Length, last: bool) -> Shift {
    let none = Length::ZERO;
    let (offset, spread) = match alignment {
        Alignment::Start => (none, none),
        Alignment::Center => (free.max(none).div_toward_zero(2), none),
        Alignment::End => (free.max(none), none),
        Alignment::Both | Alignment::ThaiDistribute if last && free >= none => (none, none),
        Alignment::Both | Alignment::ThaiDistribute => (none, free),
    };
    Shift { offset, spread }
}

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

    use super::CountedShares;
    use crate::mode::ShareRounding::{self, RemainderFirst, SumTowardZero};

    #[test]
    fn counts_the_shares_in_parts_of_a_point_as_the_mode_rounds_them() {
        // 100 half-EMUs of free space over 3 stretched spaces: 33 half-EMUs each on the line,
        // and 5.375 parts of 1/4,096 pt each in exact arithmetic, a part being 25,400/4,096
        // half-EMUs. Each excess is the space's parts less its 33 half-EMUs, over 4,096.
        let excesses = |free: i128, per_space: i64, rounding: ShareRounding| {
            let shares = CountedShares {
                free: (free, 1),
                spaces: 3,
                per_space: Length::from_units(per_space),
                rounding,
            };
            (1..=3).map(|k| shares.excess(k)).collect::<Vec<_>>()
        };
        let excess = |parts: i128, per_space: i128| (parts * 25_400 - per_space * 4_096, 4_096);
        // The sums toward zero: 5, 10 and 16 parts.
        assert_eq!(
            excesses(100, 33, SumTowardZero),
            [excess(5, 33), excess(5, 33), excess(6, 33)]
        );
        // Equal shares with the rest to the first spaces: 16 parts in all (16.125 to the
        // nearest), 5 each, and the one part left to the first space.
        assert_eq!(
            excesses(100, 33, RemainderFirst),
            [excess(6, 33), excess(5, 33), excess(5, 33)]
        );
        // A line that shrinks its spaces: -5, -10 and -16 parts toward zero, and -6, -5 and
        // -5 parts with the rest to the first space.
        assert_eq!(
            excesses(-100, -33, SumTowardZero),
            [excess(-5, -33), excess(-5, -33), excess(-6, -33)]
        );
        assert_eq!(
            excesses(-100, -33, RemainderFirst),
            [excess(-6, -33), excess(-5, -33), excess(-5, -33)]
        );
        // 105 half-EMUs are 16.93 parts: 17 to the nearest, so that the first two spaces take
        // the 2 parts left; toward zero, 16 would leave 1. The sums toward zero are 5, 11 and 16.
        assert_eq!(
            excesses(105, 35, RemainderFirst),
            [excess(6, 35), excess(6, 35), excess(5, 35)]
        );
        assert_eq!(
            excesses(105, 35, SumTowardZero),
            [excess(5, 35), excess(6, 35), excess(5, 35)]
        );
        // The free space that the exact advances leave, 99.5 half-EMUs, gives 5.348 parts
        // each, and the sums toward zero 5, 10 and 16 parts as before.
        let shares = CountedShares {
            free: (199, 2),
            spaces: 3,
            per_space: Length::from_units(33),
            rounding: SumTowardZero,
        };
        assert_eq!(shares.excess(3), excess(6, 33));
    }

    #[test]
    fn shrinks_squeezed_last_line_of_right_to_left_justified_paragraph() {
        use crate::props::{Alignment, ParaProps};
        let props = ParaProps {
            alignment: Some(Alignment::Both),
            bidi: Some(true),
            ..ParaProps::default()
        };
        let free = Length::from_units(-100);
        // A normal short RTL justified last line aligns at the right edge without spread.
        let loose_alignment = super::line_alignment(&props, true);
        assert_eq!(loose_alignment, Alignment::End);
        assert_eq!(
            super::shift(loose_alignment, Length::from_units(100), true).spread,
            Length::ZERO
        );
        // A squeezed RTL justified last line (free < 0) keeps Alignment::Both and shrinks.
        let squeezed_alignment = super::line_alignment(&props, false);
        assert_eq!(squeezed_alignment, Alignment::Both);
        assert_eq!(super::shift(squeezed_alignment, free, true).spread, free);
    }
}