mod group;
use std::rc::Rc;
use f_office_drawingml::color::on_white;
use f_office_drawingml::custom::{CustomGeometry, LiteralPath, LiteralStep};
use f_office_drawingml::shape::{Geometry, ShapeLook, quarter_turns};
use f_office_fonts::FamilyName;
use f_office_paint::{Opacity, Rgb};
use f_office_units::scale::{FULL_TURN, QUARTER_TURN};
use f_office_units::{Edges, Length, div_round_i128};
use f_office_vml::css::{self, Style};
use f_office_vml::path as vml_path;
use f_office_vml::shape_type::{self, COORDINATES, TextRect};
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};
use crate::body::{Content, InlineDrawing, read_story};
use crate::enumerations::style_place;
use crate::floating::{
Floating, InsetEdge, PageArea, Position, Relative, TextFlow, TextPath, Wrap, WrapSides,
};
use crate::ns::{self, O, R, V, W, W10};
use crate::params::{VML_ARC_SIZE, VML_STROKE_WEIGHT, VML_TEXT_BOX_INSETS, VML_WRAP_DISTANCE};
use crate::picture::{Picture, VML_IMAGE, any_turn, embedded_image, scale_to_original, turn};
use crate::props::Align;
use crate::reader::settings::{InlineVml, InlineVmlKind, VmlHolder};
use crate::reader::{PartReader, attribute};
use crate::warnings::{Drawing, Feature, ReadAs, Reason};
pub(crate) fn read(reader: &mut PartReader, node: NodeId) -> Option<Content> {
let doc = reader.doc;
skip_unread(reader, node);
let mut shapes = doc.child_elements(node).filter(|child| {
doc.is(*child, V, "group") || SHAPES.iter().any(|name| doc.is(*child, V, name))
});
let shape = shapes.next()?;
for later in shapes {
let drawing = if image_data(doc, later).is_some() {
Drawing::Picture
} else {
Drawing::Shape
};
reader.drawing_skipped(drawing, Reason::Unsupported);
}
let style = Style::new(doc.attribute(shape, None, "style").unwrap_or(""));
let holder = if doc.is(node, W, "object") && doc.child(node, O, "OLEObject").is_some() {
VmlHolder::EmbeddedObject {
original: original_size(reader, node),
}
} else {
VmlHolder::Picture
};
if doc.is(shape, V, "group") {
return match reader.style_keyword(shape, &style, "position", POSITION) {
Some(CssPosition::Floating) => group::read_floating(reader, shape, &style)
.map(|floating| Content::Floating(Box::new(floating))),
Some(CssPosition::InLine) | None => group::read_inline(reader, shape, &style),
};
}
match reader.style_keyword(shape, &style, "position", POSITION) {
Some(CssPosition::Floating) => read_floating(reader, shape, &style)
.map(|floating| Content::Floating(Box::new(floating))),
Some(CssPosition::InLine) | None => read_inline(reader, shape, &style, holder)
.or_else(|| read_inline_shape(reader, shape, &style)),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CssPosition {
InLine,
Floating,
}
const POSITION: &Values<CssPosition> = &Values::new(&[
own("static", CssPosition::InLine),
own("absolute", CssPosition::Floating),
another("relative", CssPosition::InLine),
]);
fn read_inline(
reader: &mut PartReader,
shape: NodeId,
style: &Style,
holder: VmlHolder,
) -> Option<Content> {
let doc = reader.doc;
let data = image_data(doc, shape)?;
if !doc.is(shape, V, "shape") {
reader.drawing_skipped(Drawing::Picture, Reason::Unsupported);
return None;
}
let embed = embedded_image(reader, data, VML_IMAGE)?;
let (Some(width), Some(height)) = (size(style, "width"), size(style, "height")) else {
reader.drawing_skipped(Drawing::Picture, Reason::Unsupported);
return None;
};
if changes_colors(doc, data) {
reader.feature_not_supported(Feature::VmlPictureColors);
}
let text_box = doc.child(shape, V, "textbox");
if text_box.is_some_and(|text_box| ns::text_box_content(doc, text_box).is_some()) {
reader.feature_not_supported(Feature::VmlPictureTextBox);
}
let quarters = quarter_turns_of(reader, shape, style);
let mut picture = Picture {
drops: true,
turn: turn(quarters, [false; 2]),
scale_steps: reader.vml_sizes().picture_scale(holder),
..picture(reader, embed, data, width, height)
};
let (mut width, mut height) = (width, height);
if let (
VmlHolder::EmbeddedObject {
original: Some(original),
},
Some(steps),
) = (holder, reader.vml_sizes().preview_scale())
{
scale_to_original(&mut picture, (&mut width, &mut height), original, steps);
}
Some(Content::Object {
width,
height,
picture: Some(Box::new(picture)),
extent: None,
})
}
fn original_size(reader: &mut PartReader, node: NodeId) -> Option<(Length, Length)> {
Some((
reader.twips(node, "dxaOrig")?,
reader.twips(node, "dyaOrig")?,
))
}
fn image_data(doc: &Document, shape: NodeId) -> Option<NodeId> {
let (embed, (link_namespace, link)) = VML_IMAGE;
doc.child(shape, V, "imagedata").filter(|&data| {
doc.attribute(data, Some(R), embed).is_some()
|| doc.attribute(data, Some(link_namespace), link).is_some()
})
}
fn picture(
reader: &mut PartReader,
embed: &str,
data: NodeId,
width: Length,
height: Length,
) -> Picture {
Picture::new(embed, Edges::sized(width, height), crop(reader, data))
}
fn crop(reader: &mut PartReader, data: NodeId) -> Edges<i64> {
Edges::from(
["cropleft", "croptop", "cropright", "cropbottom"].map(|name| {
reader
.or_missing_in(data, (None, name), css::fraction)
.unwrap_or(0)
}),
)
}
fn size(style: &Style, name: &str) -> Option<Length> {
style
.get(name)
.and_then(css::length)
.filter(|length| length.units() >= 0)
}
const SHAPES: [&str; 8] = [
"shape",
"rect",
"roundrect",
"oval",
"line",
"polyline",
"arc",
"curve",
];
const STRAIGHT_CONNECTOR: &str = "_x0000_t32";
fn is_line(doc: &Document, shape: NodeId) -> bool {
doc.is(shape, V, "line")
|| doc
.attribute(shape, None, "type")
.map(|t| t.trim_start_matches('#'))
== Some(STRAIGHT_CONNECTOR)
}
fn read_inline_shape(reader: &mut PartReader, shape: NodeId, style: &Style) -> Option<Content> {
let doc = reader.doc;
if image_data(doc, shape).is_some() {
return None;
}
let (Some(width), Some(height)) = (size(style, "width"), size(style, "height")) else {
reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
return None;
};
let anchor_locked = doc.child(shape, W10, "anchorlock").is_some();
let rule = doc.attribute(shape, Some(O), "hr") == Some("t");
let kind = if rule {
InlineVmlKind::HorizontalRule
} else if outlined(doc, shape) {
InlineVmlKind::Outlined
} else {
InlineVmlKind::Plain
};
let InlineVml {
drawn: (drawn_width, drawn_height),
room: (width, height),
} = reader.vml_sizes().inline((width, height), kind);
let mut floating = Floating {
width: drawn_width,
height: drawn_height,
look: Some(look(reader, shape, (drawn_width, drawn_height))),
..Floating::in_part(reader.part())
};
if let Some(flip) = reader.style_keyword(shape, style, "flip", FLIP) {
floating.look = floating.look.take().map(|look| look.flipped(flip));
}
let quarters = quarter_turns_of(reader, shape, style);
turn_drawing(&mut floating, quarters);
text_box(reader, shape, &mut floating, quarters != 0);
Some(Content::Drawing(Rc::new(InlineDrawing {
width,
height,
left: Length::ZERO,
top: Length::ZERO,
shape: floating,
drops: !rule,
anchor_locked,
extent: None,
})))
}
pub(super) fn cell_layout(
doc: &f_office_xml::Document,
node: NodeId,
) -> crate::floating::CellLayout {
let allowed = !matches!(
doc.attribute(node, Some(O), "allowincell"),
Some("f" | "F" | "false" | "FALSE" | "0")
);
crate::floating::CellLayout::of(allowed)
}
const LAYOUT_FLOW: &Values<TextFlow> = &Values::new(&[
own("horizontal", TextFlow::Across),
own("horizontal-ideographic", TextFlow::Across),
own("vertical", TextFlow::Turned),
own("vertical-ideographic", TextFlow::Turned),
]);
fn text_box(reader: &mut PartReader, shape: NodeId, floating: &mut Floating, rotated: bool) {
let doc = reader.doc;
if let Some(text_box) = doc.child(shape, V, "textbox") {
floating.insets = insets(reader, text_box);
floating.inset_edge = InsetEdge::Vml;
floating.text_rect = text_rect(reader, shape);
if let Some(content) = ns::text_box_content(doc, text_box) {
floating.blocks = read_story(reader, content);
let style = Style::new(doc.attribute(text_box, None, "style").unwrap_or(""));
let flow = reader.style_keyword(text_box, &style, "layout-flow", LAYOUT_FLOW);
if flow == Some(TextFlow::Turned) || rotated {
reader.feature_not_supported(Feature::TurnedTextBox);
}
}
}
}
fn text_rect(reader: &mut PartReader, shape: NodeId) -> Option<TextRect> {
let doc = reader.doc;
if !doc.is(shape, V, "shape") {
return None;
}
let id = doc
.attribute(shape, None, "type")?
.trim()
.trim_start_matches('#');
let kind = reader.shape_type(id)?;
let rect = path_attribute(doc, [shape, kind], "textboxrect")?;
let evaluated = evaluate_text_rect(doc, shape, kind, rect);
if evaluated.is_none() {
reader.feature_not_supported(Feature::VmlGeometry);
}
evaluated
}
fn path_attribute<'d>(doc: &'d Document, nodes: [NodeId; 2], name: &str) -> Option<&'d str> {
nodes.into_iter().find_map(|node| {
doc.child(node, V, "path")
.and_then(|path| doc.attribute(path, None, name))
})
}
fn pair(text: &str) -> Option<(i64, i64)> {
match shape_type::numbers(text)?.as_slice() {
[Some(across), Some(down)] => Some((*across, *down)),
_ => None,
}
}
fn adjust_values(doc: &Document, shape: NodeId, kind: NodeId) -> Option<Vec<i64>> {
let adjust_of = |node: NodeId| match doc.attribute(node, None, "adj") {
None => Some(Vec::new()),
Some(text) => shape_type::numbers(text),
};
let mut adjust: Vec<i64> = adjust_of(kind)?
.into_iter()
.map(Option::unwrap_or_default)
.collect();
for (index, value) in adjust_of(shape)?.into_iter().enumerate() {
if let Some(value) = value {
if adjust.len() <= index {
adjust.resize(index + 1, 0);
}
*adjust.get_mut(index)? = value;
}
}
Some(adjust)
}
fn equations(doc: &Document, nodes: [NodeId; 2]) -> Vec<&str> {
nodes
.into_iter()
.find_map(|node| doc.child(node, V, "formulas"))
.map_or_else(Vec::new, |formulas| {
doc.child_elements(formulas)
.filter(|f| doc.is(*f, V, "f"))
.filter_map(|f| doc.attribute(f, None, "eqn"))
.collect()
})
}
fn evaluate_text_rect(doc: &Document, shape: NodeId, kind: NodeId, rect: &str) -> Option<TextRect> {
let adjust = adjust_values(doc, shape, kind)?;
let size = match [shape, kind]
.into_iter()
.find_map(|node| doc.attribute(node, None, "coordsize"))
{
None => (shape_type::COORDINATES, shape_type::COORDINATES),
Some(text) => pair(text)?,
};
let values = shape_type::formulas(&equations(doc, [shape, kind]), &adjust, size)?;
let preset = doc
.attribute(kind, Some(O), "spt")
.and_then(|spt| spt.trim().parse().ok());
let edges = shape_type::text_rect(preset, rect, &values, &adjust, size)?;
let limo = match path_attribute(doc, [shape, kind], "limo") {
None => None,
Some(text) => Some(pair(text)?),
};
Some(TextRect { edges, size, limo })
}
const UNREAD: [(&str, Drawing); 1] = [("image", Drawing::Picture)];
fn skip_unread(reader: &mut PartReader, node: NodeId) {
let doc = reader.doc;
for child in doc.child_elements(node) {
if let Some((_, drawing)) = UNREAD.iter().find(|(name, _)| doc.is(child, V, name)) {
reader.drawing_skipped(*drawing, Reason::Unsupported);
}
}
}
fn floating_rotation(
reader: &mut PartReader,
shape: NodeId,
style: &Style,
floating: &Floating,
) -> i64 {
if floating.text_path.is_some() {
return 0;
}
rotation_of(reader, shape, style)
}
fn rotation_of(reader: &mut PartReader, shape: NodeId, style: &Style) -> i64 {
reader
.style_value(shape, style, "rotation", css::angle)
.unwrap_or(0)
.rem_euclid(FULL_TURN)
}
fn vml_to_drawingml_rotation(rotation: i64, css_flip: [bool; 2]) -> i64 {
let signed = if css_flip[0] ^ css_flip[1] {
-rotation
} else {
rotation
};
signed.rem_euclid(FULL_TURN)
}
fn apply_floating_rotation(
reader: &mut PartReader,
floating: &mut Floating,
raw_rotation: i64,
css_flip: [bool; 2],
picture_flip: [bool; 2],
) {
let dml_rot = vml_to_drawingml_rotation(raw_rotation, css_flip);
floating.look = floating.look.take().map(|look| look.turned(dml_rot));
let Some(picture) = &mut floating.picture else {
return;
};
if let Some(quarters) = quarter_turns(dml_rot) {
picture.turn = turn(quarters, picture_flip);
} else if picture.crop == Edges::default()
&& let Some(turned) = any_turn(dml_rot, picture_flip)
{
picture.turn = Some(turned);
} else {
reader.feature_not_supported(Feature::VmlRotation);
picture.turn = turn(0, picture_flip);
}
}
fn drawn(
reader: &mut PartReader,
shape: NodeId,
style: &Style,
box_size: (Length, Length),
) -> (Option<ShapeLook>, Option<TextPath>) {
let path = if reader.vml_sizes().reads_text_paths() {
text_path(reader, shape, style)
} else {
None
};
match path {
Some(path) => (None, Some(path)),
None => (Some(look(reader, shape, box_size)), None),
}
}
fn text_path(reader: &mut PartReader, shape: NodeId, style: &Style) -> Option<TextPath> {
let doc = reader.doc;
let kind = doc.attribute(shape, None, "type")?.trim_start_matches('#');
if kind != "_x0000_t136" {
return None;
}
let path = doc.child(shape, V, "textpath")?;
let string = doc.attribute(path, None, "string")?;
let path_style = Style::new(doc.attribute(path, None, "style").unwrap_or(""));
let face = path_style
.get("font-family")?
.trim()
.trim_matches(['"', '\'']);
let color = reader
.or_missing_in(shape, (None, "fillcolor"), css::color)
.unwrap_or(Rgb::WHITE);
let opacity = doc
.child(shape, V, "fill")
.and_then(|fill| reader.or_missing_in(fill, (None, "opacity"), css::fraction))
.map_or(Opacity::FULL, Opacity::clamped);
let rotation = reader
.style_value(shape, style, "rotation", css::angle)
.unwrap_or(0);
Some(TextPath {
string: string.to_owned(),
face: FamilyName::new(face),
color: on_white(color, opacity),
rotation,
})
}
fn read_floating(reader: &mut PartReader, shape: NodeId, style: &Style) -> Option<Floating> {
let doc = reader.doc;
let embed = match image_data(doc, shape) {
None => None,
Some(data) if changes_colors(doc, data) => {
reader.drawing_skipped(Drawing::Picture, Reason::Unsupported);
return None;
}
Some(data) => Some((embedded_image(reader, data, VML_IMAGE)?, data)),
};
let (width, height) = (size(style, "width"), size(style, "height"));
let (box_width, box_height) = (
width.unwrap_or(Length::ZERO),
height.unwrap_or(Length::ZERO),
);
let point_shape = doc.is(shape, V, "polyline") || doc.is(shape, V, "curve");
let (look, text_path) = if embed.is_some() || point_shape {
(None, None)
} else {
drawn(reader, shape, style, (box_width, box_height))
};
let z_index = reader.style_value(shape, style, "z-index", css::number);
let mut floating = Floating {
h: across(reader, shape, style),
v: position(reader, shape, style, &DOWN),
width: box_width,
height: box_height,
behind: z_index.is_some_and(|z| z < 0),
cell_layout: cell_layout(doc, shape),
stack: z_index.map_or(0, i64::unsigned_abs),
look,
picture: embed.map(|(embed, data)| picture(reader, embed, data, box_width, box_height)),
text_path,
..Floating::in_part(reader.part())
};
if !apply_floating_geometry(reader, shape, style, (width, height), &mut floating) {
return None;
}
let css_flip = if doc.is(shape, V, "line") {
[false; 2]
} else if let Some(look) = &floating.look {
look.flips()
} else {
reader
.style_keyword(shape, style, "flip", FLIP)
.unwrap_or([false; 2])
};
let rotation = floating_rotation(reader, shape, style, &floating);
apply_floating_rotation(reader, &mut floating, rotation, css_flip, css_flip);
floating.wrap = wrap(reader, shape, style);
text_box(reader, shape, &mut floating, rotation != 0);
Some(floating)
}
fn apply_floating_geometry(
reader: &mut PartReader,
shape: NodeId,
style: &Style,
(width, height): (Option<Length>, Option<Length>),
floating: &mut Floating,
) -> bool {
let doc = reader.doc;
if doc.is(shape, V, "line") {
let Some(((x0, y0), (x1, y1))) =
css_point(doc, shape, "from").zip(css_point(doc, shape, "to"))
else {
return false;
};
floating.h.offset = x0.min(x1);
floating.v.offset = y0.min(y1);
floating.width = x0.max(x1) - x0.min(x1);
floating.height = y0.max(y1) - y0.min(y1);
let flip = [x1 < x0, y1 < y0];
floating.look = floating.look.take().map(|look| look.flipped(flip));
return true;
}
if doc.is(shape, V, "polyline") || doc.is(shape, V, "curve") {
let Some(placed) = floating_point_shape(doc, shape) else {
reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
return false;
};
floating.h.offset += placed.left;
floating.v.offset += placed.top;
floating.width = placed.width;
floating.height = placed.height;
let flip = reader
.style_keyword(shape, style, "flip", FLIP)
.unwrap_or([false; 2]);
floating.look =
Some(look_with_geometry(reader, shape, None, placed.geometry).flipped(flip));
return true;
}
if width.is_none() || height.is_none() {
let drawing = if floating.picture.is_some() {
Drawing::Picture
} else {
Drawing::Shape
};
reader.drawing_skipped(drawing, Reason::Unsupported);
return false;
}
if let Some(flip) = reader.style_keyword(shape, style, "flip", FLIP) {
floating.look = floating.look.take().map(|look| look.flipped(flip));
}
true
}
const FLIP: &Values<[bool; 2]> = &Values::new(&[
own("x", [true, false]),
own("y", [false, true]),
own("xy", [true, true]),
own("yx", [true, true]),
own("x y", [true, true]),
]);
fn quarter_turns_of(reader: &mut PartReader, shape: NodeId, style: &Style) -> i64 {
let rotation = reader
.style_value(shape, style, "rotation", css::angle)
.unwrap_or(0);
quarter_turns(rotation).unwrap_or_else(|| {
reader.feature_not_supported(Feature::VmlRotation);
0
})
}
fn turn_drawing(floating: &mut Floating, quarters: i64) {
floating.look = floating
.look
.take()
.map(|look| look.turned(quarters * QUARTER_TURN));
if let Some(picture) = &mut floating.picture {
picture.turn = turn(quarters, [false; 2]);
}
}
fn changes_colors(doc: &Document, data: NodeId) -> bool {
let on = |name| matches!(doc.attribute(data, None, name), Some("t" | "true" | "1"));
doc.attribute(data, None, "gain").is_some()
|| doc.attribute(data, None, "blacklevel").is_some()
|| on("grayscale")
|| on("bilevel")
}
struct Axis {
relative: (&'static str, &'static Values<Relative>),
text: Relative,
align: (&'static str, &'static Values<Option<Align>>),
offsets: [&'static str; 2],
}
const ACROSS: Axis = Axis {
relative: ("mso-position-horizontal-relative", RELATIVE_ACROSS),
text: TEXT_ACROSS,
align: ("mso-position-horizontal", ALIGN_ACROSS),
offsets: ["margin-left", "left"],
};
const DOWN: Axis = Axis {
relative: ("mso-position-vertical-relative", RELATIVE_DOWN),
text: TEXT_DOWN,
align: ("mso-position-vertical", ALIGN_DOWN),
offsets: ["margin-top", "top"],
};
const TEXT: &str = "text";
const TEXT_ACROSS: Relative = Relative::Column;
const TEXT_DOWN: Relative = Relative::Paragraph;
const RELATIVE_ACROSS: &Values<Relative> = &Values::new(&[
own("margin", Relative::Area(PageArea::Margin)),
own("page", Relative::Area(PageArea::Page)),
own(TEXT, TEXT_ACROSS),
another("char", Relative::Area(PageArea::Margin)),
own("left-margin-area", Relative::Area(PageArea::StartMargin)),
own("right-margin-area", Relative::Area(PageArea::EndMargin)),
another("inner-margin-area", Relative::Area(PageArea::StartMargin)),
another("outer-margin-area", Relative::Area(PageArea::EndMargin)),
]);
const RELATIVE_DOWN: &Values<Relative> = &Values::new(&[
own("margin", Relative::Area(PageArea::Margin)),
own("page", Relative::Area(PageArea::Page)),
own(TEXT, TEXT_DOWN),
another("line", Relative::Paragraph),
own("top-margin-area", Relative::Area(PageArea::StartMargin)),
own("bottom-margin-area", Relative::Area(PageArea::EndMargin)),
another("inner-margin-area", Relative::Area(PageArea::StartMargin)),
another("outer-margin-area", Relative::Area(PageArea::EndMargin)),
]);
const ALIGN_ACROSS: &Values<Option<Align>> = &Values::new(&[
own("absolute", None),
own("left", Some(Align::Start)),
own("center", Some(Align::Center)),
own("right", Some(Align::End)),
own("inside", Some(Align::Inside)),
own("outside", Some(Align::Outside)),
]);
const ALIGN_DOWN: &Values<Option<Align>> = &Values::new(&[
own("absolute", None),
own("top", Some(Align::Start)),
own("center", Some(Align::Center)),
own("bottom", Some(Align::End)),
another("inside", Some(Align::Start)),
another("outside", Some(Align::End)),
]);
fn position(reader: &mut PartReader, shape: NodeId, style: &Style, axis: &Axis) -> Position {
let (property, table) = axis.relative;
let from = reader
.style_keyword(shape, style, property, table)
.unwrap_or(axis.text);
let (property, table) = axis.align;
let align = reader
.style_keyword(shape, style, property, table)
.flatten();
let offset = axis
.offsets
.iter()
.find_map(|name| reader.style_value(shape, style, name, css::length))
.unwrap_or(Length::ZERO);
Position {
from,
offset,
align,
share: None,
}
}
fn across(reader: &mut PartReader, shape: NodeId, style: &Style) -> Position {
let mut place = position(reader, shape, style, &ACROSS);
if place.from == TEXT_ACROSS {
place.from = Relative::Area(PageArea::Margin);
reader.note_text_column(shape);
}
place
}
pub(crate) fn warn_text_column(reader: &mut PartReader, shape: NodeId) {
reader.not_supported(shape, style_place(ACROSS.relative.0), TEXT);
}
pub(crate) fn warn_text_column_named(reader: &mut PartReader, element: f_office_warnings::Name) {
reader.not_supported_named(element, style_place(ACROSS.relative.0), TEXT);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum WrapType {
Square,
Beside,
TopAndBottom,
Off,
}
const WRAP_TYPE: &Values<WrapType> = &Values::new(&[
own("topAndBottom", WrapType::TopAndBottom),
own("square", WrapType::Square),
own("none", WrapType::Off),
own("tight", WrapType::Beside),
own("through", WrapType::Beside),
]);
const WRAP_SIDE: &Values<WrapSides> = &Values::new(&[
own("both", WrapSides::Both),
own("left", WrapSides::Left),
own("right", WrapSides::Right),
own("largest", WrapSides::Largest),
]);
fn wrap(reader: &mut PartReader, shape: NodeId, style: &Style) -> Option<Wrap> {
let element = reader.doc.child(shape, W10, "wrap")?;
let distance = |reader: &mut PartReader, side: &str, default: Length| {
let property = format!("mso-wrap-distance-{side}");
reader
.style_value(shape, style, &property, css::length)
.unwrap_or(default)
};
let beside = |reader: &mut PartReader, sides, polygon| Wrap::Beside {
distances: Edges {
left: distance(reader, "left", VML_WRAP_DISTANCE),
top: distance(reader, "top", Length::ZERO),
right: distance(reader, "right", VML_WRAP_DISTANCE),
bottom: distance(reader, "bottom", Length::ZERO),
},
sides,
polygon,
};
match reader.enumeration_in(element, (None, "type"), WRAP_TYPE)? {
WrapType::Square => {
let sides = reader.enumeration_in(element, (None, "side"), WRAP_SIDE);
Some(beside(reader, Some(sides.unwrap_or_default()), None))
}
WrapType::Beside => Some(beside(reader, None, Some(Edges::default()))),
WrapType::TopAndBottom => Some(Wrap::TopAndBottom {
above: distance(reader, "top", Length::ZERO),
below: distance(reader, "bottom", Length::ZERO),
}),
WrapType::Off => None,
}
}
fn insets(reader: &mut PartReader, text_box: NodeId) -> Edges<Length> {
let (side, top) = VML_TEXT_BOX_INSETS;
let defaults = [side, top, side, top];
let text = reader.doc.attribute(text_box, None, "inset").unwrap_or("");
let mut values = text.split(',').map(str::trim);
Edges::from(defaults.map(|default| match values.next() {
None | Some("") => default,
Some(value) => css::length(value).unwrap_or_else(|| {
reader.invalid(text_box, attribute("inset"), ReadAs::Missing);
default
}),
}))
}
fn on_unless_off(value: Option<&str>) -> bool {
!matches!(value, Some("f" | "false" | "0"))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FillType {
Solid,
}
const FILL_TYPE: &Values<FillType> = &Values::new(&[
own("solid", FillType::Solid),
another("gradient", FillType::Solid),
another("gradientRadial", FillType::Solid),
another("tile", FillType::Solid),
another("pattern", FillType::Solid),
another("frame", FillType::Solid),
]);
fn vml_geometry(
reader: &mut PartReader,
shape: NodeId,
kind: Option<NodeId>,
box_size: (Length, Length),
) -> Geometry {
let doc = reader.doc;
if is_line(doc, shape) {
return Geometry::Line;
}
if doc.is(shape, V, "rect") {
return Geometry::Rect;
}
if doc.is(shape, V, "oval") {
return Geometry::Ellipse;
}
if doc.is(shape, V, "roundrect") {
let arc = reader
.or_missing_in(shape, (None, "arcsize"), css::fraction)
.unwrap_or(VML_ARC_SIZE);
return Geometry::RoundRect(arc / 2);
}
if doc.is(shape, V, "arc") {
if let Some(custom) = arc_geometry(doc, shape) {
return Geometry::Custom(custom);
}
reader.feature_not_supported(Feature::VmlGeometry);
return Geometry::Rect;
}
shape_type_geometry(reader, shape, kind, box_size)
}
fn arc_geometry(doc: &Document, shape: NodeId) -> Option<CustomGeometry> {
let (start_fd, sweep_fd) = shape_type::arc_sweep(
doc.attribute(shape, None, "startangle"),
doc.attribute(shape, None, "endangle"),
)?;
let half = COORDINATES / 2;
let steps = vec![LiteralStep::AngleEllipse {
center: [half, half],
radii: [half, half],
start_fd,
sweep_fd,
move_to_start: true,
}];
CustomGeometry::from_literal_paths(vec![LiteralPath {
size: [COORDINATES, COORDINATES],
steps,
filled: true,
stroked: true,
}])
}
fn css_point(doc: &Document, shape: NodeId, name: &str) -> Option<(Length, Length)> {
let text = doc.attribute(shape, None, name).unwrap_or("0,0");
let (x, y) = text.split_once(',').unwrap_or((text, "0"));
Some((css::length(x.trim())?, css::length(y.trim())?))
}
pub(super) struct PlacedGeometry {
pub(super) left: Length,
pub(super) top: Length,
pub(super) width: Length,
pub(super) height: Length,
pub(super) geometry: Geometry,
}
struct NormalizedPoints {
left: Length,
top: Length,
width: Length,
height: Length,
points: Vec<[i64; 2]>,
}
fn floating_point_shape(doc: &Document, shape: NodeId) -> Option<PlacedGeometry> {
if doc.is(shape, V, "polyline") {
let raw = doc.attribute(shape, None, "points")?;
let mut tokens = raw
.split(|c: char| c.is_ascii_whitespace() || c == ',')
.filter(|t| !t.is_empty());
let mut pts = Vec::new();
while let Some(x) = tokens.next() {
let y = tokens.next()?;
pts.push((css::length(x)?, css::length(y)?));
}
return polyline_geometry(&pts);
}
let from = css_point(doc, shape, "from")?;
let to = css_point(doc, shape, "to")?;
let c1 = doc
.attribute(shape, None, "control1")
.map_or(Some(from), |_| css_point(doc, shape, "control1"))?;
let c2 = doc
.attribute(shape, None, "control2")
.map_or(Some(to), |_| css_point(doc, shape, "control2"))?;
curve_geometry([from, c1, c2, to])
}
fn normalize_points(pts: &[(Length, Length)]) -> Option<NormalizedPoints> {
let &(first_x, first_y) = pts.first()?;
let (mut min_x, mut max_x) = (first_x, first_x);
let (mut min_y, mut max_y) = (first_y, first_y);
for &(x, y) in pts.iter().skip(1) {
min_x = min_x.min(x);
max_x = max_x.max(x);
min_y = min_y.min(y);
max_y = max_y.max(y);
}
let width = max_x - min_x;
let height = max_y - min_y;
let scale_coord = |value: Length, min: Length, span: Length| -> Option<i64> {
if span.units() <= 0 {
return Some(0);
}
let scaled = div_round_i128(
i128::from((value - min).units()) * i128::from(COORDINATES),
i128::from(span.units()),
);
i64::try_from(scaled).ok()
};
let points = pts
.iter()
.map(|&(x, y)| {
Some([
scale_coord(x, min_x, width)?,
scale_coord(y, min_y, height)?,
])
})
.collect::<Option<Vec<_>>>()?;
Some(NormalizedPoints {
left: min_x,
top: min_y,
width,
height,
points,
})
}
pub(super) fn polyline_geometry(pts: &[(Length, Length)]) -> Option<PlacedGeometry> {
let norm = normalize_points(pts)?;
let (&first, rest) = norm.points.split_first()?;
if rest.is_empty() {
return None;
}
let mut steps = Vec::with_capacity(norm.points.len());
steps.push(LiteralStep::Move(first));
steps.extend(rest.iter().copied().map(LiteralStep::Line));
let custom = CustomGeometry::from_literal_paths(vec![LiteralPath {
size: [COORDINATES, COORDINATES],
steps,
filled: true,
stroked: true,
}])?;
Some(PlacedGeometry {
left: norm.left,
top: norm.top,
width: norm.width,
height: norm.height,
geometry: Geometry::Custom(custom),
})
}
pub(super) fn curve_geometry(pts: [(Length, Length); 4]) -> Option<PlacedGeometry> {
let norm = normalize_points(&pts)?;
let [from, c1, c2, to] = <[_; 4]>::try_from(norm.points).ok()?;
let custom = CustomGeometry::from_literal_paths(vec![LiteralPath {
size: [COORDINATES, COORDINATES],
steps: vec![LiteralStep::Move(from), LiteralStep::Cubic([c1, c2, to])],
filled: true,
stroked: true,
}])?;
Some(PlacedGeometry {
left: norm.left,
top: norm.top,
width: norm.width,
height: norm.height,
geometry: Geometry::Custom(custom),
})
}
fn shape_type_geometry(
reader: &mut PartReader,
shape: NodeId,
kind: Option<NodeId>,
box_size: (Length, Length),
) -> Geometry {
let doc = reader.doc;
let type_id = doc
.attribute(shape, None, "type")
.map(|t| t.trim().trim_start_matches('#'));
if vml_path_string(doc, shape).is_some() {
if let Some(custom) = custom_path_geometry(doc, shape, kind, box_size) {
return Geometry::Custom(custom);
}
reader.feature_not_supported(Feature::VmlGeometry);
return Geometry::Rect;
}
if matches!(type_id, None | Some("_x0000_t1" | "_x0000_t202")) {
return Geometry::Rect;
}
let has_text_path = doc.child(shape, V, "textpath").is_some()
|| kind.is_some_and(|k| doc.child(k, V, "textpath").is_some());
if !has_text_path && let Some(custom) = custom_path_geometry(doc, shape, kind, box_size) {
return Geometry::Custom(custom);
}
let geometry = match type_id {
Some("_x0000_t2") => Geometry::RoundRect(VML_ARC_SIZE / 2),
Some("_x0000_t3") => Geometry::Ellipse,
_ => Geometry::Other,
};
if matches!(geometry, Geometry::Other) {
reader.feature_not_supported(Feature::VmlGeometry);
}
geometry
}
fn look(reader: &mut PartReader, shape: NodeId, box_size: (Length, Length)) -> ShapeLook {
let doc = reader.doc;
let kind = doc
.attribute(shape, None, "type")
.and_then(|id| reader.shape_type(id.trim().trim_start_matches('#')));
let geometry = vml_geometry(reader, shape, kind, box_size);
look_with_geometry(reader, shape, kind, geometry)
}
pub(super) fn look_with_geometry(
reader: &mut PartReader,
shape: NodeId,
kind: Option<NodeId>,
geometry: Geometry,
) -> ShapeLook {
let doc = reader.doc;
let nodes = [shape, kind.unwrap_or(shape)];
let attribute = |name: &str| doc.attribute(shape, None, name);
let inherited =
|name: &str| attribute(name).or_else(|| kind.and_then(|k| doc.attribute(k, None, name)));
let fill_child = doc.child(shape, V, "fill");
let fill_on = on_unless_off(inherited("filled"))
&& on_unless_off(fill_child.and_then(|f| doc.attribute(f, None, "on")))
&& on_unless_off(path_attribute(doc, nodes, "fillok"));
let fill = fill_on.then(|| {
let fill_type =
fill_child.and_then(|fill| reader.enumeration_in(fill, (None, "type"), FILL_TYPE));
match fill_type {
Some(FillType::Solid) | None => reader
.or_missing_in(shape, (None, "fillcolor"), css::color)
.unwrap_or(Rgb::WHITE),
}
});
let stroke = doc.child(shape, V, "stroke");
let stroke_attribute = |name: &str| stroke.and_then(|s| doc.attribute(s, None, name));
let is_stroked = outlined(doc, shape)
&& on_unless_off(path_attribute(doc, nodes, "strokeok"))
&& (attribute("stroked").is_some()
|| stroke_attribute("on").is_some()
|| on_unless_off(kind.and_then(|k| doc.attribute(k, None, "stroked"))));
let line = is_stroked.then(|| {
let color = stroke
.and_then(|stroke| reader.or_missing_in(stroke, (None, "color"), css::color))
.or_else(|| reader.or_missing_in(shape, (None, "strokecolor"), css::color))
.unwrap_or(Rgb::BLACK);
let width = stroke_attribute("weight")
.or_else(|| attribute("strokeweight"))
.and_then(css::length)
.unwrap_or(VML_STROKE_WEIGHT);
(color, width)
});
ShapeLook::plain(geometry, fill, line)
}
fn vml_path_string(doc: &Document, shape: NodeId) -> Option<&str> {
doc.attribute(shape, None, "path").or_else(|| {
doc.child(shape, V, "path")
.and_then(|node| doc.attribute(node, None, "v"))
})
}
fn custom_path_geometry(
doc: &Document,
shape: NodeId,
kind: Option<NodeId>,
box_size: (Length, Length),
) -> Option<CustomGeometry> {
let nodes = [shape, kind.unwrap_or(shape)];
let text =
vml_path_string(doc, shape).or_else(|| kind.and_then(|k| vml_path_string(doc, k)))?;
let origin = nodes
.into_iter()
.find_map(|node| doc.attribute(node, None, "coordorigin"))
.map_or(Some((0, 0)), pair)?;
let (cw, ch) = nodes
.into_iter()
.find_map(|node| doc.attribute(node, None, "coordsize"))
.map_or(Some((COORDINATES, COORDINATES)), pair)?;
let (values, adjust) = evaluate_shape_formulas(doc, shape, kind, (cw, ch))?;
let parsed = vml_path::parse_with(text, origin, &values, &adjust)?;
let limo = path_attribute(doc, nodes, "limo").and_then(pair);
let stretch = LimoStretch::new((cw, ch), limo, box_size);
let paths = parsed
.into_iter()
.map(|sub| LiteralPath {
size: stretch.size,
steps: sub
.steps
.into_iter()
.map(|step| lower_vml_step(step, &stretch))
.collect(),
filled: sub.filled,
stroked: sub.stroked,
})
.collect();
CustomGeometry::from_literal_paths(paths)
}
fn evaluate_shape_formulas(
doc: &Document,
shape: NodeId,
kind: Option<NodeId>,
size: (i64, i64),
) -> Option<(Vec<i64>, Vec<i64>)> {
let Some(kind) = kind else {
let eqs = equations(doc, [shape, shape]);
if eqs.is_empty() && doc.attribute(shape, None, "adj").is_none() {
return Some((Vec::new(), Vec::new()));
}
let adjust = adjust_values(doc, shape, shape)?;
let values = shape_type::formulas(&eqs, &adjust, size)?;
return Some((values, adjust));
};
let adjust = adjust_values(doc, shape, kind)?;
let eqs = equations(doc, [shape, kind]);
let values = shape_type::formulas(&eqs, &adjust, size)?;
Some((values, adjust))
}
struct LimoStretch {
size: [i64; 2],
orig: [i64; 2],
limo_x: Option<i64>,
limo_y: Option<i64>,
}
impl LimoStretch {
fn new((cw, ch): (i64, i64), limo: Option<(i64, i64)>, (w, h): (Length, Length)) -> Self {
let plain = Self {
size: [cw, ch],
orig: [cw, ch],
limo_x: None,
limo_y: None,
};
let Some((lx, ly)) = limo else {
return plain;
};
if cw <= 0 || ch <= 0 || w.units() <= 0 || h.units() <= 0 {
return plain;
}
let wu = i128::from(w.units());
let hu = i128::from(h.units());
match (wu * i128::from(ch)).cmp(&(hu * i128::from(cw))) {
std::cmp::Ordering::Greater => {
let Some(sw) = i64::try_from(div_round_i128(i128::from(ch) * wu, hu))
.ok()
.filter(|&v| v > 0)
else {
return plain;
};
Self {
size: [sw, ch],
orig: [cw, ch],
limo_x: Some(lx),
limo_y: None,
}
}
std::cmp::Ordering::Less => {
let Some(sh) = i64::try_from(div_round_i128(i128::from(cw) * hu, wu))
.ok()
.filter(|&v| v > 0)
else {
return plain;
};
Self {
size: [cw, sh],
orig: [cw, ch],
limo_x: None,
limo_y: Some(ly),
}
}
std::cmp::Ordering::Equal => plain,
}
}
fn point(&self, [x, y]: [i64; 2]) -> [i64; 2] {
let sx = match self.limo_x {
Some(lx) if x > lx => self.size[0].saturating_sub(self.orig[0].saturating_sub(x)),
_ => x,
};
let sy = match self.limo_y {
Some(ly) if y > ly => self.size[1].saturating_sub(self.orig[1].saturating_sub(y)),
_ => y,
};
[sx, sy]
}
}
fn lower_vml_step(step: vml_path::Step, stretch: &LimoStretch) -> LiteralStep {
match step {
vml_path::Step::Move(p) => LiteralStep::Move(stretch.point(p)),
vml_path::Step::Line(p) => LiteralStep::Line(stretch.point(p)),
vml_path::Step::Cubic([c1, c2, p]) => {
LiteralStep::Cubic([stretch.point(c1), stretch.point(c2), stretch.point(p)])
}
vml_path::Step::QuadX(p) => LiteralStep::QuadX(stretch.point(p)),
vml_path::Step::QuadY(p) => LiteralStep::QuadY(stretch.point(p)),
vml_path::Step::BoxArc {
bounds: [l, t, r, b],
start,
end,
clockwise,
move_to_start,
} => {
let [nl, nt] = stretch.point([l, t]);
let [nr, nb] = stretch.point([r, b]);
LiteralStep::BoxArc {
bounds: [nl, nt, nr, nb],
start: stretch.point(start),
end: stretch.point(end),
clockwise,
move_to_start,
}
}
vml_path::Step::AngleEllipse {
center: [cx, cy],
radii: [rx, ry],
start_fd,
sweep_fd,
move_to_start,
} => {
let [nl, nt] = stretch.point([cx - rx, cy - ry]);
let [nr, nb] = stretch.point([cx + rx, cy + ry]);
LiteralStep::AngleEllipse {
center: [i64::midpoint(nl, nr), i64::midpoint(nt, nb)],
radii: [(nr - nl).abs() / 2, (nb - nt).abs() / 2],
start_fd,
sweep_fd,
move_to_start,
}
}
vml_path::Step::Close => LiteralStep::Close,
}
}
fn outlined(doc: &Document, shape: NodeId) -> bool {
let stroke_on = doc
.child(shape, V, "stroke")
.and_then(|stroke| doc.attribute(stroke, None, "on"));
on_unless_off(doc.attribute(shape, None, "stroked")) && on_unless_off(stroke_on)
}
#[cfg(test)]
mod tests;