//! Floating drawings (`wp:anchor`) that hold a text box (`wps:txbx`), a picture, or a drawing
//! group (`wpg:wgp`) of them.
use f_office_units::{Edges, Length, lowest_terms};
use f_office_vml::shape_type::TextRect;
use f_office_warnings::Name;
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};
use crate::body::{Block, read_story};
use crate::ns::{self, A, C, CX, DGM, MC, PIC, W14, WP, WP14, WPC, WPG, WPS};
use crate::picture::{BLIP_IMAGE, Picture, embedded_image};
use crate::props::Align;
use crate::reader::PartReader;
use crate::warnings::{ChartReason, Drawing, GroupTransform, Reason};
use f_office_drawingml::Feature;
use f_office_drawingml::color::{DrawColor, percentage};
use f_office_drawingml::shape::{
GroupFill, ShapeLook, TextRect as PresetTextRect, picture_fill, quarter_turns, text_rect,
};
/// What a floating position is measured from (`relativeFrom`): an area of the page, as a
/// relative size is, or the anchor paragraph, the anchor's line or the text column, which only
/// a position can name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Relative {
/// An area of the page ([`PageArea`]).
Area(PageArea),
/// The anchor paragraph.
Paragraph,
/// The line that holds the anchor (`relativeFrom="line"` of `wp:positionV`, `ST_RelFromV`
/// of ECMA-376 Part 1). Across, and on a target that counts from the paragraph's top
/// (`FromLine::ParagraphTop`), it is the anchor paragraph.
Line,
/// The text column that holds the anchor: in a table cell, the cell's text column.
Column,
}
/// An area of the page that a floating position or a relative size counts from (`relativeFrom`
/// of `wp:positionH` and `wp:positionV`, and of `wp14:sizeRelH` and `wp14:sizeRelV`,
/// `ST_SizeRelFromH` and `ST_SizeRelFromV`). A position can also count from the anchor
/// paragraph or the text column ([`Relative`]); a size cannot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PageArea {
/// The page.
Page,
/// The space between the margins.
Margin,
/// The left or the top margin area.
StartMargin,
/// The right or the bottom margin area.
EndMargin,
}
/// The names of `relativeFrom` of a position (`wp:positionH` and `wp:positionV`, `ST_RelFromH`
/// and `ST_RelFromV` of ECMA-376 Part 1, 20.4.3.4 and 20.4.3.5), read on either axis: the page,
/// the margins, a margin area, where the left, top or inside margin starts the page on its axis
/// and the right, bottom or outside margin ends it, the anchor paragraph, its line and the text
/// column. A position relative to the character (`character`) counts from the margins.
const POSITION_FROM: &Values<Relative> = &Values::new(&[
own("page", Relative::Area(PageArea::Page)),
own("margin", Relative::Area(PageArea::Margin)),
own("leftMargin", Relative::Area(PageArea::StartMargin)),
own("topMargin", Relative::Area(PageArea::StartMargin)),
own("insideMargin", Relative::Area(PageArea::StartMargin)),
own("rightMargin", Relative::Area(PageArea::EndMargin)),
own("bottomMargin", Relative::Area(PageArea::EndMargin)),
own("outsideMargin", Relative::Area(PageArea::EndMargin)),
own("paragraph", Relative::Paragraph),
own("line", Relative::Line),
own("column", Relative::Column),
another("character", Relative::Area(PageArea::Margin)),
]);
/// The names of `relativeFrom` of a relative size (`wp14:sizeRelH` and `wp14:sizeRelV`,
/// `ST_SizeRelFromH` and `ST_SizeRelFromV`), read on either axis: the page, the margins and the
/// margin areas, as [`POSITION_FROM`] reads them.
const SIZE_FROM: &Values<PageArea> = &Values::new(&[
own("page", PageArea::Page),
own("margin", PageArea::Margin),
own("leftMargin", PageArea::StartMargin),
own("topMargin", PageArea::StartMargin),
own("insideMargin", PageArea::StartMargin),
own("rightMargin", PageArea::EndMargin),
own("bottomMargin", PageArea::EndMargin),
own("outsideMargin", PageArea::EndMargin),
]);
impl Default for Relative {
/// The space between the margins, which a position counts from when it names no area: a
/// drawing without the position element, a position without `relativeFrom`, or one whose
/// value is text outside the types of [`POSITION_FROM`].
fn default() -> Self {
Self::Area(PageArea::Margin)
}
}
impl Relative {
/// Whether a position counts from the anchor's text, its paragraph or its line, and so
/// moves with the text.
#[must_use]
pub const fn follows_text(self) -> bool {
matches!(self, Self::Paragraph | Self::Line)
}
}
/// One axis of a floating position.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Position {
/// What it is measured from.
pub from: Relative,
/// The offset from the start of that area.
pub offset: Length,
/// The alignment in that area, which wins over the offset.
pub align: Option<Align>,
/// The offset as a share of that area, in thousandths of a percent
/// (`wp14:pctPosHOffset` or `wp14:pctPosVOffset`), which wins over `offset`.
pub share: Option<i64>,
}
/// The sides of a drawing that the text of its wrap flows on (`wrapText`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WrapSides {
/// Both sides, where there is room (`bothSides`).
#[default]
Both,
/// Only the left side (`left`).
Left,
/// Only the right side (`right`).
Right,
/// Only the side with more room (`largest`).
Largest,
}
/// `ST_WrapText`, the sides of a DrawingML wrap (`wrapText`): each name is drawn, and a
/// missing name is both sides.
const WRAP_TEXT: &Values<WrapSides> = &Values::new(&[
own("bothSides", WrapSides::Both),
own("left", WrapSides::Left),
own("right", WrapSides::Right),
own("largest", WrapSides::Largest),
]);
/// How the text of a text box runs in its box: across it, or turned, down or up the box.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TextFlow {
/// Across the box.
Across,
/// Turned a quarter turn clockwise: the lines run down the box.
Down,
/// Turned a quarter turn counterclockwise: the lines run up the box.
Up,
/// Turned as `Down`, with the characters of the East Asian font side upright.
EastAsianDown,
/// Turned in another of the vertical forms, which F-Office lays out across the box.
Turned,
}
/// `ST_TextVerticalType` of a text box (`vert` of `wps:bodyPr`, ECMA-376 Part 1, 21.1.2.1.1):
/// `horz` runs across the box, `vert` down it and `vert270` up it, `eaVert` down it with its East
/// Asian characters upright; every other name turns the
/// text in a form that F-Office lays out across the box with the warning
/// `turned-text-box-not-supported`.
const TEXT_VERTICAL: &Values<TextFlow> = &Values::new(&[
own("horz", TextFlow::Across),
own("vert", TextFlow::Down),
own("vert270", TextFlow::Up),
own("wordArtVert", TextFlow::Turned),
own("eaVert", TextFlow::EastAsianDown),
own("mongolianVert", TextFlow::Turned),
own("wordArtVertRtl", TextFlow::Turned),
]);
/// How the text of a text box turns on the page.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextTurn {
/// Upright, across the box.
#[default]
Upright,
/// Turned by its body, a quarter turn clockwise: laid out in a frame as long as the box is
/// high, whose lines run down the page and stack from the box's right side.
Down,
/// Turned by its body, a quarter turn counterclockwise: the lines run up the page and stack
/// from the box's left side.
Up,
/// Turned by its body as `Down`, with each glyph of a character of the East Asian font side
/// upright on the page.
EastAsianDown,
/// Turned with its shape: laid out upright in the box before the shape's quarter turns, and
/// turned with the shape about the box's centre.
WithShape,
}
/// Where the lines of a text box's body end.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BodyWrap {
/// At the width of the text area, and at the body's own breaks.
Area,
/// Only at the body's own breaks.
Unbroken,
}
/// `ST_TextWrappingType` of a text box (`wrap` of `wps:bodyPr`, ECMA-376 Part 1, 21.1.2.1.1).
const TEXT_WRAPPING: &Values<BodyWrap> = &Values::new(&[
own("square", BodyWrap::Area),
own("none", BodyWrap::Unbroken),
]);
/// `ST_AlignH` of a floating drawing's alignment across (`wp:align` in `wp:positionH`):
/// `inside` is drawn at the left and `outside` at the right, on every page.
const ALIGN_H: &Values<Align> = &Values::new(&[
own("left", Align::Start),
own("center", Align::Center),
own("right", Align::End),
own("inside", Align::Inside),
own("outside", Align::Outside),
]);
/// `ST_AlignV` of a floating drawing's alignment down (`wp:align` in `wp:positionV`): `inside`
/// is drawn at the top and `outside` at the bottom, on every page.
const ALIGN_V: &Values<Align> = &Values::new(&[
own("top", Align::Start),
own("center", Align::Center),
own("bottom", Align::End),
another("inside", Align::Start),
another("outside", Align::End),
]);
/// A floating drawing with its place, and the text box or the picture that it shows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Floating {
/// The name of the package part that holds the drawing, which a warning of the layout
/// about the drawing names.
pub part: Name,
/// The horizontal position.
pub h: Position,
/// The vertical position.
pub v: Position,
/// The width of the drawing.
pub width: Length,
/// The height of the drawing.
pub height: Length,
/// The space between the box edges and its text.
pub insets: Edges<Length>,
/// Which edge of the outline the text keeps its insets from.
pub inset_edge: InsetEdge,
/// The text rectangle of a VML shape's type, which its text lies in inside the insets, or
/// `None` for the whole box.
pub text_rect: Option<TextRect>,
/// The text rectangle of a DrawingML shape's preset geometry, which its text lies in with
/// the insets inside it, or `None` for the whole box.
pub preset_rect: Option<PresetTextRect>,
/// Whether the shape is as tall as its text (`a:spAutoFit`), whatever height it gives.
pub fits_text: bool,
/// Whether the shape is as wide as its text's widest line, whatever width it gives: its
/// text body does not wrap (`wrap="none"`).
pub fits_width: bool,
/// How the text of its text box turns on the page.
pub text_turn: TextTurn,
/// The width as a share of an area of the page (`wp14:sizeRelH`), in thousandths of a
/// percent, which wins over `width`.
pub relative_width: Option<(PageArea, i64)>,
/// The height as a share of an area of the page (`wp14:sizeRelV`), unless the shape fits
/// its height to its text.
pub relative_height: Option<(PageArea, i64)>,
/// The content of a text box.
pub blocks: Vec<Block>,
/// The color of the text box's text whose own color is automatic or missing: the font
/// color of the shape's style (`a:fontRef`), `None` when it gives none.
pub text_color: Option<[u8; 3]>,
/// The picture, which fills the drawing.
pub picture: Option<Picture>,
/// How the text keeps out of the drawing, `None` when it does not: no wrap, `wp:wrapNone`,
/// a VML wrap without a type, or a shape without height.
pub wrap: Option<Wrap>,
/// The points of the polygon of a tight or through wrap that is not a rectangle along the
/// axes, in order, in 21,600ths of the drawing's width and height from its top left corner;
/// none for another wrap.
pub outline: Vec<(i64, i64)>,
/// How far effects such as a shadow reach out of the edges of the box (`wp:effectExtent`).
pub effect: Edges<Length>,
/// The text boxes and pictures of a drawing group, each with its offset from the group's
/// top left corner. Their own positions and wraps do not apply.
pub parts: Vec<(Length, Length, Floating)>,
/// The geometry, fill and line of a shape, with or without a text box.
pub look: Option<ShapeLook>,
/// Whether the drawing lies behind the text (`behindDoc`) instead of in front of it.
pub behind: bool,
/// Whether a drawing anchored in a table cell is laid out relative to the cell
/// (`layoutInCell`). Defaults to [`CellLayout::InCell`] when absent; honored in compatibility
/// modes before 15 and treated as always on from mode 15.
pub(crate) cell_layout: CellLayout,
/// The drawing's place among the drawings of its layer, behind or in front of the text: its
/// `relativeHeight`, or the size of a VML shape's `z-index`. A drawing with a higher one
/// lies above, and drawings of the same one lie in the order of their anchors.
pub stack: u64,
/// Where the text of a text box lies in its box, down the box.
pub anchor: TextAnchor,
/// How the text anchor counts the room below the text.
pub room: Room,
/// Which rules the lines of the box's text take.
pub box_text: BoxText,
/// The parts of a SmartArt graphic, whose saved drawing gives the drawing's parts.
pub diagram: Option<crate::smartart::Diagram>,
/// The chart that the drawing shows, which its chart part gives once the parts are read.
pub chart: Option<crate::chart::Chart>,
/// The line of text that fills the box, such as a watermark's, instead of a shape.
pub text_path: Option<TextPath>,
}
/// Whether a floating drawing anchored in a table cell is laid out inside the cell
/// (`layoutInCell`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum CellLayout {
/// Laid out relative to the cell (`layoutInCell="1"` or absent).
#[default]
InCell,
/// Laid out relative to the page/column outside the cell (`layoutInCell="0"`).
OutsideCell,
}
impl CellLayout {
pub(crate) const fn of(in_cell: bool) -> Self {
if in_cell {
Self::InCell
} else {
Self::OutsideCell
}
}
}
/// A line of text that a VML shape draws to fill its box (a `v:textpath` in a shape of the type
/// 136, plain text), as a watermark is drawn.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextPath {
/// The text.
pub string: String,
/// The family of the face.
pub face: f_office_fonts::FamilyName,
/// The fill of the letters, its color already mixed with white by its opacity.
pub color: f_office_paint::Rgb,
/// How far the line is turned clockwise about the center of the box, in DrawingML's unit,
/// 60,000ths of a degree.
pub rotation: i64,
}
impl Floating {
/// A drawing of the part `part` with the defaults of every other field: no size, no wrap,
/// no content and no look, which its reader then sets.
pub(crate) fn in_part(part: &str) -> Self {
Self {
part: Name::new(part),
h: Position::default(),
v: Position::default(),
width: Length::ZERO,
height: Length::ZERO,
insets: Edges::default(),
inset_edge: InsetEdge::default(),
text_rect: None,
preset_rect: None,
fits_text: false,
fits_width: false,
text_turn: TextTurn::Upright,
relative_width: None,
relative_height: None,
blocks: Vec::new(),
text_color: None,
picture: None,
wrap: None,
outline: Vec::new(),
effect: Edges::default(),
parts: Vec::new(),
look: None,
behind: false,
cell_layout: CellLayout::InCell,
stack: 0,
anchor: TextAnchor::default(),
room: Room::default(),
box_text: BoxText::default(),
diagram: None,
chart: None,
text_path: None,
}
}
}
/// A drawing of the main document part, for a test.
#[cfg(test)]
impl Default for Floating {
fn default() -> Self {
Self::in_part(crate::testing::DOCUMENT)
}
}
/// How the text keeps out of a floating drawing: the one wrap element of DrawingML
/// (`wp:wrapTopAndBottom`, `wp:wrapSquare`, `wp:wrapTight` or `wp:wrapThrough`) or the
/// `w10:wrap` of a VML shape.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Wrap {
/// The text keeps above and below the drawing (`wp:wrapTopAndBottom`).
TopAndBottom {
/// The space to keep above the drawing's box: `distT` and the effect extent above it.
above: Length,
/// The space to keep below the drawing's box: `distB` and the effect extent below it.
below: Length,
},
/// The text flows beside the drawing's box: a square wrap (`wp:wrapSquare`), and a tight
/// or through wrap (`wp:wrapTight`, `wp:wrapThrough`), which keeps the text out of the
/// bounds of its polygon.
Beside {
/// The space to keep at the box's edges (`distL`, `distT`, `distR`, `distB`), with the
/// effect extents for a square wrap.
distances: Edges<Length>,
/// The sides of the drawing that the text of a square wrap flows on (`wrapText`), and
/// of a tight or through wrap whose polygon is its bounds. `None` for another wrap,
/// beside which a line takes the widest free piece: Word follows the outline of such a
/// polygon on each line, where F-Office keeps the text out of the polygon's bounds.
sides: Option<WrapSides>,
/// How far the bounds of a tight or through wrap's polygon lie inside the edges of the
/// box, negative outside them, zero for a tight or through wrap without a polygon;
/// `None` for a square wrap. Beside a tight or through wrap, a line without room beside
/// the drawing goes where the quirk `BlockedLines` says.
polygon: Option<Edges<Length>>,
},
}
/// Which edge of a box's outline its text keeps its insets from.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InsetEdge {
/// The outline's middle, as in a SmartArt box.
#[default]
Middle,
/// The outline's inner edge, as in a DrawingML text box (`wps:txbx`).
Inside,
/// The edge that the target chooses for a VML text box (`v:textbox`).
Vml,
}
/// Which rules the lines of a box's text take.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BoxText {
/// The rules of the document's own paragraphs: the text of a text box or of another shape.
#[default]
Paragraphs,
/// The rules of SmartArt text, the text of a shape of a SmartArt graphic's saved drawing
/// (`dsp:sp`), whose lines below single spacing take the target's SmartArt rule
/// ([`crate::quirks::SmartArtLowSpacing`]).
SmartArt,
}
/// How the text anchor of a box counts the room below its text.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Room {
/// As in a SmartArt box: the text ends at its last line, and text taller than its box
/// moves up.
#[default]
Shape,
/// As in a DrawingML text box (`wps:txbx`): the text ends below the space after its last
/// paragraph, and text taller than the box stays at the top.
TextBox,
}
/// Where the text of a text box lies in its box, down the box (`anchor` of `a:bodyPr`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextAnchor {
/// At the top.
#[default]
Top,
/// In the middle.
Center,
/// At the bottom.
Bottom,
}
impl TextAnchor {
/// The anchor that the value of `anchor` names: `ctr` the middle, `b` the bottom, and any
/// other value, or none, the top (ECMA-376 Part 1, 21.1.2.1.1).
#[must_use]
pub fn of(value: Option<&str>) -> Self {
match value {
Some("ctr") => Self::Center,
Some("b") => Self::Bottom,
_ => Self::Top,
}
}
}
/// The size of an inline or floating drawing (`wp:inline` or `wp:anchor`), from its
/// `wp:extent` in EMU, and its effect extent (`wp:effectExtent`) at each edge. A length that is
/// missing or does not read is 0. Each length is read once, so that a value that does not read
/// gives one warning.
pub(crate) fn extents(reader: &mut PartReader, drawing: NodeId) -> ([Length; 2], Edges<Length>) {
let doc = reader.doc;
let extent = doc.child(drawing, WP, "extent");
let effect = doc.child(drawing, WP, "effectExtent");
let mut length = |node: Option<NodeId>, name: &str| {
node.and_then(|n| reader.emu_length(n, name))
.unwrap_or(Length::ZERO)
};
(
["cx", "cy"].map(|name| length(extent, name)),
Edges::from(["l", "t", "r", "b"].map(|name| length(effect, name))),
)
}
/// Reads a floating drawing that holds a text box, a picture, a group, a SmartArt graphic or a
/// chart.
pub(crate) fn read_anchor(reader: &mut PartReader, drawing: NodeId) -> Option<Floating> {
let doc = reader.doc;
let anchor = doc.child(drawing, WP, "anchor")?;
let ([width, height], effects) = extents(reader, anchor);
let (wrap, outline) = read_wrap(reader, anchor, (width, height), effects);
// The shown branches of the anchor's alternate content, taken once for both axes, so that
// each choice that F-Office passes over warns once.
let shown: Vec<NodeId> = doc
.child_elements(anchor)
.filter(|node| doc.is(*node, MC, "AlternateContent"))
.filter_map(|node| crate::body::shown_branch(reader, node))
.collect();
let mut floating = Floating {
h: position(reader, (anchor, &shown), ("positionH", ALIGN_H)),
v: position(reader, (anchor, &shown), ("positionV", ALIGN_V)),
width,
height,
wrap,
outline,
effect: effects,
relative_width: relative_size(reader, anchor, "sizeRelH", "pctWidth"),
relative_height: relative_size(reader, anchor, "sizeRelV", "pctHeight"),
behind: doc
.attribute(anchor, None, "behindDoc")
.is_some_and(f_office_drawingml::boolean),
cell_layout: CellLayout::of(
doc.attribute(anchor, None, "layoutInCell")
.is_none_or(f_office_drawingml::boolean),
),
stack: doc
.attribute(anchor, None, "relativeHeight")
.and_then(|value| value.parse().ok())
.unwrap_or(0),
..Floating::in_part(reader.part())
};
if let Some(picture) = Picture::read(reader, anchor, Edges::sized(width, height)) {
let rotation = crate::picture::rotation(doc, anchor);
let turned = reader
.turned_pictures()
.turned_box((width, height), rotation);
if turned != (width, height) {
floating.wrap = floating
.wrap
.map(|wrap| swapped_wrap(wrap, (width, height)));
}
floating.picture = Some(picture);
return Some(floating);
}
let data = doc
.child(anchor, A, "graphic")
.and_then(|g| doc.child(g, A, "graphicData"))?;
// A SmartArt graphic gets its parts from its saved drawing once the parts are read.
if let Some(diagram) = crate::smartart::diagram(doc, data) {
floating.diagram = Some(diagram);
return Some(floating);
}
if let Some(group) = shape_child(doc, data, "wgp") {
read_group(reader, group, &mut floating);
keep_text_flow_of_shapes(&mut floating);
return (!floating.parts.is_empty()).then_some(floating);
}
if let Some(canvas) = doc.child(data, WPC, "wpc") {
read_canvas(reader, canvas, &mut floating);
keep_text_flow_of_shapes(&mut floating);
return (!floating.parts.is_empty()).then_some(floating);
}
// A floating chart takes its place and keeps the text out by its wrap, as any floating
// drawing does, and shows the chart in its frame as an inline chart does.
if let Some(chart) = crate::chart::reference(doc, data) {
floating.chart = Some(chart);
return Some(floating);
}
// A graphic that F-Office draws in no place is left out with a warning.
let Some(shape) = shape_child(doc, data, "wsp") else {
skip_graphic(reader, data);
return None;
};
read_shape(reader, shape, &mut floating);
keep_text_flow_of_shapes(&mut floating);
Some(floating)
}
/// The wrap `wrap` of a floating picture of `width` by `height` whose box is its frame with
/// its width and height swapped about its centre (`TurnedPictures::turned_box`): square
/// wrapping and top and bottom wrapping keep the text out of that box, half the difference
/// narrower across and taller down, with the effect extent and the wrap distances around it.
/// A tight or through wrap keeps its polygon.
fn swapped_wrap(wrap: Wrap, (width, height): (Length, Length)) -> Wrap {
let half = (width - height).div_round(2);
match wrap {
Wrap::Beside {
distances,
sides,
polygon: None,
} => Wrap::Beside {
distances: Edges {
left: distances.left - half,
top: distances.top + half,
right: distances.right - half,
bottom: distances.bottom + half,
},
sides,
polygon: None,
},
Wrap::TopAndBottom { above, below } => Wrap::TopAndBottom {
above: above + half,
below: below + half,
},
tight @ Wrap::Beside { .. } => tight,
}
}
/// The graphics of a drawing's graphic data (`a:graphicData`) that F-Office draws in some
/// places and not in others, or in no place, each by its element, with the kind of drawing
/// and the reason that the warning of its skip names: a chart (`c:chart`), which comes here
/// only without a part; a chart of Office 2016 and later (`cx:chart`), such as a
/// waterfall chart; a SmartArt graphic (`dgm:relIds`), which F-Office does not draw in a group;
/// and ink (`w14:contentPart`).
const GRAPHICS: [(&str, &str, Drawing, Reason); 4] = [
(C, "chart", Drawing::Chart, Reason::Unsupported),
(
CX,
"chart",
Drawing::Chart,
Reason::Chart(ChartReason::ChartEx),
),
(DGM, "relIds", Drawing::SmartArt, Reason::Unsupported),
(W14, "contentPart", Drawing::Shape, Reason::Unsupported),
];
/// The kind of drawing that the graphic data `data` holds, for the warning that it is left
/// out: the kind of its graphic of [`GRAPHICS`], a picture for `pic:pic`, or else a shape.
pub(crate) fn graphic_data_drawing(doc: &Document, data: NodeId) -> Drawing {
graphic_kind(doc, data).unwrap_or_else(|| {
if doc.child(data, PIC, "pic").is_some() {
Drawing::Picture
} else {
Drawing::Shape
}
})
}
/// The kind of drawing of the graphic of [`GRAPHICS`] that the graphic data `data` holds, or
/// `None` when it holds none of them.
fn graphic_kind(doc: &Document, data: NodeId) -> Option<Drawing> {
graphic_skip(doc, data).map(|(kind, _)| kind)
}
/// The kind of drawing and the reason of the skip of the graphic of [`GRAPHICS`] that the
/// graphic data `data` holds, or `None` when it holds none of them.
fn graphic_skip(doc: &Document, data: NodeId) -> Option<(Drawing, Reason)> {
GRAPHICS
.iter()
.find(|(namespace, name, _, _)| doc.child(data, namespace, name).is_some())
.map(|&(_, _, kind, reason)| (kind, reason))
}
/// Keeps the warning that the graphic that the graphic data `data` holds is left out, for a
/// reader that has not drawn it: with its kind and its reason when it is one of [`GRAPHICS`],
/// and as a shape that F-Office does not draw when it is an element of another kind, such as a
/// locked canvas (`lc:lockedCanvas`). A picture (`pic:pic`) gives no warning here, as the
/// picture reader has read it and warns of what it leaves out, such as a missing image part,
/// and graphic data without an element gives none.
fn skip_graphic(reader: &mut PartReader, data: NodeId) {
let doc = reader.doc;
if let Some((kind, reason)) = graphic_skip(doc, data) {
reader.drawing_skipped(kind, reason);
} else if doc.child(data, PIC, "pic").is_none() && doc.child_elements(data).next().is_some() {
reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
}
}
/// Reads the wrap of an anchored drawing of `size` whose effects reach `effects` out of its
/// edges, with the points of a tight or through wrap's polygon that is not a rectangle along
/// the axes. The schema allows one wrap element; of a file with more, a square wrap wins,
/// then a tight or through wrap, then a top and bottom wrap.
fn read_wrap(
reader: &mut PartReader,
anchor: NodeId,
size: (Length, Length),
effects: Edges<Length>,
) -> (Option<Wrap>, Vec<(i64, i64)>) {
let doc = reader.doc;
// Top and bottom wrap and square wrap keep the text away from the box of the drawing with
// its effect extent, such as a shadow, and the wrap distances around that.
let distances = Edges::from(
["distL", "distT", "distR", "distB"]
.map(|name| reader.emu_length(anchor, name).unwrap_or(Length::ZERO)),
);
let boxed = distances.with(effects, |distance, effect| distance + effect);
// Tight and through wraps keep the text out of the bounds of their wrap polygon, with the
// wrap distances around them.
let tight = ["wrapTight", "wrapThrough"]
.iter()
.find_map(|name| doc.child(anchor, WP, name));
let outline = tight.map_or_else(Vec::new, |wrap| polygon_points(reader, wrap));
// A polygon whose bounds lie out of range reads as no polygon, with a warning.
let insets = polygon_insets(&outline, size);
if insets.is_none() {
reader.polygon_skipped(Reason::OutOfRange);
}
let polygon = insets.unwrap_or_default();
// The text flows on the sides that a square wrap names, and so does the text of a tight
// or through wrap whose polygon is its bounds. Beside another polygon, whose outline Word
// follows on each line where F-Office keeps the text out of its bounds, a line takes the
// widest free piece.
if let Some(square) = doc.child(anchor, WP, "wrapSquare") {
let wrap = Wrap::Beside {
distances: boxed,
sides: Some(wrap_sides(reader, square)),
polygon: None,
};
return (Some(wrap), Vec::new());
}
if let Some(tight) = tight {
let bounds = fills_its_bounds(&outline);
let wrap = Wrap::Beside {
distances,
sides: bounds.then(|| wrap_sides(reader, tight)),
polygon: Some(polygon),
};
// The outline of a polygon that is not its bounds, and none of one that reads as no
// polygon.
let outline = if bounds || insets.is_none() {
Vec::new()
} else {
outline
};
return (Some(wrap), outline);
}
let wrap = doc
.child(anchor, WP, "wrapTopAndBottom")
.map(|_| Wrap::TopAndBottom {
above: boxed.top,
below: boxed.bottom,
});
(wrap, Vec::new())
}
/// The sides that the text of a DrawingML wrap flows on (`wrapText`), both when it names none.
fn wrap_sides(reader: &mut PartReader, wrap: NodeId) -> WrapSides {
reader
.enumeration_in(wrap, (None, "wrapText"), WRAP_TEXT)
.unwrap_or_default()
}
/// A size relative to an area of the page (`wp14:sizeRelH` with `wp14:pctWidth`, or
/// `wp14:sizeRelV` with `wp14:pctHeight`), as the area and thousandths of a percent of it.
fn relative_size(
reader: &mut PartReader,
anchor: NodeId,
name: &str,
share: &str,
) -> Option<(PageArea, i64)> {
let doc = reader.doc;
let node = doc.child(anchor, WP14, name)?;
let from = reader.enumeration_in(node, (None, "relativeFrom"), SIZE_FROM)?;
let value = doc.text_content(doc.child(node, WP14, share)?);
// A Strict file writes the share with a percent sign.
let thousandths = percentage(&value).filter(|v| *v > 0)?;
Some((from, thousandths))
}
/// How far the bounds of a wrap polygon (`wp:wrapPolygon`) lie inside the left, top, right
/// and bottom edges of a drawing of `size`, negative outside them. The polygon's coordinates
/// run from 0 to 21,600 across the drawing. A wrap without a polygon lies on the edges. The
/// product of a coordinate and a side is taken in `i128`, and a distance beyond
/// [`Length::FILE_LIMIT`] gives `None`.
fn polygon_insets(points: &[(i64, i64)], size: (Length, Length)) -> Option<Edges<Length>> {
const FULL: i64 = crate::params::WRAP_POLYGON_WHOLE;
let ((left, right), (top, bottom)) = (bounds(points, |p| p.0), bounds(points, |p| p.1));
let scale = |value: i64, length: Length| {
let share = i128::from(value) * i128::from(length.units()) / i128::from(FULL);
i64::try_from(share)
.ok()
.filter(|share| (-Length::FILE_LIMIT..=Length::FILE_LIMIT).contains(share))
.map(Length::from_units)
};
Some(Edges {
left: scale(left, size.0)?,
top: scale(top, size.1)?,
right: scale(FULL - right, size.0)?,
bottom: scale(FULL - bottom, size.1)?,
})
}
/// The points of a wrap's polygon (`wp:wrapPolygon`), none when it has none. A point whose
/// coordinate is missing or does not read is left out.
fn polygon_points(reader: &mut PartReader, wrap: NodeId) -> Vec<(i64, i64)> {
let doc = reader.doc;
doc.child(wrap, WP, "wrapPolygon")
.map_or_default(|polygon| {
doc.child_elements(polygon)
.filter_map(|point| {
let [x, y] = ["x", "y"].map(|name| reader.emus(point, name));
x.zip(y)
})
.collect()
})
}
/// The lowest and the highest value of the points along an axis, the whole drawing without
/// points.
fn bounds(points: &[(i64, i64)], axis: fn(&(i64, i64)) -> i64) -> (i64, i64) {
let low = points.iter().map(axis).min().unwrap_or(0);
let high = points
.iter()
.map(axis)
.max()
.unwrap_or(crate::params::WRAP_POLYGON_WHOLE);
(low, high)
}
/// Whether a wrap's polygon is its own bounds, a rectangle along the axes, as is a wrap without
/// a polygon: every point lies on a corner of the bounds.
fn fills_its_bounds(points: &[(i64, i64)]) -> bool {
let ((left, right), (top, bottom)) = (bounds(points, |p| p.0), bounds(points, |p| p.1));
points
.iter()
.all(|&(x, y)| (x == left || x == right) && (y == top || y == bottom))
}
/// Takes the wrap away from a shape without height, such as a horizontal line, which keeps no
/// text out.
fn keep_text_flow_of_shapes(floating: &mut Floating) {
if floating.height == Length::ZERO {
floating.wrap = None;
}
}
/// Reads the shape (`wps:wsp`) of an inline drawing (`wp:inline`) as a drawing of `width` by
/// `height` without a place of its own, or gives `None` when the drawing holds no shape.
pub(crate) fn read_inline_shape(
reader: &mut PartReader,
inline: NodeId,
width: Length,
height: Length,
) -> Option<Floating> {
let doc = reader.doc;
let data = doc
.child(inline, A, "graphic")
.and_then(|g| doc.child(g, A, "graphicData"))?;
let mut floating = Floating {
width,
height,
..Floating::in_part(reader.part())
};
if let Some(diagram) = crate::smartart::diagram(doc, data) {
floating.diagram = Some(diagram);
return Some(floating);
}
// An inline chart takes the room of its frame, and shows the chart in it.
if let Some(chart) = crate::chart::reference(doc, data) {
floating.chart = Some(chart);
return Some(floating);
}
// An inline group shows its shapes, text boxes and pictures as a floating group does.
if let Some(group) = shape_child(doc, data, "wgp") {
read_group(reader, group, &mut floating);
return (!floating.parts.is_empty()).then_some(floating);
}
// An inline drawing canvas shows its backdrop and children at their offsets from its corner.
if let Some(canvas) = doc.child(data, WPC, "wpc") {
read_canvas(reader, canvas, &mut floating);
return (!floating.parts.is_empty()).then_some(floating);
}
// A graphic that F-Office draws in no place keeps its room and is left out with a warning.
let Some(shape) = shape_child(doc, data, "wsp") else {
skip_graphic(reader, data);
return None;
};
read_shape(reader, shape, &mut floating);
Some(floating)
}
/// The namespaces of the elements of shapes and groups. Word writes them in its own two
/// namespaces in a Transitional document and in the namespace of `wp:anchor` in a Strict one,
/// whose schema defines `wsp`, `wgp`, `grpSp`, `txbx` and the others (ECMA-376 Part 1, 20.4.2).
const SHAPE_NAMESPACES: [&str; 3] = [WPS, WPG, WP];
/// The child `name` of `node` among the elements of shapes and groups.
fn shape_child(doc: &Document, node: NodeId, name: &str) -> Option<NodeId> {
SHAPE_NAMESPACES
.iter()
.find_map(|namespace| doc.child(node, namespace, name))
}
/// Whether `node` is the element `name` of shapes and groups.
fn is_shape_element(doc: &Document, node: NodeId, name: &str) -> bool {
SHAPE_NAMESPACES
.iter()
.any(|namespace| doc.is(node, namespace, name))
}
/// Resolves the inherited [`GroupFill`] of `group` (`wpg:wgp` or `wpg:grpSp`) whose box in
/// outermost-group coordinates is `group_box`: takes `group`'s own `wpg:grpSpPr` when it carries
/// an explicit fill (`noFill`, `solidFill`, `gradFill`, `blipFill`, `pattFill`), otherwise
/// inherits from `parent`.
fn resolve_group_fill(
doc: &Document,
group: NodeId,
group_box: Edges<Length>,
parent: Option<GroupFill>,
) -> GroupFill {
const EXPLICIT_FILLS: [&str; 5] = ["noFill", "solidFill", "gradFill", "blipFill", "pattFill"];
if let Some(props) = shape_child(doc, group, "grpSpPr")
&& EXPLICIT_FILLS
.iter()
.any(|name| doc.child(props, A, name).is_some())
{
return GroupFill {
props: Some(props),
frame: group_box,
};
}
parent.unwrap_or(GroupFill {
props: None,
frame: group_box,
})
}
/// Reads the parts of a drawing group (`wpg:wgp`) into `floating`, at their offsets from the
/// group's top left corner.
fn read_group(reader: &mut PartReader, group: NodeId, floating: &mut Floating) {
let t = xfrm(reader, group);
let ortho = read_group_ortho(reader, group);
let Some(map) = Map::root(&t, ortho) else {
reader.drawing_skipped(Drawing::Shape, Reason::OutOfRange);
return;
};
let group_box = Edges::sized(floating.width, floating.height);
let group_fill = resolve_group_fill(reader.doc, group, group_box, None);
group_parts(reader, group, map, Some(group_fill), &mut floating.parts);
}
/// Reads a drawing canvas (`wpc:wpc`) into `floating`: its optional background fill (`wpc:bg`)
/// and whole-canvas outline/effect (`wpc:whole`) painted first as a rectangle filling the canvas,
/// followed by its child shapes, pictures and nested groups at their EMU offsets from the
/// canvas's top left corner without clipping.
fn read_canvas(reader: &mut PartReader, canvas: NodeId, floating: &mut Floating) {
let doc = reader.doc;
let bg = doc.child(canvas, WPC, "bg");
let whole = doc.child(canvas, WPC, "whole");
let has_backdrop = bg.is_some_and(|n| doc.child_elements(n).next().is_some())
|| whole.is_some_and(|n| doc.child_elements(n).next().is_some());
if has_backdrop {
let mut backdrop = Floating {
width: floating.width,
height: floating.height,
look: Some(ShapeLook::read_canvas(
doc,
(bg, whole),
reader.drawing_warnings(),
)),
..Floating::in_part(reader.part())
};
if let Some(bg) = bg {
read_picture_fill(reader, bg, &mut backdrop);
}
floating.parts.push((Length::ZERO, Length::ZERO, backdrop));
}
group_parts(reader, canvas, Map::IDENTITY, None, &mut floating.parts);
}
/// Reads the picture fill of a shape whose properties are `props` into `floating`, which holds
/// the shape's look and size. The picture is drawn over the shape's whole box, in its own
/// colors: a shape whose outline is not a rectangle, and a color effect of the picture, each
/// warn. A linked image is left out with a warning.
fn read_picture_fill(reader: &mut PartReader, props: NodeId, floating: &mut Floating) {
let doc = reader.doc;
let Some(fill) = picture_fill(doc, props) else {
return;
};
let Some(blip) = doc.child(fill, A, "blip") else {
return;
};
if embedded_image(reader, blip, BLIP_IMAGE).is_none() {
return;
}
floating.picture = Picture::from_fill(reader, fill, (floating.width, floating.height));
let Some(picture) = floating.picture.as_mut() else {
return;
};
let Some(look) = floating.look.as_ref() else {
return;
};
if !look.geometry.is_shaped() {
return;
}
let full_box = picture.left == Length::ZERO
&& picture.top == Length::ZERO
&& picture.width == floating.width
&& picture.height == floating.height;
let upright = look.is_upright();
if look.geometry.is_closed_shape() && full_box && upright {
picture.geometry = look.geometry.clone();
} else {
reader.drawingml_feature_not_supported(Feature::ShapedPicture);
}
}
/// Reads the look of a shape (`wps:wsp`) and its text box, if it has one, into `floating`.
fn read_shape(reader: &mut PartReader, shape: NodeId, floating: &mut Floating) {
read_shape_with_ortho(reader, shape, Ortho::IDENTITY, None, floating);
}
/// Reads a shape (`wps:wsp`), composing an outer group transform `ortho` onto its look and
/// picture fill before computing its text box turn.
fn read_shape_with_ortho(
reader: &mut PartReader,
shape: NodeId,
ortho: Ortho,
group_fill: Option<GroupFill>,
floating: &mut Floating,
) {
let doc = reader.doc;
let props = shape_child(doc, shape, "spPr");
let style = shape_child(doc, shape, "style");
let look = match group_fill {
Some(gf) => ShapeLook::read_in_group(doc, (props, style), gf, reader.drawing_warnings()),
None => ShapeLook::read(doc, (props, style), reader.drawing_warnings()),
};
floating.look = Some(look.compose_outer(ortho.0));
floating.text_color = style
.and_then(|s| doc.child(s, A, "fontRef"))
.and_then(|f| DrawColor::read(doc, f, reader.drawing_warnings()))
.and_then(|color| color.resolve(reader.scheme()))
.map(|(rgb, _)| [rgb.r, rgb.g, rgb.b]);
if let Some(props) = props {
read_picture_fill(reader, props, floating);
if let Some(picture) = floating.picture.as_mut() {
picture.compose_outer_turn(ortho.0);
}
}
let Some(content) = shape_child(doc, shape, "txbx").and_then(|t| ns::text_box_content(doc, t))
else {
return;
};
// Page numbers in a text box count like those around it.
floating.blocks = read_story(reader, content);
let body = shape_child(doc, shape, "bodyPr");
floating.text_turn = text_turn(reader, body, floating.look.as_ref());
floating.insets = body_insets(reader, body, crate::params::TEXT_BOX_INSETS);
floating.inset_edge = InsetEdge::Inside;
floating.preset_rect = props.and_then(|props| text_rect(doc, props));
floating.fits_width = body
.and_then(|body| reader.enumeration_in(body, (None, "wrap"), TEXT_WRAPPING))
== Some(BodyWrap::Unbroken);
// The text lies at the top, in the middle or at the bottom of the box.
floating.anchor = TextAnchor::of(body.and_then(|n| doc.attribute(n, None, "anchor")));
floating.room = Room::TextBox;
// A shape that fits its height to its text does not take a relative height.
if body.and_then(|b| doc.child(b, A, "spAutoFit")).is_some() {
floating.relative_height = None;
floating.fits_text = true;
}
}
/// How Word turns the text of a shape's text box, whose body is `body` and whose look is
/// `look`: in a shape that is not turned, the body's `vert` turns it down or up the box, with the
/// East Asian characters of `eaVert` upright; a shape
/// turned by whole quarter turns other than none (ECMA-376 Part 1, 20.1.7.6) turns its text with
/// it, unless the body keeps the text upright (`upright`, Part 1, 21.1.2.1.1), and a shape
/// mirrored down turns it by a half turn more ([`ShapeLook::text_quarter_turns`]). A body that turns
/// its text in another form, or in a turned shape, is laid out upright with the warning of a
/// turned text box. The text of a shape
/// turned by another angle is warned of with the shape's turn.
fn text_turn(reader: &mut PartReader, body: Option<NodeId>, look: Option<&ShapeLook>) -> TextTurn {
let doc = reader.doc;
let flow = body.and_then(|body| reader.enumeration_in(body, (None, "vert"), TEXT_VERTICAL));
let upright = body
.and_then(|body| doc.attribute(body, None, "upright"))
.is_some_and(f_office_drawingml::boolean);
if look.is_some_and(|look| look.quarter_turns().is_none()) && !upright {
reader.feature_not_supported(crate::Feature::TurnedTextBox);
return TextTurn::Upright;
}
let quarters = look.and_then(ShapeLook::text_quarter_turns).unwrap_or(0);
match (flow.unwrap_or(TextFlow::Across), quarters) {
(TextFlow::Across, 0) => TextTurn::Upright,
(TextFlow::Across, _) if upright => TextTurn::Upright,
(TextFlow::Across, _) => TextTurn::WithShape,
(TextFlow::Down, 0) => TextTurn::Down,
(TextFlow::Up, 0) => TextTurn::Up,
(TextFlow::EastAsianDown, 0) => TextTurn::EastAsianDown,
(TextFlow::Down | TextFlow::Up | TextFlow::EastAsianDown | TextFlow::Turned, _) => {
reader.feature_not_supported(crate::Feature::TurnedTextBox);
TextTurn::Upright
}
}
}
/// The insets of a text body (`a:bodyPr` or `wps:bodyPr`): `lIns`, `tIns`, `rIns` and `bIns`
/// in EMUs, each `defaults` (at the sides, and above and below) when it is missing or does not
/// read: 0.1 inch and 0.05 inch for a text box (ECMA-376 Part 1, 21.1.2.1.1,
/// `params::TEXT_BOX_INSETS`).
pub(crate) fn body_insets(
reader: &mut PartReader,
body: Option<NodeId>,
(side, top): (Length, Length),
) -> Edges<Length> {
let mut inset = |name: &str, default: Length| {
body.and_then(|n| reader.emu_length(n, name))
.unwrap_or(default)
};
Edges {
left: inset("lIns", side),
top: inset("tIns", top),
right: inset("rIns", side),
bottom: inset("bIns", top),
}
}
/// One axis of the map from a group's child coordinates to EMUs from the top left corner of
/// the outermost group: `origin + (value - child) * num / den`. The fraction `num / den` is
/// kept in its lowest terms, which gives the same places, so that the terms of nested groups do
/// not grow when a group's child range equals its box; a place or a fraction that does not fit
/// gives `None`.
/// An axis-aligned orthogonal 2D transform (element of D4), with entries in `-1..=1`, mapping a
/// local scaled offset `(dx, dy)` to `(m[0][0]*dx + m[0][1]*dy, m[1][0]*dx + m[1][1]*dy)`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Ortho([[i32; 2]; 2]);
impl Ortho {
const IDENTITY: Self = Self([[1, 0], [0, 1]]);
/// Flip in local space first, then rotate clockwise by `quarters` (`0..=3`) in y-down space.
fn from_xfrm(quarters: i64, [flip_h, flip_v]: [bool; 2]) -> Self {
let rot = match quarters {
0 => Self([[1, 0], [0, 1]]),
1 => Self([[0, -1], [1, 0]]),
2 => Self([[-1, 0], [0, -1]]),
_ => Self([[0, 1], [-1, 0]]),
};
let sx = if flip_h { -1 } else { 1 };
let sy = if flip_v { -1 } else { 1 };
rot.compose(Self([[sx, 0], [0, sy]]))
}
const fn compose(self, inner: Self) -> Self {
let (a, b) = (self.0, inner.0);
Self([
[
a[0][0] * b[0][0] + a[0][1] * b[1][0],
a[0][0] * b[0][1] + a[0][1] * b[1][1],
],
[
a[1][0] * b[0][0] + a[1][1] * b[1][0],
a[1][0] * b[0][1] + a[1][1] * b[1][1],
],
])
}
fn apply(self, [x, y]: [i128; 2]) -> [i128; 2] {
[
i128::from(self.0[0][0]) * x + i128::from(self.0[0][1]) * y,
i128::from(self.0[1][0]) * x + i128::from(self.0[1][1]) * y,
]
}
}
/// Rational positive scale factor `num / den` for one axis of a group.
#[derive(Clone, Copy, Debug)]
struct Scale {
num: i128,
den: i128,
}
impl Scale {
const ONE: Self = Self { num: 1, den: 1 };
fn new(num: i128, den: i128) -> Self {
let (num, den) = lowest_terms(num, den);
Self { num, den }
}
fn scale(self, value: i128) -> Option<i128> {
Some(value.checked_mul(self.num)? / self.den)
}
fn compose(self, ext: i64, child_ext: i64) -> Option<Self> {
Some(Self::new(
self.num.checked_mul(i128::from(ext))?,
self.den.checked_mul(i128::from(child_ext.max(1)))?,
))
}
}
/// The affine map from a group's child coordinates to EMUs from the outermost group's corner,
/// including group flips and quarter-turn rotations.
#[derive(Clone, Copy, Debug)]
struct Map {
/// Doubled center `[2 * cx, 2 * cy]` of this group in outermost-group EMUs.
center_out2: [i128; 2],
/// Doubled center `[2 * chOff + chExt]` of the child coordinate space.
child_center2: [i128; 2],
/// Rational scale from child coordinates to local EMUs along each axis.
scale: [Scale; 2],
/// Accumulated D4 orthogonal transform from local scaled axes to outermost-group axes.
ortho: Ortho,
}
fn doubled_center(off: [i64; 2], ext: [i64; 2]) -> Option<[i128; 2]> {
Some([
i128::from(off[0])
.checked_mul(2)?
.checked_add(i128::from(ext[0]))?,
i128::from(off[1])
.checked_mul(2)?
.checked_add(i128::from(ext[1]))?,
])
}
impl Map {
const IDENTITY: Self = Self {
center_out2: [0, 0],
child_center2: [0, 0],
scale: [Scale::ONE, Scale::ONE],
ortho: Ortho::IDENTITY,
};
fn root(t: &Xfrm, ortho: Ortho) -> Option<Self> {
Some(Self {
center_out2: [i128::from(t.ext[0]), i128::from(t.ext[1])],
child_center2: doubled_center(t.child_off, t.child_ext)?,
scale: [
Scale::new(i128::from(t.ext[0]), i128::from(t.child_ext[0].max(1))),
Scale::new(i128::from(t.ext[1]), i128::from(t.child_ext[1].max(1))),
],
ortho,
})
}
fn mapped_center2(self, off: [i64; 2], ext: [i64; 2]) -> Option<[i128; 2]> {
let local = doubled_center(off, ext)?;
let across = local[0].checked_sub(self.child_center2[0])?;
let down = local[1].checked_sub(self.child_center2[1])?;
let scaled = [self.scale[0].scale(across)?, self.scale[1].scale(down)?];
let rotated = self.ortho.apply(scaled);
Some([
self.center_out2[0].checked_add(rotated[0])?,
self.center_out2[1].checked_add(rotated[1])?,
])
}
/// The unrotated corner and size of a part with the transform `t`, centered at its mapped
/// position relative to the outermost group's corner, or `None` when out of range.
fn place(self, t: &Xfrm) -> Option<([Length; 2], [Length; 2])> {
let center2 = self.mapped_center2(t.off, t.ext)?;
let sw = self.scale[0].scale(i128::from(t.ext[0]))?;
let sh = self.scale[1].scale(i128::from(t.ext[1]))?;
let left = i64::try_from(center2[0].checked_sub(sw)? / 2).ok()?;
let top = i64::try_from(center2[1].checked_sub(sh)? / 2).ok()?;
let width = i64::try_from(sw).ok()?;
let height = i64::try_from(sh).ok()?;
Some((
[Length::from_emus(left)?, Length::from_emus(top)?],
[Length::from_emus(width)?, Length::from_emus(height)?],
))
}
/// The map of a nested group inside this one with transform `t` and orthogonal transform
/// `inner_ortho`, or `None` when it does not fit.
fn inner(self, t: &Xfrm, inner_ortho: Ortho) -> Option<Self> {
Some(Self {
center_out2: self.mapped_center2(t.off, t.ext)?,
child_center2: doubled_center(t.child_off, t.child_ext)?,
scale: [
self.scale[0].compose(t.ext[0], t.child_ext[0])?,
self.scale[1].compose(t.ext[1], t.child_ext[1])?,
],
ortho: self.ortho.compose(inner_ortho),
})
}
}
/// The `a:xfrm` of a shape, picture or group, each as x and y.
#[derive(Clone, Copy, Debug)]
struct Xfrm {
/// `a:off`, the corner of the box.
off: [i64; 2],
/// `a:ext`, the size of the box.
ext: [i64; 2],
/// `a:chOff`, where the children's coordinates start, which only groups have. It
/// defaults to `off`.
child_off: [i64; 2],
/// `a:chExt`, the length of the children's coordinates, which defaults to `ext`.
child_ext: [i64; 2],
}
/// Reads the `a:xfrm` of a shape, picture or group.
fn xfrm(reader: &mut PartReader, node: NodeId) -> Xfrm {
let doc = reader.doc;
let props = ["grpSpPr", "spPr"]
.iter()
.find_map(|name| shape_child(doc, node, name).or_else(|| doc.child(node, PIC, name)))
.and_then(|props| doc.child(props, A, "xfrm"));
let mut value = |child: &str, name: &str| {
props
.and_then(|x| doc.child(x, A, child))
.and_then(|n| reader.emus(n, name))
};
let [x, y] = [value("off", "x"), value("off", "y")].map(|v| v.unwrap_or(0));
let [cx, cy] = [value("ext", "cx"), value("ext", "cy")].map(|v| v.unwrap_or(0));
Xfrm {
off: [x, y],
ext: [cx, cy],
child_off: [
value("chOff", "x").unwrap_or(x),
value("chOff", "y").unwrap_or(y),
],
child_ext: [
value("chExt", "cx").unwrap_or(cx),
value("chExt", "cy").unwrap_or(cy),
],
}
}
/// Collects the shapes, text boxes and pictures of a drawing group and of the groups inside it, each
/// with its offset from the outermost group's top left corner.
fn group_parts(
reader: &mut PartReader,
group: NodeId,
map: Map,
inherited_fill: Option<GroupFill>,
parts: &mut Vec<(Length, Length, Floating)>,
) {
let doc = reader.doc;
for child in doc.child_elements(group) {
let t = xfrm(reader, child);
// A part whose place, size or map does not fit is left out with a warning.
if is_shape_element(doc, child, "grpSp") || is_shape_element(doc, child, "wgp") {
let inner_ortho = read_group_ortho(reader, child);
let inner_box = map
.place(&t)
.and_then(|([l, tp], [w, h])| Edges::placed(l, tp, w, h))
.unwrap_or_default();
let inner_fill = resolve_group_fill(doc, child, inner_box, inherited_fill);
match map.inner(&t, inner_ortho) {
Some(inner) => group_parts(reader, child, inner, Some(inner_fill), parts),
None => reader.drawing_skipped(Drawing::Shape, Reason::OutOfRange),
}
continue;
}
let kind = if is_shape_element(doc, child, "wsp") {
Drawing::Shape
} else if doc.is(child, PIC, "pic") {
Drawing::Picture
} else {
// Another drawing in the group is left out with a warning.
skip_group_child(reader, child);
continue;
};
let Some(([left, top], [width, height])) = map.place(&t) else {
reader.drawing_skipped(kind, Reason::OutOfRange);
continue;
};
let mut part = Floating {
width,
height,
..Floating::in_part(reader.part())
};
if kind == Drawing::Shape {
let child_fill = inherited_fill.map(|gf| GroupFill {
props: gf.props,
frame: Edges {
left: gf.frame.left - left,
top: gf.frame.top - top,
right: gf.frame.right - left,
bottom: gf.frame.bottom - top,
},
});
read_shape_with_ortho(reader, child, map.ortho, child_fill, &mut part);
parts.push((left, top, part));
} else {
let frame = Edges::sized(part.width, part.height);
if let Some(mut picture) = Picture::from_pic(reader, child, frame) {
picture.compose_outer_turn(map.ortho.0);
part.picture = Some(picture);
parts.push((left, top, part));
}
}
}
}
/// Reads the orthogonal group transform (`flipH`, `flipV`, and whole quarter-turn `rot`) of
/// `group`'s `wpg:grpSpPr/a:xfrm`. Warns on [`crate::Feature::GroupTransform`] when `rot` is not a
/// whole quarter turn (drawn upright while keeping any flip). A `rot` that does not read counts
/// as missing, with a warning.
fn read_group_ortho(reader: &mut PartReader, group: NodeId) -> Ortho {
let doc = reader.doc;
let Some(xfrm) =
shape_child(doc, group, "grpSpPr").and_then(|props| doc.child(props, A, "xfrm"))
else {
return Ortho::IDENTITY;
};
let rotation = reader
.or_missing_in(xfrm, (None, "rot"), f_office_drawingml::integer)
.unwrap_or(0);
let flip = ["flipH", "flipV"].map(|name| {
doc.attribute(xfrm, None, name)
.is_some_and(f_office_drawingml::boolean)
});
let quarters = quarter_turns(rotation).unwrap_or_else(|| {
reader.feature_not_supported(crate::Feature::GroupTransform(GroupTransform::Turn));
0
});
Ortho::from_xfrm(quarters, flip)
}
/// Keeps the warning that the child `child` of a drawing group, which [`group_parts`] does not
/// read, is left out when it is a drawing, of its kind ([`group_drawing_kind`]): a chart
/// because it is in a group ([`ChartReason::InGroup`]), any other drawing as one that F-Office
/// does not draw ([`Reason::Unsupported`]). The group's own properties give no warning.
fn skip_group_child(reader: &mut PartReader, child: NodeId) {
if let Some(kind) = group_drawing_kind(reader.doc, child) {
let reason = match kind {
Drawing::Chart => Reason::Chart(ChartReason::InGroup),
Drawing::Picture | Drawing::SmartArt | Drawing::Shape => Reason::Unsupported,
};
reader.drawing_skipped(kind, reason);
}
}
/// The kind of drawing of the child `child` of a drawing group, or `None` when it is no
/// drawing, such as the group's properties: a shape (`wps:wsp`) or a group (`wpg:grpSp`) is a
/// shape, a picture (`pic:pic`) a picture, a graphic frame (`wpg:graphicFrame`) the kind of
/// its graphic ([`GRAPHICS`]) or else a shape, ink (`w14:contentPart`) a shape, and alternate
/// content the kind of the first drawing in the branch that the reader takes, else in a choice
/// that it passes over, so that a member with no branch, such as one whose only choice is a
/// chart of Office 2016 and later, still warns.
fn group_drawing_kind(doc: &Document, child: NodeId) -> Option<Drawing> {
if is_shape_element(doc, child, "wsp")
|| is_shape_element(doc, child, "grpSp")
|| is_shape_element(doc, child, "wgp")
|| doc.is(child, W14, "contentPart")
{
return Some(Drawing::Shape);
}
if doc.is(child, PIC, "pic") {
return Some(Drawing::Picture);
}
if is_shape_element(doc, child, "graphicFrame") {
let data = doc
.child(child, A, "graphic")
.and_then(|graphic| doc.child(graphic, A, "graphicData"));
return Some(
data.and_then(|data| graphic_kind(doc, data))
.unwrap_or(Drawing::Shape),
);
}
if doc.is(child, MC, "AlternateContent") {
let kind_in = |node: NodeId| {
doc.child_elements(node)
.find_map(|inner| group_drawing_kind(doc, inner))
};
return crate::body::alternate_branch(doc, child)
.and_then(kind_in)
.or_else(|| crate::body::passed_choices(doc, child).find_map(kind_in));
}
None
}
/// One axis of a drawing's place: the position element `name` (`wp:positionH` or
/// `wp:positionV`) of the anchor or of one of the `shown` branches of its alternate content,
/// whose `wp:align` the axis's table `align` reads.
fn position(
reader: &mut PartReader,
(anchor, shown): (NodeId, &[NodeId]),
(name, align): (&str, &'static Values<Align>),
) -> Position {
let doc = reader.doc;
// The position may sit in alternate content, as a share of its area (Word 2010) with a
// plain offset as the fallback; `read_anchor` gave the shown branches and warned of the
// choices that they pass over.
let node = doc
.child(anchor, WP, name)
.or_else(|| shown.iter().find_map(|branch| doc.child(*branch, WP, name)));
let Some(node) = node else {
return Position::default();
};
let from = reader
.enumeration_in(node, (None, "relativeFrom"), POSITION_FROM)
.unwrap_or_default();
// Word takes the offset in whole twips, cut toward zero.
let whole_twips = |offset: Length| offset.toward_zero_whole(Length::UNITS_PER_TWIP);
let offset = doc
.child(node, WP, "posOffset")
.and_then(|n| reader.emu_length_text(n))
.map_or(Length::ZERO, whole_twips);
// Only a value of the axis aligns: Word for Windows does not open a document with another
// value, so such a value gives the offset here, as it does in VML.
let align = doc
.child(node, WP, "align")
.and_then(|n| reader.enumeration_text(n, align));
let share = ["pctPosHOffset", "pctPosVOffset"]
.iter()
.find_map(|tag| doc.child(node, WP14, tag))
.and_then(|n| percentage(&doc.text_content(n)));
Position {
from,
offset,
align,
share,
}
}
#[cfg(test)]
mod tests {
use std::fmt::Write as _;
use f_office_units::Length;
use f_office_xml::{Document, Limits};
use super::{Wrap, WrapSides, read_anchor};
use crate::enumerations::assert_names;
use crate::ns::{A, C, PIC, R, W, WNE, WP, WP14, WPG, WPS};
use crate::props::Align;
use crate::reader::PartReader;
use crate::warnings::{Drawing, ReadAs, Reason};
use f_office_units::Edges;
/// A drawing group of 2 by 1 inches whose children count in units of 1000 per inch, with
/// a text box at (500, 0) and an inner group at (1000, 500) that maps its own 0 to 100 onto
/// 1000 by 500 units, holding a picture at (50, 0) of 50 by 100 of its units.
const GROUP: &str = r#"<wp:anchor><wp:extent cx="1828800" cy="914400"/><a:graphic><a:graphicData><wpg:wgp>
<wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/><a:chOff x="0" y="0"/><a:chExt cx="2000" cy="1000"/></a:xfrm></wpg:grpSpPr>
<wps:wsp><wps:spPr><a:xfrm><a:off x="500" y="0"/><a:ext cx="500" cy="250"/></a:xfrm></wps:spPr><wps:txbx><w:txbxContent><w:p/></w:txbxContent></wps:txbx></wps:wsp>
<wpg:grpSp><wpg:grpSpPr><a:xfrm><a:off x="1000" y="500"/><a:ext cx="1000" cy="500"/><a:chOff x="0" y="0"/><a:chExt cx="100" cy="100"/></a:xfrm></wpg:grpSpPr>
<pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill><pic:spPr><a:xfrm><a:off x="50" y="0"/><a:ext cx="50" cy="100"/></a:xfrm></pic:spPr></pic:pic>
</wpg:grpSp>
<wps:wsp><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="10" cy="10"/></a:xfrm></wps:spPr></wps:wsp>
</wpg:wgp></a:graphicData></a:graphic></wp:anchor>"#;
fn group() -> super::Floating {
anchor(GROUP)
}
/// Reads a floating drawing from the XML of its `wp:anchor`.
fn anchor(xml: &str) -> super::Floating {
anchor_warned(xml).0
}
/// The XML of a `w:drawing` that holds the `wp:anchor` `xml`, with the namespaces of its
/// parts.
fn drawing_doc(xml: &str) -> Document {
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wpg="{WPG}" xmlns:wps="{WPS}" xmlns:pic="{PIC}" xmlns:r="{R}">{xml}</w:drawing>"#
);
Document::parse(xml.as_bytes(), &Limits::default()).unwrap()
}
/// [`anchor`], with the element, the attribute and the count of each value that counts as
/// missing, and the element, the attribute, the name and the count of each name that is
/// drawn as another.
#[expect(clippy::type_complexity, reason = "the two lists of a test reading")]
fn anchor_warned(
xml: &str,
) -> (
super::Floating,
Vec<(String, Option<String>, u32)>,
Vec<(String, Option<String>, &'static str, u32)>,
) {
let doc = drawing_doc(xml);
let mut reader = PartReader::new(&doc);
let drawing = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
let mut invalid: Vec<(String, Option<String>, u32)> = reader
.invalid_values()
.into_iter()
.map(|(element, attribute, _, count)| (element, attribute, count))
.collect();
invalid.sort();
(drawing, invalid, reader.unsupported_values())
}
#[test]
fn warns_of_an_alignment_or_a_wrap_side_that_it_does_not_draw() {
let (drawing, invalid, unsupported) = anchor_warned(
r#"<wp:anchor><wp:positionH relativeFrom="page"><wp:align> outside </wp:align></wp:positionH><wp:positionV relativeFrom="page"><wp:align>middle</wp:align></wp:positionV><wp:extent cx="914400" cy="914400"/><wp:wrapSquare wrapText="both"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#,
);
// Horizontal `outside` is supported directly (`Align::Outside`); text outside the types
// counts as missing.
assert_eq!(
(drawing.h.align, drawing.v.align),
(Some(Align::Outside), None)
);
assert_eq!(drawing.wrap, Some(square(WrapSides::Both)));
assert_eq!(unsupported, vec![]);
assert_eq!(
invalid,
[
("align".to_owned(), None, 1),
("wrapSquare".to_owned(), Some("wrapText".to_owned()), 1),
]
);
let (drawing, invalid, unsupported) = anchor_warned(
r#"<wp:anchor><wp:extent cx="914400" cy="914400"/><wp:wrapSquare wrapText="largest"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#,
);
assert_eq!(drawing.wrap, Some(square(WrapSides::Largest)));
assert_eq!((invalid, unsupported), (vec![], vec![]));
}
#[test]
fn warns_of_a_place_relative_to_the_character_and_of_area_names_outside_the_types() {
use super::{PageArea, Relative};
// A position relative to the character counts from the margins, with a warning that it
// is drawn as another; a name outside the types counts as missing, with a warning, so
// that the position counts from the margins and the relative size is left out.
let (drawing, invalid, unsupported) = anchor_warned(&format!(
r#"<wp:anchor xmlns:wp14="{WP14}"><wp:positionH relativeFrom="character"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="nowhere"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="914400" cy="914400"/><wp14:sizeRelH relativeFrom="nowhere"><wp14:pctWidth>40000</wp14:pctWidth></wp14:sizeRelH><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
));
let margins = Relative::Area(PageArea::Margin);
assert_eq!((drawing.h.from, drawing.v.from), (margins, margins));
assert_eq!(drawing.relative_width, None);
let from = Some("relativeFrom".to_owned());
assert_eq!(
unsupported,
[("positionH".to_owned(), from.clone(), "character", 1)]
);
assert_eq!(
invalid,
[
("positionV".to_owned(), from.clone(), 1),
("sizeRelH".to_owned(), from, 1),
]
);
}
#[test]
fn reads_each_area_name_of_a_position_and_of_a_size_of_either_axis() {
assert_names(
super::POSITION_FROM,
"character column insideMargin leftMargin margin outsideMargin page rightMargin \
bottomMargin line paragraph topMargin",
);
assert_names(
super::SIZE_FROM,
"margin page leftMargin rightMargin insideMargin outsideMargin topMargin bottomMargin",
);
}
#[test]
fn leaves_out_a_graphic_of_another_kind_as_a_shape_with_a_warning() {
// A graphic of an element that F-Office does not read, such as a locked canvas, is left
// out with a warning, floating and inline; a picture that does not read, which the
// picture reader warns of, and graphic data without an element give none here.
const CANVAS: &str = r#"<lc:lockedCanvas xmlns:lc="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"/>"#;
let drawing = |kind: &str, graphic: &str| {
drawing_doc(&format!(
r#"<wp:{kind}><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData>{graphic}</a:graphicData></a:graphic></wp:{kind}>"#
))
};
let floating = |graphic: &str| {
let doc = drawing("anchor", graphic);
let mut reader = PartReader::new(&doc);
assert!(read_anchor(&mut reader, doc.root().unwrap()).is_none());
reader.skipped_drawings()
};
let skipped = [(Drawing::Shape, Reason::Unsupported, 1)];
assert_eq!(floating(CANVAS), skipped);
assert_eq!(floating("<pic:pic/>"), []);
assert_eq!(floating(""), []);
let doc = drawing("inline", CANVAS);
let mut reader = PartReader::new(&doc);
let node = doc.child(doc.root().unwrap(), WP, "inline").unwrap();
let shape = super::read_inline_shape(&mut reader, node, Length::ZERO, Length::ZERO);
assert!(shape.is_none());
assert_eq!(reader.skipped_drawings(), skipped);
}
/// A square wrap on `sides`, without distances.
fn square(sides: WrapSides) -> Wrap {
Wrap::Beside {
distances: Edges::default(),
sides: Some(sides),
polygon: None,
}
}
#[test]
fn reads_a_floating_chart_with_its_chart_and_its_wrap() {
let drawing = anchor(&format!(
r#"<wp:anchor behindDoc="1"><wp:positionH relativeFrom="margin"><wp:posOffset>-635000</wp:posOffset></wp:positionH><wp:extent cx="914400" cy="914400"/><wp:wrapSquare wrapText="bothSides"/><a:graphic><a:graphicData><c:chart xmlns:c="{C}" r:id="rId2"/></a:graphicData></a:graphic></wp:anchor>"#
));
// The chart waits for its part, and its frame keeps the text out on both sides.
assert_eq!(drawing.chart.map(|chart| chart.id), Some("rId2".to_owned()));
assert_eq!(drawing.wrap, Some(square(WrapSides::Both)));
assert_eq!(Some(drawing.h.offset), Length::from_points(-50));
assert!(drawing.behind);
}
#[test]
fn keeps_the_wrap_of_a_shape_but_not_of_a_shape_without_height() {
let shape = |cy: i64, wrap: &str| {
anchor(&format!(
r#"<wp:anchor distT="0" distB="0"><wp:extent cx="914400" cy="{cy}"/>{wrap}<a:graphic><a:graphicData><wps:wsp><wps:spPr><a:prstGeom prst="line"/></wps:spPr></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
))
};
// A shape without a text box or a picture keeps its top and bottom wrap.
let boxed = shape(457_200, "<wp:wrapTopAndBottom/>");
assert_eq!(
boxed.wrap,
Some(Wrap::TopAndBottom {
above: Length::ZERO,
below: Length::ZERO
})
);
// A horizontal line without height keeps no text out.
let line = shape(0, r#"<wp:wrapSquare wrapText="bothSides"/>"#);
assert_eq!(line.wrap, None);
}
#[test]
fn cuts_an_offset_toward_zero_to_whole_twips() {
let placed = |x: i64, y: i64| {
let drawing = anchor(&format!(
r#"<wp:anchor><wp:positionH relativeFrom="column"><wp:posOffset>{x}</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>{y}</wp:posOffset></wp:positionV><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
));
(drawing.h.offset, drawing.v.offset)
};
let twips = |n: i64| Length::from_twips(n).unwrap();
// 5,935,318 EMU is 9,346.96 twips, and 1,015 EMU 1.6: both go down to whole twips.
assert_eq!(placed(5_935_318, 1_015), (twips(9_346), twips(1)));
// -108,144 EMU is -170.31 twips, which goes up to -170, toward zero.
assert_eq!(placed(-108_144, -634), (twips(-170), Length::ZERO));
assert_eq!(placed(635, -635), (twips(1), twips(-1)));
}
#[test]
fn reads_a_length_with_a_unit_and_an_offset_with_spaces_as_missing() {
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wps="{WPS}"><wp:anchor distL="0.5in"><wp:positionH relativeFrom="column"><wp:posOffset> 914400 </wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>914400</wp:posOffset></wp:positionV><wp:extent cx="1in" cy="914400"/><wp:effectExtent l="0" t="0" r="0" b="12700.5"/><wp:wrapSquare wrapText="bothSides"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut reader = PartReader::new(&doc);
let drawing = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
let inch = Length::from_emus(914_400).unwrap();
assert_eq!((drawing.width, drawing.height), (inch, inch));
assert_eq!((drawing.h.offset, drawing.v.offset), (Length::ZERO, inch));
let half = Length::from_emus(457_200).unwrap();
assert_eq!(
drawing.wrap,
Some(Wrap::Beside {
distances: Edges {
left: half,
..Edges::default()
},
sides: Some(WrapSides::Both),
polygon: None,
})
);
let mut invalid = reader.invalid_values();
invalid.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(
invalid,
[
("effectExtent".into(), Some("b".into()), ReadAs::Missing, 1),
("posOffset".into(), None, ReadAs::Missing, 1),
]
);
}
#[test]
fn aligns_only_with_a_value_of_the_axis() {
let placed = |across: &str, down: &str| {
let drawing = anchor(&format!(
r#"<wp:anchor><wp:positionH relativeFrom="page"><wp:align>{across}</wp:align></wp:positionH><wp:positionV relativeFrom="page"><wp:align>{down}</wp:align></wp:positionV><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
));
(drawing.h.align, drawing.v.align)
};
assert_eq!(
placed("right", "bottom"),
(Some(Align::End), Some(Align::End))
);
assert_eq!(
placed(" center ", "inside"),
(Some(Align::Center), Some(Align::Start))
);
// A value of the other axis, an unknown value or a capital gives no alignment.
assert_eq!(placed("bottom", "right"), (None, None));
assert_eq!(placed("top", "left"), (None, None));
assert_eq!(placed("middle", "Bottom"), (None, None));
}
/// A length in thousandths of an inch.
fn inches(milli: i64) -> Length {
Length::from_emus(milli * 914_400 / 1000).unwrap()
}
#[test]
fn reads_a_drawing_group_as_one_drawing_with_its_parts() {
let group = group();
assert_eq!((group.width, group.height), (inches(2000), inches(1000)));
assert!(group.blocks.is_empty() && group.picture.is_none());
// The shape without a text box is a part too, which shows only its look.
assert_eq!(group.parts.len(), 3);
let (_, _, shape) = &group.parts[2];
assert!(shape.blocks.is_empty() && shape.picture.is_none() && shape.look.is_some());
}
#[test]
fn places_the_text_boxes_and_pictures_of_a_drawing_group() {
let group = group();
let (left, top, text_box) = &group.parts[0];
assert_eq!((*left, *top), (inches(500), Length::ZERO));
assert_eq!(
(text_box.width, text_box.height),
(inches(500), inches(250))
);
assert_eq!(text_box.blocks.len(), 1);
// The inner group puts its picture at 1000 + 50 * 10 and 500 + 0 units of the outer
// group, and makes it 500 by 500 of them.
let (left, top, picture) = &group.parts[1];
assert_eq!((*left, *top), (inches(1500), inches(500)));
assert_eq!((picture.width, picture.height), (inches(500), inches(500)));
assert_eq!(picture.picture.as_ref().unwrap().embed, "rId1");
}
#[test]
fn places_the_parts_of_an_inline_drawing_group() {
let inline = GROUP.replace("wp:anchor", "wp:inline");
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wpg="{WPG}" xmlns:wps="{WPS}" xmlns:pic="{PIC}" xmlns:r="{R}">{inline}</w:drawing>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let node = doc.child(doc.root().unwrap(), WP, "inline").unwrap();
let group =
super::read_inline_shape(&mut PartReader::new(&doc), node, inches(2000), inches(1000))
.unwrap();
assert_eq!(group.parts.len(), 3);
let (left, top, text_box) = &group.parts[0];
assert_eq!((*left, *top), (inches(500), Length::ZERO));
assert_eq!(text_box.blocks.len(), 1);
let (left, top, _) = &group.parts[1];
assert_eq!((*left, *top), (inches(1500), inches(500)));
}
#[test]
fn reads_anchored_and_inline_drawing_canvases_with_backdrop_shapes_group_and_picture() {
use crate::ns::WPC;
let canvas = r#"<wpc:wpc><wpc:bg><a:solidFill><a:srgbClr val="E8EEF5"/></a:solidFill></wpc:bg><wpc:whole><a:ln w="12700"><a:solidFill><a:srgbClr val="2F5597"/></a:solidFill></a:ln></wpc:whole><wps:wsp><wps:spPr><a:xfrm><a:off x="91440" y="45720"/><a:ext cx="914400" cy="457200"/></a:xfrm><a:prstGeom prst="rect"/></wps:spPr></wps:wsp><wpg:wgp><wpg:grpSpPr><a:xfrm><a:off x="182880" y="91440"/><a:ext cx="914400" cy="457200"/><a:chOff x="0" y="0"/><a:chExt cx="457200" cy="228600"/></a:xfrm></wpg:grpSpPr><wps:wsp><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="228600" cy="114300"/></a:xfrm><a:prstGeom prst="rect"/></wps:spPr></wps:wsp></wpg:wgp><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill><pic:spPr><a:xfrm><a:off x="457200" y="228600"/><a:ext cx="457200" cy="228600"/></a:xfrm></pic:spPr></pic:pic></wpc:wpc>"#;
let anchored = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wpc="{WPC}" xmlns:wpg="{WPG}" xmlns:wps="{WPS}" xmlns:pic="{PIC}" xmlns:r="{R}"><wp:anchor><wp:extent cx="1828800" cy="914400"/><a:graphic><a:graphicData>{canvas}</a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(anchored.as_bytes(), &Limits::default()).unwrap();
let mut reader = PartReader::new(&doc);
let drawing = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
let offsets: Vec<(Length, Length)> =
drawing.parts.iter().map(|(x, y, _)| (*x, *y)).collect();
assert_eq!(
(
reader.skipped_drawings().len(),
offsets,
drawing.parts[0].2.width,
drawing.parts[2].2.width,
drawing.parts[3]
.2
.picture
.as_ref()
.map(|p| p.embed.as_str()),
),
(
0,
vec![
(Length::ZERO, Length::ZERO),
(inches(100), inches(50)),
(inches(200), inches(100)),
(inches(500), inches(250)),
],
inches(2000),
inches(500),
Some("rId1"),
)
);
let inline = anchored.replace("wp:anchor", "wp:inline");
let doc = Document::parse(inline.as_bytes(), &Limits::default()).unwrap();
let node = doc.child(doc.root().unwrap(), WP, "inline").unwrap();
let inline_drawing =
super::read_inline_shape(&mut PartReader::new(&doc), node, inches(2000), inches(1000))
.unwrap();
assert_eq!(inline_drawing.parts.len(), 4);
}
/// The size of the range of a coordinate, `ST_Coordinate`, in EMU.
const MOST: i64 = f_office_drawingml::COORDINATE_LIMIT;
/// A drawing group of 2 by 1 inches that holds `parts`, whose children count in units of
/// 1000 per inch, with the kinds, reasons and counts of the drawings left out.
fn group_of(parts: &str) -> (super::Floating, Vec<(Drawing, Reason, u32)>) {
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wpg="{WPG}" xmlns:wps="{WPS}" xmlns:pic="{PIC}" xmlns:r="{R}"><wp:anchor><wp:extent cx="1828800" cy="914400"/><a:graphic><a:graphicData><wpg:wgp><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/><a:chOff x="0" y="0"/><a:chExt cx="2000" cy="1000"/></a:xfrm></wpg:grpSpPr>{parts}</wpg:wgp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut reader = PartReader::new(&doc);
let drawing = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
(drawing, reader.skipped_drawings())
}
/// A group part at `off` with the size `ext` whose children range over `child`, holding
/// `inner`.
fn group_part(off: (i64, i64), ext: (i64, i64), child: (i64, i64), inner: &str) -> String {
format!(
r#"<wpg:grpSp><wpg:grpSpPr><a:xfrm><a:off x="{}" y="{}"/><a:ext cx="{}" cy="{}"/><a:chOff x="0" y="0"/><a:chExt cx="{}" cy="{}"/></a:xfrm></wpg:grpSpPr>{inner}</wpg:grpSp>"#,
off.0, off.1, ext.0, ext.1, child.0, child.1
)
}
/// A picture part at `off` with the size `ext`.
fn picture_part(off: (i64, i64), ext: (i64, i64)) -> String {
format!(
r#"<pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill><pic:spPr><a:xfrm><a:off x="{}" y="{}"/><a:ext cx="{}" cy="{}"/></a:xfrm></pic:spPr></pic:pic>"#,
off.0, off.1, ext.0, ext.1
)
}
/// A shape part at `off` with the size `ext`.
fn shape_part(off: (i64, i64), ext: (i64, i64)) -> String {
format!(
r#"<wps:wsp><wps:spPr><a:xfrm><a:off x="{}" y="{}"/><a:ext cx="{}" cy="{}"/></a:xfrm></wps:spPr></wps:wsp>"#,
off.0, off.1, ext.0, ext.1
)
}
#[test]
fn places_the_parts_of_groups_nested_with_large_child_ranges_exactly() {
// Three groups inside each other, the outer one over 1000 by 1000 units at (1000, 0),
// each with a child range of the largest coordinate: the terms of their maps would
// pass `i128` without the lowest terms.
let picture = picture_part((0, 0), (MOST / 2, MOST));
let range = (MOST, MOST);
let inner = group_part((0, 0), range, range, &picture);
let middle = group_part((0, 0), range, range, &inner);
let (group, skipped) = group_of(&group_part((1000, 0), (1000, 1000), range, &middle));
assert_eq!(skipped, []);
let (left, top, part) = &group.parts[0];
assert_eq!((*left, *top), (inches(1000), Length::ZERO));
assert_eq!((part.width, part.height), (inches(500), inches(1000)));
}
#[test]
fn leaves_out_a_group_part_whose_place_or_map_lies_out_of_range_with_a_warning() {
// A picture at the largest coordinate of the group lies 2.5e16 EMU out, beyond the
// range of a length; a shape as wide as that is too; three groups that each map one
// unit to the largest coordinate give a map beyond `i128`. The small shape stays.
let one = (1, 1);
let range = (MOST, MOST);
let shapes = shape_part((0, 0), (10, 10));
let deep = group_part(
(0, 0),
range,
one,
&group_part((0, 0), range, one, &group_part((0, 0), range, one, &shapes)),
);
let parts = [
picture_part((MOST, 0), (10, 10)),
shape_part((0, 0), (MOST, 10)),
deep,
shape_part((0, 0), (10, 10)),
];
let (group, mut skipped) = group_of(&parts.concat());
skipped.sort_by_key(|(drawing, _, _)| *drawing == Drawing::Shape);
let far = Reason::OutOfRange;
assert_eq!(
skipped,
[(Drawing::Picture, far, 1), (Drawing::Shape, far, 2)]
);
assert_eq!(group.parts.len(), 1);
assert_eq!(group.parts[0].2.width, inches(10));
}
#[test]
fn reads_an_offset_within_the_range_of_a_coordinate_only() {
let placed = |x: i64| {
let (drawing, invalid, _) = anchor_warned(&format!(
r#"<wp:anchor><wp:positionH relativeFrom="page"><wp:posOffset>{x}</wp:posOffset></wp:positionH><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
));
(drawing.h.offset, invalid)
};
// The largest coordinate is whole twips.
assert_eq!(placed(MOST), (Length::from_emus(MOST).unwrap(), vec![]));
assert_eq!(placed(-MOST), (Length::from_emus(-MOST).unwrap(), vec![]));
let missing = vec![("posOffset".to_owned(), None, 1)];
assert_eq!(placed(MOST + 1), (Length::ZERO, missing.clone()));
assert_eq!(placed(-MOST - 1), (Length::ZERO, missing));
}
#[test]
fn reads_a_wrap_polygon_whose_bounds_lie_out_of_range_as_none_with_a_warning() {
// A drawing as wide as the largest coordinate with a polygon that reaches as far: the
// product of the two would pass `i64`, and the bound lies beyond the range of a length.
let doc = drawing_doc(&format!(
r#"<wp:anchor><wp:extent cx="{MOST}" cy="914400"/><wp:wrapTight><wp:wrapPolygon><wp:start x="0" y="0"/><wp:lineTo x="{MOST}" y="0"/><wp:lineTo x="{MOST}" y="21600"/><wp:lineTo x="0" y="21600"/></wp:wrapPolygon></wp:wrapTight><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:anchor>"#
));
let mut reader = PartReader::new(&doc);
let drawing = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
let Some(Wrap::Beside { polygon, .. }) = drawing.wrap else {
panic!("{:?}", drawing.wrap);
};
assert_eq!(polygon, Some(Edges::default()));
// The polygon's points read; only its bounds lie out of range, which its own warning
// says, with the part.
assert_eq!(reader.invalid_values(), []);
let mut warnings = crate::Warnings::new();
reader.finish(&mut warnings);
let skipped = crate::Warning::WrapPolygonSkipped {
part: f_office_warnings::Name::new(crate::testing::DOCUMENT),
reason: crate::Reason::OutOfRange,
};
assert_eq!(warnings.into_iter().collect::<Vec<_>>(), [(skipped, 1)]);
}
/// A picture of 2 by 1 inches with a through wrap of 0.1 inch to the sides and its polygon
/// over the middle half of its height.
fn through(edited: u8) -> super::Floating {
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:pic="{PIC}" xmlns:r="{R}"><wp:anchor distT="91440" distB="91440" distL="91440" distR="91440"><wp:extent cx="1828800" cy="914400"/><wp:wrapThrough><wp:wrapPolygon edited="{edited}"><wp:start x="0" y="5400"/><wp:lineTo x="21600" y="5400"/><wp:lineTo x="21600" y="16200"/><wp:lineTo x="0" y="16200"/></wp:wrapPolygon></wp:wrapThrough><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap()
}
#[test]
fn keeps_the_outline_of_a_wrap_polygon_that_is_not_its_bounds() {
// A rectangle keeps no outline.
assert_eq!(through(1).outline, []);
// A polygon free at the left of its bottom half keeps its points in order.
let points = [
(0, 0),
(0, 10800),
(10800, 10800),
(10800, 21600),
(21600, 21600),
(21600, 0),
(0, 0),
];
let mut polygon = String::new();
for (k, (x, y)) in points.iter().enumerate() {
let name = if k == 0 { "start" } else { "lineTo" };
write!(polygon, r#"<wp:{name} x="{x}" y="{y}"/>"#).unwrap();
}
let doc = drawing_doc(&format!(
r#"<wp:anchor><wp:extent cx="914400" cy="914400"/><wp:wrapTight wrapText="bothSides"><wp:wrapPolygon edited="1">{polygon}</wp:wrapPolygon></wp:wrapTight><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:anchor>"#
));
let drawing = read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
assert_eq!(drawing.outline, points);
}
#[test]
fn reads_the_bounds_of_a_wrap_polygon() {
// The polygon lies 0.25 inch inside the top and the bottom edges, edited or not, and
// the text keeps 0.1 inch from it.
for edited in [0, 1] {
let through = through(edited);
// The polygon is a rectangle, its own bounds, so the text flows on both sides.
assert_eq!(
through.wrap,
Some(Wrap::Beside {
distances: Edges::from([inches(100); 4]),
sides: Some(WrapSides::Both),
polygon: Some(Edges::from([
inches(0),
inches(250),
inches(0),
inches(250)
])),
})
);
}
}
/// A text box with a width of 40% of the margins and a height of 20% of the page, and the
/// body properties `body`.
fn relative_box(body: &str) -> super::Floating {
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:wp14="{WP14}" xmlns:a="{A}" xmlns:wps="{WPS}"><wp:anchor><wp:extent cx="914400" cy="914400"/><wp14:sizeRelH relativeFrom="margin"><wp14:pctWidth>40000</wp14:pctWidth></wp14:sizeRelH><wp14:sizeRelV relativeFrom="page"><wp14:pctHeight>20000</wp14:pctHeight></wp14:sizeRelV><a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent><w:p/></w:txbxContent></wps:txbx>{body}</wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap()
}
#[test]
fn reads_relative_sizes_and_keeps_the_height_of_a_box_that_fits_its_text() {
use super::PageArea;
let fixed = relative_box("<wps:bodyPr/>");
assert_eq!(fixed.relative_width, Some((PageArea::Margin, 40_000)));
assert_eq!(fixed.relative_height, Some((PageArea::Page, 20_000)));
assert_eq!(fixed.inset_edge, super::InsetEdge::Inside);
let fitting = relative_box("<wps:bodyPr><a:spAutoFit/></wps:bodyPr>");
assert_eq!(fitting.relative_width, Some((PageArea::Margin, 40_000)));
assert_eq!(fitting.relative_height, None);
// The box that fits its text takes its height from the text when it is drawn.
assert!(fitting.fits_text);
assert!(!fixed.fits_text);
}
#[test]
fn reads_the_area_names_of_a_position_and_of_a_relative_size() {
use super::{PageArea, Relative};
// A position and a size share the names of the page, the margins and the margin
// areas; only a position counts from the anchor paragraph or the text column, and a
// position with an unknown name counts from the margins.
let read = |from: &str| {
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:wp14="{WP14}" xmlns:a="{A}" xmlns:wps="{WPS}"><wp:anchor><wp:positionH relativeFrom="{from}"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:extent cx="914400" cy="914400"/><wp14:sizeRelH relativeFrom="{from}"><wp14:pctWidth>40000</wp14:pctWidth></wp14:sizeRelH><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let floating = read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
(
floating.h.from,
floating.relative_width.map(|(area, _)| area),
)
};
let cases = [
("page", Relative::Area(PageArea::Page), Some(PageArea::Page)),
(
"margin",
Relative::Area(PageArea::Margin),
Some(PageArea::Margin),
),
(
"leftMargin",
Relative::Area(PageArea::StartMargin),
Some(PageArea::StartMargin),
),
(
"topMargin",
Relative::Area(PageArea::StartMargin),
Some(PageArea::StartMargin),
),
(
"insideMargin",
Relative::Area(PageArea::StartMargin),
Some(PageArea::StartMargin),
),
(
"rightMargin",
Relative::Area(PageArea::EndMargin),
Some(PageArea::EndMargin),
),
(
"bottomMargin",
Relative::Area(PageArea::EndMargin),
Some(PageArea::EndMargin),
),
(
"outsideMargin",
Relative::Area(PageArea::EndMargin),
Some(PageArea::EndMargin),
),
("paragraph", Relative::Paragraph, None),
("line", Relative::Line, None),
("column", Relative::Column, None),
("character", Relative::Area(PageArea::Margin), None),
("nowhere", Relative::Area(PageArea::Margin), None),
];
for (from, position, size) in cases {
assert_eq!(read(from), (position, size), "{from}");
}
}
#[test]
fn reads_the_content_of_a_text_box_that_word_writes_in_a_strict_document() {
// Word writes the content of a Strict document's text box as `wne:txbxContent`.
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wne="{WNE}"><wp:anchor><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wp:wsp><wp:spPr/><wp:txbx><wne:txbxContent><w:p/><w:p/></wne:txbxContent></wp:txbx><wp:bodyPr/></wp:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let floating = read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
assert_eq!(floating.blocks.len(), 2);
}
#[test]
fn reads_the_shapes_and_percentages_of_a_strict_document() {
use super::PageArea;
// A Strict document has the shape's elements in the namespace of `wp:anchor` and
// writes a percentage with its sign.
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:wp14="{WP14}" xmlns:a="{A}"><wp:anchor><wp:positionH relativeFrom="page"><wp14:pctPosHOffset>45.5%</wp14:pctPosHOffset></wp:positionH><wp:extent cx="914400" cy="914400"/><wp14:sizeRelH relativeFrom="page"><wp14:pctWidth>37%</wp14:pctWidth></wp14:sizeRelH><a:graphic><a:graphicData><wp:wsp><wp:spPr/><wp:txbx><w:txbxContent><w:p/></w:txbxContent></wp:txbx><wp:bodyPr/></wp:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let floating = read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
assert!(floating.look.is_some());
assert_eq!(floating.blocks.len(), 1);
assert_eq!(floating.relative_width, Some((PageArea::Page, 37_000)));
assert_eq!(floating.h.share, Some(45_500));
// A group in that namespace gives its shapes as parts.
let group = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}"><wp:anchor><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wp:wgp><wp:grpSpPr/><wp:wsp><wp:spPr/></wp:wsp></wp:wgp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(group.as_bytes(), &Limits::default()).unwrap();
assert_eq!(
read_anchor(&mut PartReader::new(&doc), doc.root().unwrap())
.unwrap()
.parts
.len(),
1
);
}
#[test]
fn computes_page_numbers_in_text_boxes() {
use crate::body::{Block, Content};
let field = r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>6</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wps="{WPS}"><wp:anchor><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent>{field}</w:txbxContent></wps:txbx></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let floating = read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
let Some(Block::Paragraph(paragraph)) = floating.blocks.first() else {
panic!("no paragraph");
};
let content: Vec<&Content> = paragraph.runs.iter().flat_map(|r| &r.content).collect();
// The stored "6" is gone, and layout computes the number. The field's result and its
// end leave field marks.
let mark = &Content::FieldMark;
assert_eq!(content, vec![mark, &Content::PageNumber, mark]);
}
#[test]
fn a_position_in_alternate_content_warns_once_of_each_passed_choice() {
use crate::ns::MC;
// The place across sits in alternate content whose choice requires a namespace that
// F-Office does not take, and the place down in a second alternate content after it.
// Each axis looks in both, and the passed choice warns once.
let xml = format!(
r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:wp14="{WP14}" xmlns:a="{A}" xmlns:wps="{WPS}" xmlns:mc="{MC}" xmlns:x="urn:other"><wp:anchor><mc:AlternateContent><mc:Choice Requires="x"><wp:positionH relativeFrom="page"><wp:posOffset>914400</wp:posOffset></wp:positionH></mc:Choice><mc:Fallback><wp:positionH relativeFrom="page"><wp:posOffset>457200</wp:posOffset></wp:positionH></mc:Fallback></mc:AlternateContent><mc:AlternateContent><mc:Choice Requires="wp14"><wp:positionV relativeFrom="page"><wp14:pctPosVOffset>10000</wp14:pctPosVOffset></wp:positionV></mc:Choice><mc:Fallback><wp:positionV relativeFrom="page"><wp:posOffset>0</wp:posOffset></wp:positionV></mc:Fallback></mc:AlternateContent><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent><w:p/></w:txbxContent></wps:txbx></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut reader = PartReader::new(&doc);
let floating = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
// The fallback places the drawing across, and the taken choice down.
assert_eq!(
(floating.h.offset, floating.h.share, floating.v.share),
(inches(500), None, Some(10_000))
);
let mut warnings = crate::Warnings::default();
reader.finish(&mut warnings);
let kinds: Vec<_> = warnings
.iter()
.map(|(warning, count)| (warning.kind().to_string(), count))
.collect();
assert_eq!(kinds, [("alternate-choice-not-supported".to_string(), 1)]);
}
#[test]
fn gives_a_group_member_in_alternate_content_with_no_branch_the_kind_of_a_passed_choice() {
use crate::ns::{CX, MC};
let member = |fallback: &str| {
format!(
r#"<mc:AlternateContent xmlns:mc="{MC}" xmlns:wpg="{WPG}" xmlns:a="{A}" xmlns:cx="{CX}" xmlns:pic="{PIC}"><mc:Choice Requires="cx"><wpg:graphicFrame><a:graphic><a:graphicData><cx:chart/></a:graphicData></a:graphic></wpg:graphicFrame></mc:Choice>{fallback}</mc:AlternateContent>"#
)
};
// (fallback, kind): a chart of Office 2016 and later is no taken choice, so with no
// fallback, or a fallback with no drawing, the passed choice gives the kind; a
// fallback's drawing gives its own.
let cases = [
("", Some(Drawing::Chart)),
("<mc:Fallback/>", Some(Drawing::Chart)),
(
"<mc:Fallback><pic:pic/></mc:Fallback>",
Some(Drawing::Picture),
),
];
for (fallback, kind) in cases {
let xml = member(fallback);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
assert_eq!(
super::group_drawing_kind(&doc, doc.root().unwrap()),
kind,
"{xml}"
);
}
}
#[test]
fn a_text_box_takes_the_font_color_of_its_shape_style() {
let shape = |style: &str| {
anchor(&format!(
r#"<wp:anchor><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/><wps:style>{style}</wps:style><wps:txbx><w:txbxContent><w:p/></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
))
.text_color
};
assert_eq!(
shape(r#"<a:fontRef idx="minor"><a:srgbClr val="ED7D31"/></a:fontRef>"#),
Some([0xED, 0x7D, 0x31])
);
// A scheme color that the reading has no theme for gives none.
assert_eq!(
shape(r#"<a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef>"#),
None
);
assert_eq!(shape(r#"<a:fontRef idx="minor"/>"#), None);
}
#[test]
fn composes_group_flips_and_quarter_turns_on_children_and_nested_groups() {
// flipH composed with (rot=90 * flipV) cancels the two reflections to pure rot=90.
let flip_h = super::Ortho::from_xfrm(0, [true, false]);
let inner = super::Ortho::from_xfrm(1, [false, true]);
assert_eq!(
flip_h.compose(inner),
super::Ortho::from_xfrm(1, [false, false])
);
// A 120x60 pt group rotated 90 deg CW rotates a child rect at (6, 6, 26, 20) to center
// (74, -11) with unrotated box (61, -21, 26, 20) and 90 deg CW look rotation.
let pt = 12_700_i64;
let group = anchor(&format!(
concat!(
r#"<wp:anchor><wp:extent cx="{w}" cy="{h}"/><a:graphic><a:graphicData>"#,
r#"<wpg:wgp><wpg:grpSpPr><a:xfrm rot="5400000">"#,
r#"<a:off x="0" y="0"/><a:ext cx="{w}" cy="{h}"/>"#,
r#"<a:chOff x="0" y="0"/><a:chExt cx="{w}" cy="{h}"/>"#,
r#"</a:xfrm></wpg:grpSpPr>"#,
r#"<wps:wsp><wps:spPr><a:xfrm><a:off x="{cx}" y="{cy}"/><a:ext cx="{cw}" cy="{ch}"/></a:xfrm>"#,
r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></wps:spPr></wps:wsp>"#,
r#"</wpg:wgp></a:graphicData></a:graphic></wp:anchor>"#,
),
w = 120 * pt,
h = 60 * pt,
cx = 6 * pt,
cy = 6 * pt,
cw = 26 * pt,
ch = 20 * pt,
));
assert_eq!(group.parts.len(), 1);
let (left, top, ref part) = group.parts[0];
assert_eq!(
(left, top, part.width, part.height),
(
Length::from_points(61).unwrap(),
Length::from_points(-21).unwrap(),
Length::from_points(26).unwrap(),
Length::from_points(20).unwrap(),
)
);
assert_eq!(
part.look.as_ref().and_then(super::ShapeLook::quarter_turns),
Some(1)
);
}
#[test]
fn inherits_group_fill_across_nested_groups_and_preserves_own_fills() {
let pt = 12_700_i64;
let group = anchor(&format!(
concat!(
r#"<wp:anchor><wp:extent cx="{w}" cy="{h}"/><a:graphic><a:graphicData>"#,
r#"<wpg:wgp><wpg:grpSpPr><a:xfrm>"#,
r#"<a:off x="0" y="0"/><a:ext cx="{w}" cy="{h}"/>"#,
r#"<a:chOff x="0" y="0"/><a:chExt cx="{w}" cy="{h}"/>"#,
r#"</a:xfrm><a:solidFill><a:srgbClr val="22AA55"/></a:solidFill></wpg:grpSpPr>"#,
r#"<wpg:grpSp><wpg:grpSpPr><a:xfrm>"#,
r#"<a:off x="0" y="0"/><a:ext cx="{w}" cy="{h}"/>"#,
r#"<a:chOff x="0" y="0"/><a:chExt cx="{w}" cy="{h}"/>"#,
r#"</a:xfrm></wpg:grpSpPr>"#,
r#"<wps:wsp><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="{cw}" cy="{ch}"/></a:xfrm>"#,
r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:grpFill/></wps:spPr></wps:wsp>"#,
r#"<wps:wsp><wps:spPr><a:xfrm><a:off x="{cw}" y="0"/><a:ext cx="{cw}" cy="{ch}"/></a:xfrm>"#,
r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val="CC3333"/></a:solidFill></wps:spPr></wps:wsp>"#,
r#"</wpg:grpSp></wpg:wgp></a:graphicData></a:graphic></wp:anchor>"#,
),
w = 200 * pt,
h = 50 * pt,
cw = 80 * pt,
ch = 50 * pt,
));
assert_eq!(group.parts.len(), 2);
let theme = f_office_drawingml::theme::ShapeTheme::default();
assert_eq!(
group.parts[0].2.look.as_ref().and_then(|l| l.fill(&theme)),
Some((
f_office_paint::Rgb {
r: 0x22,
g: 0xAA,
b: 0x55
},
f_office_paint::Opacity::FULL
))
);
assert_eq!(
group.parts[1].2.look.as_ref().and_then(|l| l.fill(&theme)),
Some((
f_office_paint::Rgb {
r: 0xCC,
g: 0x33,
b: 0x33
},
f_office_paint::Opacity::FULL
))
);
}
}