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
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
//! The lines that a line draws of its own: a note separator's rule, the bars of fractions and
//! radicals, a check box, and a tab's fill, underline and line through.

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

use crate::grid::{Device, LineRounding, Rounding};
use crate::layout::measure::bar_edges;
use crate::layout::{Layout, decisions};
use crate::lines::Piece;
use crate::params;
use crate::props::{Strike, Underline};
use crate::text::{Face, FaceIndex};

impl Layout<'_> {
    /// Draws a piece that paints lines of its own: a note separator's rule, a fraction's bar, a
    /// radical's or a bar structure's bar, or a check box.
    pub(super) fn draw_lines_of(&mut self, piece: Piece, x: Length, baseline: Length) {
        match piece {
            Piece::Rule { face, width } => self.rule(face, (x, width), baseline),
            Piece::Bar { face, width } => self.fraction_bar(face, (x, width), baseline),
            Piece::Vinculum {
                face,
                width,
                top,
                thickness,
                ..
            } => self.vinculum(face, (x, width), (top, thickness), baseline),
            Piece::CheckBox { face, .. } => self.check_box(face, x, baseline),
            _ => {}
        }
    }

    /// Draws the bar of a stacked fraction from `x` with its width. Its middle lies at the
    /// math axis above the fraction's own baseline and it has the math font's fraction rule
    /// thickness, both at the size of the fraction's face; its top and its bottom each lie on
    /// the nearest dot, and it is at least one dot thick, as every line of the text layout
    /// whose thickness comes from a font is. The fraction's baseline is the line's, raised or
    /// lowered as its face's glyphs are, so the bar of a fraction inside a part or a script
    /// stands on that part.
    fn fraction_bar(&mut self, face: FaceIndex, (x, width): (Length, Length), baseline: Length) {
        let Some(face) = self.shaper.faces().get(face).copied() else {
            return;
        };
        let (top, bottom) = bar_edges(&self.device, face.size);
        let own = baseline - self.device.shift_dots(face.rise);
        self.items.push(Item::Rect(Rect {
            x,
            y: own - top,
            width,
            // The edges lie on dots, so only the floor can change the thickness. Where it acts,
            // its dot lies below the top edge and ends one dot below the bottom edge, from
            // which the denominator keeps its gap minimum (`gap_minimums::keep`).
            height: self
                .device
                .line_thickness(top - bottom, LineRounding::Nearest),
            color: face.color,
        }));
    }

    /// Draws the bar of a radical or of a bar structure from `x` with its width: its top lies
    /// `top` above the baseline of its face, and it is `thickness` thick, to the nearest dot
    /// and at least one dot, as a fraction's bar is.
    fn vinculum(
        &mut self,
        face: FaceIndex,
        (x, width): (Length, Length),
        (top, thickness): (Length, Length),
        baseline: Length,
    ) {
        let Some(face) = self.shaper.faces().get(face).copied() else {
            return;
        };
        let own = baseline - self.device.shift_dots(face.rise);
        self.items.push(Item::Rect(Rect {
            x,
            y: own - top,
            width,
            height: self.device.line_thickness(thickness, LineRounding::Nearest),
            color: face.color,
        }));
    }

    /// Draws the rule of a note separator from `x` with its width, at the strikeout position
    /// and with the strikeout thickness of its face, at least one dot thick.
    fn rule(&mut self, face: FaceIndex, (x, width): (Length, Length), baseline: Length) {
        let Some(face) = self.shaper.faces().get(face).copied() else {
            return;
        };
        let top = baseline - face.scale(i64::from(face.metrics.strikeout_position));
        let thickness = face.scale(i64::from(face.metrics.strikeout_thickness));
        self.items.push(Item::Rect(Rect {
            x,
            y: self.device.snap(top),
            width,
            height: self.device.line_thickness(thickness, LineRounding::Nearest),
            color: face.color,
        }));
    }

    /// Draws the square of a check box form field. Its cell is as wide and as high as the
    /// single line of its face, from the top of that line above the baseline, with the cell's
    /// height in whole device units. Its strokes are `params::CHECK_BOX_STROKE` wide, to the
    /// nearest device dot. Its side between the middles of the strokes is the cell less three
    /// strokes, and one dot less on a target with `CheckBoxSide::ThreeStrokesAndDot`, and the
    /// square stands in the middle of the cell, with the middles of its strokes on whole device
    /// dots.
    fn check_box(&mut self, face: FaceIndex, x: Length, baseline: Length) {
        let Some(face) = self.shaper.faces().get(face).copied() else {
            return;
        };
        let stroke = self.device.snap(params::CHECK_BOX_STROKE);
        let cell = self.device.snap(face.line_height());
        // The side between the middles of the strokes: the outer edge lies one stroke inside
        // the cell on each side, and each middle half a stroke inside the outer edge.
        let three_strokes = cell - stroke * 2 - stroke;
        let side =
            decisions::check_box_side(&self.context.quirks, three_strokes, self.device.dots(1));
        // Half the room beside the side, in whole dots: the room is three strokes, so it is
        // never negative.
        let margin = self.device.floor((cell - side).div_toward_zero(2));
        let left = self.device.snap(x) + margin;
        let top = self.device.snap(baseline - face.ascent()) + margin;
        let half = stroke.div_toward_zero(2);
        let bars = [
            (left - half, top - half, side + stroke, stroke),
            (left - half, top + side - half, side + stroke, stroke),
            (left - half, top + half, stroke, side - stroke),
            (left + side - half, top + half, stroke, side - stroke),
        ];
        for (x, y, width, height) in bars {
            self.items.push(Item::Rect(Rect {
                x,
                y,
                width,
                height,
                color: face.color,
            }));
        }
    }

    /// Draws the fill, the underline and the line through of a tab's own run across the tab's
    /// width, also at the end of a line.
    pub(super) fn tab_marks(
        &mut self,
        face: FaceIndex,
        (x, width): (Length, Length),
        baseline: Length,
    ) {
        let Some(face) = self.shaper.faces().get(face).copied() else {
            return;
        };
        if width <= Length::ZERO {
            return;
        }
        if let Some(color) = face.background {
            self.items.push(Item::Rect(Rect {
                x,
                y: baseline - face.ascent(),
                width,
                height: face.ascent() + face.descent(),
                color,
            }));
        }
        // A tab has no word under it, so an underline of words leaves it out.
        let rects = run_lines(&self.device, &face, ((x, x + width), &[]), baseline);
        self.items.extend(rects.into_iter().map(Item::Rect));
    }
}

/// The rectangles of the lines of a run of `face` over `span` on `baseline`: its underline,
/// then its line through, each in the form of its kind. `words` holds the span of each word of
/// the run, under which an underline of words draws.
pub(super) fn run_lines(
    device: &Device,
    face: &Face,
    (span, words): ((Length, Length), &[(Length, Length)]),
    baseline: Length,
) -> Vec<Rect> {
    let metrics = face.metrics;
    let single = span_line(
        device,
        face,
        (span, baseline),
        (metrics.underline_position, metrics.underline_thickness),
    );
    let mut rects = Vec::new();
    // quirk: UnderlineForms (src/quirks.rs), which gives the kinds that reach here.
    match face.lines.under {
        Underline::None => {}
        Underline::Single | Underline::Wave | Underline::WavyHeavy | Underline::WavyDouble => {
            rects.push(single);
        }
        Underline::Words => rects.extend(words.iter().map(|&(start, end)| {
            let (start, end) = (device.snap(start), device.snap(end));
            Rect {
                x: start,
                width: end - start,
                ..single
            }
        })),
        Underline::Double => {
            let (upper, lower) = double_lines(device, &single, baseline);
            rects.extend([upper, lower]);
        }
        Underline::Thick => rects.push(thick_line(device, &single, baseline)),
        kind => {
            let (pattern, heavy) = dashes(kind);
            let band = if heavy {
                thick_line(device, &single, baseline)
            } else {
                single
            };
            rects.extend(dashed(device, &band, span, pattern));
        }
    }
    if face.lines.through.is_on() {
        let line = span_line(
            device,
            face,
            (span, baseline),
            (metrics.strikeout_position, metrics.strikeout_thickness),
        );
        match face.lines.through {
            Strike::Double => rects.extend([
                Rect {
                    y: line.y - line.height,
                    ..line
                },
                Rect {
                    y: line.y + line.height,
                    ..line
                },
            ]),
            Strike::Single | Strike::None => rects.push(line),
        }
    }
    rects
}

/// The two lines of a double underline, from the single underline `single` of the same run on
/// `baseline`, `p` below the baseline and `s` thick, in whole dots: each line `ceil(s / 2)`
/// thick, the upper one's top `ceil(p / 2)` below the baseline, and the lower one's bottom at
/// the single line's bottom, or lower where the lines would lie closer than the double's gap.
fn double_lines(device: &Device, single: &Rect, baseline: Length) -> (Rect, Rect) {
    let in_dots = |length: Length| device.count(length, Rounding::TowardZero);
    let below = in_dots(single.y - baseline);
    let thick = in_dots(single.height);
    let each = thick - thick.div_euclid(2);
    let upper = below - below.div_euclid(2);
    let gap = in_dots(device.snap(params::UNDERLINE_DOUBLE_GAP));
    let bottom = (below + thick).max(upper + 2 * each + gap);
    let at = |dots: i64| baseline + device.dots(dots);
    (
        Rect {
            y: at(upper),
            height: device.dots(each),
            ..*single
        },
        Rect {
            y: at(bottom - each),
            height: device.dots(each),
            ..*single
        },
    )
}

/// The line of a thick underline: from the top of a double underline's upper line to the top
/// of its lower line.
fn thick_line(device: &Device, single: &Rect, baseline: Length) -> Rect {
    let (upper, lower) = double_lines(device, single, baseline);
    Rect {
        height: lower.y - upper.y,
        ..upper
    }
}

/// The row of dots and dashes of a dotted or dashed kind of underline, as lengths that are on
/// and off in turn from the run's start, and whether the kind is heavy, drawn in the band of a
/// thick underline.
const fn dashes(kind: Underline) -> (&'static [Length], bool) {
    match kind {
        Underline::DottedHeavy => (&params::UNDERLINE_DOTTED, true),
        Underline::Dash => (&params::UNDERLINE_DASH, false),
        Underline::DashedHeavy => (&params::UNDERLINE_DASH, true),
        Underline::DashLong => (&params::UNDERLINE_DASH_LONG, false),
        Underline::DashLongHeavy => (&params::UNDERLINE_DASH_LONG, true),
        Underline::DotDash => (&params::UNDERLINE_DOT_DASH, false),
        Underline::DashDotHeavy => (&params::UNDERLINE_DOT_DASH, true),
        Underline::DotDotDash => (&params::UNDERLINE_DOT_DOT_DASH, false),
        Underline::DashDotDotHeavy => (&params::UNDERLINE_DOT_DOT_DASH, true),
        // A dotted underline, and the kinds that draw no row.
        _ => (&params::UNDERLINE_DOTTED, false),
    }
}

/// The pieces of `band` that `pattern` draws over `span`: lengths on and off in turn from the
/// span's start, each end on the nearest dot, the last piece cut at the span's end.
fn dashed(device: &Device, band: &Rect, span: (Length, Length), pattern: &[Length]) -> Vec<Rect> {
    let mut rects = Vec::new();
    let end = device.snap(span.1);
    let mut at = device.snap(span.0);
    if pattern.iter().all(|&length| length <= Length::ZERO) {
        return rects;
    }
    for (index, &length) in pattern.iter().enumerate().cycle() {
        if at >= end {
            break;
        }
        let next = device.snap(at + length).min(end);
        if index % 2 == 0 && next > at {
            rects.push(Rect {
                x: at,
                width: next - at,
                ..*band
            });
        }
        at = next.max(at + device.dots(1));
    }
    rects
}

/// A line from `start` to `end` whose top is `position` font units above the baseline. Word
/// puts the line's ends on the nearest device dots of the page, its top and its thickness on
/// whole device dots, and a line is at least one device dot thick.
fn span_line(
    device: &Device,
    face: &Face,
    ((start, end), baseline): ((Length, Length), Length),
    (position, thickness): (i16, i16),
) -> Rect {
    let thickness = device.line_thickness(face.scale(i64::from(thickness)), LineRounding::Nearest);
    let top = baseline - device.snap(face.scale(i64::from(position)));
    let (start, end) = (device.snap(start), device.snap(end));
    Rect {
        x: start,
        y: top,
        width: end - start,
        height: thickness,
        color: face.color,
    }
}

#[cfg(test)]
mod tests {
    use f_office_paint::{Rect, Rgb};
    use f_office_units::Length;

    use super::{dashed, double_lines, thick_line};
    use crate::grid::Device;
    use crate::params;
    use crate::props::{Strike, Underline};
    use crate::quirks::UnderlineForms;
    use crate::text::RunLines;

    /// A device of 600 dots per inch, whose dot is 0.12 pt.
    fn device() -> Device {
        Device::per_inch(600).unwrap()
    }

    /// A single underline from 0 to 72 pt, `below` dots below the baseline 0 and `thick` dots
    /// thick.
    fn single(below: i64, thick: i64) -> Rect {
        let dot = device().dots(1);
        Rect {
            x: Length::ZERO,
            y: dot * below,
            width: Length::from_points(72).unwrap(),
            height: dot * thick,
            color: Rgb::BLACK,
        }
    }

    /// The top and the thickness of a rectangle in dots.
    fn band(rect: &Rect) -> (i64, i64) {
        let dot = device().dots(1).units();
        (rect.y.units() / dot, rect.height.units() / dot)
    }

    #[test]
    fn puts_a_double_underline_in_a_box_from_half_the_single_lines_place() {
        // A single line 10 dots below the baseline and 6 thick: each line 3 thick, the upper
        // one at 5, and the lower one moved down to keep the gap of 8 dots.
        let (upper, lower) = double_lines(&device(), &single(10, 6), Length::ZERO);
        assert_eq!((band(&upper), band(&lower)), ((5, 3), (16, 3)));
        // 22 dots below and 10 thick: the lower line ends at the single line's bottom.
        let (upper, lower) = double_lines(&device(), &single(22, 10), Length::ZERO);
        assert_eq!((band(&upper), band(&lower)), ((11, 5), (27, 5)));
        // A thick line reaches from the upper line's top to the lower line's top.
        assert_eq!(
            band(&thick_line(&device(), &single(10, 6), Length::ZERO)),
            (5, 11)
        );
        assert_eq!(
            band(&thick_line(&device(), &single(22, 10), Length::ZERO)),
            (11, 16)
        );
        assert_eq!(
            device().snap(params::UNDERLINE_DOUBLE_GAP),
            device().dots(1) * 8
        );
    }

    #[test]
    fn draws_a_row_of_dots_from_the_runs_start_and_cuts_the_last_at_its_end() {
        let ten = Length::from_points(10).unwrap();
        let dots = dashed(
            &device(),
            &single(10, 6),
            (Length::ZERO, ten),
            &params::UNDERLINE_DOTTED,
        );
        let dot = device().dots(1).units();
        let pieces: Vec<(i64, i64)> = dots
            .iter()
            .map(|rect| (rect.x.units() / dot, (rect.x + rect.width).units() / dot))
            .collect();
        // 1.44 pt is 12 dots on and 12 off; 10 pt is 83 and a third dots, 83 on the device.
        assert_eq!(pieces, [(0, 12), (24, 36), (48, 60), (72, 83)]);
    }

    #[test]
    fn draws_every_kind_as_a_single_line_unless_the_target_draws_each_form() {
        let drawn = |lines, forms| {
            crate::text::ShaperSettings::base_with(|p| p.with_variant(forms))
                .run_lines(lines, false)
        };
        let lines = |kind, forms| drawn((Some(kind), Some(Strike::Double)), forms);
        let all_single = lines(Underline::DotDash, UnderlineForms::AllSingle);
        assert_eq!(
            (all_single.under, all_single.through),
            (Underline::Single, Strike::Single)
        );
        let by_kind = lines(Underline::DotDash, UnderlineForms::ByKind);
        assert_eq!(
            (by_kind.under, by_kind.through),
            (Underline::DotDash, Strike::Double)
        );
        // The waves stay single lines, and no line stays none.
        assert_eq!(
            lines(Underline::WavyDouble, UnderlineForms::ByKind).under,
            Underline::Single
        );
        assert_eq!(
            drawn((None, Some(Strike::None)), UnderlineForms::ByKind),
            RunLines::default()
        );
    }
}