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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Letter joints between Arabic letters: how each character joins the letters beside it, and
//! which joints of a line's words can take a kashida, a run of tatweel glyphs (U+0640), and of
//! which kind. Justification lengthens these joints, and line breaking counts them.

use super::{Piece, Placed, stretches};
use crate::text::FaceIndex;

/// How a character joins the letters beside it in Arabic script (the joining types of the
/// Unicode Standard), for the characters that F-Office asks about.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Joining {
    /// A letter that joins the letter before it and the letter after it, and the tatweel.
    Dual,
    /// A letter that joins only the letter before it.
    Right,
    /// A mark, which the joining passes over.
    Transparent,
    /// A character that joins neither.
    None,
}

/// How `ch` joins the letters beside it.
const fn joining(ch: char) -> Joining {
    match ch {
        '\u{0610}'..='\u{061A}'
        | '\u{064B}'..='\u{065F}'
        | '\u{0670}'
        | '\u{06D6}'..='\u{06DC}'
        | '\u{06DF}'..='\u{06E4}'
        | '\u{06E7}'
        | '\u{06E8}'
        | '\u{06EA}'..='\u{06ED}' => Joining::Transparent,
        '\u{0622}'..='\u{0625}'
        | '\u{0627}'
        | '\u{0629}'
        | '\u{062F}'..='\u{0632}'
        | '\u{0648}'
        | '\u{0671}'..='\u{0673}'
        | '\u{0675}'..='\u{0677}'
        | '\u{0688}'..='\u{0699}'
        | '\u{06C0}'
        | '\u{06C3}'..='\u{06CB}'
        | '\u{06CD}'
        | '\u{06CF}'
        | '\u{06D2}'
        | '\u{06D3}'
        | '\u{06D5}'
        | '\u{06EE}'
        | '\u{06EF}' => Joining::Right,
        '\u{0620}'
        | '\u{0626}'
        | '\u{0628}'
        | '\u{062A}'..='\u{062E}'
        | '\u{0633}'..='\u{0647}'
        | '\u{0649}'
        | '\u{064A}'
        | '\u{066E}'
        | '\u{066F}'
        | '\u{0678}'..='\u{0687}'
        | '\u{069A}'..='\u{06BF}'
        | '\u{06C1}'
        | '\u{06C2}'
        | '\u{06CC}'
        | '\u{06CE}'
        | '\u{06D0}'
        | '\u{06D1}'
        | '\u{06FA}'..='\u{06FC}'
        | '\u{06FF}' => Joining::Dual,
        _ => Joining::None,
    }
}

/// Whether a letter joint after `ch` is a letter joint after a seen, sheen, sad or dad, the first place of a
/// word's kashida.
const fn after_seen(ch: char) -> bool {
    matches!(ch, '\u{0633}'..='\u{0636}')
}

/// Whether `ch` has the shape of a beh between two letter joints: beh, teh, theh, peh, noon, yeh,
/// Farsi yeh or yeh with hamza.
const fn beh_shaped(ch: char) -> bool {
    matches!(
        ch,
        '\u{0628}'
            | '\u{062A}'
            | '\u{062B}'
            | '\u{067E}'
            | '\u{0646}'
            | '\u{064A}'
            | '\u{06CC}'
            | '\u{0626}'
    )
}

/// The class of a letter joint of a word that can take its kashida: a letter joint before the letter that ends
/// a joined group of the word, or before a letter of the shape of a beh that joins the letter
/// after it, from the letter joint that takes the word's kashida first. Of equal classes, the last letter joint
/// in reading order takes it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Ending {
    /// Before teh marbuta, heh, heh doachashmee, heh with yeh, dal or thal.
    Heh,
    /// Before alef and its forms with hamza and madda, lam, kaf, keheh, gaf, beh, teh, theh or
    /// peh.
    Alef,
    /// Before waw, waw with hamza, ain, ghain, qaf or feh.
    Waw,
    /// Before reh, zain, jeh, yeh, alef maksura, Farsi yeh or yeh with hamza.
    Reh,
    /// Before a letter of the shape of a beh ([`beh_shaped`]) that joins the letter after it,
    /// which ends no group.
    Tooth,
    /// Before any other letter.
    Other,
    /// Before a ligature glyph, which stands for more than one letter.
    Ligature,
}

impl Ending {
    /// The class of a letter joint before a letter glyph whose first letter is `first`, or that is a
    /// ligature glyph when `ligature`.
    const fn of(first: char, ligature: bool) -> Self {
        if ligature {
            return Self::Ligature;
        }
        match first {
            '\u{0629}' | '\u{0647}' | '\u{062F}' | '\u{0630}' | '\u{06C0}' | '\u{06BE}' => {
                Self::Heh
            }
            '\u{0622}' | '\u{0623}' | '\u{0625}' | '\u{0627}' | '\u{0671}' | '\u{0644}'
            | '\u{0643}' | '\u{06A9}' | '\u{06AF}' | '\u{0628}' | '\u{062A}' | '\u{062B}'
            | '\u{067E}' => Self::Alef,
            '\u{0648}' | '\u{0624}' | '\u{0639}' | '\u{063A}' | '\u{0642}' | '\u{0641}' => {
                Self::Waw
            }
            '\u{0631}' | '\u{0632}' | '\u{0698}' | '\u{064A}' | '\u{0649}' | '\u{06CC}'
            | '\u{0626}' => Self::Reh,
            _ => Self::Other,
        }
    }
}

/// One letter glyph of a word: the index of the last piece that belongs to it (its marks and
/// the later parts of a ligature), its first and last letter, its face, and whether it starts
/// a run.
#[derive(Clone, Copy)]
struct Letter {
    end: usize,
    first: char,
    last: char,
    face: FaceIndex,
    starts_run: bool,
}

impl Letter {
    /// Whether the letter glyph joins the letter glyph `next` after it in reading order.
    fn joins(&self, next: &Self) -> bool {
        joining(self.last) == Joining::Dual
            && matches!(joining(next.first), Joining::Dual | Joining::Right)
            && self.face == next.face
            && !next.starts_run
    }
}

/// The letter joint of a word that takes its kashida, as the index of the piece after which the
/// tatweels go, with the face that draws them: the word's last letter joint after a seen, sheen, sad
/// or dad, or else, of the letter joints before a letter glyph that ends a joined group or before a
/// letter of the shape of a beh that joins the letter after it, the one of the first class
/// ([`Ending`]), the last of equal ones. `None` for a word without such a letter joint.
fn word_letter_joint(letters: &[Option<Letter>]) -> Option<(usize, FaceIndex)> {
    let mut seen = None;
    let mut ending: Option<(Ending, usize, FaceIndex)> = None;
    for (at, pair) in letters.windows(2).enumerate() {
        let [Some(left), Some(right)] = pair else {
            continue;
        };
        if !left.joins(right) {
            continue;
        }
        if after_seen(left.last) {
            seen = Some((left.end, left.face));
        }
        let ends_group = match letters.get(at + 2) {
            Some(Some(next)) => !right.joins(next),
            _ => true,
        };
        let class = if ends_group {
            Some(Ending::of(right.first, right.first != right.last))
        } else {
            (right.first == right.last && beh_shaped(right.first)).then_some(Ending::Tooth)
        };
        if let Some(class) = class
            && ending.is_none_or(|(best, _, _)| class <= best)
        {
            ending = Some((class, left.end, left.face));
        }
    }
    seen.or(ending.map(|(_, end, face)| (end, face)))
}

/// Letter joints that take kashidas, in reading order: the index of the piece after which the
/// tatweels go, with the face that draws them.
type Joints = Vec<(usize, FaceIndex)>;

/// The letter joints of a word after a seen, sheen, sad or dad, in reading order, as the indexes
/// of the pieces after which the tatweels go, with the faces that draw them.
fn word_seen_joints(letters: &[Option<Letter>], out: &mut Joints) {
    for pair in letters.windows(2) {
        if let [Some(left), Some(right)] = pair
            && left.joins(right)
            && after_seen(left.last)
        {
            out.push((left.end, left.face));
        }
    }
}

/// The letter joints of a word before the last letter of each of its joined groups whose
/// ending is that of an alef or a heh ([`Ending::Alef`], [`Ending::Heh`]), where that letter is
/// no ligature and the letter joint does not follow a seen, sheen, sad or dad, in reading order,
/// as the indexes of the pieces after which the tatweels go, with the faces that draw them.
fn word_final_joints(letters: &[Option<Letter>], out: &mut Joints) {
    for (at, pair) in letters.windows(2).enumerate() {
        let [Some(left), Some(right)] = pair else {
            continue;
        };
        let ends_group = match letters.get(at + 2) {
            Some(Some(next)) => !right.joins(next),
            _ => true,
        };
        if left.joins(right)
            && !after_seen(left.last)
            && ends_group
            && matches!(
                Ending::of(right.first, right.first != right.last),
                Ending::Alef | Ending::Heh
            )
        {
            out.push((left.end, left.face));
        }
    }
}

/// The letter joints of the words of `pieces` that can take a kashida, in reading order, from the piece
/// at `from`: the letter joint of each word ([`word_letter_joint`]).
pub(crate) fn letter_joints(pieces: &[Placed], from: usize) -> Vec<(usize, FaceIndex)> {
    word_joints(pieces, from, |letters, out| {
        out.extend(word_letter_joint(letters));
    })
}

/// The letter joints of the words of `pieces` after a seen, sheen, sad or dad, in reading order,
/// from the piece at `from` ([`word_seen_joints`]).
pub(crate) fn seen_joints(pieces: &[Placed], from: usize) -> Vec<(usize, FaceIndex)> {
    word_joints(pieces, from, word_seen_joints)
}

/// The letter joints of the words of `pieces` before an alef or a heh that ends a joined group,
/// in reading order, from the piece at `from` ([`word_final_joints`]).
pub(crate) fn final_joints(pieces: &[Placed], from: usize) -> Joints {
    word_joints(pieces, from, word_final_joints)
}

/// The letter joints of a line's words that line breaking counts, by kind.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct JointCounts {
    /// The letter joints after a seen, sheen, sad or dad.
    pub seen: usize,
    /// The other letter joints, between two letters that join.
    pub other: usize,
}

/// Counts the letter joints of a word by kind ([`JointCounts`]).
fn word_joint_counts(letters: &[Option<Letter>], counts: &mut JointCounts) {
    for pair in letters.windows(2) {
        if let [Some(left), Some(right)] = pair
            && left.joins(right)
        {
            if after_seen(left.last) {
                counts.seen += 1;
            } else {
                counts.other += 1;
            }
        }
    }
}

/// The letter joints of the words of `pieces`, by kind ([`word_joint_counts`]).
pub(crate) fn joint_counts(pieces: &[Placed]) -> JointCounts {
    word_joints(pieces, 0, word_joint_counts)
}

/// The letter joints that `of_word` gives for each word of `pieces`, in reading order, from the
/// piece at `from`. A word ends at a space, at a piece that is no glyph and at a list label.
fn word_joints<T: Default>(
    pieces: &[Placed],
    from: usize,
    of_word: fn(&[Option<Letter>], &mut T),
) -> T {
    let mut out = T::default();
    let mut letters: Vec<Option<Letter>> = Vec::new();
    for (index, placed) in pieces.iter().enumerate().skip(from) {
        let glyph = match &placed.piece {
            Piece::Glyph(glyph) if !glyph.label && !stretches(&placed.piece) => glyph,
            _ => {
                of_word(&letters, &mut out);
                letters.clear();
                continue;
            }
        };
        let joins = joining(glyph.ch);
        match letters.last_mut() {
            Some(Some(letter)) if glyph.part => {
                letter.end = index;
                letter.last = glyph.ch;
                continue;
            }
            Some(Some(letter)) if joins == Joining::Transparent => {
                letter.end = index;
                continue;
            }
            _ => {}
        }
        letters.push(
            matches!(joins, Joining::Dual | Joining::Right).then_some(Letter {
                end: index,
                first: glyph.ch,
                last: glyph.ch,
                face: glyph.face,
                starts_run: glyph.starts_run,
            }),
        );
    }
    of_word(&letters, &mut out);
    out
}

#[cfg(test)]
mod tests {
    use super::{
        Ending, Joining, JointCounts, Joints, Letter, joining, word_final_joints,
        word_joint_counts, word_letter_joint, word_seen_joints,
    };
    use crate::text::FaceIndex;

    #[test]
    fn joins_dual_letters_after_and_right_letters_before_only() {
        assert_eq!(joining('\u{0628}'), Joining::Dual);
        assert_eq!(joining('\u{0627}'), Joining::Right);
        assert_eq!(joining('\u{064E}'), Joining::Transparent);
        assert_eq!(joining('\u{0621}'), Joining::None);
        assert_eq!(joining('a'), Joining::None);
    }

    #[test]
    fn lengthens_the_letter_joint_before_a_tooth_before_one_before_a_group_of_the_last_class() {
        // beh, noon and jeem: the letter joint before the noon, a tooth that joins the jeem, comes
        // before the letter joint before the jeem, which ends the word's group.
        let letter = |end, ch| {
            Some(Letter {
                end,
                first: ch,
                last: ch,
                face: FaceIndex::nth(0),
                starts_run: false,
            })
        };
        let word = [
            letter(0, '\u{0628}'),
            letter(1, '\u{0646}'),
            letter(2, '\u{062C}'),
        ];
        assert_eq!(word_letter_joint(&word).map(|(end, _)| end), Some(0));
        // A seen takes it first.
        let word = [
            letter(0, '\u{0633}'),
            letter(1, '\u{0646}'),
            letter(2, '\u{062C}'),
        ];
        assert_eq!(word_letter_joint(&word).map(|(end, _)| end), Some(0));
        let word = [
            letter(0, '\u{0628}'),
            letter(1, '\u{0633}'),
            letter(2, '\u{062C}'),
        ];
        assert_eq!(word_letter_joint(&word).map(|(end, _)| end), Some(1));
    }

    #[test]
    fn lengthens_every_letter_joint_after_a_seen_that_joins_the_next_letter() {
        // seen, beh, sad, reh and sheen: the seen and the sad join the letters after them, the
        // reh joins no letter after it, and the last sheen ends the word.
        let letter = |end, ch| {
            Some(Letter {
                end,
                first: ch,
                last: ch,
                face: FaceIndex::nth(0),
                starts_run: false,
            })
        };
        let word = [
            letter(0, '\u{0633}'),
            letter(1, '\u{0628}'),
            letter(2, '\u{0635}'),
            letter(3, '\u{0631}'),
            letter(4, '\u{0634}'),
        ];
        let mut joints = Vec::new();
        word_seen_joints(&word, &mut joints);
        assert_eq!(
            joints.iter().map(|&(end, _)| end).collect::<Vec<_>>(),
            [0, 2]
        );
    }

    #[test]
    fn lengthens_the_letter_joints_before_an_alef_or_a_heh_that_ends_a_group_but_after_a_seen() {
        // beh, alef, beh, beh, reh, jeem, dal, seen and teh: the joints before the alef and the
        // dal end their groups as an alef and a heh; the reh ends one as a reh, the beh before
        // the jeem joins it, and the teh follows a seen.
        let letter = |end, ch| {
            Some(Letter {
                end,
                first: ch,
                last: ch,
                face: FaceIndex::nth(0),
                starts_run: false,
            })
        };
        let word = [
            letter(0, '\u{0628}'),
            letter(1, '\u{0627}'),
            letter(2, '\u{0628}'),
            letter(3, '\u{0628}'),
            letter(4, '\u{0631}'),
            letter(5, '\u{062C}'),
            letter(6, '\u{062F}'),
            letter(7, '\u{0633}'),
            letter(8, '\u{062A}'),
        ];
        let mut joints = Vec::new();
        word_final_joints(&word, &mut joints);
        assert_eq!(
            joints.iter().map(|&(end, _)| end).collect::<Vec<_>>(),
            [0, 5]
        );
        // A lam that ends a group as the first letter of a ligature is no final joint.
        let ligature = Some(Letter {
            end: 1,
            first: '\u{0644}',
            last: '\u{0627}',
            face: FaceIndex::nth(0),
            starts_run: false,
        });
        let mut joints = Vec::new();
        word_final_joints(&[letter(0, '\u{0628}'), ligature], &mut joints);
        assert_eq!(joints, Joints::new());
    }

    #[test]
    fn counts_the_joints_after_a_seen_apart_from_the_other_joints() {
        // seen, beh, alef, dal, sad and reh: the seen and the sad join the letters after them,
        // the beh joins the alef, and the alef and the dal join no letter after them.
        let letter = |end, ch| {
            Some(Letter {
                end,
                first: ch,
                last: ch,
                face: FaceIndex::nth(0),
                starts_run: false,
            })
        };
        let word = [
            letter(0, '\u{0633}'),
            letter(1, '\u{0628}'),
            letter(2, '\u{0627}'),
            letter(3, '\u{062F}'),
            letter(4, '\u{0635}'),
            letter(5, '\u{0631}'),
        ];
        let mut counts = JointCounts::default();
        word_joint_counts(&word, &mut counts);
        assert_eq!(counts, JointCounts { seen: 2, other: 1 });
        // A letter of another run starts a new group.
        let mut word = word;
        if let Some(Some(beh)) = word.get_mut(1) {
            beh.starts_run = true;
        }
        let mut counts = JointCounts::default();
        word_joint_counts(&word, &mut counts);
        assert_eq!(counts, JointCounts { seen: 1, other: 1 });
    }

    #[test]
    fn ranks_heh_before_alef_before_waw_before_reh_before_the_rest_and_ligatures_last() {
        let classes = ['\u{0647}', '\u{0627}', '\u{0648}', '\u{0631}', '\u{062C}']
            .map(|ch| Ending::of(ch, false));
        assert!(classes.is_sorted());
        assert!(Ending::Reh < Ending::Tooth && Ending::Tooth < Ending::Other);
        assert!(Ending::of('\u{0644}', true) > Ending::Other);
    }
}