Skip to content

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

IDML: frames take corners, effects and text wrap from their object style

aiongg5d872fbf1ead
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index 9d73562b9..1530c22c7 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -2487,26 +2487,16 @@ fn text_frame_pref(o: &TextFrameOptions, rule_color: &str) -> El {
.attr("AutoSizingType", names::auto_size_out(o.auto_size))
.attr("AutoSizingReferencePoint", names::REF_POINTS[(o.auto_size_ref as usize).min(8)]);
let el = if o.column_width > 0.0 { el.attr("TextColumnFixedWidth", num(o.column_width)) } else { el };
- let d = TextFrameOptions::default();
- let rule_set = o.column_rule
- || o.column_rule_weight != d.column_rule_weight
- || o.column_rule_color != d.column_rule_color
- || o.column_rule_tint != d.column_rule_tint
- || o.column_rule_offset != d.column_rule_offset
- || o.column_rule_top_inset != d.column_rule_top_inset
- || o.column_rule_bottom_inset != d.column_rule_bottom_inset;
- let el = if rule_set {
- 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))
- } 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])
}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index d85d9ee02..b4ced8b6a 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -1922,25 +1922,63 @@ impl<'r> Importer<'r> {
})
}
+ /// An item's applied object style and the styles it is based on, nearest first.
+ fn style_chain(&self, e: &El) -> Vec<&El> {
+ let mut chain: Vec<&El> = Vec::new();
+ let mut os = e.get("AppliedObjectStyle").map(str::to_string);
+ 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| if b.starts_with("ObjectStyle/") { b } else { format!("ObjectStyle/{}", names::escape_id(&b)) });
+ }
+ chain
+ }
+
/// Resolve an item attribute, falling back to its object style chain.
fn attr_or_style(&self, e: &El, k: &str) -> Option<String> {
if let Some(v) = e.get(k) {
return Some(v.to_string());
}
- let mut os = e.get("AppliedObjectStyle").map(str::to_string);
- let mut depth = 0;
- while let Some(id) = os {
- depth += 1;
- if depth > 16 {
- break;
+ self.style_chain(e).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.
+ fn with_style(&self, e: &El, name: &str) -> Option<El> {
+ let chain = self.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),
}
- let Some(s) = self.object_els.get(&id) else { break };
- if let Some(v) = s.get(k) {
- return Some(v.to_string());
+ }
+ if let Some(c) = e.find(name) {
+ match &mut out {
+ Some(o) => overlay(o, c, 0),
+ None => out = Some(c.clone()),
}
- os = s.prop("BasedOn").map(|b| if b.starts_with("ObjectStyle/") { b } else { format!("ObjectStyle/{}", names::escape_id(&b)) });
}
- None
+ out
}
fn stroke_from(&mut self, e: &El, item: Option<&El>) -> Stroke {
@@ -2046,22 +2084,31 @@ impl<'r> Importer<'r> {
it.stroke.weight = 1.0;
}
}
- // Corners.
+ // Corners: each corner takes the nearest level (the item, then its object style chain) that
+ // gives a value. A level's all-corners attributes stand in only when it has no per-corner one.
let cn = crate::export::corner_names(&it.path);
- // The legacy all-corners attributes apply only when no per-corner attribute is present.
- let per_corner = cn.iter().any(|n| e.get(&format!("{n}CornerOption")).is_some());
- let legacy = if per_corner { (None, None) } else { (e.get("CornerOption"), e.num("CornerRadius")) };
let mut corners = CornerOptions::default();
- for (i, n) in cn.iter().enumerate() {
- let shape = e.get(&format!("{n}CornerOption")).or(legacy.0).map(names::corner_in).unwrap_or_default();
- let size = e.num(&format!("{n}CornerRadius")).or(legacy.1).unwrap_or(0.0);
- corners.corners[i] = Corner { shape, size };
+ {
+ let mut levels = vec![e];
+ levels.extend(self.style_chain(e));
+ let pick = |kind: &str, n: &str| -> Option<&str> {
+ levels.iter().find_map(|l| {
+ l.get(&format!("{n}Corner{kind}")).or_else(|| {
+ (!cn.iter().any(|m| l.get(&format!("{m}Corner{kind}")).is_some())).then(|| l.get(&format!("Corner{kind}"))).flatten()
+ })
+ })
+ };
+ for (c, n) in corners.corners.iter_mut().zip(cn) {
+ let shape = pick("Option", n).map(names::corner_in).unwrap_or_default();
+ let size = pick("Radius", n).and_then(|v| v.trim().parse().ok()).filter(|v: &f64| v.is_finite()).unwrap_or(0.0);
+ *c = Corner { shape, size };
+ }
}
if !corners.is_none() {
it.corners = corners;
}
// Transparency.
- if let Some(t) = e.find("TransparencySetting") {
+ if let Some(t) = self.with_style(e, "TransparencySetting") {
if let Some(bs) = t.find("BlendingSetting") {
if let Some(o) = bs.num("Opacity") {
it.opacity = (o / 100.0).clamp(0.0, 1.0) as f32;
@@ -2094,7 +2141,7 @@ impl<'r> Importer<'r> {
}
}
// Text wrap.
- if let Some(w) = e.find("TextWrapPreference") {
+ if let Some(w) = self.with_style(e, "TextWrapPreference") {
let mut tw = TextWrap {
mode: names::wrap_mode_in(w.get("TextWrapMode").unwrap_or("None")),
invert: w.get("Inverse") == Some("true"),
@@ -2138,8 +2185,8 @@ impl<'r> Importer<'r> {
sid
}
};
- let mut options = e.find("TextFramePreference").map(|t| self.frame_options(t)).unwrap_or_default();
- if let Some(g) = e.find("BaselineFrameGridOption")
+ let mut options = self.with_style(e, "TextFramePreference").map(|t| self.frame_options(&t)).unwrap_or_default();
+ if let Some(g) = self.with_style(e, "BaselineFrameGridOption")
&& g.get("UseCustomBaselineFrameGrid") == Some("true")
{
options.baseline_grid =
@@ -2167,7 +2214,7 @@ impl<'r> Importer<'r> {
_ => {
if let Some(g) = e.elements().find(|c| matches!(c.local(), "Image" | "PDF" | "EPS" | "ImportedPage" | "WMF" | "PICT" | "SVG")) {
it.content = self.graphic(g);
- if let (Some(ff), Content::Graphic(gr)) = (e.elements().find(|c| c.local() == "FrameFittingOption"), &mut it.content) {
+ if let (Some(ff), Content::Graphic(gr)) = (self.with_style(e, "FrameFittingOption"), &mut it.content) {
gr.crop = [ff.num("TopCrop"), ff.num("LeftCrop"), ff.num("BottomCrop"), ff.num("RightCrop")].map(|v| v.unwrap_or(0.0));
gr.fit_align = ff.get("FittingAlignment").map_or(4, names::anchor_in);
if ff.get("AutoFit") == Some("true") {
@@ -2345,6 +2392,72 @@ impl<'r> Importer<'r> {
}
}
+/// 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()),
+ _ => {}
+ }
+ }
+}
+
/// Drop-shadow angle (degrees) from IDML offsets (inverse of export's mapping).
fn names_angle(x: f64, y: f64) -> f64 {
if x == 0.0 && y == 0.0 {
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index 7b747587a..e3fed6526 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -8,6 +8,7 @@ use designcraft_geom::{Rect, shapes};
use super::*;
mod decorations;
+mod object_styles;
fn zip_files(files: &[(&str, &str)]) -> Vec<u8> {
use zip::write::SimpleFileOptions;
diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs
new file mode 100644
index 000000000..aa2bf68be
--- /dev/null
+++ b/crates/idml/src/tests/object_styles.rs
@@ -0,0 +1,168 @@
+//! Page items take the values their object style chain gives wherever the item has none.
+
+use designcraft_geom::corners::CornerShape;
+
+use super::*;
+
+const NONE_STYLE: &str = r#"<ObjectStyle Self="ObjectStyle/$ID/[None]" Name="$ID/[None]" CornerRadius="12" CornerOption="None"
+ TopLeftCornerOption="None" TopRightCornerOption="None" BottomLeftCornerOption="None" BottomRightCornerOption="None"
+ TopLeftCornerRadius="12" TopRightCornerRadius="12" BottomLeftCornerRadius="12" BottomRightCornerRadius="12">
+ <TransparencySetting><DropShadowSetting Mode="None" Opacity="75" XOffset="7" YOffset="7" Size="5" Spread="0"/></TransparencySetting>
+ <TextWrapPreference TextWrapMode="None"><Properties><TextWrapOffset Top="0" Left="0" Bottom="0" Right="0"/></Properties></TextWrapPreference>
+ </ObjectStyle>"#;
+
+/// A document with `styles` after `[None]` and one 100 pt square rectangle per entry of `items`
+/// (attributes, children).
+fn fixture(styles: &str, items: &[(&str, &str)]) -> Document {
+ let designmap = format!(
+ r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
+ <RootObjectStyleGroup Self="ro">{NONE_STYLE}{styles}</RootObjectStyleGroup>
+ <idPkg:Spread src="Spreads/Spread_s.xml"/>
+ </Document>"#
+ );
+ let rects: String = items
+ .iter()
+ .enumerate()
+ .map(|(i, (attrs, kids))| {
+ format!(
+ r#"<Rectangle Self="r{i}" {attrs}>
+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>
+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 100"/>
+ <PathPointType Anchor="100 100"/><PathPointType Anchor="100 0"/>
+ </PathPointArray></GeometryPathType></PathGeometry></Properties>
+ {kids}
+ </Rectangle>"#
+ )
+ })
+ .collect();
+ let spread = format!(
+ r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+ <Spread Self="s"><Page Self="p" GeometricBounds="0 0 200 200" ItemTransform="1 0 0 1 0 0"/>{rects}</Spread>
+ </idPkg:Spread>"#
+ );
+ import_idml(&zip_files(&[("designmap.xml", &designmap), ("Spreads/Spread_s.xml", &spread)])).unwrap()
+}
+
+fn assert_round(it: &designcraft_doc::Item, size: f64) {
+ for c in it.corners.corners {
+ assert_eq!(c.shape, CornerShape::Rounded, "{:?}", it.corners);
+ assert!((c.size - size).abs() < 1e-9, "{:?}", it.corners);
+ }
+}
+
+const ROUND: &str = r#"<ObjectStyle Self="ObjectStyle/Round" Name="Round"
+ TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner"
+ TopLeftCornerRadius="17" TopRightCornerRadius="17" BottomLeftCornerRadius="17" BottomRightCornerRadius="17" CornerRadius="17">
+ <Properties><BasedOn type="string">$ID/[None]</BasedOn></Properties>
+ <TransparencySetting><DropShadowSetting Mode="Drop" Opacity="30" XOffset="2" YOffset="2" Spread="10"/></TransparencySetting>
+ </ObjectStyle>"#;
+
+#[test]
+fn frames_take_corners_and_drop_shadow_from_their_object_style() {
+ let d = fixture(
+ ROUND,
+ &[
+ (r#"AppliedObjectStyle="ObjectStyle/Round""#, ""),
+ (
+ r#"AppliedObjectStyle="ObjectStyle/Round" TopLeftCornerRadius="13.98" TopRightCornerRadius="13.98"
+ BottomLeftCornerRadius="13.98" BottomRightCornerRadius="13.98" CornerRadius="13.98""#,
+ r#"<TransparencySetting><DropShadowSetting XOffset="2.33" YOffset="2.33" Size="5.825"/></TransparencySetting>"#,
+ ),
+ ],
+ );
+ let items = &d.spreads[0].items;
+ // Style only.
+ assert_round(&items[0], 17.0);
+ let ds = &items[0].effects.drop_shadow;
+ assert!(ds.on);
+ assert!((ds.distance - 2.0f64.hypot(2.0)).abs() < 1e-9);
+ assert!((ds.opacity - 0.3).abs() < 1e-6);
+ assert_eq!((ds.size, ds.spread), (5.0, 10.0), "size from [None], spread from the style");
+ // Local radius and offsets over the style's corner shape and shadow.
+ assert_round(&items[1], 13.98);
+ let ds = &items[1].effects.drop_shadow;
+ assert!(ds.on);
+ assert!((ds.distance - 2.33f64.hypot(2.33)).abs() < 1e-9);
+ assert!((ds.opacity - 0.3).abs() < 1e-6);
+ assert_eq!((ds.size, ds.spread), (5.825, 10.0));
+}
+
+#[test]
+fn values_resolve_through_the_based_on_chain_attribute_by_attribute() {
+ let styles = format!(
+ r#"{ROUND}
+ <ObjectStyle Self="ObjectStyle/Wrapped" Name="Wrapped">
+ <Properties><BasedOn type="object">ObjectStyle/Round</BasedOn></Properties>
+ <TransparencySetting><BlendingSetting Opacity="80"/><DropShadowSetting Opacity="50"/></TransparencySetting>
+ <TextWrapPreference TextWrapMode="BoundingBoxTextWrap"><Properties><TextWrapOffset Top="4" Left="4" Bottom="4" Right="4"/></Properties></TextWrapPreference>
+ </ObjectStyle>"#
+ );
+ let d = fixture(
+ &styles,
+ &[(
+ r#"AppliedObjectStyle="ObjectStyle/Wrapped" TopRightCornerOption="BevelCorner""#,
+ r#"<TextWrapPreference><Properties><TextWrapOffset Top="9"/></Properties></TextWrapPreference>"#,
+ )],
+ );
+ let it = &d.spreads[0].items[0];
+ let shapes: Vec<CornerShape> = it.corners.corners.iter().map(|c| c.shape).collect();
+ assert_eq!(shapes.iter().filter(|s| **s == CornerShape::Rounded).count(), 3, "{shapes:?}");
+ assert_eq!(shapes.iter().filter(|s| **s == CornerShape::Bevel).count(), 1, "{shapes:?}");
+ assert!(it.corners.corners.iter().all(|c| c.size == 17.0));
+ assert!((it.opacity - 0.8).abs() < 1e-6);
+ let ds = &it.effects.drop_shadow;
+ assert!(ds.on, "Mode from the grandparent style");
+ assert!((ds.opacity - 0.5).abs() < 1e-6);
+ assert!((ds.distance - 2.0f64.hypot(2.0)).abs() < 1e-9);
+ assert_eq!(it.wrap.mode, designcraft_doc::WrapMode::BoundingBox);
+ assert_eq!(it.wrap.offsets, [9.0, 4.0, 4.0, 4.0]);
+}
+
+#[test]
+fn item_overrides_and_disabled_categories_turn_style_effects_off() {
+ let styles = format!(
+ r#"{ROUND}
+ <ObjectStyle Self="ObjectStyle/NoShadow" Name="NoShadow">
+ <Properties><BasedOn type="object">ObjectStyle/Round</BasedOn></Properties>
+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="false"/>
+ </ObjectStyle>"#
+ );
+ let d = fixture(
+ &styles,
+ &[
+ (
+ r#"AppliedObjectStyle="ObjectStyle/Round" TopLeftCornerOption="None" TopRightCornerOption="None" BottomLeftCornerOption="None" BottomRightCornerOption="None""#,
+ r#"<TransparencySetting><DropShadowSetting Mode="None"/></TransparencySetting>"#,
+ ),
+ (r#"AppliedObjectStyle="ObjectStyle/NoShadow""#, ""),
+ (r#"AppliedObjectStyle="ObjectStyle/NoShadow""#, r#"<TransparencySetting><DropShadowSetting Mode="Drop"/></TransparencySetting>"#),
+ ],
+ );
+ let items = &d.spreads[0].items;
+ assert!(items[0].corners.is_none());
+ assert!(!items[0].effects.drop_shadow.on);
+ assert!(!items[1].effects.drop_shadow.on);
+ assert_round(&items[1], 17.0);
+ // The item's own shadow, without the disabled style's values.
+ let ds = &items[2].effects.drop_shadow;
+ assert!(ds.on);
+ assert!((ds.opacity - 0.75).abs() < 1e-6);
+}
+
+#[test]
+fn exported_frames_keep_their_own_values_over_their_object_style() {
+ let mut d = small_doc();
+ let style = designcraft_doc::TextFrameOptions { columns: 2, column_rule: true, column_rule_weight: 3.0, ..Default::default() };
+ std::sync::Arc::make_mut(&mut d.styles).object.push(designcraft_doc::ObjectStyle {
+ name: "Ruled".into(),
+ text_frame: Some(style),
+ ..Default::default()
+ });
+ let fid = d.spreads[0].items[0].id;
+ let it = d.item_mut(fid).unwrap();
+ it.object_style = "Ruled".into();
+ let want = it.text_frame().unwrap().options.clone();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let got = back.spreads[0].items.iter().find(|i| i.object_style == "Ruled").and_then(|i| i.text_frame()).unwrap();
+ assert_eq!(got.options, want);
+}