DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge idml-style-effects: IDML: frames take corners, effects and text wrap from their object style
aiongg06baf887fbb0
diff --cc crates/idml/src/import.rsindex 63cd63b3f,b4ced8b6a..12a60927d--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -2293,9 -1939,48 +2293,45 @@@ impl<'r> Importer<'r>/// 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());- }- self.style_chain(e).iter().find_map(|s| s.get(k)).map(str::to_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.+ fn with_style(&self, e: &El, name: &str) -> Option<El> {- let chain = self.style_chain(e);++ 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+ }+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");@@@ -2399,24 -2084,31 +2435,24 @@@it.stroke.weight = 1.0;}}- // 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);- let mut corners = CornerOptions::default();- {- 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 };+ // Corners: each corner's shape and radius come from the item, then its object style chain;+ // at each level a per-corner attribute wins over the legacy all-corners one.+ if tag != "Group" {+ let levels: Vec<&El> = std::iter::once(e).chain(self.object_style_chain(e)).collect();+ let corner =+ |n: &str, what: &str| levels.iter().find_map(|s| s.get(&format!("{n}Corner{what}")).or_else(|| s.get(&format!("Corner{what}"))));+ let mut corners = CornerOptions::default();+ for (i, n) in crate::export::corner_names(&it.path).iter().enumerate() {+ let shape = corner(n, "Option").map(names::corner_in).unwrap_or_default();+ let size = corner(n, "Radius").and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite()).unwrap_or(INDESIGN_CORNER_SIZE);+ corners.corners[i] = Corner { shape, size };+ }+ if !corners.is_none() {+ it.corners = corners;}- }- 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;@@@ -2449,8 -2141,18 +2485,8 @@@}}// Text wrap.- if let Some(w) = e.find("TextWrapPreference") {- it.wrap = text_wrap(w);+ 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"),- side: names::wrap_side_in(w.get("TextWrapSide").unwrap_or("BothSides")),- ..TextWrap::default()- };- if let Some(o) = w.prop_el("TextWrapOffset") {- tw.offsets =- [o.num("Top").unwrap_or(0.0), o.num("Left").unwrap_or(0.0), o.num("Bottom").unwrap_or(0.0), o.num("Right").unwrap_or(0.0)];- }- it.wrap = tw;++ it.wrap = text_wrap(&w);}// Type on a path.if tag != "TextFrame"@@@ -2483,14 -2185,8 +2519,14 @@@sid}};- let mut options = self.with_style(e, "TextFramePreference").map(|t| self.frame_options(&t)).unwrap_or_default();+ // Options the frame doesn't set come from its object style chain.+ let prefs: Vec<&El> = std::iter::once(e).chain(self.object_style_chain(e)).filter_map(|s| s.find("TextFramePreference")).collect();+ let mut options = text_frame_options(&prefs);+ // `prefs` borrows the object styles, so the rule colour's swatch is resolved after it.+ if let Some(r) = Prefs(&prefs).get("ColumnRuleStrokeColor").map(str::to_string) {+ options.column_rule_color = self.swatch_ref(&r);+ }- if let Some(g) = e.find("BaselineFrameGridOption")+ if let Some(g) = self.with_style(e, "BaselineFrameGridOption")&& g.get("UseCustomBaselineFrameGrid") == Some("true"){options.baseline_grid =@@@ -2730,22 -2392,73 +2766,88 @@@}}+ /// 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).+/// A `TextWrapPreference` element (of a page item or a placed graphic).+fn text_wrap(w: &El) -> TextWrap {+ let mut tw = TextWrap {+ mode: names::wrap_mode_in(w.get("TextWrapMode").unwrap_or("None")),+ invert: w.get("Inverse") == Some("true"),+ side: names::wrap_side_in(w.get("TextWrapSide").unwrap_or("BothSides")),+ contour: names::contour_type_in(w.find("ContourOption").and_then(|c| c.get("ContourType")).unwrap_or("SameAsClipping")),+ ..TextWrap::default()+ };+ if let Some(o) = w.prop_el("TextWrapOffset") {+ tw.offsets = [o.num("Top").unwrap_or(0.0), o.num("Left").unwrap_or(0.0), o.num("Bottom").unwrap_or(0.0), o.num("Right").unwrap_or(0.0)];+ }+ tw+}+fn names_angle(x: f64, y: f64) -> f64 {if x == 0.0 && y == 0.0 {return 135.0;diff --cc crates/idml/src/tests.rsindex 3e49dfc5b,e3fed6526..34a024ea9--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -8,9 -8,7 +8,10 @@@ use designcraft_geom::{Rect, shapes}use super::*;mod decorations;+mod rtl_binding;+mod variables;+mod wrap;+ mod object_styles;fn zip_files(files: &[(&str, &str)]) -> Vec<u8> {use zip::write::SimpleFileOptions;