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
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Faces at their sizes, and the glyphs measured with them.

use f_office_fonts::FontId;
use f_office_paint::{Opacity, Outline, Rgb};
use f_office_units::Length;

use super::SingleLine;
use crate::FaceMetrics;
use crate::props::{BidiLanguageClass, EastAsianScript, Strike, Underline};
use f_office_units::div_round;

/// One font face at one size with the run settings that painting needs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Face {
    /// The font in the database.
    pub font: FontId,
    /// Its metrics.
    pub metrics: FaceMetrics,
    /// The nominal font size.
    pub size: Length,
    /// The font size that the line height uses. For a superscript or subscript, it is the
    /// full size before the reduction.
    pub line_size: Length,
    /// The target's rule for the single line of the font ([`SingleLine`]).
    pub single_line: SingleLine,
    /// The text color.
    pub color: Rgb,
    /// The lines that painting adds to the run.
    pub lines: RunLines,
    /// The fill behind the run's text: its highlight, or else its shading.
    pub background: Option<Rgb>,
    /// How far the baseline of a superscript, or of raised text, moves up (positive) or down
    /// (negative).
    pub rise: Length,
    /// The part of `rise` that comes from raised or lowered text (`w:position`), which moves
    /// the run's ascent and descent in its line too.
    pub raised: Length,
    /// Where the run lies in an equation, for its line and its drawing.
    pub math: MathFace,
    /// The line along the outline of each glyph, if any.
    pub outline: Option<Outline>,
    /// How each glyph's interior is filled (`w14:textFill`).
    pub text_fill: DrawnTextFill,
    /// Whether the run has an effect that F-Office does not draw, such as a reflection.
    pub effect: bool,
    /// The room that the shadow of the run's text takes in its line.
    pub shadow_room: ShadowRoom,
    /// The shadow of the run's text that the target draws as the filled paths of its glyphs,
    /// if any.
    pub shadow: Option<DrawnShadow>,
    /// The glow around the run's text (`w14:glow`) that the target draws as an effect picture
    /// under the text, if any.
    pub glow: Option<DrawnGlow>,
    /// The reflection under the run's text (`w14:reflection`) that the target draws as an effect
    /// picture under the text, if any.
    pub reflection: Option<DrawnReflection>,
    /// Legacy WordprocessingML embossed or imprinted text relief (`w:emboss` or `w:imprint`).
    pub relief: Option<TextRelief>,
    /// Whether the run's pairs of glyphs are kerned.
    pub kerned: bool,
    /// The East Asian script of the run's language (`w:lang w:eastAsia`, or the document's
    /// `w:themeFontLang`), used for East Asian punctuation kerning (`lines::kerned_pair`).
    pub east_asian_script: Option<EastAsianScript>,
    /// Whether the run turns standard ligatures on in a document of a mode that joins them.
    pub ligatures: bool,
    /// The run's character scale in percent (`w:w`), if any, with which some targets draw its
    /// glyphs ([`crate::grid::Device::glyph_turn`]).
    pub scale: Option<i64>,
    /// How the face stands in for the one that the run asks for.
    pub standing: Standing,
}

/// How a run's glyph interiors are filled (`w14:textFill`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum DrawnTextFill {
    /// Normal opaque solid fill in [`Face::color`].
    #[default]
    Solid,
    /// No interior fill (`w14:noFill` or hollow `w:outline`): hollow when outlined, hidden when not.
    None,
    /// Opaque white interior fill (`#FFFFFF`) masking a shadow behind `w:outline` + `w:shadow`.
    White,
    /// Translucent solid fill in [`Face::color`] at this opacity (`0 < opacity < FULL`).
    Translucent(Opacity),
    /// Linear gradient fill interned in [`super::Shaper::text_gradient`].
    Gradient(usize),
}

/// The room that the shadow of a run's text takes in its line, past the face's own ascent and
/// descent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct ShadowRoom {
    /// The room above the ascent.
    pub above: Length,
    /// The room below the descent.
    pub below: Length,
}

impl ShadowRoom {
    /// Whether the room is none.
    #[must_use]
    pub fn is_none(self) -> bool {
        self == Self::default()
    }
}

/// How the target draws a run's text shadow: as one filled path of its glyphs' outlines, or as an
/// effect picture of its glyphs' outlines (with an optional blur, opacity and outline stroke).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ShadowForm {
    /// One filled path of the glyphs' outlines (sharp, opaque, no outline).
    Paths,
    /// One effect picture of the glyphs' outlines, blurred by `blur`, at `opacity`, and stroked
    /// by `outline_width` (zero when the run has no outline).
    Picture {
        /// The scaled blur radius, zero for a sharp shadow.
        blur: Length,
        /// The opacity of the shadow (`100% - w14:alpha`).
        opacity: f_office_paint::Opacity,
        /// The width of the line along the glyphs' outlines (`w14:textOutline`), zero when none.
        outline_width: Length,
    },
}

/// The shadow of a run's text that the target draws before the text: how far it lies right of and
/// below the glyphs, its color and its form.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DrawnShadow {
    /// How far right of the glyphs it lies, below 0 when it lies left of them.
    pub across: Length,
    /// How far below the glyphs it lies, below 0 when it lies above them.
    pub down: Length,
    /// Its color.
    pub color: Rgb,
    /// Whether the target draws it as filled paths or as an effect picture.
    pub form: ShadowForm,
}

/// Legacy WordprocessingML embossed or imprinted relief (`w:emboss`, `w:imprint`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TextRelief {
    /// Raised relief (`w:emboss`): `#999999` at `(0, 0)`, `#000000` at `(-2d, -2d)`, main at `(-d, -d)`.
    Emboss,
    /// Engraved relief (`w:imprint`): `#000000` at `(+2d, +2d)`, `#999999` at `(0, 0)`, main at `(+d, +d)`.
    Imprint,
}

/// The glow around a run's text (`w14:glow`) that the target draws as an effect picture under
/// the text: its scaled radius, color, and opacity.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DrawnGlow {
    /// The scaled glow radius.
    pub radius: Length,
    /// Its color.
    pub color: Rgb,
    /// Its opacity (`100% - w14:alpha`).
    pub opacity: Opacity,
}

/// The reflection under a run's text (`w14:reflection`) drawn as an effect picture under the text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DrawnReflection {
    /// Mirror pivot below the run's baseline (`dist * descent / REFLECTION_DIST_SCALE`).
    pub pivot: Length,
    /// Scaled blur radius (`blurRad * line_size / TEXT_SHADOW_SIZE`).
    pub blur: Length,
    /// Start of the opacity fade below the run's baseline.
    pub fade_start: Length,
    /// End of the opacity fade below the run's baseline.
    pub fade_end: Length,
    /// Starting opacity at `fade_start`.
    pub start_opacity: Opacity,
    /// Ending opacity at `fade_end`.
    pub end_opacity: Opacity,
    /// Width of the run's outline stroke (`w14:textOutline`), zero when none.
    pub outline_width: Length,
}

/// Where a run lies in an equation, as far as its line and its drawing need.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct MathFace {
    /// Whether the run lies in a part of a stacked fraction, or in a limit over or under an
    /// n-ary operator. Such a run takes its line at its own size, and the room that it needs
    /// above the line's text comes on top of the line, unscaled by multiple spacing.
    pub in_fraction: bool,
    /// Whether the run is an n-ary operator that a display draws with the larger variant of
    /// its glyph from the math font's `MATH` table.
    pub large: bool,
    /// The level of the run's script glyphs, a script or a script of a script; none where the
    /// run keeps its base glyphs.
    pub script_level: Option<f_office_fonts::ScriptLevel>,
    /// How the line gives the run its room.
    pub room: MathRoom,
    /// Whether the run is the text of a phantom that is not shown, which takes its room in the
    /// line and draws nothing.
    pub phantom: bool,
}

/// How a line gives a run of an equation its room.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MathRoom {
    /// The room of its font's lines.
    #[default]
    Lines,
    /// For a part of a fraction of an inline equation in a font without a `MATH` table, room
    /// below the line as far as the ink of its glyphs, and not as far as its font's descent.
    InkBelow,
    /// For a display's n-ary operator drawn with the larger variant of its glyph, for a run
    /// in a limit over or under it, for a part of a fraction of an inline equation, and on a
    /// target whose quirk variant is `DisplayFractionRoom::Ink` for a part of a fraction of a
    /// display, the room of its ink, with the math font's `MathLeading` (`leading`, at the size
    /// of the equation) above it, and not the room of its font's lines. Only for a font with a
    /// `MATH` table.
    Ink {
        /// The space above the ink.
        leading: Length,
    },
    /// On a target whose quirk variant is `ScriptRoom::Ink`, for a superscript or a subscript of
    /// an inline equation outside a fraction: the room of its font's lines on the line's
    /// baseline, as `Lines` gives, and also the room of its ink as drawn, raised or lowered with
    /// the script (`Face::rise`), with the math font's `MathLeading` (`leading`, at the size of
    /// the equation) above it. Only for a font with a `MATH` table.
    LinesAndInk {
        /// The space above the ink.
        leading: Length,
    },
}

/// How a face stands in for the face that a run asks for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Standing {
    /// Whether the face stands in for a bold face that its family does not have.
    pub synthetic_bold: bool,
    /// Whether the face is an upright face that stands in for an italic face: its family has
    /// no italic face, or the target draws the run's characters in the upright face of an
    /// italic run.
    pub synthetic_italic: bool,
    /// Whether the face stands in for the font that the run names, which the fonts of the
    /// layout do not hold under that name.
    pub font: bool,
}

/// The lines that painting adds to a run.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct RunLines {
    /// The kind of line under the text, in the form that the target draws.
    pub under: Underline,
    /// The line through the text, in the form that the target draws.
    pub through: Strike,
    /// A bar in the margin beside each of the run's lines, which marks a tracked change.
    pub change_bar: bool,
}

impl Face {
    /// Scales a value in font units to the nominal size.
    #[must_use]
    pub fn scale(&self, font_units: i64) -> Length {
        self.scale_to(font_units, self.size)
    }

    fn scale_to(&self, font_units: i64, size: Length) -> Length {
        let em = i64::from(self.metrics.units_per_em.max(1));
        Length::from_units(div_round(font_units * size.units(), em))
    }

    /// The single line height: the font's own line ([`Self::own_line`]), at the line size.
    #[must_use]
    pub fn line_height(&self) -> Length {
        self.scale_to(
            self.own_line() + 2 * self.east_asian_extra(),
            self.line_size,
        )
    }

    /// The part of the line below the baseline: the face's descent, at the line size.
    #[must_use]
    pub fn descent(&self) -> Length {
        let descent = i64::from(self.metrics.descent) + self.east_asian_extra();
        self.scale_to(descent, self.line_size)
    }

    /// The font's single line in font units, by the target's rule ([`SingleLine::of_metrics`]).
    fn own_line(&self) -> i64 {
        self.single_line.of_metrics(&self.metrics)
    }

    /// The room that the line of a font made for East Asian text gets above and below its
    /// text: 0.15 of its own line each, in font units.
    fn east_asian_extra(&self) -> i64 {
        self.single_line.east_asian_room(&self.metrics)
    }

    /// The face's win line at its size: the top of the font without a line gap
    /// ([`FaceMetrics::script_top`](crate::FaceMetrics::script_top)) and its descent, which
    /// is `usWinAscent` plus `usWinDescent` for a font that does not set `USE_TYPO_METRICS`.
    #[must_use]
    pub fn win_line(&self) -> Length {
        self.scale(i64::from(self.metrics.script_top) + i64::from(self.metrics.descent))
    }

    /// The top of the face without a line gap at its size
    /// ([`FaceMetrics::script_top`](crate::FaceMetrics::script_top)), `usWinAscent` for a
    /// font that does not set `USE_TYPO_METRICS`.
    #[must_use]
    pub fn win_top(&self) -> Length {
        self.scale(i64::from(self.metrics.script_top))
    }

    /// The face's ascent and descent at the line size, as [`Self::ascent`] and
    /// [`Self::descent`] give them, in whole parts of `params::HEIGHT_PARTS_PER_POINT` of a point
    /// instead of half-EMUs, for a face of `params::WHOLE_HEIGHT_UNITS_PER_EM` units per em
    /// whose run is neither raised nor lowered and whose shadow takes no room; `None` for
    /// another face, or where the parts are not whole, which a size in half points never gives.
    #[must_use]
    pub fn whole_line(&self) -> Option<(i64, i64)> {
        if self.metrics.units_per_em != crate::params::WHOLE_HEIGHT_UNITS_PER_EM
            || self.raised != Length::ZERO
            || !self.shadow_room.is_none()
        {
            return None;
        }
        let per_part = i64::from(self.metrics.units_per_em) * Length::UNITS_PER_POINT;
        let parts = |font_units: i64| {
            let scaled =
                font_units * self.line_size.units() * crate::params::HEIGHT_PARTS_PER_POINT;
            (scaled % per_part == 0).then_some(scaled / per_part)
        };
        let line = parts(self.own_line() + 2 * self.east_asian_extra())?;
        let descent = parts(i64::from(self.metrics.descent) + self.east_asian_extra())?;
        Some((line - descent, descent))
    }

    /// The part of the line above the baseline.
    #[must_use]
    pub fn ascent(&self) -> Length {
        self.line_height() - self.descent()
    }

    /// The part of the line above the baseline that the run needs, raised or lowered with
    /// its text, with the room of its shadow.
    #[must_use]
    pub fn raised_ascent(&self) -> Length {
        self.shifted_ascent() + self.shadow_room.above
    }

    /// The part of the line below the baseline that the run needs, raised or lowered with
    /// its text, with the room of its shadow.
    #[must_use]
    pub fn raised_descent(&self) -> Length {
        self.shifted_descent() + self.shadow_room.below
    }

    /// The part of the line above the baseline that the run needs, raised or lowered with
    /// its text, without the room of its shadow.
    #[must_use]
    pub fn shifted_ascent(&self) -> Length {
        self.ascent() + self.raised
    }

    /// The part of the line below the baseline that the run needs, raised or lowered with
    /// its text, without the room of its shadow.
    #[must_use]
    pub fn shifted_descent(&self) -> Length {
        self.descent() - self.raised
    }
}

/// The inherited direction of a run, separate from complex script formatting.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RunDirection {
    /// No RTL characteristics apply.
    #[default]
    LeftToRight,
    /// The run has RTL characteristics, with the class of its bidi language.
    RightToLeft(BidiLanguageClass),
}

impl RunDirection {
    /// The direction of a run that has `w:rtl` when `rtl`, with the class of its bidi
    /// language; a run without a bidi language has the first class.
    #[must_use]
    pub fn of(rtl: bool, class: Option<BidiLanguageClass>) -> Self {
        if rtl {
            Self::RightToLeft(class.unwrap_or_default())
        } else {
            Self::LeftToRight
        }
    }

    /// This direction with the class `class` of the bidi language, for a run with `w:rtl`.
    #[must_use]
    pub fn with_class(self, class: Option<BidiLanguageClass>) -> Self {
        match self {
            Self::LeftToRight => self,
            Self::RightToLeft(_) => Self::RightToLeft(class.unwrap_or_default()),
        }
    }

    /// The class of the bidi language of a run with `w:rtl`; none for another run.
    #[must_use]
    pub fn class(self) -> Option<BidiLanguageClass> {
        match self {
            Self::LeftToRight => None,
            Self::RightToLeft(class) => Some(class),
        }
    }
}

/// The side of the border between a run's East Asian font and its other fonts that a character
/// lies on (its font side). The PDF writer of a target with
/// `FontSideChange::StartsObject` starts a text object where the side changes, also when both
/// fonts name one face.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FontSide {
    /// A character that the run's East Asian font draws.
    EastAsian,
    /// A character that the run's other fonts draw.
    Other,
    /// A space, a complex script character, or another character that no rule puts on a side.
    #[default]
    Open,
}

/// The index of a face in a shaper's faces ([`super::Shaper::faces`]), which only the shaper
/// makes, when it first uses the face.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FaceIndex(pub(super) usize);

#[cfg(test)]
impl FaceIndex {
    /// The face that a shaper used `n`-th, from 0, for a test that names faces by their order.
    pub(crate) const fn nth(n: usize) -> Self {
        Self(n)
    }
}

#[cfg(test)]
impl Glyph {
    /// A glyph of the face `face` that shows `ch`, for tests: the glyph ID 1 and an advance of
    /// 10 half-EMUs, left to right, with no offset, spacing or written width, and not in a list
    /// label.
    pub(crate) fn plain(face: FaceIndex, ch: char) -> Self {
        Self {
            face,
            ch,
            id: 1,
            advance: Length::from_units(10),
            offset: (Length::ZERO, Length::ZERO),
            spacing: Length::ZERO,
            kerning: Length::ZERO,
            auto_space: Length::ZERO,
            counted: Length::ZERO,
            written: None,
            part: false,
            label: false,
            space: SpaceKind::Free,
            starts_run: false,
            left_out_before: LeftOutBefore::Nothing,
            direction: RunDirection::LeftToRight,
            side: FontSide::Open,
            place: TextPlace::default(),
            sizing: LineSizing::ByFace,
        }
    }
}

/// The faces that a shaper has used so far, read by their face indices.
#[derive(Clone, Copy, Debug)]
pub struct Faces<'s>(pub(super) &'s [Face]);

impl<'s> Faces<'s> {
    /// The face at `index`, or none for an index of another shaper beyond its faces.
    #[must_use]
    pub fn get(self, index: FaceIndex) -> Option<&'s Face> {
        self.0.get(index.0)
    }
}

/// How a line treats a space glyph.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SpaceKind {
    /// A space that a line may break at and that a justified line stretches or shrinks.
    #[default]
    Free,
    /// A space typed in an equation's math run: a line does not break at it, and a justified
    /// line neither stretches nor shrinks it. It sizes its line as a space does.
    Equation,
    /// The space after a binary operator or a relation at the top level of an equation in a
    /// line, a no-break space after a hair space for a relation: a line may break after it, and
    /// all of it hangs past the line's end there, but a justified line neither stretches nor
    /// shrinks it.
    Operator,
    /// A no-break space that a justified line stretches or shrinks as a free space, where the
    /// target gives it a plain space's share: a line does not break at it.
    NoBreak,
    /// A continuation glyph of a math glyph assembly (such as a stretched accent or grouping
    /// character) whose text is a space (`U+0020`) so PDF text extraction does not repeat the
    /// character: a line does not break at it, a justified line does not stretch it, and its ink
    /// still sizes the line.
    Assembly,
}

/// What the shaper left out of a run's text right before a glyph's character, in reading
/// order, that the PDF writer's text objects ask.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LeftOutBefore {
    /// Nothing that the writer asks.
    #[default]
    Nothing,
    /// A format character: U+200B to U+200F, U+202A to U+202E or U+FEFF.
    FormatCharacter,
}

/// Whether a glyph sizes the line that holds it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineSizing {
    /// It sizes its line by its face.
    #[default]
    ByFace,
    /// It sizes no line: an en or em space that its slot's face lacks and a substitute face
    /// draws.
    Nothing,
}

/// One measured glyph.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Glyph {
    /// The index of its face in [`super::Shaper::faces`].
    pub face: FaceIndex,
    /// The character that it shows.
    pub ch: char,
    /// The glyph ID in the font.
    pub id: u32,
    /// The advance width at the nominal size.
    pub advance: Length,
    /// Where the glyph's origin lies from its place in the line, to the right and up, at the
    /// nominal size: the place that the font's layout tables give a mark over its letter, or
    /// a letter that joins the next one at another height. Zero for every other glyph.
    pub offset: (Length, Length),
    /// The character spacing of its run that `advance` holds, at the nominal size, which the
    /// device steps on its own, on a target that keeps the spacing apart from the glyph's own
    /// width; else zero.
    ///
    /// quirk: `DeviceAdvance` (src/quirks.rs)
    pub spacing: Length,
    /// The pair kerning with the next glyph that `advance` holds, at the nominal size, which the
    /// device steps in whole dots on its own where the target steps the kerned run so; else
    /// zero.
    ///
    /// quirk: `KernedDeviceWidths::OwnWithKerningOnItsOwn` (src/quirks.rs)
    pub kerning: Length,
    /// The East Asian / Latin or digit auto-space (`w:autoSpaceDE` / `w:autoSpaceDN`) that
    /// `advance` holds, which the device steps in whole dots on its own under
    /// `EastAsianAutoSpace::AverageWidthHalf`; else zero.
    ///
    /// quirk: `EastAsianAutoSpace::AverageWidthHalf` (src/quirks.rs)
    pub auto_space: Length,
    /// What line breaking counts beside `advance` when it tests whether the glyph fits, at the
    /// nominal size: one font unit of a synthetic bold face, the font size over its units per
    /// em, a space too, except a later part of a ligature, on a target that counts it; else
    /// zero.
    ///
    /// quirk: `SyntheticBoldWidth::CountsAFontUnit` (src/quirks.rs)
    pub counted: Length,
    /// The width in whole thousandths of an em that the target's PDF writer writes for the
    /// glyph, where the writer does not round its placed advance: the target's rule of written
    /// widths from the glyph's advance in font units where it differs from that rounding of
    /// the glyph's own advance, or its own advance rounded when kerning or character spacing
    /// changed its advance.
    pub written: Option<u16>,
    /// Whether the glyph is a later part of the ligature before it. A part has no advance and
    /// draws nothing, and its character joins the ligature's text.
    pub part: bool,
    /// Whether the glyph belongs to a list label, whose descent does not size its line.
    pub label: bool,
    /// How a line treats the glyph where it is a space.
    pub space: SpaceKind,
    /// Whether the glyph is the first glyph of a run of the document (`w:r`).
    pub starts_run: bool,
    /// What the shaper left out of its run's text right before the glyph's character, in
    /// reading order.
    pub left_out_before: LeftOutBefore,
    /// Whether the run's inherited direction is RTL, separate from complex script formatting.
    pub direction: RunDirection,
    /// The side of the border between its run's East Asian font and its other fonts that its
    /// character lies on.
    pub side: FontSide,
    /// Where its character lies in the text that Word cuts into pieces.
    pub place: TextPlace,
    /// Whether it sizes its line.
    pub sizing: LineSizing,
}

/// Where a glyph's character lies in its paragraph's text, in UTF-16 code units. Word cuts the
/// text into pieces of [`crate::mode::ModeRules::text_piece_length`] characters, which it
/// counts from the start of each run
/// and from the first character of the paragraph on each page, and the PDF writer starts a
/// text object at each piece.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TextPlace {
    /// From the start of its run.
    pub in_run: u32,
    /// From the start of its paragraph.
    pub in_paragraph: u32,
    /// Whether the character starts a run that starts a text buffer. Only the trace of the test
    /// tools reads it.
    pub starts_buffer: bool,
    /// The index of its run among the runs of its paragraph, from 0; none for a glyph of a list
    /// label. Only the text map reads it, to find where a hyperlink's text and a bookmark lie.
    pub run: Option<u32>,
}

impl TextPlace {
    /// Whether the character starts a piece of `length` characters, when the paragraph's part
    /// on the page starts at `from` in the paragraph.
    #[must_use]
    pub fn starts_piece(self, from: u32, length: usize) -> bool {
        let count = self.in_run.min(self.in_paragraph.saturating_sub(from));
        count > 0 && usize::try_from(count).is_ok_and(|c| c % length.max(1) == 0)
    }
}