f-office-docx 0.3.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
//! The category labels below a plot area where the target's quirk `ChartPlotArea` is
//! `FontLines`. Each label is wrapped at its spaces into lines that fit in its category width,
//! the plot area's width over the number of categories, and each line is centered on its
//! category's middle. When a word of a label is wider than the category width, every label
//! stands on one line turned counterclockwise and its line box ends centered below its
//! category's middle: turned 45 degrees, or 90 degrees where the category width over the square
//! root of two is less than the labels' win line. Labels turned 45 degrees that would pass
//! their categories' middles by more than the room at the frame's left move the plot area's
//! left edge right.

use f_office_paint::{Glyph, GlyphRun, Item, Rgb, Turn};
use f_office_units::{Edges, Length};

use super::labels::ChartText;
use super::{LabelLines, chart_props};
use crate::chart::{ChartGroup, Columns, PlotPlace};
use crate::layout::Layout;
use crate::params::CHART_TURNED_LABEL_CUT_SHARE;

/// How Word sets a chart's category labels in their category width.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum CategoryForm {
    /// Each label upright, on the lines into which it wraps: the lines of each label, none for
    /// an empty name.
    Upright(Vec<Vec<String>>),
    /// Every label on one line, turned 45 degrees counterclockwise: each label's width, zero
    /// for an empty name.
    Diagonal(Vec<Length>),
    /// Every label on one line, turned 90 degrees counterclockwise: the widest label's width.
    Vertical(Length),
}

impl CategoryForm {
    /// How far the labels reach below the plot area beyond one upright line of `lines`: a line
    /// for each line beyond the first of the label with the most lines, or for turned labels
    /// the height of the widest label's turned line box less a line.
    pub(super) fn room(&self, lines: LabelLines) -> Option<Length> {
        match self {
            Self::Upright(rows) => {
                let most = rows.iter().map(Vec::len).max().unwrap_or(1).max(1);
                lines.line.checked_mul(i64::try_from(most).ok()? - 1)
            }
            Self::Diagonal(widths) => {
                let widest = widths.iter().copied().max().unwrap_or(Length::ZERO);
                Some((diagonal(widest + lines.line)? - lines.line).max(Length::ZERO))
            }
            Self::Vertical(widest) => Some((*widest - lines.line).max(Length::ZERO)),
        }
    }

    /// How far labels turned 45 degrees reach left of the frame's left edge, with the
    /// categories of a plot area `span` wide that starts there: the most by which a label's
    /// width over the square root of two passes its category's middle's distance from the
    /// edge. `None` for labels of another form.
    pub(super) fn left_reach(&self, span: Length) -> Option<Length> {
        let Self::Diagonal(widths) = self else {
            return None;
        };
        let count = i64::try_from(widths.len()).ok()?.max(1);
        let mut reach: Option<Length> = None;
        for (index, width) in (0_i64..).zip(widths) {
            let middle = span
                .checked_mul(index.checked_mul(2)? + 1)?
                .div_toward_zero(count.checked_mul(2)?);
            let past = diagonal(*width)? - middle;
            reach = Some(reach.map_or(past, |reach| reach.max(past)));
        }
        reach
    }
}

/// The outcome of wrapping a label in a width.
enum Wrapped {
    /// The lines of the label.
    Lines(Vec<String>),
    /// A word alone is wider than the width.
    Wider,
}

impl Layout<'_> {
    /// The form of the category labels of `chart` below a plot area `span` wide in `frame`
    /// ([`Self::category_form`] in the category width, the span over the number of
    /// categories). `None` for horizontal bars and scatter charts, whose labels below are
    /// values, for a chart without cached category names, and for turned labels whose room
    /// below the plot area ([`Layout::below_base`], [`CategoryForm::room`] and
    /// [`Layout::legend_bottom`]) is more than [`CHART_TURNED_LABEL_CUT_SHARE`] of the frame's
    /// height, which Word cuts short.
    pub(super) fn below_form(
        &mut self,
        chart: &Columns,
        span: Length,
        frame: Edges<Length>,
    ) -> Option<CategoryForm> {
        let (
            ChartGroup::Columns { .. }
            | ChartGroup::Columns3D { .. }
            | ChartGroup::Lines { .. }
            | ChartGroup::Combo { .. },
            Some(names),
        ) = (&chart.group, &chart.category_names)
        else {
            return None;
        };
        let lines = self.label_lines(chart)?;
        let width = span.div_toward_zero(i64::try_from(names.len()).ok()?.max(1));
        let form = self.category_form(chart, width, lines.line)?;
        if matches!(form, CategoryForm::Upright(_)) {
            return Some(form);
        }
        let room = self.below_base(chart)?
            + form.room(lines)?
            + self.legend_bottom(chart, lines, frame)?;
        let (part, whole) = CHART_TURNED_LABEL_CUT_SHARE;
        let limit = (frame.bottom - frame.top).checked_mul(part)?;
        (room.checked_mul(whole)? <= limit).then_some(form)
    }

    /// How Word sets the category labels of `chart` in a category `width` wide
    /// ([`CategoryForm`]): turned when a word of a label is wider than the width
    /// ([`Self::turned_form`]), else upright with each label wrapped at its spaces, each line
    /// as many words as fit. `None` when the chart has no cached category names, when a label
    /// needs more than one face, and beside a manual plot area for labels that wrap or turn,
    /// whose room these rules do not place.
    pub(super) fn category_form(
        &mut self,
        chart: &Columns,
        width: Length,
        line: Length,
    ) -> Option<CategoryForm> {
        let names = chart.category_names.as_ref()?;
        let props = chart_props(chart, chart.label_size);
        let mut rows = Vec::with_capacity(names.len());
        let mut turned = false;
        for name in names {
            if name.is_empty() {
                rows.push(Vec::new());
                continue;
            }
            let wrap = wrapped(name, width, |text| {
                self.chart_text(&props, text).map(|shaped| shaped.width())
            })?;
            match wrap {
                Wrapped::Lines(lines) => rows.push(lines),
                Wrapped::Wider => turned = true,
            }
        }
        let automatic = chart.plot_place == PlotPlace::Automatic;
        if turned {
            return self.turned_form(chart, width, line).filter(|_| automatic);
        }
        (automatic || rows.iter().all(|lines| lines.len() <= 1))
            .then_some(CategoryForm::Upright(rows))
    }

    /// The turned form of the category labels of `chart` in a category `width` wide, for labels
    /// of a win `line`: by 45 degrees, or by 90 where the width over the square root of two is
    /// less than the line. `None` where the width is less than the line, where Word may leave
    /// labels out, which these rules do not choose.
    fn turned_form(
        &mut self,
        chart: &Columns,
        width: Length,
        line: Length,
    ) -> Option<CategoryForm> {
        let props = chart_props(chart, chart.label_size);
        let mut widths = Vec::new();
        for name in chart.category_names.iter().flatten() {
            widths.push(if name.is_empty() {
                Length::ZERO
            } else {
                self.chart_text(&props, name)?.width()
            });
        }
        if width < line {
            None
        } else if diagonal(width)? < line {
            let widest = widths.iter().copied().max().unwrap_or(Length::ZERO);
            Some(CategoryForm::Vertical(widest))
        } else {
            Some(CategoryForm::Diagonal(widths))
        }
    }

    /// The category labels below `anchor` (either `plot.bottom` or an interior category axis
    /// crossing) in `frame` in their form ([`Self::below_form`]): upright, each line centered by
    /// its width at the label size on its category's middle, the first line's baseline
    /// [`LabelLines::category_baseline`] below `anchor` and each next line's one win line lower;
    /// or turned ([`Self::turned_category`]).
    pub(super) fn category_labels(
        &mut self,
        chart: &Columns,
        (plot, anchor, frame): (Edges<Length>, Length, Edges<Length>),
        lines: LabelLines,
    ) -> Option<Vec<Item>> {
        let names = chart.category_names.as_ref()?;
        let count = i64::try_from(names.len()).ok()?;
        let span = plot.right - plot.left;
        let form = self.below_form(chart, span, frame)?;
        let color = self.label_color(chart.category_label_fill.as_ref());
        let mut items = Vec::new();
        for (index, name) in (0_i64..).zip(names) {
            if name.is_empty() {
                continue;
            }
            let share = span.checked_mul(index.checked_mul(2)? + 1)?;
            let middle = plot.left + share.div_toward_zero(count * 2);
            let place = (middle, anchor, lines);
            items.extend(self.category_items(chart, (&form, index, name), color, place)?);
        }
        Some(items)
    }

    /// The items of the label `name` of the category `index` in the form `form`, in `color`,
    /// below the category's `middle` and the plot area's `bottom`.
    fn category_items(
        &mut self,
        chart: &Columns,
        (form, index, name): (&CategoryForm, i64, &str),
        color: Rgb,
        (middle, bottom, lines): (Length, Length, LabelLines),
    ) -> Option<Vec<Item>> {
        match form {
            CategoryForm::Upright(rows) => {
                let rows = rows.get(usize::try_from(index).ok()?)?;
                let baseline = bottom + lines.category_baseline()?;
                self.upright_category(chart, rows, color, (middle, baseline, lines))
            }
            CategoryForm::Diagonal(_) => Some(vec![self.turned_category(
                chart,
                name,
                color,
                (middle, bottom, lines),
            )?]),
            CategoryForm::Vertical(_) => Some(vec![self.vertical_category(
                chart,
                name,
                color,
                (middle, bottom, lines),
            )?]),
        }
    }

    /// The lines `rows` of an upright category label in `color`, each centered by its width at
    /// the label size on the category's `middle`, the first on the `baseline` and each next
    /// one win line of `lines` lower.
    fn upright_category(
        &mut self,
        chart: &Columns,
        rows: &[String],
        color: Rgb,
        (middle, baseline, lines): (Length, Length, LabelLines),
    ) -> Option<Vec<Item>> {
        let mut items = Vec::with_capacity(rows.len());
        for (row, text) in (0_i64..).zip(rows) {
            let down = baseline + lines.line.checked_mul(row)?;
            items.push(self.chart_label(chart, text, color, |width| {
                Some((middle - width.div_toward_zero(2), down))
            })?);
        }
        Some(items)
    }

    /// The category label `name` turned 45 degrees counterclockwise, in `color`: its line box,
    /// its width at the label size by a win line of `lines`, turns about the middle of its end,
    /// which lies on the category's `middle` across, and the box's top corner lies where an
    /// upright label's line box starts, [`LabelLines::category_baseline`] less the top below
    /// the plot area's `bottom`.
    fn turned_category(
        &mut self,
        chart: &Columns,
        name: &str,
        color: Rgb,
        (middle, bottom, lines): (Length, Length, LabelLines),
    ) -> Option<Item> {
        let shaped = self.chart_text(&chart_props(chart, chart.label_size), name)?;
        let half = lines.line.div_toward_zero(2);
        let end_middle = bottom + lines.category_baseline()? - lines.top + diagonal(half)?;
        // From the end's middle down the glyphs to the baseline, then back along the text.
        let to_baseline = diagonal(lines.top - half)?;
        let along = diagonal(shaped.width())?;
        let start = (
            middle + to_baseline - along,
            end_middle + to_baseline + along,
        );
        let part = diagonal_part()?;
        let turn = Turn {
            xx: part,
            yx: -part,
            xy: part,
            yy: part,
        };
        shaped.turned_item(start, (turn, color), |reached| {
            diagonal(reached).map(|step| (step, -step))
        })
    }

    /// The category label `name` turned 90 degrees counterclockwise, in `color`: its line box,
    /// its width at the label size by a win line of `lines`, is centered across on the
    /// category's `middle`, and its end lies where an upright label's line box starts,
    /// [`LabelLines::category_baseline`] less the top below the plot area's `bottom`.
    fn vertical_category(
        &mut self,
        chart: &Columns,
        name: &str,
        color: Rgb,
        (middle, bottom, lines): (Length, Length, LabelLines),
    ) -> Option<Item> {
        let shaped = self.chart_text(&chart_props(chart, chart.label_size), name)?;
        let half = lines.line.div_toward_zero(2);
        let start = (
            middle + lines.top - half,
            bottom + lines.category_baseline()? - lines.top + shaped.width(),
        );
        shaped.turned_item(start, (UPWARD, color), |reached| {
            Some((Length::ZERO, -reached))
        })
    }
}

/// The turn of a text that reads upward: a quarter turn counterclockwise.
pub(super) const UPWARD: Turn = Turn {
    xx: 0,
    yx: -Turn::SCALE,
    xy: Turn::SCALE,
    yy: 0,
};

impl ChartText {
    /// The glyph run of the text under `turn`, in `color`, its first glyph's origin at `start`
    /// and each next glyph's moved by `step` of the advances before it along the turned baseline.
    pub(super) fn turned_item(
        self,
        (x, y): (Length, Length),
        (turn, color): (Turn, Rgb),
        mut step: impl FnMut(Length) -> Option<(Length, Length)>,
    ) -> Option<Item> {
        let (font, size) = (self.font, self.size);
        let mut shown = String::new();
        let mut glyphs = Vec::with_capacity(self.glyphs.len());
        let mut reached = self.lead;
        for ((id, text), advance) in self.glyphs.into_iter().zip(self.advances) {
            let (across, down) = step(reached)?;
            let text_start = u32::try_from(shown.len()).ok()?;
            shown.push_str(&text);
            glyphs.push(Glyph {
                id,
                x: x + across,
                y: y + down,
                text_start,
                text_end: u32::try_from(shown.len()).ok()?,
            });
            reached += advance;
        }
        Some(Item::Glyphs(GlyphRun {
            font,
            size,
            color,
            text: shown,
            glyphs,
            outline: None,
            filled: true,
            effect: false,
            turn: Some(turn),
        }))
    }
}

/// `length` over the square root of two, toward zero: a side of the square whose diagonal it
/// is, the reach across or down of a step of that length at 45 degrees.
pub(super) fn diagonal(length: Length) -> Option<Length> {
    diagonal_units(length.units()).map(Length::from_units)
}

/// The entry of a turn by 45 degrees: [`Turn::SCALE`] over the square root of two, to the
/// nearest millionth, so that the turn keeps the em's height, as a reader of a PDF finds it.
fn diagonal_part() -> Option<i32> {
    let scale = i64::from(Turn::SCALE);
    let side = diagonal_units(scale)?;
    let next = side.checked_mul(2)? + 1;
    let nearest = if next.checked_mul(next)? < scale.checked_mul(scale)?.checked_mul(2)? {
        side + 1
    } else {
        side
    };
    i32::try_from(nearest).ok()
}

/// `units` over the square root of two, toward zero.
fn diagonal_units(units: i64) -> Option<i64> {
    let square = i128::from(units).checked_mul(i128::from(units))? / 2;
    let side = i64::try_from(square.isqrt()).ok()?;
    Some(if units < 0 { -side } else { side })
}

/// `text` wrapped at its spaces into lines whose `measure` is at most `width`: each line takes
/// the next word while the line with it fits. [`Wrapped::Wider`] when a word alone is wider;
/// `None` when `measure` gives no width.
fn wrapped(
    text: &str,
    width: Length,
    mut measure: impl FnMut(&str) -> Option<Length>,
) -> Option<Wrapped> {
    let mut rows: Vec<String> = Vec::new();
    for word in text.split(' ') {
        if let Some(last) = rows.last_mut() {
            let joined = format!("{last} {word}");
            if measure(&joined)? <= width {
                *last = joined;
                continue;
            }
        }
        if measure(word)? > width {
            return Some(Wrapped::Wider);
        }
        rows.push(word.to_owned());
    }
    Some(Wrapped::Lines(rows))
}

#[cfg(test)]
pub(super) fn wrapped_lines(
    text: &str,
    width: Length,
    measure: impl FnMut(&str) -> Option<Length>,
) -> Option<Vec<String>> {
    match wrapped(text, width, measure)? {
        Wrapped::Lines(lines) => Some(lines),
        Wrapped::Wider => None,
    }
}