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
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Tests of the border line list, on a layout without a document.

use f_office_paint::{Item, Rect};
use f_office_units::Length;

use super::Direction;
use crate::layout::Layout;
use crate::layout::testing::with_layout;
use crate::props::{Border, BorderParts, Color};

/// A border of one line half a point wide, in the automatic color.
fn border() -> Border {
    let width = Length::from_eighth_points(4).expect("a whole number of units");
    Border::new(BorderParts::single(width), Length::ZERO, Color::Auto)
}

/// The place and the size of the line that [`draw`] draws, in units.
const LINE: [i64; 4] = [1000, 2000, 30_000, 100];

/// Draws a line of [`border`] at [`LINE`], as a pass of a table does.
fn draw(layout: &mut Layout<'_>) {
    let [x, y, width, height] = LINE.map(Length::from_units);
    let at = f_office_paint::Point { x, y };
    layout.push_line(border(), super::line_rect(border(), at, width, height));
}

/// The item of the line at [`LINE`].
fn line() -> Item {
    let [x, y, width, height] = LINE.map(Length::from_units);
    Item::Rect(Rect {
        x,
        y,
        width,
        height,
        color: border().color.drawn(),
    })
}

/// How many items of the layout are the line at [`LINE`].
fn lines(layout: &Layout<'_>) -> usize {
    layout
        .items
        .to_vec()
        .iter()
        .filter(|item| **item == line())
        .count()
}

#[test]
fn draws_a_border_line_once_where_two_passes_give_it() {
    with_layout(|layout| {
        draw(layout);
        draw(layout);
        assert_eq!(layout.items.to_vec(), [line()]);
    });
}

#[test]
fn draws_a_border_line_that_another_item_before_it_equals() {
    with_layout(|layout| {
        // A rectangle that is no border line, such as a fill, at the place of the line.
        layout.items.push(line());
        draw(layout);
        assert_eq!(lines(layout), 2);
    });
}

#[test]
fn draws_a_border_line_again_after_a_cut_trial() {
    with_layout(|layout| {
        // A trial draws the line, and its items are cut; the line is drawn again, once.
        draw(layout);
        layout.items.cut(0);
        draw(layout);
        assert_eq!(layout.items.to_vec(), [line()]);
        // Another cut, and a rectangle that is no border line takes the place where the line
        // stood: the line that the cut took no longer hides it.
        layout.items.cut(0);
        layout.items.push(line());
        draw(layout);
        assert_eq!(lines(layout), 2);
    });
}

#[test]
fn keeps_a_border_line_once_when_a_fill_goes_in_before_it() {
    with_layout(|layout| {
        let entry = layout.items.open_fills();
        draw(layout);
        // A fill goes in under the line, before it in the items.
        let [x, y, width, _] = LINE.map(Length::from_units);
        let fill = Item::Rect(Rect {
            x,
            y,
            width,
            height: Length::from_units(1000),
            color: f_office_paint::Rgb::BLACK,
        });
        layout.items.put_fills(entry, vec![fill]);
        draw(layout);
        assert_eq!(lines(layout), 1);
        assert_eq!(layout.items.count(), 2);
    });
}

#[test]
fn starts_the_list_afresh_with_the_items_of_a_new_page() {
    with_layout(|layout| {
        draw(layout);
        assert_eq!(layout.items.take(), [line()]);
        // On the next page, a rectangle that is no border line stands where the line stood.
        layout.items.push(line());
        draw(layout);
        assert_eq!(lines(layout), 2);
    });
}

/// The dashes of a piece from 0 to `end` units along, `width` units across, as start and end
/// along it.
fn dash_spans(
    dash: crate::props::DashStyle,
    end: i64,
    width: i64,
    direction: Direction,
) -> Vec<(i64, i64)> {
    let u = Length::from_units;
    let piece = if direction == Direction::Across {
        f_office_units::Edges {
            left: u(0),
            top: u(50),
            right: u(end),
            bottom: u(50 + width),
        }
    } else {
        f_office_units::Edges {
            left: u(50),
            top: u(0),
            right: u(50 + width),
            bottom: u(end),
        }
    };
    super::dashes(piece, dash, direction)
        .into_iter()
        .map(|b| {
            if direction == Direction::Across {
                (b.left.units(), b.right.units())
            } else {
                (b.top.units(), b.bottom.units())
            }
        })
        .collect()
}

#[test]
fn dashes_a_piece_from_its_start_and_cuts_the_last_dash_at_its_end() {
    use crate::props::DashStyle;
    assert_eq!(
        dash_spans(DashStyle::Dotted, 10, 2, Direction::Across),
        [(0, 2), (4, 6), (8, 10)]
    );
    assert_eq!(
        dash_spans(DashStyle::Dotted, 9, 2, Direction::Across),
        [(0, 2), (4, 6), (8, 9)]
    );
    assert_eq!(
        dash_spans(DashStyle::Dashed, 9, 1, Direction::Down),
        [(0, 3), (4, 7), (8, 9)]
    );
    assert_eq!(
        dash_spans(DashStyle::DotDash, 14, 1, Direction::Across),
        [(0, 3), (4, 5), (6, 9), (10, 11), (12, 14)]
    );
    assert_eq!(
        dash_spans(DashStyle::DotDotDash, 13, 1, Direction::Down),
        [(0, 3), (4, 5), (6, 7), (8, 11), (12, 13)]
    );
    // A junction square, as long as the line is wide, is one whole dash.
    assert_eq!(
        dash_spans(DashStyle::Dotted, 2, 2, Direction::Across),
        [(0, 2)]
    );
}

#[test]
fn leaves_the_lines_of_a_row_whole_with_a_warning_when_one_is_no_rectangle_that_reads() {
    with_layout(|layout| {
        draw(layout);
        // An item that is no rectangle among the row's lines, which a rectangle beyond the
        // range of a length stands for.
        let other = Item::Group(f_office_paint::Group {
            items: Vec::new(),
            clip: None,
            places: f_office_paint::GroupPlaces::Own,
        });
        layout.items.push(other.clone());
        let part = f_office_warnings::Name::new(crate::testing::DOCUMENT);
        assert_eq!(layout.split_at_junctions(0, &[], &part), []);
        assert_eq!(layout.items.to_vec(), [line(), other]);
        let limits: Vec<_> = layout
            .output
            .warnings
            .iter()
            .map(|(warning, count)| (warning.clone(), count))
            .collect();
        assert_eq!(
            limits,
            [(
                crate::Warning::LimitReached {
                    part,
                    limit: crate::warnings::Limit::LineRange,
                },
                1
            )]
        );
    });
}

#[test]
fn gives_the_inner_and_the_outer_edge_of_each_side_line() {
    use super::{CellSide, LineEdge, LinePart, SideLines};
    let part = |start, thick| LinePart {
        start: Length::from_units(start),
        thick: Length::from_units(thick),
    };
    let sides = SideLines {
        left: vec![part(0, 2), part(4, 1)],
        right: vec![part(10, 3)],
        ..SideLines::default()
    };
    let edge = |side, edge| sides.edge(side, edge).map(Length::units);
    assert_eq!(edge(CellSide::Left, LineEdge::Outer), Some(0));
    assert_eq!(edge(CellSide::Left, LineEdge::Inner), Some(5));
    assert_eq!(edge(CellSide::Right, LineEdge::Inner), Some(10));
    assert_eq!(edge(CellSide::Right, LineEdge::Outer), Some(13));
    let none = SideLines::default();
    assert_eq!(none.edge(CellSide::Left, LineEdge::Inner), None);
}

#[test]
fn the_squares_near_a_line_hold_every_square_on_it() {
    use f_office_paint::Rgb;
    use f_office_units::Edges;

    use super::{Junction, SquareOrder};
    let u = Length::from_units;
    let square = |left, top, size| Junction {
        edges: Edges {
            left: u(left),
            top: u(top),
            right: u(left + size),
            bottom: u(top + size),
        },
        color: Rgb::default(),
        count: 1,
    };
    let squares = [
        square(0, 0, 4),
        square(10, 2, 1),
        square(20, 9, 2),
        square(30, 20, 1),
    ];
    let order = SquareOrder::of(&squares);
    for (line, direction) in [
        (
            Edges {
                left: u(0),
                top: u(2),
                right: u(40),
                bottom: u(10),
            },
            Direction::Across,
        ),
        (
            Edges {
                left: u(9),
                top: u(0),
                right: u(21),
                bottom: u(30),
            },
            Direction::Down,
        ),
    ] {
        let near = order.near(line, direction);
        let on: Vec<_> = (squares.iter().map(|square| square.edges))
            .filter(|j| {
                j.left < line.right
                    && j.right > line.left
                    && j.top < line.bottom
                    && j.bottom > line.top
            })
            .collect();
        assert_eq!(on.len(), 2 + usize::from(direction == Direction::Across));
        assert!(on.iter().all(|j| near.contains(j)));
    }
}

/// A dashed line across from `left` to `right` units along, 4 units wide, or a solid line
/// down at `left` to `right` across, from 0 to 100 units down, in the color of [`border`].
fn drawn(left: i64, right: i64, direction: Direction) -> super::DrawnLine {
    let u = Length::from_units;
    let edges = if direction == Direction::Across {
        f_office_units::Edges {
            left: u(left),
            top: u(50),
            right: u(right),
            bottom: u(54),
        }
    } else {
        f_office_units::Edges {
            left: u(left),
            top: u(0),
            right: u(right),
            bottom: u(100),
        }
    };
    let dash = (direction == Direction::Across).then_some(crate::props::DashStyle::Dashed);
    super::DrawnLine {
        edges,
        color: border().color.drawn(),
        dash,
    }
}

/// The rooms of [`super::cell_cuts`] for the lines across `across` and down `down`, as their
/// left and right ends.
fn cell_cut_rooms(across: &[(i64, i64)], down: &[(i64, i64)]) -> Vec<(i64, i64)> {
    let across: Vec<_> = across
        .iter()
        .map(|&(l, r)| drawn(l, r, Direction::Across))
        .collect();
    let down: Vec<_> = down
        .iter()
        .map(|&(l, r)| drawn(l, r, Direction::Down))
        .collect();
    super::cell_cuts(&across, &down)
        .into_iter()
        .map(|room| (room.edges.left.units(), room.edges.right.units()))
        .collect()
}

#[test]
fn cuts_a_dashed_line_where_it_passes_to_the_next_cell_or_leaves_a_gap_shorter_than_it_is_wide() {
    // Two cells' lines that meet, overlap or leave a gap of 3 units are cut where the second
    // starts, by a room as long as the line is wide.
    assert_eq!(cell_cut_rooms(&[(0, 100), (100, 200)], &[]), [(100, 104)]);
    assert_eq!(cell_cut_rooms(&[(0, 101), (100, 200)], &[]), [(100, 104)]);
    assert_eq!(cell_cut_rooms(&[(0, 100), (103, 200)], &[]), [(103, 107)]);
    // A gap as long as the line is wide parts two lines that the cells do not join.
    assert_eq!(cell_cut_rooms(&[(0, 100), (104, 200)], &[]), []);
    // A line down at the pass meets the line there already.
    assert_eq!(cell_cut_rooms(&[(0, 100), (100, 200)], &[(98, 102)]), []);
}

/// A border of one line `eighths` eighths of a point wide, in the automatic color.
fn border_of(eighths: i64) -> Border {
    let width = Length::from_eighth_points(eighths).expect("a whole number of units");
    Border::new(BorderParts::single(width), Length::ZERO, Color::Auto)
}

/// A device of 600 dots per inch that draws a table's line its width rounded down to whole
/// dots, as the targets whose cells' boxes place their lines by their inner edges do.
fn inner_edge_device() -> crate::grid::Device {
    crate::layout::testing::device_at(600, |profile| {
        profile.with_variant(crate::quirks::TableLines::RoundsCenters)
    })
}

/// The cell margins of a table without a style that sets them: none above or below the text and
/// those of an unset side, 10 twips (4 1/6 dots of 600 dpi), on the left and the right, as in
/// the designs of cell spacing zero.
fn default_margins() -> super::Sides<Length> {
    let side = crate::params::UNSET_SIDE_MARGIN;
    super::Sides {
        left: side,
        right: side,
        top: Length::ZERO,
        bottom: Length::ZERO,
    }
}

#[test]
fn places_the_lines_of_a_box_the_whole_dots_of_its_margins_outside_the_text_on_the_dots() {
    // A row from dot 700 to dot 825 with lines of 0.75 pt (6.25 dots) and margins of 15
    // twips (6.25 dots) above and below: the text's top, 712.5 dots, goes to dot 713 and its
    // bottom, 812.5 dots, to dot 812, a half toward the content; each line's inner edge lies 6
    // dots outside, at 707 and at 818, where Word draws them.
    let device = inner_edge_device();
    let line = border_of(6);
    let sides = super::Sides {
        left: None,
        right: None,
        top: Some(line),
        bottom: Some(line),
    };
    let fifteen = Length::from_twips(15).expect("a whole number of units");
    let margins = super::Sides {
        top: fifteen,
        bottom: fifteen,
        ..default_margins()
    };
    let edges = super::inner_edges(
        &device,
        (&sides, &margins),
        (Length::ZERO, Length::ZERO),
        (device.dots(700), device.dots(825)),
        (Length::ZERO, Length::ZERO),
    );
    assert_eq!(edges.top, Some((device.dots(707), device.dots(6))));
    assert_eq!(edges.bottom, Some((device.dots(818), device.dots(6))));
    // Margins of whole dots leave the lines where they lie without margins.
    let whole = super::Sides {
        top: Length::from_twips(12).expect("a whole number of units"),
        bottom: Length::from_twips(24).expect("a whole number of units"),
        ..default_margins()
    };
    let edges = super::inner_edges(
        &device,
        (&sides, &whole),
        (Length::ZERO, Length::ZERO),
        (device.dots(700), device.dots(825)),
        (Length::ZERO, Length::ZERO),
    );
    assert_eq!(edges.top, Some((device.dots(706), device.dots(6))));
    assert_eq!(edges.bottom, Some((device.dots(819), device.dots(6))));
}

#[test]
fn keeps_each_side_line_inside_the_dot_of_its_box_edge() {
    // A box's left edge at 5,153.5 twips goes to 5,154 twips, 2,147.5 dots. With lines of 0.75
    // pt and margins of 112 twips (46 2/3 dots), the text's left edge, 2,200 5/12 dots, goes to
    // dot 2,200, which puts the left line's inner edge 47 dots outside, at 2,153, and its outer
    // edge past the box edge's dot 2,148. The line stays inside, its inner edge at 2,154, where
    // Word draws it. A box's right edge at 2,148.5 twips goes to 2,149 twips,
    // 895 5/12 dots: the text's right edge, 842.5 dots, goes to 843, the line's inner edge 47
    // dots outside to 890, and its outer edge past dot 895, so the line's inner edge lies at 889.
    let device = inner_edge_device();
    let line = border_of(6);
    let sides = super::Sides {
        left: Some(line),
        right: Some(line),
        top: None,
        bottom: None,
    };
    let side = Length::from_twips(112).expect("a whole number of units");
    let margins = super::Sides {
        left: side,
        right: side,
        ..default_margins()
    };
    let half = Length::from_units(Length::UNITS_PER_TWIP / 2);
    let twips = |whole: i64| Length::from_twips(whole).expect("a whole number of units") + half;
    let edges = super::inner_edges(
        &device,
        (&sides, &margins),
        (twips(5153), twips(2148)),
        (Length::ZERO, Length::ZERO),
        (Length::ZERO, Length::ZERO),
    );
    assert_eq!(edges.left, Some((device.dots(2154), device.dots(6))));
    assert_eq!(edges.right, Some((device.dots(889), device.dots(6))));
}

#[test]
fn leaves_gaps_between_touching_boxes_by_the_twelfth_of_the_column_edge_and_the_line_width() {
    // Columns of 601 twips from 1,540 twips put the 11 inner edges of a table of 12 columns on
    // 11 twelfths of a dot, and each box edge lies half its left line's width further right.
    // The counts of gaps of 0, 1 and 2 dots between the right line of one box and the left
    // line of the next are those of Word's page of such a table.
    let device = inner_edge_device();
    let margins = default_margins();
    for (eighths, expected) in [
        (2, [5, 6, 0]),
        (4, [4, 7, 0]),
        (8, [0, 11, 0]),
        (12, [0, 8, 3]),
        (24, [7, 4, 0]),
    ] {
        let line = border_of(eighths);
        let sides = super::Sides {
            left: Some(line),
            right: Some(line),
            top: None,
            bottom: None,
        };
        let mut counts = [0; 3];
        for column in 1..12 {
            let edge = Length::from_twips(1540 + 601 * column).expect("a whole number of units")
                + line.width.div_toward_zero(2);
            let edges = super::inner_edges(
                &device,
                (&sides, &margins),
                (edge, edge),
                (Length::ZERO, Length::ZERO),
                (Length::ZERO, Length::ZERO),
            );
            let (left, thick) = edges.left.expect("a single left line");
            let (right, _) = edges.right.expect("a single right line");
            let gap = (left - thick) - (right + thick);
            let dots = usize::try_from(gap.units() / device.dots(1).units()).expect("no overlap");
            counts[dots] += 1;
        }
        assert_eq!(counts, expected, "lines of {eighths} eighths of a point");
    }
}

#[test]
fn places_the_lines_across_a_box_from_the_dots_of_the_table_top_and_of_the_closing_line_foot() {
    let device = inner_edge_device();
    let dots = |whole: i64, quarters: i64| {
        device.dots(whole) + Length::from_units(device.dots(1).units() * quarters / 4)
    };
    let line = border_of(4);
    let sides = super::Sides {
        left: None,
        right: None,
        top: Some(line),
        bottom: Some(line),
    };
    let wide = border_of(12).width;
    let margins = super::Sides {
        left: Length::ZERO,
        right: Length::ZERO,
        top: Length::ZERO,
        bottom: Length::ZERO,
    };
    let edges = |top, bottom, around| {
        super::inner_edges(
            &device,
            (&sides, &margins),
            (Length::ZERO, Length::ZERO),
            (top, bottom),
            around,
        )
    };
    // A row edge at 2,788.75 dots goes to dot 2,789, and the bottom line of 0.5 pt (4.17
    // dots) above it to 2,785, rounding a half toward the box's content.
    let between = edges(dots(2600, 0), dots(2788, 3), (Length::ZERO, Length::ZERO));
    assert_eq!(between.bottom, Some((device.dots(2785), device.dots(4))));
    // Above a closing line of 1.5 pt (12.5 dots), the foot of that line, 2,801.25 dots, goes
    // to dot 2,801, and the bottom line lies both widths above it, at 2,784.
    let last = edges(dots(2600, 0), dots(2788, 3), (Length::ZERO, wide));
    assert_eq!(last.bottom, Some((device.dots(2784), device.dots(4))));
    // Below an opening line of 1.5 pt, the top line's inner edge lies both widths below the
    // table's top on its dot, 2,218 + 12.5 + 4.17 dots, at 2,235.
    let first = edges(dots(2218, 1), dots(2400, 0), (wide, Length::ZERO));
    assert_eq!(first.top, Some((device.dots(2235), device.dots(4))));
}