f-office-docx 0.2.2

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
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
//! Pictures in the EMF and WMF formats, drawn from their records.
//!
//! `f-office-emf` plays the records of an EMF or WMF picture into the picture's box. Its lines,
//! shapes and bitmaps are display list items, and its text comes back with a face name and a
//! size, which the shaper turns into glyphs here. A face that the target has draws its own
//! text. The text of a face that the target lacks takes the face that the target's font mapper
//! gives the font's character set and pitch and family, when the target's font environment
//! knows it, and otherwise the faces that Word's own text would find for that name. What an
//! EMF picture draws shows only inside the box of the picture, inside its crop, and inside the
//! clips of its records.

use f_office_drawingml::color::on_white;
use f_office_drawingml::shape::{Geometry, outside_ring, picture_clip_path, picture_outside_ring};
use f_office_drawingml::{Feature as DrawingMlFeature, Warning as DrawingMlWarning};
use f_office_effects::{MaskFormat, MaskSource};
use f_office_emf::{Drawing, FontHeight, Frame, Horizontal, Text, Vertical};
use f_office_paint::{
    Clip, FillRule, Glyph as PaintGlyph, GlyphRun, Group, GroupClip, GroupPlaces, ImageFormat,
    Item, Opacity, PathCommand, PathItem, Point, Rect, Rgb, Turn,
};
use f_office_units::{Edges, Length};

use super::{Layout, decisions};
use crate::FamilyName;
use crate::picture::Picture;
use crate::props::{FontRef, RunProps};
use crate::text::FaceIndex;

use crate::params::METAFILE_BOLD_WEIGHT as BOLD_WEIGHT;

impl Layout<'_> {
    /// The items of a picture when the drawing's box has its top left corner at `x` and
    /// `top`: its outer shadow ([`Self::picture_shadow`]), the picture's own items
    /// ([`Self::picture_image`]), then its line.
    pub(super) fn picture_items(&mut self, picture: &Picture, x: Length, top: Length) -> Vec<Item> {
        self.picture_items_in(picture, x, top, None)
    }

    /// The items of a picture as [`Self::picture_items`] gives them, with its own items cut to
    /// `cut` where it has one and the picture reaches past it ([`clipped_to`]).
    pub(super) fn picture_items_in(
        &mut self,
        picture: &Picture,
        x: Length,
        top: Length,
        cut: Option<PictureCut>,
    ) -> Vec<Item> {
        let line = self.picture_line(picture, x, top);
        let mut items = self.picture_shadow(picture, (x, top), line.as_ref());
        items.extend(self.picture_glow(picture, (x, top), line.as_ref()));
        items.extend(self.picture_reflection(picture, (x, top)));
        let (image, baked_line) = if let Some(soft_edge) = picture.soft_edge.as_deref() {
            if let Some(feathered) = self.picture_soft_edge(picture, (x, top), soft_edge.radius) {
                (vec![feathered], true)
            } else {
                self.output.warnings.push(crate::Warning::DrawingMl {
                    part: soft_edge.part.clone(),
                    warning: DrawingMlWarning::FeatureNotSupported {
                        feature: DrawingMlFeature::SoftEdge,
                    },
                });
                (self.picture_image(picture, x, top), false)
            }
        } else {
            (self.picture_image(picture, x, top), false)
        };
        let image = if !baked_line
            && !image.is_empty()
            && let Some((commands, fill_rule)) = picture.clip_path(x, top)
        {
            vec![Item::Group(Group {
                items: image,
                clip: Some(GroupClip {
                    commands,
                    fill_rule,
                }),
                places: GroupPlaces::Own,
            })]
        } else {
            image
        };
        match cut.zip(picture.drawn_bounds(x, top)) {
            Some((cut, bounds)) => items.extend(clipped_to(image, bounds, cut)),
            None => items.extend(image),
        }
        if !baked_line {
            items.extend(line);
        }
        items
    }

    /// The effect-picture item of a raster picture with `a:softEdge`, baking any picture border
    /// into the feathered image. Returns `None` for metafiles or pictures outside effect limits.
    fn picture_soft_edge(
        &self,
        picture: &Picture,
        (x, top): (Length, Length),
        radius: Length,
    ) -> Option<Item> {
        let image = picture.image.as_ref()?;
        let format = mask_format(image.format)?;
        let shown = picture.shown(x, top)?;
        let border = decisions::picture_line(&self.context.quirks, || {
            let (rgb, alpha, width) = picture
                .line
                .as_ref()?
                .resolve(&self.shaper.theme().shapes)?;
            Some((on_white(rgb, alpha), width))
        });
        let clip = picture_clip_path(&picture.geometry, shown);
        let bytes = image.load_bytes()?;
        super::shadow::soft_edge_picture(super::shadow::SoftEdgePlacement {
            format,
            data: &bytes,
            shown,
            crop: picture.crop,
            border,
            clip,
            opacity: picture.opacity,
            color: picture.color.clone(),
            turn: picture.turn,
            radius,
        })
    }

    /// The items of a picture's own outer shadow where the target draws it
    /// ([`decisions::picture_shadow`]): an opaque, uncropped, upright-or-quarter-turned picture
    /// ([`opaque_picture`]) casts its whole covered box filled together with its `line`, as a
    /// shape's ([`super::shadow::items`]). Any other raster picture (PNG with alpha, GIF, BMP,
    /// TIFF, `a:alphaModFix`, negative crop, or non-quarter turn) casts its alpha channel masked
    /// by its crop and scaled by its opacity, composited beneath its `line`
    /// ([`super::shadow::masked_picture`]). Metafile pictures and shadows that cast nothing are
    /// left out with a warning.
    fn picture_shadow(
        &mut self,
        picture: &Picture,
        (x, top): (Length, Length),
        line: Option<&Item>,
    ) -> Vec<Item> {
        let Some(shadow) = picture.shadow.as_deref() else {
            return Vec::new();
        };
        let glow_radius = picture
            .glow
            .as_deref()
            .map_or(Length::ZERO, |glow| glow.glow.radius);
        let theme = &self.shaper.theme().shapes;
        let cast = decisions::picture_shadow(&self.context.quirks, || {
            let color = shadow.shadow.color(theme)?;
            if opaque_picture(picture) {
                let frame = opaque_picture_frame(picture, (x, top), line)?;
                return super::shadow::items_with_glow(
                    shadow.shadow.blur,
                    shadow.shadow.offset(),
                    color,
                    glow_radius,
                    &frame,
                );
            }
            let (covered, placement) = picture_mask_placement(picture, (x, top))?;
            super::shadow::masked_picture_with_glow(
                covered,
                line,
                placement,
                shadow.shadow.offset(),
                shadow.shadow.blur,
                glow_radius,
                color,
            )
            .map(|item| vec![item])
        })
        .flatten();
        cast.unwrap_or_else(|| {
            self.output.warnings.push(crate::Warning::DrawingMl {
                part: shadow.part.clone(),
                warning: DrawingMlWarning::FeatureNotSupported {
                    feature: DrawingMlFeature::Shadow,
                },
            });
            Vec::new()
        })
    }

    /// The items of a picture's own glow (`a:glow`) where the target draws picture shadows
    /// ([`decisions::picture_shadow`]). Metafile pictures and glows that cast nothing are left
    /// out with a warning.
    fn picture_glow(
        &mut self,
        picture: &Picture,
        (x, top): (Length, Length),
        line: Option<&Item>,
    ) -> Vec<Item> {
        let Some(glow) = picture.glow.as_deref() else {
            return Vec::new();
        };
        let theme = &self.shaper.theme().shapes;
        let cast = decisions::picture_shadow(&self.context.quirks, || {
            let color = glow.glow.color(theme)?;
            if opaque_picture(picture) {
                let frame = opaque_picture_frame(picture, (x, top), line)?;
                return super::shadow::glow_items(glow.glow.radius, color, &frame);
            }
            let (covered, placement) = picture_mask_placement(picture, (x, top))?;
            super::shadow::masked_picture_glow(covered, line, placement, glow.glow.radius, color)
                .map(|item| vec![item])
        })
        .flatten();
        cast.unwrap_or_else(|| {
            self.output.warnings.push(crate::Warning::DrawingMl {
                part: glow.part.clone(),
                warning: DrawingMlWarning::FeatureNotSupported {
                    feature: DrawingMlFeature::Glow,
                },
            });
            Vec::new()
        })
    }

    /// The effect picture of a picture's own reflection (`a:reflection`) where the target draws
    /// picture effects ([`decisions::picture_shadow`]). Metafile, turned, or out-of-range pictures
    /// are left out with a warning.
    fn picture_reflection(
        &mut self,
        picture: &Picture,
        (x, top): (Length, Length),
    ) -> Option<Item> {
        let reflection = picture.reflection.as_deref()?;
        let cast = decisions::picture_shadow(&self.context.quirks, || {
            let image = picture.image.as_ref()?;
            let format = mask_format(image.format)?;
            let shown = picture.shown(x, top)?;
            let border = decisions::picture_line(&self.context.quirks, || {
                let (rgb, alpha, width) = picture
                    .line
                    .as_ref()?
                    .resolve(&self.shaper.theme().shapes)?;
                Some((on_white(rgb, alpha), width))
            });
            let clip = picture_clip_path(&picture.geometry, shown);
            let bytes = image.load_bytes()?;
            super::shadow::picture_reflection_item(super::shadow::PictureReflectionPlacement {
                format,
                data: &bytes,
                shown,
                crop: picture.crop,
                border,
                clip,
                opacity: picture.opacity,
                color: picture.color.clone(),
                turn: picture.turn,
                reflection: reflection.reflection,
            })
        })
        .flatten();
        if cast.is_none() {
            self.output.warnings.push(crate::Warning::DrawingMl {
                part: reflection.part.clone(),
                warning: DrawingMlWarning::FeatureNotSupported {
                    feature: DrawingMlFeature::Reflection,
                },
            });
        }
        cast
    }

    /// The line around a picture where the target draws it, turned with the picture
    /// ([`Picture::turned_line`]). Like a shape's line, a white line is drawn as any other
    /// color, and a color that lets the page show through is mixed with white.
    fn picture_line(&self, picture: &Picture, x: Length, top: Length) -> Option<Item> {
        decisions::picture_line(&self.context.quirks, || {
            let (rgb, alpha, width) = picture
                .line
                .as_ref()?
                .resolve(&self.shaper.theme().shapes)?;
            let color = on_white(rgb, alpha);
            if picture.geometry == Geometry::Rect {
                let ring = outside_ring(picture.covered(x, top)?, width, color);
                return picture.turned_line(x, top, ring);
            }
            let mut ring =
                picture_outside_ring(&picture.geometry, picture.shown(x, top)?, width, color)?;
            if let Item::Path(path) = &mut ring {
                picture.turn_commands(x, top, &mut path.commands)?;
            }
            Some(ring)
        })
    }

    /// The drawing of an EMF or WMF picture, in one group, or the image item of any other
    /// picture, when the drawing's box has its top left corner at `x` and `top`. A target's
    /// PDF writer draws a metafile in its own space, where the writer's stretch and digits do
    /// not reach. The group of an EMF picture shows nothing outside the box that the picture
    /// shows, inside its crop; a WMF picture's group cuts nothing.
    fn picture_image(&mut self, picture: &Picture, x: Length, top: Length) -> Vec<Item> {
        let metafile = picture
            .image
            .as_ref()
            .filter(|image| matches!(image.format, ImageFormat::Emf | ImageFormat::Wmf));
        let drawings = metafile
            .zip(picture.whole(x, top))
            .and_then(|(image, whole)| {
                let frame = Frame {
                    x: whole.left,
                    y: whole.top,
                    width: whole.width(),
                    height: whole.height(),
                };
                // The reader keeps the warnings of each picture's records once
                // (`warnings::of_metafile`), so each placement drops its own.
                let bytes = image.load_bytes()?;
                let played = if image.format == ImageFormat::Wmf {
                    f_office_emf::play_wmf(&bytes, frame)
                } else {
                    f_office_emf::play(&bytes, frame)
                };
                played.map(|played| played.value)
            });
        let Some(drawings) = drawings else {
            return picture.item(x, top).into_iter().collect();
        };
        let clip = metafile
            .filter(|image| image.format == ImageFormat::Emf)
            .and_then(|_| picture.shown(x, top))
            .map(|shown| GroupClip::rect(shown.left, shown.top, shown.width(), shown.height()));
        vec![Item::Group(Group {
            items: self.metafile_items(drawings),
            clip,
            places: GroupPlaces::Own,
        })]
    }

    /// The items of a metafile's drawings, a clip of its records as a group with that clip.
    fn metafile_items(&mut self, drawings: Vec<Drawing>) -> Vec<Item> {
        let mut items = Vec::with_capacity(drawings.len());
        for drawing in drawings {
            match drawing {
                Drawing::Item(item) => items.push(item),
                Drawing::Text(text) => items.extend(self.metafile_text(&text)),
                Drawing::Clipped(clipped) => items.push(Item::Group(Group {
                    items: self.metafile_items(clipped.drawings),
                    clip: Some(clipped.clip),
                    places: GroupPlaces::Own,
                })),
            }
        }
        items
    }

    /// The items of a line of metafile text: optional opaque background box, glyph run, and
    /// optional strikeout line; empty when no face has its glyphs.
    fn metafile_text(&mut self, text: &Text) -> Vec<Item> {
        let bold = text.weight >= BOLD_WEIGHT;
        let family = self.metafile_family(text, bold);
        let props = RunProps {
            font_ascii: Some(FontRef::Name(family.clone())),
            font_hansi: Some(FontRef::Name(family)),
            bold: Some(bold),
            italic: Some(text.italic),
            size: Some(1),
            ..RunProps::default()
        };
        let Some(face) = self.shaper.line_face(&props) else {
            return Vec::new();
        };
        let Some(&found) = self.shaper.faces().get(face) else {
            return Vec::new();
        };
        let metrics = found.metrics;
        let per_em = i64::from(metrics.units_per_em.max(1));
        let (ascent, descent) = (i64::from(metrics.hhea_ascender), i64::from(metrics.descent));
        let em = match text.height {
            FontHeight::Em(em) => em,
            FontHeight::Cell(cell) => {
                f_office_units::div_round(cell * per_em, (ascent + descent).max(1))
            }
        };
        let scaled = |font_units: i64| f_office_units::div_round(font_units * em, per_em);
        let baseline = match text.align.vertical {
            Vertical::Baseline => text.y,
            Vertical::Top => {
                text.y
                    + decisions::metafile_top_ascent(
                        &self.context.quirks,
                        || scaled(ascent),
                        || self.logical_pixel_ascent(text, face),
                    )
            }
            Vertical::Bottom => text.y - scaled(descent),
        };
        let (start, total, placed) =
            self.place_metafile_glyphs(text, face, found.font, baseline, |font_units| {
                f_office_units::div_round(font_units * em, per_em)
            });
        let Some(placed) = placed else {
            return Vec::new();
        };
        let mut out = Vec::new();
        let origin = (text.x, text.y);
        if let Some(bg) = text.background
            && total > 0
        {
            out.push(turned_box(
                text.turn,
                origin,
                (start, baseline - scaled(ascent)),
                (start + total, baseline + scaled(descent)),
                bg,
            ));
        }
        out.push(Item::Glyphs(GlyphRun {
            font: found.font,
            size: Length::from_units(em),
            color: text.color,
            text: text.text.clone(),
            glyphs: placed,
            outline: None,
            filled: true,
            effect: false,
            turn: text.turn,
        }));
        if text.strikeout && total > 0 {
            let top = baseline - scaled(i64::from(metrics.strikeout_position));
            let thick = scaled(i64::from(metrics.strikeout_thickness)).max(1);
            out.push(turned_box(
                text.turn,
                origin,
                (start, top),
                (start + total, top + thick),
                text.color,
            ));
        }
        out
    }

    /// Places the glyphs of a metafile text line, returning `(start_x, total_width, glyphs)`.
    fn place_metafile_glyphs(
        &mut self,
        text: &Text,
        face: FaceIndex,
        font: f_office_fonts::FontId,
        baseline: i64,
        scaled: impl Fn(i64) -> i64,
    ) -> (i64, i64, Option<Vec<PaintGlyph>>) {
        let chars: Vec<(usize, char)> = text.text.char_indices().collect();
        let glyphs: Vec<(u32, i64)> = chars
            .iter()
            .enumerate()
            .map(|(index, (_, ch))| {
                let id = self.shaper.glyph(face, *ch).map_or(0, |g| g.id);
                let own = self
                    .shaper
                    .font_advance(font, id)
                    .map_or(0, |advance| scaled(i64::from(advance)));
                let advance = text
                    .advances
                    .as_ref()
                    .and_then(|list| list.get(index).copied())
                    .unwrap_or(own);
                (id, advance)
            })
            .collect();
        let total: i64 = glyphs.iter().map(|(_, advance)| advance).sum();
        let start = match text.align.horizontal {
            Horizontal::Left => text.x,
            Horizontal::Center => text.x - total / 2,
            Horizontal::Right => text.x - total,
        };
        let mut x = start;
        let mut placed = Vec::with_capacity(chars.len());
        for ((id, advance), (index, ch)) in glyphs.iter().zip(&chars) {
            let end = index + ch.len_utf8();
            let (x_turned, y_turned) = turned(text.turn, (text.x, text.y), (x, baseline));
            let (Ok(text_start), Ok(text_end)) = (u32::try_from(*index), u32::try_from(end)) else {
                return (start, total, None);
            };
            placed.push(PaintGlyph {
                id: *id,
                x: Length::from_units(x_turned),
                y: Length::from_units(y_turned),
                text_start,
                text_end,
            });
            x += advance;
        }
        (start, total, Some(placed))
    }

    /// The pixel ascent of the face `face` at the size of a line's font in whole logical units,
    /// times the size of a logical unit at the scale of the line; `None` for a font of a cell
    /// height or of a size beyond the pixel sizes of a font.
    fn logical_pixel_ascent(&self, text: &Text, face: FaceIndex) -> Option<i64> {
        let FontHeight::Em(em) = text.height else {
            return None;
        };
        let pels = u16::try_from(text.logical_height).ok()?;
        let (ascent, _) = self.shaper.whole_pixel_heights(face, pels)?;
        Some(f_office_units::div_round(
            ascent * em,
            i64::from(pels.max(1)),
        ))
    }

    /// The family that draws a line of metafile text: the font's own face when the target has
    /// it, else the face that the target's font mapper gives the font's character set and
    /// pitch and family, when the target's font environment knows it, else the font's own
    /// name, for the faces that a run's text would take. The characters that the face lacks
    /// draw as its missing glyph.
    fn metafile_family(&self, text: &Text, bold: bool) -> String {
        let fonts = self.shaper.fonts();
        let own = FamilyName::new(text.face.as_str());
        if fonts.face(&own, bold, text.italic).is_some() {
            return text.face.clone();
        }
        fonts
            .metafile_face(&own, text.charset, text.pitch_and_family)
            .map_or_else(|| text.face.clone(), |mapped| mapped.as_str().to_owned())
    }
}

/// A filled axis-aligned or turned box in `color` with level corners `(left, top)` and
/// `(right, bottom)` rotated about `origin` by `turn`.
fn turned_box(
    turn: Option<Turn>,
    origin: (i64, i64),
    (left, top): (i64, i64),
    (right, bottom): (i64, i64),
    color: Rgb,
) -> Item {
    let pt = |x: i64, y: i64| {
        let (tx, ty) = turned(turn, origin, (x, y));
        Point {
            x: Length::from_units(tx),
            y: Length::from_units(ty),
        }
    };
    Item::Path(PathItem {
        commands: vec![
            PathCommand::MoveTo(pt(left, top)),
            PathCommand::LineTo(pt(right, top)),
            PathCommand::LineTo(pt(right, bottom)),
            PathCommand::LineTo(pt(left, bottom)),
            PathCommand::Close,
        ],
        color,
        fill_rule: FillRule::NonZero,
    })
}

/// The point `(x, y)` of a level line, turned by `turn` about the line's reference point
/// `origin`.
fn turned(turn: Option<Turn>, origin: (i64, i64), (x, y): (i64, i64)) -> (i64, i64) {
    let Some(turn) = turn else {
        return (x, y);
    };
    let (along, down) = (x - origin.0, y - origin.1);
    let step = |across: i32, downward: i32| {
        f_office_units::div_round(
            along * i64::from(across) + down * i64::from(downward),
            i64::from(Turn::SCALE),
        )
    };
    (
        origin.0 + step(turn.xx, turn.xy),
        origin.1 + step(turn.yx, turn.yy),
    )
}

#[cfg(test)]
mod tests;

/// Whether `picture` covers its whole upright-or-quarter-turned box: its file is a JPEG file or
/// a PNG file that cannot make a pixel clear, it keeps the file's alpha, its crop adds no space
/// around the file, and its turn is at most whole quarter turns.
fn opaque_picture(picture: &Picture) -> bool {
    let Some(image) = picture.image.as_ref() else {
        return false;
    };
    let crop = picture.crop;
    opaque_image_file(image)
        && picture.opacity == Opacity::FULL
        && [crop.left, crop.top, crop.right, crop.bottom]
            .iter()
            .all(|share| *share >= 0)
        && picture.turn.is_none_or(|turn| turn.xx == 0 || turn.xy == 0)
}

/// Whether `image` is a raster file that cannot contain any transparent pixel.
fn opaque_image_file(image: &f_office_paint::Image) -> bool {
    match image.format {
        ImageFormat::Jpeg => true,
        ImageFormat::Png => {
            if let Some(prefix) = image.load_prefix(crate::params::IMAGE_HEADER_PREFIX_BYTES)
                && (f_office_paint::image_header::png_header_complete(&prefix)
                    || prefix.len() < crate::params::IMAGE_HEADER_PREFIX_BYTES)
                && let Some(clear) = f_office_paint::image_header::png_can_be_clear(&prefix)
            {
                return !clear;
            }
            image.load_bytes().is_some_and(|bytes| {
                f_office_paint::image_header::png_can_be_clear(&bytes) == Some(false)
            })
        }
        _ => false,
    }
}

/// Maps a raster [`ImageFormat`] to its [`MaskFormat`], or `None` for metafiles and other formats.
fn mask_format(format: ImageFormat) -> Option<MaskFormat> {
    match format {
        ImageFormat::Png => Some(MaskFormat::Png),
        ImageFormat::Jpeg => Some(MaskFormat::Jpeg),
        ImageFormat::Gif => Some(MaskFormat::Gif),
        ImageFormat::Bmp => Some(MaskFormat::Bmp),
        ImageFormat::Tiff => Some(MaskFormat::Tiff),
        ImageFormat::Emf | ImageFormat::Wmf | ImageFormat::EffectPicture | ImageFormat::Unknown => {
            None
        }
    }
}

/// The shadow mask source of a raster `picture`, or `None` for a metafile or unsupported format.
fn picture_mask_source(picture: &Picture) -> Option<MaskSource> {
    let image = picture.image.as_ref()?;
    if opaque_image_file(image) {
        return Some(MaskSource::Opaque);
    }
    let format = mask_format(image.format)?;
    let bytes = image.load_bytes()?;
    Some(MaskSource::Image {
        format,
        data: bytes.to_vec(),
    })
}

/// What an inline picture shows nothing outside of.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PictureCut {
    /// The box of the picture's line, from the top of its space before to the bottom of its
    /// space after, as a top and a bottom down the page; it leaves the picture whole across.
    Line(Length, Length),
    /// The text area of the text box or the frame that holds the picture's line, on all four
    /// sides.
    Box(Edges<Length>),
}

impl PictureCut {
    /// The top and the bottom of the cut down the page.
    const fn down(self) -> (Length, Length) {
        match self {
            Self::Line(top, bottom) => (top, bottom),
            Self::Box(edges) => (edges.top, edges.bottom),
        }
    }

    /// The part of the edges `from` and `to` across that the cut leaves: all of them for a
    /// line's box.
    fn across(self, from: Length, to: Length) -> (Length, Length) {
        match self {
            Self::Line(..) => (from, to),
            Self::Box(edges) => (from.max(edges.left), to.min(edges.right)),
        }
    }

    /// The cut for a picture whose top moves by `top` and whose bottom moves by `bottom` onto
    /// the device's dots: a line's box moves with the picture, so that it cuts the picture on
    /// the dots where it cuts it at its exact place; a box stays where it is.
    pub(super) fn moved(self, (top, bottom): (Length, Length)) -> Self {
        match self {
            Self::Line(above, below) => Self::Line(above + top, below + bottom),
            Self::Box(_) => self,
        }
    }
}

/// The items `items` of a picture whose drawing covers `bounds`, cut to `cut` where the drawing
/// reaches past it. An upright image item goes into a group of the page's items under a clip of
/// what the cut leaves of the bounds, which the writer writes as the page's: the whole image with
/// its own clip, as Word writes a cut picture's file whole under a clip path of that part. A
/// turned image item, which the writer always writes whole, takes the cut as its own clip, or the
/// part of its own clip inside the cut. A metafile's group goes into a group of its own under the
/// cut. A band down the page keeps the bounds, or the image's own clip, across. Items of a picture
/// inside the cut stay as they are.
fn clipped_to(items: Vec<Item>, bounds: Edges<Length>, cut: PictureCut) -> Vec<Item> {
    let (top, bottom) = cut.down();
    let (left, right) = cut.across(bounds.left, bounds.right);
    let inside = bounds.top >= top && bounds.bottom <= bottom;
    if inside && (left, right) == (bounds.left, bounds.right) {
        return items;
    }
    let rect = |left: Length, top: Length, right: Length, bottom: Length| {
        GroupClip::rect(
            left,
            top,
            (right - left).max(Length::ZERO),
            (bottom - top).max(Length::ZERO),
        )
    };
    items
        .into_iter()
        .map(|item| match item {
            Item::Image(image) if image.turn.is_none() => {
                let shown = rect(left, top.max(bounds.top), right, bottom.min(bounds.bottom));
                Item::Group(Group::of_page(vec![Item::Image(image)], shown))
            }
            Item::Image(mut image) => {
                let (clip_left, clip_right, clip_top, clip_bottom) = match image.clip {
                    Some(clip) => {
                        let (clip_left, clip_right) = cut.across(clip.x, clip.x + clip.width);
                        (
                            clip_left,
                            clip_right,
                            clip.y.max(top),
                            (clip.y + clip.height).min(bottom),
                        )
                    }
                    None => (left, right, top, bottom),
                };
                image.clip = Some(Clip {
                    x: clip_left,
                    y: clip_top,
                    width: (clip_right - clip_left).max(Length::ZERO),
                    height: (clip_bottom - clip_top).max(Length::ZERO),
                });
                Item::Image(image)
            }
            Item::Group(_) => Item::Group(Group {
                items: vec![item],
                clip: Some(rect(left, top, right, bottom)),
                places: GroupPlaces::Own,
            }),
            other => other,
        })
        .collect()
}

/// The opaque outline item(s) of a picture (its clip path or covered rectangle) plus its
/// optional border line, used to cast shadows and glows.
fn opaque_picture_frame(
    picture: &Picture,
    (x, top): (Length, Length),
    line: Option<&Item>,
) -> Option<Vec<Item>> {
    let frame = if let Some((commands, fill_rule)) = picture.clip_path(x, top) {
        Item::Path(PathItem {
            commands,
            fill_rule,
            color: Rgb::default(),
        })
    } else {
        let covered = picture.covered(x, top)?;
        Item::Rect(Rect {
            x: covered.left,
            y: covered.top,
            width: covered.width(),
            height: covered.height(),
            color: Rgb::default(),
        })
    };
    Some(std::iter::once(frame).chain(line.cloned()).collect())
}

/// The covered bounds and alpha mask placement of a raster picture for masked shadows and glows.
fn picture_mask_placement(
    picture: &Picture,
    (x, top): (Length, Length),
) -> Option<(Edges<Length>, super::shadow::MaskPlacement)> {
    let source = picture_mask_source(picture)?;
    let covered = picture.drawn_bounds(x, top)?;
    let corners = picture.turned_whole_corners(x, top)?;
    let placement = super::shadow::MaskPlacement {
        source,
        opacity: picture.opacity,
        corners,
        crop: picture.crop,
    };
    Some((covered, placement))
}