Skip to content

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

Merge wrap-boundary: IDML: import and wrap around custom text-wrap boundaries

aionggb6cc59d3490f
diff --cc crates/compose/src/lib.rs
index 643ae68cd,25bbb11eb..a68579b94
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -450,21 -387,34 +450,27 @@@ fn wrap_exclusion
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)) {
++ if let Some(custom) = 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 = matches!(wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom);
++ return Exclusion { rect, mode: 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]));
+ let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|path| Contour::of(&path, inv * xf, o[0]));
let rect = contour.as_ref().map_or_else(|| inv.transform_rect_bbox(r), Contour::bounds);
- Exclusion { rect, mode: other.wrap.mode, side, contour }
+ Exclusion { rect, mode: wrap.mode, side, contour }
}
-/// The outline a contour wrap follows, in the item's inner space. Graphic frames follow their contour type; detected edges, alpha channels and image paths need
-/// the image, so they follow the frame's path (as other frames do).
-fn contour_path(it: &designcraft_doc::Item) -> designcraft_geom::BezPath {
- let frame = designcraft_geom::corners::apply(&it.path, &it.corners);
- if it.wrap.contour == designcraft_doc::ContourType::BoundingBox
- && let Some(g) = it.graphic()
- && let Some(fb) = it.path.bounds()
+/// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space.
+/// Bounding Box follows the part of the placed graphic the frame shows; detected edges, alpha
+/// channels and image paths need the image, so they follow the frame's path (as other frames do).
+fn contour_path(it: &Item, kind: designcraft_doc::ContourType) -> designcraft_geom::BezPath {
+ if kind == designcraft_doc::ContourType::BoundingBox
+ && let Some(r) = it.graphic().and_then(|g| g.shown_bounds(it.inner_bounds()))
{
- let gb = g.xf.transform_rect_bbox(Rect::new(0.0, 0.0, g.size.0, g.size.1));
- let r = gb.intersect(fb);
- if r.width() > 0.0 && r.height() > 0.0 {
- return designcraft_geom::kurbo::Shape::to_path(&r, 0.1);
- }
+ return designcraft_geom::kurbo::Shape::to_path(&r, 0.1);
}
- frame
+ designcraft_geom::corners::apply(&it.path, &it.corners)
}
/// One frame of the thread, ready for composition.
@@@ -2695,8 -2247,8 +2701,7 @@@ fn free_slots(f: &FrameSpec, col: Rect
let overlaps_band = r.y0 < y1 && r.y1 > y0;
let blocked = match ex.mode {
WrapMode::JumpToNextColumn if y1 > r.y0 && 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::JumpObject if overlaps_band && r.x0 < col.x1 && r.x1 > col.x0 => return vec![],
+ WrapMode::BoundingBox | WrapMode::Contour if overlaps_band => match &ex.contour {
Some(c) => c.band_extent(y0, y1),
None => Some((r.x0, r.x1)),
},
diff --cc crates/doc/src/item.rs
index 8f7733689,57fd21b2a..b83c6bacc
--- a/crates/doc/src/item.rs
+++ b/crates/doc/src/item.rs
@@@ -492,14 -445,13 +492,19 @@@ 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>,
}
+impl TextWrap {
+ pub fn is_default(&self) -> bool {
+ *self == TextWrap::default()
+ }
+}
+
/// Frame fitting options (Object → Fitting → Frame Fitting Options).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
diff --cc crates/engine/src/cmd/object.rs
index fc319a406,88c01d22c..2b37a86b4
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@@ -516,7 -512,7 +516,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, content?: bool (the placed graphic instead of its frame; default: whether the selection is the frame's content), 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",
++ "{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, content?: bool (the placed graphic instead of its frame; default: whether the selection is the frame's content), ids?}; offset or contour drops an imported custom wrap boundary",
has_selection,
text_wrap
),
@@@ -1651,25 -1361,26 +1654,30 @@@ fn text_wrap(s: &mut Session, p: &Value
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 {
- i.wrap.mode = m;
+ w.mode = m;
}
if let Some(o) = off {
- i.wrap.offsets = o;
+ w.offsets = o;
}
if let Some(v) = invert {
- i.wrap.invert = v;
+ w.invert = v;
}
if let Some(v) = side {
- i.wrap.side = v;
+ w.side = v;
}
if let Some(c) = contour {
- i.wrap.contour = c;
+ 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() {
+ i.wrap.path = None;
+ }
},
false,
)
diff --cc crates/engine/src/tests.rs
index f3c994ada,854aa628c..491876966
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -628,27 -523,41 +628,62 @@@ fn object_set_flags_and_wrap_invert()
assert!(s.execute("object.textWrap", &json!({"side": "middle"})).is_err());
}
+#[test]
+fn text_wrap_on_selected_content_sets_the_graphic_wrap() {
+ let mut s = session();
+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();
+ let f = s.execute("frame.create", &json!({"rect": [300, 300, 400, 400], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
+ s.execute("place.load", &json!({"base64": cmd::base64_encode(&png)})).unwrap();
+ s.execute("place.drop", &json!({"frame": f})).unwrap();
+ let item = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).cloned().unwrap();
+ s.execute("selection.set", &json!({"ids": [f], "content": true})).unwrap();
+ s.execute("object.textWrap", &json!({"mode": "boundingBox", "offset": 4})).unwrap();
+ let it = item(&s);
+ assert_eq!(it.wrap.mode, designcraft_doc::WrapMode::None, "the frame keeps no wrap");
+ let g = it.graphic().unwrap();
+ assert_eq!((g.wrap.mode, g.wrap.offsets), (designcraft_doc::WrapMode::BoundingBox, [4.0; 4]));
+ // The frame selected: the frame's own wrap.
+ s.execute("selection.set", &json!({"ids": [f]})).unwrap();
+ s.execute("object.textWrap", &json!({"mode": "jumpObject"})).unwrap();
+ let it = item(&s);
+ assert_eq!((it.wrap.mode, it.graphic().unwrap().wrap.mode), (designcraft_doc::WrapMode::JumpObject, designcraft_doc::WrapMode::BoundingBox));
+}
+
+ #[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 --cc crates/idml/src/export.rs
index ede5463e1,d42c88c77..632410ab4
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@@ -2704,25 -2474,6 +2704,28 @@@ fn margin_el(pg: &designcraft_doc::Page
}
/// `rule_color` is the IDML reference of the column rule's swatch.
+/// `TextWrapPreference` of a page item or a placed graphic.
+fn text_wrap_pref(w: &designcraft_doc::TextWrap) -> El {
+ with_props(
+ El::new("TextWrapPreference")
+ .attr("Inverse", bool_s(w.invert))
+ .attr("ApplyToMasterPageOnly", "false")
+ .attr("TextWrapSide", names::wrap_side_out(w.side))
+ .attr("TextWrapMode", names::wrap_mode_out(w.mode)),
- 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"))
+}
+
fn text_frame_pref(o: &TextFrameOptions, rule_color: &str) -> El {
let mut inset = El::new("InsetSpacing").attr("type", "list");
for v in o.inset {
diff --cc crates/idml/src/import.rs
index 1dfa5a234,00562f19e..f2a0c60ac
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@@ -2487,22 -2092,27 +2487,29 @@@ impl<'r> Importer<'r>
{
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")] };
+ }
}
// 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")),
- contour: names::contour_type_in(w.find("ContourOption").and_then(|c| c.get("ContourType")).unwrap_or("SameAsClipping")),
- ..TextWrap::default()
- };
- if let Some(o) = w.prop_el("TextWrapOffset") {
- tw.offsets =
- [o.num("Top").unwrap_or(0.0), o.num("Left").unwrap_or(0.0), o.num("Bottom").unwrap_or(0.0), o.num("Right").unwrap_or(0.0)];
- }
+ if let Some(w) = self.with_style(e, "TextWrapPreference") {
- it.wrap = text_wrap(&w);
++ 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;
}
// Type on a path.
if tag != "TextFrame"
@@@ -3181,11 -2546,46 +3188,51 @@@ fn path_of(pg: &El) -> PathData
PathData::new(subs)
}
+/// The page a placed PDF shows (0-based), from its `PDFAttribute` (`PageNumber` is 1-based).
+fn pdf_page_in(g: &El) -> u32 {
+ g.find("PDFAttribute").and_then(|a| a.get("PageNumber")).and_then(|v| v.trim().parse::<u32>().ok()).map_or(0, |n| n.saturating_sub(1))
+}
+
+ /// 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 --cc crates/idml/src/tests.rs
index 6c4605508,7d40e4925..d85b5139c
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -2859,92 -1430,95 +2859,185 @@@ fn imports_and_round_trips_text_wrap_si
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);
+ }
+ }