f-office-docx 0.1.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
//! The pictures of a page border's sides of an art style, such as `apples`, on a target that
//! draws them (`ArtPageBorders::Pictures`), from the pictures that the caller gives.

use f_office_paint::{
    Group, GroupClip, GroupPlaces, Item, PathCommand, PathItem, Point, Rect, Rgb,
};
use f_office_units::{Edges, Length, div_round};

use crate::art_pictures::{
    ArtItem, ArtPicture, ArtPictures, ArtRect, SidePicture, UNIT, UnitCommand, UnitPoint,
};
use crate::body::ArtSide;
use crate::grid::{Device, Rounding};
use crate::params::{ART_PICTURE_EXTRA_DOTS, ART_STROKE_UNIT};
use crate::props::ArtStyle;

/// The side of the corner square of an art side of `size` points, in whole device dots, a half
/// up: also the height of each of its pictures across the side.
pub(super) fn corner_dots(size: u32, device: &Device) -> i64 {
    Length::from_points(i64::from(size)).map_or(0, |side| device.count(side, Rounding::HalfUp))
}

/// A box on the page.
#[derive(Clone, Copy)]
struct PartBox {
    left: Length,
    top: Length,
    right: Length,
    bottom: Length,
}

/// A side of an art style with its picture and the side of its corner square on the device, or
/// `None` for a side that is not drawn.
type DrawnSide<'a> = Option<(ArtSide, &'a ArtPicture, Length)>;

/// The pictures of one side of an art border.
struct SideRun<'a> {
    /// The side, if it is drawn.
    side: DrawnSide<'a>,
    /// The side's own shapes in a picture.
    own: fn(&ArtPicture) -> &SidePicture,
    /// Whether the side runs across the page, as the top and the bottom sides do.
    across: bool,
    /// The start and the end of the side's box along it, its corner squares included.
    along: (Length, Length),
    /// The side's outer edge.
    outer: Length,
    /// Whether the side's band lies after its outer edge in x or y, as for the top and the left
    /// sides, or before it.
    after: bool,
}

/// The picture of one corner square of an art border.
struct CornerRun<'a> {
    /// The side whose picture the corner takes, if one is drawn.
    side: DrawnSide<'a>,
    /// The corner's items in a picture.
    shapes: fn(&ArtPicture) -> &[ArtItem],
    /// The corner of the border's box.
    at: (Length, Length),
    /// Whether the square lies before the corner in x and in y.
    before: (bool, bool),
}

/// Adds to `items` the pictures of the art sides of a page border, `sides`, whose box has the
/// outer edges `edges` on the device dots, and gives the style and size of each side whose
/// picture `pictures` lacks, which is not drawn. Each side has a corner square at each end,
/// of [`corner_dots`]; between them lie as many pictures as fit at
/// [`ART_PICTURE_EXTRA_DOTS`] longer than the square each, all of one length in whole dots,
/// and the dots left over make the last pictures one dot longer each, in the order of the
/// side's x or y. Each picture of the side's `repeat` shapes is stretched to its own box, and
/// its `span` shapes to the box from corner to corner. A corner takes the picture of the top or
/// the bottom side when that side is of an art style, else that of the left or the right side.
/// The pictures lie on the device's dots, and the items of a border are a group whose every
/// point the writer places ([`GroupPlaces::Points`]), as Word's PDF writer moves them by its
/// page offsets; a picture's rectangles go into groups of stroked rectangles
/// ([`GroupPlaces::Stroked`]), whose edges the writer places and holds at their own places.
pub(super) fn art_items(
    sides: &Edges<Option<ArtSide>>,
    edges: Edges<Length>,
    device: &Device,
    pictures: &ArtPictures,
    items: &mut Vec<Item>,
) -> Vec<(ArtStyle, u32)> {
    let mut missing = Vec::new();
    let mut found = |side: Option<ArtSide>| {
        let art = side?;
        let picture = pictures.picture(art.style, art.size);
        if picture.is_none() && !missing.contains(&(art.style, art.size)) {
            missing.push((art.style, art.size));
        }
        Some((art, picture?, device.dots(corner_dots(art.size, device))))
    };
    let drawn = Edges {
        left: found(sides.left),
        top: found(sides.top),
        right: found(sides.right),
        bottom: found(sides.bottom),
    };
    let mut border = Vec::new();
    for run in side_runs(drawn, edges) {
        run.draw(device, &mut border);
    }
    for corner in corner_runs(drawn, edges) {
        corner.draw(&mut border);
    }
    if !border.is_empty() {
        items.push(Item::Group(Group {
            items: border,
            clip: None,
            places: GroupPlaces::Points,
        }));
    }
    missing
}

/// The runs of the four sides, `drawn`, of a border whose box has the outer edges `edges`.
fn side_runs(drawn: Edges<DrawnSide<'_>>, edges: Edges<Length>) -> [SideRun<'_>; 4] {
    let Edges {
        left,
        top,
        right,
        bottom,
    } = edges;
    [
        SideRun {
            side: drawn.top,
            own: |p| &p.sides.top,
            across: true,
            along: (left, right),
            outer: top,
            after: true,
        },
        SideRun {
            side: drawn.bottom,
            own: |p| &p.sides.bottom,
            across: true,
            along: (left, right),
            outer: bottom,
            after: false,
        },
        SideRun {
            side: drawn.left,
            own: |p| &p.sides.left,
            across: false,
            along: (top, bottom),
            outer: left,
            after: true,
        },
        SideRun {
            side: drawn.right,
            own: |p| &p.sides.right,
            across: false,
            along: (top, bottom),
            outer: right,
            after: false,
        },
    ]
}

/// The four corners of a border whose sides are `drawn` and whose box has the outer edges
/// `edges`: each from the side across when it is drawn, else from the side down.
fn corner_runs(drawn: Edges<DrawnSide<'_>>, edges: Edges<Length>) -> [CornerRun<'_>; 4] {
    let Edges {
        left,
        top,
        right,
        bottom,
    } = edges;
    [
        CornerRun {
            side: drawn.top.or(drawn.left),
            shapes: |p| &p.corners.top_left,
            at: (left, top),
            before: (false, false),
        },
        CornerRun {
            side: drawn.top.or(drawn.right),
            shapes: |p| &p.corners.top_right,
            at: (right, top),
            before: (true, false),
        },
        CornerRun {
            side: drawn.bottom.or(drawn.left),
            shapes: |p| &p.corners.bottom_left,
            at: (left, bottom),
            before: (false, true),
        },
        CornerRun {
            side: drawn.bottom.or(drawn.right),
            shapes: |p| &p.corners.bottom_right,
            at: (right, bottom),
            before: (true, true),
        },
    ]
}

impl SideRun<'_> {
    /// Adds the side's pictures to `items`: its `repeat` shapes on each square between the
    /// corner squares and its `span` shapes from corner to corner.
    fn draw(self, device: &Device, items: &mut Vec<Item>) {
        let Some((art, picture, corner)) = self.side else {
            return;
        };
        let band = if self.after {
            (self.outer, self.outer + corner)
        } else {
            (self.outer - corner, self.outer)
        };
        let (first, last) = (self.along.0 + corner, self.along.1 - corner);
        let part = |along: (Length, Length)| PartBox::of(self.across, along, band);
        let color = art.color.rgb();
        let own = (self.own)(picture);
        for along in squares(first, last, corner, device) {
            draw(&own.repeat, part(along), color, items);
        }
        draw(&own.span, part((first, last)), color, items);
    }
}

impl CornerRun<'_> {
    /// Adds the corner's picture to `items`, stretched to its square.
    fn draw(self, items: &mut Vec<Item>) {
        let Some((art, picture, corner)) = self.side else {
            return;
        };
        let span = |at: Length, before: bool| {
            if before {
                (at - corner, at)
            } else {
                (at, at + corner)
            }
        };
        let square = PartBox::of(
            true,
            span(self.at.0, self.before.0),
            span(self.at.1, self.before.1),
        );
        draw((self.shapes)(picture), square, art.color.rgb(), items);
    }
}

impl PartBox {
    /// The box from `along.0` to `along.1` along a side and from `band.0` to `band.1` across
    /// it: along x for a side that runs `across`, else along y.
    const fn of(across: bool, along: (Length, Length), band: (Length, Length)) -> Self {
        if across {
            Self {
                left: along.0,
                top: band.0,
                right: along.1,
                bottom: band.1,
            }
        } else {
            Self {
                left: band.0,
                top: along.0,
                right: band.1,
                bottom: along.1,
            }
        }
    }
}

/// The start and end of each picture of a side from `first` to `last`, whose corner squares
/// are `corner` long, on the device's dots.
fn squares(first: Length, last: Length, corner: Length, device: &Device) -> Vec<(Length, Length)> {
    let length = device.count(last - first, Rounding::HalfUp);
    let step = device.count(corner, Rounding::HalfUp) + ART_PICTURE_EXTRA_DOTS;
    let count = if step > 0 { length / step } else { 0 };
    if count <= 0 {
        return Vec::new();
    }
    let base = length / count;
    let longer = length - count * base;
    let offset = |index: i64| index * base + (index - (count - longer)).max(0);
    (0..count)
        .map(|index| {
            (
                first + device.dots(offset(index)),
                first + device.dots(offset(index + 1)),
            )
        })
        .collect()
}

/// Adds to `items` the items of a picture, `picture`, stretched to `part`, with black as `color`
/// when the side has a color: each shape a path, each rectangle a filled rectangle in a group
/// of stroked rectangles of its stroke width (one group for each run of rectangles of one
/// width), and the items between a clip and its end a group with the clip, whose every point
/// the writer places.
fn draw(picture: &[ArtItem], part: PartBox, color: Option<Rgb>, items: &mut Vec<Item>) {
    let place = |point: UnitPoint| Point {
        x: share(part.left, part.right, point.x),
        y: share(part.top, part.bottom, point.y),
    };
    let outline = |commands: &[UnitCommand]| -> Vec<PathCommand> {
        commands
            .iter()
            .map(|command| match *command {
                UnitCommand::Move(to) => PathCommand::MoveTo(place(to)),
                UnitCommand::Line(to) => PathCommand::LineTo(place(to)),
                UnitCommand::Quad(control, to) => PathCommand::QuadTo(place(control), place(to)),
                UnitCommand::Cubic(first, second, to) => {
                    PathCommand::CubicTo(place(first), place(second), place(to))
                }
                UnitCommand::Close => PathCommand::Close,
            })
            .collect()
    };
    let fill = |own: Rgb| match color {
        Some(side) if own == Rgb::BLACK => side,
        _ => own,
    };
    let mut open: Vec<(GroupClip, Vec<Item>)> = Vec::new();
    for item in picture {
        match item {
            ArtItem::Rect(rect) => {
                let (top_left, bottom_right) = (place(rect.top_left), place(rect.bottom_right));
                let drawn = Rect {
                    x: top_left.x,
                    y: top_left.y,
                    width: bottom_right.x - top_left.x,
                    height: bottom_right.y - top_left.y,
                    color: fill(rect.color),
                };
                push_stroked(held(&mut open, items), drawn, stroke_width(rect));
            }
            ArtItem::Shape(shape) => {
                let fill = fill(shape.color);
                let path = Item::Path(PathItem {
                    commands: outline(&shape.commands),
                    color: fill,
                    fill_rule: shape.fill_rule,
                });
                held(&mut open, items).push(path);
            }
            ArtItem::Clip(clip) => open.push((
                GroupClip {
                    commands: outline(&clip.commands),
                    fill_rule: clip.fill_rule,
                },
                Vec::new(),
            )),
            ArtItem::End => end_clip(&mut open, items),
        }
    }
    while !open.is_empty() {
        end_clip(&mut open, items);
    }
}

/// The width of the outline of a picture's rectangle, from its parts of a point.
fn stroke_width(rect: &ArtRect) -> Length {
    Length::from_units(div_round(
        i64::from(rect.stroke) * Length::UNITS_PER_POINT,
        i64::from(ART_STROKE_UNIT),
    ))
}

/// Adds `rect` to the group of stroked rectangles of `width` that ends `items`, or to a new one.
fn push_stroked(items: &mut Vec<Item>, rect: Rect, width: Length) {
    let places = GroupPlaces::Stroked { width };
    if let Some(Item::Group(group)) = items.last_mut()
        && group.places == places
        && group.clip.is_none()
    {
        group.items.push(Item::Rect(rect));
        return;
    }
    items.push(Item::Group(Group {
        items: vec![Item::Rect(rect)],
        clip: None,
        places,
    }));
}

/// The items of the innermost open clip of `open`, or `items` when none is open.
fn held<'a>(open: &'a mut [(GroupClip, Vec<Item>)], items: &'a mut Vec<Item>) -> &'a mut Vec<Item> {
    match open.last_mut() {
        Some((_, inside)) => inside,
        None => items,
    }
}

/// Ends the innermost open clip of `open`: its items become a group with the clip, whose every
/// point the writer places, in the items of the clip around it or in `items`.
fn end_clip(open: &mut Vec<(GroupClip, Vec<Item>)>, items: &mut Vec<Item>) {
    if let Some((clip, inside)) = open.pop() {
        held(open, items).push(Item::Group(Group {
            items: inside,
            clip: Some(clip),
            places: GroupPlaces::Points,
        }));
    }
}

/// The place `millionths` of the way from `from` to `to`, to the nearest unit, a half up.
fn share(from: Length, to: Length, millionths: i32) -> Length {
    let span = i128::from((to - from).units()) * i128::from(millionths);
    let unit = i128::from(UNIT);
    let moved = (span * 2 + unit).div_euclid(unit * 2);
    from + Length::from_units(i64::try_from(moved).unwrap_or(0))
}