f-office 0.3.0

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
//! The JSON form of an edit list (the feature `json`): a list of objects, each with its
//! operation in `op`, such as
//! `[{"op": "replace", "at": "p12", "find": "30 days", "with": "45 days"}, {"op": "xml", "part": "word/styles.xml", "at": "w:style[@w:styleId='Heading1']", "expect": "...", "xml": "..."}]`.
//! A named edit's `at` is the address of a block of the body, such as `t2/r4`; a raw edit's is
//! a path in its part. The caller gives what the list does not hold ([`ListContext`]): the
//! author of the comments that name none, and the bytes of the image files that the image edits
//! name.

use std::fmt;

use f_office_units::Length;
use f_office_units::measure::universal_measure;
use f_office_units::scale::EMUS_PER_INCH;
use serde_json::{Map, Value};

use super::image::{ImageError, image_file};
use super::{Edit, EditLimits, NamedEdit, Path, PathError, Place, XmlEdit};
use crate::{Address, AddressError};

/// The operations of an edit list that F-Office makes.
const OPERATIONS: &str = "replace, set-text, insert-before, insert-after, insert-row-before, insert-row-after, insert-image-before, insert-image-after, comment, delete, style, xml";

/// The fields of a raw edit, besides `op`.
const XML_FIELDS: [&str; 4] = ["part", "at", "expect", "xml"];

/// The fields of a replace, besides `op`.
const REPLACE_FIELDS: [&str; 3] = ["at", "find", "with"];

/// The fields of an insert, besides `op`; `style` may be left out.
const INSERT_FIELDS: [&str; 3] = ["at", "text", "style"];

/// The fields of a delete, besides `op`.
const DELETE_FIELDS: [&str; 1] = ["at"];

/// The fields of a style edit, besides `op`.
const STYLE_FIELDS: [&str; 2] = ["at", "style"];

/// The fields of a set-text, besides `op`.
const SET_TEXT_FIELDS: [&str; 2] = ["at", "text"];

/// The fields of a new row, besides `op`; `cells` may be left out.
const ROW_FIELDS: [&str; 2] = ["at", "cells"];

/// The fields of a comment, besides `op`; `find` may be left out, and `author` when the
/// caller gives one ([`ListContext::author`]).
const COMMENT_FIELDS: [&str; 4] = ["at", "text", "find", "author"];

/// The fields of a new image, besides `op`; `width` and `height` may be left out.
const IMAGE_FIELDS: [&str; 5] = ["at", "image", "alt", "width", "height"];

/// What an edit list takes from its caller besides its JSON.
#[derive(Clone, Copy)]
pub struct ListContext<'c> {
    /// The author of each comment without an `author` field, such as the value of
    /// `foffice edit --author`; with none, such a comment is refused.
    pub author: Option<&'c str>,
    /// Reads the image file that the `image` field of an image edit names, or gives why it
    /// does not read.
    pub read_image: &'c dyn Fn(&str) -> Result<Vec<u8>, String>,
}

impl Default for ListContext<'_> {
    /// No author and no image files.
    fn default() -> Self {
        Self {
            author: None,
            read_image: &no_image_files,
        }
    }
}

/// The reader of image files of a caller that gives none.
fn no_image_files(_: &str) -> Result<Vec<u8>, String> {
    Err("the caller reads no image files".to_owned())
}

impl fmt::Debug for ListContext<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ListContext")
            .field("author", &self.author)
            .finish_non_exhaustive()
    }
}

/// Why bytes are not an edit list.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ListError {
    /// The list is larger than [`EditLimits::max_list_bytes`].
    TooLarge {
        /// The limit.
        limit: usize,
    },
    /// The list holds more edits than [`EditLimits::max_edits`].
    TooManyEdits {
        /// The limit.
        limit: usize,
    },
    /// The bytes are not JSON: the JSON reader's message, with the line and the column.
    Json(String),
    /// The JSON is not a list.
    NotAList,
    /// One entry of the list, by its index from 0, is not an edit.
    Entry {
        /// The entry's index.
        index: usize,
        /// What is wrong with it.
        fault: EntryFault,
    },
}

/// What is wrong with one entry of an edit list.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EntryFault {
    /// The entry is not an object.
    NotAnObject,
    /// The entry has no `op` text.
    NoOperation,
    /// The entry's `op` names no operation that F-Office makes.
    UnknownOperation(String),
    /// The entry lacks a field of its operation, or has one that is not text.
    Field(&'static str),
    /// The entry has a field that its operation does not take.
    UnknownField(String),
    /// The entry's `at` is not a path.
    Path(PathError),
    /// The `at` of a named edit is not an address.
    Address(AddressError),
    /// A comment has no `author` field, and the caller gives no author.
    NoAuthor,
    /// The `cells` of a new row is not a list of texts.
    Cells,
    /// A `width` or a `height` is not a length with its unit.
    Length(&'static str),
    /// The image file does not read: why, from the caller's reader.
    ImageFile(String),
    /// The file is not an image that an edit inserts.
    Image(ImageError),
}

impl fmt::Display for ListError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooLarge { limit } => write!(
                f,
                "the edit list is larger than {limit} bytes: split it into several lists"
            ),
            Self::TooManyEdits { limit } => write!(
                f,
                "the edit list holds more than {limit} edits: split it into several lists"
            ),
            Self::Json(message) => write!(f, "the edit list is not JSON: {message}"),
            Self::NotAList => {
                f.write_str("the edit list must be a JSON list of edits: [{...}, ...]")
            }
            Self::Entry { index, fault } => write!(f, "edit {index} of the list (from 0): {fault}"),
        }
    }
}

impl fmt::Display for EntryFault {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotAnObject => {
                f.write_str("an edit must be a JSON object such as {\"op\": \"xml\", ...}")
            }
            Self::NoOperation => write!(f, "the edit has no \"op\" text: give one of {OPERATIONS}"),
            Self::UnknownOperation(operation) => write!(
                f,
                "the operation {operation} is not one that F-Office makes: give one of {OPERATIONS}"
            ),
            Self::Field(field) => write!(f, "the edit needs the text field \"{field}\""),
            Self::UnknownField(field) => write!(
                f,
                "the edit has the field \"{field}\", which its operation does not take"
            ),
            Self::Path(error) => error.fmt(f),
            Self::Address(error) => error.fmt(f),
            Self::NoAuthor => f.write_str(
                "a comment needs an author: supply a default author or an \"author\" field in the edit",
            ),
            Self::Cells => f.write_str(
                "the field \"cells\" must be a list of texts, one for each of the first cells, such as [\"Total\", \"45\"]",
            ),
            Self::Length(field) => write!(
                f,
                "the field \"{field}\" must be a length with its unit, such as 8cm, 3in or 144pt"
            ),
            Self::ImageFile(why) => write!(f, "the image file does not read: {why}"),
            Self::Image(error) => error.fmt(f),
        }
    }
}

impl std::error::Error for ListError {}

/// Reads the edit list `json`, with the author and the image files of `context`.
///
/// # Errors
///
/// Returns [`ListError`] for a list beyond `limits`, for bytes that are not a JSON list, and for
/// an entry that is not an edit, with its index.
pub fn parse(
    json: &[u8],
    limits: &EditLimits,
    context: &ListContext<'_>,
) -> Result<Vec<Edit>, ListError> {
    if json.len() > limits.max_list_bytes {
        return Err(ListError::TooLarge {
            limit: limits.max_list_bytes,
        });
    }
    let value: Value =
        serde_json::from_slice(json).map_err(|error| ListError::Json(error.to_string()))?;
    let Value::Array(entries) = value else {
        return Err(ListError::NotAList);
    };
    if entries.len() > limits.max_edits {
        return Err(ListError::TooManyEdits {
            limit: limits.max_edits,
        });
    }
    entries
        .iter()
        .enumerate()
        .map(|(index, entry)| {
            edit(entry, limits, context).map_err(|fault| ListError::Entry { index, fault })
        })
        .collect()
}

/// The edit of one entry.
fn edit(entry: &Value, limits: &EditLimits, context: &ListContext<'_>) -> Result<Edit, EntryFault> {
    let Value::Object(fields) = entry else {
        return Err(EntryFault::NotAnObject);
    };
    let operation = fields
        .get("op")
        .and_then(Value::as_str)
        .ok_or(EntryFault::NoOperation)?;
    match operation {
        "xml" => xml(fields),
        "replace" => replace(fields),
        "insert-before" => insert(fields, Place::Before),
        "insert-after" => insert(fields, Place::After),
        "delete" => delete(fields),
        "style" => style(fields),
        "set-text" => set_text(fields),
        "insert-row-before" => row(fields, Place::Before),
        "insert-row-after" => row(fields, Place::After),
        "comment" => comment(fields, context),
        "insert-image-before" => image(fields, Place::Before, limits, context),
        "insert-image-after" => image(fields, Place::After, limits, context),
        other => Err(EntryFault::UnknownOperation(other.to_owned())),
    }
}

/// A raw edit.
fn xml(fields: &Map<String, Value>) -> Result<Edit, EntryFault> {
    known_fields(fields, &XML_FIELDS)?;
    Ok(Edit::Xml(XmlEdit {
        part: text(fields, "part")?.to_owned(),
        at: text(fields, "at")?
            .parse::<Path>()
            .map_err(EntryFault::Path)?,
        expect: text(fields, "expect")?.to_owned(),
        xml: text(fields, "xml")?.to_owned(),
    }))
}

/// A replace of a paragraph's text.
fn replace(fields: &Map<String, Value>) -> Result<Edit, EntryFault> {
    known_fields(fields, &REPLACE_FIELDS)?;
    Ok(Edit::Named(NamedEdit::Replace {
        at: address(fields)?,
        find: text(fields, "find")?.to_owned(),
        with: text(fields, "with")?.to_owned(),
    }))
}

/// A new paragraph at `place` of its block.
fn insert(fields: &Map<String, Value>, place: Place) -> Result<Edit, EntryFault> {
    known_fields(fields, &INSERT_FIELDS)?;
    Ok(Edit::Named(NamedEdit::Insert {
        at: address(fields)?,
        place,
        text: text(fields, "text")?.to_owned(),
        style: optional_text(fields, "style")?.map(str::to_owned),
    }))
}

/// A delete of a block or a row.
fn delete(fields: &Map<String, Value>) -> Result<Edit, EntryFault> {
    known_fields(fields, &DELETE_FIELDS)?;
    Ok(Edit::Named(NamedEdit::Delete {
        at: address(fields)?,
    }))
}

/// A new style of a paragraph or a table.
fn style(fields: &Map<String, Value>) -> Result<Edit, EntryFault> {
    known_fields(fields, &STYLE_FIELDS)?;
    Ok(Edit::Named(NamedEdit::Style {
        at: address(fields)?,
        style: text(fields, "style")?.to_owned(),
    }))
}

/// All the text of a paragraph or a cell.
fn set_text(fields: &Map<String, Value>) -> Result<Edit, EntryFault> {
    known_fields(fields, &SET_TEXT_FIELDS)?;
    Ok(Edit::Named(NamedEdit::SetText {
        at: address(fields)?,
        text: text(fields, "text")?.to_owned(),
    }))
}

/// A new row at `place` of its row.
fn row(fields: &Map<String, Value>, place: Place) -> Result<Edit, EntryFault> {
    known_fields(fields, &ROW_FIELDS)?;
    let cells = match fields.get("cells") {
        None => Vec::new(),
        Some(Value::Array(items)) => items
            .iter()
            .map(|item| item.as_str().map(str::to_owned).ok_or(EntryFault::Cells))
            .collect::<Result<_, _>>()?,
        Some(_) => return Err(EntryFault::Cells),
    };
    Ok(Edit::Named(NamedEdit::InsertRow {
        at: address(fields)?,
        place,
        cells,
    }))
}

/// A comment on a paragraph, by the entry's author or else the caller's.
fn comment(fields: &Map<String, Value>, context: &ListContext<'_>) -> Result<Edit, EntryFault> {
    known_fields(fields, &COMMENT_FIELDS)?;
    let author = optional_text(fields, "author")?
        .or(context.author)
        .ok_or(EntryFault::NoAuthor)?;
    Ok(Edit::Named(NamedEdit::Comment {
        at: address(fields)?,
        text: text(fields, "text")?.to_owned(),
        find: optional_text(fields, "find")?.map(str::to_owned),
        author: author.to_owned(),
    }))
}

/// A new image at `place` of its block, from the file that the caller reads.
fn image(
    fields: &Map<String, Value>,
    place: Place,
    limits: &EditLimits,
    context: &ListContext<'_>,
) -> Result<Edit, EntryFault> {
    known_fields(fields, &IMAGE_FIELDS)?;
    let at = address(fields)?;
    let alt = text(fields, "alt")?.to_owned();
    let size = (length(fields, "width")?, length(fields, "height")?);
    let data = (context.read_image)(text(fields, "image")?).map_err(EntryFault::ImageFile)?;
    let image = image_file(data, limits).map_err(EntryFault::Image)?;
    Ok(Edit::Named(NamedEdit::InsertImage {
        at,
        place,
        image,
        alt,
        size,
    }))
}

/// The length of the field `name`, if the entry has it: a universal measure, such as `8cm`.
fn length(fields: &Map<String, Value>, name: &'static str) -> Result<Option<Length>, EntryFault> {
    optional_text(fields, name)?
        .map(|value| {
            universal_measure(value, EMUS_PER_INCH)
                .and_then(Length::from_emus)
                .ok_or(EntryFault::Length(name))
        })
        .transpose()
}

/// The address of a named edit's `at`.
fn address(fields: &Map<String, Value>) -> Result<Address, EntryFault> {
    text(fields, "at")?
        .parse::<Address>()
        .map_err(EntryFault::Address)
}

/// Checks that each field is `op` or one of `known`.
fn known_fields(fields: &Map<String, Value>, known: &[&str]) -> Result<(), EntryFault> {
    match fields
        .keys()
        .find(|field| *field != "op" && !known.contains(&field.as_str()))
    {
        Some(field) => Err(EntryFault::UnknownField(field.clone())),
        None => Ok(()),
    }
}

/// The text of the field `name`, if the entry has it.
fn optional_text<'v>(
    fields: &'v Map<String, Value>,
    name: &'static str,
) -> Result<Option<&'v str>, EntryFault> {
    fields
        .get(name)
        .map(|value| value.as_str().ok_or(EntryFault::Field(name)))
        .transpose()
}

/// The text of the field `name`.
fn text<'v>(fields: &'v Map<String, Value>, name: &'static str) -> Result<&'v str, EntryFault> {
    fields
        .get(name)
        .and_then(Value::as_str)
        .ok_or(EntryFault::Field(name))
}