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
//! SmartArt graphics (`dgm:relIds`). Word saves the shapes of a SmartArt graphic and their text
//! in a drawing part (`dsp:drawing`), which F-Office draws as a group of shapes with text boxes.

use std::collections::HashMap;

use f_office_drawingml::color::{DrawColor, percentage};
use f_office_drawingml::shape::ShapeLook;
use f_office_drawingml::theme::ShapeTheme;
use f_office_units::scale::{DRAWING_WHOLE, HALF_POINTS_PER_POINT, LINE, PERCENT};
use f_office_units::{Edges, Length, div_round};
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};

use crate::body::{Block, Content, DrawingMut, Paragraph, Run, visit_drawings};
use crate::floating::{BoxText, Floating, TextAnchor, body_insets};
use crate::ns::{A, DGM, DSP, R};
use crate::params::{DRAWING_FONT_SIZE, DRAWING_LINE_SCALE};
use crate::props::{Alignment, Color, FontRef, LineSpacing, ParaProps, RunProps, Underline};
use crate::reader::{PartReader, attribute};
use crate::warnings::ReadAs;

/// The parts of a drawing group, each with its offset from the group's top left corner.
pub type Parts = Vec<(Length, Length, Floating)>;

/// The relationship IDs of the parts of a SmartArt graphic that F-Office reads.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Diagram {
    /// The data part (`r:dm`), which names the saved drawing.
    pub data: String,
    /// The colors part (`r:cs`), which gives the text colors of the style labels.
    pub colors: Option<String>,
}

/// The parts of a SmartArt graphic (`dgm:relIds`) in a `a:graphicData`.
#[must_use]
pub fn diagram(doc: &Document, graphic_data: NodeId) -> Option<Diagram> {
    let ids = doc.child(graphic_data, DGM, "relIds")?;
    Some(Diagram {
        data: doc.attribute(ids, Some(R), "dm")?.to_owned(),
        colors: doc.attribute(ids, Some(R), "cs").map(str::to_owned),
    })
}

/// The text color of each shape of a saved drawing, by its `modelId`: the first text fill
/// (`dgm:txFillClrLst`) that the colors part, which `reader` reads, gives the style label
/// (`presStyleLbl`) of the shape's point in the data part. A label without a text fill gives
/// none.
#[must_use]
pub(crate) fn text_colors(
    (data, data_root): (&Document, NodeId),
    (reader, colors_root): (&mut PartReader, NodeId),
    theme: &ShapeTheme,
) -> HashMap<String, Color> {
    let colors = reader.doc;
    let mut fills: HashMap<&str, Color> = HashMap::new();
    for label in doc_children(colors, colors_root, DGM, "styleLbl") {
        let fill = colors
            .child(label, DGM, "txFillClrLst")
            .and_then(|list| color_of(reader, list, theme));
        if let (Some(name), Some(fill)) = (colors.attribute(label, None, "name"), fill) {
            fills.insert(name, fill);
        }
    }
    let mut by_model = HashMap::new();
    let points = data.child(data_root, DGM, "ptLst");
    for point in points
        .into_iter()
        .flat_map(|list| doc_children(data, list, DGM, "pt"))
    {
        let label = data
            .child(point, DGM, "prSet")
            .and_then(|set| data.attribute(set, None, "presStyleLbl"));
        let model = data.attribute(point, None, "modelId");
        if let (Some(model), Some(fill)) = (model, label.and_then(|l| fills.get(l))) {
            by_model.insert(model.to_owned(), *fill);
        }
    }
    by_model
}

fn doc_children<'a>(
    doc: &'a Document,
    node: NodeId,
    namespace: &'a str,
    name: &'a str,
) -> impl Iterator<Item = NodeId> + 'a {
    doc.child_elements(node)
        .filter(move |child| doc.is(*child, namespace, name))
}

/// The relationship ID of the drawing part that a data part names (`dsp:dataModelExt`).
#[must_use]
pub fn drawing_id(doc: &Document, root: NodeId) -> Option<String> {
    let list = doc.child(root, DGM, "extLst")?;
    doc.child_elements(list)
        .filter_map(|ext| doc.child(ext, DSP, "dataModelExt"))
        .find_map(|node| doc.attribute(node, None, "relId"))
        .map(str::to_owned)
}

/// Gives each SmartArt graphic in `blocks`, also inside tables, text boxes and groups, the
/// parts that `find` reads from the saved drawing of its data part.
pub fn attach_drawings(blocks: &mut [Block], find: &mut dyn FnMut(&Diagram) -> Parts) {
    visit_drawings(blocks, &mut |drawing| {
        if let DrawingMut::Floating(floating) = drawing
            && let Some(diagram) = &floating.diagram
        {
            floating.parts = find(diagram);
        }
    });
}

/// The shapes of a drawing part, each as a part of a drawing group with its offset: the shape
/// with its look, and its text in a box of its own (`dsp:txXfrm`).
pub(crate) fn read_drawing(
    reader: &mut PartReader,
    root: NodeId,
    theme: &ShapeTheme,
    text_colors: &HashMap<String, Color>,
) -> Parts {
    let mut parts = Vec::new();
    if let Some(tree) = reader.doc.child(root, DSP, "spTree") {
        let context = Context { theme, text_colors };
        shapes(reader, tree, &context, &mut parts);
    }
    parts
}

/// What the shapes of a drawing part read from the rest of the package.
struct Context<'a> {
    theme: &'a ShapeTheme,
    text_colors: &'a HashMap<String, Color>,
}

fn shapes(reader: &mut PartReader, tree: NodeId, context: &Context, parts: &mut Parts) {
    let doc = reader.doc;
    for child in doc.child_elements(tree) {
        if doc.is(child, DSP, "grpSp") {
            shapes(reader, child, context, parts);
        } else if doc.is(child, DSP, "sp") {
            shape(reader, child, context, parts);
        }
    }
}

/// The box of an `a:off` and `a:ext` pair under `node`, none when a length is missing or does
/// not read.
fn frame(reader: &mut PartReader, node: NodeId) -> Option<Edges<Length>> {
    let doc = reader.doc;
    let mut value = |child: &str, name: &str| {
        let node = doc.child(node, A, child)?;
        reader.emu_length(node, name)
    };
    Edges::placed(
        value("off", "x")?,
        value("off", "y")?,
        value("ext", "cx")?,
        value("ext", "cy")?,
    )
}

fn shape(reader: &mut PartReader, sp: NodeId, context: &Context, parts: &mut Parts) {
    let doc = reader.doc;
    let theme = context.theme;
    let props = doc.child(sp, DSP, "spPr");
    let style = doc.child(sp, DSP, "style");
    let Some(shape_box) = props
        .and_then(|p| doc.child(p, A, "xfrm"))
        .and_then(|x| frame(reader, x))
    else {
        return;
    };
    // F-Office does not draw a picture fill of a shape of a SmartArt graphic.
    reader.warn_of_picture_fill(props);
    parts.push((
        shape_box.left,
        shape_box.top,
        Floating {
            width: shape_box.width(),
            height: shape_box.height(),
            look: Some(ShapeLook::read(
                doc,
                (props, style),
                reader.drawing_warnings(),
            )),
            ..Floating::in_part(reader.part())
        },
    ));
    let Some(text) = doc.child(sp, DSP, "txBody") else {
        return;
    };
    let text_box = doc
        .child(sp, DSP, "txXfrm")
        .and_then(|t| frame(reader, t))
        .unwrap_or(shape_box);
    // The text takes the font that the style refers to, and the text color of the shape's
    // style label, or else the color that the style refers to.
    let font_ref = style.and_then(|s| doc.child(s, A, "fontRef"));
    let label_color = doc
        .attribute(sp, None, "modelId")
        .and_then(|id| context.text_colors.get(id))
        .copied();
    let base = Base {
        font: match font_ref.and_then(|f| doc.attribute(f, None, "idx")) {
            Some("major") => FontRef::MajorLatin,
            _ => FontRef::MinorLatin,
        },
        color: label_color.or_else(|| font_ref.and_then(|f| color_of(reader, f, theme))),
        scale: autofit_scale(reader, text),
    };
    let body = doc.child(text, A, "bodyPr");
    let anchor = TextAnchor::of(body.and_then(|b| doc.attribute(b, None, "anchor")));
    let blocks = doc
        .child_elements(text)
        .filter(|p| doc.is(*p, A, "p"))
        .map(|p| Block::Paragraph(paragraph(reader, p, &base, theme)))
        .collect();
    parts.push((
        text_box.left,
        text_box.top,
        Floating {
            width: text_box.width(),
            height: text_box.height(),
            blocks,
            insets: body_insets(reader, body, crate::params::TEXT_BOX_INSETS),
            anchor,
            box_text: BoxText::SmartArt,
            ..Floating::in_part(reader.part())
        },
    ));
}

/// What the text of a shape takes from its style and its body.
struct Base {
    font: FontRef,
    color: Option<Color>,
    /// The share of the font size that autofit leaves, in 100,000ths.
    scale: i64,
}

/// The share of the font size that `a:normAutofit fontScale` leaves, in 100,000ths: all of it
/// without one, and when the value does not read, with a warning.
fn autofit_scale(reader: &mut PartReader, text: NodeId) -> i64 {
    let doc = reader.doc;
    doc.child(text, A, "bodyPr")
        .and_then(|b| doc.child(b, A, "normAutofit"))
        .and_then(|n| reader.or_missing_in(n, (None, "fontScale"), percentage))
        .unwrap_or(DRAWING_WHOLE)
}

/// The color of the first color element under `node`, resolved against the theme, with the
/// warnings of its value in the reader's DrawingML warnings.
fn color_of(reader: &mut PartReader, node: NodeId, theme: &ShapeTheme) -> Option<Color> {
    let (rgb, _) =
        DrawColor::read(reader.doc, node, reader.drawing_warnings())?.resolve(&theme.colors)?;
    Some(Color::Rgb([rgb.r, rgb.g, rgb.b]))
}

/// `ST_TextAlignType`, the alignment of a paragraph of a drawing: the distributed alignment
/// (`dist`) is drawn justified, and the low justification (`justLow`) and the Thai distribution
/// (`thaiDist`) at the start; a missing name is the start.
const TEXT_ALIGN: &Values<Alignment> = &Values::new(&[
    own("l", Alignment::Start),
    own("ctr", Alignment::Center),
    own("r", Alignment::End),
    own("just", Alignment::Both),
    another("justLow", Alignment::Start),
    another("dist", Alignment::Both),
    another("thaiDist", Alignment::Start),
]);

/// Converts a DrawingML paragraph (`a:p`) into a paragraph that sets everything it needs, so
/// that the document's styles do not change it.
fn paragraph(reader: &mut PartReader, p: NodeId, base: &Base, theme: &ShapeTheme) -> Paragraph {
    let id = reader.paragraph_id();
    let doc = reader.doc;
    let ppr = doc.child(p, A, "pPr");
    let mut length = |name: &str| {
        ppr.and_then(|n| reader.emu_length(n, name))
            .unwrap_or(Length::ZERO)
    };
    let (indent_left, indent_first) = (length("marL"), length("indent"));
    let alignment = ppr
        .and_then(|n| reader.enumeration_in(n, (None, "algn"), TEXT_ALIGN))
        .unwrap_or(Alignment::Start);
    let mut runs: Vec<Run> = Vec::new();
    for child in doc.child_elements(p) {
        if doc.is(child, A, "r") || doc.is(child, A, "fld") {
            let props = run_props(reader, doc.child(child, A, "rPr"), base, theme);
            let text = doc
                .child(child, A, "t")
                .map_or_default(|t| doc.text_content(t));
            runs.push(Run::new(props, vec![Content::Text(text)]));
        } else if doc.is(child, A, "br") {
            let props = run_props(reader, doc.child(child, A, "rPr"), base, theme);
            runs.push(Run::new(props, vec![Content::LineBreak]));
        }
    }
    // A paragraph with text and a bullet character (`a:buChar`) starts with the bullet, the
    // first character of `char`, in the look of its first run, then a tab, which stops at the
    // hanging indent (`marL`).
    let bullet = ppr
        .and_then(|n| doc.child(n, A, "buChar"))
        .and_then(|n| doc.attribute(n, None, "char"))
        .and_then(|text| text.chars().next());
    let has_text = runs.iter().any(|run| {
        run.content
            .iter()
            .any(|content| matches!(content, Content::Text(text) if !text.is_empty()))
    });
    if let (Some(bullet), true, Some(first)) = (bullet, has_text, runs.first()) {
        let label = Run::new(
            first.props.clone(),
            vec![Content::Text(bullet.to_string()), Content::Tab],
        );
        runs.insert(0, label);
    }
    let mark = run_props(reader, doc.child(p, A, "endParaRPr"), base, theme);
    // Spacing given as a share of a line counts in lines of the paragraph's size, the size at
    // which its first run draws.
    let size = runs.first().map_or(&mark, |r| &r.props).drawn_half_points();
    let line = ppr
        .and_then(|n| doc.child(n, A, "lnSpc"))
        .and_then(|n| doc.child(n, A, "spcPct"))
        .and_then(|s| reader.or_missing_in(s, (None, "val"), percentage))
        .map_or(LineSpacing::Auto(LINE), |share| {
            let multiple = div_round(LINE.saturating_mul(share), DRAWING_WHOLE);
            LineSpacing::Auto(reader.bounded_line_multiple(multiple))
        });
    let mut spacing = |name: &str| -> Length {
        let Some(node) = ppr.and_then(|n| doc.child(n, A, name)) else {
            return Length::ZERO;
        };
        if let Some(points) = doc
            .child(node, A, "spcPts")
            .and_then(|s| reader.or_missing_in(s, (None, "val"), f_office_drawingml::integer))
        {
            return Length::from_units(points * Length::UNITS_PER_POINT / PERCENT);
        }
        let percent = doc.child(node, A, "spcPct");
        let share = percent
            .and_then(|s| reader.or_missing_in(s, (None, "val"), percentage))
            .unwrap_or(0);
        // A line is 1.2 times the font size. The product of a size and a share of the file is
        // taken in `i128`, and a spacing beyond the range of a length counts as missing.
        let (part, whole) = DRAWING_LINE_SCALE;
        let units = i128::from(size) * i128::from(Length::UNITS_PER_HALF_POINT) * i128::from(part)
            / i128::from(whole)
            * i128::from(share)
            / i128::from(DRAWING_WHOLE);
        let limit = Length::FILE_LIMIT;
        match i64::try_from(units) {
            Ok(units) if (-limit..=limit).contains(&units) => Length::from_units(units),
            _ => {
                if let Some(percent) = percent {
                    reader.invalid(percent, attribute("val"), ReadAs::Missing);
                }
                Length::ZERO
            }
        }
    };
    Paragraph {
        id,
        props: ParaProps {
            alignment: Some(alignment),
            before: Some(spacing("spcBef")),
            after: Some(spacing("spcAft")),
            line: Some(line),
            indent_left: Some(indent_left),
            indent_right: Some(Length::ZERO),
            indent_first: Some(indent_first),
            contextual_spacing: Some(false),
            mark,
            ..ParaProps::default()
        },
        runs,
        source: crate::source_span::SourceSpan::NONE,
    }
}

/// The run properties of a DrawingML run (`a:rPr`), with the size, font and color that the
/// shape gives where the run gives none, and the smallest kerned size of its `kern`.
fn run_props(
    reader: &mut PartReader,
    rpr: Option<NodeId>,
    base: &Base,
    theme: &ShapeTheme,
) -> RunProps {
    let doc = reader.doc;
    let attribute = |name: &str| rpr.and_then(|n| doc.attribute(n, None, name));
    // `sz` counts in hundredths of a point, 18 pt by default. Its reader keeps it within 32
    // bits, and the autofit scale's within the 32 bits of `xsd:int`, so their product fits in
    // an `i64`. The size in half points then follows the rule of `w:sz`: above the largest
    // size it reads as the limit, with a warning, and a size of 0 or below stays.
    let hundredths = rpr
        .and_then(|n| reader.or_missing_in(n, (None, "sz"), f_office_drawingml::integer))
        .unwrap_or(DRAWING_FONT_SIZE * PERCENT);
    let size = reader.bounded_font_size(
        hundredths * base.scale / DRAWING_WHOLE / (PERCENT / HALF_POINTS_PER_POINT),
    );
    // `kern` names the smallest size, in hundredths of a point, at which the run is kerned
    // (ECMA-376 Part 1, 21.1.2.3.9), and a value below 0 does not read. The threshold in half
    // points is the smallest whole one at or above it, and 0 kerns every size. A run without
    // a value that reads keeps the `w:kern` that the layout gives it from the styles part.
    let per_half_point = PERCENT / HALF_POINTS_PER_POINT;
    let kern = rpr
        .and_then(|n| {
            reader.or_missing_in(n, (None, "kern"), |value| {
                f_office_drawingml::integer(value).filter(|hundredths| *hundredths >= 0)
            })
        })
        .map(|hundredths| ((hundredths + per_half_point - 1) / per_half_point).max(1));
    let on = |name: &str| attribute(name).is_some_and(f_office_drawingml::boolean);
    let font = rpr
        .and_then(|n| doc.child(n, A, "latin"))
        .and_then(|l| doc.attribute(l, None, "typeface"))
        .map_or(base.font.clone(), FontRef::of_typeface);
    let color = rpr
        .and_then(|n| doc.child(n, A, "solidFill"))
        .and_then(|fill| color_of(reader, fill, theme))
        .or(base.color);
    RunProps {
        font_ascii: Some(font.clone()),
        font_hansi: Some(font),
        size: Some(size),
        kern,
        bold: Some(on("b")),
        italic: Some(on("i")),
        underline: Some(if attribute("u").is_some_and(|u| u != "none") {
            Underline::Single
        } else {
            Underline::None
        }),
        color: Some(color.unwrap_or(Color::Auto)),
        ..RunProps::default()
    }
}

#[cfg(test)]
mod tests;