f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! The substitute faces of the target that chooses them by the block of a character: the face
//! that draws a character which the face of its slot lacks, by the character's block and by the
//! face's family or its PANOSE class, and for the shapes, symbols and bullets outside the table's
//! blocks the first face of their group's steps that has the character.

use f_office_fonts::{FaceClassification, FamilyName};

use crate::params::{
    PANOSE_FIRST_SANS_SERIF, PANOSE_LAST_SANS_SERIF, PANOSE_LATIN_PICTORIAL, PANOSE_LATIN_TEXT,
    PANOSE_MONOSPACED,
};

/// The class of a face by its PANOSE numbers, by which the table chooses the substitute of
/// most blocks.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PanoseClass {
    /// A face whose characters all have one width.
    Monospaced,
    /// A face of Latin text without serifs.
    Sans,
    /// Every other face: with serifs, a script or decorative face, or one without PANOSE
    /// numbers.
    Roman,
}

impl PanoseClass {
    /// The class of a face with the classification `classification`, roman without one.
    pub(super) fn of(classification: Option<FaceClassification>) -> Self {
        let Some(FaceClassification { panose, .. }) = classification else {
            return Self::Roman;
        };
        let [family_kind, serif_style, _, proportion, ..] = panose;
        if proportion == PANOSE_MONOSPACED {
            Self::Monospaced
        } else if family_kind == PANOSE_LATIN_TEXT
            && (PANOSE_FIRST_SANS_SERIF..=PANOSE_LAST_SANS_SERIF).contains(&serif_style)
        {
            Self::Sans
        } else {
            Self::Roman
        }
    }
}

/// A row of the table: the characters of one or more blocks, the faces whose own substitute
/// for them stands before the class's, and the substitute of each class.
struct Row {
    /// The first and the last character of each block of the row.
    blocks: &'static [(char, char)],
    /// The families that have a substitute of their own for these characters, each with it.
    own: &'static [(&'static str, &'static str)],
    /// The substitute of each class.
    by_class: ByClass,
}

/// The substitute face of each [`PanoseClass`].
struct ByClass {
    monospaced: &'static str,
    sans: &'static str,
    roman: &'static str,
}

impl ByClass {
    /// The same substitute for every class.
    const fn all(family: &'static str) -> Self {
        Self {
            monospaced: family,
            sans: family,
            roman: family,
        }
    }

    /// The substitute of `class`.
    const fn of(&self, class: PanoseClass) -> &'static str {
        match class {
            PanoseClass::Monospaced => self.monospaced,
            PanoseClass::Sans => self.sans,
            PanoseClass::Roman => self.roman,
        }
    }
}

/// The table of substitute faces of the target that chooses them by block.
const ROWS: [Row; 7] = [
    // Hangul syllables, jamo and compatibility jamo.
    Row {
        blocks: &[
            ('\u{1100}', '\u{11FF}'),
            ('\u{3130}', '\u{318F}'),
            ('\u{AC00}', '\u{D7A3}'),
        ],
        own: &[
            ("Times New Roman", "Batang"),
            ("SimSun", "Batang"),
            ("DengXian", "Batang"),
            ("PMingLiU", "Batang"),
            ("MS PMincho", "Batang"),
        ],
        by_class: ByClass::all("Malgun Gothic"),
    },
    // Devanagari.
    Row {
        blocks: &[('\u{0900}', '\u{097F}')],
        own: &[],
        by_class: ByClass::all("Nirmala UI"),
    },
    // The circled numbers 1 to 20.
    Row {
        blocks: &[('\u{2460}', '\u{2473}')],
        own: &[],
        by_class: ByClass::all("Cambria Math"),
    },
    // The parenthesized numbers and the numbers with a full stop.
    Row {
        blocks: &[('\u{2474}', '\u{249B}')],
        own: &[
            ("Times New Roman", "Yu Gothic"),
            ("Batang", "Yu Gothic"),
            ("PMingLiU", "Yu Gothic"),
        ],
        by_class: ByClass {
            monospaced: "MS Mincho",
            sans: "MS Gothic",
            roman: "MS Mincho",
        },
    },
    // Hebrew, Arabic and Greek Extended.
    Row {
        blocks: &[
            ('\u{0590}', '\u{05FF}'),
            ('\u{0600}', '\u{06FF}'),
            ('\u{1F00}', '\u{1FFF}'),
        ],
        own: &[],
        by_class: ByClass {
            monospaced: "Courier New",
            sans: "Arial",
            roman: "Times New Roman",
        },
    },
    // Latin Extended-A, Latin Extended Additional and Cyrillic.
    Row {
        blocks: &[
            ('\u{0100}', '\u{017F}'),
            ('\u{1E00}', '\u{1EFF}'),
            ('\u{0400}', '\u{04FF}'),
        ],
        own: &[],
        by_class: ByClass {
            monospaced: "Calibri",
            sans: "Calibri",
            roman: "Cambria",
        },
    },
    // Miscellaneous Symbols and Dingbats.
    Row {
        blocks: &[('\u{2600}', '\u{26FF}'), ('\u{2700}', '\u{27BF}')],
        own: &[],
        by_class: ByClass::all("Segoe UI Symbol"),
    },
];

/// A step of a group of characters outside the rows of the table: a face that the character
/// takes when the faces of the steps before lack it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Step {
    /// The face of the class: Courier New, Arial or Times New Roman.
    Class,
    /// Cambria Math.
    CambriaMath,
    /// The East Asian face of the class: MS Gothic under a sans face, MS Mincho under the
    /// others.
    EastAsian,
    /// Segoe UI Symbol.
    SegoeUiSymbol,
}

impl Step {
    /// The face of the step under a face of `class`.
    const fn face(self, class: PanoseClass) -> &'static str {
        match self {
            Self::Class => CLASS_FACES.of(class),
            Self::CambriaMath => "Cambria Math",
            Self::EastAsian => EAST_ASIAN_FACES.of(class),
            Self::SegoeUiSymbol => "Segoe UI Symbol",
        }
    }
}

/// The class faces of the steps [`Step::Class`].
const CLASS_FACES: ByClass = ByClass {
    monospaced: "Courier New",
    sans: "Arial",
    roman: "Times New Roman",
};

/// The East Asian faces of the steps [`Step::EastAsian`].
const EAST_ASIAN_FACES: ByClass = ByClass {
    monospaced: "MS Mincho",
    sans: "MS Gothic",
    roman: "MS Mincho",
};

/// A group of characters outside the rows of the table: the characters of its blocks, and the
/// steps that they take in order.
struct Group {
    blocks: &'static [(char, char)],
    steps: &'static [Step],
}

/// The groups of characters outside the rows of the table, the first that holds a character
/// deciding its steps.
const GROUPS: [Group; 4] = [
    // The bullets of General Punctuation, whose substitutes are not settled, keep the face of
    // their slot.
    Group {
        blocks: &[('\u{2023}', '\u{2023}'), ('\u{2043}', '\u{2043}')],
        steps: &[],
    },
    // The en space and the em space, which take the steps of the shapes.
    Group {
        blocks: &[FIXED_SPACES],
        steps: &[Step::Class, Step::CambriaMath, Step::SegoeUiSymbol],
    },
    // The shapes: Spacing Modifier Letters, Arrows, Box Drawing, Block Elements and Geometric
    // Shapes.
    Group {
        blocks: &[
            ('\u{02B0}', '\u{02FF}'),
            ('\u{2190}', '\u{21FF}'),
            ('\u{2500}', '\u{25FF}'),
        ],
        steps: &[Step::Class, Step::CambriaMath, Step::SegoeUiSymbol],
    },
    // The symbols: General Punctuation, Letterlike Symbols, Number Forms, Mathematical
    // Operators and Miscellaneous Technical.
    Group {
        blocks: &[
            ('\u{2000}', '\u{206F}'),
            ('\u{2100}', '\u{218F}'),
            ('\u{2200}', '\u{23FF}'),
        ],
        steps: &[Step::CambriaMath, Step::EastAsian, Step::SegoeUiSymbol],
    },
];

/// The en space and the em space, the white space that takes a substitute face.
const FIXED_SPACES: (char, char) = ('\u{2002}', '\u{2003}');

/// Whether the result of a text form field keeps `ch` in its own face where that face lacks
/// it, with no substitute: the [`FIXED_SPACES`].
pub(super) fn kept_in_form_text(ch: char) -> bool {
    (FIXED_SPACES.0..=FIXED_SPACES.1).contains(&ch)
}

/// Whether `ch` stays out of the groups: white space other than the line and paragraph
/// separators and the [`FIXED_SPACES`], a control or format character, which draw no glyph of
/// their own, or a character of the private use area.
fn left_alone(ch: char) -> bool {
    (ch.is_whitespace()
        && !matches!(ch, '\u{2028}' | '\u{2029}')
        && !(FIXED_SPACES.0..=FIXED_SPACES.1).contains(&ch))
        || ch.is_control()
        || matches!(ch, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{206F}')
        || ('\u{E000}'..='\u{F8FF}').contains(&ch)
}

/// The substitute faces of `ch` for a face of the family `family` and the classification
/// `classification` that lacks it, in order: the face of its row of the table, or, for a
/// character of a Latin slot (`latin`), the faces of its group's steps, of which the first that
/// has `ch` draws it. Empty when neither holds `ch`, and for a pictorial face outside the rows.
pub(super) fn substitutes(
    (family, classification): (&str, Option<FaceClassification>),
    ch: char,
    latin: bool,
) -> Vec<FamilyName> {
    let holds = |blocks: &[(char, char)]| {
        blocks
            .iter()
            .any(|&(first, last)| (first..=last).contains(&ch))
    };
    let class = PanoseClass::of(classification);
    if let Some(row) = ROWS.iter().find(|row| holds(row.blocks)) {
        let own = row
            .own
            .iter()
            .find(|(named, _)| FamilyName::new(family).is(named))
            .map(|&(_, substitute)| substitute);
        return vec![FamilyName::from_static(
            own.unwrap_or_else(|| row.by_class.of(class)),
        )];
    }
    let pictorial = classification.is_some_and(|c| c.panose[0] == PANOSE_LATIN_PICTORIAL);
    if !latin || pictorial || left_alone(ch) {
        return Vec::new();
    }
    let steps = GROUPS
        .iter()
        .find(|group| holds(group.blocks))
        .map_or(&[][..], |group| group.steps);
    steps
        .iter()
        .map(|step| FamilyName::from_static(step.face(class)))
        .collect()
}

/// Whether a face of the family `family` and the classification `classification` keeps a
/// character of the East Asian slot that MS Mincho has: an East Asian face, or Times New Roman.
pub(super) fn keeps_east_asian(family: &str, classification: Option<FaceClassification>) -> bool {
    classification.is_some_and(|c| c.east_asian) || FamilyName::new(family).is("Times New Roman")
}

/// The face that takes a character of the East Asian slot of a face that does not keep it.
pub(super) const EAST_ASIAN_SUBSTITUTE: FamilyName = FamilyName::from_static("MS Mincho");

/// The face that takes a Devanagari character of a list label, such as a digit of
/// `hindiNumbers`, which the label's face lacks, in place of the row of body text.
const LABEL_DEVANAGARI_SUBSTITUTE: FamilyName = FamilyName::from_static("Mangal");

/// The substitute of `ch` in a list label, where it differs from that of body text.
pub(super) fn label_substitute(ch: char) -> Option<FamilyName> {
    ('\u{0900}'..='\u{097F}')
        .contains(&ch)
        .then_some(LABEL_DEVANAGARI_SUBSTITUTE)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A face's classification with the PANOSE numbers `panose`.
    const fn classified(panose: [u8; 10], east_asian: bool) -> FaceClassification {
        FaceClassification { panose, east_asian }
    }

    /// The substitutes of `ch` in a Latin slot under the face `family` of the PANOSE numbers
    /// `panose`, in order.
    fn steps(family: &str, panose: [u8; 10], ch: char) -> Vec<String> {
        substitutes((family, Some(classified(panose, false))), ch, true)
            .iter()
            .map(|f| f.as_str().to_owned())
            .collect()
    }

    /// The first substitute of `ch` under the face `family` of the PANOSE numbers `panose`.
    fn take(family: &str, panose: [u8; 10], ch: char) -> Option<String> {
        steps(family, panose, ch).into_iter().next()
    }

    /// The PANOSE class of a face with the PANOSE numbers `panose`.
    fn class(panose: [u8; 10]) -> PanoseClass {
        PanoseClass::of(Some(classified(panose, false)))
    }

    const SANS: [u8; 10] = [2, 11, 6, 4, 2, 2, 2, 2, 2, 4];
    const ROMAN: [u8; 10] = [2, 4, 5, 3, 5, 4, 6, 3, 2, 4];
    const MONOSPACED: [u8; 10] = [2, 7, 3, 9, 2, 2, 5, 2, 4, 4];
    const SCRIPT: [u8; 10] = [3, 15, 7, 2, 3, 3, 2, 2, 2, 4];

    #[test]
    fn the_class_reads_the_proportion_before_the_serif_style() {
        assert_eq!(class(SANS), PanoseClass::Sans);
        assert_eq!(class(ROMAN), PanoseClass::Roman);
        let monospaced_sans = [2, 11, 6, 9, 2, 2, 4, 3, 2, 4];
        assert_eq!(class(monospaced_sans), PanoseClass::Monospaced);
        assert_eq!(class(MONOSPACED), PanoseClass::Monospaced);
        // A script face is not a face of Latin text, whatever its serif style.
        assert_eq!(class(SCRIPT), PanoseClass::Roman);
        assert_eq!(PanoseClass::of(None), PanoseClass::Roman);
    }

    #[test]
    fn latin_and_complex_blocks_take_the_face_of_the_class() {
        assert_eq!(take("Segoe UI", SANS, 'č').as_deref(), Some("Calibri"));
        assert_eq!(take("Georgia", ROMAN, 'Ж').as_deref(), Some("Cambria"));
        assert_eq!(
            take("Courier New", MONOSPACED, 'ě').as_deref(),
            Some("Calibri")
        );
        assert_eq!(take("Segoe UI", SANS, 'א').as_deref(), Some("Arial"));
        assert_eq!(
            take("Courier New", MONOSPACED, 'ש').as_deref(),
            Some("Courier New")
        );
    }

    #[test]
    fn other_blocks_take_their_face() {
        assert_eq!(
            take("Georgia", ROMAN, '\u{2474}').as_deref(),
            Some("MS Mincho")
        );
        assert_eq!(
            take("Segoe UI", SANS, '\u{2488}').as_deref(),
            Some("MS Gothic")
        );
        assert_eq!(
            take("Segoe UI", SANS, '한').as_deref(),
            Some("Malgun Gothic")
        );
        assert_eq!(take("Georgia", ROMAN, 'क').as_deref(), Some("Nirmala UI"));
        assert_eq!(take("Georgia", ROMAN, '①').as_deref(), Some("Cambria Math"));
        assert_eq!(take("Georgia", ROMAN, 'ก'), None);
    }

    #[test]
    fn symbols_and_dingbats_take_segoe_ui_symbol() {
        assert_eq!(take("Arial", SANS, '❏').as_deref(), Some("Segoe UI Symbol"));
        assert_eq!(
            take("Courier New", MONOSPACED, '☎').as_deref(),
            Some("Segoe UI Symbol")
        );
    }

    #[test]
    fn shapes_take_the_class_face_then_cambria_math() {
        assert_eq!(
            steps("Open Sans", SANS, '\u{25CF}'),
            ["Arial", "Cambria Math", "Segoe UI Symbol"]
        );
        assert_eq!(
            take("Roboto", ROMAN, '\u{25CB}').as_deref(),
            Some("Times New Roman")
        );
        assert_eq!(
            take("Consolas", MONOSPACED, '\u{2193}').as_deref(),
            Some("Courier New")
        );
        assert_eq!(take("Verdana", SANS, '\u{02CD}').as_deref(), Some("Arial"));
    }

    #[test]
    fn symbols_take_cambria_math_then_the_east_asian_face_of_the_class() {
        assert_eq!(
            steps("Century Gothic", SANS, '\u{2028}'),
            ["Cambria Math", "MS Gothic", "Segoe UI Symbol"]
        );
        assert_eq!(
            steps("Garamond", ROMAN, '\u{203B}'),
            ["Cambria Math", "MS Mincho", "Segoe UI Symbol"]
        );
        assert_eq!(
            take("Rockwell", ROMAN, '\u{2103}').as_deref(),
            Some("Cambria Math")
        );
        assert_eq!(
            take("Consolas", MONOSPACED, '\u{2160}').as_deref(),
            Some("Cambria Math")
        );
    }

    #[test]
    fn en_and_em_spaces_take_the_class_face_then_cambria_math() {
        assert_eq!(
            steps("Arial Narrow", SANS, '\u{2002}'),
            ["Arial", "Cambria Math", "Segoe UI Symbol"]
        );
        assert_eq!(
            take("Comic Sans MS", SCRIPT, '\u{2003}').as_deref(),
            Some("Times New Roman")
        );
        assert_eq!(
            steps("Courier New", MONOSPACED, '\u{2002}'),
            ["Courier New", "Cambria Math", "Segoe UI Symbol"]
        );
    }

    #[test]
    fn the_bullets_of_general_punctuation_take_no_substitute() {
        assert_eq!(take("Calibri", SANS, '\u{2023}'), None);
        assert_eq!(take("Garamond", ROMAN, '\u{2043}'), None);
    }

    #[test]
    fn spaces_controls_private_use_and_pictorial_faces_stay_out_of_the_groups() {
        assert_eq!(take("Arial Narrow", SANS, '\u{2009}'), None);
        assert_eq!(take("Arial Narrow", SANS, '\u{200C}'), None);
        assert_eq!(take("Arial", SANS, '\u{0009}'), None);
        assert_eq!(take("Times New Roman", ROMAN, '\u{F02A}'), None);
        let pictorial = [5, 5, 1, 2, 1, 7, 6, 2, 5, 7];
        assert_eq!(take("Symbol", pictorial, '\u{2022}'), None);
        assert_eq!(take("Arial", SANS, '\u{20AC}'), None);
        let east_asian_slot =
            substitutes(("SimSun", Some(classified(ROMAN, true))), '\u{2010}', false);
        assert_eq!(east_asian_slot.len(), 0);
    }

    #[test]
    fn a_face_of_its_own_row_takes_its_own_substitute() {
        assert_eq!(
            take("Times New Roman", ROMAN, '한').as_deref(),
            Some("Batang")
        );
        assert_eq!(take("simsun", ROMAN, '한').as_deref(), Some("Batang"));
        let parenthesized = take("Times New Roman", ROMAN, '\u{2474}');
        assert_eq!(parenthesized.as_deref(), Some("Yu Gothic"));
        assert_eq!(
            take("Times New Roman", ROMAN, 'č').as_deref(),
            Some("Cambria")
        );
    }

    #[test]
    fn east_asian_faces_and_times_new_roman_keep_east_asian_characters() {
        assert!(keeps_east_asian("SimSun", Some(classified(ROMAN, true))));
        assert!(keeps_east_asian(
            "Times New Roman",
            Some(classified(ROMAN, false))
        ));
        assert!(!keeps_east_asian("Calibri", Some(classified(SANS, false))));
        assert!(!keeps_east_asian("Calibri", None));
    }
}