Skip to content

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

IDML: import and wrap around custom text-wrap boundaries

aiongg47d17ca6f508
diff --git a/Cargo.lock b/Cargo.lock
index 9473c974a..519019fd6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1028,6 +1028,7 @@ dependencies = [
"designcraft-compose",
"designcraft-doc",
"designcraft-geom",
+ "log",
"quick-xml 0.38.4",
"thiserror 2.0.21",
"zip",
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 30b81c7d6..25bbb11eb 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -292,7 +292,7 @@ pub struct Exclusion {
pub mode: WrapMode,
/// Where text may go beside the object. Spine sides are resolved to `LeftSide`/`RightSide`.
pub side: WrapSide,
- /// Contour wrap: the outline the text follows (None wraps around `rect`).
+ /// Contour wrap, or a custom boundary: the outline the text follows (None wraps around `rect`).
pub contour: Option<Contour>,
}
@@ -387,6 +387,12 @@ pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, in
WrapSide::AwayFromSpine => WrapSide::RightSide,
s => s,
};
+ // A custom boundary already includes the offsets.
+ if let Some(custom) = other.wrap.path.as_ref().and_then(|p| Contour::of(&p.to_bezpath(), inv * xf, 0.0)) {
+ let rect = custom.bounds();
+ let contour = matches!(other.wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom);
+ return Exclusion { rect, mode: other.wrap.mode, side, contour };
+ }
let contour = (other.wrap.mode == WrapMode::Contour && other.shape != designcraft_doc::Shape::Group)
.then(|| contour_path(other))
.and_then(|path| Contour::of(&path, inv * xf, other.wrap.offsets[0]));
@@ -2242,8 +2248,7 @@ fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, size: f64, rtl: bool)
let blocked = match ex.mode {
WrapMode::JumpToNextColumn if y1 > r.y0 && r.x0 < col.x1 && r.x1 > col.x0 => return vec![],
WrapMode::JumpObject if overlaps_band && r.x0 < col.x1 && r.x1 > col.x0 => return vec![],
- WrapMode::BoundingBox if overlaps_band => Some((r.x0, r.x1)),
- WrapMode::Contour if overlaps_band => match &ex.contour {
+ WrapMode::BoundingBox | WrapMode::Contour if overlaps_band => match &ex.contour {
Some(c) => c.band_extent(y0, y1),
None => Some((r.x0, r.x1)),
},
diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs
index 4c480808e..57fd21b2a 100644
--- a/crates/doc/src/item.rs
+++ b/crates/doc/src/item.rs
@@ -436,7 +436,7 @@ pub enum ContourType {
}
/// Text Wrap panel settings.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct TextWrap {
pub mode: WrapMode,
@@ -445,6 +445,11 @@ pub struct TextWrap {
pub invert: bool,
pub side: WrapSide,
pub contour: ContourType,
+ /// A custom wrap boundary in the item's inner space, offsets already included. Bounding-box
+ /// and contour wraps follow it instead of the frame; other modes use its bounds. Resizing the
+ /// item transforms it with the path; other path edits keep it as it is.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub path: Option<PathData>,
}
/// Frame fitting options (Object → Fitting → Frame Fitting Options).
diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs
index bd5320799..64e3869de 100644
--- a/crates/engine/src/cmd/layout.rs
+++ b/crates/engine/src/cmd/layout.rs
@@ -50,6 +50,9 @@ fn adjust_layout(d: &mut designcraft_doc::Document, before: &[(designcraft_doc::
} else {
let inner = it.xf.inverse() * m * it.xf;
it.path.transform(inner);
+ if let Some(w) = &mut it.wrap.path {
+ w.transform(inner);
+ }
let ib = it.inner_bounds();
if let designcraft_doc::Content::Graphic(g) = &mut it.content {
// Content keeps its size but moves with the frame; auto-fit refits.
diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs
index 2facf6780..88c01d22c 100644
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@ -512,7 +512,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Wrap",
["Window"],
Some("Cmd+Alt+W"),
- "{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side or contour is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping, ids?}",
+ "{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side or contour is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping, ids?}; offset or contour drops an imported custom wrap boundary",
has_selection,
text_wrap
),
@@ -1003,6 +1003,9 @@ fn union_bounds(d: &Document, ids: &[ItemId]) -> Rect {
/// Transform an item's geometry in its own space: the path and the gradient vector with it.
pub(crate) fn bake(it: &mut Item, inner: Affine) {
it.path.transform(inner);
+ if let Some(w) = &mut it.wrap.path {
+ w.transform(inner);
+ }
if let Some([x0, y0, x1, y1]) = it.fill.gradient_vector {
let (a, b) = (inner * Point::new(x0, y0), inner * Point::new(x1, y1));
it.fill.gradient_vector = Some([a.x, a.y, b.x, b.y]);
@@ -1373,6 +1376,11 @@ fn text_wrap(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(c) = contour {
i.wrap.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() {
+ i.wrap.path = None;
+ }
},
false,
)
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index a0c6a66cd..854aa628c 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -523,6 +523,41 @@ fn object_set_flags_and_wrap_invert() {
assert!(s.execute("object.textWrap", &json!({"side": "middle"})).is_err());
}
+#[test]
+fn custom_wrap_path_follows_resize_and_yields_to_offsets() {
+ let mut s = session();
+ let r = s.execute("frame.create", &json!({"rect": [0, 0, 100, 100]})).unwrap();
+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
+ s.execute("selection.set", &json!({"ids": [id.0]})).unwrap();
+ s.execute("object.textWrap", &json!({"mode": "boundingBox"})).unwrap();
+ let inner = s.doc().unwrap().doc.item(id).unwrap().path.clone();
+ let custom = designcraft_geom::PathData::single(designcraft_geom::SubPath::polyline(
+ &[designcraft_geom::Point::new(0.0, 0.0), designcraft_geom::Point::new(40.0, 0.0), designcraft_geom::Point::new(0.0, 100.0)],
+ true,
+ ));
+ s.edit(|d, _| {
+ if let Some(it) = d.item_mut(id) {
+ it.wrap.path = Some(custom.clone());
+ }
+ Ok(())
+ })
+ .unwrap();
+ let wrap_path = |s: &Session| s.doc().unwrap().doc.item(id).unwrap().wrap.path.clone();
+ // Side and mode keep the boundary.
+ s.execute("object.textWrap", &json!({"side": "rightSide"})).unwrap();
+ s.execute("object.textWrap", &json!({"mode": "contour"})).unwrap();
+ assert_eq!(wrap_path(&s), Some(custom.clone()));
+ // Resizing scales it with the frame's path.
+ let b = inner.bounds().unwrap();
+ let to = [b.x0, b.y0, b.x0 + 2.0 * b.width(), b.y1];
+ s.execute("transform.resize", &json!({"from": [b.x0, b.y0, b.x1, b.y1], "to": to})).unwrap();
+ let w = wrap_path(&s).unwrap().bounds().unwrap();
+ assert!((w.width() - 80.0).abs() < 1e-6 && (w.height() - 100.0).abs() < 1e-6, "{w:?}");
+ // An offset rebuilds the wrap from the frame.
+ s.execute("object.textWrap", &json!({"offset": 6})).unwrap();
+ assert_eq!(wrap_path(&s), None);
+}
+
#[test]
fn gridify_while_drawing_frames() {
use designcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
diff --git a/crates/idml/Cargo.toml b/crates/idml/Cargo.toml
index 7e11a33f5..023ac183a 100644
--- a/crates/idml/Cargo.toml
+++ b/crates/idml/Cargo.toml
@@ -13,6 +13,7 @@ designcraft-geom = { workspace = true }
designcraft-color = { workspace = true }
designcraft-doc = { workspace = true }
thiserror = { workspace = true }
+log = { workspace = true }
quick-xml = { workspace = true }
zip = { workspace = true }
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index 84ed20c7c..d42c88c77 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -1723,13 +1723,16 @@ impl<'a> Ex<'a> {
.attr("ApplyToMasterPageOnly", "false")
.attr("TextWrapSide", names::wrap_side_out(w.side))
.attr("TextWrapMode", names::wrap_mode_out(w.mode)),
- vec![
- El::new("TextWrapOffset")
+ w.path
+ .iter()
+ .filter(|p| !p.is_empty())
+ .map(path_geometry)
+ .chain([El::new("TextWrapOffset")
.attr("Top", num(w.offsets[0]))
.attr("Left", num(w.offsets[1]))
.attr("Bottom", num(w.offsets[2]))
- .attr("Right", num(w.offsets[3])),
- ],
+ .attr("Right", num(w.offsets[3]))])
+ .collect(),
)
.child(El::new("ContourOption").attr("ContourType", names::contour_type_out(w.contour)).attr("IncludeInsideEdges", "false")),
);
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index 02ced7940..00562f19e 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -2106,6 +2106,12 @@ impl<'r> Importer<'r> {
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(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;
}
// Type on a path.
@@ -2540,6 +2546,46 @@ fn path_of(pg: &El) -> PathData {
PathData::new(subs)
}
+/// Anchors a custom text wrap boundary may have.
+const MAX_WRAP_PATH_ANCHORS: usize = 4096;
+
+/// A custom text wrap boundary (`TextWrapPreference/Properties/PathGeometry`), in the item's inner
+/// space like its own path. Hostile input is an error: too many anchors, a malformed or non-finite
+/// point, or no points at all.
+fn wrap_path_of(pg: &El) -> std::result::Result<PathData, &'static str> {
+ let finite = |s: Option<&str>| -> std::result::Result<Option<Point>, &'static str> {
+ let Some(s) = s else { return Ok(None) };
+ let v = nums(s);
+ match (v.first(), v.get(1)) {
+ (Some(&x), Some(&y)) if v.len() == 2 && x.is_finite() && y.is_finite() => Ok(Some(Point::new(x, y))),
+ _ => Err("malformed or non-finite point"),
+ }
+ };
+ let mut subs = Vec::new();
+ let mut n = 0usize;
+ for g in pg.find_all("GeometryPathType") {
+ let closed = g.get("PathOpen") != Some("true");
+ let mut anchors = Vec::new();
+ for p in g.find("PathPointArray").into_iter().flat_map(|arr| arr.find_all("PathPointType")) {
+ n = n.saturating_add(1);
+ if n > MAX_WRAP_PATH_ANCHORS {
+ return Err("too many points");
+ }
+ let a = finite(p.get("Anchor"))?.ok_or("point without an anchor")?;
+ let hin = finite(p.get("LeftDirection"))?.unwrap_or(a);
+ let hout = finite(p.get("RightDirection"))?.unwrap_or(a);
+ anchors.push(Anchor::with_handles(a, hin, hout));
+ }
+ if !anchors.is_empty() {
+ subs.push(SubPath::new(anchors, closed));
+ }
+ }
+ if subs.is_empty() {
+ return Err("no points");
+ }
+ Ok(PathData::new(subs))
+}
+
/// IDML link URI → file system path (`file:/a%20b` → `/a b`, `file:///C:/x` → `C:/x`).
pub(crate) fn uri_to_path(uri: &str) -> String {
let rest = uri.strip_prefix("file://").or_else(|| uri.strip_prefix("file:")).unwrap_or(uri);
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index c006ea1ad..7d40e4925 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -1416,7 +1416,7 @@ fn imports_and_round_trips_text_wrap_side_and_contour_type() {
]);
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;
+ 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)
@@ -1426,6 +1426,99 @@ fn imports_and_round_trips_text_wrap_side_and_contour_type() {
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;
+ 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));
}
+
+/// 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);
+ }
+}