f-office-docx 0.1.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
//! The look of a run's glyphs from its properties: size, rise, scale, spacing and colors.

use f_office_paint::{Join, Outline, Rgb};
use f_office_units::Length;
use f_office_units::scale::PERCENT;

use super::{Glyph, OPERATOR_BREAK_SPACE, ShaperSettings, SpaceKind};
use crate::FaceMetrics;
use crate::character_class::CharacterClass;
use crate::grid::{Dot, Rounding};
use crate::props::{
    Color, MathScript, MathStep, MathStyle, OutlineColor, RunProps, TextOutline, VerticalAlign,
};
use crate::styles::FullWidthSpacing;

/// How a superscript or subscript moves: the variant of the quirk `ScriptPlacement`
/// (`src/quirks.rs`) that the target's profile names, with what it needs.
#[derive(Clone, Copy)]
pub(super) enum ScriptMove<'a> {
    /// By the size that it loses, a superscript no higher than the cap, if any
    /// (`ScriptPlacement::LostSize`).
    LostSize(Option<Length>),
    /// To the edges of its line (`ScriptPlacement::AlignsLineEdges`).
    LineEdges(Edges<'a>),
}

/// How large a superscript or subscript is: the variant of the quirk `ScriptSize`
/// (`src/quirks.rs`), with the share of the run's size that the font gives.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ScriptScale {
    /// Two thirds of the run's size, rounded down to whole half-points
    /// (`ScriptSize::TwoThirds`).
    TwoThirds,
    /// [`crate::params::SCRIPT_FALLBACK_SIZE`] of the run's size, to the nearest half-point:
    /// the font's own script values are not used (`ScriptSize::FaceValues`).
    Fallback,
    /// The font's own share, `part` over `whole` of the run's size to the nearest half-point,
    /// unless that comes to at most [`crate::params::SCRIPT_FALLBACK_LINE_SHARE`] of the run's
    /// size; then [`Self::Fallback`] (`ScriptSize::FaceValues`).
    OwnShare { part: i64, whole: i64 },
}

impl ScriptScale {
    /// The share of `ScriptSize::FaceValues` for a run of the vertical alignment `vertical` in
    /// a font of the metrics `metrics`: the font's own `OS/2` y size of that kind of script over
    /// its units per em, or [`crate::params::SCRIPT_FALLBACK_SIZE`] when the font's superscript
    /// size or offset lies outside the values that kept their sizes, or when the size of the
    /// kind of script is not positive.
    pub(super) fn of_face(metrics: &FaceMetrics, vertical: Option<VerticalAlign>) -> Self {
        let em = i64::from(metrics.units_per_em.max(1));
        let size = i64::from(metrics.superscript_size);
        let offset = i64::from(metrics.superscript_offset);
        // `value` font units against the share `part` over `whole` of the em.
        let at_most = |value: i64, (part, whole): (i64, i64)| value * whole <= part * em;
        let own = match vertical {
            Some(VerticalAlign::Subscript) => i64::from(metrics.subscript_size),
            Some(VerticalAlign::Superscript | VerticalAlign::Baseline) | None => size,
        };
        let kept = at_most(size, crate::params::SCRIPT_KEPT_SIZE_MAX)
            && offset > 0
            && at_most(offset, crate::params::SCRIPT_KEPT_OFFSET_MAX)
            && own > 0;
        if kept {
            Self::OwnShare {
                part: own,
                whole: em,
            }
        } else {
            Self::Fallback
        }
    }

    /// Whether a script of a run of the size `full` takes [`Self::Fallback`]'s size rather than
    /// a share that its font gives: always under [`Self::Fallback`], and under
    /// [`Self::OwnShare`] on a line where the font's share comes to at most
    /// [`crate::params::SCRIPT_FALLBACK_LINE_SHARE`] of the run's size.
    pub(super) fn falls_back(self, full: Length) -> bool {
        match self {
            Self::TwoThirds => false,
            Self::Fallback => true,
            Self::OwnShare { part, whole } => {
                let (most, of) = crate::params::SCRIPT_FALLBACK_LINE_SHARE;
                nearest_half_points(full, part, whole) * of <= full * most
            }
        }
    }

    /// The size of a script of a run of the size `full`.
    fn size(self, full: Length) -> Length {
        match self {
            Self::TwoThirds => {
                let (part, whole) = crate::params::SCRIPT_SIZE;
                whole_half_points((full * part).div_toward_zero(whole))
            }
            Self::Fallback => {
                let (part, whole) = crate::params::SCRIPT_FALLBACK_SIZE;
                nearest_half_points(full, part, whole)
            }
            Self::OwnShare { .. } if self.falls_back(full) => Self::Fallback.size(full),
            Self::OwnShare { part, whole } => nearest_half_points(full, part, whole),
        }
    }
}

/// What a script that moves to the edges of its line needs: the font's metrics, one dot of
/// the layout device, and the heights that the font's `VDMX` table gives by pixels per em
/// (`Fonts::device_heights`).
#[derive(Clone, Copy)]
pub(super) struct Edges<'a> {
    pub(super) metrics: &'a FaceMetrics,
    pub(super) dot: Dot,
    pub(super) heights: &'a dyn Fn(u16) -> Option<(i16, i16)>,
    /// The room that the line of a font made for East Asian text gets below its text, in font
    /// units; 0 for another font. It belongs to the bottom of the font.
    pub(super) room: i64,
}

impl Edges<'_> {
    /// The top of the font at the font size `size` with `gap` font units above it, rounded
    /// as [`half_points`] says. The top is the `VDMX` height at the size's pixels per em on
    /// the layout device when the font gives one, else the font's `script_top`.
    fn top(&self, size: Length, gap: i64) -> Length {
        let dots = self.pixels(size).map_or_else(
            || self.dots(i64::from(self.metrics.script_top) + gap, size),
            |(y_max, _)| i64::from(y_max) + self.dots(gap, size),
        );
        half_points(dots, self.dot)
    }

    /// The bottom of the font at the font size `size`, rounded as [`half_points`] says: the
    /// `VDMX` depth at the size's pixels per em when the font gives one, else its `descent`,
    /// and below it the room of a font made for East Asian text, in whole dots.
    fn bottom(&self, size: Length) -> Length {
        let dots = self.pixels(size).map_or_else(
            || self.dots(i64::from(self.metrics.descent) + self.room, size),
            |(_, y_min)| -i64::from(y_min) + self.dots(self.room, size),
        );
        half_points(dots, self.dot)
    }

    /// `font_units` at the font size `size`, in whole dots, halves up.
    fn dots(&self, font_units: i64, size: Length) -> i64 {
        let em = i64::from(self.metrics.units_per_em.max(1));
        let units = i128::from(font_units) * i128::from(size.units());
        self.dot.count_exact(units, i128::from(em)).unwrap_or(0)
    }

    /// The font's `VDMX` heights at the pixels per em of the font size `size`, one pixel to a
    /// dot of the layout device.
    fn pixels(&self, size: Length) -> Option<(i16, i16)> {
        let pels = u16::try_from(self.dot.count(size, Rounding::HalfUp)).ok()?;
        (self.heights)(pels)
    }
}

/// The size of the glyphs and the rise of their baseline, a script's size as `scale` gives it.
pub(super) fn size_and_rise(
    props: &RunProps,
    how: ScriptMove<'_>,
    scale: ScriptScale,
) -> (Length, Length) {
    let full = full_size(props);
    let small = scale.size(full);
    // A superscript rises by the size that it loses, but no higher than its font raises
    // superscripts, and a subscript drops by a quarter of that size.
    let lost = full - small;
    let rise = match (props.vertical, how) {
        (Some(VerticalAlign::Superscript), ScriptMove::LostSize(cap)) => {
            cap.map_or(lost, |cap| lost.min(cap))
        }
        (Some(VerticalAlign::Subscript), ScriptMove::LostSize(_)) => {
            -lost.div_round(crate::params::SUBSCRIPT_DROP_PARTS)
        }
        // A superscript in a font whose own script values are not used meets the top of its
        // line with no cap by the font's offset, the top of the font no higher than its em; the
        // top of a font made for East Asian text is its em, so its superscript rises by the size
        // that it loses.
        (Some(VerticalAlign::Superscript), ScriptMove::LineEdges(edges))
            if scale.falls_back(full) =>
        {
            if edges.metrics.east_asian {
                lost
            } else {
                let m = edges.metrics;
                let gap = i64::from(m.line_top) - i64::from(m.script_top);
                edges.top(full, gap).min(full) - edges.top(small, 0).min(small)
            }
        }
        // quirk: ScriptPlacement::AlignsLineEdges (src/quirks.rs)
        (Some(VerticalAlign::Superscript), ScriptMove::LineEdges(edges)) => {
            let m = edges.metrics;
            let gap = i64::from(m.line_top) - i64::from(m.script_top);
            let rise = edges.top(full, gap) - edges.top(small, 0);
            capped(rise, m.superscript_offset, m, full)
        }
        (Some(VerticalAlign::Subscript), ScriptMove::LineEdges(edges)) => {
            -edge_drop(edges, scale, full, small)
        }
        (Some(VerticalAlign::Baseline) | None, _) => Length::ZERO,
    };
    let size = match props.vertical {
        Some(VerticalAlign::Superscript | VerticalAlign::Subscript) => small,
        Some(VerticalAlign::Baseline) | None => full,
    };
    // Raised or lowered text (`w:position`) moves by its own distance as well.
    (size, rise + props.position.unwrap_or(Length::ZERO))
}

/// How far a subscript of the size `small` on a line of the size `full` drops to meet the bottom
/// of its line, from the bottoms of its font. Where the font's values size scripts, a subscript
/// in a font whose own script values are not used has no cap by the font's offset, but drops no
/// farther than a share of the run's size, to the nearest half-point; a font whose own values
/// size its subscript and whose subscript offset is 0 does not lower it, and the bottom of a
/// font made for East Asian text lies below its descent by the room that its line gets there.
fn edge_drop(edges: Edges<'_>, scale: ScriptScale, full: Length, small: Length) -> Length {
    let m = edges.metrics;
    let edges = match scale {
        ScriptScale::TwoThirds => Edges { room: 0, ..edges },
        ScriptScale::Fallback | ScriptScale::OwnShare { .. } => edges,
    };
    let drop = edges.bottom(full) - edges.bottom(small);
    if scale.falls_back(full) {
        let (part, whole) = crate::params::SCRIPT_FALLBACK_DROP_MAX;
        drop.min(nearest_half_points(full, part, whole))
    } else if matches!(scale, ScriptScale::OwnShare { .. }) && m.subscript_offset <= 0 {
        Length::ZERO
    } else {
        capped(drop, m.subscript_offset, m, full)
    }
}

/// `part` over `whole` of `length`, to the nearest half-point, halves up.
fn nearest_half_points(length: Length, part: i64, whole: i64) -> Length {
    let half_point = Length::UNITS_PER_HALF_POINT;
    (length * part).div_round(whole * half_point) * half_point
}

/// `length` cut toward zero to whole half-points, down for a font size.
fn whole_half_points(length: Length) -> Length {
    let half_point = Length::UNITS_PER_HALF_POINT;
    length.div_toward_zero(half_point) * half_point
}

impl MathStyle {
    /// The size of a part in this style, for an equation of the size `full`: a script takes
    /// [`crate::params::MATH_SCRIPT_PERCENT`] of it and a script inside a script
    /// [`crate::params::MATH_SCRIPT_SCRIPT_PERCENT`], each rounded down to whole half-points.
    fn size(self, full: Length) -> Length {
        let percent = match self {
            Self::Display | Self::Text => return full,
            Self::Script => crate::params::MATH_SCRIPT_PERCENT,
            Self::ScriptScript => crate::params::MATH_SCRIPT_SCRIPT_PERCENT,
        };
        whole_half_points((full * percent).div_toward_zero(PERCENT))
    }
}

/// The size and rise of a run of an equation in the parts `script`, with the layout device's dot
/// `dot`, and whether the run lies in a part of a fraction. Each part has the size of its style.
/// Each superscript and numerator rises, and each subscript and denominator drops, by its shift at
/// the size of its base, which is the part one step out; a fraction's parts shift further in a
/// display. A limit over or under an n-ary operator moves by the shift that `limit` gives for it at
/// the size of its base, from the operator's glyph and the math font, or else as a superscript or a
/// subscript. The size of a step's base comes from the size of its structure's control properties
/// when they give one, and else from the run's own size. A superscript in a fraction's denominator,
/// at any depth, rises by the cramped shift, unless it stands beside a subscript, and so does a
/// superscript in the element of a radical. A delimiter of
/// `m:d` and an n-ary operator inside a line move further by the shift that `axis` gives for its character at its size, which puts the
/// middle of its glyph's ink on the math axis. The sum rounds to the nearest dot. Raised text
/// (`w:position`) moves by its own distance as well. The limits over and under an operator take
/// their line raised and lowered, as the parts of a fraction do, so the flag that the function
/// returns holds for them too.
pub(super) fn math_size_and_rise(
    props: &RunProps,
    script: MathScript,
    dot: Dot,
    limit: &dyn Fn(MathStep, Length) -> Option<Length>,
    axis: &dyn Fn(char, Length) -> Option<Length>,
) -> (Length, Length, bool) {
    let full = full_size(props);
    let mut style = if script.is_display() {
        MathStyle::Display
    } else {
        MathStyle::Text
    };
    let mut rise = Length::ZERO;
    let mut in_fraction = false;
    // A fraction's denominator, and every part inside it, is cramped, and so is the element
    // of a radical.
    let mut cramped = script.is_cramped();
    for (step, control_size) in script.steps_with_control_sizes() {
        in_fraction |= matches!(
            step,
            MathStep::Numerator
                | MathStep::Denominator
                | MathStep::UpperLimit(_)
                | MathStep::LowerLimit(_)
        );
        // A structure shifts its parts by the size of its control properties, whatever the
        // size of the parts' runs.
        let structure = control_size
            .filter(|half_points| *half_points > 0)
            .and_then(Length::from_half_points)
            .unwrap_or(full);
        let base = style.size(structure);
        let display = style == MathStyle::Display;
        let ((units, em), sign) = match step {
            MathStep::Superscript if cramped => {
                (crate::params::MATH_SUPERSCRIPT_SHIFT_UP_CRAMPED, 1)
            }
            MathStep::Superscript
            | MathStep::SuperscriptBesideSubscript
            | MathStep::UpperLimit(_) => (crate::params::MATH_SUPERSCRIPT_SHIFT_UP, 1),
            MathStep::Subscript | MathStep::LowerLimit(_) => {
                (crate::params::MATH_SUBSCRIPT_SHIFT_DOWN, -1)
            }
            MathStep::Numerator if display => (crate::params::MATH_NUMERATOR_DISPLAY_SHIFT_UP, 1),
            MathStep::Numerator => (crate::params::MATH_NUMERATOR_SHIFT_UP, 1),
            MathStep::Denominator if display => {
                (crate::params::MATH_DENOMINATOR_DISPLAY_SHIFT_DOWN, -1)
            }
            MathStep::Denominator => (crate::params::MATH_DENOMINATOR_SHIFT_DOWN, -1),
            // The layout raises a radical's degree once its root sign is chosen.
            MathStep::Degree => ((0, 1), 1),
        };
        rise += limit(step, base).unwrap_or_else(|| (base * units).div_round(em) * sign);
        cramped |= step == MathStep::Denominator;
        style = style.inside(step);
    }
    let size = style.size(full);
    // A delimiter of `m:d` and an n-ary operator inside a line stand with the middle of their
    // glyph's ink on the math axis.
    rise += script
        .axis_character()
        .and_then(|ch| axis(ch, size))
        .unwrap_or(Length::ZERO);
    let position = props.position.unwrap_or(Length::ZERO);
    (size, dot.snap(rise) + position, in_fraction)
}

/// A height of `dots` whole dots of `dot`, rounded to the nearest half-point, halves up. With
/// the rounding to whole dots before it, a height rounds twice.
fn half_points(dots: i64, dot: Dot) -> Length {
    let half_point = Length::UNITS_PER_HALF_POINT;
    dot.dots(dots).div_round(half_point) * half_point
}

/// `distance`, but no more than the font's `offset` at the full size `full`, to the nearest
/// half-point, when the font gives an offset.
fn capped(distance: Length, offset: i16, metrics: &FaceMetrics, full: Length) -> Length {
    let em = i64::from(metrics.units_per_em.max(1));
    let half_point = Length::UNITS_PER_HALF_POINT;
    if offset > 0 {
        let cap = (full * i64::from(offset)).div_round(em * half_point) * half_point;
        distance.min(cap)
    } else {
        distance
    }
}

/// How high the font of a run raises a superscript at the run's full size (`OS/2`
/// `ySuperscriptYOffset`), or `None` when the font does not say.
pub(super) fn superscript_cap(props: &RunProps, metrics: &FaceMetrics) -> Option<Length> {
    let offset = i64::from(metrics.superscript_offset);
    let em = i64::from(metrics.units_per_em);
    // quirk: SuperscriptRise::RoundsToNearest (src/quirks.rs)
    (offset > 0 && em > 0).then(|| (full_size(props) * offset).div_round(em))
}

/// Makes the characters of a run wider or narrower by a percentage of their width (`w:w`).
/// Character spacing comes after it and keeps its size.
pub(super) fn scale(glyphs: &mut [Glyph], percent: Option<i64>) {
    let Some(percent) = percent.filter(|p| *p != PERCENT) else {
        return;
    };
    for glyph in glyphs {
        glyph.advance = (glyph.advance * percent).div_toward_zero(PERCENT);
    }
}

/// Adds a run's character spacing to the advance of each of its glyphs, and, where the shaper's
/// `settings` keep it apart from the glyph's own width
/// ([`ShaperSettings::spacing_on_its_own`]), to the spacing that the glyph carries for the
/// device's steps. A later part of a ligature takes none: the ligature's glyph takes the
/// spacing once for all its characters. With [`FullWidthSpacing::Twice`], the document's
/// setting, the spacing goes to each half cell, so a full-width character, which fills two,
/// takes it twice.
pub(super) fn spread(glyphs: &mut [Glyph], spacing: Option<Length>, settings: &ShaperSettings) {
    let Some(spacing) = spacing.filter(|s| *s != Length::ZERO) else {
        return;
    };
    for glyph in glyphs.iter_mut().filter(|g| !g.part) {
        let twice = settings.full_width_spacing == FullWidthSpacing::Twice;
        let cells = if twice && CharacterClass::FullWidthCell.contains(glyph.ch) {
            2
        } else {
            1
        };
        glyph.advance += spacing * cells;
        if let Some(own) = settings.spacing_on_its_own(spacing * cells) {
            glyph.spacing += own;
        }
    }
}

/// Makes each space typed in an equation's math run an equation space
/// ([`SpaceKind::Equation`]), with its own glyph and width, and each operator break space a
/// no-break space where the line may break ([`SpaceKind::Operator`]), together with the hair
/// space of a relation's space just before it.
pub(super) fn hold_math_spaces(glyphs: &mut [Glyph]) {
    let mut before: Option<&mut Glyph> = None;
    for glyph in glyphs.iter_mut() {
        match glyph.ch {
            ' ' => glyph.space = SpaceKind::Equation,
            OPERATOR_BREAK_SPACE => {
                glyph.ch = '\u{00A0}';
                glyph.space = SpaceKind::Operator;
                if let Some(before) = before
                    && before.ch == crate::math::HAIR_SPACE
                {
                    before.space = SpaceKind::Operator;
                }
            }
            _ => {}
        }
        before = Some(glyph);
    }
}

/// Whether a run is kerned: `w:kern` names the smallest kerned size in half-points, and 0
/// turns kerning off.
pub(super) fn kerned(props: &RunProps) -> bool {
    let size = props.drawn_half_points();
    props
        .kern
        .is_some_and(|threshold| threshold > 0 && size >= threshold)
}

/// Whether a run in a part of a fraction (`in_fraction`) lies in an inline equation, so that
/// its room below the line follows the ink of its glyphs in a font without a `MATH` table. The
/// parts of a fraction of a display take their room from their font's lines, unless the target's
/// quirk variant `DisplayFractionRoom::Ink` gives them the room of their ink in a math font.
pub(super) fn math_ink_below(props: &RunProps, in_fraction: bool) -> bool {
    in_fraction && !props.math_script.is_some_and(MathScript::is_display)
}

/// The run's font size before any superscript or subscript reduction. The reader bounds a
/// run's size by [`crate::params::MAX_FONT_SIZE`], so the size is always a length.
pub(super) fn full_size(props: &RunProps) -> Length {
    Length::from_half_points(props.drawn_half_points()).unwrap_or(Length::ZERO)
}

/// The color of a run's text: automatic, or none, is black.
pub(super) fn color(props: &RunProps) -> Rgb {
    props.color.map_or(Rgb::BLACK, Color::drawn)
}

/// The fill behind a run: its highlight, which covers its shading, or else its shading. A
/// white fill is drawn too: it covers the fill of the paragraph or the cell under the run.
pub(super) fn background(props: &RunProps) -> Option<Rgb> {
    props
        .highlight
        .and_then(Color::rgb)
        .or_else(|| props.shading.and_then(Color::rgb))
}

/// The line along the glyph outlines of a run. Word draws an outline with a theme
/// color in yellow, whatever the theme color is.
pub(super) fn outline(props: &RunProps) -> Option<Outline> {
    const SCHEME_YELLOW: Rgb = {
        let [r, g, b] = crate::params::OUTLINE_THEME_COLOR;
        Rgb { r, g, b }
    };
    match props.outline? {
        TextOutline::None => None,
        TextOutline::Solid { width, color } => Some(Outline {
            width,
            color: match color {
                OutlineColor::Rgb([r, g, b]) => Rgb { r, g, b },
                OutlineColor::Scheme => SCHEME_YELLOW,
            },
            join: Join::Round,
        }),
    }
}