f-office 0.2.4

Renders Office Open XML documents the way Microsoft Office does.
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
//! The edit check of the round trip: one named edit of each [`Operation`] on a document, at the
//! block that a fixed rule chooses from the document's text blocks, each made alone on the file
//! as it was with [`crate::edit::apply`], and what the new file gives ([`Made`]). The rules read
//! no document text into the edit list but the word that a replace and a comment find.

use std::collections::HashSet;
use std::sync::OnceLock;

use f_office_opc::{Limits, Package, relationships_part};
use f_office_xml::{Document as Xml, NodeId};
use image::codecs::png::PngEncoder;
use image::{ExtendedColorType, ImageEncoder as _};

use crate::edit::{self, Edit, EditFault, EditLimits, Edited, NamedEdit, NamedFault, Place};
use crate::{
    Address, Document, Error, FontDatabase, Options, TextBlock, TextBlockKind, Warned, Warning,
};

/// The text of the paragraph that [`Operation::Insert`] inserts.
const INSERTED: &str = "Inserted paragraph";

/// The text that [`Operation::SetText`] gives a cell.
const SET_TEXT: &str = "Set text";

/// The text of the first cell of the row that [`Operation::InsertRow`] and
/// [`Operation::GridRow`] insert.
const NEW_CELL: &str = "New cell";

/// The text and the author of the comment of [`Operation::Comment`] and
/// [`Operation::CommentFind`].
const COMMENT: (&str, &str) = ("Comment of the edit check", "Edit check");

/// The text that describes the image of [`Operation::Image`].
const ALT: &str = "Gray image of the edit check";

/// The width and the height in pixels of the image of [`Operation::Image`], a PNG file without
/// a resolution: 25 by 12.5 inches at the 96 pixels per inch that the edit then takes, wider
/// than the column of any page that Word makes, so that the edit makes it as wide as its column.
const IMAGE_PIXELS: (u32, u32) = (2_400, 1_200);

/// The gray of every pixel of the image of [`Operation::Image`].
const IMAGE_GRAY: u8 = 0xc0;

/// The name of the content types part (ECMA-376 Part 2, 10.1.2.1).
const CONTENT_TYPES: &str = "[Content_Types].xml";

/// The fewest characters of the word that [`Operation::Replace`] replaces.
const MIN_WORD_CHARS: usize = 4;

/// An operation of the edit check, with the rule that chooses its block.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Operation {
    /// In the first paragraph of the document, in the order of the text blocks, whose text
    /// holds a word (letters and digits) of at least four characters only once, replaces the
    /// first such word with the word in brackets. A word next to a brace, which may be part of
    /// a marker such as `{PAGE}`, does not count.
    Replace,
    /// Inserts a paragraph after the first paragraph of the body whose text is not empty.
    Insert,
    /// Gives the first paragraph of the body whose style is not S the style S, the style of
    /// the first paragraph of the body that has one.
    Style,
    /// Deletes the first paragraph of the body whose text is not empty, among the blocks of
    /// the body after its first block and before its last.
    Delete,
    /// Gives the first cell of the first table of the body the text `Set text`.
    SetText,
    /// Inserts a row after the first row of the first table of the body, with the text
    /// `New cell` in its first cell.
    InsertRow,
    /// Inserts a row as [`Operation::InsertRow`] does, after the first row of the tables of the
    /// body, in the order of the blocks, whose `w:trPr` gives a `w:gridBefore` or a
    /// `w:gridAfter` of more than zero grid columns.
    GridRow,
    /// Comments on all of the paragraph that [`Operation::Insert`] chooses.
    Comment,
    /// Comments on the word that [`Operation::Replace`] chooses, in its paragraph.
    CommentFind,
    /// Inserts a PNG image of 2,400 by 1,200 gray pixels without a resolution after the
    /// paragraph that [`Operation::Insert`] chooses, at its own size, which the edit makes as
    /// wide as the column.
    Image,
}

impl Operation {
    /// Every operation, in the order of the counts.
    pub const ALL: [Self; 10] = [
        Self::Replace,
        Self::Insert,
        Self::Style,
        Self::Delete,
        Self::SetText,
        Self::InsertRow,
        Self::GridRow,
        Self::Comment,
        Self::CommentFind,
        Self::Image,
    ];

    /// The name of the operation in the counts: the name of its edit in an edit list, or for a
    /// second rule of one edit, that name with a word for the rule.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Replace => "replace",
            Self::Insert => "insert-after",
            Self::Style => "style",
            Self::Delete => "delete",
            Self::SetText => "set-text",
            Self::InsertRow => "insert-row-after",
            Self::GridRow => "insert-row-grid",
            Self::Comment => "comment",
            Self::CommentFind => "comment-find",
            Self::Image => "insert-image-after",
        }
    }

    /// The edit that the rule chooses in the file `docx`, whose text blocks are `blocks`, or
    /// none when no block fits it.
    #[must_use]
    pub fn edit(self, docx: &[u8], blocks: &[TextBlock]) -> Option<NamedEdit> {
        match self {
            Self::Replace => replace_word(blocks).map(|(block, word)| NamedEdit::Replace {
                at: block.address.clone(),
                find: word.to_owned(),
                with: format!("[{word}]"),
            }),
            Self::Insert => first_text_paragraph(blocks).map(|at| NamedEdit::Insert {
                at,
                place: Place::After,
                text: INSERTED.to_owned(),
                style: None,
            }),
            Self::Style => style(blocks),
            Self::Delete => delete(blocks),
            Self::SetText => first_cell(blocks).map(|at| NamedEdit::SetText {
                at,
                text: SET_TEXT.to_owned(),
            }),
            Self::InsertRow => first_row(blocks).map(new_row),
            Self::GridRow => grid_row(docx, blocks).map(new_row),
            Self::Comment => first_text_paragraph(blocks).map(|at| comment(at, None)),
            Self::CommentFind => replace_word(blocks)
                .map(|(block, word)| comment(block.address.clone(), Some(word.to_owned()))),
            Self::Image => {
                let at = first_text_paragraph(blocks)?;
                let image = edit::image_file(check_image()?.to_vec(), &EditLimits::default());
                Some(NamedEdit::InsertImage {
                    at,
                    place: Place::After,
                    image: image.ok()?,
                    alt: ALT.to_owned(),
                    size: (None, None),
                })
            }
        }
    }

    /// Whether the edit changes or adds parts other than the main document part: the comments
    /// part, or the image part, with the main part's relationships and the content types.
    const fn adds_parts(self) -> bool {
        matches!(self, Self::Comment | Self::CommentFind | Self::Image)
    }
}

/// What one edit of the check gave.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EditOutcome {
    /// The rule found no block for the operation.
    NoAddress,
    /// `apply` refused the edit, for the fault of this kind, such as `text-not-found`.
    Refused(String),
    /// `apply` made the edit.
    Made(Made),
}

/// What a made edit gave.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "four independent findings of one check, each counted on its own"
)]
pub struct Made {
    /// Whether the new file lays out.
    pub lays_out: bool,
    /// Whether the new file's text blocks are those that the edit makes; false when it does not
    /// lay out.
    pub blocks_confirmed: bool,
    /// Whether the new file opens with every part of the file before and the bytes of each part
    /// that the operation does not change, and adds no part that the operation does not add:
    /// a comment and an image change the main part's relationships part and the content types
    /// part, a comment also the comments part, which it adds when the file has none, and an
    /// image adds its image part.
    pub other_parts_kept: bool,
    /// Whether the edit warned that a note stays in its part ([`Warning::NoteKept`]).
    pub note_kept: bool,
}

/// Lays out `docx` for its text blocks, makes the edit of each operation alone on it, and lays
/// out each new file.
///
/// # Errors
///
/// Returns the error of the layout of `docx`.
pub fn edits(
    docx: &[u8],
    fonts: &FontDatabase,
    options: &Options,
) -> Result<Vec<(Operation, EditOutcome)>, Error> {
    let before = Document::open(docx, fonts, options)?;
    let blocks = before.value.text_blocks();
    Ok(Operation::ALL
        .into_iter()
        .map(|operation| {
            let outcome = operation
                .edit(docx, blocks)
                .map_or(EditOutcome::NoAddress, |named| {
                    check(docx, blocks, (operation, named), (fonts, options))
                });
            (operation, outcome)
        })
        .collect())
}

/// Makes the edit `named` of `operation` on `docx`, whose text blocks are `blocks`, and checks
/// the new file.
fn check(
    docx: &[u8],
    blocks: &[TextBlock],
    (operation, named): (Operation, NamedEdit),
    (fonts, options): (&FontDatabase, &Options),
) -> EditOutcome {
    match edit::apply(docx, blocks, &[Edit::Named(named)], &EditLimits::default()) {
        Err(error) => EditOutcome::Refused(fault_kind(&error.fault)),
        Ok(edited) => EditOutcome::Made(made(docx, operation, &edited, (fonts, options))),
    }
}

/// What the new file of a made edit of `operation` gives.
fn made(
    docx: &[u8],
    operation: Operation,
    edited: &Warned<Edited>,
    (fonts, options): (&FontDatabase, &Options),
) -> Made {
    let after = Document::open(&edited.value.docx, fonts, options).ok();
    let blocks_confirmed = match (&after, &edited.value.expected) {
        (Some(after), Some(expected)) => expected.compare(after.value.text_blocks()).is_ok(),
        _ => false,
    };
    Made {
        lays_out: after.is_some(),
        blocks_confirmed,
        other_parts_kept: other_parts_kept(operation, docx, &edited.value.docx),
        note_kept: edited
            .warnings
            .iter()
            .any(|(warning, _)| *warning == Warning::NoteKept),
    }
}

/// Whether `after` opens with every part of `before`, by name, and with the bytes of each part
/// that `operation` does not change, and holds no part but those and the parts that it adds.
/// Every operation changes the main document part. A comment and an image also change the main
/// part's relationships part (or add it, when the file had none), the content types part and,
/// for a comment, the part that the main part's comments relationship names; a comment adds
/// that part when the file had none, and an image adds its image part.
fn other_parts_kept(operation: Operation, before: &[u8], after: &[u8]) -> bool {
    let limits = Limits::default();
    let (Ok(before), Ok(after)) = (
        Package::open(before, &limits),
        Package::open(after, &limits),
    ) else {
        return false;
    };
    let Ok(main) = before.main_document() else {
        return false;
    };
    let mut changed = vec![main.clone()];
    let mut added = 0;
    if operation.adds_parts() {
        let relationships = relationships_part(&main);
        added = 1 + usize::from(before.part(&relationships).is_none());
        changed.extend([relationships, CONTENT_TYPES.to_owned()]);
        changed.extend(comments_part(&after, &main));
    }
    let is_changed = |name: &str| changed.iter().any(|part| part.eq_ignore_ascii_case(name));
    after.part_names().count() <= before.part_names().count() + added
        && before.part_names().all(|name| {
            after.part(name).is_some()
                && (is_changed(name) || before.part(name) == after.part(name))
        })
}

/// The name of the part that the comments relationship of the main document part `main` of
/// `package` names, if it has one.
fn comments_part(package: &Package, main: &str) -> Option<String> {
    package
        .relationships(main)
        .ok()?
        .relationships
        .iter()
        .find(|relationship| !relationship.external && relationship.rel_type.ends_with("/comments"))
        .map(|relationship| relationship.target.clone())
}

/// The paragraphs of the body outside tables, each with its style and text.
fn body_paragraphs(blocks: &[TextBlock]) -> impl Iterator<Item = (&TextBlock, Option<&str>, &str)> {
    blocks
        .iter()
        .filter(|block| block.address.steps().len() == 1)
        .filter_map(paragraph)
}

/// The block with its style and text, when it is a paragraph.
fn paragraph(block: &TextBlock) -> Option<(&TextBlock, Option<&str>, &str)> {
    match &block.kind {
        TextBlockKind::Paragraph { style, text } => Some((block, style.as_deref(), text)),
        _ => None,
    }
}

/// The address of the first paragraph of the body whose text is not empty.
fn first_text_paragraph(blocks: &[TextBlock]) -> Option<Address> {
    body_paragraphs(blocks)
        .find(|(_, _, text)| !text.is_empty())
        .map(|(block, _, _)| block.address.clone())
}

/// The paragraph and the word of [`Operation::Replace`].
fn replace_word(blocks: &[TextBlock]) -> Option<(&TextBlock, &str)> {
    blocks
        .iter()
        .filter_map(paragraph)
        .find_map(|(block, _, text)| once_word(text).map(|word| (block, word)))
}

/// The address of the first cell of the first table of the body: the cell of the first block
/// whose address has the four steps of a paragraph in a cell of a table of the body.
fn first_cell(blocks: &[TextBlock]) -> Option<Address> {
    let paragraph = blocks
        .iter()
        .find(|block| block.address.steps().len() == 4)?
        .address
        .to_string();
    paragraph.rsplit_once('/')?.0.parse().ok()
}

/// The address of the first row of the first table of the body.
fn first_row(blocks: &[TextBlock]) -> Option<Address> {
    body_tables(blocks)
        .find(|(_, rows)| *rows > 0)
        .and_then(|(block, _)| row_address(block, 0))
}

/// The tables of the body, each with its number of rows.
fn body_tables(blocks: &[TextBlock]) -> impl Iterator<Item = (&TextBlock, usize)> {
    blocks
        .iter()
        .filter(|block| block.address.steps().len() == 1)
        .filter_map(|block| match block.kind {
            TextBlockKind::Table { rows } => Some((block, rows)),
            _ => None,
        })
}

/// The address of the row of the index `index` of the table `table`.
fn row_address(table: &TextBlock, index: usize) -> Option<Address> {
    format!("{}/r{}", table.address, index + 1).parse().ok()
}

/// The address of the row of [`Operation::GridRow`] in the file `docx`, whose text blocks are
/// `blocks`: the row elements whose properties give a grid before or after, found by the span
/// of each row that the blocks of the tables give.
fn grid_row(docx: &[u8], blocks: &[TextBlock]) -> Option<Address> {
    let package = Package::open(docx, &Limits::default()).ok()?;
    let main = package.main_document().ok()?;
    let xml = Xml::parse(package.part(&main)?, &package.limits().xml).ok()?;
    let starts = grid_row_starts(&xml)?;
    body_tables(blocks).find_map(|(table, _)| {
        let index = table.row_sources.iter().position(|source| {
            source
                .as_ref()
                .is_some_and(|source| starts.contains(&source.start))
        })?;
        row_address(table, index)
    })
}

/// The offsets of the row elements of the main document part `xml` whose `w:trPr` gives a
/// `w:gridBefore` or a `w:gridAfter` of more than zero grid columns, in the namespace of the
/// document element, which is the main namespace in both spellings of WordprocessingML.
fn grid_row_starts(xml: &Xml) -> Option<HashSet<usize>> {
    let root = xml.root().ok()?;
    let w = xml.namespace_uri(xml.element(root)?.name.namespace?);
    let mut starts = HashSet::new();
    let mut stack: Vec<NodeId> = vec![root];
    while let Some(node) = stack.pop() {
        if xml.is(node, w, "tr") && has_grid_edge(xml, w, node) {
            starts.extend(xml.span(node).ok().map(|span| span.start));
        }
        stack.extend(xml.child_elements(node));
    }
    Some(starts)
}

/// Whether the row `row` gives a grid before or after it of more than zero grid columns.
fn has_grid_edge(xml: &Xml, w: &str, row: NodeId) -> bool {
    xml.child(row, w, "trPr").is_some_and(|properties| {
        ["gridBefore", "gridAfter"].into_iter().any(|local| {
            xml.child(properties, w, local)
                .and_then(|edge| xml.attribute(edge, Some(w), "val"))
                .and_then(|value| value.trim().parse::<u32>().ok())
                .is_some_and(|columns| columns > 0)
        })
    })
}

/// The edit of [`Operation::InsertRow`] at the row `at`.
fn new_row(at: Address) -> NamedEdit {
    NamedEdit::InsertRow {
        at,
        place: Place::After,
        cells: vec![NEW_CELL.to_owned()],
    }
}

/// The comment of [`Operation::Comment`] at `at`, on the one match of `find` when given.
fn comment(at: Address, find: Option<String>) -> NamedEdit {
    let (text, author) = COMMENT;
    NamedEdit::Comment {
        at,
        text: text.to_owned(),
        find,
        author: author.to_owned(),
    }
}

/// The PNG file of [`Operation::Image`], made once.
fn check_image() -> Option<&'static [u8]> {
    static FILE: OnceLock<Option<Vec<u8>>> = OnceLock::new();
    FILE.get_or_init(|| {
        let (width, height) = IMAGE_PIXELS;
        let pixels = vec![IMAGE_GRAY; usize::try_from(u64::from(width) * u64::from(height)).ok()?];
        let mut file = Vec::new();
        PngEncoder::new(&mut file)
            .write_image(&pixels, width, height, ExtendedColorType::L8)
            .ok()?;
        Some(file)
    })
    .as_deref()
}

/// The first word of `text`, a run of letters and digits, of at least [`MIN_WORD_CHARS`]
/// characters that `text` holds only once and that no brace touches.
fn once_word(text: &str) -> Option<&str> {
    text.split(|c: char| !c.is_alphanumeric())
        .filter(|word| word.chars().count() >= MIN_WORD_CHARS)
        .find(|word| {
            let mut found = text.match_indices(word);
            match (found.next(), found.next()) {
                (Some((start, _)), None) => {
                    !text[..start].ends_with('{') && !text[start + word.len()..].starts_with('}')
                }
                _ => false,
            }
        })
}

/// The edit of [`Operation::Style`].
fn style(blocks: &[TextBlock]) -> Option<NamedEdit> {
    let style = body_paragraphs(blocks).find_map(|(_, style, _)| style)?;
    let (block, _, _) = body_paragraphs(blocks).find(|(_, other, _)| *other != Some(style))?;
    Some(NamedEdit::Style {
        at: block.address.clone(),
        style: style.to_owned(),
    })
}

/// The edit of [`Operation::Delete`].
fn delete(blocks: &[TextBlock]) -> Option<NamedEdit> {
    let body: Vec<&TextBlock> = blocks
        .iter()
        .filter(|block| block.address.steps().len() == 1)
        .collect();
    let inner = body.get(1..body.len().saturating_sub(1))?;
    inner
        .iter()
        .filter_map(|block| paragraph(block))
        .find(|(_, _, text)| !text.is_empty())
        .map(|(block, _, _)| NamedEdit::Delete {
            at: block.address.clone(),
        })
}

/// The kind of an edit's fault, for the counts: a short name, with the element's name for a
/// match that crosses an element or for a range end.
fn fault_kind(fault: &EditFault) -> String {
    let kind = match fault {
        EditFault::Named(fault) => return named_kind(fault),
        EditFault::TooManyEdits { .. } => "too-many-edits",
        EditFault::Package(_) => "package",
        EditFault::XmlTooLarge { .. } => "xml-too-large",
        EditFault::NoSuchPart(_) => "no-such-part",
        EditFault::PartNotXml(_) => "part-not-xml",
        EditFault::PartNotUtf8(_) => "part-not-utf8",
        EditFault::UndeclaredPathPrefix(_) => "undeclared-path-prefix",
        EditFault::NoElement { .. } => "no-element",
        EditFault::Ambiguous { .. } => "ambiguous",
        EditFault::ExpectNotXml(_) => "expect-not-xml",
        EditFault::ExpectNotOneElement => "expect-not-one-element",
        EditFault::ExpectDiffers => "expect-differs",
        EditFault::XmlNotValid(_) => "xml-not-valid",
        EditFault::Overlap { .. } => "overlap",
        EditFault::PartBroken(_) => "part-broken",
        EditFault::Write(_) => "write",
    };
    kind.to_owned()
}

/// The kind of a named edit's fault, as [`fault_kind`] names it.
fn named_kind(fault: &NamedFault) -> String {
    let kind = match fault {
        NamedFault::MatchCrossesElement { element } => return format!("match crosses {element}"),
        NamedFault::MatchCrossesEdge { element } => {
            return format!("match crosses the edge of {element}");
        }
        NamedFault::RangeEnd { element } => return format!("range end {element}"),
        NamedFault::MainPart(_) => "main-part",
        NamedFault::TrackedChanges => "tracked-changes",
        NamedFault::NoBlock(_) => "no-block",
        NamedFault::OutsideBody(_) => "outside-body",
        NamedFault::WrongKind { .. } => "wrong-kind",
        NamedFault::NoElement(_) => "no-element",
        NamedFault::NoPrefix => "no-prefix",
        NamedFault::EmptyFind => "empty-find",
        NamedFault::TextNotFound => "text-not-found",
        NamedFault::TextNotFoundOutsideEquations => "text-not-found-outside-equations",
        NamedFault::TextAmbiguous { .. } => "text-ambiguous",
        NamedFault::MatchesOverlap { .. } => "matches-overlap",
        NamedFault::BadCharacter(_) => "bad-character",
        NamedFault::SectionBreak => "section-break",
        NamedFault::NeedsParagraph => "needs-paragraph",
        NamedFault::LastRow => "last-row",
        NamedFault::NoSuchStyle { .. } => "no-such-style",
        NamedFault::NewXml(_) => "new-xml",
        NamedFault::WrappedCells => "wrapped-cells",
        NamedFault::TooManyCells { .. } => "too-many-cells",
        NamedFault::MergedCellText { .. } => "merged-cell-text",
        NamedFault::EmptyAuthor => "empty-author",
        NamedFault::EmptyAlt => "empty-alt",
        NamedFault::ImageSize => "image-size",
        NamedFault::NoFreeId(_) => "no-free-id",
        NamedFault::Part { .. } => "part",
        _ => "other",
    };
    kind.to_owned()
}

#[cfg(test)]
mod tests;