f-office-drawingml 0.3.0

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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Gradient fills (`a:gradFill`, ECMA-376 Part 1, 20.1.8.33) of a linear shade, which
//! F-Office paints as gradient items.

use f_office_paint::{FillRule, GradientItem, GradientStop, PathCommand, Point, Rgb};
use f_office_units::fixed::{ONE, rounded, sin_cos};
use f_office_units::scale::{DRAWING_WHOLE, FULL_TURN};
use f_office_units::{Edges, Length, div_round_i128};
use f_office_warnings::Warnings;
use f_office_xml::{Document, NodeId};

use crate::color::{
    ColorNames, DrawColor, PlaceholderModifiers, SchemeColors, WORD_2010, percentage,
};
use crate::{A, Warning, attribute_of, integer, integer_of};

mod curve;
#[cfg(test)]
mod tests;

/// The most stops (`a:gs`) of a gradient that F-Office reads; a gradient with more is not
/// painted.
const MOST_STOPS: usize = 256;

/// The fewest stops of a gradient that F-Office paints.
const FEWEST_STOPS: usize = 2;

/// The largest size of a component of an axis direction in [`LinearGradient::axis`], so that
/// its products with lengths and with itself fit in an `i128`.
const DIRECTION_BITS: u32 = 31;

/// A gradient fill with a linear shade (`a:gradFill` with `a:lin`, or with no shade element on
/// a shape) that F-Office paints as Word does, between the colors of its stops along an axis at
/// its angle through the filled box: in straight lines, or along a smooth curve for a gradient
/// of two colors.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LinearGradient {
    /// Its stops in the order of their places: each place on the axis in thousandths of a
    /// percent (`pos` of `a:gs`), from the axis' start (0) to its end (100,000), and its color.
    stops: Vec<(i64, DrawColor)>,
    /// The angle of its direction (`ang` of `a:lin`), in 60,000ths of a degree, clockwise from
    /// the page's x axis with y down: 90° runs from the top to the bottom.
    angle: i64,
    /// Whether the angle is that of a unit square stretched to the filled box (`scaled` of
    /// `a:lin`), rather than the angle in the box itself.
    scaled: bool,
    /// Whether the gradient rotates and flips with its shape (`rotWithShape`, true by default).
    rot_with_shape: bool,
}

impl LinearGradient {
    /// Reads the gradient fill `fill` (`a:gradFill`), with the warnings of its values in
    /// `warnings`. `None` for a gradient that F-Office does not paint: one with a path shade
    /// (`a:path`) or with no shade, one that tiles or flips (`a:tileRect` other than the whole
    /// box, `flip` other than `none`), an angle beyond the schema's, a stop whose place does not
    /// read or lies beyond the axis, whose color does not read, is not opaque or changes by a
    /// modifier that F-Office does not apply (such as `a:hueOff`), and fewer than two or more
    /// than 256 stops. A missing angle is 0, and a missing `scaled` is false.
    #[must_use]
    pub fn read(doc: &Document, fill: NodeId, warnings: &mut Warnings<Warning>) -> Option<Self> {
        let (angle, scaled, rot_with_shape) = read_linear_head(doc, fill, false, warnings)?;
        let stops = read_stops(doc, fill, true, warnings)?;
        Some(Self {
            stops,
            angle,
            scaled,
            rot_with_shape,
        })
    }

    /// Reads a Word 2010 text gradient fill (`w14:gradFill`, [MS-DOCX] 2.6.1), where elements
    /// and attributes carry the `w14` namespace (`w14:gsLst`, `w14:gs`, `w14:pos`, `w14:lin`,
    /// `w14:ang`, `w14:scaled`). Returns `None` for path shades (`w14:path`), translucent stops,
    /// unsupported modifiers, out-of-range angles or stop positions, or fewer than 2 / more than
    /// 256 stops.
    #[must_use]
    pub fn read_word2010(
        doc: &Document,
        fill: NodeId,
        warnings: &mut Warnings<Warning>,
    ) -> Option<Self> {
        let (angle, scaled) = read_word2010_head(doc, fill)?;
        let list = doc.child(fill, WORD_2010, "gsLst")?;
        let mut stops = Vec::new();
        for stop in doc
            .child_elements(list)
            .filter(|&node| doc.is(node, WORD_2010, "gs"))
        {
            if stops.len() == MOST_STOPS {
                return None;
            }
            let place = percentage(doc.attribute(stop, Some(WORD_2010), "pos")?)?;
            let (color, unread) =
                DrawColor::read_marked(doc, stop, ColorNames::Word2010, warnings)?;
            if !(0..=DRAWING_WHOLE).contains(&place) || unread || !color.opaque() {
                return None;
            }
            stops.push((place, color));
        }
        if stops.len() < FEWEST_STOPS {
            return None;
        }
        stops.sort_by_key(|&(place, _)| place);
        Some(Self {
            stops,
            angle,
            scaled,
            rot_with_shape: true,
        })
    }

    /// The `(angle, scaled, rot_with_shape)` parameters of this linear gradient.
    pub(crate) const fn linear_params(&self) -> (i64, bool, bool) {
        (self.angle, self.scaled, self.rot_with_shape)
    }

    /// Resolves the gradient's stops against `scheme`, expanding a two-color gradient along
    /// Word's smooth curve and other gradients by straight linear stops.
    pub(crate) fn resolve_stops(&self, scheme: &SchemeColors) -> Option<Vec<GradientStop>> {
        let colors = self
            .stops
            .iter()
            .map(|(place, color)| Some((*place, color.resolve(scheme)?.0)))
            .collect::<Option<Vec<_>>>()?;
        match two_colors(&colors) {
            Some(colors) => Some(curve_stops(&colors)),
            None => colors
                .iter()
                .map(|&(place, rgb)| {
                    // A place of thousandths of a percent in millionths of the axis.
                    Some(GradientStop::new(u32::try_from(place * 10).ok()?, rgb))
                })
                .collect(),
        }
    }

    /// The gradient item that fills `commands` (with `fill_rule`) along the gradient's axis over
    /// the box from `top_left` to `bottom_right`, its colors resolved by `scheme`.
    #[must_use]
    pub fn fill_path(
        &self,
        commands: Vec<PathCommand>,
        fill_rule: FillRule,
        corners: (Point, Point),
        scheme: &SchemeColors,
    ) -> Option<GradientItem> {
        let stops = self.resolve_stops(scheme)?;
        let axis = self.axis(corners)?;
        Some(GradientItem::new(commands, fill_rule, axis, stops))
    }

    /// The gradient item that fills the box from `top_left` to `bottom_right` with the
    /// gradient, its colors resolved by `scheme`, with each stop at its place along the axis.
    /// A gradient of two colors, two stops at the axis' ends or three whose ends have one
    /// color, takes many stops instead, which follow the smooth curve between its colors with
    /// the middle color of three in the middle, as Word paints it.
    /// The axis runs through the box's middle in the gradient's direction, from the line across
    /// it through the corner where the direction starts to the line through the opposite
    /// corner; the direction is the angle's, or, for a scaled gradient, the angle's on a unit
    /// square stretched to the box. `None` when a stop's color is a theme color that `scheme`
    /// lacks, for a scaled gradient over a box with no width and no height, and for a box too
    /// large for the arithmetic.
    #[must_use]
    pub fn item(
        &self,
        (top_left, bottom_right): (Point, Point),
        scheme: &SchemeColors,
    ) -> Option<GradientItem> {
        let stops = self.resolve_stops(scheme)?;
        let (left, top, right, bottom) = (top_left.x, top_left.y, bottom_right.x, bottom_right.y);
        let corner = |x: Length, y: Length| Point { x, y };
        let commands = vec![
            PathCommand::MoveTo(corner(left, top)),
            PathCommand::LineTo(corner(right, top)),
            PathCommand::LineTo(corner(right, bottom)),
            PathCommand::LineTo(corner(left, bottom)),
            PathCommand::Close,
        ];
        let axis = self.axis((top_left, bottom_right))?;
        Some(GradientItem::new(commands, FillRule::NonZero, axis, stops))
    }

    /// The axis of the gradient over the box from `top_left` to `bottom_right`: through the
    /// box's middle in the gradient's direction, from the line across it through the corner
    /// where the direction starts to the line through the opposite corner. The direction is
    /// the angle's, or, for a scaled gradient, the angle's on a unit square stretched to the
    /// box, which has the direction (cos ÷ width, sin ÷ height). `None` for a scaled gradient
    /// over a box with no width and no height, which has no direction, and for a box too large
    /// for the arithmetic.
    fn axis(&self, corners: (Point, Point)) -> Option<(Point, Point)> {
        linear_axis(self.angle, self.scaled, corners)
    }
}

/// Computes the gradient axis for direction `(angle, scaled)` across `corners`.
pub(crate) fn linear_axis(
    angle: i64,
    scaled: bool,
    (top_left, bottom_right): (Point, Point),
) -> Option<(Point, Point)> {
    let width = i128::from((bottom_right.x - top_left.x).units());
    let height = i128::from((bottom_right.y - top_left.y).units());
    let [sin, cos] = sin_cos(i128::from(angle) * ONE);
    let (across, down) = if scaled {
        (cos * height, sin * width)
    } else {
        (cos, sin)
    };
    // Only the direction counts: the larger component moves below 2^31.
    let shift = (128
        - across
            .unsigned_abs()
            .max(down.unsigned_abs())
            .leading_zeros())
    .saturating_sub(DIRECTION_BITS);
    let (across, down) = (across >> shift, down >> shift);
    let square = across * across + down * down;
    if square == 0 {
        return None;
    }
    // The axis' length times the direction's length: times the direction, over the
    // direction's square, it is the axis from its middle to its end in doubled units.
    let reach = across
        .abs()
        .checked_mul(width.abs())?
        .checked_add(down.abs().checked_mul(height.abs())?)?;
    // The ends in doubled units from the doubled middle, so that an axis along an edge ends
    // on the box's edges.
    let offset = |component: i128| Some(rounded(component.checked_mul(reach)?, square));
    let (along, onto) = (offset(across)?, offset(down)?);
    let doubled = |low: Length, high: Length| i128::from(low.units()) + i128::from(high.units());
    let (x, y) = (
        doubled(top_left.x, bottom_right.x),
        doubled(top_left.y, bottom_right.y),
    );
    let point = |x: i128, y: i128| {
        Some(Point {
            x: Length::from_units(i64::try_from(rounded(x, 2)).ok()?),
            y: Length::from_units(i64::try_from(rounded(y, 2)).ok()?),
        })
    };
    Some((point(x - along, y - onto)?, point(x + along, y + onto)?))
}

/// The path geometry of a DrawingML `<a:path path="...">` gradient fill.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PathGradientKind {
    /// Radial circle centered in the shape box (`path="circle"`).
    Circle,
    /// Rectangular Chebyshev gradient centered at `a:fillToRect` (`path="rect"`).
    Rect,
    /// Contour gradient following the shape's geometry (`path="shape"`).
    Shape,
}

/// The shade geometry of a shape gradient fill drawn as an effect picture.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EffectGradientKind {
    /// Linear shade (`a:lin`) with translucent stops.
    Linear { angle: i64, scaled: bool },
    /// Path shade (`a:path`) with its focus center `(cx, cy)` in `0..=100_000`.
    Path {
        kind: PathGradientKind,
        focus: (i64, i64),
    },
}

/// A shape gradient fill that renders as an effect picture: either a path gradient
/// (`circle`, `rect`, or `shape`) or a linear gradient with translucent stops.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct EffectGradient {
    stops: Vec<(i64, DrawColor)>,
    kind: EffectGradientKind,
    rot_with_shape: bool,
}

impl EffectGradient {
    /// The shade geometry of this gradient.
    pub(crate) const fn kind(&self) -> EffectGradientKind {
        self.kind
    }

    /// Whether the gradient rotates and flips with its shape (`rotWithShape`).
    pub(crate) const fn rot_with_shape(&self) -> bool {
        self.rot_with_shape
    }

    /// Resolves the gradient's stops into `(place_millionths, [r, g, b, a])` entries against
    /// `scheme`. Opaque two-color path gradients expand along Word's gamma-2.2 smooth curve
    /// directly across `0..=1_000_000`; multi-stop and translucent gradients interpolate
    /// linearly in RGBA.
    pub(crate) fn resolve_stops(&self, scheme: &SchemeColors) -> Option<Vec<(u32, [u8; 4])>> {
        let mut resolved = Vec::with_capacity(self.stops.len());
        let mut all_opaque = true;
        for (place, color) in &self.stops {
            let (rgb, opacity) = color.resolve(scheme)?;
            let alpha = u8::try_from(div_round_i128(
                i128::from(opacity.share()) * 255,
                i128::from(DRAWING_WHOLE),
            ))
            .ok()?;
            if alpha < u8::MAX {
                all_opaque = false;
            }
            resolved.push((*place, rgb, alpha));
        }
        if all_opaque && matches!(self.kind, EffectGradientKind::Path { .. }) {
            let rgb_stops: Vec<(i64, Rgb)> = resolved
                .iter()
                .map(|&(place, rgb, _)| (place, rgb))
                .collect();
            if let Some(colors) = two_colors(&rgb_stops) {
                return Some(curve_direct_stops(&colors));
            }
        }
        resolved
            .iter()
            .map(|&(place, rgb, alpha)| {
                let place = u32::try_from(place * 10).ok()?;
                Some((place, [rgb.r, rgb.g, rgb.b, alpha]))
            })
            .collect()
    }
}

/// A drawable shape gradient fill: opaque linear gradients paint as vector `GradientItem`s,
/// while path gradients and translucent linear gradients paint as effect pictures.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ShapeFillGradient {
    Linear(LinearGradient),
    Effect(EffectGradient),
}

impl ShapeFillGradient {
    /// Reads any drawable shape `a:gradFill`: opaque linear (`Linear`), translucent linear
    /// (`Effect`), or path (`circle`, `rect`, `shape` -> `Effect`).
    pub(crate) fn read_shape(
        doc: &Document,
        fill: NodeId,
        warnings: &mut Warnings<Warning>,
    ) -> Option<Self> {
        let (kind, rot_with_shape) = read_shape_head(doc, fill, warnings)?;
        let stops = read_stops(doc, fill, false, warnings)?;
        match kind {
            EffectGradientKind::Linear { angle, scaled }
                if stops.iter().all(|(_, color)| color.opaque()) =>
            {
                Some(Self::Linear(LinearGradient {
                    stops,
                    angle,
                    scaled,
                    rot_with_shape,
                }))
            }
            kind => Some(Self::Effect(EffectGradient {
                stops,
                kind,
                rot_with_shape,
            })),
        }
    }

    /// The color of the first stop (lowest position).
    pub(crate) fn first_color(&self) -> Option<DrawColor> {
        let stops = match self {
            Self::Linear(grad) => &grad.stops,
            Self::Effect(grad) => &grad.stops,
        };
        stops.first().map(|(_, color)| color.clone())
    }
}

/// The resolved spatial mapping of an effect-picture shape gradient in page coordinates.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResolvedEffectGradientKind {
    /// Linear gradient axis from `start` to `end`.
    Linear {
        /// Axis start (`0%`).
        start: Point,
        /// Axis end (`100%`).
        end: Point,
    },
    /// Radial circle or ellipse centered at `center` with semi-axes `rx` and `ry`.
    Radial {
        /// Focus center (`0%`).
        center: Point,
        /// Horizontal semi-axis radius (`100%`).
        rx: Length,
        /// Vertical semi-axis radius (`100%`).
        ry: Length,
    },
    /// Rectangular Chebyshev gradient centered at `center` across `bounds`.
    Rect {
        /// Focus center (`0%`).
        center: Point,
        /// Gradient outer box (`100%`).
        bounds: Edges<Length>,
    },
    /// Shape-contour ray-to-boundary gradient centered at `center`.
    Shape {
        /// Focus center (`0%`).
        center: Point,
    },
}

/// A resolved path or translucent gradient fill for a placed shape, ready for layout to render
/// as an effect picture.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedEffectGradient {
    /// Spatial gradient mapping in page coordinates.
    pub kind: ResolvedEffectGradientKind,
    /// Sorted RGBA stops `(place_millionths, [r, g, b, a])`.
    pub stops: Vec<(u32, [u8; 4])>,
}

/// The colors of a gradient of two colors at the starts of its pieces and at its end, when
/// `stops`, each a place in thousandths of a percent and a color in the order of the places,
/// make one: two stops at the axis' start and end, or three whose first lies at the start and
/// last at the end in one color, with the middle one at any place between them, which Word
/// puts in the middle. `None` for every other gradient, which Word joins by straight lines.
fn two_colors(stops: &[(i64, Rgb)]) -> Option<Vec<Rgb>> {
    match *stops {
        [(0, first), (DRAWING_WHOLE, last)] => Some(vec![first, last]),
        [(0, first), (place, middle), (DRAWING_WHOLE, last)]
            if first == last && 0 < place && place < DRAWING_WHOLE =>
        {
            Some(vec![first, middle, last])
        }
        _ => None,
    }
}

/// The stops of a gradient through `colors`, from [`two_colors`], as Word samples it: the
/// colors at the [`curve::PIECE_STEPS`] places of each piece between two colors and at the
/// end, each at the place that Word's samples of two tiles, the first mirrored, give it in the
/// second tile, which covers the box.
fn curve_stops(colors: &[Rgb]) -> Vec<GradientStop> {
    let count = curve::PIECE_STEPS * colors.len().saturating_sub(1) + 1;
    let mut stops = Vec::with_capacity(count);
    for (piece, pair) in colors.windows(2).enumerate() {
        let [from, to] =
            [pair.first(), pair.last()].map(|color| color.copied().unwrap_or(Rgb::BLACK));
        // A piece after the first starts with the color that ends the one before it.
        let first = usize::from(piece > 0);
        for step in first..=curve::PIECE_STEPS {
            let rgb = Rgb {
                r: curve::channel(from.r, to.r, step),
                g: curve::channel(from.g, to.g, step),
                b: curve::channel(from.b, to.b, step),
            };
            let place = sample_place(piece * curve::PIECE_STEPS + step, count);
            stops.push(GradientStop::new(place, rgb));
        }
    }
    stops
}

/// Samples `colors` (from [`two_colors`]) directly across `0..=1_000_000` (without linear's
/// mirrored-tile offset), matching Word's 256-entry Type 0 radial/path curve table.
fn curve_direct_stops(colors: &[Rgb]) -> Vec<(u32, [u8; 4])> {
    let count = curve::PIECE_STEPS * colors.len().saturating_sub(1) + 1;
    let last = u64::try_from(count.saturating_sub(1)).unwrap_or(1).max(1);
    let end = u64::from(GradientStop::END);
    let mut stops = Vec::with_capacity(count);
    for (piece, pair) in colors.windows(2).enumerate() {
        let [from, to] =
            [pair.first(), pair.last()].map(|color| color.copied().unwrap_or(Rgb::BLACK));
        let first = usize::from(piece > 0);
        for step in first..=curve::PIECE_STEPS {
            let idx = u64::try_from(piece * curve::PIECE_STEPS + step).unwrap_or(last);
            let place = u32::try_from((idx * end * 2 + last) / (last * 2))
                .map_or(GradientStop::END, |p| p.min(GradientStop::END));
            stops.push((
                place,
                [
                    curve::channel(from.r, to.r, step),
                    curve::channel(from.g, to.g, step),
                    curve::channel(from.b, to.b, step),
                    u8::MAX,
                ],
            ));
        }
    }
    stops
}

/// The place, in millionths of the axis, of the sample `index` of the `count` of a tile that
/// is the second of two over twice the axis, the first mirrored: (2 index + 1) / (2 count - 1)
/// of the axis, rounded to the nearest, so that the last sample lies at the axis' end.
fn sample_place(index: usize, count: usize) -> u32 {
    let (Ok(index), Ok(count)) = (u64::try_from(index), u64::try_from(count)) else {
        return GradientStop::END;
    };
    let (part, whole) = (2 * index + 1, (2 * count).saturating_sub(1).max(1));
    let end = u64::from(GradientStop::END);
    u32::try_from((2 * part * end + whole) / (2 * whole))
        .map_or(GradientStop::END, |place| place.min(GradientStop::END))
}

/// Reads and sorts the `a:gs` stops inside `a:gsLst` of `fill`.
fn read_stops(
    doc: &Document,
    fill: NodeId,
    require_opaque: bool,
    warnings: &mut Warnings<Warning>,
) -> Option<Vec<(i64, DrawColor)>> {
    let list = doc.child(fill, A, "gsLst")?;
    let mut stops = Vec::new();
    for stop in doc
        .child_elements(list)
        .filter(|&node| doc.is(node, A, "gs"))
    {
        if stops.len() == MOST_STOPS {
            return None;
        }
        let place = attribute_of(doc, stop, "pos", percentage, warnings)?;
        let (color, unread) = DrawColor::read_marked(doc, stop, ColorNames::DrawingMl, warnings)?;
        if !(0..=DRAWING_WHOLE).contains(&place) || unread || (require_opaque && !color.opaque()) {
            return None;
        }
        stops.push((place, color));
    }
    if stops.len() < FEWEST_STOPS {
        return None;
    }
    stops.sort_by_key(|&(place, _)| place);
    Some(stops)
}

/// Reads the linear-shade `(angle, scaled)` header of a Word 2010 `w14:gradFill`, returning
/// `None` for `<w14:path>` or an out-of-range angle.
fn read_word2010_head(doc: &Document, fill: NodeId) -> Option<(i64, bool)> {
    if doc.child(fill, WORD_2010, "path").is_some() {
        return None;
    }
    let Some(shade) = doc.child(fill, WORD_2010, "lin") else {
        return Some((0, false));
    };
    let angle = match doc.attribute(shade, Some(WORD_2010), "ang") {
        Some(text) => integer(text)?,
        None => 0,
    };
    if !(0..FULL_TURN).contains(&angle) {
        return None;
    }
    let scaled = doc
        .attribute(shade, Some(WORD_2010), "scaled")
        .is_some_and(crate::boolean);
    Some((angle, scaled))
}

/// Reads the linear-shade parameters `(angle, scaled, rot_with_shape)` of `a:gradFill`,
/// returning `None` for `<a:path>`, tiled/flipped fills, out-of-range angles, or an omitted
/// `<a:lin>` when `allow_omitted_lin` is false.
fn read_linear_head(
    doc: &Document,
    fill: NodeId,
    allow_omitted_lin: bool,
    warnings: &mut Warnings<Warning>,
) -> Option<(i64, bool, bool)> {
    if doc.child(fill, A, "path").is_some() || !whole_tile(doc, fill) {
        return None;
    }
    let (angle, scaled) = match doc.child(fill, A, "lin") {
        Some(shade) => {
            let angle = integer_of(doc, shade, "ang", warnings).unwrap_or(0);
            if !(0..FULL_TURN).contains(&angle) {
                return None;
            }
            let scaled = doc
                .attribute(shade, None, "scaled")
                .is_some_and(crate::boolean);
            (angle, scaled)
        }
        None if allow_omitted_lin => (0, false),
        None => return None,
    };
    let rot_with_shape = doc
        .attribute(fill, None, "rotWithShape")
        .is_none_or(crate::boolean);
    Some((angle, scaled, rot_with_shape))
}

/// Reads a shape `a:gradFill`'s shade kind (`a:path` or `a:lin` / omitted) and `rotWithShape`.
fn read_shape_head(
    doc: &Document,
    fill: NodeId,
    warnings: &mut Warnings<Warning>,
) -> Option<(EffectGradientKind, bool)> {
    if !whole_tile(doc, fill) {
        return None;
    }
    let rot_with_shape = doc
        .attribute(fill, None, "rotWithShape")
        .is_none_or(crate::boolean);
    if let Some(path) = doc.child(fill, A, "path") {
        let kind = match doc.attribute(path, None, "path") {
            Some("circle") => PathGradientKind::Circle,
            Some("rect") => PathGradientKind::Rect,
            Some("shape") => PathGradientKind::Shape,
            _ => return None,
        };
        let focus = read_fill_to_rect(doc, path, warnings);
        return Some((EffectGradientKind::Path { kind, focus }, rot_with_shape));
    }
    let (angle, scaled, _) = read_linear_head(doc, fill, true, warnings)?;
    Some((EffectGradientKind::Linear { angle, scaled }, rot_with_shape))
}

/// Reads the focus center `(cx, cy)` in `0..=100_000` from `<a:fillToRect>` inside `<a:path>`,
/// defaulting to `(50_000, 50_000)` when `<a:fillToRect>` is omitted.
fn read_fill_to_rect(doc: &Document, path: NodeId, warnings: &mut Warnings<Warning>) -> (i64, i64) {
    let half = DRAWING_WHOLE / 2;
    let Some(rect) = doc.child(path, A, "fillToRect") else {
        return (half, half);
    };
    let mut side = |name: &str| attribute_of(doc, rect, name, percentage, warnings).unwrap_or(0);
    let (l, t, r, b) = (side("l"), side("t"), side("r"), side("b"));
    let cx = i64::midpoint(l, DRAWING_WHOLE - r).clamp(0, DRAWING_WHOLE);
    let cy = i64::midpoint(t, DRAWING_WHOLE - b).clamp(0, DRAWING_WHOLE);
    (cx, cy)
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum ThemeStopColor {
    Fixed(DrawColor),
    Placeholder(PlaceholderModifiers),
}

/// A gradient fill defined in a theme's format scheme (`a:fillStyleLst` or `a:bgFillStyleLst`),
/// whose stops may use either concrete colors or the placeholder color (`phClr`) with
/// [`PlaceholderModifiers`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ThemeGradient {
    stops: Vec<(i64, ThemeStopColor)>,
    kind: EffectGradientKind,
    rot_with_shape: bool,
}

impl ThemeGradient {
    /// Reads a drawable gradient fill element (`a:gradFill`) of a theme's format scheme.
    pub(crate) fn read(doc: &Document, fill: NodeId) -> Option<Self> {
        if !doc.is(fill, A, "gradFill") {
            return None;
        }
        let mut warnings = Warnings::new();
        let (kind, rot_with_shape) = read_shape_head(doc, fill, &mut warnings)?;
        let list = doc.child(fill, A, "gsLst")?;
        let mut stops = Vec::new();
        for stop in doc
            .child_elements(list)
            .filter(|&node| doc.is(node, A, "gs"))
        {
            if stops.len() == MOST_STOPS {
                return None;
            }
            let place = attribute_of(doc, stop, "pos", percentage, &mut warnings)?;
            if !(0..=DRAWING_WHOLE).contains(&place) {
                return None;
            }
            let color = if let Some(modifiers) =
                PlaceholderModifiers::read_child(doc, stop, &mut warnings)
            {
                ThemeStopColor::Placeholder(modifiers)
            } else {
                let (color, unread) =
                    DrawColor::read_marked(doc, stop, ColorNames::DrawingMl, &mut warnings)?;
                if unread {
                    return None;
                }
                ThemeStopColor::Fixed(color)
            };
            stops.push((place, color));
        }
        if stops.len() < FEWEST_STOPS {
            return None;
        }
        stops.sort_by_key(|&(place, _)| place);
        Some(Self {
            stops,
            kind,
            rot_with_shape,
        })
    }

    /// Resolves this theme gradient for a shape whose `a:fillRef` holds `reference_color`.
    pub(crate) fn resolve(&self, reference_color: Option<&DrawColor>) -> Option<ShapeFillGradient> {
        let mut stops = Vec::with_capacity(self.stops.len());
        for (place, stop) in &self.stops {
            let color = match stop {
                ThemeStopColor::Fixed(color) => color.clone(),
                ThemeStopColor::Placeholder(modifiers) => {
                    reference_color?.clone().in_place_of(*modifiers)
                }
            };
            stops.push((*place, color));
        }
        match self.kind {
            EffectGradientKind::Linear { angle, scaled }
                if stops.iter().all(|(_, color)| color.opaque()) =>
            {
                Some(ShapeFillGradient::Linear(LinearGradient {
                    stops,
                    angle,
                    scaled,
                    rot_with_shape: self.rot_with_shape,
                }))
            }
            kind => Some(ShapeFillGradient::Effect(EffectGradient {
                stops,
                kind,
                rot_with_shape: self.rot_with_shape,
            })),
        }
    }
}

/// Whether the gradient fill `fill` fills the box once, as Word paints it: without a flip
/// (`flip` missing or `none`) and with a tile of the whole box (`a:tileRect` missing, or with
/// no inset on any side).
fn whole_tile(doc: &Document, fill: NodeId) -> bool {
    let flips = doc
        .attribute(fill, None, "flip")
        .is_some_and(|flip| flip != "none");
    let tiled = doc.child(fill, A, "tileRect").is_some_and(|tile| {
        ["l", "t", "r", "b"].iter().any(|side| {
            doc.attribute(tile, None, side)
                .is_some_and(|inset| percentage(inset) != Some(0))
        })
    });
    !flips && !tiled
}