f-office-docx 0.2.1

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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! A drawn chart of horizontal bars, on a target whose quirk `ChartHorizontalBars` is
//! `Turned`: its column chart twin turned. The plot area keeps the twin's top and bottom and
//! starts after the widest category label as the twin's starts after the widest value label.
//! The value axis across the bottom takes its units and the plot area's right edge as a scatter
//! chart's x axis does ([`super::scatter`]). The categories' bands run up from the bottom, and
//! in each band the series' bars stand from the bottom up as a column chart's stand from the
//! left. The legend names the series in the reverse order ([`legend_order`]).

use f_office_paint::Item;
use f_office_units::scale::THOUSANDTHS;
use f_office_units::{Edges, Length};

use super::scatter::x_units;
use super::{
    BarDirection, DrawnText, LabelLines, ValueAxis, ZERO, chart_props, holds_all_data_labels, sum,
    ten_power,
};
use crate::chart::{BarStacking, ChartGroup, Columns, Decimal, LegendPlace, PlotPlace, Series};
use crate::layout::{Layout, decisions};

/// The decimal scale (`10^9`) used for 100%-stacked bar shares so each segment endpoint keeps
/// nine decimal places of precision and normalizes exact `1` and `-1` back to exponent 0.
pub(super) const SHARE_SCALE: i128 =
    (THOUSANDTHS as i128) * (THOUSANDTHS as i128) * (THOUSANDTHS as i128);
/// The exponent matching [`SHARE_SCALE`].
pub(super) const SHARE_EXPONENT: i32 = -(THOUSANDTHS.ilog10().cast_signed()
    + THOUSANDTHS.ilog10().cast_signed()
    + THOUSANDTHS.ilog10().cast_signed());

/// A grid of `(from, to)` value-axis endpoints for each `(series, category)` bar of a stacked or
/// 100%-stacked chart; `None` at a blank point.
pub(super) struct BarSegments(Vec<Vec<Option<(Decimal, Decimal)>>>);

impl BarSegments {
    /// Allocates an empty grid for `series` series and `categories` categories.
    fn empty(series: usize, categories: usize) -> Self {
        Self(vec![vec![None; categories]; series])
    }

    /// Writes `segment` for `(series, category)` when in bounds.
    fn set(&mut self, series: usize, category: usize, segment: (Decimal, Decimal)) {
        if let Some(slot) = self.0.get_mut(series).and_then(|row| row.get_mut(category)) {
            *slot = Some(segment);
        }
    }

    /// Reads the segment of `(series, category)`, or `None` when blank or out of bounds.
    pub(super) fn get(&self, series: i64, category: i64) -> Option<(Decimal, Decimal)> {
        let s = usize::try_from(series).ok()?;
        let c = usize::try_from(category).ok()?;
        *self.0.get(s)?.get(c)?
    }

    /// Every segment's outer cumulative endpoint `to`, for value-axis scaling.
    pub(super) fn outer_ends(&self) -> impl Iterator<Item = Decimal> + Clone + '_ {
        self.0.iter().flatten().flatten().map(|&(_, to)| to)
    }
}

/// Whether bars run individually from the crossing axis or between stacked segments.
pub(super) enum BarSpans {
    /// Clustered bars: each bar runs from `axis.crossing` to its value.
    Clustered,
    /// Stacked or 100%-stacked bars: each bar runs between its precomputed `(from, to)`.
    Stacked(BarSegments),
}

impl BarSpans {
    /// Computes the bar spans of `chart`, or `None` when stacked segment arithmetic overflows.
    pub(super) fn of(chart: &Columns) -> Option<Self> {
        match chart.group.stacking() {
            Some(BarStacking::Stacked | BarStacking::PercentStacked) => {
                Some(Self::Stacked(stacked_segments(chart)?))
            }
            _ => Some(Self::Clustered),
        }
    }

    /// The `(from, to)` value-axis endpoints of `(series, category)` with raw `value` and
    /// `crossing`, or `None` when stacked and out of bounds.
    pub(super) fn endpoints(
        &self,
        (series, category): (i64, i64),
        (crossing, value): (Decimal, Decimal),
    ) -> Option<(Decimal, Decimal)> {
        match self {
            Self::Clustered => Some((crossing, value)),
            Self::Stacked(segments) => segments.get(series, category),
        }
    }
}

/// The stacked `(from, to)` value-axis segments of `chart` when its group is stacked or
/// 100%-stacked, or `None` when a calculation overflows or the chart is not stacked.
pub(super) fn stacked_segments(chart: &Columns) -> Option<BarSegments> {
    match chart.group.stacking()? {
        BarStacking::Clustered => None,
        BarStacking::Stacked => sum_segments(chart),
        BarStacking::PercentStacked => percent_segments(chart),
    }
}

/// Cumulative `(from, to)` segments for a `stacked` chart: positive values stack above zero and
/// negative values stack below zero in series order, skipping blank points.
fn sum_segments(chart: &Columns) -> Option<BarSegments> {
    let bars = chart.bar_series();
    let mut segments = BarSegments::empty(bars.len(), chart.categories);
    for category in 0..chart.categories {
        let (mut pos, mut neg) = (ZERO, ZERO);
        for (series_idx, series) in bars.iter().enumerate() {
            let Some(value) = series.values.get(category).copied().flatten() else {
                continue;
            };
            let acc = if value.digits < 0 { &mut neg } else { &mut pos };
            let next = sum(*acc, value)?;
            segments.set(series_idx, category, (*acc, next));
            *acc = next;
        }
    }
    Some(segments)
}

/// Cumulative `(from, to)` share segments for a `percentStacked` chart: each category divides its
/// non-blank values by the sum of their magnitudes, stacking positive shares above zero and
/// negative shares below zero.
fn percent_segments(chart: &Columns) -> Option<BarSegments> {
    let mut segments = BarSegments::empty(chart.bar_series().len(), chart.categories);
    for category in 0..chart.categories {
        fill_percent_category(chart, category, &mut segments)?;
    }
    Some(segments)
}

/// Scaled non-blank values of one category for a 100%-stacked chart.
enum ScaledCategory {
    /// Every series is blank at this category.
    Empty,
    /// Scaled signed integer values (at a common exponent) and the sum of their absolute values.
    Values(Vec<Option<i128>>, i128),
}

/// Scales one category's non-blank series values to a common exponent and returns the scaled
/// values alongside the sum of their absolute magnitudes, or `None` on overflow.
fn scale_percent_category(series: &[Series], category: usize) -> Option<ScaledCategory> {
    let min_exp = series
        .iter()
        .filter_map(|s| s.values.get(category).copied().flatten())
        .map(|v| v.exponent)
        .min();
    let Some(min_exp) = min_exp else {
        return Some(ScaledCategory::Empty);
    };
    let mut scaled = Vec::with_capacity(series.len());
    let mut total = 0_i128;
    for one in series {
        let Some(value) = one.values.get(category).copied().flatten() else {
            scaled.push(None);
            continue;
        };
        let v = i128::from(value.digits).checked_mul(ten_power(value.exponent, min_exp)?)?;
        total = total.checked_add(v.checked_abs()?)?;
        scaled.push(Some(v));
    }
    Some(ScaledCategory::Values(scaled, total))
}

/// Computes one category's cumulative share segments into `segments`.
fn fill_percent_category(
    chart: &Columns,
    category: usize,
    segments: &mut BarSegments,
) -> Option<()> {
    let ScaledCategory::Values(scaled, total) =
        scale_percent_category(chart.bar_series(), category)?
    else {
        return Some(());
    };
    let (mut pos, mut neg) = (0_i128, 0_i128);
    for (series_idx, value) in scaled.into_iter().enumerate() {
        let Some(v) = value else {
            continue;
        };
        if total == 0 {
            segments.set(series_idx, category, (ZERO, ZERO));
            continue;
        }
        let acc = if v < 0 { &mut neg } else { &mut pos };
        let next = acc.checked_add(v)?;
        segments.set(
            series_idx,
            category,
            (share_decimal(*acc, total)?, share_decimal(next, total)?),
        );
        *acc = next;
    }
    Some(())
}

/// Cumulative plotted values for a stacked or 100%-stacked line group (`ChartGroup::Lines` or
/// the line group of `ChartGroup::Combo`), indexed `[line_series][category]`. Unlike stacked
/// bars, stacked lines accumulate algebraically across series in series order, treating blank
/// points in any non-empty category as zero. Returns an empty `Vec` when the line group is
/// unstacked, or `None` when decimal arithmetic overflows.
pub(super) fn stacked_line_values(chart: &Columns) -> Option<Vec<Vec<Option<Decimal>>>> {
    match chart.group.line_stacking() {
        Some(BarStacking::Stacked) => sum_line_values(chart.line_series(), chart.categories),
        Some(BarStacking::PercentStacked) => {
            percent_line_values(chart.line_series(), chart.categories)
        }
        _ => Some(Vec::new()),
    }
}

/// Algebraic cumulative sums for a `stacked` line group.
fn sum_line_values(lines: &[Series], categories: usize) -> Option<Vec<Vec<Option<Decimal>>>> {
    let mut out = vec![vec![None; categories]; lines.len()];
    for category in 0..categories {
        if lines
            .iter()
            .all(|s| s.values.get(category).copied().flatten().is_none())
        {
            continue;
        }
        let mut acc = ZERO;
        for (series, row) in lines.iter().zip(&mut out) {
            if let Some(value) = series.values.get(category).copied().flatten() {
                acc = sum(acc, value)?;
            }
            if let Some(slot) = row.get_mut(category) {
                *slot = Some(acc);
            }
        }
    }
    Some(out)
}

/// Algebraic cumulative shares for a `percentStacked` line group.
fn percent_line_values(lines: &[Series], categories: usize) -> Option<Vec<Vec<Option<Decimal>>>> {
    let mut out = vec![vec![None; categories]; lines.len()];
    for category in 0..categories {
        let ScaledCategory::Values(scaled, total) = scale_percent_category(lines, category)? else {
            continue;
        };
        let mut acc = 0_i128;
        for (value, row) in scaled.into_iter().zip(&mut out) {
            if let Some(v) = value {
                acc = acc.checked_add(v)?;
            }
            let plotted = if total == 0 {
                ZERO
            } else {
                share_decimal(acc, total)?
            };
            if let Some(slot) = row.get_mut(category) {
                *slot = Some(plotted);
            }
        }
    }
    Some(out)
}

/// `acc / total` as a normalized [`Decimal`] rounded half away from zero to nine decimal places.
fn share_decimal(acc: i128, total: i128) -> Option<Decimal> {
    let scaled = acc.checked_mul(SHARE_SCALE)?;
    let half = total / 2;
    let rounded = if scaled >= 0 {
        scaled.checked_add(half)? / total
    } else {
        scaled.checked_sub(half)? / total
    };
    Some(
        Decimal {
            digits: i64::try_from(rounded).ok()?,
            exponent: SHARE_EXPONENT,
        }
        .normalized(),
    )
}

impl Layout<'_> {
    /// The items of a chart of clustered horizontal bars with the gap and overlap
    /// `(gap, overlap)` in its frame `frame`, and which of its text they hold, as
    /// [`Self::columns`] gives them for a column chart. The value axis takes at most the units
    /// of [`x_units`] for the frame's width and the advance of the labels' zero. The plot area
    /// is the twin's ([`Self::label_plot`]) with the widest category label in the place of the
    /// widest value label, and it ends half the width of the last value label left of the
    /// twin's right edge. A deleted value axis ([`crate::chart::AxisForms::value_deleted`])
    /// draws no value labels: the plot area ends at the twin's right edge, and its bottom is
    /// that of a plot area without a band of labels below it. `None` when a step gives no place, and for an axis that the category
    /// axis crosses above its lowest value or a manual layout of the plot area, which these
    /// rules do not place.
    pub(super) fn horizontal_bars(
        &mut self,
        chart: &Columns,
        (gap, overlap): (i64, i64),
        frame: Edges<Length>,
    ) -> Option<(Vec<Item>, DrawnText)> {
        if chart.plot_place != PlotPlace::Automatic {
            return None;
        }
        let props = chart_props(chart, chart.value_label_size);
        let zero = self.chart_text(&props, "0")?.width();
        let most = x_units(frame.right - frame.left, zero);
        let axis = ValueAxis::for_chart(chart, most)?;
        if axis.crossing == axis.high
            && !chart.axis_forms.low_labels
            && !chart.axis_forms.category_hidden
        {
            return None;
        }
        let widest = if chart.axis_forms.category_hidden {
            Length::ZERO
        } else {
            self.widest_category(chart)?
        };
        let labels_at_left = !chart.axis_forms.category_hidden
            && (axis.crossing == axis.low || chart.axis_forms.low_labels);
        let (plot, twin) =
            self.horizontal_plot(chart, &axis, &props, (widest, labels_at_left), frame)?;
        let right = BarDirection::Right;
        let crossing = self.place(&axis, right.values(plot), axis.crossing)?;
        let label_anchor = self.horizontal_label_anchor(
            chart,
            (plot.left, crossing, widest, labels_at_left),
            frame.left,
        )?;
        let mut items = self.gridlines(chart, (&axis, right), plot);
        items.extend(self.bars(chart, (gap, overlap), (&axis, right), (plot, crossing)));
        items.extend(self.value_axis(chart, (&axis, right), plot));
        items.extend(self.chart_upright(&chart.axis, (plot.top, plot.bottom), crossing));
        items.extend(self.category_ticks(chart, (plot, right), crossing));
        let context = self.context;
        let data_labels = decisions::chart_data_labels(&context.quirks, || {
            self.data_labels(chart, (gap, overlap), (&axis, right), (plot, frame))
        });
        let all_data_labels = holds_all_data_labels(chart, data_labels.is_some());
        items.extend(data_labels.into_iter().flatten());
        let axes_and_legend =
            self.bar_texts(chart, (&axis, plot, twin, label_anchor), frame, &mut items);
        Some((
            items,
            DrawnText {
                axes_and_legend,
                data_labels: all_data_labels,
            },
        ))
    }

    /// Computes `(plot, twin)` for horizontal bars, adjusting `plot.right` for the last value
    /// label and `plot.left` for the first value label when category labels stand inside the plot.
    fn horizontal_plot(
        &mut self,
        chart: &Columns,
        axis: &ValueAxis,
        props: &crate::props::RunProps,
        (widest, labels_at_left): (Length, bool),
        frame: Edges<Length>,
    ) -> Option<(Edges<Length>, Edges<Length>)> {
        let deleted = chart.axis_forms.value_deleted;
        let twin = self.label_plot(
            chart,
            (labels_at_left.then_some(widest), None),
            !deleted,
            frame,
        )?;
        let mut plot = twin;
        if !deleted {
            let format = chart.value_format.as_ref()?;
            if !labels_at_left {
                let (first, _) = self.written_text(props, (format, axis.label(0)?))?;
                plot.left += first.room().div_toward_zero(2);
            }
            let (last, _) = self.written_text(props, (format, axis.label(axis.steps)?))?;
            plot.right -= last.room().div_toward_zero(2);
        }
        (plot.right > plot.left && plot.bottom > plot.top).then_some((plot, twin))
    }

    /// The horizontal anchor for left-side category labels (`plot.left` when labels stand at the
    /// left edge, else `crossing`), or `None` when shifted interior labels would clip past the
    /// frame's left margin.
    fn horizontal_label_anchor(
        &mut self,
        chart: &Columns,
        (plot_left, crossing, widest, labels_at_left): (Length, Length, Length, bool),
        frame_left: Length,
    ) -> Option<Length> {
        if labels_at_left || chart.axis_forms.category_hidden {
            return Some(plot_left);
        }
        let gap = self.label_lines(chart)?.label_gap()?;
        (crossing - gap - widest >= frame_left + crate::params::CHART_LINES_LABEL_START)
            .then_some(crossing)
    }

    /// The width of the widest category label at the label size, or `None` when no category
    /// has a name.
    pub(super) fn widest_category(&mut self, chart: &Columns) -> Option<Length> {
        let props = chart_props(chart, chart.label_size);
        let names = chart.category_names.as_ref()?;
        if names.iter().all(String::is_empty) {
            return None;
        }
        names.iter().map(|name| self.text_width(&props, name)).max()
    }

    /// The text of a chart of horizontal bars in `plot`: the value labels across the bottom
    /// as a scatter chart's x labels ([`Self::x_labels`]) unless the value axis is deleted, the category labels at the left
    /// ([`Self::left_category_labels`]), the title, and the legend at its place beside the
    /// twin's plot area `twin`, whose right edge the last value label does not move; added to
    /// `items`; and whether they are all of the chart's text.
    fn bar_texts(
        &mut self,
        chart: &Columns,
        (axis, plot, twin, crossing): (&ValueAxis, Edges<Length>, Edges<Length>, Length),
        frame: Edges<Length>,
        items: &mut Vec<Item>,
    ) -> bool {
        let (Some(lines), Some(value_lines)) = (self.label_lines(chart), self.value_lines(chart))
        else {
            return false;
        };
        // A deleted value axis draws no labels.
        let values = if chart.axis_forms.value_deleted {
            Some(Vec::new())
        } else {
            chart.value_format.as_ref().and_then(|format| {
                let labels = (axis, format, chart.value_label_size);
                self.x_labels(chart, labels, plot, value_lines)
            })
        };
        let categories = if chart.axis_forms.category_hidden {
            Some(Vec::new())
        } else {
            self.left_category_labels(chart, plot, crossing, lines)
        };
        let all = values.is_some() && categories.is_some();
        items.extend(values.into_iter().flatten());
        items.extend(categories.into_iter().flatten());
        let title = chart.title.as_ref().map_or(Some(()), |title| {
            self.chart_title(title, frame)
                .map(|lines| items.extend(lines))
        });
        let axis_titles = self
            .axis_title_items(chart, (axis, plot), frame)
            .map(|titles| items.extend(titles));
        let legend = chart.legend.map_or(Some(()), |_| {
            self.chart_legend(chart, twin, frame)
                .map(|legend| items.extend(legend))
        });
        all && title.is_some() && axis_titles.is_some() && legend.is_some()
    }

    /// One label for each category with a name, in its band from the bottom up: it ends its
    /// width at the label size before the labels' gap before the plot area, and its baseline
    /// lies [`LabelLines::value_baseline`] below its band's exact middle, as a value label of
    /// the column chart twin stands at its value; an empty name draws no label. `None` when the
    /// chart has no category names or a band is lower than the labels' win line, where Word
    /// leaves labels out, which these rules do not choose.
    fn left_category_labels(
        &mut self,
        chart: &Columns,
        plot: Edges<Length>,
        crossing: Length,
        lines: LabelLines,
    ) -> Option<Vec<Item>> {
        let names = chart.category_names.as_ref()?;
        let (gap, down) = (lines.label_gap()?, lines.value_baseline()?);
        let count = i64::try_from(names.len()).ok()?.max(1);
        let span = plot.bottom - plot.top;
        if span.div_toward_zero(count) < lines.line {
            return None;
        }
        let end = crossing - gap;
        let color = self.label_color(chart.category_label_fill.as_ref());
        let mut items = Vec::with_capacity(names.len());
        for (index, name) in (0_i64..).zip(names) {
            if name.is_empty() {
                continue;
            }
            let rise = span
                .checked_mul(index.checked_mul(2)?.checked_add(1)?)?
                .div_toward_zero(count.checked_mul(2)?);
            let middle = plot.bottom - rise;
            items.push(self.chart_label(chart, name, color, |width| {
                Some((end - width, middle + down))
            })?);
        }
        Some(items)
    }
}

/// Whether a stacked or 100%-stacked line chart reverses its legend entries to match the top-down
/// stacking order in a vertical side legend (`LegendPlace::Left` or `Right`).
pub(super) const fn reverses_line_legend(chart: &Columns) -> bool {
    matches!(
        chart.group,
        ChartGroup::Lines {
            stacking: BarStacking::Stacked | BarStacking::PercentStacked,
            ..
        }
    ) && matches!(chart.legend, Some(LegendPlace::Left | LegendPlace::Right))
}

/// The series in the order of the legend's entries: the reverse order for a chart of clustered
/// horizontal bars (whose first series stands lowest in each band) and for a stacked line chart
/// with a side legend (whose last series stands highest), and their forward order for every other
/// chart.
pub(super) fn legend_order(chart: &Columns) -> Vec<&Series> {
    if reverses_line_legend(chart) {
        return chart.series.iter().rev().collect();
    }
    match chart.group {
        // quirk: ChartHorizontalBars::Turned (src/quirks.rs)
        ChartGroup::Bars {
            stacking: BarStacking::Clustered,
            ..
        } => chart.series.iter().rev().collect(),
        ChartGroup::Bars { .. }
        | ChartGroup::Columns { .. }
        | ChartGroup::Lines { .. }
        | ChartGroup::Scatter { .. }
        | ChartGroup::Pie { .. }
        | ChartGroup::Doughnut { .. }
        | ChartGroup::Combo { .. } => chart.series.iter().collect(),
    }
}