use f_office_paint::stroke::{self, StrokeCap};
use f_office_paint::{
FillRule, GradientItem, GradientStop, Item, Opacity, PathCommand, PathItem, Point, Rgb,
};
use f_office_units::scale::{DRAWING_WHOLE, FULL_TURN, QUARTER_TURN};
use f_office_units::{Edges, Length, div_round_i128, fixed};
use f_office_warnings::{Name, Warnings};
use f_office_xml::enumeration::{Values, own};
use f_office_xml::{Document, NodeId};
use crate::color::{DrawColor, SchemeColors};
use crate::custom::{self, CustomGeometry, OutOfRange, Place};
use crate::dash::{DashStyle, LineDash, MAX_DASHES, ReadDash, read_cap, read_dash};
use crate::effect::{Glow, OuterShadow, Reflection};
use crate::gradient::{
EffectGradientKind, PathGradientKind, ResolvedEffectGradient, ResolvedEffectGradientKind,
ShapeFillGradient, linear_axis,
};
use crate::line_end::{LineEnds, ReadEnds, read_ends, trim_polyline};
use crate::theme::{ShapeTheme, StyleReference};
use crate::{A, Feature, Warning, attribute_of, effect, emus_of, enumeration, integer_of, preset};
pub use crate::preset::TextRect;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Geometry {
Custom(CustomGeometry),
#[default]
Rect,
RoundRect(i64),
Ellipse,
Line,
Other,
}
impl Geometry {
#[must_use]
pub const fn is_shaped(&self) -> bool {
matches!(
self,
Self::RoundRect(_) | Self::Ellipse | Self::Line | Self::Custom(_)
)
}
#[must_use]
pub const fn is_closed_shape(&self) -> bool {
matches!(self, Self::RoundRect(_) | Self::Ellipse | Self::Custom(_))
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CompoundLine {
#[default]
Single,
Double,
ThickThin,
ThinThick,
Triple,
}
const COMPOUND: &Values<CompoundLine> = &Values::new(&[
own("sng", CompoundLine::Single),
own("dbl", CompoundLine::Double),
own("thickThin", CompoundLine::ThickThin),
own("thinThick", CompoundLine::ThinThick),
own("tri", CompoundLine::Triple),
]);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Preset {
Rect,
RoundRect,
Ellipse,
Line,
}
pub(crate) const SHAPE_TYPES: [&str; 187] = [
"line",
"lineInv",
"triangle",
"rtTriangle",
"rect",
"diamond",
"parallelogram",
"trapezoid",
"nonIsoscelesTrapezoid",
"pentagon",
"hexagon",
"heptagon",
"octagon",
"decagon",
"dodecagon",
"star4",
"star5",
"star6",
"star7",
"star8",
"star10",
"star12",
"star16",
"star24",
"star32",
"roundRect",
"round1Rect",
"round2SameRect",
"round2DiagRect",
"snipRoundRect",
"snip1Rect",
"snip2SameRect",
"snip2DiagRect",
"plaque",
"ellipse",
"teardrop",
"homePlate",
"chevron",
"pieWedge",
"pie",
"blockArc",
"donut",
"noSmoking",
"rightArrow",
"leftArrow",
"upArrow",
"downArrow",
"stripedRightArrow",
"notchedRightArrow",
"bentUpArrow",
"leftRightArrow",
"upDownArrow",
"leftUpArrow",
"leftRightUpArrow",
"quadArrow",
"leftArrowCallout",
"rightArrowCallout",
"upArrowCallout",
"downArrowCallout",
"leftRightArrowCallout",
"upDownArrowCallout",
"quadArrowCallout",
"bentArrow",
"uturnArrow",
"circularArrow",
"leftCircularArrow",
"leftRightCircularArrow",
"curvedRightArrow",
"curvedLeftArrow",
"curvedUpArrow",
"curvedDownArrow",
"swooshArrow",
"cube",
"can",
"lightningBolt",
"heart",
"sun",
"moon",
"smileyFace",
"irregularSeal1",
"irregularSeal2",
"foldedCorner",
"bevel",
"frame",
"halfFrame",
"corner",
"diagStripe",
"chord",
"arc",
"leftBracket",
"rightBracket",
"leftBrace",
"rightBrace",
"bracketPair",
"bracePair",
"straightConnector1",
"bentConnector2",
"bentConnector3",
"bentConnector4",
"bentConnector5",
"curvedConnector2",
"curvedConnector3",
"curvedConnector4",
"curvedConnector5",
"callout1",
"callout2",
"callout3",
"accentCallout1",
"accentCallout2",
"accentCallout3",
"borderCallout1",
"borderCallout2",
"borderCallout3",
"accentBorderCallout1",
"accentBorderCallout2",
"accentBorderCallout3",
"wedgeRectCallout",
"wedgeRoundRectCallout",
"wedgeEllipseCallout",
"cloudCallout",
"cloud",
"ribbon",
"ribbon2",
"ellipseRibbon",
"ellipseRibbon2",
"leftRightRibbon",
"verticalScroll",
"horizontalScroll",
"wave",
"doubleWave",
"plus",
"flowChartProcess",
"flowChartDecision",
"flowChartInputOutput",
"flowChartPredefinedProcess",
"flowChartInternalStorage",
"flowChartDocument",
"flowChartMultidocument",
"flowChartTerminator",
"flowChartPreparation",
"flowChartManualInput",
"flowChartManualOperation",
"flowChartConnector",
"flowChartPunchedCard",
"flowChartPunchedTape",
"flowChartSummingJunction",
"flowChartOr",
"flowChartCollate",
"flowChartSort",
"flowChartExtract",
"flowChartMerge",
"flowChartOfflineStorage",
"flowChartOnlineStorage",
"flowChartMagneticTape",
"flowChartMagneticDisk",
"flowChartMagneticDrum",
"flowChartDisplay",
"flowChartDelay",
"flowChartAlternateProcess",
"flowChartOffpageConnector",
"actionButtonBlank",
"actionButtonHome",
"actionButtonHelp",
"actionButtonInformation",
"actionButtonForwardNext",
"actionButtonBackPrevious",
"actionButtonEnd",
"actionButtonBeginning",
"actionButtonReturn",
"actionButtonDocument",
"actionButtonSound",
"actionButtonMovie",
"gear6",
"gear9",
"funnel",
"mathPlus",
"mathMinus",
"mathMultiply",
"mathDivide",
"mathEqual",
"mathNotEqual",
"cornerTabs",
"squareTabs",
"plaqueTabs",
"chartX",
"chartStar",
"chartPlus",
];
const PRESETS: &Values<Option<Preset>> = &Values::with_others(
&[
own("rect", Some(Preset::Rect)),
own("roundRect", Some(Preset::RoundRect)),
own("ellipse", Some(Preset::Ellipse)),
own("line", Some(Preset::Line)),
own("straightConnector1", Some(Preset::Line)),
],
&SHAPE_TYPES,
None,
);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Width {
Exact(Length),
Style(usize),
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum StrokeDash {
Own(Option<LineDash>),
Style(usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StrokeCapSource {
Own(StrokeCap),
Style(usize),
Default,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StrokeEnds {
Own(LineEnds),
Style(usize),
}
struct ResolvedGradient {
axis: (Point, Point),
stops: Vec<GradientStop>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LineStyleColor {
Own,
Required(usize),
Style(usize),
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Stroke {
color: DrawColor,
width: Width,
in_style: LineStyleColor,
dash: StrokeDash,
cap: StrokeCapSource,
ends: StrokeEnds,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GroupFill {
pub props: Option<NodeId>,
pub frame: Edges<Length>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ShapeLook {
pub geometry: Geometry,
pub compound: CompoundLine,
fill: Option<DrawColor>,
fill_gradient: Option<ShapeFillGradient>,
fill_gradient_frame: Option<Edges<Length>>,
line: Option<Stroke>,
blank_line: Option<Width>,
flip: [bool; 2],
rotation: i64,
styles: [Option<StyleReference>; 5],
effect_ref: Option<(usize, Option<DrawColor>)>,
shadow: Option<OuterShadow>,
glow: Option<Glow>,
reflection: Option<Reflection>,
}
const DEFAULT_LINE_EMUS: i64 = 9_525;
const THINNEST: Length = Length::from_units(Length::UNITS_PER_DOT);
const HALF_SIDE_SHARE: i64 = DRAWING_WHOLE / 2;
impl ShapeLook {
#[must_use]
pub const fn is_upright(&self) -> bool {
self.rotation == 0 && !self.flip[0] && !self.flip[1]
}
#[must_use]
pub fn read(
doc: &Document,
(props, style): (Option<NodeId>, Option<NodeId>),
warnings: &mut Warnings<Warning>,
) -> Self {
let geometry = props.map_or(Geometry::Other, |p| geometry(doc, p, warnings));
Self::read_with(doc, (props, style), geometry, None, warnings)
}
#[must_use]
pub fn read_in_group(
doc: &Document,
(props, style): (Option<NodeId>, Option<NodeId>),
group_fill: GroupFill,
warnings: &mut Warnings<Warning>,
) -> Self {
let geometry = props.map_or(Geometry::Other, |p| geometry(doc, p, warnings));
Self::read_with(doc, (props, style), geometry, Some(group_fill), warnings)
}
#[must_use]
pub fn read_line(
doc: &Document,
props: Option<NodeId>,
warnings: &mut Warnings<Warning>,
) -> Self {
Self::read_with(doc, (props, None), Geometry::Line, None, warnings)
}
#[must_use]
pub fn read_canvas(
doc: &Document,
(bg, whole): (Option<NodeId>, Option<NodeId>),
warnings: &mut Warnings<Warning>,
) -> Self {
let (shadow, glow, reflection) =
whole.map_or_default(|w| shape_effects(doc, w, false, warnings));
let compound = whole
.and_then(|w| doc.child(w, A, "ln"))
.and_then(|ln| enumeration(doc, ln, "cmpd", (COMPOUND, warnings)))
.unwrap_or_default();
let (fill, fill_gradient, fill_gradient_frame, _) =
fill(doc, (bg, None), true, None, warnings);
let (line, _) = line(doc, (whole, None), false, warnings);
let blank_line = whole
.and_then(|w| doc.child(w, A, "ln"))
.filter(|ln| doc.child(*ln, A, "noFill").is_some())
.and_then(|ln| emus_of(doc, ln, "w", warnings))
.map(Width::Exact);
Self {
compound,
fill,
fill_gradient,
fill_gradient_frame,
geometry: Geometry::Rect,
line,
blank_line,
flip: [false; 2],
rotation: 0,
styles: [None; 5],
effect_ref: None,
shadow,
glow,
reflection,
}
}
fn read_with(
doc: &Document,
(props, style): (Option<NodeId>, Option<NodeId>),
geometry: Geometry,
group_fill: Option<GroupFill>,
warnings: &mut Warnings<Warning>,
) -> Self {
let reference = |name: &str, warnings: &mut Warnings<Warning>| {
let node = style.and_then(|s| doc.child(s, A, name))?;
let index =
attribute_of(doc, node, "idx", |i| i.parse::<usize>().ok(), warnings).unwrap_or(0);
Some((index, node))
};
let xfrm = props.and_then(|p| doc.child(p, A, "xfrm"));
let flag = |name: &str| {
xfrm.and_then(|x| doc.attribute(x, None, name))
.is_some_and(crate::boolean)
};
let rotation = xfrm
.and_then(|x| integer_of(doc, x, "rot", warnings))
.unwrap_or(0);
let area = geometry != Geometry::Line;
let flip = [flag("flipH"), flag("flipV")];
let flipped = flip != [false; 2];
let (raw_shadow, glow, reflection) =
props.map_or_default(|props| shape_effects(doc, props, flipped, warnings));
let shadow = raw_shadow.map(|shadow| shadow.rotated_by(rotation));
let compound = props
.and_then(|p| doc.child(p, A, "ln"))
.and_then(|ln| enumeration(doc, ln, "cmpd", (COMPOUND, warnings)))
.unwrap_or_default();
let fill_reference = reference("fillRef", warnings);
let (fill, fill_gradient, fill_gradient_frame, fill_style) =
fill(doc, (props, fill_reference), area, group_fill, warnings);
let open = matches!(geometry, Geometry::Line | Geometry::Custom(_));
let line_reference = reference("lnRef", warnings);
let (line, [line_style, dash_style, ends_style]) =
line(doc, (props, line_reference), open, warnings);
let own_effects = props.is_some_and(|p| {
["effectLst", "effectDag"]
.iter()
.any(|name| doc.child(p, A, name).is_some())
});
let effect_ref = reference("effectRef", warnings)
.filter(|(index, _)| *index > 0 && !own_effects)
.map(|(index, node)| (index, DrawColor::read(doc, node, warnings)));
let effect_style = effect_ref
.as_ref()
.map(|(index, _)| StyleReference::Effect(*index));
Self {
compound,
fill,
fill_gradient,
fill_gradient_frame,
geometry,
line,
blank_line: props
.and_then(|p| doc.child(p, A, "ln"))
.filter(|ln| doc.child(*ln, A, "noFill").is_some())
.and_then(|ln| {
emus_of(doc, ln, "w", warnings)
.map(Width::Exact)
.or_else(|| {
line_reference
.filter(|(index, _)| *index > 0)
.map(|(index, _)| Width::Style(index))
})
}),
flip,
rotation,
styles: [fill_style, line_style, dash_style, ends_style, effect_style],
effect_ref,
shadow,
glow,
reflection,
}
}
#[must_use]
pub const fn shadow(&self) -> Option<&OuterShadow> {
self.shadow.as_ref()
}
#[must_use]
pub const fn glow(&self) -> Option<&Glow> {
self.glow.as_ref()
}
#[must_use]
pub const fn reflection(&self) -> Option<&Reflection> {
self.reflection.as_ref()
}
#[must_use]
pub fn shadow_in(&self, theme: &ShapeTheme) -> Option<OuterShadow> {
if let Some(shadow) = &self.shadow {
return Some(shadow.clone());
}
let (index, color) = self.effect_ref.as_ref()?;
let flipped = self.flip != [false; 2];
theme
.effect_shadow(*index, color.as_ref())
.filter(|shadow| !shadow.turns_with_shape() || !flipped)
.map(|shadow| shadow.rotated_by(self.rotation))
}
#[must_use]
pub fn inset_line_width(&self, theme: &ShapeTheme) -> Option<Length> {
self.line(theme)
.map(|(_, _, width)| width)
.or_else(|| match self.blank_line? {
Width::Exact(width) => Some(width),
Width::Style(index) => theme.line_width(index),
})
}
#[must_use]
pub fn quarter_turns(&self) -> Option<i64> {
quarter_turns(self.rotation)
}
#[must_use]
pub const fn flips(&self) -> [bool; 2] {
self.flip
}
#[must_use]
pub fn text_quarter_turns(&self) -> Option<i64> {
let mirrored_down = if self.flip[1] { FULL_TURN / 2 } else { 0 };
quarter_turns(self.rotation + mirrored_down)
}
#[must_use]
pub fn in_line_style(
geometry: Geometry,
fill: Option<DrawColor>,
(color, index): (DrawColor, usize),
) -> Self {
Self {
geometry,
compound: CompoundLine::Single,
fill,
fill_gradient: None,
fill_gradient_frame: None,
line: Some(Stroke {
color,
width: Width::Style(index),
in_style: LineStyleColor::Required(index),
dash: StrokeDash::Style(index),
cap: StrokeCapSource::Style(index),
ends: StrokeEnds::Style(index),
}),
blank_line: None,
flip: [false; 2],
rotation: 0,
styles: [None; 5],
effect_ref: None,
shadow: None,
glow: None,
reflection: None,
}
}
#[must_use]
pub fn plain(geometry: Geometry, fill: Option<Rgb>, line: Option<(Rgb, Length)>) -> Self {
Self {
geometry,
compound: CompoundLine::Single,
fill: fill.map(DrawColor::rgb),
fill_gradient: None,
fill_gradient_frame: None,
line: line.map(|(rgb, width)| Stroke {
color: DrawColor::rgb(rgb),
width: Width::Exact(width),
in_style: LineStyleColor::Own,
dash: StrokeDash::Own(None),
cap: StrokeCapSource::Default,
ends: StrokeEnds::Own(LineEnds::default()),
}),
blank_line: None,
flip: [false; 2],
rotation: 0,
styles: [None; 5],
effect_ref: None,
shadow: None,
glow: None,
reflection: None,
}
}
#[must_use]
pub fn flipped(self, flip: [bool; 2]) -> Self {
Self { flip, ..self }
}
#[must_use]
pub fn turned(self, rotation: i64) -> Self {
Self { rotation, ..self }
}
#[must_use]
pub fn rotated_by(self, rotation: i64) -> Self {
Self {
rotation: (self.rotation + rotation).rem_euclid(FULL_TURN),
..self
}
}
#[must_use]
pub fn compose_outer(self, matrix: [[i32; 2]; 2]) -> Self {
if matrix == [[1, 0], [0, 1]] {
return self;
}
let det = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
let flip_h = det < 0;
let col0 = if flip_h {
[-matrix[0][0], -matrix[1][0]]
} else {
[matrix[0][0], matrix[1][0]]
};
let quarters = match col0 {
[1, 0] => 0,
[0, 1] => 1,
[-1, 0] => 2,
_ => 3,
};
let signed = if flip_h {
-self.rotation
} else {
self.rotation
};
let rotation = (signed + quarters * QUARTER_TURN).rem_euclid(FULL_TURN);
Self {
flip: [self.flip[0] ^ flip_h, self.flip[1]],
rotation,
..self
}
}
#[must_use]
pub fn fill(&self, theme: &ShapeTheme) -> Option<(Rgb, Opacity)> {
if self.geometry == Geometry::Line {
return None;
}
let color = self.fill.as_ref()?.clone();
let color = match self.styles[0] {
Some(StyleReference::Fill(index)) => theme.fill_color(index, color),
_ => color,
};
color.resolve(&theme.colors)
}
#[must_use]
pub fn theme_features(&self, theme: &ShapeTheme) -> Vec<Feature> {
let mut features = Vec::new();
for feature in self
.styles
.iter()
.flatten()
.filter_map(|s| theme.feature(*s))
{
if !features.contains(&feature) {
features.push(feature);
}
}
if let Some(StyleReference::Fill(index)) = self.styles[0]
&& theme.has_fill_gradient(index)
&& theme.fill_gradient(index, self.fill.as_ref()).is_none()
&& !features.contains(&Feature::ThemeStyle)
{
features.push(Feature::ThemeStyle);
}
if let Some((index, _)) = &self.effect_ref
&& theme.has_effect_shadow(*index)
&& self.shadow_in(theme).is_none()
&& !features.contains(&Feature::Shadow)
{
features.push(Feature::Shadow);
}
features
}
#[must_use]
pub fn line(&self, theme: &ShapeTheme) -> Option<(Rgb, Opacity, Length)> {
let stroke = self.line.as_ref()?;
let color = match stroke.in_style {
LineStyleColor::Own => stroke.color.clone(),
LineStyleColor::Required(index) => theme.line_style(index, stroke.color.clone())?.0,
LineStyleColor::Style(index) => theme.line_color(index, stroke.color.clone()),
};
let (rgb, alpha) = color.resolve(&theme.colors)?;
let width = match stroke.width {
Width::Exact(width) => Some(width),
Width::Style(index) => theme.line_width(index),
}
.or_else(|| Length::from_emus(DEFAULT_LINE_EMUS))?;
Some((rgb, alpha, width))
}
#[must_use]
pub fn compound_left_out(&self) -> bool {
self.compound != CompoundLine::Single && matches!(self.geometry, Geometry::Custom(_))
}
pub fn items(
&self,
frame: Edges<Length>,
fill: Option<Rgb>,
line: Option<(Rgb, Length)>,
parts: &[i64],
) -> Result<Vec<Item>, OutOfRange> {
let dash = line.and_then(|(_, width)| self.resolve_dash(None, width));
let ends = self.resolve_ends(None);
self.items_with_style(None, frame, fill, line, parts, (dash.as_ref(), ends))
}
pub fn items_with_theme(
&self,
theme: &ShapeTheme,
frame: Edges<Length>,
fill: Option<Rgb>,
line: Option<(Rgb, Length)>,
parts: &[i64],
) -> Result<Vec<Item>, OutOfRange> {
let dash = line.and_then(|(_, width)| self.resolve_dash(Some(theme), width));
let ends = self.resolve_ends(Some(theme));
self.items_with_style(Some(theme), frame, fill, line, parts, (dash.as_ref(), ends))
}
fn resolve_gradient(&self, theme: Option<&ShapeTheme>) -> Option<ShapeFillGradient> {
if self.geometry == Geometry::Line {
return None;
}
if let Some(gradient) = &self.fill_gradient {
return Some(gradient.clone());
}
if let Some(StyleReference::Fill(index)) = self.styles[0] {
return theme?.fill_gradient(index, self.fill.as_ref());
}
None
}
pub fn resolve_effect_gradient(
&self,
theme: &ShapeTheme,
frame: Edges<Length>,
) -> Result<Option<ResolvedEffectGradient>, OutOfRange> {
let Some(ShapeFillGradient::Effect(grad)) = self.resolve_gradient(Some(theme)) else {
return Ok(None);
};
let Some(stops) = grad.resolve_stops(&theme.colors) else {
return Ok(None);
};
let (grad_frame, shown, exact_quarters) = self.gradient_box(frame);
let kind = match grad.kind() {
EffectGradientKind::Linear { angle, scaled } => {
let Some((start, end)) = self.linear_axis_in_page(
(angle, scaled, grad.rot_with_shape()),
grad_frame,
shown,
exact_quarters,
)?
else {
return Ok(None);
};
ResolvedEffectGradientKind::Linear { start, end }
}
EffectGradientKind::Path {
kind: PathGradientKind::Circle,
..
} => {
let center = box_center(shown);
let radius = hypot_length(
grad_frame.width().div_toward_zero(2),
grad_frame.height().div_toward_zero(2),
);
ResolvedEffectGradientKind::Radial {
center,
rx: radius,
ry: radius,
}
}
EffectGradientKind::Path {
kind: PathGradientKind::Shape,
..
} if self.geometry == Geometry::Ellipse && exact_quarters.is_some() => {
ResolvedEffectGradientKind::Radial {
center: box_center(shown),
rx: shown.width().div_toward_zero(2),
ry: shown.height().div_toward_zero(2),
}
}
EffectGradientKind::Path {
kind: PathGradientKind::Rect,
focus,
} => {
let center = self.focus_point_in_page(
focus,
grad.rot_with_shape(),
grad_frame,
shown,
exact_quarters,
)?;
if exact_quarters.is_some() {
ResolvedEffectGradientKind::Rect {
center,
bounds: shown,
}
} else {
ResolvedEffectGradientKind::Shape { center }
}
}
EffectGradientKind::Path {
kind: PathGradientKind::Shape,
focus,
} => {
let center = self.focus_point_in_page(
focus,
grad.rot_with_shape(),
grad_frame,
shown,
exact_quarters,
)?;
if self.geometry == Geometry::Rect && exact_quarters.is_some() {
ResolvedEffectGradientKind::Rect {
center,
bounds: shown,
}
} else {
ResolvedEffectGradientKind::Shape { center }
}
}
};
Ok(Some(ResolvedEffectGradient { kind, stops }))
}
fn focus_point_in_page(
&self,
(fx, fy): (i64, i64),
rot_with_shape: bool,
frame: Edges<Length>,
shown: Edges<Length>,
exact_quarters: Option<i64>,
) -> Result<Point, OutOfRange> {
let place_in = |box_: Edges<Length>, (cx, cy): (i64, i64)| {
let x = box_.left
+ Length::from_units(
i64::try_from(div_round_i128(
i128::from(box_.width().units()) * i128::from(cx),
i128::from(DRAWING_WHOLE),
))
.unwrap_or(0),
);
let y = box_.top
+ Length::from_units(
i64::try_from(div_round_i128(
i128::from(box_.height().units()) * i128::from(cy),
i128::from(DRAWING_WHOLE),
))
.unwrap_or(0),
);
point(x, y)
};
if !rot_with_shape {
let bounds = if exact_quarters.is_some() {
shown
} else {
let (low, high) = rotated_frame_bounds(frame, self.rotation)?;
Edges {
left: low.x,
top: low.y,
right: high.x,
bottom: high.y,
}
};
return Ok(place_in(bounds, (fx, fy)));
}
let fx = if self.flip[0] { DRAWING_WHOLE - fx } else { fx };
let fy = if self.flip[1] { DRAWING_WHOLE - fy } else { fy };
let pt = place_in(frame, (fx, fy));
match exact_quarters {
Some(0) => Ok(pt),
Some(quarters) => {
let center = (
frame.left + frame.width().div_toward_zero(2),
frame.top + frame.height().div_toward_zero(2),
);
let (tx, ty) = custom::turned((pt.x, pt.y), center, quarters);
Ok(point(tx, ty))
}
None => {
let center2 = frame_center_doubled(frame)?;
rotate_point_about(pt, center2, self.rotation)
}
}
}
fn linear_axis_in_page(
&self,
(angle, scaled, rot_with_shape): (i64, bool, bool),
frame: Edges<Length>,
shown: Edges<Length>,
exact_quarters: Option<i64>,
) -> Result<Option<(Point, Point)>, OutOfRange> {
let box_corners =
|box_: Edges<Length>| (point(box_.left, box_.top), point(box_.right, box_.bottom));
if !rot_with_shape {
let bounds = match exact_quarters {
Some(_) => box_corners(shown),
None => rotated_frame_bounds(frame, self.rotation)?,
};
return Ok(linear_axis(angle, scaled, bounds));
}
let Some((start, end)) = linear_axis(angle, scaled, box_corners(frame)) else {
return Ok(None);
};
let flip_pt = |pt: Point| Point {
x: if self.flip[0] {
frame.left + (frame.right - pt.x)
} else {
pt.x
},
y: if self.flip[1] {
frame.top + (frame.bottom - pt.y)
} else {
pt.y
},
};
let (start, end) = (flip_pt(start), flip_pt(end));
match exact_quarters {
Some(0) => Ok(Some((start, end))),
Some(quarters) => {
let center = (
frame.left + frame.width().div_toward_zero(2),
frame.top + frame.height().div_toward_zero(2),
);
let turn = |pt: Point| {
let (tx, ty) = custom::turned((pt.x, pt.y), center, quarters);
point(tx, ty)
};
Ok(Some((turn(start), turn(end))))
}
None => {
let center2 = frame_center_doubled(frame)?;
Ok(Some((
rotate_point_about(start, center2, self.rotation)?,
rotate_point_about(end, center2, self.rotation)?,
)))
}
}
}
fn resolve_dash(&self, theme: Option<&ShapeTheme>, width: Length) -> Option<DashStyle> {
let stroke = self.line.as_ref()?;
let dash = match &stroke.dash {
StrokeDash::Own(dash) => dash.as_ref()?,
StrokeDash::Style(index) => theme?.line_dash(*index)?,
};
let cap = match stroke.cap {
StrokeCapSource::Own(cap) => cap,
StrokeCapSource::Style(index) => {
theme.and_then(|t| t.line_cap(index)).unwrap_or_default()
}
StrokeCapSource::Default => StrokeCap::Flat,
};
let drawn = half_width(width) * 2;
dash.resolve(drawn, cap)
}
fn resolve_ends(&self, theme: Option<&ShapeTheme>) -> LineEnds {
let Some(stroke) = self.line.as_ref() else {
return LineEnds::default();
};
match stroke.ends {
StrokeEnds::Own(ends) => ends,
StrokeEnds::Style(index) => theme.and_then(|t| t.line_ends(index)).unwrap_or_default(),
}
}
fn gradient_box(&self, frame: Edges<Length>) -> (Edges<Length>, Edges<Length>, Option<i64>) {
if let Some(rel) = self.fill_gradient_frame {
let group_box = Edges {
left: frame.left + rel.left,
top: frame.top + rel.top,
right: frame.left + rel.right,
bottom: frame.top + rel.bottom,
};
return (group_box, group_box, Some(0));
}
let exact_quarters = quarter_turns(self.rotation);
let shown = shown_box(frame, exact_quarters.unwrap_or(0));
(frame, shown, exact_quarters)
}
fn resolved_gradient(
&self,
theme: Option<&ShapeTheme>,
frame: Edges<Length>,
) -> Result<Option<ResolvedGradient>, OutOfRange> {
let Some(ShapeFillGradient::Linear(grad)) = self.resolve_gradient(theme) else {
return Ok(None);
};
let colors = theme.map_or_else(SchemeColors::default, |t| t.colors);
let Some(stops) = grad.resolve_stops(&colors) else {
return Ok(None);
};
let (grad_frame, shown, exact_quarters) = self.gradient_box(frame);
Ok(self
.linear_axis_in_page(grad.linear_params(), grad_frame, shown, exact_quarters)?
.map(|axis| ResolvedGradient { axis, stops }))
}
fn items_with_style(
&self,
theme: Option<&ShapeTheme>,
frame: Edges<Length>,
fill: Option<Rgb>,
line: Option<(Rgb, Length)>,
parts: &[i64],
(dash, ends): (Option<&DashStyle>, LineEnds),
) -> Result<Vec<Item>, OutOfRange> {
if self.geometry == Geometry::Other {
return Ok(Vec::new());
}
let exact_quarters = quarter_turns(self.rotation);
let quarters = exact_quarters.unwrap_or(0);
let center = (
frame.left + frame.width().div_toward_zero(2),
frame.top + frame.height().div_toward_zero(2),
);
let shown = shown_box(frame, quarters);
let gradient = self.resolved_gradient(theme, frame)?;
let fill_color = if gradient.is_some() {
Some(Rgb::BLACK)
} else {
fill
};
let (mut fill_item, mut stroke_items) = if let Geometry::Custom(geometry) = &self.geometry {
let place = Place {
frame,
flip: self.flip,
quarters,
};
let line = line.map(|(color, width)| (color, half_width(width)));
let (filled, stroked) =
custom::fill_and_stroke(geometry, &place, fill_color, line, dash, ends)?;
(
filled.map(Item::Path),
stroked.map(Item::Path).into_iter().collect(),
)
} else if self.geometry == Geometry::Line {
(
None,
self.line_items(
self.line_ends(frame, quarters, center),
line,
parts,
(dash, ends),
),
)
} else {
let filled = fill_color
.map(|color| path(self.outline(shown, Length::ZERO), color, FillRule::NonZero));
let stroked = line.map_or_else(Vec::new, |(color, width)| {
self.stroke_closed(shown, color, half_width(width), parts, dash)
});
(filled, stroked)
};
if exact_quarters.is_none() {
rotate_items(fill_item.as_mut_slice(), frame, self.rotation)?;
rotate_items(&mut stroke_items, frame, self.rotation)?;
}
if let (Some(ResolvedGradient { axis, stops }), Some(Item::Path(path_item))) =
(gradient, &mut fill_item)
{
fill_item = Some(Item::Gradient(GradientItem::new(
std::mem::take(&mut path_item.commands),
path_item.fill_rule,
axis,
stops,
)));
}
let mut items = Vec::with_capacity(usize::from(fill_item.is_some()) + stroke_items.len());
items.extend(fill_item);
items.extend(stroke_items);
Ok(items)
}
fn stroke_closed(
&self,
shown: Edges<Length>,
color: Rgb,
half: Length,
parts: &[i64],
dash: Option<&DashStyle>,
) -> Vec<Item> {
if parts.len() > 1 {
return self.stroke_closed_compound(shown, color, half, parts, dash);
}
if let Some(style) = dash {
let points = self.dashed_outline_points(shown);
if let Some(commands) =
stroke::dashes(&points, half, &style.pattern, style.cap, MAX_DASHES)
{
return vec![path(commands, color, FillRule::NonZero)];
}
}
let mut ring = self.outline(shown, half);
if shown.width() > half * 2 && shown.height() > half * 2 {
ring.extend(self.outline(shown, -half));
}
vec![path(ring, color, FillRule::EvenOdd)]
}
fn stroke_closed_compound(
&self,
shown: Edges<Length>,
color: Rgb,
half: Length,
parts: &[i64],
dash: Option<&DashStyle>,
) -> Vec<Item> {
let bands = compound_bands(half, parts);
if let Some(style) = dash {
let items = self.stroke_closed_dashed_bands(shown, color, &bands, style);
if !items.is_empty() {
return items;
}
}
let mut rings = Vec::new();
for (outer, inner) in bands {
let outer_box = grow_edges(shown, outer);
if outer_box.width() <= Length::ZERO || outer_box.height() <= Length::ZERO {
continue;
}
rings.extend(self.compound_outline(shown, outer));
let inner_box = grow_edges(shown, inner);
if inner_box.width() > Length::ZERO && inner_box.height() > Length::ZERO {
rings.extend(self.compound_outline(shown, inner));
}
}
(!rings.is_empty())
.then(|| path(rings, color, FillRule::EvenOdd))
.into_iter()
.collect()
}
fn stroke_closed_dashed_bands(
&self,
shown: Edges<Length>,
color: Rgb,
bands: &[(Length, Length)],
style: &DashStyle,
) -> Vec<Item> {
let mut items = Vec::with_capacity(bands.len());
for &(outer, inner) in bands {
let mid = (outer + inner).div_toward_zero(2);
let band_half = (outer - inner).div_toward_zero(2);
if band_half <= Length::ZERO {
continue;
}
let band_box = grow_edges(shown, mid);
if band_box.width() <= Length::ZERO || band_box.height() <= Length::ZERO {
continue;
}
let points = self.dashed_outline_points(band_box);
if let Some(commands) =
stroke::dashes(&points, band_half, &style.pattern, style.cap, MAX_DASHES)
{
items.push(path(commands, color, FillRule::NonZero));
}
}
items
}
fn compound_outline(&self, shown: Edges<Length>, grow: Length) -> Vec<PathCommand> {
match self.geometry {
Geometry::Rect => rounded(grow_edges(shown, grow), grow.max(Length::ZERO)),
_ => self.outline(shown, grow),
}
}
fn line_items(
&self,
ends: [(Length, Length); 2],
line: Option<(Rgb, Length)>,
parts: &[i64],
(dash, arrows): (Option<&DashStyle>, LineEnds),
) -> Vec<Item> {
let Some((color, width)) = line else {
return Vec::new();
};
let half = half_width(width);
let drawn_width = half * 2;
let start = point(ends[0].0, ends[0].1);
let end = point(ends[1].0, ends[1].1);
let head_trim = arrows.head.map_or(Length::ZERO, |e| e.shorten(drawn_width));
let tail_trim = arrows.tail.map_or(Length::ZERO, |e| e.shorten(drawn_width));
let shaft_pts = if arrows.any() {
trim_polyline(&[start, end], head_trim, tail_trim)
} else {
vec![start, end]
};
let mut items = self.line_shaft_items(&shaft_pts, color, half, parts, dash);
if arrows.any() {
let mut arrow_cmds = Vec::new();
if let Some(head) = arrows.head {
arrow_cmds.extend(head.commands(end, start, drawn_width));
}
if let Some(tail) = arrows.tail {
arrow_cmds.extend(tail.commands(start, end, drawn_width));
}
if !arrow_cmds.is_empty() {
items.push(path(arrow_cmds, color, FillRule::NonZero));
}
}
items
}
fn line_shaft_items(
&self,
shaft_pts: &[Point],
color: Rgb,
half: Length,
parts: &[i64],
dash: Option<&DashStyle>,
) -> Vec<Item> {
let [a, b] = *shaft_pts else {
return Vec::new();
};
let ends = [(a.x, a.y), (b.x, b.y)];
if parts.len() <= 1 {
if let Some(style) = dash
&& let Some(commands) =
stroke::dashes(shaft_pts, half, &style.pattern, style.cap, MAX_DASHES)
{
return vec![path(commands, color, FillRule::NonZero)];
}
return stroke_line(ends, half, color).into_iter().collect();
}
let sign = if self.flip[0] == self.flip[1] { 1 } else { -1 };
compound_line(ends, half, color, parts, sign)
}
fn dashed_outline_points(&self, shown: Edges<Length>) -> Vec<Point> {
let Edges {
left,
top,
right,
bottom,
} = shown;
match self.geometry {
Geometry::RoundRect(adjust) => {
let shorter = (right - left).min(bottom - top);
let share = adjust.clamp(0, HALF_SIDE_SHARE);
let r = (shorter * share)
.div_toward_zero(DRAWING_WHOLE)
.min(shorter.div_toward_zero(2))
.max(Length::ZERO);
if r == Length::ZERO {
return rect_dash_points(shown);
}
let k = stroke::kappa(r);
let mut pts = vec![point(left, top + r)];
pts.extend(stroke::cubic_points([
point(left, top + r),
point(left, top + r - k),
point(left + r - k, top),
point(left + r, top),
]));
pts.push(point(right - r, top));
pts.extend(stroke::cubic_points([
point(right - r, top),
point(right - r + k, top),
point(right, top + r - k),
point(right, top + r),
]));
pts.push(point(right, bottom - r));
pts.extend(stroke::cubic_points([
point(right, bottom - r),
point(right, bottom - r + k),
point(right - r + k, bottom),
point(right - r, bottom),
]));
pts.push(point(left + r, bottom));
pts.extend(stroke::cubic_points([
point(left + r, bottom),
point(left + r - k, bottom),
point(left, bottom - r + k),
point(left, bottom - r),
]));
pts.push(point(left, top + r));
pts
}
Geometry::Ellipse => {
let (cx, cy) = (
(left + right).div_toward_zero(2),
(top + bottom).div_toward_zero(2),
);
let (kx, ky) = (
stroke::kappa((right - left).div_toward_zero(2)),
stroke::kappa((bottom - top).div_toward_zero(2)),
);
let mut pts = vec![point(left, cy)];
pts.extend(stroke::cubic_points([
point(left, cy),
point(left, cy - ky),
point(cx - kx, top),
point(cx, top),
]));
pts.extend(stroke::cubic_points([
point(cx, top),
point(cx + kx, top),
point(right, cy - ky),
point(right, cy),
]));
pts.extend(stroke::cubic_points([
point(right, cy),
point(right, cy + ky),
point(cx + kx, bottom),
point(cx, bottom),
]));
pts.extend(stroke::cubic_points([
point(cx, bottom),
point(cx - kx, bottom),
point(left, cy + ky),
point(left, cy),
]));
pts
}
_ => rect_dash_points(shown),
}
}
fn line_ends(
&self,
frame: Edges<Length>,
quarters: i64,
center: (Length, Length),
) -> [(Length, Length); 2] {
let [flip_x, flip_y] = self.flip;
let Edges {
left,
top,
right,
bottom,
} = frame;
let start = (
if flip_x { right } else { left },
if flip_y { bottom } else { top },
);
let end = (
if flip_x { left } else { right },
if flip_y { top } else { bottom },
);
[start, end].map(|point| custom::turned(point, center, quarters))
}
fn outline(&self, shown: Edges<Length>, grow: Length) -> Vec<PathCommand> {
let Edges {
left,
top,
right,
bottom,
} = shown;
let grown = Edges {
left: left - grow,
top: top - grow,
right: right + grow,
bottom: bottom + grow,
};
match self.geometry {
Geometry::RoundRect(adjust) => {
let shorter = (right - left).min(bottom - top);
let share = adjust.clamp(0, HALF_SIDE_SHARE);
let radius = (shorter * share).div_toward_zero(DRAWING_WHOLE) + grow;
rounded(grown, radius.max(Length::ZERO))
}
Geometry::Ellipse => ellipse(grown),
_ => rounded(grown, Length::ZERO),
}
}
}
fn grow_edges(edges: Edges<Length>, grow: Length) -> Edges<Length> {
Edges {
left: edges.left - grow,
top: edges.top - grow,
right: edges.right + grow,
bottom: edges.bottom + grow,
}
}
fn compound_bands(half: Length, parts: &[i64]) -> Vec<(Length, Length)> {
let total: i64 = parts.iter().sum();
if total <= 0 || parts.iter().any(|part| *part <= 0) {
return vec![(half, -half)];
}
let span = i128::from(half.units()) * 2;
let offset = |pos: i64| -> Length {
let delta = div_round_i128(span * i128::from(pos), i128::from(total));
let delta = i64::try_from(delta).unwrap_or(0);
Length::from_units(half.units().saturating_sub(delta))
};
let mut bands = Vec::with_capacity(parts.len().div_ceil(2));
let mut acc = 0_i64;
for (index, &part) in parts.iter().enumerate() {
let next = acc + part;
if index % 2 == 0 {
bands.push((offset(acc), offset(next)));
}
acc = next;
}
bands
}
fn half_width(width: Length) -> Length {
width.max(THINNEST).div_toward_zero(2)
}
fn geometry(doc: &Document, props: NodeId, warnings: &mut Warnings<Warning>) -> Geometry {
if let Some(custom) = doc.child(props, A, "custGeom") {
return custom::read(doc, custom, warnings).map_or(Geometry::Other, Geometry::Custom);
}
doc.child(props, A, "prstGeom")
.map_or(Geometry::Other, |preset| {
preset_geometry(doc, preset, warnings)
})
}
fn preset_geometry(doc: &Document, preset: NodeId, warnings: &mut Warnings<Warning>) -> Geometry {
let Some(name) = doc.attribute(preset, None, "prst") else {
warnings.push(Warning::InvalidValue {
element: Name::new("prstGeom"),
attribute: Name::new("prst"),
});
return Geometry::Other;
};
if let Some((None, ..)) = PRESETS.find(name)
&& let Some(geometry) = preset::geometry(name, &adjust_values(doc, preset), warnings)
{
return Geometry::Custom(geometry);
}
match enumeration(doc, preset, "prst", (PRESETS, warnings)).flatten() {
Some(Preset::Rect) => Geometry::Rect,
Some(Preset::RoundRect) => {
let adjust = doc
.child(preset, A, "avLst")
.into_iter()
.flat_map(|list| doc.child_elements(list))
.filter(|gd| doc.attribute(*gd, None, "name") == Some("adj"))
.find(|gd| doc.attribute(*gd, None, "fmla").is_some())
.and_then(|gd| attribute_of(doc, gd, "fmla", guide_value, warnings))
.unwrap_or(16_667);
Geometry::RoundRect(adjust)
}
Some(Preset::Ellipse) => Geometry::Ellipse,
Some(Preset::Line) => Geometry::Line,
None => Geometry::Other,
}
}
fn adjust_values(doc: &Document, preset: NodeId) -> Vec<(&str, &str)> {
doc.child(preset, A, "avLst")
.into_iter()
.flat_map(|list| doc.child_elements(list))
.filter(|gd| doc.is(*gd, A, "gd"))
.filter_map(|gd| {
Some((
doc.attribute(gd, None, "name")?,
doc.attribute(gd, None, "fmla")?,
))
})
.collect()
}
#[must_use]
pub fn text_rect(doc: &Document, props: NodeId) -> Option<TextRect> {
let preset = doc.child(props, A, "prstGeom")?;
let name = doc.attribute(preset, None, "prst")?;
preset::text_rect(name, &adjust_values(doc, preset))
}
fn guide_value(formula: &str) -> Option<i64> {
formula.strip_prefix("val ")?.trim().parse().ok()
}
#[must_use]
pub fn quarter_turns(rotation: i64) -> Option<i64> {
let turn = rotation.rem_euclid(FULL_TURN);
(turn % QUARTER_TURN == 0).then_some(turn / QUARTER_TURN)
}
#[must_use]
pub fn turned_clockwise(point: [i64; 2], center: [i64; 2], rotation: i64) -> Option<[i64; 2]> {
let [sin, cos] = fixed::sin_cos(i128::from(rotation) * fixed::ONE);
let ([x, y], [cx, cy]) = (point.map(i128::from), center.map(i128::from));
let (dx, dy) = (x - cx, y - cy);
let x = cx + fixed::product(dx, cos) - fixed::product(dy, sin);
let y = cy + fixed::product(dx, sin) + fixed::product(dy, cos);
Some([i64::try_from(x).ok()?, i64::try_from(y).ok()?])
}
fn shown_box(frame: Edges<Length>, quarters: i64) -> Edges<Length> {
let (width, height) = (frame.width(), frame.height());
let cx = frame.left + width.div_toward_zero(2);
let cy = frame.top + height.div_toward_zero(2);
let (w, h) = if quarters % 2 == 1 {
(height, width)
} else {
(width, height)
};
let (left, top) = (cx - w.div_toward_zero(2), cy - h.div_toward_zero(2));
Edges {
left,
top,
right: left + w,
bottom: top + h,
}
}
fn box_center(edges: Edges<Length>) -> Point {
point(
edges.left + edges.width().div_toward_zero(2),
edges.top + edges.height().div_toward_zero(2),
)
}
fn hypot_length(a: Length, b: Length) -> Length {
let (a, b) = (i128::from(a.units()), i128::from(b.units()));
let sum = a.saturating_mul(a).saturating_add(b.saturating_mul(b));
Length::from_units(i64::try_from(sum.isqrt()).unwrap_or(i64::MAX))
}
fn frame_center_doubled(frame: Edges<Length>) -> Result<[i64; 2], OutOfRange> {
let cx2 = frame
.left
.units()
.checked_add(frame.right.units())
.ok_or(OutOfRange)?;
let cy2 = frame
.top
.units()
.checked_add(frame.bottom.units())
.ok_or(OutOfRange)?;
Ok([cx2, cy2])
}
fn rotate_point_about(pt: Point, center2: [i64; 2], rotation: i64) -> Result<Point, OutOfRange> {
let x2 = pt.x.units().checked_mul(2).ok_or(OutOfRange)?;
let y2 = pt.y.units().checked_mul(2).ok_or(OutOfRange)?;
let [rx2, ry2] = turned_clockwise([x2, y2], center2, rotation).ok_or(OutOfRange)?;
Ok(Point {
x: Length::from_units(rx2).div_round(2),
y: Length::from_units(ry2).div_round(2),
})
}
fn rotated_frame_bounds(frame: Edges<Length>, rotation: i64) -> Result<(Point, Point), OutOfRange> {
let center2 = frame_center_doubled(frame)?;
let corners = [
point(frame.left, frame.top),
point(frame.right, frame.top),
point(frame.right, frame.bottom),
point(frame.left, frame.bottom),
];
let mut rotated = corners
.into_iter()
.map(|pt| rotate_point_about(pt, center2, rotation));
let first = rotated.next().ok_or(OutOfRange)??;
let (mut min_x, mut min_y, mut max_x, mut max_y) = (first.x, first.y, first.x, first.y);
for pt in rotated {
let pt = pt?;
min_x = min_x.min(pt.x);
min_y = min_y.min(pt.y);
max_x = max_x.max(pt.x);
max_y = max_y.max(pt.y);
}
Ok((point(min_x, min_y), point(max_x, max_y)))
}
fn rotate_items(items: &mut [Item], frame: Edges<Length>, rotation: i64) -> Result<(), OutOfRange> {
let center2 = frame_center_doubled(frame)?;
let mut failed = false;
let mut turn_pt = |pt: Point| {
if let Ok(rotated) = rotate_point_about(pt, center2, rotation) {
rotated
} else {
failed = true;
pt
}
};
for item in items {
item.map_places(&mut turn_pt, |length| length);
}
if failed { Err(OutOfRange) } else { Ok(()) }
}
#[must_use]
pub fn picture_fill(doc: &Document, props: NodeId) -> Option<NodeId> {
doc.child(props, A, "blipFill")
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PictureLine {
color: DrawColor,
width: Length,
}
impl PictureLine {
#[must_use]
pub fn resolve(&self, theme: &ShapeTheme) -> Option<(Rgb, Opacity, Length)> {
let (rgb, alpha) = self.color.resolve(&theme.colors)?;
Some((rgb, alpha, self.width))
}
}
fn shape_effects(
doc: &Document,
props: NodeId,
turned: bool,
warnings: &mut Warnings<Warning>,
) -> (Option<OuterShadow>, Option<Glow>, Option<Reflection>) {
let (raw_shadow, glow, raw_reflection) = effect::shape_effects_of(doc, props, warnings);
let shadow = raw_shadow.filter(|shadow| {
let fixed = !shadow.turns_with_shape() || !turned;
if !fixed {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::Shadow,
});
}
fixed
});
let reflection = raw_reflection.filter(|reflection| {
let fixed = !reflection.turns_with_shape() || !turned;
if !fixed {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::Reflection,
});
}
fixed
});
(shadow, glow, reflection)
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PictureLook {
pub geometry: Geometry,
pub line: Option<PictureLine>,
pub shadow: Option<OuterShadow>,
pub soft_edge: Option<Length>,
pub glow: Option<Glow>,
pub reflection: Option<Reflection>,
}
fn picture_geometry(doc: &Document, props: NodeId, warnings: &mut Warnings<Warning>) -> Geometry {
if let Some(custom) = doc.child(props, A, "custGeom") {
if let Some(geom) = custom::read(doc, custom, warnings) {
return Geometry::Custom(geom);
}
warnings.push(Warning::FeatureNotSupported {
feature: Feature::ShapedPicture,
});
return Geometry::Rect;
}
let Some(preset) = doc.child(props, A, "prstGeom") else {
return Geometry::Rect;
};
match preset_geometry(doc, preset, warnings) {
geom @ (Geometry::Rect
| Geometry::RoundRect(_)
| Geometry::Ellipse
| Geometry::Custom(_)) => geom,
Geometry::Line => {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::ShapedPicture,
});
Geometry::Rect
}
Geometry::Other => Geometry::Rect,
}
}
pub fn picture_properties(
doc: &Document,
props: NodeId,
warnings: &mut Warnings<Warning>,
) -> PictureLook {
let geometry = picture_geometry(doc, props, warnings);
let turned = doc.child(props, A, "xfrm").is_some_and(|xfrm| {
let flag = |name| doc.attribute(xfrm, None, name).is_some_and(crate::boolean);
flag("flipH")
|| flag("flipV")
|| doc
.attribute(xfrm, None, "rot")
.is_some_and(|rot| rot.trim().parse::<i64>() != Ok(0))
});
let (raw_shadow, soft_edge, glow, raw_reflection) =
effect::picture_effects_of(doc, props, warnings);
let shadow = raw_shadow.filter(|shadow| {
let fixed = !shadow.turns_with_shape() || !turned;
if !fixed {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::Shadow,
});
}
fixed
});
let reflection = raw_reflection.filter(|reflection| {
let fixed = !reflection.turns_with_shape() || !turned;
if !fixed {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::Reflection,
});
}
fixed
});
let line = doc.child(props, A, "ln").and_then(|ln| {
let line = picture_line(doc, ln, warnings);
let filled = color_holder(doc, ln).is_some() || other_fill(doc, ln).is_some();
if line.is_none() && filled {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::PictureLine,
});
}
line
});
PictureLook {
geometry,
line,
shadow,
soft_edge,
glow,
reflection,
}
}
fn picture_line(
doc: &Document,
ln: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<PictureLine> {
let (holder, None) = color_holder(doc, ln)? else {
return None;
};
let compound = enumeration(doc, ln, "cmpd", (COMPOUND, warnings)).unwrap_or_default();
if compound != CompoundLine::Single
|| !matches!(read_dash(doc, ln), ReadDash::Omitted | ReadDash::Solid)
{
return None;
}
let width = emus_of(doc, ln, "w", warnings).or_else(|| Length::from_emus(DEFAULT_LINE_EMUS))?;
Some(PictureLine {
color: DrawColor::read(doc, holder, warnings)?,
width,
})
}
#[must_use]
pub fn outside_ring(frame: Edges<Length>, width: Length, color: Rgb) -> Item {
let width = width.max(THINNEST);
let grown = Edges {
left: frame.left - width,
top: frame.top - width,
right: frame.right + width,
bottom: frame.bottom + width,
};
let mut ring = rounded(grown, width.div_toward_zero(2));
ring.extend(rounded(frame, Length::ZERO));
path(ring, color, FillRule::EvenOdd)
}
fn round_radius(frame: Edges<Length>, adjust: i64) -> Length {
let shorter = frame.width().min(frame.height());
let share = adjust.clamp(0, HALF_SIDE_SHARE);
(shorter * share)
.div_toward_zero(DRAWING_WHOLE)
.max(Length::ZERO)
}
#[must_use]
pub fn picture_clip_path(
geometry: &Geometry,
frame: Edges<Length>,
) -> Option<(Vec<PathCommand>, FillRule)> {
match geometry {
Geometry::RoundRect(adjust) => Some((
rounded(frame, round_radius(frame, *adjust)),
FillRule::EvenOdd,
)),
Geometry::Ellipse => Some((ellipse(frame), FillRule::EvenOdd)),
Geometry::Custom(custom) => {
let place = Place {
frame,
flip: [false, false],
quarters: 0,
};
let (filled, _) = custom::fill_and_stroke(
custom,
&place,
Some(Rgb::BLACK),
None,
None,
LineEnds::default(),
)
.ok()?;
let filled = filled?;
Some((filled.commands, filled.fill_rule))
}
Geometry::Rect | Geometry::Line | Geometry::Other => None,
}
}
#[must_use]
pub fn picture_outside_ring(
geometry: &Geometry,
frame: Edges<Length>,
width: Length,
color: Rgb,
) -> Option<Item> {
let width = width.max(THINNEST);
match geometry {
Geometry::Rect | Geometry::Line | Geometry::Other => {
Some(outside_ring(frame, width, color))
}
Geometry::RoundRect(adjust) => {
let inner_r = round_radius(frame, *adjust);
let outer_r = if inner_r == Length::ZERO {
width.div_toward_zero(2)
} else {
inner_r + width
};
let mut ring = rounded(grow_edges(frame, width), outer_r);
ring.extend(rounded(frame, inner_r));
Some(path(ring, color, FillRule::EvenOdd))
}
Geometry::Ellipse => {
let mut ring = ellipse(grow_edges(frame, width));
ring.extend(ellipse(frame));
Some(path(ring, color, FillRule::EvenOdd))
}
Geometry::Custom(custom) => {
let place = Place {
frame,
flip: [false, false],
quarters: 0,
};
let (_, stroked) = custom::fill_and_stroke(
custom,
&place,
None,
Some((color, width.div_toward_zero(2))),
None,
LineEnds::default(),
)
.ok()?;
stroked.map(Item::Path)
}
}
}
const OTHER_FILLS: [(&str, Option<Feature>); 3] = [
("blipFill", None),
("pattFill", Some(Feature::PatternFill)),
("grpFill", Some(Feature::GroupFill)),
];
fn other_fill(doc: &Document, node: NodeId) -> Option<(&'static str, Option<Feature>)> {
OTHER_FILLS
.into_iter()
.find(|(name, _)| doc.child(node, A, name).is_some())
}
type ReadFill = (
Option<DrawColor>,
Option<ShapeFillGradient>,
Option<Edges<Length>>,
Option<StyleReference>,
);
fn explicit_fill(
doc: &Document,
props: NodeId,
area: bool,
gradient_frame: Option<Edges<Length>>,
warnings: &mut Warnings<Warning>,
) -> Option<ReadFill> {
if doc.child(props, A, "noFill").is_some() {
return Some((None, None, None, None));
}
if let Some(solid) = doc.child(props, A, "solidFill") {
return Some((DrawColor::read(doc, solid, warnings), None, None, None));
}
if let Some(grad_node) = doc.child(props, A, "gradFill") {
return Some(read_grad_fill(
doc,
grad_node,
area,
gradient_frame,
warnings,
));
}
if doc.child(props, A, "blipFill").is_some() {
if area && gradient_frame.is_some() {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::PictureFill,
});
}
return Some((None, None, None, None));
}
if doc.child(props, A, "pattFill").is_some() {
if area {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::PatternFill,
});
}
return Some((None, None, None, None));
}
None
}
fn read_grad_fill(
doc: &Document,
grad_node: NodeId,
area: bool,
gradient_frame: Option<Edges<Length>>,
warnings: &mut Warnings<Warning>,
) -> ReadFill {
if area {
let mut grad_warnings = Warnings::new();
if let Some(gradient) = ShapeFillGradient::read_shape(doc, grad_node, &mut grad_warnings) {
warnings.extend(grad_warnings, std::convert::identity);
return (gradient.first_color(), Some(gradient), gradient_frame, None);
}
warnings.push(Warning::FeatureNotSupported {
feature: Feature::GradientFill,
});
}
let stop = doc
.child(grad_node, A, "gsLst")
.and_then(|list| doc.child(list, A, "gs"))
.unwrap_or(grad_node);
(DrawColor::read(doc, stop, warnings), None, None, None)
}
fn fill(
doc: &Document,
(props, reference): (Option<NodeId>, Option<(usize, NodeId)>),
area: bool,
group_fill: Option<GroupFill>,
warnings: &mut Warnings<Warning>,
) -> ReadFill {
if let Some(props) = props {
if let Some(found) = explicit_fill(doc, props, area, None, warnings) {
return found;
}
if doc.child(props, A, "grpFill").is_some() {
return resolve_group_fill_element(doc, area, group_fill, warnings);
}
}
let Some((index, node)) = reference.filter(|(index, _)| *index > 0) else {
return (None, None, None, None);
};
let style = area.then_some(StyleReference::Fill(index));
(DrawColor::read(doc, node, warnings), None, None, style)
}
fn resolve_group_fill_element(
doc: &Document,
area: bool,
group_fill: Option<GroupFill>,
warnings: &mut Warnings<Warning>,
) -> ReadFill {
let Some(group_fill) = group_fill else {
if area {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::GroupFill,
});
}
return (None, None, None, None);
};
let Some(group_props) = group_fill.props else {
return (None, None, None, None);
};
explicit_fill(doc, group_props, area, Some(group_fill.frame), warnings)
.unwrap_or((None, None, None, None))
}
fn color_holder(doc: &Document, node: NodeId) -> Option<(NodeId, Option<Feature>)> {
if let Some(solid) = doc.child(node, A, "solidFill") {
return Some((solid, None));
}
let gradient = doc.child(node, A, "gradFill")?;
let stop = doc
.child(gradient, A, "gsLst")
.and_then(|list| doc.child(list, A, "gs"))
.unwrap_or(gradient);
Some((stop, Some(Feature::GradientFill)))
}
fn line(
doc: &Document,
(props, reference): (Option<NodeId>, Option<(usize, NodeId)>),
open: bool,
warnings: &mut Warnings<Warning>,
) -> (Option<Stroke>, [Option<StyleReference>; 3]) {
let own = props.and_then(|p| doc.child(p, A, "ln"));
let reference = reference.filter(|(index, _)| *index > 0);
if own.is_some_and(|ln| doc.child(ln, A, "noFill").is_some()) {
return (None, [None; 3]);
}
let own_holder = own.and_then(|ln| color_holder(doc, ln));
let feature = match own_holder {
Some((_, feature)) => feature,
None => own
.filter(|ln| other_fill(doc, *ln).is_some())
.map(|_| Feature::LineFill),
};
if let Some(feature) = feature {
warnings.push(Warning::FeatureNotSupported { feature });
}
let style = match own_holder {
Some(_) => None,
None => reference.map(|(index, _)| StyleReference::Line(index)),
};
let holder = own_holder
.map(|(node, _)| node)
.or_else(|| reference.map(|(_, node)| node));
let Some(color) = holder.and_then(|holder| DrawColor::read(doc, holder, warnings)) else {
return (None, [None; 3]);
};
let index = reference.map(|(index, _)| index);
let (dash, cap, ends, dash_style, ends_style) =
line_decorations(doc, own, index, open, warnings);
let styles = [style, dash_style, ends_style];
let width = own
.and_then(|ln| emus_of(doc, ln, "w", warnings))
.map(Width::Exact)
.or_else(|| index.map(Width::Style))
.unwrap_or(Width::Exact(
Length::from_emus(DEFAULT_LINE_EMUS).unwrap_or(Length::ZERO),
));
let in_style = match style {
Some(StyleReference::Line(index)) => LineStyleColor::Style(index),
_ => LineStyleColor::Own,
};
(
Some(Stroke {
color,
width,
in_style,
dash,
cap,
ends,
}),
styles,
)
}
fn line_decorations(
doc: &Document,
own: Option<NodeId>,
index: Option<usize>,
open: bool,
warnings: &mut Warnings<Warning>,
) -> (
StrokeDash,
StrokeCapSource,
StrokeEnds,
Option<StyleReference>,
Option<StyleReference>,
) {
let own_dash = own.map_or(ReadDash::Omitted, |ln| read_dash(doc, ln));
if own_dash == ReadDash::Unsupported {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::LineDash,
});
}
let own_ends = own.map_or(ReadEnds::Omitted, |ln| read_ends(doc, ln));
if open && own_ends == ReadEnds::Unsupported {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::LineEnd,
});
}
let dash_style = index
.filter(|_| own_dash == ReadDash::Omitted)
.map(StyleReference::LineDash);
let ends_style = index
.filter(|_| open && own_ends == ReadEnds::Omitted)
.map(StyleReference::LineEnds);
let dash = match own_dash {
ReadDash::Omitted => index.map_or(StrokeDash::Own(None), StrokeDash::Style),
ReadDash::Solid | ReadDash::Unsupported => StrokeDash::Own(None),
ReadDash::Dashed(dash) => StrokeDash::Own(Some(dash)),
};
let cap = match own.and_then(|ln| read_cap(doc, ln)) {
Some(cap) => StrokeCapSource::Own(cap),
None => index.map_or(StrokeCapSource::Default, StrokeCapSource::Style),
};
let ends = match own_ends {
ReadEnds::Omitted => index.map_or(StrokeEnds::Own(LineEnds::default()), StrokeEnds::Style),
ReadEnds::Present(ends) => StrokeEnds::Own(ends),
ReadEnds::Unsupported => StrokeEnds::Own(LineEnds::default()),
};
(dash, cap, ends, dash_style, ends_style)
}
fn rect_dash_points(shown: Edges<Length>) -> Vec<Point> {
let Edges {
left,
top,
right,
bottom,
} = shown;
vec![
point(left, bottom),
point(right, bottom),
point(right, top),
point(left, top),
point(left, bottom),
]
}
const fn point(x: Length, y: Length) -> Point {
Point { x, y }
}
fn path(commands: Vec<PathCommand>, color: Rgb, fill_rule: FillRule) -> Item {
Item::Path(PathItem {
commands,
color,
fill_rule,
})
}
fn rounded(shown: Edges<Length>, radius: Length) -> Vec<PathCommand> {
let Edges {
left,
top,
right,
bottom,
} = shown;
let r = radius
.min((right - left).div_toward_zero(2))
.min((bottom - top).div_toward_zero(2))
.max(Length::ZERO);
if r == Length::ZERO {
return vec![
PathCommand::MoveTo(point(left, top)),
PathCommand::LineTo(point(right, top)),
PathCommand::LineTo(point(right, bottom)),
PathCommand::LineTo(point(left, bottom)),
PathCommand::Close,
];
}
let k = stroke::kappa(r);
vec![
PathCommand::MoveTo(point(left + r, top)),
PathCommand::LineTo(point(right - r, top)),
PathCommand::CubicTo(
point(right - r + k, top),
point(right, top + r - k),
point(right, top + r),
),
PathCommand::LineTo(point(right, bottom - r)),
PathCommand::CubicTo(
point(right, bottom - r + k),
point(right - r + k, bottom),
point(right - r, bottom),
),
PathCommand::LineTo(point(left + r, bottom)),
PathCommand::CubicTo(
point(left + r - k, bottom),
point(left, bottom - r + k),
point(left, bottom - r),
),
PathCommand::LineTo(point(left, top + r)),
PathCommand::CubicTo(
point(left, top + r - k),
point(left + r - k, top),
point(left + r, top),
),
PathCommand::Close,
]
}
fn ellipse(shown: Edges<Length>) -> Vec<PathCommand> {
let Edges {
left,
top,
right,
bottom,
} = shown;
let (cx, cy) = (
(left + right).div_toward_zero(2),
(top + bottom).div_toward_zero(2),
);
let control = |side: Length| stroke::kappa(side.div_toward_zero(2));
let (kx, ky) = (control(right - left), control(bottom - top));
vec![
PathCommand::MoveTo(point(cx, top)),
PathCommand::CubicTo(point(cx + kx, top), point(right, cy - ky), point(right, cy)),
PathCommand::CubicTo(
point(right, cy + ky),
point(cx + kx, bottom),
point(cx, bottom),
),
PathCommand::CubicTo(
point(cx - kx, bottom),
point(left, cy + ky),
point(left, cy),
),
PathCommand::CubicTo(point(left, cy - ky), point(cx - kx, top), point(cx, top)),
PathCommand::Close,
]
}
fn stroke_line(ends: [(Length, Length); 2], half: Length, color: Rgb) -> Option<Item> {
stroke_band(ends, [half, -half], color)
}
fn compound_line(
ends: [(Length, Length); 2],
half: Length,
color: Rgb,
parts: &[i64],
sign: i64,
) -> Vec<Item> {
let total: i64 = parts.iter().sum();
if total <= 0 || parts.iter().any(|part| *part <= 0) {
return Vec::new();
}
let mut used = 0;
parts
.iter()
.enumerate()
.filter_map(|(index, part)| {
let low = (half * (2 * used)).div_toward_zero(total) - half;
used += part;
let high = (half * (2 * used)).div_toward_zero(total) - half;
(index % 2 == 0)
.then(|| stroke_band(ends, [low * sign, high * sign], color))
.flatten()
})
.collect()
}
fn stroke_band(
[(x0, y0), (x1, y1)]: [(Length, Length); 2],
[low, high]: [Length; 2],
color: Rgb,
) -> Option<Item> {
let (dx, dy) = (i128::from((x1 - x0).units()), i128::from((y1 - y0).units()));
let length = (dx * dx + dy * dy).isqrt();
if length == 0 {
return None;
}
let side = |d: i128, offset: Length| {
Length::from_units(i64::try_from(d * i128::from(offset.units()) / length).unwrap_or(0))
};
let (lx, ly) = (side(-dy, low), side(dx, low));
let (hx, hy) = (side(-dy, high), side(dx, high));
let commands = vec![
PathCommand::MoveTo(point(x0 + lx, y0 + ly)),
PathCommand::LineTo(point(x1 + lx, y1 + ly)),
PathCommand::LineTo(point(x1 + hx, y1 + hy)),
PathCommand::LineTo(point(x0 + hx, y0 + hy)),
PathCommand::Close,
];
Some(path(commands, color, FillRule::NonZero))
}
#[cfg(test)]
mod tests;