f-office-drawingml 0.2.2

DrawingML shapes, pictures, fills, lines, themes and colors.
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
//! DrawingML line ends / arrowheads (`a:headEnd`, `a:tailEnd`, ECMA-376 Part 1, 20.1.8.37 and
//! 20.1.8.57).

use f_office_paint::{PathCommand, Point, stroke};
use f_office_units::Length;
use f_office_xml::{Document, NodeId};

use crate::A;

/// Minimum effective line width for arrowhead scaling: 2 pt (`50,800` half-EMUs).
const MIN_END_SCALE: Length = Length::from_units(2 * Length::UNITS_PER_POINT);

/// The shape of a line end (`ST_LineEndType`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EndKind {
    Triangle,
    Stealth,
    Diamond,
    Oval,
    Arrow,
}

/// The width or length class of a line end (`ST_LineEndWidth`, `ST_LineEndLength`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum EndSize {
    Small,
    #[default]
    Medium,
    Large,
}

impl EndSize {
    fn parse(value: Option<&str>) -> Self {
        match value {
            Some("sm") => Self::Small,
            Some("lg") => Self::Large,
            _ => Self::Medium,
        }
    }

    /// Standard size multiplier (`sm=2`, `med=3`, `lg=5`).
    const fn factor(self) -> i64 {
        match self {
            Self::Small => 2,
            Self::Medium => 3,
            Self::Large => 5,
        }
    }

    /// Stealth inner-notch depth multiplier (`sm=1`, `med=2`, `lg=3`).
    const fn stealth_notch(self) -> i64 {
        match self {
            Self::Small => 1,
            Self::Medium => 2,
            Self::Large => 3,
        }
    }

    /// Open-arrow wing length numerator over 2 (`sm=2.0`, `med=3.0`, `lg=4.5`).
    const fn arrow_length_halves(self) -> i64 {
        match self {
            Self::Small => 4,
            Self::Medium => 6,
            Self::Large => 9,
        }
    }

    /// Open-arrow wing half-width numerator over 4 (`sm=1.25`, `med=1.75`, `lg=2.50`).
    const fn arrow_half_width_quarters(self) -> i64 {
        match self {
            Self::Small => 5,
            Self::Medium => 7,
            Self::Large => 10,
        }
    }
}

/// One arrowhead at the start (`headEnd`) or end (`tailEnd`) of an open stroke.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct LineEnd {
    pub(crate) kind: EndKind,
    pub(crate) width: EndSize,
    pub(crate) length: EndSize,
}

/// Both optional ends of an open stroke.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct LineEnds {
    pub(crate) head: Option<LineEnd>,
    pub(crate) tail: Option<LineEnd>,
}

/// What `read_ends` found on an `a:ln` element.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ReadEnds {
    /// Neither `a:headEnd` nor `a:tailEnd` was present (shape inherits from `a:lnRef`).
    Omitted,
    /// Explicit ends (possibly both `none`).
    Present(LineEnds),
    /// An end had an unrecognized `type` attribute.
    Unsupported,
}

impl LineEnds {
    /// Whether either end draws an arrowhead.
    pub(crate) const fn any(self) -> bool {
        self.head.is_some() || self.tail.is_some()
    }
}

/// Reads `a:headEnd` and `a:tailEnd` on `ln`.
pub(crate) fn read_ends(doc: &Document, ln: NodeId) -> ReadEnds {
    let head_node = doc.child(ln, A, "headEnd");
    let tail_node = doc.child(ln, A, "tailEnd");
    if head_node.is_none() && tail_node.is_none() {
        return ReadEnds::Omitted;
    }
    let head = match head_node.map_or(ReadOne::None, |n| read_one(doc, n)) {
        ReadOne::None => None,
        ReadOne::End(end) => Some(end),
        ReadOne::Unsupported => return ReadEnds::Unsupported,
    };
    let tail = match tail_node.map_or(ReadOne::None, |n| read_one(doc, n)) {
        ReadOne::None => None,
        ReadOne::End(end) => Some(end),
        ReadOne::Unsupported => return ReadEnds::Unsupported,
    };
    ReadEnds::Present(LineEnds { head, tail })
}

enum ReadOne {
    None,
    End(LineEnd),
    Unsupported,
}

/// Reads one `a:headEnd` or `a:tailEnd` element.
fn read_one(doc: &Document, node: NodeId) -> ReadOne {
    let kind = match doc.attribute(node, None, "type") {
        None | Some("none") => return ReadOne::None,
        Some("triangle") => EndKind::Triangle,
        Some("stealth") => EndKind::Stealth,
        Some("diamond") => EndKind::Diamond,
        Some("oval") => EndKind::Oval,
        Some("arrow") => EndKind::Arrow,
        Some(_) => return ReadOne::Unsupported,
    };
    ReadOne::End(LineEnd {
        kind,
        width: EndSize::parse(doc.attribute(node, None, "w")),
        length: EndSize::parse(doc.attribute(node, None, "len")),
    })
}

impl LineEnd {
    /// How far the line shaft is shortened from this end for a stroke of drawn width `width`.
    pub(crate) fn shorten(self, width: Length) -> Length {
        let scale = width.max(MIN_END_SCALE);
        match self.kind {
            EndKind::Triangle => scale * self.length.factor() - scale.div_round(2),
            EndKind::Stealth => scale * self.length.stealth_notch(),
            EndKind::Diamond | EndKind::Oval => Length::ZERO,
            EndKind::Arrow => {
                let (back, half_span) = arrow_wing(scale, self.width, self.length);
                arrow_miter(width.div_toward_zero(2), back, half_span)
            }
        }
    }

    /// Filled path commands (`FillRule::NonZero`) for this arrowhead placed at `tip`, pointing
    /// along the outward tangent from `from` to `tip`, on a stroke of drawn width `width`.
    pub(crate) fn commands(self, from: Point, tip: Point, width: Length) -> Vec<PathCommand> {
        let dx = i128::from((tip.x - from.x).units());
        let dy = i128::from((tip.y - from.y).units());
        let len = (dx * dx + dy * dy).isqrt();
        if len == 0 {
            return Vec::new();
        }
        let frame = LocalFrame { tip, dx, dy, len };
        let scale = width.max(MIN_END_SCALE);
        let full_len = scale * self.length.factor();
        let half_w = (scale * self.width.factor()).div_round(2);
        match self.kind {
            EndKind::Triangle => vec![
                PathCommand::MoveTo(frame.at(Length::ZERO, Length::ZERO)),
                PathCommand::LineTo(frame.at(-full_len, -half_w)),
                PathCommand::LineTo(frame.at(-full_len, half_w)),
                PathCommand::Close,
            ],
            EndKind::Stealth => {
                let notch = scale * self.length.stealth_notch();
                vec![
                    PathCommand::MoveTo(frame.at(Length::ZERO, Length::ZERO)),
                    PathCommand::LineTo(frame.at(-full_len, -half_w)),
                    PathCommand::LineTo(frame.at(-notch, Length::ZERO)),
                    PathCommand::LineTo(frame.at(-full_len, half_w)),
                    PathCommand::Close,
                ]
            }
            EndKind::Diamond => {
                let rx = full_len.div_round(2);
                vec![
                    PathCommand::MoveTo(frame.at(rx, Length::ZERO)),
                    PathCommand::LineTo(frame.at(Length::ZERO, -half_w)),
                    PathCommand::LineTo(frame.at(-rx, Length::ZERO)),
                    PathCommand::LineTo(frame.at(Length::ZERO, half_w)),
                    PathCommand::Close,
                ]
            }
            EndKind::Oval => oval_commands(&frame, full_len.div_round(2), half_w),
            EndKind::Arrow => arrow_commands(&frame, width, scale, self.width, self.length),
        }
    }
}

/// Trims `head` units from the start and `tail` units from the end of an open polyline `points`.
/// Returns an empty vector if the trimming consumes the entire polyline.
pub(crate) fn trim_polyline(points: &[Point], head: Length, tail: Length) -> Vec<Point> {
    let trimmed = trim_start(points, head.max(Length::ZERO));
    if trimmed.len() < 2 {
        return Vec::new();
    }
    let mut rev: Vec<Point> = trimmed.into_iter().rev().collect();
    rev = trim_start(&rev, tail.max(Length::ZERO));
    if rev.len() < 2 {
        return Vec::new();
    }
    rev.reverse();
    rev
}

/// First non-degenerate outward `(from, tip)` tangent at the start (`head`) of `points`.
pub(crate) fn head_tangent(points: &[Point]) -> Option<(Point, Point)> {
    let tip = *points.first()?;
    let next = points
        .iter()
        .skip(1)
        .copied()
        .find(|p| p.x != tip.x || p.y != tip.y)?;
    Some((next, tip))
}

/// Last non-degenerate outward `(from, tip)` tangent at the end (`tail`) of `points`.
pub(crate) fn tail_tangent(points: &[Point]) -> Option<(Point, Point)> {
    let tip = *points.last()?;
    let prev = points
        .iter()
        .rev()
        .skip(1)
        .copied()
        .find(|p| p.x != tip.x || p.y != tip.y)?;
    Some((prev, tip))
}

/// Trims `amount` along `points` from its start.
fn trim_start(points: &[Point], amount: Length) -> Vec<Point> {
    if amount <= Length::ZERO || points.len() < 2 {
        return points.to_vec();
    }
    let mut left = i128::from(amount.units());
    for (idx, pair) in points.windows(2).enumerate() {
        let [a, b] = *pair else { continue };
        let dx = i128::from((b.x - a.x).units());
        let dy = i128::from((b.y - a.y).units());
        let seg = (dx * dx + dy * dy).isqrt();
        if seg == 0 {
            continue;
        }
        if left < seg {
            let start = Point {
                x: a.x + Length::from_units(round_div(dx * left, seg)),
                y: a.y + Length::from_units(round_div(dy * left, seg)),
            };
            let mut out = Vec::with_capacity(points.len() - idx);
            out.push(start);
            if let Some(rest) = points.get(idx + 1..) {
                out.extend_from_slice(rest);
            }
            return out;
        }
        left -= seg;
    }
    Vec::new()
}

/// Local orthonormal frame centered at `tip`, with `+along` along `(dx, dy)` and `+perp` along
/// `(-dy, dx)`.
struct LocalFrame {
    tip: Point,
    dx: i128,
    dy: i128,
    len: i128,
}

impl LocalFrame {
    fn at(&self, along: Length, perp: Length) -> Point {
        let a = i128::from(along.units());
        let p = i128::from(perp.units());
        Point {
            x: self.tip.x + Length::from_units(round_div(self.dx * a - self.dy * p, self.len)),
            y: self.tip.y + Length::from_units(round_div(self.dy * a + self.dx * p, self.len)),
        }
    }
}

/// Filled oval arrowhead centered at `tip` with semi-axes `(rx, ry)`, wound counter-clockwise
/// to match [`stroke::band`] and [`stroke::disc`] under `FillRule::NonZero`.
fn oval_commands(frame: &LocalFrame, rx: Length, ry: Length) -> Vec<PathCommand> {
    let kx = stroke::kappa(rx);
    let ky = stroke::kappa(ry);
    let zero = Length::ZERO;
    vec![
        PathCommand::MoveTo(frame.at(zero, -ry)),
        PathCommand::CubicTo(frame.at(-kx, -ry), frame.at(-rx, -ky), frame.at(-rx, zero)),
        PathCommand::CubicTo(frame.at(-rx, ky), frame.at(-kx, ry), frame.at(zero, ry)),
        PathCommand::CubicTo(frame.at(kx, ry), frame.at(rx, ky), frame.at(rx, zero)),
        PathCommand::CubicTo(frame.at(rx, -ky), frame.at(kx, -ry), frame.at(zero, -ry)),
        PathCommand::Close,
    ]
}

/// Open-V `arrow` wing offsets `(back, half_span)` from the centerline apex.
fn arrow_wing(scale: Length, width: EndSize, length: EndSize) -> (Length, Length) {
    let back = (scale * length.arrow_length_halves()).div_round(2);
    let half_span = (scale * width.arrow_half_width_quarters()).div_round(4);
    (back, half_span)
}

/// Miter extension `(half / sin(alpha))` along the shaft for an open V of half-stroke `half`.
fn arrow_miter(half: Length, back: Length, half_span: Length) -> Length {
    let dx = i128::from(back.units());
    let dy = i128::from(half_span.units());
    if dy <= 0 {
        return Length::ZERO;
    }
    let arm = (dx * dx + dy * dy).isqrt();
    Length::from_units(round_div(i128::from(half.units()) * arm, dy))
}

/// Filled outline of an open-V `arrow` end: miter-joined chevron whose outer tip sits at `tip`
/// (`0, 0`), with round caps of radius `width / 2` at both wing tips.
fn arrow_commands(
    frame: &LocalFrame,
    width: Length,
    scale: Length,
    w_size: EndSize,
    l_size: EndSize,
) -> Vec<PathCommand> {
    let half = width.div_toward_zero(2);
    let (back, half_span) = arrow_wing(scale, w_size, l_size);
    let dx = i128::from(back.units());
    let dy = i128::from(half_span.units());
    let arm = (dx * dx + dy * dy).isqrt();
    if arm == 0 || dy == 0 {
        return Vec::new();
    }
    let miter = Length::from_units(round_div(i128::from(half.units()) * arm, dy));
    // Normal offset from wing centerline to outer edge: `(nx, ny) = (dy, dx) * half / arm`.
    let nx = Length::from_units(round_div(dy * i128::from(half.units()), arm));
    let ny = Length::from_units(round_div(dx * i128::from(half.units()), arm));
    let back_x = -miter - back;
    let w_top = frame.at(back_x, -half_span);
    let w_bot = frame.at(back_x, half_span);
    let mut commands = vec![
        PathCommand::MoveTo(frame.at(back_x + nx, -half_span - ny)),
        PathCommand::LineTo(frame.at(back_x - nx, -half_span + ny)),
        PathCommand::LineTo(frame.at(-(miter * 2), Length::ZERO)),
        PathCommand::LineTo(frame.at(back_x - nx, half_span - ny)),
        PathCommand::LineTo(frame.at(back_x + nx, half_span + ny)),
        PathCommand::LineTo(frame.at(Length::ZERO, Length::ZERO)),
        PathCommand::Close,
    ];
    commands.extend(stroke::disc(w_top, half));
    commands.extend(stroke::disc(w_bot, half));
    commands
}

/// Rounds `num / den` (`den > 0`) to the nearest `i64`.
fn round_div(num: i128, den: i128) -> i64 {
    let rounded = if num >= 0 {
        (num + den / 2) / den
    } else {
        (num - den / 2) / den
    };
    i64::try_from(rounded).unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pt(x: i64, y: i64) -> Point {
        Point {
            x: Length::from_points(x).unwrap(),
            y: Length::from_points(y).unwrap(),
        }
    }

    #[test]
    fn scales_arrowheads_with_two_point_minimum_floor() {
        let tri = LineEnd {
            kind: EndKind::Triangle,
            width: EndSize::Medium,
            length: EndSize::Medium,
        };
        let thin = Length::from_emus(9_525).unwrap(); // 0.75 pt -> s = 2 pt
        let thick = Length::from_points(4).unwrap(); // 4 pt -> s = 4 pt
        assert_eq!(tri.shorten(thin), Length::from_points(5).unwrap());
        assert_eq!(tri.shorten(thick), Length::from_points(10).unwrap());
        let stealth = LineEnd {
            kind: EndKind::Stealth,
            width: EndSize::Medium,
            length: EndSize::Medium,
        };
        assert_eq!(stealth.shorten(thin), Length::from_points(4).unwrap());
        assert_eq!(stealth.shorten(thick), Length::from_points(8).unwrap());
        let oval = LineEnd {
            kind: EndKind::Oval,
            width: EndSize::Medium,
            length: EndSize::Medium,
        };
        assert_eq!(oval.shorten(thick), Length::ZERO);
    }

    #[test]
    fn trims_polylines_and_builds_all_five_arrowhead_shapes() {
        let poly = [pt(0, 0), pt(100, 0), pt(100, 60)];
        let trimmed = trim_polyline(
            &poly,
            Length::from_points(10).unwrap(),
            Length::from_points(15).unwrap(),
        );
        assert_eq!(trimmed, vec![pt(10, 0), pt(100, 0), pt(100, 45)]);
        assert_eq!(
            trim_polyline(
                &[pt(0, 0), pt(10, 0)],
                Length::from_points(8).unwrap(),
                Length::from_points(8).unwrap(),
            ),
            Vec::new()
        );
        let w = Length::from_points(4).unwrap();
        for kind in [
            EndKind::Triangle,
            EndKind::Stealth,
            EndKind::Diamond,
            EndKind::Oval,
            EndKind::Arrow,
        ] {
            let end = LineEnd {
                kind,
                width: EndSize::Medium,
                length: EndSize::Medium,
            };
            assert_ne!(end.commands(pt(0, 0), pt(100, 0), w), Vec::new());
        }
    }
}