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
//! A drawn 3-D column chart, on a target whose quirk `ChartColumns3D` is `Picture`: one picture
//! of the floor, the walls' gridlines and the columns, in an oblique projection, over the plot
//! area of its 2-D twin, and the twin's labels, title and legend placed from the picture's
//! front.
//!
//! The figure's plot area is the plot area of a 2-D column chart of the same text, whose value
//! axis ends at the values without headroom ([`ValueAxis::flush_for_chart`]), with its edges
//! moved by [`CHART_COLUMN_3D_PLOT_MOVES`]. A column's front is a 2-D clustered column's
//! ([`Clusters`]); its depth is its width times the view's depth percentage, and it stands in
//! the middle of the floor, which is the column's depth and the gap depth deep. The figure is
//! scaled to fit the plot area with [`CHART_COLUMN_3D_MARGIN`] at each side and
//! [`CHART_COLUMN_3D_ROOM`] beyond the floor's depth ([`f_office_effects::ColumnChart`]); its
//! box stands in the middle of the plot area, and its picture has the box's pixels at
//! [`CHART_COLUMN_3D_PIXELS_PER_INCH`], rounded up, and one more. The value labels stand at
//! the side wall's front edge as a 2-D chart's stand at its plot area, but their baselines take
//! [`CHART_COLUMN_3D_VALUE_BASELINE_DESCENTS`] win descents off the em and the win top where a
//! 2-D chart's take three; the category labels stand below the floor's front edge,
//! [`CHART_COLUMN_3D_CATEGORY_DROP`] lower than a 2-D chart's below its plot area. The data
//! labels are not drawn.

use f_office_drawingml::color::on_white;
use f_office_drawingml::theme::ShapeTheme;
use f_office_effects::{Angle, Column, ColumnChart, Picture, PixelLength, Scene, Share, WallLine};
use f_office_paint::{
    Image, ImageColor, ImageFormat, ImageItem, InkConversion, Item, Opacity, Rgb,
};
use f_office_units::scale::{DEGREE, PERCENT};
use f_office_units::{Edges, Length};

use super::{Clusters, DrawnText, ValueAxis, bar_paint, holds_all_data_labels, room_units, share};
use crate::chart::{ColumnView, Columns, PlotPlace, Series};
use crate::layout::{Layout, decisions};
use crate::params::{
    CHART_AXIS_STEPS, CHART_COLUMN_3D_CATEGORY_DROP, CHART_COLUMN_3D_LINE_TONE,
    CHART_COLUMN_3D_LINE_WIDTH, CHART_COLUMN_3D_MARGIN, CHART_COLUMN_3D_PIXELS_PER_INCH,
    CHART_COLUMN_3D_PLOT_MOVES, CHART_COLUMN_3D_ROOM, CHART_COLUMN_3D_SIDE_TONE,
    CHART_COLUMN_3D_TOP_TONE, CHART_COLUMN_3D_VALUE_BASELINE_DESCENTS,
};

impl Layout<'_> {
    /// The items of the 3-D column chart `chart` with the gap width `gap`, the gap depth
    /// `gap_depth` and the view `view` in its frame `frame`, and the text that they hold, or
    /// `None` when these rules do not place it: a manual layout of its plot area, a crossing of
    /// its axes other than at its lowest value, a value below zero, a series in a gradient,
    /// or no room.
    pub(super) fn columns_3d(
        &mut self,
        chart: &Columns,
        (gap, gap_depth, view): (i64, i64, ColumnView),
        frame: Edges<Length>,
    ) -> Option<(Vec<Item>, DrawnText)> {
        if chart.plot_place != PlotPlace::Automatic {
            return None;
        }
        let shape = (gap, gap_depth, view);
        let (axis, twin) = self.flush_axis_and_plot(chart, shape, frame)?;
        if axis.crossing != axis.low || axis.low != super::ZERO {
            return None;
        }
        let plot = moved(twin);
        let picture = self.column_picture(chart, shape, (&axis, plot))?;
        let front = picture.front(plot)?;
        let mut items = vec![picture.item()];
        let all_data_labels = holds_all_data_labels(chart, false);
        let axes_and_legend = self.column_texts(chart, (&axis, front), (twin, frame), &mut items);
        Some((
            items,
            DrawnText {
                axes_and_legend,
                data_labels: all_data_labels,
            },
        ))
    }

    /// The labels of `chart`'s axes at the front `front` of its picture with the value axis
    /// `axis`, its title and its legend beside the plot area `twin` of its 2-D twin in `frame`,
    /// added to `items`, and whether they are all its text of these kinds. A value label's
    /// baseline lies [`CHART_COLUMN_3D_VALUE_BASELINE_DESCENTS`] win descents lower below its
    /// value's place on the side wall's front edge than a 2-D chart's, and a category label's
    /// [`CHART_COLUMN_3D_CATEGORY_DROP`] lower below the floor's front edge than a 2-D chart's
    /// below its plot area.
    fn column_texts(
        &mut self,
        chart: &Columns,
        (axis, front): (&ValueAxis, Edges<Length>),
        (twin, frame): (Edges<Length>, Edges<Length>),
        items: &mut Vec<Item>,
    ) -> bool {
        let (Some(lines), Some(value_lines)) = (self.label_lines(chart), self.value_lines(chart))
        else {
            return false;
        };
        let (Some(flat), Some(solid)) = (
            value_lines.value_baseline(),
            value_lines.value_baseline_with(CHART_COLUMN_3D_VALUE_BASELINE_DESCENTS),
        ) else {
            return false;
        };
        let drop = solid - flat;
        let lowered = Edges {
            top: front.top + drop,
            bottom: front.bottom + drop,
            ..front
        };
        let (labels, mut all) = self.shown_value_labels(chart, axis, lowered, value_lines);
        items.extend(labels);
        if !chart.axis_forms.category_hidden {
            let anchor = front.bottom + CHART_COLUMN_3D_CATEGORY_DROP;
            let categories = self.category_labels(chart, (front, anchor, frame), lines);
            all &= categories.is_some();
            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 legend = chart.legend.map_or(Some(()), |_| {
            self.chart_legend(chart, twin, frame)
                .map(|legend| items.extend(legend))
        });
        all && title.is_some() && legend.is_some()
    }

    /// The value axis without headroom of `chart` and the plot area of its 2-D twin with that
    /// axis' labels, with at most as many units as the height of the picture's front holds
    /// where the target counts them ([`decisions::chart_axis_room`]): the front of the figure
    /// of the shape `shape` (the gap width, the gap depth and the view) on the page, which is
    /// lower than the plot area by the room that the depth takes.
    fn flush_axis_and_plot(
        &mut self,
        chart: &Columns,
        shape: (i64, i64, ColumnView),
        frame: Edges<Length>,
    ) -> Option<(ValueAxis, Edges<Length>)> {
        let axis = ValueAxis::flush_for_chart(chart, CHART_AXIS_STEPS)?;
        let plot = self.font_line_plot_with(chart, (&axis, None), frame)?;
        let context = self.context;
        decisions::chart_axis_room(&context.quirks, (axis, plot), |(axis, plot)| {
            let line = self.chart_line(chart, chart.value_label_size)?;
            let moved = moved(plot);
            let front = self
                .column_picture(chart, shape, (&axis, moved))?
                .front(moved)?;
            let most = room_units(front.bottom - front.top, line);
            if axis.steps <= most {
                return Some((axis, plot));
            }
            let axis = ValueAxis::flush_for_chart(chart, most)?;
            let plot = self.font_line_plot_with(chart, (&axis, None), frame)?;
            Some((axis, plot))
        })
    }

    /// The picture of `chart`'s columns over the plot area `plot` of its 2-D twin, with the
    /// value axis `axis`.
    fn column_picture(
        &self,
        chart: &Columns,
        (gap, gap_depth, view): (i64, i64, ColumnView),
        (axis, plot): (&ValueAxis, Edges<Length>),
    ) -> Option<ColumnPicture> {
        let (width, height) = (plot.right - plot.left, plot.bottom - plot.top);
        let clusters = Clusters::of(chart, (gap, 0), width)?;
        let depth = clusters
            .thickness
            .checked_mul(view.depth)?
            .div_toward_zero(PERCENT);
        let floor_depth = depth
            .checked_mul(PERCENT + gap_depth)?
            .div_toward_zero(PERCENT);
        let front_depth = depth.checked_mul(gap_depth)?.div_toward_zero(2 * PERCENT);
        let mut scene = ColumnChart::new(
            (
                Angle::from_sixty_thousandths(view.tilt.checked_mul(DEGREE)?),
                Angle::from_sixty_thousandths(view.turn.checked_mul(DEGREE)?),
            ),
            (pixels(width)?, pixels(height)?),
            pixels(floor_depth)?,
            (
                PixelLength::ratio(CHART_COLUMN_3D_MARGIN.0, CHART_COLUMN_3D_MARGIN.1)?,
                PixelLength::ratio(CHART_COLUMN_3D_ROOM.0, CHART_COLUMN_3D_ROOM.1)?,
            ),
        );
        scene.gridlines = self.wall_lines(chart, (axis, height))?;
        let fronts = ColumnFronts {
            clusters: &clusters,
            axis,
            height,
            depths: (front_depth, depth),
        };
        scene.columns = self.solid_columns(chart, &fronts)?;
        ColumnPicture::placed(plot, scene)
    }

    /// The gridlines of `chart`'s value axis `axis` on the walls of a front `height` high, in
    /// their tone and width in 3-D.
    fn wall_lines(
        &self,
        chart: &Columns,
        (axis, height): (&ValueAxis, Length),
    ) -> Option<Vec<WallLine>> {
        let theme = &self.shaper.theme().shapes;
        let Some((rgb, alpha, line_width)) =
            chart.gridlines.as_ref().and_then(|look| look.line(theme))
        else {
            return Some(Vec::new());
        };
        let color = tone(on_white(rgb, alpha), CHART_COLUMN_3D_LINE_TONE);
        let line_width = pixels(
            line_width
                .checked_mul(CHART_COLUMN_3D_LINE_WIDTH.0)?
                .div_round(CHART_COLUMN_3D_LINE_WIDTH.1),
        )?;
        axis.labels()
            .map(|value| {
                let up = share(height, value, axis.high)?;
                Some(WallLine::new(pixels(up)?, line_width, color))
            })
            .collect()
    }

    /// The columns of `chart`, each series' in its place in each category's cluster, or `None`
    /// when a value lies below zero or a series' fill is not one color.
    fn solid_columns(&self, chart: &Columns, fronts: &ColumnFronts<'_>) -> Option<Vec<Column>> {
        let theme = &self.shaper.theme().shapes;
        let mut columns = Vec::new();
        for category in 0..i64::try_from(chart.categories).ok()? {
            for (index, series) in (0_i64..).zip(chart.bar_series()) {
                fronts.push_column(&mut columns, series, (category, index), theme)?;
            }
        }
        Some(columns)
    }
}

/// What places the columns of a 3-D column chart: the clusters of their fronts, the value axis
/// over the front's height, and how deep the columns' fronts lie behind the floor's front edge
/// and how deep the columns are.
struct ColumnFronts<'a> {
    /// The clusters of the columns' fronts across the front.
    clusters: &'a Clusters,
    /// The value axis.
    axis: &'a ValueAxis,
    /// The front's height.
    height: Length,
    /// The depth of the columns' fronts behind the floor's front edge, and of the columns.
    depths: (Length, Length),
}

impl ColumnFronts<'_> {
    /// Adds to `columns` the column of `series` in the category `category`, at the place
    /// `index` of its cluster, when it has a value and a fill; `None` when the value lies below
    /// zero or the fill is not one color.
    fn push_column(
        &self,
        columns: &mut Vec<Column>,
        series: &Series,
        (category, index): (i64, i64),
        theme: &ShapeTheme,
    ) -> Option<()> {
        let at = usize::try_from(category).ok()?;
        let Some(value) = series.values.get(at).copied().flatten() else {
            return Some(());
        };
        if value.digits < 0 {
            return None;
        }
        let Some(paint) = bar_paint(&series.fill, category, theme) else {
            return Some(());
        };
        let super::BarPaint::Color(fill) = paint else {
            return None;
        };
        let left = self.clusters.start((category, index))?;
        let right = left + self.clusters.thickness;
        let up = share(self.height, value.min(self.axis.high), self.axis.high)?;
        let (front, depth) = self.depths;
        columns.push(Column::new(
            (pixels(left)?, pixels(right)?),
            pixels(up)?,
            (pixels(front)?, pixels(front + depth)?),
            [
                channels(fill),
                tone(fill, CHART_COLUMN_3D_TOP_TONE),
                tone(fill, CHART_COLUMN_3D_SIDE_TONE),
            ],
        ));
        Some(())
    }
}

/// The picture of a 3-D column chart and the box on the page that it covers.
struct ColumnPicture {
    /// The box that the picture covers.
    place: Edges<Length>,
    /// The picture.
    picture: Picture,
}

impl ColumnPicture {
    /// The picture of the figure `scene` in the middle of the plot area `plot`, which its box
    /// fills in one direction.
    fn placed(plot: Edges<Length>, scene: ColumnChart) -> Option<Self> {
        let (width, height) = (plot.right - plot.left, plot.bottom - plot.top);
        let (across, down) = scene.box_shares()?;
        let box_width = part(width, across)?;
        let box_height = part(height, down)?;
        let left = plot.left + (width - box_width).div_toward_zero(2);
        let top = plot.top + (height - box_height).div_toward_zero(2);
        Some(Self {
            place: Edges {
                left,
                top,
                right: left + box_width,
                bottom: top + box_height,
            },
            picture: Picture {
                width: picture_pixels(box_width)?,
                height: picture_pixels(box_height)?,
                scene: Scene::Columns(scene),
            },
        })
    }

    /// The picture's item, an image over its box.
    fn item(&self) -> Item {
        Item::Image(ImageItem {
            x: self.place.left,
            y: self.place.top,
            width: self.place.right - self.place.left,
            height: self.place.bottom - self.place.top,
            clip: None,
            turn: None,
            image: Image {
                format: ImageFormat::EffectPicture,
                data: self.picture.encode().into(),
                opacity: Opacity::FULL,
                color: ImageColor::Original,
                inks: InkConversion::EmbeddedProfile,
            },
        })
    }

    /// The front of the floor and the walls on the page: from the floor's front left corner to
    /// the top of the side wall's front edge and the right end of the floor's front edge, for
    /// the plot area `plot` of the twin, whose width and height the front has before the scale.
    fn front(&self, plot: Edges<Length>) -> Option<Edges<Length>> {
        let (width, height) = (plot.right - plot.left, plot.bottom - plot.top);
        let corner = self.page_point(PixelLength::ZERO, PixelLength::ZERO)?;
        let right = self.page_point(pixels(width)?, PixelLength::ZERO)?;
        let top = self.page_point(PixelLength::ZERO, pixels(height)?)?;
        Some(Edges {
            left: corner.0,
            top: top.1,
            right: right.0,
            bottom: corner.1,
        })
    }

    /// Where the point of the front `across` the floor's front edge and `up` the side wall's
    /// front edge lands on the page.
    fn page_point(&self, across: PixelLength, up: PixelLength) -> Option<(Length, Length)> {
        let point = self.picture.front_point(across, up)?;
        let place = self.place;
        Some((
            place.left + part(place.right - place.left, point.across)?,
            place.top + part(place.bottom - place.top, point.down)?,
        ))
    }
}

/// The figure's plot area: the plot area `twin` of the 2-D twin with its edges moved by
/// [`CHART_COLUMN_3D_PLOT_MOVES`].
fn moved(twin: Edges<Length>) -> Edges<Length> {
    let [left, top, right, bottom] = CHART_COLUMN_3D_PLOT_MOVES;
    Edges {
        left: twin.left + left,
        top: twin.top + top,
        right: twin.right + right,
        bottom: twin.bottom + bottom,
    }
}

/// `length` in pixels at [`CHART_COLUMN_3D_PIXELS_PER_INCH`].
fn pixels(length: Length) -> Option<PixelLength> {
    PixelLength::ratio(
        length
            .units()
            .checked_mul(CHART_COLUMN_3D_PIXELS_PER_INCH)?,
        Length::UNITS_PER_INCH,
    )
}

/// The pixels of a picture over a box `side` long: the side at
/// [`CHART_COLUMN_3D_PIXELS_PER_INCH`], rounded up, and one more.
pub(super) fn picture_pixels(side: Length) -> Option<u32> {
    let units = side.units().checked_mul(CHART_COLUMN_3D_PIXELS_PER_INCH)?;
    let whole = units.div_euclid(Length::UNITS_PER_INCH)
        + i64::from(units.rem_euclid(Length::UNITS_PER_INCH) != 0);
    u32::try_from(whole).ok().filter(|&n| n > 0)?.checked_add(1)
}

/// The part `share` of `length`, rounded to the nearest unit.
fn part(length: Length, share: Share) -> Option<Length> {
    let whole = i64::from(Share::ratio(1, 1)?.hundred_thousandths());
    Some(
        length
            .checked_mul(i64::from(share.hundred_thousandths()))?
            .div_round(whole),
    )
}

/// The red, green and blue of `color`.
const fn channels(color: Rgb) -> [u8; 3] {
    [color.r, color.g, color.b]
}

/// `color` at the share `tone` of each channel, rounded to the nearest, at most 255.
pub(super) fn tone(color: Rgb, (numerator, denominator): (i64, i64)) -> [u8; 3] {
    channels(color).map(|channel| {
        let toned = (i64::from(channel) * numerator * 2 + denominator) / (denominator * 2);
        u8::try_from(toned).unwrap_or(u8::MAX)
    })
}