Skip to content

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

Merge object-style-effects: Object styles carry effects (#653)

aionggb2aa5c1ec8a5
diff --cc ROADMAP.md
index 2a2408b3d,a1209f723..e4f9c2596
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -1,8 -1,8 +1,8 @@@
# DesignCraft roadmap
-**Stage: pre-alpha** · next: alpha, ~0% and ~15–25 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%)
+**Stage: pre-alpha** · next: alpha, ~5–7 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%)
- > **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill) · **Target:** Adobe InDesign 2026
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (object styles carry effects) · **Target:** Adobe InDesign 2026
++> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects) · **Target:** Adobe InDesign 2026
DesignCraft aims at full Adobe InDesign parity, and to be better: faster, open (documented JSON
format + IDML), scriptable by agents (MCP), and available on the web.
@@@ -128,12 -129,13 +128,13 @@@ list) · [roadmap.md](docs/roadmap.md)
Newest first.
+ - **2026-10-13** · Object styles carry effects (drop shadow, feather, inner and outer shadows and glows, bevel, satin, gradient and directional feather). New styles from a selection keep its effects, `style.object.edit` changes a style's effects and every item that follows them, `style.object.clearOverrides` returns items to their style, and new frames take their default style's effects. IDML carries only the drop shadow and feather, for ObjectStyles (with their effects category and BasedOn chain) as for items (#653). No readiness percentage change.
-- **2026-10-12** · macOS Dock Quit uses the same unsaved-document prompts as window and menu Quit. Repeated requests keep the current answers; Cancel retains every tab and unsaved recovery checkpoint, and completed Save/Don't Save answers exit through the ordinary event loop. No readiness percentage change.
-- **2026-10-12** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
-- **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.
-- **2026-10-12** · Book numbering and style updates prepare every chapter before saving. Only closed native chapters are changed; imported IDML remains a read-only style/PDF source. If a later disk write fails, the error names the completed chapters; the batch is not a whole-book transaction. No readiness percentage change.
-- **2026-10-12** · Desktop write callbacks and CLI raster exports use the atomic writer too; open readers retain the original bytes, while private Unix modes and symlink targets survive replacement. Permanent tests cover both actual callers. No readiness percentage change.
-- **2026-10-12** · Save As, library edits and book collection edits persist prospective values before changing live state; failed writes preserve the document and existing collections. Save a Copy rebases data-source paths for its destination without changing the open document. No readiness percentage change.
+- **2026-10-13** · A parent can be based on another parent (`layout.parents.options`). Pages draw the base parent's items, then the parent's, then their own, on screen and in PDF and image export; chains work, cycles are refused, overrides reach base items, `document.inspect` reports `basedOn`, and IDML round-trips it. No readiness percentage change.
+- **2026-10-12** · The Effects dialog, as in InDesign: Object › Effects (Transparency…, Drop Shadow… and the rest, and their shortcuts) and the Effects panel's fx button open it on the chosen effect, turned on. Transparency and every effect in one window, in the document's units, with X/Y offsets, Preview on the page, Cancel putting things back, and OK as one undo step (`object.effects`). Shadows default to InDesign's 120° light angle. No readiness percentage change.
+- **2026-10-12** · Editing type on a path: the Type tool clicks, drags and double-clicks along the curve (the character under the pointer, not one on the straightened line), a click on the letters themselves hits the frame, and the caret and highlight bend with the path. No readiness percentage change.
+- **2026-10-12** · Type on a path has start and end brackets, as in InDesign: selected path type shows them across the path, and dragging either with the Selection or Direct Selection tool moves where the text starts or ends (text past the end bracket is overset). `type.pathOptions {end}`; IDML reads and writes EndBracket. No readiness percentage change.
+- **2026-10-12** · The Pen tool continues an open path from either end point, as in InDesign: the cursor shows it over an end point, a click there carries on drawing that path, a drag first reshapes the end point's direction lines, and the other end closes it. Object › Paths › Reverse Path (`path.reverse`); `path.setAnchor`; `path.appendAnchor` and `path.close` take a subpath. No readiness percentage change.
+- **2026-10-12** · The Eyedropper puts a colour sampled from an image on the stroke when the toolbox's Stroke box is in front, as in InDesign (a line takes it on its stroke). No readiness percentage change.
- **2026-10-12** · Window close and application/menu Quit ask about unsaved documents; later Cancel keeps every tab open, including earlier Don't Save choices. Approvals are rechecked after edits. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
- **2026-10-12** · Each running app keeps recovery data in its own locked folder; current folder and lock ownership are checked before writes and cleanup. Failed isolation disables recovery with a warning instead of sharing document IDs. No readiness percentage change.
- **2026-10-12** · Native engine saves and exports replace files atomically; failed writes retain the original, private staging preserves Unix permissions, and valid long filenames work. Desktop Services and CLI raster exports remain separate follow-ups. No readiness percentage change.
diff --cc crates/doc/src/styles.rs
index 8dcb62d86,88c09b4dc..72590d47c
--- a/crates/doc/src/styles.rs
+++ b/crates/doc/src/styles.rs
@@@ -725,9 -713,13 +747,13 @@@ impl Styles
pub fn object_style(&self, name: &str) -> Option<&ObjectStyle> {
self.object.iter().find(|s| s.name == name)
}
+ /// The effects object style `name` sets, if any (for new items that get a default style).
+ pub fn object_effects(&self, name: &str) -> Option<&Effects> {
+ self.object_style(name)?.effects.as_ref()
+ }
- /// The paragraph style chain from root to `name` (cycle-safe).
- fn para_chain(&self, name: &str) -> Vec<&ParagraphStyle> {
+ /// The paragraph style chain from root to `name` (cycle-safe): resolution starts at its first.
+ pub fn para_chain(&self, name: &str) -> Vec<&ParagraphStyle> {
let mut chain = Vec::new();
let mut cur = self.para(name);
while let Some(s) = cur {
diff --cc crates/engine/src/cmd/file.rs
index f35549562,a1e69e4e7..fa7c8558b
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@@ -515,13 -373,16 +515,16 @@@ fn file_place(s: &mut Session, p: &Valu
let (x, y) = (px.unwrap_or(pr.x0), py.unwrap_or(pr.y0));
let id = ItemId(d.alloc());
let k = w / nw;
- let (bx, by, bw, bh) = crop_box.unwrap_or((0.0, 0.0, nw, nh));
let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(x, y, x + bw * k, y + bh * k)));
it.object_style = d.styles.default_graphic_frame.clone();
+ if let Some(e) = d.styles.object_effects(&it.object_style) {
+ it.effects = e.clone();
+ }
it.content = Content::Graphic(Graphic {
asset: aid,
- size: (nw, nh),
- xf: Affine::translate((x - bx * k, y - by * k)) * Affine::scale(k),
+ size: (bw, bh),
+ xf: Affine::translate((x, y)) * Affine::scale(k),
+ clip: None,
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
diff --cc crates/engine/src/cmd/object.rs
index b915c228b,03194519c..7e68b46e7
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@@ -6,7 -6,7 +6,7 @@@ use std::sync::Arc
use designcraft_color::BlendMode;
use designcraft_doc::{
- Content, Document, Fill, Item, ItemId, ItemLoc, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke, TextFrame, TextFrameOptions,
- Content, Document, Effects, Fill, Item, ItemId, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke, TextFrame, TextFrameOptions,
++ Content, Document, Effects, Fill, Item, ItemId, ItemLoc, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke, TextFrame, TextFrameOptions,
TextSel,
};
use designcraft_geom::{Affine, Point, Rect, Vec2, shapes};
@@@ -508,41 -452,27 +478,36 @@@ pub fn specs() -> Vec<CommandSpec>
has_selection,
|s, p| {
let p2 = p.clone();
- set_flag(
- s,
- p,
- move |i| {
- let e = &mut i.effects.directional_feather;
- e.on = p2.get("on").and_then(Value::as_bool).unwrap_or(!e.on);
- match p2.get("widths") {
- Some(Value::Number(n)) => e.widths = [n.as_f64().unwrap_or(0.0).max(0.0); 4],
- Some(v @ Value::Array(_)) => {
- if let Ok(w) = serde_json::from_value::<[f64; 4]>(v.clone()) {
- e.widths = w.map(|x| x.max(0.0));
- }
+ set_effects(s, p, "object.directionalFeather", move |fx| {
+ let e = &mut fx.directional_feather;
+ e.on = p2.get("on").and_then(Value::as_bool).unwrap_or(!e.on);
+ match p2.get("widths") {
+ Some(Value::Number(n)) => e.widths = [n.as_f64().unwrap_or(0.0).max(0.0); 4],
+ Some(v @ Value::Array(_)) => {
+ if let Ok(w) = serde_json::from_value::<[f64; 4]>(v.clone()) {
+ e.widths = w.map(|x| x.max(0.0));
}
- _ => {}
}
- if e.on && e.widths.iter().all(|w| *w <= 0.0) {
- e.widths = [9.0; 4];
- }
- },
- false,
- )
+ _ => {}
+ }
+ if e.on && e.widths.iter().all(|w| *w <= 0.0) {
+ e.widths = [9.0; 4];
+ }
+ })
}
),
+ cmd!(
+ "object.effects",
+ "Effects",
+ [],
+ None,
+ "{effects?: {dropShadow?: {on?, color?, opacity?, angle?, globalLight?, distance?, size?, spread?}, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, feather? (width), directionalFeather?, gradientFeather?} (the fields given replace the object's, as the Effects dialog sets them), opacity?: 0..1, blend?, ids?} — every effect at once, one undo step",
+ has_selection,
- set_effects
++ effects_all
+ ),
cmd!("object.feather", "Basic Feather", ["Object", "Effects"], None, "{width (0 = off), ids?}", has_selection, |s, p| {
let w = f64_or(p, "width", 9.0).max(0.0);
- set_flag(s, p, move |i| i.effects.feather = w, false)
+ set_effects(s, p, "object.feather", move |fx| fx.feather = w)
}),
cmd!("object.content", "Content", ["Object", "Content"], None, "{type: graphic|text|unassigned, ids?}", has_selection, content_type),
cmd!(
@@@ -1812,307 -1358,37 +1780,323 @@@ fn ungroup(s: &mut Session, p: &Value)
})
}
-fn set_flag(s: &mut Session, p: &Value, f: impl Fn(&mut Item), deselect: bool) -> Result<Value> {
- let ids = targets(s, p)?;
- s.edit(|d, sel| {
- for id in &ids {
- if let Some(it) = d.item_mut(*id) {
- f(it);
+fn text_wrap(s: &mut Session, p: &Value) -> Result<Value> {
+ use designcraft_doc::{ContourType, WrapMode, WrapSide};
+ let side: Option<WrapSide> = match p.get("side") {
+ Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown side"))?),
+ None => None,
+ };
+ // Detected edges, alpha channels and image paths need the image's pixels or paths, which
+ // composition doesn't read; those types aren't offered.
+ let contour = match p.get("contour").map(|v| serde_json::from_value::<ContourType>(v.clone())) {
+ Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping))) => Some(c),
+ Some(_) => return Err(bad("object.textWrap", "unsupported contour type")),
+ None => None,
+ };
+ let mode: Option<WrapMode> = match p.get("mode") {
+ Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown mode"))?),
+ None if side.is_some() || contour.is_some() => None,
+ None => Some(WrapMode::BoundingBox),
+ };
+ let off = match p.get("offset") {
+ Some(Value::Number(n)) => Some([n.as_f64().unwrap_or(0.0); 4]),
+ Some(v) => serde_json::from_value(v.clone()).ok(),
+ None => None,
+ };
+ let invert = p.get("invert").and_then(Value::as_bool);
+ let content = match p.get("content").and_then(Value::as_bool) {
+ Some(c) => c,
+ None => p.get("ids").is_none() && p.get("id").is_none() && s.doc()?.selection.content,
+ };
+ set_flag(
+ s,
+ p,
+ move |i| {
+ let w = match &mut i.content {
+ Content::Graphic(g) if content => &mut g.wrap,
+ _ => &mut i.wrap,
+ };
+ if let Some(m) = mode {
+ w.mode = m;
+ }
+ if let Some(o) = off {
+ w.offsets = o;
+ }
+ if let Some(v) = invert {
+ w.invert = v;
+ }
+ if let Some(v) = side {
+ w.side = v;
+ }
+ if let Some(c) = contour {
+ w.contour = c;
+ }
+ // A custom boundary has the offsets built in and replaces the contour, so setting
+ // either one rebuilds the wrap from the frame.
+ if off.is_some() || contour.is_some() {
+ w.path = None;
}
+ },
+ false,
+ )
+}
+
+fn corner_options(s: &mut Session, p: &Value) -> Result<Value> {
+ use designcraft_geom::corners::{Corner, CornerOptions, CornerShape};
+ let opts = match p.get("corners") {
+ Some(v) => {
+ let corners: [Corner; 4] =
+ serde_json::from_value(v.clone()).map_err(|e| bad("object.cornerOptions", format!("corners: four {{shape, size}} entries ({e})")))?;
+ if corners.iter().any(|c| !c.size.is_finite() || c.size < 0.0) {
+ return Err(bad("object.cornerOptions", "corner sizes must be finite and not negative"));
+ }
+ CornerOptions { corners }
}
- if deselect {
- *sel = Selection::default();
+ None => {
+ let shape = p.get("shape").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or(CornerShape::Rounded);
+ CornerOptions::uniform(shape, f64_or(p, "size", 12.0))
}
- Ok(json!({"changed": ids.len()}))
- })
+ };
+ set_flag(s, p, move |i| i.corners = opts, false)
}
-/// Edits the targets' effects. A value that isn't a finite number is refused; the others are
-/// clamped to their ranges.
-fn set_effects(s: &mut Session, p: &Value, cmd: &'static str, f: impl Fn(&mut Effects)) -> Result<Value> {
- let ids = targets(s, p)?;
- s.edit(|d, _| {
- for id in &ids {
- if let Some(it) = d.item_mut(*id) {
+/// `object.matchAttributes`: the selected objects (or `ids`) take `from`'s appearance.
+pub(super) fn match_attributes(s: &mut Session, p: &Value) -> Result<Value> {
+ let from = super::id_param(p, "from").ok_or_else(|| bad("object.matchAttributes", "missing from"))?;
+ let src = s.doc()?.doc.item(from).cloned().ok_or(designcraft_doc::DocError::NoItem(from))?;
+ set_flag(
+ s,
+ p,
+ move |i| {
+ if i.id == src.id {
+ return;
+ }
+ i.fill = src.fill.clone();
+ i.stroke = src.stroke.clone();
+ i.corners = src.corners;
+ i.opacity = src.opacity;
+ i.blend = src.blend;
+ i.effects = src.effects.clone();
+ },
+ false,
+ )
+}
+
+/// `patch` merged into `base`: objects field by field (recursively), anything else replaced.
+fn merge_json(base: &mut Value, patch: &Value) {
+ match (base, patch) {
+ (Value::Object(b), Value::Object(p)) => {
+ for (k, v) in p {
+ merge_json(b.entry(k.clone()).or_insert(Value::Null), v);
+ }
+ }
+ (b, p) => *b = p.clone(),
+ }
+}
+
+/// Keep effect values in their ranges: opacities 0–1, sizes and distances ≥ 0, percentages 0–100.
+fn sanitize_effects(e: &mut designcraft_doc::Effects) -> Result<()> {
+ const ID: &str = "object.effects";
+ let len = |v: &mut f64| -> Result<()> {
+ if !v.is_finite() {
+ return Err(bad(ID, "values must be finite"));
+ }
+ *v = v.clamp(0.0, 10_000.0);
+ Ok(())
+ };
+ let pct = |v: &mut f64| -> Result<()> {
+ if !v.is_finite() {
+ return Err(bad(ID, "values must be finite"));
+ }
+ *v = v.clamp(0.0, 100.0);
+ Ok(())
+ };
+ let ang = |v: &mut f64| -> Result<()> {
+ if !v.is_finite() {
+ return Err(bad(ID, "values must be finite"));
+ }
+ *v = (*v + 180.0).rem_euclid(360.0) - 180.0;
+ Ok(())
+ };
+ let op = |v: &mut f32| -> Result<()> {
+ if !v.is_finite() {
+ return Err(bad(ID, "values must be finite"));
+ }
+ *v = v.clamp(0.0, 1.0);
+ Ok(())
+ };
+ let ds = &mut e.drop_shadow;
+ op(&mut ds.opacity)?;
+ ang(&mut ds.angle)?;
+ len(&mut ds.distance)?;
+ len(&mut ds.size)?;
+ pct(&mut ds.spread)?;
+ let is = &mut e.inner_shadow;
+ op(&mut is.opacity)?;
+ ang(&mut is.angle)?;
+ len(&mut is.distance)?;
+ len(&mut is.size)?;
+ pct(&mut is.choke)?;
+ let og = &mut e.outer_glow;
+ op(&mut og.opacity)?;
+ len(&mut og.size)?;
+ pct(&mut og.spread)?;
+ let ig = &mut e.inner_glow;
+ op(&mut ig.opacity)?;
+ len(&mut ig.size)?;
+ pct(&mut ig.choke)?;
+ let bv = &mut e.bevel;
+ len(&mut bv.size)?;
+ len(&mut bv.depth)?;
+ ang(&mut bv.angle)?;
+ op(&mut bv.highlight_opacity)?;
+ op(&mut bv.shadow_opacity)?;
+ let sa = &mut e.satin;
+ op(&mut sa.opacity)?;
+ ang(&mut sa.angle)?;
+ len(&mut sa.distance)?;
+ len(&mut sa.size)?;
+ len(&mut e.feather)?;
+ for w in &mut e.directional_feather.widths {
+ len(w)?;
+ }
+ let gf = &mut e.gradient_feather;
+ ang(&mut gf.angle)?;
+ op(&mut gf.start)?;
+ op(&mut gf.end)?;
+ Ok(())
+}
+
- fn set_effects(s: &mut Session, p: &Value) -> Result<Value> {
++fn effects_all(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "object.effects";
+ let patch = match p.get("effects") {
+ None | Some(Value::Null) => None,
+ Some(v @ Value::Object(_)) => Some(v.clone()),
+ Some(_) => return Err(bad(ID, "effects must be an object")),
+ };
+ let opacity = match p.get("opacity") {
+ None | Some(Value::Null) => None,
+ Some(v) => Some(v.as_f64().filter(|o| o.is_finite()).ok_or_else(|| bad(ID, "opacity must be a number"))?.clamp(0.0, 1.0) as f32),
+ };
+ let blend = match p.get("blend") {
+ None | Some(Value::Null) => None,
+ Some(v) => {
+ let raw = v.as_str().ok_or_else(|| bad(ID, "blend must be a string"))?;
+ Some(BlendMode::parse(raw).ok_or_else(|| bad(ID, format!("unknown blend mode `{raw}`")))?)
+ }
+ };
+ let ids = targets(s, p)?;
+ s.edit(|d, _| {
+ let mut changed = 0;
+ for id in &ids {
+ let Some(it) = d.item_mut(*id) else { continue };
+ if it.locked {
+ continue;
+ }
+ if let Some(patch) = &patch {
+ let mut cur = serde_json::to_value(&it.effects).map_err(|e| bad(ID, e.to_string()))?;
+ merge_json(&mut cur, patch);
+ let mut fx: designcraft_doc::Effects = serde_json::from_value(cur).map_err(|e| bad(ID, format!("effects: {e}")))?;
+ sanitize_effects(&mut fx)?;
+ it.effects = fx;
+ }
+ if let Some(o) = opacity {
+ it.opacity = o;
+ }
+ if let Some(b) = blend {
+ it.blend = b;
+ }
+ changed += 1;
+ }
+ Ok(json!({"changed": changed}))
+ })
+}
+
+fn set_flag(s: &mut Session, p: &Value, f: impl Fn(&mut Item), deselect: bool) -> Result<Value> {
+ let ids = targets(s, p)?;
+ s.edit(|d, sel| {
+ for id in &ids {
+ if let Some(it) = d.item_mut(*id) {
+ f(it);
+ }
+ }
+ if deselect {
+ *sel = Selection::default();
+ }
+ Ok(json!({"changed": ids.len()}))
+ })
+}
+
+/// An object a colour command may change: neither it nor its layer is locked.
+fn unlocked(d: &Document, it: &Item) -> bool {
+ !it.locked && d.layer(it.layer).is_none_or(|l| !l.locked)
+}
+
+fn has_editable_selection(s: &Session) -> std::result::Result<(), String> {
+ has_selection(s)?;
+ let st = s.active().ok_or_else(|| super::NOTHING_SELECTED.to_string())?;
+ if st.selection.items.iter().any(|id| st.doc.item(*id).is_some_and(|it| unlocked(&st.doc, it))) {
+ Ok(())
+ } else {
+ Err("the selected objects are locked".into())
+ }
+}
+
+/// Runs `f` on each unlocked target in one edit (one undo step).
+fn edit_unlocked(s: &mut Session, p: &Value, f: impl Fn(&mut Item)) -> Result<Value> {
+ let ids = targets(s, p)?;
+ s.edit(|d, _| {
+ let mut changed = 0;
+ for id in &ids {
+ if d.item(*id).is_some_and(|it| unlocked(d, it))
+ && let Some(it) = d.item_mut(*id)
+ {
+ f(it);
+ changed += 1;
+ }
+ }
+ Ok(json!({"changed": changed}))
+ })
+}
+
+/// A stroke that gets a colour needs a weight to show it.
+fn visible_weight(st: &mut Stroke) {
+ if st.swatch != designcraft_color::swatch::NONE && st.weight <= 0.0 {
+ st.weight = Stroke::default().weight;
+ }
+}
+
+fn swap_fill_stroke(it: &mut Item) {
+ let fill = std::mem::take(&mut it.fill);
+ it.fill = Fill { swatch: std::mem::take(&mut it.stroke.swatch), tint: it.stroke.tint, ..fill.clone() };
+ it.stroke.swatch = fill.swatch;
+ it.stroke.tint = fill.tint;
+ visible_weight(&mut it.stroke);
+}
+
+fn default_fill_stroke(it: &mut Item) {
+ it.fill = Fill { swatch: designcraft_color::swatch::NONE.into(), tint: 1.0, ..it.fill.clone() };
+ it.stroke.swatch = designcraft_color::swatch::BLACK.into();
+ it.stroke.tint = 1.0;
+ visible_weight(&mut it.stroke);
+}
+
++/// Edits the targets' effects. A value that isn't a finite number is refused; the others are
++/// clamped to their ranges.
++fn set_effects(s: &mut Session, p: &Value, cmd: &'static str, f: impl Fn(&mut Effects)) -> Result<Value> {
++ let ids = targets(s, p)?;
++ s.edit(|d, _| {
++ for id in &ids {
++ if let Some(it) = d.item_mut(*id) {
+ let mut fx = it.effects.clone();
+ f(&mut fx);
+ it.effects = fx.sanitized().map_err(|m| bad(cmd, m))?;
+ }
+ }
+ Ok(json!({"changed": ids.len()}))
+ })
+ }
+
fn all_flag(s: &mut Session, f: impl Fn(&mut Item)) -> Result<Value> {
s.edit(|d, _| {
for i in 0..d.spreads.len() {
diff --cc crates/engine/src/cmd/style.rs
index 97efaed94,c5d592e4b..41714330a
--- a/crates/engine/src/cmd/style.rs
+++ b/crates/engine/src/cmd/style.rs
@@@ -937,9 -896,53 +1038,47 @@@ fn create_object(s: &mut Session, p: &V
})
}
+ fn edit_object(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "style.object.edit";
+ let name = str_param(p, "name").ok_or_else(|| bad(CMD, "missing name"))?.to_string();
+ if name == designcraft_doc::NO_OBJECT_STYLE {
+ return Err(bad(CMD, format!("`{name}` can't be edited")));
+ }
+ let old = s.doc()?.doc.styles.object_style(&name).cloned().ok_or_else(|| bad(CMD, format!("no object style `{name}`")))?;
+ let effects = if p.get("effects").is_some_and(Value::is_null) {
+ if EFFECT_KEYS.iter().any(|k| p.get(k).is_some()) {
+ return Err(bad(CMD, "`effects: null` can't be combined with effect settings"));
+ }
+ None
+ } else {
+ match effects_param(CMD, p, old.effects.as_ref().unwrap_or(&Effects::default()))? {
+ Some(e) => Some(e),
+ None => return Ok(json!({"name": name, "updated": 0})),
+ }
+ };
+ if effects == old.effects {
+ return Ok(json!({"name": name, "updated": 0}));
+ }
+ s.edit(|d, _| {
+ let Some(os) = d.styles_mut().object.iter_mut().find(|o| o.name == name) else {
+ return Err(bad(CMD, format!("no object style `{name}`")));
+ };
+ os.effects = effects.clone();
+ // An item follows the style while its effects are the style's. When the style didn't set
+ // effects before, only items without effects of their own follow (the default styles are
+ // on most frames).
+ let follows = old.effects.clone().unwrap_or_default();
+ let updated = match &effects {
+ Some(new) => d.update_items(|it| it.object_style == name && it.effects == follows, |it| it.effects = new.clone()),
+ None => 0,
+ };
+ Ok(json!({"name": name, "updated": updated}))
+ })
+ }
+
/// The swatch name of a colour value ("C=… M=… Y=… K=…" / "R=… G=… B=…").
fn value_name(color: designcraft_color::Color) -> String {
- match color {
- designcraft_color::Color::Cmyk { c, m, y, k } => designcraft_color::swatch::cmyk_name(c, m, y, k),
- other => {
- let [r, g, b] = other.to_rgb();
- format!("R={} G={} B={}", (r * 255.0).round(), (g * 255.0).round(), (b * 255.0).round())
- }
- }
+ designcraft_color::swatch::value_name(color)
}
fn load_swatches(s: &mut Session, p: &Value) -> Result<Value> {
diff --cc crates/idml/src/export.rs
index 3f06e8e55,07f14a852..ee9b1edd2
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@@ -1845,61 -1704,16 +1867,51 @@@ impl<'a> Ex<'a>
}
let mut el = with_props(el, props);
// 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;
- if it.opacity < 1.0 || it.blend != designcraft_color::BlendMode::Normal || ds.on || it.effects.feather > 0.0 || styled {
+ 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 {
++ 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)));
- if ds.on {
- let a = self.d.light_angle(ds.angle, ds.global_light).to_radians();
- t.push(
- El::new("DropShadowSetting")
- .attr("Mode", "Drop")
- .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("EffectColor", self.sw(&ds.color)),
- );
- }
- if it.effects.feather > 0.0 {
- t.push(El::new("FeatherSetting").attr("Mode", "Standard").attr("Width", num(it.effects.feather)));
+ 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);
}
if let Content::Text(t) = &it.content {
diff --cc crates/idml/src/import.rs
index 87daf3955,27966ca29..579bdadc1
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@@ -2360,71 -1988,98 +2361,154 @@@ 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());
- }
+ /// An item's object style chain: its applied style, the styles that one is based on, then
+ /// `[None]` (cycle-safe).
+ fn object_style_chain(&self, e: &El) -> Vec<&El> {
+ let mut chain: Vec<&El> = Vec::new();
let mut os = e.get("AppliedObjectStyle").map(str::to_string);
- let mut depth = 0;
while let Some(id) = os {
- depth += 1;
- if depth > 16 {
+ let Some(s) = self.object_els.get(&id) else { break };
+ if chain.len() >= 16 || chain.iter().any(|c| std::ptr::eq(*c, s)) {
break;
}
- let Some(s) = self.object_els.get(&id) else { break };
- if let Some(v) = s.get(k) {
- return Some(v.to_string());
+ 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)) }
+ });
+ }
+ if let Some(none) = self.object_els.get("ObjectStyle/$ID/[None]")
+ && !chain.iter().any(|c| std::ptr::eq(*c, none))
+ {
+ chain.push(none);
+ }
+ chain
+ }
+
+ /// Resolve an item attribute, falling back to its object style chain.
+ 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.
+ 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),
}
- os = s.prop("BasedOn").map(|b| if b.starts_with("ObjectStyle/") { b } else { format!("ObjectStyle/{}", names::escape_id(&b)) });
}
- None
+ 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 and feather of a `TransparencySetting` into `fx`.
++ /// Reads the drop shadow, feather, gradient feather and directional feather of a
++ /// `TransparencySetting` into `fx`.
+ 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,
+ };
+ }
+ 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);
+ }
++ 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 element and the styles it is based on, nearest first (cycle-safe, bounded).
- fn object_style_chain(&self, e: &El) -> Vec<El> {
++ fn object_style_bases(&self, e: &El) -> Vec<El> {
+ let mut chain = vec![e.clone()];
+ let mut seen: HashSet<String> = e.get("Self").map(str::to_string).into_iter().collect();
+ let mut next = e.prop("BasedOn");
+ while let Some(b) = next {
+ let id = if b.starts_with("ObjectStyle/") { b } else { format!("ObjectStyle/{}", names::escape_id(&b)) };
+ if chain.len() >= 16 || !seen.insert(id.clone()) {
+ break;
+ }
+ let Some(s) = self.object_els.get(&id) else { break };
+ chain.push(s.clone());
+ next = s.prop("BasedOn");
+ }
+ chain
+ }
+
+ /// 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.
+ fn style_effects(&mut self, e: &El) -> Option<Effects> {
- let chain = self.object_style_chain(e);
++ let chain = self.object_style_bases(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)
+ }
+
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");
@@@ -2554,49 -2207,19 +2638,16 @@@
it.blend = names::blend_in(m);
}
}
- 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();
- it.effects.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,
- };
- }
- if let Some(f) = t.find("FeatherSetting")
- && f.get("Mode").is_some_and(|m| m != "None")
- {
- it.effects = Effects { feather: f.num("Width").unwrap_or(9.0), ..it.effects.clone() };
- }
- if let Some(g) = t.find("GradientFeatherSetting")
- && g.boolean("Applied") == Some(true)
- {
- it.effects.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);
- it.effects.directional_feather =
- DirectionalFeather { on: true, widths: [w("TopWidth"), w("LeftWidth"), w("BottomWidth"), w("RightWidth")] };
- }
- self.effects_in(t, &mut it.effects);
++ self.effects_in(&t, &mut it.effects);
}
// Text wrap.
- if let Some(w) = e.find("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)];
+ if let Some(w) = self.with_style(e, "TextWrapPreference") {
+ let mut tw = text_wrap(&w);
+ if let Some(pg) = w.prop_el("PathGeometry") {
+ match wrap_path_of(pg) {
+ Ok(p) => tw.path = Some(p),
+ Err(why) => log::warn!("IDML: custom text wrap boundary of {} dropped: {why}", e.get("Self").unwrap_or("an item")),
+ }
}
it.wrap = tw;
}
diff --cc crates/idml/src/tests.rs
index 473ab7298,92d83c1df..d49988942
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -2608,875 -1455,82 +2608,955 @@@ fn list_numbering_format_expression_and
check(&import_idml(&export_idml(&d)).unwrap());
}
+/// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is
+/// set in that family instead of counting as a missing font drawn in the fallback.
+#[test]
+fn applied_font_with_an_id_prefix_names_the_family() {
+ let styles = STYLES.replace(">Source Serif 4</AppliedFont>", ">$ID/Source Serif 4</AppliedFont>");
+ let story = STORY.replace(
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14">"#,
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14"><Properties><AppliedFont type="string">$ID/Source Serif 4</AppliedFont></Properties>"#,
+ );
+ let bytes = zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", &styles),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", &story),
+ ]);
+ let d = import_idml_with(&bytes, &|_| None).unwrap();
+ let fonts: Vec<&str> = d.styles.paragraph.iter().filter_map(|s| s.chars.font_family.as_deref()).collect();
+ assert!(!fonts.is_empty() && fonts.iter().all(|f| *f == "Source Serif 4"), "{fonts:?}");
+ let (sid, story) = d.stories.iter().next().unwrap();
+ let bold = story.runs().find(|(r, _)| story.text[r.clone()].starts_with("bold")).unwrap().1;
+ assert_eq!(bold.over.font_family.as_deref(), Some("Source Serif 4"));
+ // The bundled family draws the text (an unknown family would fall back to Source Sans 3).
+ let cs = designcraft_compose::compose_story(&d, *sid, &Default::default());
+ let first_para = story.text.find('\n').unwrap();
+ let families: Vec<&str> = cs
+ .frames
+ .iter()
+ .flat_map(|f| &f.lines)
+ .flat_map(|l| &l.glyphs)
+ .filter(|g| g.visible && g.len > 0 && g.byte < first_para)
+ .map(|g| g.face.get().family.as_str())
+ .collect();
+ assert!(!families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"), "{families:?}");
+}
+
+#[test]
+fn list_tab_position_round_trips_as_a_tab_stop() {
+ use designcraft_doc::{ListType, ParaAttrs, ParagraphStyle, TabAlign, TabStop};
+ let stop = |position, align| TabStop { position, align, leader: String::new(), align_on: String::new() };
+ let mut d = Document::new(&NewDocument::default());
+ std::sync::Arc::make_mut(&mut d.styles).paragraph.push(ParagraphStyle {
+ name: "List".into(),
+ based_on: None,
+ next_style: None,
+ para: ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(Some(24.0)), ..Default::default() },
+ chars: CharAttrs::default(),
+ shortcut: String::new(),
+ });
+ let local = ParaAttrs {
+ list_type: Some(ListType::Bullets),
+ list_tab: Some(Some(36.0)),
+ tabs: Some(vec![stop(100.0, TabAlign::Right)]),
+ ..Default::default()
+ };
+ let ended = ParaAttrs { list_type: Some(ListType::None), ..Default::default() };
+ let lid = d.default_layer();
+ for (i, (text, style, para)) in
+ [("Local\tx", "", local), ("Styled\ty", "List", ParaAttrs::default()), ("Ended\tz", "List", ended)].into_iter().enumerate()
+ {
+ let pf = ParaFormat { style: if style.is_empty() { ParaFormat::default().style } else { style.into() }, para, ..Default::default() };
+ let y = 40.0 + 100.0 * i as f64;
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, y, 300.0, y + 80.0), lid, text, pf).unwrap();
+ }
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let tabs = |prefix: &str| {
+ let s = back.stories.values().find(|s| s.text.starts_with(prefix)).unwrap();
+ back.styles.resolve_para(&s.paras[0]).0.tabs
+ };
+ assert_eq!(tabs("Local"), vec![stop(36.0, TabAlign::Left), stop(100.0, TabAlign::Right)]);
+ assert_eq!(tabs("Styled"), vec![stop(24.0, TabAlign::Left)]);
+ assert_eq!(tabs("Ended"), vec![], "a paragraph that ends the list has no list tab stop");
+}
+
+#[test]
+fn round_trips_the_zero_point_and_ruler_origin() {
+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });
+ d.settings.zero_point = [36.0, 18.5];
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(back.settings.zero_point, [36.0, 18.5]);
+ for origin in [designcraft_doc::RulerOrigin::Page, designcraft_doc::RulerOrigin::Spine, designcraft_doc::RulerOrigin::Spread] {
+ d.settings.ruler_origin = origin;
+ assert_eq!(import_idml(&export_idml(&d)).unwrap().settings.ruler_origin, origin);
+ }
+ // A hostile ZeroPoint lands on the pasteboard; a malformed one is ignored.
+ let fixture = |zp: &str| {
+ let designmap = format!(
+ r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d" ZeroPoint="{zp}">
+ <idPkg:Spread src="Spreads/Spread_s.xml"/>
+ </Document>"#
+ );
+ let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+ <Spread Self="s"><Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/></Spread>
+ </idPkg:Spread>"#;
+ import_idml(&zip_files(&[("designmap.xml", &designmap), ("Spreads/Spread_s.xml", spread)])).unwrap()
+ };
+ let [x, y] = fixture("1e300 -1e300").settings.zero_point;
+ assert!(x.is_finite() && y.is_finite() && x < 1e4 && y > -1e4, "{x} {y}");
+ assert_eq!(fixture("12").settings.zero_point, [0.0, 0.0]);
+ assert_eq!(fixture("NaN 4").settings.zero_point, [0.0, 0.0]);
+}
+
+#[test]
+fn kenten_shatai_and_grid_settings_import_and_round_trip() {
+ use designcraft_doc::cjk::CharacterAlignment;
+ use designcraft_doc::cjk_settings::{AdornmentOverprint, KentenAlignment, KentenKind, KentenPosition};
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" AutoTcy="3" AutoTcyIncludeRoman="true" RotateSingleByteCharacters="true" AllowArbitraryHyphenation="true" GridAlignment="AlignEmCenter" GridAlignFirstLineOnly="true" GridGyoudori="2" ParagraphGyoudori="true">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="KentenSmallBlackCircle" KentenFontSize="6" KentenXScale="80" KentenYScale="120" KentenPlacement="1.5" KentenPosition="BelowLeft" KentenAlignment="AlignKentenLeft" KentenCharacterSet="CharacterInput" KentenTint="50" KentenStrokeTint="-1" KentenWeight="0.5" KentenOverprintFill="OverprintOn" KentenOverprintStroke="Auto" ShataiMagnification="20" ShataiDegreeAngle="6000" ShataiAdjustRotation="true" ShataiAdjustTsume="false"><Properties><KentenFont type="string">$ID/</KentenFont><KentenFontStyle type="enumeration">Nothing</KentenFontStyle><KentenFillColor type="string">Text Color</KentenFillColor></Properties><Content>甲乙</Content></CharacterStyleRange>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="Custom" KentenCustomCharacter="★"><Content>丙</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let doc = import_idml(&fixture_with_story(story)).unwrap();
+ let st = doc.stories.values().find(|s| s.text.contains("甲乙")).unwrap();
+ let runs: Vec<CharAttrs> = st.runs().map(|(_, f)| f.over.clone()).collect();
+ let a = &runs[0];
+ assert_eq!((a.kenten, a.kenten_kind, a.kenten_character.as_deref()), (Some(true), Some(KentenKind::SmallBlackCircle), Some("\u{2022}")));
+ assert_eq!((a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance), (Some(Some(6.0)), Some(0.8), Some(1.2), Some(1.5)));
+ assert_eq!((a.kenten_position, a.kenten_alignment), (Some(KentenPosition::BelowLeft), Some(KentenAlignment::Start)));
+ assert_eq!((a.kenten_font.as_deref(), a.kenten_font_style.as_deref(), a.kenten_fill.as_deref()), (Some(""), Some(""), Some("")));
+ assert_eq!((a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight), (Some(Some(0.5)), Some(None), Some(Some(0.5))));
+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (Some(AdornmentOverprint::On), Some(AdornmentOverprint::Auto)));
+ assert_eq!(a.kenten_character_set.as_deref(), Some("CharacterInput"));
+ assert_eq!(
+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),
+ (Some(20.0), Some(60.0), Some(true), Some(false))
+ );
+ let custom = runs.iter().find(|r| r.kenten_kind == Some(KentenKind::Custom)).unwrap();
+ assert_eq!(custom.kenten_character.as_deref(), Some("★"));
+ let p = &st.paras[0].para;
+ assert_eq!((p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break), (Some(3), Some(true), Some(true), Some(true)));
+ assert_eq!((p.grid_align, p.grid_reference), (Some(designcraft_doc::GridAlign::FirstLineOnly), Some(CharacterAlignment::EmCenter)));
+ assert_eq!((p.grid_gyoudori, p.paragraph_gyoudori), (Some(2), Some(true)));
+
+ let back = import_idml(&export_idml(&doc)).unwrap();
+ let st2 = back.stories.values().find(|s| s.text.contains("甲乙")).unwrap();
+ let runs2: Vec<CharAttrs> = st2.runs().map(|(_, f)| f.over.clone()).collect();
+ for (a, b) in runs.iter().zip(&runs2) {
+ assert_eq!((a.kenten, a.kenten_kind, &a.kenten_character), (b.kenten, b.kenten_kind, &b.kenten_character));
+ assert_eq!(
+ (a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance),
+ (b.kenten_size, b.kenten_x_scale, b.kenten_y_scale, b.kenten_distance)
+ );
+ assert_eq!(
+ (a.kenten_position, a.kenten_alignment, &a.kenten_character_set),
+ (b.kenten_position, b.kenten_alignment, &b.kenten_character_set)
+ );
+ assert_eq!((&a.kenten_font, &a.kenten_font_style, &a.kenten_fill), (&b.kenten_font, &b.kenten_font_style, &b.kenten_fill));
+ assert_eq!(
+ (a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight),
+ (b.kenten_fill_tint, b.kenten_stroke_tint, b.kenten_stroke_weight)
+ );
+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (b.kenten_overprint_fill, b.kenten_overprint_stroke));
+ assert_eq!(
+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),
+ (b.shatai_magnification, b.shatai_angle, b.shatai_adjust_rotation, b.shatai_adjust_tsume)
+ );
+ }
+ let p2 = &st2.paras[0].para;
+ assert_eq!(
+ (p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break),
+ (p2.auto_tcy, p2.auto_tcy_include_roman, p2.rotate_roman, p2.roman_word_break)
+ );
+ assert_eq!(
+ (p.grid_align, p.grid_reference, p.grid_gyoudori, p.paragraph_gyoudori),
+ (p2.grid_align, p2.grid_reference, p2.grid_gyoudori, p2.paragraph_gyoudori)
+ );
+}
+
+#[test]
+fn ruby_settings_import_from_idml_and_round_trip() {
+ use designcraft_doc::cjk_settings::AdornmentOverprint;
+ use designcraft_doc::ruby::{RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubyType};
+ // InDesign's names: RubyFlag is a number, colours and fonts are properties.
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" RubyFlag="1" RubyString="かん じ" RubyType="PerCharacterRuby" RubyAlignment="RubyCenter" RubyPosition="BelowLeft" RubyYOffset="-1.4173228" RubyFontSize="-1" RubyXScale="90" RubyParentOverhangAmount="RubyOverhangNoLimit" RubyParentSpacing="RubyParentBothSides" RubyAutoAlign="false" RubyAutoScaling="true" RubyParentScalingPercent="40" RubyAutoTcyDigits="2" RubyTint="-1" RubyOverprintFill="Auto"><Properties><RubyFont type="string">$ID/</RubyFont><RubyFontStyle type="enumeration">Nothing</RubyFontStyle><RubyFill type="string">Text Color</RubyFill></Properties><Content>漢字</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let doc = import_idml(&fixture_with_story(story)).unwrap();
+ let a = doc.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();
+ assert_eq!(a.ruby.as_deref(), Some("かん じ"));
+ assert_eq!(a.ruby_type, Some(RubyType::PerCharacter));
+ assert_eq!(a.ruby_alignment, Some(RubyAlignment::Center));
+ assert_eq!(a.ruby_position, Some(RubyPosition::BelowLeft));
+ assert_eq!(a.ruby_y_offset, Some(-1.4173228));
+ assert_eq!(a.ruby_font_size, Some(None));
+ assert_eq!(a.ruby_x_scale, Some(0.9));
+ assert_eq!(a.ruby_overhang_amount, Some(RubyOverhang::NoLimit));
+ assert_eq!(a.ruby_parent_spacing, Some(RubyParentSpacing::BothSides));
+ assert_eq!((a.ruby_auto_align, a.ruby_auto_scaling, a.ruby_scaling_min), (Some(false), Some(true), Some(0.4)));
+ assert_eq!(a.ruby_auto_tcy_digits, Some(2));
+ assert_eq!((a.ruby_font.as_deref(), a.ruby_font_style.as_deref(), a.ruby_fill.as_deref()), (Some(""), Some(""), Some("")));
+ assert_eq!((a.ruby_fill_tint, a.ruby_overprint_fill), (Some(None), Some(AdornmentOverprint::Auto)));
+
+ // Every setting survives export and import.
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 200.0), lid, "漢字", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().format_chars(0.."漢字".len(), |f| {
+ let o = &mut f.over;
+ o.ruby = Some("かん じ".into());
+ o.ruby_type = Some(RubyType::PerCharacter);
+ o.ruby_alignment = Some(RubyAlignment::OneAki);
+ o.ruby_position = Some(RubyPosition::BelowLeft);
+ o.ruby_x_offset = Some(1.5);
+ o.ruby_y_offset = Some(-1.25);
+ o.ruby_font = Some("Source Sans 3".into());
+ o.ruby_font_style = Some("Bold".into());
+ o.ruby_font_size = Some(Some(7.0));
+ o.ruby_x_scale = Some(0.9);
+ o.ruby_y_scale = Some(1.1);
+ o.ruby_open_type_pro = Some(false);
+ o.ruby_auto_tcy_digits = Some(3);
+ o.ruby_auto_tcy_include_roman = Some(true);
+ o.ruby_auto_tcy_auto_scale = Some(false);
+ o.ruby_overhang = Some(true);
+ o.ruby_overhang_amount = Some(RubyOverhang::HalfChar);
+ o.ruby_parent_spacing = Some(RubyParentSpacing::EqualAki);
+ o.ruby_auto_align = Some(false);
+ o.ruby_auto_scaling = Some(true);
+ o.ruby_scaling_min = Some(0.5);
+ o.ruby_fill = Some("[Black]".into());
+ o.ruby_fill_tint = Some(Some(0.5));
+ o.ruby_stroke = Some(String::new());
+ o.ruby_stroke_tint = Some(None);
+ o.ruby_stroke_weight = Some(Some(0.25));
+ o.ruby_overprint_fill = Some(AdornmentOverprint::On);
+ o.ruby_overprint_stroke = Some(AdornmentOverprint::Off);
+ });
+ let a = d.stories[&sid].runs().next().unwrap().1.over.clone();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let b = back.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();
+ macro_rules! same {
+ ($($f:ident),*) => { $( assert_eq!(a.$f, b.$f, stringify!($f)); )* };
+ }
+ same!(
+ ruby,
+ ruby_type,
+ ruby_alignment,
+ ruby_position,
+ ruby_x_offset,
+ ruby_y_offset,
+ ruby_font,
+ ruby_font_style,
+ ruby_font_size,
+ ruby_x_scale,
+ ruby_y_scale,
+ ruby_open_type_pro,
+ ruby_auto_tcy_digits,
+ ruby_auto_tcy_include_roman,
+ ruby_auto_tcy_auto_scale,
+ ruby_overhang,
+ ruby_overhang_amount,
+ ruby_parent_spacing,
+ ruby_auto_align,
+ ruby_auto_scaling,
+ ruby_scaling_min,
+ ruby_fill,
+ ruby_fill_tint,
+ ruby_stroke,
+ ruby_stroke_tint,
+ ruby_stroke_weight,
+ ruby_overprint_fill,
+ ruby_overprint_stroke
+ );
+}
+
+/// A file's tab list is sanitized as the Tabs commands check theirs: a hostile one imports
+/// within the limits instead of failing the import.
+#[test]
+fn hostile_tab_lists_import_within_the_limits() {
+ let item = |position: &str, leader: &str| {
+ format!(
+ r#"<ListItem type="record"><Alignment type="enumeration">LeftAlign</Alignment><AlignmentCharacter type="string">.</AlignmentCharacter><Leader type="string">{leader}</Leader><Position type="unit">{position}</Position></ListItem>"#
+ )
+ };
+ let mut items: String = (0..500).rev().map(|i| item(&(i * 3).to_string(), "")).collect();
+ items.push_str(&item("NaN", ""));
+ items.push_str(&item("1e300", "0123456789"));
+ let story = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <Properties><TabList type="list">{items}</TabList></Properties>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Many tabs</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#
+ );
+ let report = import_idml_report(&fixture_with_story(&story), &|_| None).unwrap();
+ assert!(report.warnings.iter().any(|w| w.starts_with("tab lists repaired to fit the limits") && w.ends_with("): 1")), "{:?}", report.warnings);
+ let doc = report.document;
+ let tabs = doc.stories.values().find(|s| s.text.contains("Many tabs")).unwrap().paras[0].para.tabs.clone().unwrap();
+ assert_eq!(tabs.len(), designcraft_doc::MAX_TAB_STOPS);
+ assert!(tabs.iter().all(|t| t.position.is_finite() && t.leader.chars().count() <= designcraft_doc::MAX_TAB_LEADER));
+ assert!(tabs.windows(2).all(|w| w[0].position < w[1].position), "sorted");
+ assert_eq!((tabs[0].position, tabs[99].position), (0.0, 297.0), "the first stops by position");
+ // A list within the limits, unsorted and with a char stop on `.`, imports without a warning.
+ let fine = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <Properties><TabList type="list">{}{}<ListItem type="record"><Alignment type="enumeration">CharacterAlign</Alignment><AlignmentCharacter type="string">.</AlignmentCharacter><Leader type="string"></Leader><Position type="unit">40</Position></ListItem></TabList></Properties>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Few tabs</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#,
+ item("90", "."),
+ item("12", "")
+ );
+ let report = import_idml_report(&fixture_with_story(&fine), &|_| None).unwrap();
+ assert!(report.warnings.is_empty(), "{:?}", report.warnings);
+}
+
+#[test]
+fn cell_edge_gap_colours_and_tints_import_and_round_trip_per_edge() {
+ let styles = CASCADE_STYLES.replace(
+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed""#,
+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed" TopEdgeStrokeGapColor="Color/Paper" TopEdgeStrokeGapTint="60" BottomEdgeStrokeGapColor="Color/Brand""#,
+ );
+ let story = CASCADE_STORY.replace(
+ r#"<Cell Name="1:1">"#,
+ r#"<Cell Name="1:1" LeftEdgeStrokeType="StrokeStyle/$ID/Dotted" LeftEdgeStrokeGapColor="Color/Brand" LeftEdgeStrokeGapTint="30" RightEdgeStrokeGapColor="Color/Paper">"#,
+ );
+ let gaps = |d: &Document| {
+ let base = d.styles.cell.iter().find(|s| s.name == "Base").unwrap().strokes.clone();
+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();
+ let cell = table.cell(1, 1).unwrap().strokes.clone();
+ (base.map(|e| (e.gap_color, e.gap_tint)), cell.map(|e| (e.gap_color, e.gap_tint)))
+ };
+ let d = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();
+ d.check().unwrap();
+ let (style, cell) = gaps(&d);
+ assert_eq!(style[0], (Some("[Paper]".to_string()), Some(0.6)));
+ assert_eq!(style[2], (Some("Brand".to_string()), None));
+ assert_eq!((style[1].clone(), style[3].clone()), ((None, None), (None, None)));
+ assert_eq!(cell[1], ("Brand".to_string(), 0.3), "left");
+ assert_eq!(cell[3], ("[Paper]".to_string(), 1.0), "right");
+ assert_eq!(cell[0].0, "[Paper]", "the Base style's top gap colour reaches the cell");
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(gaps(&back), (style, cell));
+}
+
+#[test]
+fn em_box_first_baseline_offset_round_trips() {
+ use designcraft_doc::FirstBaseline;
+ let first = |d: &Document| d.spreads[0].items[0].text_frame().unwrap().options.first_baseline;
+ let d = inset_fixture(r#"<TextFramePreference FirstBaselineOffset="EmboxHeight"/>"#, "");
+ assert_eq!(first(&d), FirstBaseline::EmboxHeight);
+ assert_eq!(first(&import_idml(&export_idml(&d)).unwrap()), FirstBaseline::EmboxHeight);
+ let unknown = inset_fixture(r#"<TextFramePreference FirstBaselineOffset="SomethingElse"/>"#, "");
+ assert_eq!(first(&unknown), FirstBaseline::Ascent);
+}
+
+#[test]
+fn imports_and_round_trips_text_wrap_side_and_contour_type() {
+ let wrap = r#"<TextWrapPreference TextWrapMode="Contour" TextWrapSide="LeftSide"><ContourOption ContourType="BoundingBox" IncludeInsideEdges="false"/></TextWrapPreference><Image Self="im""#;
+ let spread = SPREAD.replace(r#"<Image Self="im""#, wrap);
+ assert_ne!(spread, SPREAD);
+ let bytes = zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", &spread),
+ ("Stories/Story_s1.xml", STORY),
+ ]);
+ let mut d = import_idml(&bytes).unwrap();
+ let id = d.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().id;
+ let w = d.item(id).unwrap().wrap.clone();
+ assert_eq!(
+ (w.mode, w.side, w.contour),
+ (designcraft_doc::WrapMode::Contour, designcraft_doc::WrapSide::LeftSide, designcraft_doc::ContourType::BoundingBox)
+ );
+ // Every side and contour type survives export and import (detected edges included, which
+ // composition follows as the frame's path).
+ d.item_mut(id).unwrap().wrap.side = designcraft_doc::WrapSide::AwayFromSpine;
+ d.item_mut(id).unwrap().wrap.contour = designcraft_doc::ContourType::DetectEdges;
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap.clone();
+ assert_eq!((w.side, w.contour), (designcraft_doc::WrapSide::AwayFromSpine, designcraft_doc::ContourType::DetectEdges));
+}
+
+fn feather_fixture(transparency: &str) -> Document {
+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
+ <idPkg:Spread src="Spreads/Spread_s.xml"/>
+ </Document>"#;
+ let rect = |id: &str, inner: &str| {
+ format!(
+ r#"<Rectangle Self="{id}" ItemTransform="1 0 0 1 0 0">
+ <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>
+ {inner}
+ </Rectangle>"#
+ )
+ };
+ 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"/>
+ {}{}
+ </Spread>
+ </idPkg:Spread>"#,
+ rect("a", transparency),
+ rect("b", "")
+ );
+ import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", &spread)])).unwrap()
+}
+
+#[test]
+fn imports_gradient_and_directional_feathers() {
+ let d = feather_fixture(
+ r#"<TransparencySetting>
+ <GradientFeatherSetting Applied="true" Type="Linear" Angle="0" Length="50" GradientStart="10 20">
+ <OpacityGradientStop Self="s0" Opacity="90" Location="20"/>
+ <OpacityGradientStop Self="s2" Opacity="10" Location="80" Midpoint="40"/>
+ <OpacityGradientStop Self="s1" Opacity="55" Location="50" Midpoint="50"/>
+ </GradientFeatherSetting>
+ <DirectionalFeatherSetting Applied="true" LeftWidth="3" RightWidth="4" TopWidth="5" BottomWidth="6" Angle="0" Noise="0" ChokeAmount="0"/>
+ </TransparencySetting>"#,
+ );
+ let items = &d.spreads[0].items;
+ let gf = &items[0].effects.gradient_feather;
+ assert!(gf.on && !gf.radial);
+ assert!((gf.start - 0.9).abs() < 1e-6 && (gf.end - 0.1).abs() < 1e-6, "{gf:?}");
+ let v = gf.vector.unwrap();
+ for (a, b) in v.iter().zip([20.0, 20.0, 50.0, 20.0]) {
+ assert!((a - b).abs() < 1e-9, "{v:?}");
+ }
+ let df = &items[0].effects.directional_feather;
+ assert!(df.on);
+ assert_eq!(df.widths, [5.0, 3.0, 6.0, 4.0]);
+ assert_eq!(items[1].effects, designcraft_doc::Effects::default());
+
+ // Not applied: the settings stay off.
+ let off = feather_fixture(
+ r#"<TransparencySetting>
+ <GradientFeatherSetting Applied="false" Length="50" GradientStart="10 20"/>
+ <DirectionalFeatherSetting Applied="false" LeftWidth="3"/>
+ </TransparencySetting>"#,
+ );
+ assert_eq!(off.spreads[0].items[0].effects, designcraft_doc::Effects::default());
+}
+
+#[test]
+fn gradient_and_directional_feathers_round_trip() {
+ use designcraft_doc::{DirectionalFeather, GradientFeather, Item, ItemId};
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let add = |d: &mut Document, effects: designcraft_doc::Effects| {
+ let mut it = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 120.0)));
+ it.effects = effects;
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ };
+ let linear = designcraft_doc::Effects {
+ gradient_feather: GradientFeather { on: true, radial: false, angle: 0.0, start: 0.75, end: 0.25, vector: Some([50.0, 60.0, 110.0, 60.0]) },
+ directional_feather: DirectionalFeather { on: true, widths: [1.0, 2.0, 3.0, 4.0] },
+ ..Default::default()
+ };
+ let radial = designcraft_doc::Effects {
+ gradient_feather: GradientFeather { on: true, radial: true, angle: 30.0, start: 0.0, end: 1.0, vector: None },
+ ..Default::default()
+ };
+ add(&mut d, linear.clone());
+ add(&mut d, radial.clone());
+ add(&mut d, designcraft_doc::Effects::default());
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let effects: Vec<_> = back.spreads[0].items.iter().map(|i| i.effects.clone()).collect();
+ assert_eq!(effects, [linear, radial, designcraft_doc::Effects::default()]);
+}
+
+/// One single-column text frame at (0, 0)-(300, 200) on page 1, beside a 100 pt wide rectangle
+/// with a bounding-box wrap and `wrap_props` inside its `TextWrapPreference/Properties`.
+fn custom_wrap_fixture(wrap_props: &str) -> Vec<u8> {
+ let rect = |w: f64, h: f64| {
+ format!(
+ r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray><PathPointType Anchor="0 0"/><PathPointType Anchor="0 {h}"/><PathPointType Anchor="{w} {h}"/><PathPointType Anchor="{w} 0"/></PathPointArray></GeometryPathType></PathGeometry>"#
+ )
+ };
+ let spread = format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <Spread Self="sp1" PageCount="2" ItemTransform="1 0 0 1 0 0">
+ <Page Self="p1" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350"/>
+ <Page Self="p2" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350"/>
+ <TextFrame Self="t1" ParentStory="s1" PreviousTextFrame="n" NextTextFrame="n" ItemLayer="L1" ItemTransform="1 0 0 1 -450 -300">
+ <Properties>{frame}</Properties>
+ </TextFrame>
+ <Rectangle Self="w" ItemLayer="L1" ItemTransform="1 0 0 1 -450 -300">
+ <Properties>{obj}</Properties>
+ <TextWrapPreference TextWrapMode="BoundingBoxTextWrap" TextWrapSide="BothSides"><Properties>{wrap_props}<TextWrapOffset Top="0" Left="0" Bottom="0" Right="0"/></Properties></TextWrapPreference>
+ </Rectangle>
+ </Spread>
+</idPkg:Spread>"#,
+ frame = rect(300.0, 200.0),
+ obj = rect(100.0, 200.0),
+ );
+ let words = "wrap ".repeat(120);
+ let story = format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <Story Self="s1"><ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{words}</Content></CharacterStyleRange></ParagraphStyleRange></Story>
+</idPkg:Story>"#
+ );
+ zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", &spread),
+ ("Stories/Story_s1.xml", &story),
+ ])
+}
+
+/// The custom boundary: 40 pt wide, the full height of the 100 pt wide rectangle.
+const NARROW_WRAP_PATH: &str = r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray><PathPointType Anchor="0 0" LeftDirection="0 0" RightDirection="0 0"/><PathPointType Anchor="0 200" LeftDirection="0 200" RightDirection="0 200"/><PathPointType Anchor="40 200" LeftDirection="40 200" RightDirection="40 200"/><PathPointType Anchor="40 0" LeftDirection="40 0" RightDirection="40 0"/></PathPointArray></GeometryPathType></PathGeometry>"#;
+
+fn wrapping_item(d: &Document) -> &designcraft_doc::Item {
+ d.spreads[0].items.iter().find(|i| i.wrap.mode != designcraft_doc::WrapMode::None).unwrap()
+}
+
+/// Leftmost line start in the frame.
+fn first_line_x(d: &Document) -> f64 {
+ let sid = *d.stories.keys().next().unwrap();
+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());
+ assert!(cs.frames[0].lines.len() > 3);
+ cs.frames[0].lines.iter().map(|l| l.x0).fold(f64::INFINITY, f64::min)
+}
+
+#[test]
+fn custom_wrap_boundary_imports_composes_and_round_trips() {
+ let plain = import_idml_with(&custom_wrap_fixture(""), &|_| None).unwrap();
+ assert_eq!(wrapping_item(&plain).wrap.path, None);
+ assert!(first_line_x(&plain) >= 100.0 - 1e-6, "the frame's bounds push text to x = 100");
+
+ let d = import_idml_with(&custom_wrap_fixture(NARROW_WRAP_PATH), &|_| None).unwrap();
+ let path = wrapping_item(&d).wrap.path.clone().unwrap();
+ assert_eq!(path.bounds(), Some(Rect::new(0.0, 0.0, 40.0, 200.0)));
+ let x = first_line_x(&d);
+ assert!((40.0 - 1e-6..100.0).contains(&x), "lines start at the custom boundary's edge, not the frame's: {x}");
+
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(wrapping_item(&back).wrap.path, Some(path));
+}
+
+#[test]
+fn hostile_custom_wrap_boundary_is_dropped() {
+ let nan = NARROW_WRAP_PATH.replacen(r#"Anchor="40 200""#, r#"Anchor="NaN 200""#, 1);
+ let inf = NARROW_WRAP_PATH.replacen(r#"Anchor="40 200""#, r#"Anchor="inf 200""#, 1);
+ let huge = format!(
+ r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{}</PathPointArray></GeometryPathType></PathGeometry>"#,
+ r#"<PathPointType Anchor="1 1"/>"#.repeat(50_000)
+ );
+ let empty = r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray/></GeometryPathType></PathGeometry>"#;
+ for props in [nan.as_str(), inf.as_str(), huge.as_str(), empty] {
+ let d = import_idml_with(&custom_wrap_fixture(props), &|_| None).unwrap();
+ let it = wrapping_item(&d);
+ assert_eq!(it.wrap.mode, designcraft_doc::WrapMode::BoundingBox);
+ assert_eq!(it.wrap.path, None);
+ assert!(first_line_x(&d) >= 100.0 - 1e-6);
+ }
+}
+
+/// A family name keeps its spaces ("Minion Pro " is a font of its own) and `FontStyle="Nothing"`
+/// leaves the style to the paragraph, also after an export.
+#[test]
+fn applied_font_keeps_spaces_and_font_style_nothing_inherits() {
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Text%3aBody" FontStyle="Bold">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" FontStyle="Nothing"><Properties><AppliedFont type="string">DC Space </AppliedFont></Properties><Content>Spaced</Content></CharacterStyleRange>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" FontStyle="$ID/Nothing"><Content> plain</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let check = |d: &Document| {
+ let s = d.stories.values().find(|s| s.text.contains("Spaced")).unwrap();
+ let (_, base) = d.styles.resolve_para(&s.paras[0]);
+ let runs: Vec<_> = s.runs().map(|(_, f)| f.clone()).collect();
+ assert_eq!(runs[0].over.font_family.as_deref(), Some("DC Space "));
+ for f in &runs {
+ assert_eq!(d.styles.resolve_char(&base, f).font_style, "Bold", "the enclosing range's style");
+ }
+ };
+ let d = import_idml(&fixture_with_story(story)).unwrap();
+ check(&d);
+ check(&import_idml(&export_idml(&d)).unwrap());
+}
+
+fn tracked_story(body: &str) -> String {
+ format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <Story Self="s1">{body}</Story>
+</idPkg:Story>"#
+ )
+}
+
+const CSR: &str = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]">"#;
+
+#[test]
+fn tracked_deleted_text_takes_no_room_and_round_trips() {
+ let psr = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle">"#;
+ let kwn = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle" KeepWithNext="2">"#;
+ let tracked = tracked_story(&format!(
+ r#"{psr}{CSR}<Content>The first paragraph keeps a </Content><Change Self="c1" ChangeType="DeletedText"><Content>deleted </Content></Change><Content>word.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>
+{kwn}{CSR}<Change Self="c2" ChangeType="DeletedText"><Br/></Change></CharacterStyleRange></ParagraphStyleRange>
+{psr}{CSR}<Change Self="c3" ChangeType="InsertedText"><Content>New </Content></Change><Content>second paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#
+ ));
+ let plain = tracked_story(&format!(
+ r#"{psr}{CSR}<Content>The first paragraph keeps a word.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>
+{psr}{CSR}<Content>New second paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#
+ ));
+ let lines = |d: &Document| {
+ let sid = *d.stories.keys().next().unwrap();
+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());
+ cs.frames.iter().flat_map(|f| f.lines.iter().map(|l| (l.baseline, l.x0, l.end_x))).collect::<Vec<_>>()
+ };
+ let d = import_idml_with(&fixture_with_story(&tracked), &|_| None).unwrap();
+ let story = d.stories.values().next().unwrap();
+ assert_eq!(story.text, "The first paragraph keeps a deleted word.\n\nNew second paragraph.");
+ let marks = |s: &designcraft_doc::Story| s.runs().map(|(r, f)| (s.text[r].to_string(), f.over.change)).collect::<Vec<_>>();
+ use designcraft_doc::ChangeMark::{Deleted, Inserted};
+ let want = vec![
+ ("The first paragraph keeps a ".to_string(), None),
+ ("deleted ".to_string(), Some(Deleted)),
+ ("word.\n".to_string(), None),
+ ("\n".to_string(), Some(Deleted)),
+ ("New ".to_string(), Some(Inserted)),
+ ("second paragraph.".to_string(), None),
+ ];
+ assert_eq!(marks(story), want);
+ let reference = import_idml_with(&fixture_with_story(&plain), &|_| None).unwrap();
+ let expected = lines(&reference);
+ assert!(expected.len() >= 2);
+ assert_eq!(lines(&d), expected);
+ // Export writes the changes back as `Change` elements.
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(marks(back.stories.values().next().unwrap()), want);
+}
+
+#[test]
+fn same_para_style_spacing_imports_and_round_trips() {
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" SameParaStyleSpacing="0">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Gap</Content><Br/></CharacterStyleRange>
+ </ParagraphStyleRange>
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" SameParaStyleSpacing="Nothing">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Ignore</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let d = import_idml(&fixture_with_story(story)).unwrap();
+ let st = d.stories.values().find(|s| s.text.contains("Gap")).unwrap();
+ assert_eq!(st.paras[0].para.same_para_style_spacing, Some(Some(0.0)));
+ // Ignore is an explicit "off", not an unset value.
+ assert_eq!(st.paras[1].para.same_para_style_spacing, Some(None));
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let b = back.stories.values().find(|s| s.text.contains("Gap")).unwrap();
+ assert_eq!(b.paras[0].para.same_para_style_spacing, Some(Some(0.0)));
+ // The explicit Ignore survives the round trip too.
+ assert_eq!(b.paras[1].para.same_para_style_spacing, Some(None));
+}
+
+/// SameParaStyleSpacing set as a `Properties` element on the based-on style (`Normal`) reaches
+/// the headings: consecutive headings sit one leading apart. SetIgnore keeps the usual spacing.
+#[test]
+fn same_para_style_spacing_from_a_based_on_style_element_closes_the_gap() {
+ let styles = r#"<?xml version="1.0" encoding="UTF-8"?>
+<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <RootCharacterStyleGroup Self="rc">
+ <CharacterStyle Self="CharacterStyle/$ID/[No character style]" Name="$ID/[No character style]"/>
+ </RootCharacterStyleGroup>
+ <RootParagraphStyleGroup Self="rp">
+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12">
+ <Properties><AppliedFont type="string">Source Serif 4</AppliedFont><Leading type="unit">13</Leading></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle">
+ <Properties><BasedOn type="string">$ID/[No paragraph style]</BasedOn><SameParaStyleSpacing type="unit">0</SameParaStyleSpacing></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Heading" Name="Heading" SpaceBefore="18" SpaceAfter="4.5">
+ <Properties><BasedOn type="object">ParagraphStyle/$ID/NormalParagraphStyle</BasedOn></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Loose" Name="Loose" SpaceBefore="18" SpaceAfter="4.5">
+ <Properties><BasedOn type="object">ParagraphStyle/$ID/NormalParagraphStyle</BasedOn><SameParaStyleSpacing type="enumeration">SetIgnore</SameParaStyleSpacing></Properties>
+ </ParagraphStyle>
+ </RootParagraphStyleGroup>
+</idPkg:Styles>"#;
+ let para = |style: &str, text: &str| {
+ format!(
+ r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/{style}"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{text}</Content><Br/></CharacterStyleRange></ParagraphStyleRange>"#
+ )
+ };
+ let story = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">{}{}{}{}</Story></idPkg:Story>"#,
+ para("Heading", "One"),
+ para("Heading", "Two"),
+ para("Loose", "Three"),
+ para("Loose", "Four")
+ );
+ let d = import_idml(&fixture_with_table_styles(styles, &story)).unwrap();
+ let sid = d.stories.iter().find(|(_, s)| s.text.contains("One")).map(|(id, _)| *id).unwrap();
+ let cs = designcraft_compose::compose_story(&d, sid, &Default::default());
+ let baseline = |para: usize| cs.frames[0].lines.iter().find(|l| l.para == para).unwrap().baseline;
+ assert!((baseline(1) - baseline(0) - 13.0).abs() < 1e-6, "{} {}", baseline(0), baseline(1));
+ assert!((baseline(3) - baseline(2) - 13.0 - 4.5 - 18.0).abs() < 1e-6, "{} {}", baseline(2), baseline(3));
+}
+
+/// Composed lines (baseline, left, right) of the only story.
+fn story_lines(d: &Document) -> Vec<(f64, f64, f64)> {
+ let sid = *d.stories.keys().next().unwrap();
+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());
+ cs.frames.iter().flat_map(|f| f.lines.iter().map(|l| (l.baseline, l.x0, l.end_x))).collect()
+}
+
+const PSR: &str = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle">"#;
+
+/// Lays out like the same story without the deleted paragraph.
+fn assert_deleted_para_takes_no_room(deleted: &str, deleted_text: &str) {
+ let tracked = tracked_story(&format!(
+ r#"{PSR}{CSR}<Content>First live paragraph.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>
+{deleted}
+{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#
+ ));
+ let plain = tracked_story(&format!(
+ r#"{PSR}{CSR}<Content>First live paragraph.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>
+{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#
+ ));
+ let d = import_idml_with(&fixture_with_story(&tracked), &|_| None).unwrap();
+ let story = d.stories.values().next().unwrap();
+ let marks: Vec<_> = story.runs().map(|(r, f)| (story.text[r].to_string(), f.over.change)).collect();
+ let want = vec![
+ ("First live paragraph.\n".to_string(), None),
+ (deleted_text.to_string(), Some(designcraft_doc::ChangeMark::Deleted)),
+ ("Second live paragraph.".to_string(), None),
+ ];
+ assert_eq!(marks, want);
+ let expected = story_lines(&import_idml_with(&fixture_with_story(&plain), &|_| None).unwrap());
+ assert_eq!(expected.len(), 2);
+ assert_eq!(story_lines(&d), expected);
+}
+
+#[test]
+fn tracked_deleted_paragraph_range_stays_deleted() {
+ assert_deleted_para_takes_no_room(
+ &format!(
+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Deleted text</Content><Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#
+ ),
+ "Deleted text\n",
+ );
+}
+
+#[test]
+fn tracked_deleted_frame_break_does_not_break() {
+ let fb = "\u{E003}";
+ let nf = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" ParagraphBreakType="NextFrame">"#;
+ // The change around the paragraph range.
+ assert_deleted_para_takes_no_room(
+ &format!(
+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Gone</Content></CharacterStyleRange>{nf}<Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#
+ ),
+ &format!("Gone{fb}\n"),
+ );
+ // The change inside the character range.
+ assert_deleted_para_takes_no_room(
+ &format!(
+ r#"{PSR}{nf}<Change Self="c1" ChangeType="DeletedText"><Content>Gone</Content><Br/></Change></CharacterStyleRange></ParagraphStyleRange>"#
+ ),
+ &format!("Gone{fb}\n"),
+ );
+}
+
+#[test]
+fn live_frame_break_before_deleted_paragraph_still_breaks() {
+ let nf = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" ParagraphBreakType="NextFrame">"#;
+ let first =
+ format!(r#"{PSR}{CSR}<Content>First live paragraph.</Content></CharacterStyleRange>{nf}<Br/></CharacterStyleRange></ParagraphStyleRange>"#);
+ let second = format!(r#"{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#);
+ let deleted = format!(
+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Gone</Content><Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#
+ );
+ let import = |body: String| import_idml_with(&fixture_with_story(&tracked_story(&body)), &|_| None).unwrap();
+ let reference = import(format!("{first}\n{second}"));
+ let sid = *reference.stories.keys().next().unwrap();
+ let per_frame: Vec<usize> =
+ designcraft_compose::compose_story(&reference, sid, &Default::default()).frames.iter().map(|f| f.lines.len()).collect();
+ assert!(per_frame.first() == Some(&1) && per_frame.get(1).is_some_and(|n| *n > 0), "the break sends the second paragraph on");
+ let expected = story_lines(&reference);
+ assert_eq!(story_lines(&import(format!("{first}\n{deleted}\n{second}"))), expected);
+}
+
+#[test]
+fn vertical_balance_columns_balances_the_imported_frame() {
+ let text = "Balanced columns end at about the same depth when the story ends in the frame. ".repeat(4);
+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
+ <idPkg:Spread src="Spreads/Spread_s.xml"/>
+ <idPkg:Story src="Stories/Story_s1.xml"/>
+ </Document>"#;
+ let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+ <Spread Self="s">
+ <Page Self="p" GeometricBounds="0 0 400 400" ItemTransform="1 0 0 1 0 0"/>
+ <TextFrame Self="f" ParentStory="s1">
+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>
+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 150"/>
+ <PathPointType Anchor="300 150"/><PathPointType Anchor="300 0"/>
+ </PathPointArray></GeometryPathType></PathGeometry></Properties>
+ <TextFramePreference TextColumnCount="2" TextColumnGutter="12" VerticalBalanceColumns="true"/>
+ </TextFrame>
+ </Spread>
+ </idPkg:Spread>"#;
+ let story = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange><CharacterStyleRange><Content>{text}</Content></CharacterStyleRange></ParagraphStyleRange>
+ </Story></idPkg:Story>"#
+ );
+ let mut d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread), ("Stories/Story_s1.xml", &story)])).unwrap();
+ let sid = *d.stories.keys().next().unwrap();
+ let per_column = |d: &Document| {
+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());
+ assert!(!cs.is_overset());
+ let ft = &cs.frames[0];
+ [0, 1].map(|c| ft.lines.iter().filter(|l| l.column == c).count())
+ };
+ let on = per_column(&d);
+ assert!(on[1] > 0 && on[0] - on[1] <= 1, "balanced: {on:?}");
+ let fid = d.stories[&sid].frames[0];
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.balance_columns = false;
+ let off = per_column(&d);
+ assert!(off[0] > off[1] + 1, "unbalanced: {off:?}");
+}
+
+#[test]
+fn type_on_a_path_keeps_its_start_and_end_brackets() {
+ use designcraft_geom::{Anchor, PathData, Point, SubPath};
+ for end in [Some(250.0), None] {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let id = designcraft_doc::ItemId(d.alloc());
+ let line = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(100.0, 300.0)), Anchor::corner(Point::new(500.0, 300.0))], false));
+ let mut it = designcraft_doc::Item::new(id, lid, Shape::GraphicLine, line);
+ let sid = designcraft_doc::StoryId(d.alloc());
+ let mut tf = designcraft_doc::TextFrame { story: sid, options: Default::default() };
+ tf.options.path = Some(designcraft_doc::PathType { start: 30.0, end, ..Default::default() });
+ it.content = designcraft_doc::Content::Text(tf);
+ let mut story = designcraft_doc::Story::with_text(sid, "Along", Default::default());
+ story.frames = vec![id];
+ d.stories.insert(sid, std::sync::Arc::new(story));
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let pt = back.spreads[0].items[0].text_frame().unwrap().options.path.clone().unwrap();
+ assert!((pt.start - 30.0).abs() < 1e-6, "{pt:?}");
+ assert_eq!(pt.end.map(|e| e.round()), end, "an end bracket at the path's end is no end bracket");
+ }
+}
+
+/// Based on Parent travels as the parent pages' `AppliedMaster`; a cycle in a file is broken on
+/// import with a warning.
+#[test]
+fn parent_based_on_round_trips_and_cycles_are_broken() {
+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });
+ let a = d.parents[0].id;
+ let b = d.add_parent("B", "Opening", 2, 12.0, designcraft_doc::Margins::uniform(36.0));
+ d.add_parent("C", "Closing", 2, 12.0, designcraft_doc::Margins::uniform(36.0));
+ let set = |d: &mut Document, pi: usize, on| std::sync::Arc::make_mut(&mut d.parents[pi]).parent.as_mut().unwrap().based_on = on;
+ set(&mut d, 1, Some(a));
+ set(&mut d, 2, Some(b));
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let base_of = |d: &Document, pi: usize| {
+ let b = d.parents[pi].parent.as_ref().unwrap().based_on?;
+ d.parents.iter().find(|p| p.id == b).and_then(|p| p.parent.as_ref()).map(|i| i.prefix.clone())
+ };
+ assert_eq!((base_of(&back, 0), base_of(&back, 1), base_of(&back, 2)), (None, Some("A".into()), Some("B".into())));
+
+ set(&mut d, 0, Some(b));
+ let r = import_idml_report(&export_idml(&d), &|_| None).unwrap();
+ assert!(r.warnings.iter().any(|w| w.contains("A-Parent") && w.contains("cycle")), "{:?}", r.warnings);
+ assert_eq!((base_of(&r.document, 0), base_of(&r.document, 1)), (None, Some("A".into())));
+}
++
+ #[test]
+ fn object_style_effects_round_trip() {
+ use designcraft_doc::{DropShadow, Effects, ObjectStyle};
+ let mut d = Document::new(&NewDocument::default());
+ let fx = Effects {
+ drop_shadow: DropShadow { on: true, distance: 5.0, size: 12.0, opacity: 0.28, ..Default::default() },
+ feather: 3.0,
+ ..Default::default()
+ };
+ d.styles_mut().object.push(ObjectStyle { name: "Photo".into(), effects: Some(fx.clone()), ..Default::default() });
+ d.styles_mut().object.push(ObjectStyle { name: "Plain".into(), fill: Some(Fill::swatch("Black")), ..Default::default() });
+ let lid = d.default_layer();
+ let id = designcraft_doc::ItemId(d.alloc());
+ let mut it = designcraft_doc::Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 140.0)));
+ it.object_style = "Photo".into();
+ it.effects = fx.clone();
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ // A frame that turned the style's effects off writes them off, so it doesn't take the style's.
+ let id = designcraft_doc::ItemId(d.alloc());
+ let mut off = designcraft_doc::Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(200.0, 40.0, 300.0, 140.0)));
+ off.object_style = "Photo".into();
+ d.insert_item(SpreadRef::Doc(0), off, None).unwrap();
+
+ let bytes = export_idml(&d);
+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
+ let mut spreads = String::new();
+ for i in 0..zip.len() {
+ let mut f = zip.by_index(i).unwrap();
+ if f.name().starts_with("Spreads/") {
+ std::io::Read::read_to_string(&mut f, &mut spreads).unwrap();
+ }
+ }
+ assert!(spreads.contains(r#"<DropShadowSetting Mode="None""#) && spreads.contains(r#"<FeatherSetting Mode="None""#), "{spreads}");
+ let back = import_idml(&bytes).unwrap();
+ let style = |n: &str| back.styles.object.iter().find(|s| s.name == n).unwrap();
+ let got = style("Photo").effects.clone().unwrap();
+ let ds = &got.drop_shadow;
+ assert!(ds.on && ds.size == 12.0 && (ds.opacity - 0.28).abs() < 1e-6, "{ds:?}");
+ assert!((ds.distance - 5.0).abs() < 1e-6 && (ds.angle - 135.0).abs() < 1e-6, "{ds:?}");
+ assert_eq!(got.feather, 3.0);
+ assert!(style("Plain").effects.is_none());
+ // The frame's effects are the style's, so it follows later edits of the style.
+ let frames: Vec<_> = back.spreads[0].items.iter().filter(|i| i.object_style == "Photo").collect();
+ assert_eq!(frames[0].effects, got);
+ assert_eq!(frames[1].effects, Effects::default());
+ }
+
+ #[test]
+ fn object_style_effects_import_by_category_and_based_on() {
+ let styles = r#"
+ <ObjectStyle Self="ObjectStyle/Base" Name="Base">
+ <TransparencySetting>
+ <DropShadowSetting Mode="Drop" XOffset="3" YOffset="4" Size="9" Opacity="50"/>
+ <FeatherSetting Mode="Standard" Width="6"/>
+ </TransparencySetting>
+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="true" EnableFeather="false"/>
+ </ObjectStyle>
+ <ObjectStyle Self="ObjectStyle/Child" Name="Child">
+ <Properties><BasedOn type="object">ObjectStyle/Base</BasedOn></Properties>
+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="true" EnableFeather="true"/>
+ </ObjectStyle>
+ <ObjectStyle Self="ObjectStyle/Off" Name="Off">
+ <TransparencySetting><DropShadowSetting Mode="Drop" Size="9"/></TransparencySetting>
+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="false" EnableFeather="false"/>
+ </ObjectStyle>
+ <ObjectStyle Self="ObjectStyle/Loop" Name="Loop">
+ <Properties><BasedOn type="object">ObjectStyle/Loop</BasedOn></Properties>
+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="true"/>
+ </ObjectStyle>"#;
+ let d = inset_fixture("", styles);
+ let fx = |n: &str| d.styles.object.iter().find(|s| s.name == n).unwrap().effects.clone();
+ let base = fx("Base").unwrap();
+ assert!(base.drop_shadow.on && base.drop_shadow.size == 9.0 && (base.drop_shadow.distance - 5.0).abs() < 1e-9);
+ assert_eq!(base.feather, 0.0, "EnableFeather=false");
+ let child = fx("Child").unwrap();
+ assert_eq!((child.drop_shadow.size, child.feather), (9.0, 6.0), "settings from the BasedOn style");
+ assert!(fx("Off").is_none());
+ assert!(!fx("Loop").unwrap().drop_shadow.on);
+ }
diff --cc docs/target-app-parity.md
index 2d918d8ad,9f924101b..0501242c1
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@@ -1,6 -1,6 +1,6 @@@
# DesignCraft parity with Adobe InDesign
- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (object styles carry effects) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
The authoritative assessment of how close DesignCraft is to Adobe InDesign. [ROADMAP.md](../ROADMAP.md)
summarizes it; [gaps.md](gaps.md) lists every known shortfall one at a time; the feature-by-feature
@@@ -410,10 -401,10 +410,11 @@@ It is evidence of breadth: each item ex
- Nested styles (through/up to N sentences, words, characters, letters, digits, tabs, breaks, spaces or given characters) and GREP styles (regex → character style), edited in Paragraph Style Options and composed under local formatting; `ui.dialog.open` for agents. Nested line styles are still to come; nested and GREP styles round-trip through IDML.
- Table and cell styles (round-trip through IDML): cell styles (fill, insets, vertical justification, strokes, paragraph style) and table styles (region cell styles, border, alternating rows, spacing); apply from the Table panel, edits re-apply to every user; `style.cell.*`, `style.table.*`.
- Style groups: paragraph and character styles shown in group folders, Move to Group (new, existing, none); `style.group` renames every use (styles, stories, table cells, footnotes, object styles).
+ - Object styles carry effects: `style.object.create` keeps the selection's effects, `style.object.apply` sets them, and `style.object.edit {name, dropShadow?, feather?, …, effects?: null}` changes them on the style and on every item whose effects still match it (items with their own effects keep them; `style.object.clearOverrides` returns them to the style). New frames take their default style's effects. Effect values that aren't finite numbers are refused and the others clamped, in these commands and in the `object.*` effect commands. IDML carries only the drop shadow and feather, for ObjectStyles (read per effects category flag, settings from the BasedOn chain) as for items; the other effects stay in `.designcraft` files. There is no Object Style Options dialog yet.
- Scrubby zoom: drag the Zoom tool left or right to zoom continuously around the press point.
+- Spring-loaded Zoom: hold Cmd+Space (Ctrl+Space on Windows/Linux) for the Zoom cursor and click/scrubby zoom; Alt-click zooms out. Release returns to the previous tool without changing the document or undo history. Text-frame and text-field typing suppress the shortcut; Space remains Hand.
- Guides belong to the active layer: hidden with it (or with its Show Guides off) and locked with it.
-- Pencil tool (N): freehand strokes simplified to smooth paths (Alt closes); Smooth and Erase tools re-fit or remove the stretch you drag along (`path.smooth`, `path.erase`).
+- Pencil tool (N): freehand strokes, shown as you draw in the layer's colour, simplified to smooth paths (Alt closes); Smooth and Erase tools re-fit or remove the stretch you drag along (`path.smooth`, `path.erase`).
- Edit › Keyboard Shortcuts: every command, click and press the new keys, conflicts shown, per-command and global reset; `window.setShortcut`.
- Primary Text Frame (New Document) and Smart Text Reflow: pages are added while the primary story oversets and empty ones at the end removed, in the same undo step (Preferences › Type).
- Glyphs panel: every character of any font (rendered by our renderer), search by character or U+code, click to insert, recently used.