Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge remote-tracking branch 'origin/main' into effect-blend-modes

moppeeerb6fec896f9f7
diff --cc crates/doc/src/item/effects.rs
index 000000000,fa416643b..46aac2e95
mode 000000,100644..100644
--- a/crates/doc/src/item/effects.rs
+++ b/crates/doc/src/item/effects.rs
@@@ -1,0 -1,345 +1,363 @@@
+ use super::{BlendMode, Deserialize, Serialize, is_default};
+
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct DropShadow {
+ pub on: bool,
+ pub color: String,
+ pub opacity: f32,
+ pub angle: f64,
+ /// Use Global Light (the document angle instead of `angle`).
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub global_light: bool,
+ pub distance: f64,
+ pub size: f64,
+ pub spread: f64,
++ /// How the shadow blends with what's behind it (InDesign: Multiply). A document saved before
++ /// effects had modes reads Normal, as they were drawn then.
++ #[serde(default = "normal_blend")]
++ pub mode: BlendMode,
++}
++
++/// The blend of an effect saved before effects had one.
++fn normal_blend() -> BlendMode {
++ BlendMode::Normal
+ }
+
+ impl Default for DropShadow {
+ fn default() -> Self {
+ DropShadow {
+ on: false,
++ mode: BlendMode::Multiply,
+ color: designcraft_color::swatch::BLACK.into(),
+ opacity: 0.75,
+ angle: 120.0,
+ distance: 7.0,
+ size: 5.0,
+ spread: 0.0,
+ global_light: false,
+ }
+ }
+ }
+
+ /// Inner shadow: a blurred, offset shadow inside the object's edge.
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct InnerShadow {
+ pub on: bool,
+ pub color: String,
+ pub opacity: f32,
+ pub angle: f64,
+ /// Use Global Light (the document angle instead of `angle`).
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub global_light: bool,
+ pub distance: f64,
+ pub size: f64,
+ /// Percentage (0–100) of `size` that hardens the edge instead of blurring it.
+ pub choke: f64,
++ /// How the shadow blends with the object (InDesign: Multiply; Normal when saved before).
++ #[serde(default = "normal_blend")]
++ pub mode: BlendMode,
+ }
+
+ impl Default for InnerShadow {
+ fn default() -> Self {
+ InnerShadow {
+ on: false,
++ mode: BlendMode::Multiply,
+ color: designcraft_color::swatch::BLACK.into(),
+ opacity: 0.75,
+ angle: 120.0,
+ distance: 7.0,
+ size: 7.0,
+ choke: 0.0,
+ global_light: false,
+ }
+ }
+ }
+
+ /// Outer glow: a blurred silhouette around the object, without offset.
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct OuterGlow {
+ pub on: bool,
+ pub color: String,
+ pub opacity: f32,
+ pub size: f64,
+ /// Percentage (0–100) of `size` that grows the silhouette instead of blurring it.
+ pub spread: f64,
++ /// How the glow blends with what's behind it (InDesign: Screen; Normal when saved before).
++ #[serde(default = "normal_blend")]
++ pub mode: BlendMode,
+ }
+
+ impl Default for OuterGlow {
+ fn default() -> Self {
- OuterGlow { on: false, color: designcraft_color::swatch::BLACK.into(), opacity: 0.75, size: 7.0, spread: 0.0 }
++ // InDesign starts a glow screened in white.
++ OuterGlow { on: false, color: designcraft_color::swatch::PAPER.into(), opacity: 0.75, size: 7.0, spread: 0.0, mode: BlendMode::Screen }
+ }
+ }
+
+ #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct Effects {
+ /// Drop shadow. `size` is the blur size; `spread` is a percentage (0–100) of it that grows
+ /// the silhouette instead of blurring it.
+ pub drop_shadow: DropShadow,
+ /// Basic feather width (0 = off).
+ pub feather: f64,
+ /// Basic feather's choke and corners.
+ #[serde(skip_serializing_if = "is_default")]
+ pub feather_options: FeatherOptions,
+ #[serde(skip_serializing_if = "is_default")]
+ pub inner_shadow: InnerShadow,
+ #[serde(skip_serializing_if = "is_default")]
+ pub outer_glow: OuterGlow,
+ #[serde(skip_serializing_if = "is_default")]
+ pub gradient_feather: GradientFeather,
+ #[serde(skip_serializing_if = "is_default")]
+ pub inner_glow: InnerGlow,
+ #[serde(skip_serializing_if = "is_default")]
+ pub bevel: Bevel,
+ #[serde(skip_serializing_if = "is_default")]
+ pub satin: Satin,
+ #[serde(skip_serializing_if = "is_default")]
+ pub directional_feather: DirectionalFeather,
+ }
+
+ /// Basic Feather › Corners: how the fade follows the shape's corners.
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ pub enum FeatherCorners {
+ /// Mitred: the fade keeps the corners sharp.
+ Sharp,
+ /// The fade rounds the corners by its width.
+ Rounded,
+ /// From opaque to transparent, softly (InDesign's default).
+ #[default]
+ Diffused,
+ }
+
+ /// Basic Feather options besides its width.
+ #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct FeatherOptions {
+ /// Percentage (0–100) of the width that stays opaque: the fade gets shorter.
+ pub choke: f64,
+ pub corners: FeatherCorners,
+ }
+
+ /// Inner/Outer Glow › Technique.
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ pub enum GlowTechnique {
+ /// A soft, blurred glow.
+ #[default]
+ Softer,
+ /// A glow that keeps closer to the shape's edges.
+ Precise,
+ }
+
+ /// Directional Feather: each side fades over its own width (item space, before rotation).
+ #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct DirectionalFeather {
+ pub on: bool,
+ /// Top, left, bottom, right widths in points.
+ pub widths: [f64; 4],
+ }
+
+ /// Inner Glow: a glow inside the edge (or from the centre).
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct InnerGlow {
+ pub on: bool,
+ pub color: String,
+ pub opacity: f32,
+ pub size: f64,
+ /// Percentage (0–100) of `size` that hardens the glow.
+ pub choke: f64,
+ /// Glow from the centre instead of the edges.
+ pub center: bool,
+ /// How the glow blends with the object (InDesign: Screen).
+ pub mode: BlendMode,
+ pub technique: GlowTechnique,
+ }
+
+ impl Default for InnerGlow {
+ fn default() -> Self {
+ InnerGlow {
+ on: false,
+ color: designcraft_color::swatch::PAPER.into(),
+ opacity: 0.75,
+ size: 7.0,
+ choke: 0.0,
+ center: false,
+ mode: BlendMode::Screen,
+ technique: GlowTechnique::Softer,
+ }
+ }
+ }
+
+ /// Bevel and Emboss (inner bevel): a highlight on the lit edges, a shadow on the others.
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct Bevel {
+ pub on: bool,
+ pub size: f64,
+ /// Depth in percent (scales the highlight and shadow offset).
+ pub depth: f64,
+ pub angle: f64,
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub global_light: bool,
+ pub highlight: String,
+ pub highlight_opacity: f32,
+ pub shadow: String,
+ pub shadow_opacity: f32,
+ }
+
+ impl Default for Bevel {
+ fn default() -> Self {
+ Bevel {
+ on: false,
+ size: 7.0,
+ depth: 100.0,
+ angle: 120.0,
+ global_light: true,
+ highlight: designcraft_color::swatch::PAPER.into(),
+ highlight_opacity: 0.75,
+ shadow: designcraft_color::swatch::BLACK.into(),
+ shadow_opacity: 0.75,
+ }
+ }
+ }
+
+ /// Satin: soft interior shading from two offset copies of the shape.
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct Satin {
+ pub on: bool,
+ pub color: String,
+ pub opacity: f32,
+ pub angle: f64,
+ pub distance: f64,
+ pub size: f64,
+ pub invert: bool,
+ }
+
+ impl Default for Satin {
+ fn default() -> Self {
+ Satin { on: false, color: designcraft_color::swatch::BLACK.into(), opacity: 0.5, angle: 120.0, distance: 7.0, size: 7.0, invert: false }
+ }
+ }
+
+ /// Gradient Feather: the object fades from `start` to `end` opacity along a gradient.
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct GradientFeather {
+ pub on: bool,
+ pub radial: bool,
+ /// Degrees (linear), when no vector was dragged.
+ pub angle: f64,
+ pub start: f32,
+ pub end: f32,
+ /// Gradient Feather tool vector in the item's space: start and end (linear), centre and
+ /// radius point (radial).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub vector: Option<[f64; 4]>,
+ }
+
+ impl Default for GradientFeather {
+ fn default() -> Self {
+ GradientFeather { on: false, radial: false, angle: 0.0, start: 1.0, end: 0.0, vector: None }
+ }
+ }
+
+ impl GradientFeather {
+ /// The gradient's two points in item space for an object with inner bounds `b`.
+ pub fn points(&self, b: designcraft_geom::Rect) -> (designcraft_geom::Point, designcraft_geom::Point) {
+ use designcraft_geom::{Point, Vec2};
+ if let Some([x0, y0, x1, y1]) = self.vector {
+ return (Point::new(x0, y0), Point::new(x1, y1));
+ }
+ let c = b.center();
+ if self.radial {
+ return (c, c + Vec2::new(b.width().max(b.height()) / 2.0, 0.0));
+ }
+ let a = self.angle.to_radians();
+ let d = Vec2::new(a.cos(), -a.sin());
+ let half = (b.width() * d.x.abs() + b.height() * d.y.abs()) / 2.0;
+ (c - d * half, c + d * half)
+ }
+ }
+
+ impl Effects {
+ /// These effects with opacities in 0–1, percentages in 0–100 and sizes, widths and distances
+ /// not below 0, or an error naming the first value that isn't a finite number.
+ pub fn sanitized(mut self) -> Result<Effects, String> {
+ fn finite(name: &str, v: f64) -> Result<f64, String> {
+ if v.is_finite() { Ok(v) } else { Err(format!("{name} must be a finite number")) }
+ }
+ let len = |name: &str, v: f64| finite(name, v).map(|v| v.max(0.0));
+ let pct = |name: &str, v: f64| finite(name, v).map(|v| v.clamp(0.0, 100.0));
+ let opacity = |name: &str, v: f32| finite(name, f64::from(v)).map(|v| v.clamp(0.0, 1.0) as f32);
+ let ds = &mut self.drop_shadow;
+ ds.opacity = opacity("dropShadow.opacity", ds.opacity)?;
+ ds.angle = finite("dropShadow.angle", ds.angle)?;
+ ds.distance = len("dropShadow.distance", ds.distance)?;
+ ds.size = len("dropShadow.size", ds.size)?;
+ ds.spread = pct("dropShadow.spread", ds.spread)?;
+ self.feather = len("feather", self.feather)?;
+ let e = &mut self.inner_shadow;
+ e.opacity = opacity("innerShadow.opacity", e.opacity)?;
+ e.angle = finite("innerShadow.angle", e.angle)?;
+ e.distance = len("innerShadow.distance", e.distance)?;
+ e.size = len("innerShadow.size", e.size)?;
+ e.choke = pct("innerShadow.choke", e.choke)?;
+ let e = &mut self.outer_glow;
+ e.opacity = opacity("outerGlow.opacity", e.opacity)?;
+ e.size = len("outerGlow.size", e.size)?;
+ e.spread = pct("outerGlow.spread", e.spread)?;
+ let e = &mut self.gradient_feather;
+ e.angle = finite("gradientFeather.angle", e.angle)?;
+ e.start = opacity("gradientFeather.start", e.start)?;
+ e.end = opacity("gradientFeather.end", e.end)?;
+ if let Some(v) = &mut e.vector {
+ for c in v.iter_mut() {
+ *c = finite("gradientFeather.vector", *c)?;
+ }
+ }
+ let e = &mut self.inner_glow;
+ e.opacity = opacity("innerGlow.opacity", e.opacity)?;
+ e.size = len("innerGlow.size", e.size)?;
+ e.choke = pct("innerGlow.choke", e.choke)?;
+ let e = &mut self.bevel;
+ e.size = len("bevel.size", e.size)?;
+ e.depth = len("bevel.depth", e.depth)?;
+ e.angle = finite("bevel.angle", e.angle)?;
+ e.highlight_opacity = opacity("bevel.highlightOpacity", e.highlight_opacity)?;
+ e.shadow_opacity = opacity("bevel.shadowOpacity", e.shadow_opacity)?;
+ let e = &mut self.satin;
+ e.opacity = opacity("satin.opacity", e.opacity)?;
+ e.angle = finite("satin.angle", e.angle)?;
+ e.distance = len("satin.distance", e.distance)?;
+ e.size = len("satin.size", e.size)?;
+ for w in self.directional_feather.widths.iter_mut() {
+ *w = len("directionalFeather.widths", *w)?;
+ }
+ Ok(self)
+ }
+
+ /// Any effect drawn with soft (raster) filters?
+ pub fn any(&self) -> bool {
+ self.drop_shadow.on
+ || self.feather > 0.0
+ || self.inner_shadow.on
+ || self.outer_glow.on
+ || self.gradient_feather.on
+ || self.inner_glow.on
+ || self.bevel.on
+ || self.satin.on
+ || self.directional_feather.on
+ }
+ }
diff --cc crates/idml/src/export/item.rs
index 000000000,5ed93879b..371718b65
mode 000000,100644..100644
--- a/crates/idml/src/export/item.rs
+++ b/crates/idml/src/export/item.rs
@@@ -1,0 -1,515 +1,516 @@@
+ use super::common::{affine_s, bool_s, p, pct, uid, with_props};
+ use super::{
+ Affine, ColumnsKind, Content, El, Ex, HashSet, Item, Node, OBJECT_BUILTINS, PathData, Shape, TextFrameOptions, base64_encode, escape_id, names,
+ num, pt,
+ };
+
+ impl<'a> Ex<'a> {
+ pub(super) fn item_el(&mut self, it: &Item, xf: Affine) -> El {
+ let d = self.d;
+ let path_text = matches!(&it.content, Content::Text(t) if t.options.path.is_some());
+ let tag = match (&it.content, it.shape) {
+ (Content::Text(_), _) if path_text => match it.shape {
+ Shape::GraphicLine => "GraphicLine",
+ Shape::Oval => "Oval",
+ Shape::Rectangle => "Rectangle",
+ _ => "Polygon",
+ },
+ (Content::Text(_), _) => "TextFrame",
+ (Content::Group { .. }, Shape::Group) => "Group",
+ (_, Shape::Oval) => "Oval",
+ (_, Shape::Polygon) | (_, Shape::Path) => "Polygon",
+ (_, Shape::GraphicLine) => "GraphicLine",
+ _ => "Rectangle",
+ };
+ let mut el = El::new(tag).attr("Self", uid(it.id.0));
+ if let Some(o) = it.overrides {
+ el.set("OverriddenPageItem", uid(o.0));
+ }
+ if let Content::Text(t) = &it.content
+ && let Some(pt) = &t.options.path
+ {
+ // Type on a path: a TextPath child holds the story.
+ let len = designcraft_geom::warp::PathWarp::new(&it.path.to_bezpath(), false).length();
+ el.push(
+ El::new("TextPath")
+ .attr("Self", format!("{}tp", uid(it.id.0)))
+ .attr("ParentStory", uid(t.story.0))
+ .attr("PreviousTextFrame", "n")
+ .attr("NextTextFrame", "n")
+ .attr("PathEffect", "RainbowPathEffect")
+ .attr("PathAlignment", "CenterPathAlignment")
+ .attr("TextAlignment", names::path_align_out(pt.align))
+ .attr("FlipPathEffect", if pt.flip { "Flipped" } else { "NotFlipped" })
+ .attr("StartBracket", num(pt.start))
+ .attr("EndBracket", num(pt.end.map_or(len, |e| e.min(len)))),
+ );
+ } else if let Content::Text(t) = &it.content {
+ let (prev, next) = self.threads.get(&it.id.0).copied().unwrap_or((None, None));
+ el.set("ParentStory", uid(t.story.0));
+ el.set("PreviousTextFrame", prev.map(uid).unwrap_or_else(|| "n".into()));
+ el.set("NextTextFrame", next.map(uid).unwrap_or_else(|| "n".into()));
+ }
+ if tag != "Group" {
+ el.set(
+ "ContentType",
+ match it.content {
+ Content::Text(_) => "TextType",
+ Content::Graphic(_) => "GraphicType",
+ _ => "Unassigned",
+ },
+ );
+ }
+ el.set("Name", if it.name.is_empty() { "$ID/".to_string() } else { it.name.clone() });
+ el.set("ItemLayer", uid(it.layer.0));
+ el.set("Visible", bool_s(!it.hidden));
+ el.set("Locked", bool_s(it.locked));
+ el.set("Nonprinting", bool_s(it.nonprinting));
+ let os = if it.object_style.is_empty() { designcraft_doc::NO_OBJECT_STYLE } else { &it.object_style };
+ el.set("AppliedObjectStyle", names::style_self("ObjectStyle", OBJECT_BUILTINS, os));
+ el.set("ItemTransform", affine_s(xf));
+ el.set("FillColor", self.sw(&it.fill.swatch));
+ el.set("FillTint", pct(it.fill.tint as f64));
+ el.set("OverprintFill", bool_s(it.fill.overprint));
+ if let Some([x0, y0, x1, y1]) = it.fill.gradient_vector {
+ // Gradient Swatch tool vector: start, length and angle in the item's space.
+ el.set("GradientFillStart", format!("{} {}", num(x0), num(y0)));
+ el.set("GradientFillLength", num((x1 - x0).hypot(y1 - y0)));
+ el.set("GradientFillAngle", num((-(y1 - y0)).atan2(x1 - x0).to_degrees()));
+ } else if let Some(a) = it.fill.gradient_angle {
+ el.set("GradientFillAngle", num(a));
+ }
+ // The same on the stroke.
+ if let Some([x0, y0, x1, y1]) = it.stroke.gradient_vector {
+ el.set("GradientStrokeStart", format!("{} {}", num(x0), num(y0)));
+ el.set("GradientStrokeLength", num((x1 - x0).hypot(y1 - y0)));
+ el.set("GradientStrokeAngle", num((-(y1 - y0)).atan2(x1 - x0).to_degrees()));
+ } else if let Some(a) = it.stroke.gradient_angle {
+ el.set("GradientStrokeAngle", num(a));
+ }
+ self.stroke_attrs(&mut el, &it.stroke);
+ // Corner options: map path-order corners to the named corners by geometry.
+ if !it.corners.is_none() {
+ let names_by_index = corner_names(&it.path);
+ for (i, c) in it.corners.corners.iter().enumerate() {
+ let n = names_by_index[i];
+ el.set(&format!("{n}CornerOption"), names::corner_out(c.shape));
+ el.set(&format!("{n}CornerRadius"), num(c.size));
+ }
+ }
+ let mut props = Vec::new();
+ if tag != "Group" && !it.path.is_empty() {
+ props.push(path_geometry(&it.path));
+ }
+ let mut el = with_props(el, props);
+ self.append_transparency(&mut el, it, os);
+ if let Content::Text(t) = &it.content {
+ el.push(text_frame_pref(&t.options, &self.sw(&t.options.column_rule_color)));
+ if let Some(g) = t.options.baseline_grid {
+ el.push(
+ El::new("BaselineFrameGridOption")
+ .attr("UseCustomBaselineFrameGrid", "true")
+ .attr("StartingOffsetForBaselineFrameGrid", num(g.start))
+ .attr(
+ "BaselineFrameGridRelativeOption",
+ match g.relative_to {
+ designcraft_doc::FrameGridRelative::TopOfPage => "TopOfPageOfBaselineFrameGridRelativeOption",
+ designcraft_doc::FrameGridRelative::TopMargin => "TopOfMarginOfBaselineFrameGridRelativeOption",
+ designcraft_doc::FrameGridRelative::TopOfFrame => "TopOfFrameOfBaselineFrameGridRelativeOption",
+ designcraft_doc::FrameGridRelative::TopInset => "TopOfInsetOfBaselineFrameGridRelativeOption",
+ },
+ )
+ .attr("BaselineFrameGridIncrement", num(g.increment)),
+ );
+ }
+ }
+ el.push(text_wrap_pref(&it.wrap));
+ match &it.content {
+ Content::Group { items } => {
+ for c in items {
+ let e = self.item_el(c, c.xf);
+ el.push(e);
+ }
+ }
+ Content::Graphic(g) => {
+ if g.auto_fit != designcraft_doc::Fitting::None || g.fit_align != 4 || g.crop != [0.0; 4] {
+ el.push(
+ El::new("FrameFittingOption")
+ .attr("AutoFit", bool_s(g.auto_fit != designcraft_doc::Fitting::None))
+ .attr("TopCrop", num(g.crop[0]))
+ .attr("LeftCrop", num(g.crop[1]))
+ .attr("BottomCrop", num(g.crop[2]))
+ .attr("RightCrop", num(g.crop[3]))
+ .attr("FittingOnEmptyFrame", names::fitting_out(g.auto_fit))
+ .attr("FittingAlignment", names::anchor_out(g.fit_align)),
+ );
+ }
+ if let Some(asset) = d.assets.get(&g.asset) {
+ let e = self.image_el(asset, g);
+ el.push(e);
+ }
+ }
+ _ => {}
+ }
+ el
+ }
+
+ fn append_transparency(&self, el: &mut El, it: &Item, os: &str) {
+ // Transparency.
+ // An item whose style sets effects writes the effects it has turned off too, so that on
+ // import it doesn't take the style's.
+ let styled = self.d.styles.object_effects(os).is_some();
+ let ds = &it.effects.drop_shadow;
+ let (gf, df) = (&it.effects.gradient_feather, &it.effects.directional_feather);
+ if it.opacity < 1.0 || it.blend != designcraft_color::BlendMode::Normal || ds.on || it.effects.feather > 0.0 || gf.on || df.on || styled {
+ let mut t = El::new("TransparencySetting");
+ t.push(El::new("BlendingSetting").attr("BlendMode", names::blend_out(it.blend)).attr("Opacity", pct(it.opacity as f64)));
+ for c in self.effect_els(&it.effects, styled) {
+ t.push(c);
+ }
+ if df.on {
+ let [top, left, bottom, right] = df.widths;
+ t.push(
+ El::new("DirectionalFeatherSetting")
+ .attr("Applied", "true")
+ .attr("LeftWidth", num(left))
+ .attr("RightWidth", num(right))
+ .attr("TopWidth", num(top))
+ .attr("BottomWidth", num(bottom)),
+ );
+ }
+ if gf.on {
+ let mut g = El::new("GradientFeatherSetting").attr("Applied", "true").attr("Type", if gf.radial { "Radial" } else { "Linear" });
+ if let Some([x0, y0, x1, y1]) = gf.vector {
+ // Gradient Feather tool vector: start, length and angle in the item's space.
+ g.set("Angle", num((-(y1 - y0)).atan2(x1 - x0).to_degrees()));
+ g.set("Length", num((x1 - x0).hypot(y1 - y0)));
+ g.set("GradientStart", format!("{} {}", num(x0), num(y0)));
+ } else {
+ g.set("Angle", num(gf.angle));
+ }
+ let id = uid(it.id.0);
+ for (i, (opacity, location)) in [(gf.start, 0.0), (gf.end, 100.0)].into_iter().enumerate() {
+ let mut s = El::new("OpacityGradientStop")
+ .attr("Self", format!("{id}TransparencySetting1GradientFeatherSetting1OpacityGradientStop{i}"))
+ .attr("Opacity", pct(opacity as f64))
+ .attr("Location", num(location));
+ if i > 0 {
+ s.set("Midpoint", "50");
+ }
+ g.push(s);
+ }
+ t.push(g);
+ }
+ el.push(t);
+ }
+ }
+
+ /// The `TransparencySetting` children for `e`'s drop shadow and feather; `all` also writes the
+ /// effects that are off (`Mode="None"`), as an object style that sets effects does.
+ pub(super) fn effect_els(&self, e: &designcraft_doc::Effects, all: bool) -> Vec<El> {
+ let mut out = Vec::new();
+ let ds = &e.drop_shadow;
+ if ds.on || all {
+ let a = self.d.light_angle(ds.angle, ds.global_light).to_radians();
+ out.push(
+ El::new("DropShadowSetting")
+ .attr("Mode", if ds.on { "Drop" } else { "None" })
+ .attr("XOffset", num(-ds.distance * a.cos()))
+ .attr("YOffset", num(ds.distance * a.sin()))
+ .attr("Size", num(ds.size))
+ .attr("Spread", num(ds.spread))
+ .attr("Opacity", pct(ds.opacity as f64))
++ .attr("BlendMode", names::blend_out(ds.mode))
+ .attr("EffectColor", self.sw(&ds.color)),
+ );
+ }
+ if e.feather > 0.0 || all {
+ let corners = match e.feather_options.corners {
+ designcraft_doc::FeatherCorners::Sharp => "Sharp",
+ designcraft_doc::FeatherCorners::Rounded => "Rounded",
+ designcraft_doc::FeatherCorners::Diffused => "Diffusion",
+ };
+ out.push(
+ El::new("FeatherSetting")
+ .attr("Mode", if e.feather > 0.0 { "Standard" } else { "None" })
+ .attr("Width", num(e.feather))
+ .attr("ChokeAmount", num(e.feather_options.choke))
+ .attr("CornerType", corners),
+ );
+ }
+ out
+ }
+
+ fn image_el(&mut self, asset: &designcraft_doc::Asset, g: &designcraft_doc::Graphic) -> El {
+ let is_pdf = asset.mime == "application/pdf";
+ let is_eps = asset.mime == "application/postscript" || designcraft_images::is_eps(&asset.data);
+ let mut el = El::new(if is_eps {
+ "EPS"
+ } else if is_pdf {
+ "PDF"
+ } else {
+ "Image"
+ })
+ .attr("Self", self.fresh());
+ // A PDF is vector: its page size in `pixels` isn't a resolution, and a cropped graphic
+ // spans less than the page. An EPS's `pixels` is its preview raster, so it still counts.
+ if let Some((pw, ph)) = asset.pixels.filter(|_| !is_pdf)
+ && g.size.0 > 0.0
+ && g.size.1 > 0.0
+ {
+ el.set("ActualPpi", pt(pw as f64 * 72.0 / g.size.0, ph as f64 * 72.0 / g.size.1));
+ }
+ el.set("ItemTransform", affine_s(g.xf));
+ // The swatch that colours a greyscale or bitmap image; written only when it exists.
+ if !g.fill.is_none()
+ && let Some(id) = self.swatch_ids.get(&g.fill.swatch)
+ {
+ el.set("FillColor", id.clone());
+ el.set("FillTint", pct(g.fill.tint as f64));
+ }
+ let embed = !asset.data.is_empty() && (self.opts.embed_images || asset.link.is_none());
+ let mut props = Vec::new();
+ if embed {
+ let mut c = El::new("Contents");
+ c.children.push(Node::CData(base64_encode(&asset.data)));
+ props.push(c);
+ }
+ props.push(El::new("GraphicBounds").attr("Left", "0").attr("Top", "0").attr("Right", num(g.size.0)).attr("Bottom", num(g.size.1)));
+ let mut el = with_props(el, props);
+ if !g.wrap.is_default() {
+ el.push(text_wrap_pref(&g.wrap));
+ }
+ if let Some(c) = &g.clip {
+ el.push(clipping_settings(c));
+ }
+ if let Some(options) = &g.layer_options {
+ el.push(self.layer_option_el(options));
+ }
+ let uri = match &asset.link {
+ Some(l) => path_to_uri(l),
+ None => format!("file:{}", asset.name),
+ };
+ el.push(
+ El::new("Link")
+ .attr("Self", self.fresh())
+ .attr("AssetURL", "$ID/")
+ .attr("AssetID", "$ID/")
+ .attr("LinkResourceURI", uri)
+ .attr("LinkResourceFormat", format!("$ID/{}", format_name(if is_eps { "application/postscript" } else { &asset.mime })))
+ .attr("StoredState", if embed { "Embedded" } else { "Normal" })
+ .attr("LinkClassID", "35906")
+ .attr("LinkClientID", "257")
+ .attr("LinkResourceModified", "false")
+ .attr("LinkObjectModified", "false")
+ .attr("ShowInUI", "true")
+ .attr("CanEmbed", "true")
+ .attr("CanUnembed", "true")
+ .attr("CanPackage", "true")
+ .attr("ImportPolicy", "NoAutoImport")
+ .attr("ExportPolicy", "NoAutoExport"),
+ );
+ if is_pdf {
+ // `GraphicBounds` span the chosen box, as graphic space does. Without `PDFAttribute`
+ // the page would be cropped to its visible content, which changes the graphic's size
+ // and so its scale and position.
+ el.push(
+ El::new("PDFAttribute")
+ .attr("PageNumber", asset.page.saturating_add(1))
+ .attr("PDFCrop", names::pdf_crop_out(asset.pdf_crop))
+ .attr("TransparentBackground", "true"),
+ );
+ }
+ el
+ }
+ }
+
+ /// Style folder tree (names `A/B/C` → groups A, B).
+ #[derive(Default)]
+ pub(super) struct Group {
+ styles: Vec<El>,
+ groups: Vec<(String, Group)>,
+ }
+
+ impl Group {
+ pub(super) fn insert(&mut self, name: &str, el: El) {
+ let builtin = name.starts_with('[');
+ let mut segs: Vec<&str> = if builtin { vec![name] } else { name.split('/').collect() };
+ let _leaf = segs.pop();
+ let mut g = self;
+ for s in segs {
+ let i = match g.groups.iter().position(|(n, _)| n == s) {
+ Some(i) => i,
+ None => {
+ g.groups.push((s.to_string(), Group::default()));
+ g.groups.len() - 1
+ }
+ };
+ g = &mut g.groups[i].1;
+ }
+ g.styles.push(el);
+ }
+
+ pub(super) fn emit(self, parent: &mut El, kind: &str, path: &str) {
+ for s in self.styles {
+ parent.push(s);
+ }
+ for (name, g) in self.groups {
+ let full = if path.is_empty() { name.clone() } else { format!("{path}:{name}") };
+ let mut ge = El::new(kind).attr("Self", format!("{kind}/{}", escape_id(&full))).attr("Name", &name);
+ g.emit(&mut ge, kind, &full);
+ parent.push(ge);
+ }
+ }
+ }
+
+ /// `rule_color` is the IDML reference of the column rule's swatch.
+ /// `TextWrapPreference` of a page item or a placed graphic.
+ fn text_wrap_pref(w: &designcraft_doc::TextWrap) -> El {
+ with_props(
+ El::new("TextWrapPreference")
+ .attr("Inverse", bool_s(w.invert))
+ .attr("ApplyToMasterPageOnly", "false")
+ .attr("TextWrapSide", names::wrap_side_out(w.side))
+ .attr("TextWrapMode", names::wrap_mode_out(w.mode)),
+ w.path
+ .iter()
+ .filter(|p| !p.is_empty())
+ .map(path_geometry)
+ .chain([El::new("TextWrapOffset")
+ .attr("Top", num(w.offsets[0]))
+ .attr("Left", num(w.offsets[1]))
+ .attr("Bottom", num(w.offsets[2]))
+ .attr("Right", num(w.offsets[3]))])
+ .collect(),
+ )
+ .child(El::new("ContourOption").attr("ContourType", names::contour_type_out(w.contour)).attr("IncludeInsideEdges", "false"))
+ }
+
+ pub(super) fn text_frame_pref(o: &TextFrameOptions, rule_color: &str) -> El {
+ let mut inset = El::new("InsetSpacing").attr("type", "list");
+ for v in o.inset {
+ inset.push(p("ListItem", "unit", num(v)));
+ }
+ let el = El::new("TextFramePreference")
+ .attr("TextColumnCount", o.columns.max(1))
+ .attr("TextColumnGutter", num(o.gutter))
+ .attr("UseFixedColumnWidth", bool_s(o.columns_kind == ColumnsKind::FixedWidth))
+ .attr("UseFlexibleColumnWidth", bool_s(o.columns_kind == ColumnsKind::FlexibleWidth))
+ .attr("VerticalBalanceColumns", bool_s(o.balance_columns))
+ .attr("FirstBaselineOffset", names::first_baseline_out(o.first_baseline))
+ .attr("MinimumFirstBaselineOffset", num(o.first_baseline_min))
+ .attr("VerticalJustification", names::vj_out(o.vertical_justification))
+ .attr("VerticalThreshold", num(o.vj_paragraph_spacing_limit))
+ .attr("IgnoreWrap", bool_s(o.ignore_wrap))
+ .attr("AutoSizingType", names::auto_size_out(o.auto_size))
+ .attr("AutoSizingReferencePoint", names::REF_POINTS[(o.auto_size_ref as usize).min(8)])
+ .attr("UseMinimumHeightForAutoSizing", bool_s(o.auto_size_use_min_height))
+ .attr("MinimumHeightForAutoSizing", num(o.auto_size_min_height))
+ .attr("UseMinimumWidthForAutoSizing", bool_s(o.auto_size_use_min_width))
+ .attr("MinimumWidthForAutoSizing", num(o.auto_size_min_width))
+ .attr("UseNoLineBreaksForAutoSizing", bool_s(o.auto_size_no_line_breaks));
+ let el = if o.column_width > 0.0 { el.attr("TextColumnFixedWidth", num(o.column_width)) } else { el };
+ // Written on every frame: on import a frame takes any value it lacks from its object style.
+ let el = el
+ .attr("ColumnRuleOverride", bool_s(o.column_rule))
+ .attr("ColumnRuleStrokeWidth", num(o.column_rule_weight))
+ .attr("ColumnRuleStrokeColor", rule_color)
+ .attr("ColumnRuleStrokeTint", num(f64::from(o.column_rule_tint) * 100.0))
+ .attr("ColumnRuleOffset", num(o.column_rule_offset))
+ .attr("ColumnRuleTopInset", num(o.column_rule_top_inset))
+ .attr("ColumnRuleBottomInset", num(o.column_rule_bottom_inset))
+ .attr("ColumnRuleInsetChainOverride", bool_s(o.column_rule_top_inset == o.column_rule_bottom_inset));
+ with_props(el, vec![inset])
+ }
+
+ /// `<ClippingPathSettings>` with the outline (graphic space is the image's inner space, whose
+ /// `GraphicBounds` start at 0,0).
+ fn clipping_settings(c: &designcraft_doc::ClippingPath) -> El {
+ let mut geometry = path_geometry(&c.path);
+ geometry.name = "ClippingPathGeometry".into();
+ let el = El::new("ClippingPathSettings")
+ .attr("ClippingType", names::clipping_kind_out(c.kind))
+ .attr("InvertPath", bool_s(c.invert))
+ .attr("IncludeInsideEdges", bool_s(c.include_inside_edges))
+ .attr("RestrictToFrame", bool_s(c.restrict_to_frame))
+ .attr("UseHighResolutionImage", bool_s(c.use_high_resolution))
+ .attr("Threshold", num(c.threshold))
+ .attr("Tolerance", num(c.tolerance))
+ .attr("InsetFrame", num(c.inset))
+ .attr("AppliedPathName", if c.source_name.is_empty() { "$ID/" } else { c.source_name.as_str() })
+ .attr("Index", c.source_index.to_string());
+ with_props(el, vec![geometry])
+ }
+
+ fn path_geometry(path: &PathData) -> El {
+ let mut pg = El::new("PathGeometry");
+ for sp in &path.subpaths {
+ let mut arr = El::new("PathPointArray");
+ for a in &sp.anchors {
+ arr.push(
+ El::new("PathPointType")
+ .attr("Anchor", pt(a.p.x, a.p.y))
+ .attr("LeftDirection", pt(a.h_in.x, a.h_in.y))
+ .attr("RightDirection", pt(a.h_out.x, a.h_out.y)),
+ );
+ }
+ pg.push(El::new("GeometryPathType").attr("PathOpen", bool_s(!sp.closed)).child(arr));
+ }
+ pg
+ }
+
+ /// IDML corner names for anchors 0..4 of a path (by position on its bounding box).
+ pub(crate) fn corner_names(path: &PathData) -> [&'static str; 4] {
+ let default = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"];
+ let Some(sp) = path.subpaths.first() else { return default };
+ if sp.anchors.len() != 4 {
+ return default;
+ }
+ let Some(b) = path.bounds() else { return default };
+ let c = b.center();
+ let mut out = default;
+ let mut seen = HashSet::new();
+ for (i, a) in sp.anchors.iter().enumerate() {
+ let n = match (a.p.y < c.y, a.p.x < c.x) {
+ (true, true) => "TopLeft",
+ (true, false) => "TopRight",
+ (false, false) => "BottomRight",
+ (false, true) => "BottomLeft",
+ };
+ if !seen.insert(n) {
+ return default;
+ }
+ out[i] = n;
+ }
+ out
+ }
+
+ fn format_name(mime: &str) -> &'static str {
+ match mime {
+ "image/png" => "Portable Network Graphics (PNG)",
+ "image/jpeg" => "JPEG",
+ "image/gif" => "GIF",
+ "image/tiff" => "TIFF",
+ "application/pdf" => "Adobe Portable Document Format (PDF)",
+ "application/postscript" => "Encapsulated PostScript (EPS)",
+ _ => "Portable Network Graphics (PNG)",
+ }
+ }
+
+ /// File path → IDML link URI (`file:/abs/path` with spaces percent-encoded).
+ pub(crate) fn path_to_uri(path: &str) -> String {
+ if path.contains(':') && !path.starts_with('/') && path.chars().nth(1) != Some(':') {
+ return path.to_string(); // already a URI
+ }
+ let mut out = String::from("file:");
+ let p = path.replace('\\', "/");
+ for c in p.chars() {
+ match c {
+ ' ' => out.push_str("%20"),
+ '%' => out.push_str("%25"),
+ '#' => out.push_str("%23"),
+ c => out.push(c),
+ }
+ }
+ out
+ }
diff --cc crates/idml/src/import/object_style.rs
index 000000000,bcdaedb66..343e67211
mode 000000,100644..100644
--- a/crates/idml/src/import/object_style.rs
+++ b/crates/idml/src/import/object_style.rs
@@@ -1,0 -1,321 +1,324 @@@
+ use super::values::{finite, tint};
+ use super::{Corner, DirectionalFeather, DropShadow, Effects, El, GradientFeather, HashMap, Importer, Node, Stroke, names};
+
+ /// InDesign's corner size where a file gives a corner shape without one.
+ pub(super) const INDESIGN_CORNER_SIZE: f64 = 12.0;
+
+ /// The four corners of a paragraph border or shading (`prefix` `ParagraphBorder` /
+ /// `ParagraphShading`): top left, top right, bottom right, bottom left. Unset when none is given.
+ pub(super) fn corners(e: &El, prefix: &str) -> Option<[Corner; 4]> {
+ let keys = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"];
+ let shapes = keys.map(|n| e.prop(&format!("{prefix}{n}CornerOption")));
+ let sizes = keys.map(|n| e.num(&format!("{prefix}{n}CornerRadius")));
+ if shapes.iter().all(Option::is_none) && sizes.iter().all(Option::is_none) {
+ return None;
+ }
+ let mut out = [Corner::default(); 4];
+ for (c, (shape, size)) in out.iter_mut().zip(shapes.iter().zip(sizes)) {
+ c.shape = shape.as_deref().map_or(designcraft_geom::corners::CornerShape::None, |s| names::corner_in(s.trim()));
+ c.size = size.filter(|v| v.is_finite()).map_or(12.0, |v| v.max(0.0));
+ }
+ Some(out)
+ }
+
+ impl<'r> Importer<'r> {
+ /// An item's object style chain: its applied style, the styles that one is based on, then
+ /// `[None]` (cycle-safe).
+ pub(super) fn object_style_chain(&self, e: &El) -> Vec<&El> {
+ let mut chain = self.object_style_bases(e.get("AppliedObjectStyle").map(str::to_string));
+ if let Some(none) = self.object_els.get("ObjectStyle/$ID/[None]")
+ && !chain.iter().any(|c| std::ptr::eq(*c, none))
+ {
+ chain.push(none);
+ }
+ chain
+ }
+
+ /// Object style `id` and the styles it is based on, nearest first (cycle-safe, at most 16).
+ fn object_style_bases(&self, id: Option<String>) -> Vec<&El> {
+ let mut chain: Vec<&El> = Vec::new();
+ let mut os = id;
+ while let Some(id) = os {
+ let Some(s) = self.object_els.get(&id) else { break };
+ if chain.len() >= 16 || chain.iter().any(|c| std::ptr::eq(*c, s)) {
+ break;
+ }
+ chain.push(s);
+ os = s.prop("BasedOn").map(|b| {
+ let b = b.trim();
+ if b.starts_with("ObjectStyle/") { b.to_string() } else { format!("ObjectStyle/{}", names::escape_id(b)) }
+ });
+ }
+ chain
+ }
+
+ /// Resolve an item attribute, falling back to its object style chain.
+ pub(super) fn attr_or_style(&self, e: &El, k: &str) -> Option<String> {
+ e.get(k).or_else(|| self.object_style_chain(e).into_iter().find_map(|s| s.get(k))).map(str::to_string)
+ }
+
+ /// The item's child element `name` laid over the same element of each style in its object style
+ /// chain: attributes and nested elements merge one by one, nearer levels winning. IDML writes on an
+ /// item only the values that differ from its style. Effects whose category the applied style turns
+ /// off (`ObjectStyle*EffectsCategorySettings`) come from the item alone.
+ pub(super) fn with_style(&self, e: &El, name: &str) -> Option<El> {
+ let chain = self.object_style_chain(e);
+ let category = match name {
+ "TransparencySetting" => Some("ObjectStyleObjectEffectsCategorySettings"),
+ "StrokeTransparencySetting" => Some("ObjectStyleStrokeEffectsCategorySettings"),
+ "FillTransparencySetting" => Some("ObjectStyleFillEffectsCategorySettings"),
+ "ContentTransparencySetting" => Some("ObjectStyleContentEffectsCategorySettings"),
+ _ => None,
+ };
+ let enabled = |effect: &str| {
+ let Some(flag) = category.and_then(|_| effect_flag(effect)) else { return true };
+ chain.iter().find_map(|s| category.and_then(|c| s.find(c)).and_then(|c| c.get(flag))) != Some("false")
+ };
+ let mut out: Option<El> = None;
+ for s in chain.iter().rev() {
+ let Some(c) = s.find(name) else { continue };
+ let mut c = c.clone();
+ c.children.retain(|n| !matches!(n, Node::El(x) if !enabled(x.local())));
+ match &mut out {
+ Some(o) => overlay(o, &c, 0),
+ None => out = Some(c),
+ }
+ }
+ if let Some(c) = e.find(name) {
+ match &mut out {
+ Some(o) => overlay(o, c, 0),
+ None => out = Some(c.clone()),
+ }
+ }
+ out
+ }
+
+ /// Reads the drop shadow, feather, gradient feather and directional feather of a
+ /// `TransparencySetting` into `fx`.
+ pub(super) fn effects_in(&mut self, t: &El, fx: &mut Effects) {
+ if let Some(ds) = t.find("DropShadowSetting")
+ && ds.get("Mode") == Some("Drop")
+ {
+ let x = ds.num("XOffset").unwrap_or(4.95);
+ let y = ds.num("YOffset").unwrap_or(4.95);
+ let def = DropShadow::default();
+ fx.drop_shadow = DropShadow {
+ on: true,
+ color: ds.get("EffectColor").map(|c| self.swatch_ref(c)).unwrap_or(def.color),
+ opacity: ds.num("Opacity").map(|o| (o / 100.0) as f32).unwrap_or(def.opacity),
+ angle: names_angle(x, y),
+ distance: x.hypot(y),
+ size: ds.num("Size").unwrap_or(def.size),
+ spread: ds.num("Spread").unwrap_or(def.spread),
+ global_light: false,
++ // Without the attribute (earlier DesignCraft exports) the shadow stays Normal, as it
++ // rendered then; a new shadow's default is Multiply.
++ mode: ds.get("BlendMode").map_or(designcraft_color::BlendMode::Normal, names::blend_in),
+ };
+ }
+ if let Some(f) = t.find("FeatherSetting")
+ && f.get("Mode").is_some_and(|m| m != "None")
+ {
+ fx.feather = f.num("Width").unwrap_or(9.0);
+ fx.feather_options.choke = finite(f.num("ChokeAmount")).unwrap_or(0.0).clamp(0.0, 100.0);
+ fx.feather_options.corners = match f.get("CornerType") {
+ Some("Sharp") => designcraft_doc::FeatherCorners::Sharp,
+ Some("Rounded") => designcraft_doc::FeatherCorners::Rounded,
+ _ => designcraft_doc::FeatherCorners::Diffused,
+ };
+ }
+ if let Some(g) = t.find("GradientFeatherSetting")
+ && g.boolean("Applied") == Some(true)
+ {
+ fx.gradient_feather = gradient_feather_in(g);
+ }
+ if let Some(df) = t.find("DirectionalFeatherSetting")
+ && df.boolean("Applied") == Some(true)
+ {
+ let w = |k: &str| finite(df.num(k)).unwrap_or(0.0).max(0.0);
+ fx.directional_feather = DirectionalFeather { on: true, widths: [w("TopWidth"), w("LeftWidth"), w("BottomWidth"), w("RightWidth")] };
+ }
+ }
+
+ /// An object style's drop shadow and feather. Each is read when the effects category turns it
+ /// on (without category settings: when its setting is on), from the nearest style in the
+ /// BasedOn chain that has the setting. `None` when the style sets neither.
+ pub(super) fn style_effects(&mut self, e: &El) -> Option<Effects> {
+ let mut chain = self.object_style_bases(e.get("Self").map(str::to_string));
+ if chain.is_empty() {
+ chain.push(e);
+ }
+ let category = chain.iter().find_map(|s| s.find("ObjectStyleObjectEffectsCategorySettings")).cloned();
+ let setting = |name: &str| chain.iter().find_map(|s| s.find("TransparencySetting")?.find(name)).cloned();
+ let mut t = El::new("TransparencySetting");
+ let mut any = false;
+ for (name, flag) in [("DropShadowSetting", "EnableDropShadow"), ("FeatherSetting", "EnableFeather")] {
+ let el = setting(name);
+ let on = match &category {
+ Some(c) => c.get(flag) == Some("true"),
+ None => el.as_ref().and_then(|x| x.get("Mode")).is_some_and(|m| m != "None"),
+ };
+ any |= on;
+ if let (true, Some(el)) = (on, el) {
+ t.push(el);
+ }
+ }
+ if !any {
+ return None;
+ }
+ let mut fx = Effects::default();
+ self.effects_in(&t, &mut fx);
+ Some(fx)
+ }
+
+ pub(super) fn stroke_from(&mut self, e: &El, item: Option<&El>) -> Stroke {
+ let g = |s: &Self, k: &str| -> Option<String> { if item.is_some() { s.attr_or_style(e, k) } else { e.get(k).map(str::to_string) } };
+ let color = g(self, "StrokeColor");
+ let mut s = Stroke::none();
+ if let Some(c) = color {
+ s.swatch = self.swatch_ref(&c);
+ }
+ if let Some(w) = g(self, "StrokeWeight").and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) {
+ s.weight = w;
+ }
+ if let Some(t) = g(self, "StrokeTint").and_then(|v| v.parse().ok()) {
+ s.tint = tint(Some(t)).unwrap_or(1.0);
+ }
+ if let Some(t) = g(self, "StrokeType") {
+ s.kind = names::stroke_type_in(&t);
+ }
+ if let Some(v) = g(self, "StrokeAlignment") {
+ s.align = names::stroke_align_in(&v);
+ }
+ if let Some(v) = g(self, "EndCap") {
+ s.cap = names::cap_in(&v);
+ }
+ if let Some(v) = g(self, "EndJoin") {
+ s.join = names::join_in(&v);
+ }
+ if let Some(v) = g(self, "MiterLimit").and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) {
+ s.miter_limit = v;
+ }
+ if let Some(v) = g(self, "LeftLineEnd") {
+ s.start = names::arrow_in(&v);
+ }
+ if let Some(v) = g(self, "RightLineEnd") {
+ s.end = names::arrow_in(&v);
+ }
+ if let Some(v) = g(self, "GapColor") {
+ s.gap_swatch = self.swatch_ref(&v);
+ }
+ if let Some(t) = g(self, "GapTint").and_then(|v| v.parse().ok()) {
+ s.gap_tint = tint(Some(t)).unwrap_or(1.0);
+ }
+ s.overprint = g(self, "OverprintStroke").as_deref() == Some("true");
+ s.gap_overprint = g(self, "OverprintGap").as_deref() == Some("true");
+ s
+ }
+ }
+
+ /// The object style category flag that turns an effect element on or off.
+ fn effect_flag(effect: &str) -> Option<&'static str> {
+ Some(match effect {
+ "BlendingSetting" => "EnableTransparency",
+ "DropShadowSetting" => "EnableDropShadow",
+ "FeatherSetting" => "EnableFeather",
+ "InnerShadowSetting" => "EnableInnerShadow",
+ "OuterGlowSetting" => "EnableOuterGlow",
+ "InnerGlowSetting" => "EnableInnerGlow",
+ "BevelAndEmbossSetting" => "EnableBevelEmboss",
+ "SatinSetting" => "EnableSatin",
+ "DirectionalFeatherSetting" => "EnableDirectionalFeather",
+ "GradientFeatherSetting" => "EnableGradientFeather",
+ _ => return None,
+ })
+ }
+
+ /// Lays `top` over `base`: attributes one by one, child elements matched by name and merged the same
+ /// way, text replaced. A property given in one form (attribute or `Properties` child) replaces the
+ /// other form in `base`.
+ fn overlay(base: &mut El, top: &El, depth: usize) {
+ if depth > 32 {
+ *base = top.clone();
+ return;
+ }
+ for (k, v) in &top.attrs {
+ base.set(k, v);
+ if let Some(Node::El(p)) = base.children.iter_mut().find(|n| matches!(n, Node::El(p) if p.local() == "Properties")) {
+ p.children.retain(|n| !matches!(n, Node::El(x) if x.local() == k));
+ }
+ }
+ if let Some(p) = top.find("Properties") {
+ let names: Vec<&str> = p.elements().map(El::local).collect();
+ base.attrs.retain(|(k, _)| !names.contains(&k.as_str()));
+ }
+ let has_text = top.children.iter().any(|n| matches!(n, Node::Text(t) | Node::CData(t) if !t.trim().is_empty()));
+ if has_text {
+ base.children.retain(|n| !matches!(n, Node::Text(_) | Node::CData(_)));
+ }
+ // The k-th child of a name merges with the k-th child of that name in `base` (repeated elements
+ // such as gradient stops pair up in order).
+ let mut seen: HashMap<&str, usize> = HashMap::new();
+ for n in &top.children {
+ match n {
+ Node::El(c) => {
+ let k = seen.entry(c.local()).or_insert(0);
+ let slot = base
+ .children
+ .iter_mut()
+ .filter_map(|b| match b {
+ Node::El(b) if b.local() == c.local() => Some(b),
+ _ => None,
+ })
+ .nth(*k);
+ *k += 1;
+ match slot {
+ Some(b) => overlay(b, c, depth + 1),
+ None => base.children.push(n.clone()),
+ }
+ }
+ Node::Text(_) | Node::CData(_) if has_text => base.children.push(n.clone()),
+ _ => {}
+ }
+ }
+ }
+
+ /// A `GradientFeatherSetting`. The model holds two opacity stops at the ends of the gradient: the
+ /// first and last `OpacityGradientStop` give them; with a linear vector, their `Location`s move its
+ /// ends.
+ fn gradient_feather_in(g: &El) -> GradientFeather {
+ let def = GradientFeather::default();
+ let angle = finite(g.num("Angle")).unwrap_or(0.0);
+ let mut stops: Vec<(f64, f64)> = g
+ .find_all("OpacityGradientStop")
+ .filter_map(|s| Some((finite(s.num("Location"))?.clamp(0.0, 100.0) / 100.0, finite(s.num("Opacity"))?.clamp(0.0, 100.0) / 100.0)))
+ .collect();
+ stops.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let (first, last) = match (stops.first(), stops.last()) {
+ (Some(&a), Some(&b)) => (a, b),
+ _ => ((0.0, def.start as f64), (1.0, def.end as f64)),
+ };
+ let start: Option<[f64; 2]> = g
+ .prop("GradientStart")
+ .and_then(|s| s.split_whitespace().map(|v| v.parse().ok().filter(|v: &f64| v.is_finite())).collect::<Option<Vec<f64>>>())
+ .and_then(|v| v.try_into().ok());
+ let radial = g.get("Type") == Some("Radial");
+ let vector = match (start, finite(g.num("Length"))) {
+ (Some([x, y]), Some(len)) if len > 0.0 => {
+ let a = angle.to_radians();
+ let (dx, dy) = (len * a.cos(), -len * a.sin());
+ let (l0, l1) = if !radial && last.0 > first.0 { (first.0, last.0) } else { (0.0, 1.0) };
+ Some([x + dx * l0, y + dy * l0, x + dx * l1, y + dy * l1])
+ }
+ _ => None,
+ };
+ GradientFeather { on: true, radial, angle, start: first.1 as f32, end: last.1 as f32, vector }
+ }
+
+ fn names_angle(x: f64, y: f64) -> f64 {
+ if x == 0.0 && y == 0.0 {
+ return 135.0;
+ }
+ let a = y.atan2(-x).to_degrees();
+ if a < 0.0 { a + 360.0 } else { a }
+ }