use std::rc::Rc;
use f_office_drawingml::shape::turned_clockwise;
use f_office_units::measure::decimal_thousandths;
use f_office_units::scale::THOUSANDTHS;
use f_office_units::{Length, div_round_i128, lowest_terms};
use f_office_vml::css::{self, Style};
use f_office_xml::{Document, NodeId};
use super::{
DOWN, FLIP, SHAPES, UNREAD, across, apply_floating_rotation, changes_colors, curve_geometry,
drawn, floating_rotation, image_data, look, look_with_geometry, pair, picture,
polyline_geometry, position, rotation_of, size, text_box, wrap,
};
use crate::body::{Content, InlineDrawing};
use crate::floating::Floating;
use crate::ns::{V, W10};
use crate::params::VML_GROUP_COORDINATES;
use crate::picture::{VML_IMAGE, embedded_image};
use crate::reader::PartReader;
use crate::warnings::{Drawing, Feature, Reason};
pub(super) fn read_floating(
reader: &mut PartReader,
group: NodeId,
style: &Style,
) -> Option<Floating> {
let (Some(width), Some(height)) = (size(style, "width"), size(style, "height")) else {
reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
return None;
};
let z_index = reader.style_value(group, style, "z-index", css::number);
let mut floating = Floating {
h: across(reader, group, style),
v: position(reader, group, style, &DOWN),
width,
height,
behind: z_index.is_some_and(|z| z < 0),
stack: z_index.map_or(0, i64::unsigned_abs),
wrap: wrap(reader, group, style),
..Floating::in_part(reader.part())
};
let rotation = rotation_of(reader, group, style);
let Some(map) = GroupMap::root(reader, group, style, (width, height)) else {
reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
return None;
};
collect_parts(reader, group, map, &mut floating.parts);
apply_group_rotation(
reader,
&mut floating.parts,
[width.units(), height.units()],
rotation,
map.flip(),
);
Some(floating)
}
pub(super) fn read_inline(
reader: &mut PartReader,
group: NodeId,
style: &Style,
) -> Option<Content> {
let (Some(width), Some(height)) = (size(style, "width"), size(style, "height")) else {
reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
return None;
};
if rotation_of(reader, group, style) != 0 {
reader.feature_not_supported(Feature::VmlRotation);
}
let Some(map) = GroupMap::root(reader, group, style, (width, height)) else {
reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
return None;
};
let anchor_locked = reader.doc.child(group, W10, "anchorlock").is_some();
let mut floating = Floating {
width,
height,
..Floating::in_part(reader.part())
};
collect_parts(reader, group, map, &mut floating.parts);
Some(Content::Drawing(Rc::new(InlineDrawing {
width,
height,
left: Length::ZERO,
top: Length::ZERO,
shape: floating,
drops: true,
anchor_locked,
extent: None,
})))
}
fn apply_group_rotation(
reader: &mut PartReader,
parts: &mut [(Length, Length, Floating)],
center2: [i64; 2],
rotation: i64,
flip: [bool; 2],
) {
if rotation == 0 {
return;
}
if flip != [false; 2] {
reader.feature_not_supported(Feature::VmlRotation);
return;
}
for (left, top, part) in parts {
rotate_group_part(reader, (left, top), part, center2, rotation);
}
}
fn rotate_group_part(
reader: &mut PartReader,
(left, top): (&mut Length, &mut Length),
part: &mut Floating,
center2: [i64; 2],
rotation: i64,
) {
let Some((new_left, new_top)) = rotated_child_origin(*left, *top, part, center2, rotation)
else {
reader.feature_not_supported(Feature::VmlRotation);
return;
};
*left = new_left;
*top = new_top;
part.look = part.look.take().map(|look| look.rotated_by(rotation));
if let Some(pic) = &mut part.picture
&& !pic.compose_outer_rotation(rotation)
{
reader.feature_not_supported(Feature::VmlRotation);
}
if !part.blocks.is_empty() {
reader.feature_not_supported(Feature::TurnedTextBox);
}
}
fn rotated_child_origin(
left: Length,
top: Length,
part: &Floating,
center2: [i64; 2],
rotation: i64,
) -> Option<(Length, Length)> {
let cx2 = left
.units()
.checked_mul(2)?
.checked_add(part.width.units())?;
let cy2 = top
.units()
.checked_mul(2)?
.checked_add(part.height.units())?;
let [rx2, ry2] = turned_clockwise([cx2, cy2], center2, rotation)?;
let new_left = Length::from_units(rx2.checked_sub(part.width.units())?).div_round(2);
let new_top = Length::from_units(ry2.checked_sub(part.height.units())?).div_round(2);
Some((new_left, new_top))
}
#[derive(Clone, Copy, Debug)]
struct GroupAxis {
origin: i64,
coord_origin: i64,
coord_size: i64,
num: i128,
den: i128,
flip: bool,
}
impl GroupAxis {
fn new(len: Length, coord_origin: i64, coord_size: i64, flip: bool) -> Option<Self> {
if coord_size <= 0 {
return None;
}
let origin_t = coord_origin.checked_mul(THOUSANDTHS)?;
let size_t = coord_size.checked_mul(THOUSANDTHS)?;
let (num, den) = lowest_terms(i128::from(len.units()), i128::from(size_t));
Some(Self {
origin: 0,
coord_origin: origin_t,
coord_size: size_t,
num,
den,
flip,
})
}
fn span(self, len_t: i64) -> Option<i64> {
let scaled = i128::from(len_t).checked_mul(self.num)?;
i64::try_from(div_round_i128(scaled, self.den)).ok()
}
fn place(self, pos_t: i64, len_t: i64) -> Option<i64> {
let local = pos_t.checked_sub(self.coord_origin)?;
let shifted = if self.flip {
self.coord_size.checked_sub(local.checked_add(len_t)?)?
} else {
local
};
self.origin.checked_add(self.span(shifted)?)
}
fn point(self, pos_t: i64) -> Option<i64> {
let local = pos_t.checked_sub(self.coord_origin)?;
let shifted = if self.flip {
self.coord_size.checked_sub(local)?
} else {
local
};
self.origin.checked_add(self.span(shifted)?)
}
fn inner(
self,
(pos_t, len_t): (i64, i64),
(coord_origin, coord_size): (i64, i64),
flip: bool,
) -> Option<Self> {
if len_t < 0 || coord_size <= 0 {
return None;
}
let origin_t = coord_origin.checked_mul(THOUSANDTHS)?;
let size_t = coord_size.checked_mul(THOUSANDTHS)?;
let origin = self.place(pos_t, len_t)?;
let num = self.num.checked_mul(i128::from(len_t))?;
let den = self.den.checked_mul(i128::from(size_t))?;
let (num, den) = lowest_terms(num, den);
Some(Self {
origin,
coord_origin: origin_t,
coord_size: size_t,
num,
den,
flip: self.flip ^ flip,
})
}
}
#[derive(Clone, Copy, Debug)]
struct GroupMap {
x: GroupAxis,
y: GroupAxis,
}
impl GroupMap {
fn root(
reader: &mut PartReader,
group: NodeId,
style: &Style,
(width, height): (Length, Length),
) -> Option<Self> {
let (ox, oy) = group_origin(reader.doc, group)?;
let (cw, ch) = group_size(reader.doc, group)?;
let flip = reader
.style_keyword(group, style, "flip", FLIP)
.unwrap_or([false; 2]);
Some(Self {
x: GroupAxis::new(width, ox, cw, flip[0])?,
y: GroupAxis::new(height, oy, ch, flip[1])?,
})
}
fn flip(self) -> [bool; 2] {
[self.x.flip, self.y.flip]
}
fn place_box(self, rect: [i64; 4]) -> Option<([Length; 2], [Length; 2])> {
let [left, top, width, height] = rect;
if width < 0 || height < 0 {
return None;
}
Some((
[
checked_length(self.x.place(left, width)?)?,
checked_length(self.y.place(top, height)?)?,
],
[
checked_length(self.x.span(width)?)?,
checked_length(self.y.span(height)?)?,
],
))
}
fn point(self, x: i64, y: i64) -> Option<[Length; 2]> {
Some([
checked_length(self.x.point(x)?)?,
checked_length(self.y.point(y)?)?,
])
}
fn inner(
self,
rect: [i64; 4],
origin: (i64, i64),
size: (i64, i64),
flip: [bool; 2],
) -> Option<Self> {
Some(Self {
x: self
.x
.inner((rect[0], rect[2]), (origin.0, size.0), flip[0])?,
y: self
.y
.inner((rect[1], rect[3]), (origin.1, size.1), flip[1])?,
})
}
}
fn checked_length(units: i64) -> Option<Length> {
(-Length::FILE_LIMIT..=Length::FILE_LIMIT)
.contains(&units)
.then_some(Length::from_units(units))
}
fn group_origin(doc: &Document, group: NodeId) -> Option<(i64, i64)> {
doc.attribute(group, None, "coordorigin")
.map_or(Some((0, 0)), pair)
}
fn group_size(doc: &Document, group: NodeId) -> Option<(i64, i64)> {
doc.attribute(group, None, "coordsize")
.map_or(Some((VML_GROUP_COORDINATES, VML_GROUP_COORDINATES)), pair)
}
fn coord_thousandths(text: &str) -> Option<i64> {
let trimmed = text.trim();
let stripped = trimmed
.strip_suffix("pt")
.or_else(|| trimmed.strip_suffix("PT"))
.or_else(|| trimmed.strip_suffix("Pt"))
.or_else(|| trimmed.strip_suffix("pT"))
.unwrap_or(trimmed)
.trim();
decimal_thousandths(stripped)
}
fn coord_pair(text: &str) -> Option<(i64, i64)> {
let (x, y) = text.split_once(',').unwrap_or((text, "0"));
Some((coord_thousandths(x)?, coord_thousandths(y)?))
}
fn child_rect(style: &Style) -> Option<[i64; 4]> {
let left = style.get("left").and_then(coord_thousandths).unwrap_or(0);
let top = style.get("top").and_then(coord_thousandths).unwrap_or(0);
let width = style.get("width").and_then(coord_thousandths)?;
let height = style.get("height").and_then(coord_thousandths)?;
Some([left, top, width, height])
}
fn collect_parts(
reader: &mut PartReader,
group: NodeId,
map: GroupMap,
parts: &mut Vec<(Length, Length, Floating)>,
) {
let doc = reader.doc;
for child in doc.child_elements(group) {
if doc.is(child, V, "group") {
collect_nested_group(reader, child, map, parts);
} else if SHAPES.iter().any(|name| doc.is(child, V, name)) {
if let Some(entry) = read_child(reader, child, map) {
parts.push(entry);
}
} else if let Some((_, drawing)) = UNREAD.iter().find(|(name, _)| doc.is(child, V, name)) {
reader.drawing_skipped(*drawing, Reason::Unsupported);
}
}
}
fn collect_nested_group(
reader: &mut PartReader,
child: NodeId,
map: GroupMap,
parts: &mut Vec<(Length, Length, Floating)>,
) {
let doc = reader.doc;
let style = Style::new(doc.attribute(child, None, "style").unwrap_or(""));
let rotation = rotation_of(reader, child, &style);
let flip = reader
.style_keyword(child, &style, "flip", FLIP)
.unwrap_or([false; 2]);
let placed = child_rect(&style).and_then(|rect| {
let origin = group_origin(doc, child)?;
let size = group_size(doc, child)?;
let ([left, top], [w, h]) = map.place_box(rect)?;
let center2 = [
left.units().checked_mul(2)?.checked_add(w.units())?,
top.units().checked_mul(2)?.checked_add(h.units())?,
];
Some((map.inner(rect, origin, size, flip)?, center2))
});
match placed {
Some((inner_map, center2)) => {
let start = parts.len();
collect_parts(reader, child, inner_map, parts);
if let Some(slice) = parts.get_mut(start..) {
apply_group_rotation(reader, slice, center2, rotation, inner_map.flip());
}
}
None => reader.drawing_skipped(Drawing::Shape, Reason::Unsupported),
}
}
fn read_child(
reader: &mut PartReader,
child: NodeId,
map: GroupMap,
) -> Option<(Length, Length, Floating)> {
let doc = reader.doc;
let style = Style::new(doc.attribute(child, None, "style").unwrap_or(""));
if doc.is(child, V, "line") {
read_line_child(reader, child, &style, map)
} else if doc.is(child, V, "polyline") {
read_polyline_child(reader, child, &style, map)
} else if doc.is(child, V, "curve") {
read_curve_child(reader, child, &style, map)
} else {
read_box_child(reader, child, &style, map)
}
}
fn read_polyline_child(
reader: &mut PartReader,
child: NodeId,
style: &Style,
map: GroupMap,
) -> Option<(Length, Length, Floating)> {
let doc = reader.doc;
let raw = doc.attribute(child, 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()?;
let [px, py] = map.point(coord_thousandths(x)?, coord_thousandths(y)?)?;
pts.push((px, py));
}
let placed = polyline_geometry(&pts)?;
let mut part = Floating {
width: placed.width,
height: placed.height,
look: Some(look_with_geometry(reader, child, None, placed.geometry)),
..Floating::in_part(reader.part())
};
let rotation = rotation_of(reader, child, style);
apply_floating_rotation(reader, &mut part, rotation, [false; 2], [false; 2]);
text_box(reader, child, &mut part, rotation != 0);
Some((placed.left, placed.top, part))
}
fn read_curve_child(
reader: &mut PartReader,
child: NodeId,
style: &Style,
map: GroupMap,
) -> Option<(Length, Length, Floating)> {
let doc = reader.doc;
let mapped = |name: &str, fallback: (i64, i64)| -> Option<((i64, i64), (Length, Length))> {
let pair_val = match doc.attribute(child, None, name) {
Some(text) => coord_pair(text)?,
None => fallback,
};
let [px, py] = map.point(pair_val.0, pair_val.1)?;
Some((pair_val, (px, py)))
};
let (from_raw, from) = mapped("from", (0, 0))?;
let (to_raw, to) = mapped("to", (0, 0))?;
let (_, c1) = mapped("control1", from_raw)?;
let (_, c2) = mapped("control2", to_raw)?;
let placed = curve_geometry([from, c1, c2, to])?;
let mut part = Floating {
width: placed.width,
height: placed.height,
look: Some(look_with_geometry(reader, child, None, placed.geometry)),
..Floating::in_part(reader.part())
};
let rotation = rotation_of(reader, child, style);
apply_floating_rotation(reader, &mut part, rotation, [false; 2], [false; 2]);
text_box(reader, child, &mut part, rotation != 0);
Some((placed.left, placed.top, part))
}
fn read_line_child(
reader: &mut PartReader,
child: NodeId,
style: &Style,
map: GroupMap,
) -> Option<(Length, Length, Floating)> {
let doc = reader.doc;
let (fx, fy) = coord_pair(doc.attribute(child, None, "from").unwrap_or("0,0"))?;
let (tx, ty) = coord_pair(doc.attribute(child, None, "to").unwrap_or("0,0"))?;
let [x0, y0] = map.point(fx, fy)?;
let [x1, y1] = map.point(tx, ty)?;
let left = x0.min(x1);
let top = y0.min(y1);
let width = x0.max(x1) - left;
let height = y0.max(y1) - top;
let flip = [x1 < x0, y1 < y0];
let mut part = Floating {
width,
height,
look: Some(look(reader, child, (width, height)).flipped(flip)),
..Floating::in_part(reader.part())
};
let rotation = rotation_of(reader, child, style);
apply_floating_rotation(reader, &mut part, rotation, [false; 2], [false; 2]);
text_box(reader, child, &mut part, rotation != 0);
Some((left, top, part))
}
fn read_box_child(
reader: &mut PartReader,
child: NodeId,
style: &Style,
map: GroupMap,
) -> Option<(Length, Length, Floating)> {
let doc = reader.doc;
let embed = match image_data(doc, child) {
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 Some(([left, top], [width, height])) = child_rect(style).and_then(|r| map.place_box(r))
else {
let drawing = if embed.is_some() {
Drawing::Picture
} else {
Drawing::Shape
};
reader.drawing_skipped(drawing, Reason::Unsupported);
return None;
};
let child_flip = reader
.style_keyword(child, style, "flip", FLIP)
.unwrap_or([false; 2]);
let group_flip = map.flip();
let effective_flip = [child_flip[0] ^ group_flip[0], child_flip[1] ^ group_flip[1]];
let (look, text_path) = embed.as_ref().map_or_else(
|| drawn(reader, child, style, (width, height)),
|_| (None, None),
);
let mut part = Floating {
width,
height,
look: look.map(|l| l.flipped(effective_flip)),
picture: embed.map(|(embed, data)| picture(reader, embed, data, width, height)),
text_path,
..Floating::in_part(reader.part())
};
let rotation = floating_rotation(reader, child, style, &part);
apply_floating_rotation(reader, &mut part, rotation, effective_flip, effective_flip);
text_box(reader, child, &mut part, rotation != 0);
Some((left, top, part))
}