Skip to content

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

Layout: text wrap set on a placed graphic wraps text

aiongg7f2b5cfa6895
diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs
index 6d6b1b980..85b5c29d7 100644
--- a/crates/compose/src/cache.rs
+++ b/crates/compose/src/cache.rs
@@ -8,7 +8,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
-use designcraft_doc::{Document, Item, Story, StoryId, Styles, WrapMode};
+use designcraft_doc::{Document, Item, Story, StoryId, Styles};
use crate::vars::RunningIndex;
use crate::{ComposeOptions, ComposedStory};
@@ -261,7 +261,9 @@ fn signature(doc: &Document, story: &Arc<Story>) -> (Vec<usize>, Vec<Arc<Item>>)
if !spreads.contains(&loc.spread) {
spreads.push(loc.spread);
for it in &sp.items {
- if it.wrap.mode != WrapMode::None {
+ let mut wraps = false;
+ it.walk(&mut |i| wraps |= i.has_wrap());
+ if wraps {
sig.push(Arc::as_ptr(it) as usize);
keep.push(it.clone());
}
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 3dd7c25b3..ed4c9cd5b 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -29,11 +29,11 @@ use std::rc::Rc;
use std::sync::{Arc, Mutex};
use designcraft_doc::{
- Align, Composer, Document, FirstBaseline, GridAlign, ItemId, ParaProps, SpanColumns, StartParagraph, Story, StoryId, TabAlign, TextFrameOptions,
- VerticalJustification, WrapMode, story,
+ Align, Composer, Content, Document, FirstBaseline, GridAlign, Item, ItemId, ParaProps, SpanColumns, StartParagraph, Story, StoryId, TabAlign,
+ TextFrameOptions, VerticalJustification, WrapMode, story,
};
use designcraft_fonts::{FontDb, ScopedFonts};
-use designcraft_geom::{Point, Rect};
+use designcraft_geom::{Affine, Point, Rect};
use crate::breaker::{Break, Spacing};
pub use crate::cache::Cache;
@@ -344,6 +344,37 @@ pub struct ComposeOptions {
pub xrefs: Option<Arc<xref::XrefIndex>>,
}
+/// Nesting depth past which wrap obstacles inside groups are not collected.
+const MAX_WRAP_DEPTH: usize = 64;
+
+/// The text wrap obstacles of a page item, the graphic it holds and the items in it, as
+/// (spread-space box grown by the wrap offsets, mode). `parent` maps the item's parent space to
+/// the spread; `skip` is the text frame being wrapped.
+fn wrap_obstacles(it: &Item, parent: Affine, skip: ItemId, depth: usize, out: &mut Vec<(Rect, WrapMode)>) {
+ if it.id == skip || it.hidden || depth > MAX_WRAP_DEPTH {
+ return;
+ }
+ let grow = |r: Rect, o: [f64; 4]| Rect::new(r.x0 - o[1], r.y0 - o[0], r.x1 + o[3], r.y1 + o[2]);
+ if it.wrap.mode != WrapMode::None {
+ out.push((grow(parent.transform_rect_bbox(it.bounds()), it.wrap.offsets), it.wrap.mode));
+ }
+ let xf = parent * it.xf;
+ match &it.content {
+ // A wrap on the placed graphic follows the part of it the frame shows.
+ Content::Graphic(g) if g.wrap.mode != WrapMode::None => {
+ if let Some(r) = g.shown_bounds(it.inner_bounds()) {
+ out.push((grow(xf.transform_rect_bbox(r), g.wrap.offsets), g.wrap.mode));
+ }
+ }
+ Content::Group { .. } => {
+ for c in it.shown_children() {
+ wrap_obstacles(c, xf, skip, depth + 1, out);
+ }
+ }
+ _ => {}
+ }
+}
+
/// Build the frame specs of a story from the document (geometry, wrap, page names, grid).
pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec<FrameSpec> {
let Some(st) = doc.story(sid) else { return vec![] };
@@ -359,19 +390,14 @@ pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec<FrameSpec> {
if !tf.options.ignore_wrap
&& let Some(sp) = spread
{
+ let mut obstacles = Vec::new();
for other in &sp.items {
- if other.id == item.id || other.wrap.mode == WrapMode::None || other.hidden {
- continue;
- }
if doc.layer(other.layer).is_some_and(|l| !l.visible) {
continue;
}
- let o = other.wrap.offsets;
- let b = other.bounds();
- let r = Rect::new(b.x0 - o[1], b.y0 - o[0], b.x1 + o[3], b.y1 + o[2]);
- let inner = inv.transform_rect_bbox(r);
- exclusions.push(Exclusion { rect: inner, mode: other.wrap.mode });
+ wrap_obstacles(other, Affine::IDENTITY, item.id, 0, &mut obstacles);
}
+ exclusions.extend(obstacles.into_iter().map(|(r, mode)| Exclusion { rect: inv.transform_rect_bbox(r), mode }));
}
let (page_name, page, left_page) = match (loc.spread, spread) {
(designcraft_doc::SpreadRef::Doc(si), Some(sp)) => {
diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs
index 5cfe05fe2..cae0ac8d5 100644
--- a/crates/doc/src/item.rs
+++ b/crates/doc/src/item.rs
@@ -426,6 +426,12 @@ pub struct TextWrap {
pub side: WrapSide,
}
+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")]
@@ -455,6 +461,9 @@ pub struct Graphic {
/// Frame Fitting Options › Crop Amount: top, left, bottom, right (negative adds space).
#[serde(default)]
pub crop: [f64; 4],
+ /// Text wrap set on the graphic itself (Direct Selection), around the part its frame shows.
+ #[serde(default, skip_serializing_if = "TextWrap::is_default")]
+ pub wrap: TextWrap,
}
fn center_ref() -> u8 {
@@ -614,6 +623,13 @@ fn is_zero_usize(v: &usize) -> bool {
}
impl Graphic {
+ /// The part of the graphic its frame shows, in the frame's inner space (bounding boxes);
+ /// None when nothing shows.
+ pub fn shown_bounds(&self, frame: Rect) -> Option<Rect> {
+ let r = self.xf.transform_rect_bbox(Rect::new(0.0, 0.0, self.size.0, self.size.1)).intersect(frame);
+ (r.width() > 0.0 && r.height() > 0.0).then_some(r)
+ }
+
/// The graphic transform that fits it into `frame` (the frame's inner rect) with `mode`,
/// honouring the crop amounts and the reference point.
pub fn fitted(&self, frame: Rect, mode: Fitting) -> Option<Affine> {
@@ -1071,6 +1087,10 @@ impl Item {
_ => None,
}
}
+ /// Does this item, or the graphic it holds, wrap text?
+ pub fn has_wrap(&self) -> bool {
+ self.wrap.mode != WrapMode::None || self.graphic().is_some_and(|g| g.wrap.mode != WrapMode::None)
+ }
pub fn graphic(&self) -> Option<&Graphic> {
match &self.content {
Content::Graphic(g) => Some(g),
diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs
index deb0948bc..a9aa84606 100644
--- a/crates/engine/src/cmd/datamerge/fill.rs
+++ b/crates/engine/src/cmd/datamerge/fill.rs
@@ -370,7 +370,15 @@ fn place_image(
page: 0,
}),
);
- let mut g = Graphic { asset: aid, size: (nw, nh), xf: Affine::translate((inner.x0, inner.y0)), auto_fit: mode, fit_align: 0, crop: [0.0; 4] };
+ let mut g = Graphic {
+ asset: aid,
+ size: (nw, nh),
+ xf: Affine::translate((inner.x0, inner.y0)),
+ auto_fit: mode,
+ fit_align: 0,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ };
if let Some(xf) = g.fitted(inner, mode) {
g.xf = xf;
}
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs
index f47863851..ad9a34fbc 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -267,6 +267,7 @@ fn flatten(d: &designcraft_doc::Document, cache: &designcraft_compose::Cache, pp
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
it.stroke.weight = 0.0;
it
@@ -432,6 +433,7 @@ fn rasterize_where(
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
img_item.stroke.weight = 0.0;
img_item.alt_text = it.alt_text.clone();
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index f871a43e8..a979983a4 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -360,6 +360,7 @@ fn file_place(s: &mut Session, p: &Value) -> Result<Value> {
auto_fit: designcraft_doc::Fitting::FillProportionally,
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
fid
} else {
@@ -378,6 +379,7 @@ fn file_place(s: &mut Session, p: &Value) -> Result<Value> {
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
d.insert_item(spread, it, None)?;
id
@@ -474,6 +476,7 @@ fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {
auto_fit: designcraft_doc::Fitting::FillProportionally,
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
fid
}
@@ -496,6 +499,7 @@ fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
d.insert_item(sr, it, None)?;
id
diff --git a/crates/engine/src/cmd/mathexpr.rs b/crates/engine/src/cmd/mathexpr.rs
index 791a0d704..e0d42e9a2 100644
--- a/crates/engine/src/cmd/mathexpr.rs
+++ b/crates/engine/src/cmd/mathexpr.rs
@@ -21,8 +21,15 @@ fn math_item(d: &mut designcraft_doc::Document, latex: &str, size: f64, lid: des
let id = ItemId(d.alloc());
let r = Rect::new(at.0, at.1, at.0 + w, at.1 + h);
let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(r));
- it.content =
- Content::Graphic(Graphic { asset: aid, size: (w, h), xf: Affine::translate(at), auto_fit: Default::default(), fit_align: 4, crop: [0.0; 4] });
+ it.content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (w, h),
+ xf: Affine::translate(at),
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ });
it.alt_text = latex.to_string();
it.name = "Math".into();
it
diff --git a/crates/engine/src/cmd/media.rs b/crates/engine/src/cmd/media.rs
index b80089585..6364191fe 100644
--- a/crates/engine/src/cmd/media.rs
+++ b/crates/engine/src/cmd/media.rs
@@ -38,6 +38,7 @@ pub(crate) fn place_media(s: &mut Session, p: &Value, name: String, mime: &str,
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
it.media = Some(MediaOptions { controls: true, ..Default::default() });
fid
@@ -54,6 +55,7 @@ pub(crate) fn place_media(s: &mut Session, p: &Value, name: String, mime: &str,
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
it.media = Some(MediaOptions { controls: true, ..Default::default() });
d.insert_item(spread, it, None)?;
diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs
index 17c44c27a..0999a5a2b 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, offset?: number|[t,l,b,r], invert?: bool, ids?}",
+ "{mode: none|boundingBox|contour|jumpObject|jumpToNextColumn, offset?: number|[t,l,b,r], invert?: bool, content?: bool (the placed graphic instead of its frame; default: whether the selection is the frame's content), ids?}",
has_selection,
|s, p| {
let mode = p.get("mode").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or(designcraft_doc::WrapMode::BoundingBox);
@@ -522,16 +522,24 @@ pub fn specs() -> Vec<CommandSpec> {
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| {
- i.wrap.mode = mode;
+ let w = match &mut i.content {
+ Content::Graphic(g) if content => &mut g.wrap,
+ _ => &mut i.wrap,
+ };
+ w.mode = mode;
if let Some(o) = off {
- i.wrap.offsets = o;
+ w.offsets = o;
}
if let Some(v) = invert {
- i.wrap.invert = v;
+ w.invert = v;
}
},
false,
diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs
index 028971e97..76df84d8a 100644
--- a/crates/engine/src/cmd/table.rs
+++ b/crates/engine/src/cmd/table.rs
@@ -1436,6 +1436,7 @@ fn place_graphic(s: &mut Session, p: &Value) -> Result<Value> {
auto_fit: if fill { designcraft_doc::Fitting::FillProportionally } else { designcraft_doc::Fitting::FitProportionally },
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
clamp_selection(d, sel);
Ok(json!({"asset": aid.0, "row": r, "col": c}))
diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs
index 15a05d084..fd0607bcd 100644
--- a/crates/engine/src/sample.rs
+++ b/crates/engine/src/sample.rs
@@ -85,6 +85,7 @@ fn graphic_frame(d: &mut Document, sr: SpreadRef, r: Rect, asset: AssetId, px: (
auto_fit: designcraft_doc::Fitting::FillProportionally,
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
it.object_style = designcraft_doc::BASIC_GRAPHICS_FRAME.into();
d.insert_item(sr, it, None)?;
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index c1032bccf..30d129459 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -513,6 +513,27 @@ fn object_set_flags_and_wrap_invert() {
assert!(item(&s).wrap.invert);
}
+#[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 gridify_while_drawing_frames() {
use designcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
diff --git a/crates/epub/src/lib.rs b/crates/epub/src/lib.rs
index 643f59341..7cc8399a2 100644
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@ -850,6 +850,7 @@ mod tests {
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index 9d73562b9..0522ea450 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -1715,21 +1715,7 @@ impl<'a> Ex<'a> {
);
}
}
- let w = &it.wrap;
- el.push(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")
- .attr("Top", num(w.offsets[0]))
- .attr("Left", num(w.offsets[1]))
- .attr("Bottom", num(w.offsets[2]))
- .attr("Right", num(w.offsets[3])),
- ],
- ));
+ el.push(text_wrap_pref(&it.wrap));
match &it.content {
Content::Group { items } => {
for c in items {
@@ -1779,6 +1765,9 @@ impl<'a> Ex<'a> {
}
props.push(El::new("GraphicBounds").attr("Left", "0").attr("Top", "0").attr("Right", num(g.size.0)).attr("Bottom", num(g.size.1)));
let mut el = with_props(el, props);
+ if !g.wrap.is_default() {
+ el.push(text_wrap_pref(&g.wrap));
+ }
let uri = match &asset.link {
Some(l) => path_to_uri(l),
None => format!("file:{}", asset.name),
@@ -2468,6 +2457,24 @@ fn margin_el(pg: &designcraft_doc::Page) -> El {
}
/// `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")
+ .attr("Top", num(w.offsets[0]))
+ .attr("Left", num(w.offsets[1]))
+ .attr("Bottom", num(w.offsets[2]))
+ .attr("Right", num(w.offsets[3])),
+ ],
+ )
+}
+
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 --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index d85d9ee02..5e0b204e4 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -2095,17 +2095,7 @@ impl<'r> Importer<'r> {
}
// 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)];
- }
- it.wrap = tw;
+ it.wrap = text_wrap(w);
}
// Type on a path.
if tag != "TextFrame"
@@ -2236,6 +2226,8 @@ impl<'r> Importer<'r> {
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ // A wrap set on the placed graphic (Direct Selection) is stored on the graphic element.
+ wrap: g.find("TextWrapPreference").map(text_wrap).unwrap_or_default(),
})
}
@@ -2346,6 +2338,20 @@ impl<'r> Importer<'r> {
}
/// Drop-shadow angle (degrees) from IDML offsets (inverse of export's mapping).
+/// A `TextWrapPreference` element (of a page item or a placed graphic).
+fn text_wrap(w: &El) -> TextWrap {
+ let mut tw = TextWrap {
+ mode: names::wrap_mode_in(w.get("TextWrapMode").unwrap_or("None")),
+ invert: w.get("Inverse") == Some("true"),
+ side: names::wrap_side_in(w.get("TextWrapSide").unwrap_or("BothSides")),
+ ..TextWrap::default()
+ };
+ if let Some(o) = w.prop_el("TextWrapOffset") {
+ tw.offsets = [o.num("Top").unwrap_or(0.0), o.num("Left").unwrap_or(0.0), o.num("Bottom").unwrap_or(0.0), o.num("Right").unwrap_or(0.0)];
+ }
+ tw
+}
+
fn names_angle(x: f64, y: f64) -> f64 {
if x == 0.0 && y == 0.0 {
return 135.0;
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index 7b747587a..81f274850 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -8,6 +8,7 @@ use designcraft_geom::{Rect, shapes};
use super::*;
mod decorations;
+mod wrap;
fn zip_files(files: &[(&str, &str)]) -> Vec<u8> {
use zip::write::SimpleFileOptions;
diff --git a/crates/idml/src/tests/wrap.rs b/crates/idml/src/tests/wrap.rs
new file mode 100644
index 000000000..0ba76b3e0
--- /dev/null
+++ b/crates/idml/src/tests/wrap.rs
@@ -0,0 +1,114 @@
+use super::*;
+
+const NS: &str = r#"xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="14.0""#;
+
+fn wrap_pref(mode: &str, offset: f64) -> String {
+ format!(
+ r#"<TextWrapPreference Inverse="false" ApplyToMasterPageOnly="false" TextWrapSide="BothSides" TextWrapMode="{mode}"><Properties><TextWrapOffset Top="{offset}" Left="{offset}" Bottom="{offset}" Right="{offset}"/></Properties></TextWrapPreference>"#
+ )
+}
+
+fn rect_path(x0: f64, y0: f64, x1: f64, y1: f64) -> String {
+ let pts: String = [(x0, y0), (x0, y1), (x1, y1), (x1, y0)]
+ .iter()
+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))
+ .collect();
+ format!(
+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#
+ )
+}
+
+/// A page with a text frame (50, 60)–(370, 540) and a 100 pt square image frame at (160, 150)
+/// over it; the image (60 px scaled to fill the frame) and its frame carry the given wraps.
+fn wrap_doc(frame_wrap: &str, image_wrap: &str) -> Document {
+ let lorem =
+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ".repeat(12);
+ let designmap = format!(
+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Document {NS} Self="d" StoryList="s1" Name="wrap.indd"><idPkg:Graphic src="Resources/Graphic.xml"/><idPkg:Styles src="Resources/Styles.xml"/><idPkg:Preferences src="Resources/Preferences.xml"/><Layer Self="L1" Name="Layer 1" Visible="true" Locked="false"/><idPkg:Spread src="Spreads/Spread_sp1.xml"/><idPkg:Story src="Stories/Story_s1.xml"/></Document>"#
+ );
+ let prefs = format!(r#"<idPkg:Preferences {NS}><DocumentPreference PageWidth="400" PageHeight="600" FacingPages="false"/></idPkg:Preferences>"#);
+ let spread = format!(
+ r#"<idPkg:Spread {NS}><Spread Self="sp1" PageCount="1" ItemTransform="1 0 0 1 0 0"><Page Self="p1" GeometricBounds="0 0 600 400" ItemTransform="1 0 0 1 0 -300"/>
+<TextFrame Self="t1" ParentStory="s1" PreviousTextFrame="n" NextTextFrame="n" ItemLayer="L1" ItemTransform="1 0 0 1 0 -300">{}<TextFramePreference FirstBaselineOffset="LeadingOffset"/></TextFrame>
+<Rectangle Self="r1" ItemLayer="L1" ContentType="GraphicType" ItemTransform="1 0 0 1 0 -300">{}{frame_wrap}<Image Self="im1" ItemTransform="1.6667 0 0 1.6667 160 150"><Properties><GraphicBounds Left="0" Top="0" Right="60" Bottom="60"/></Properties>{image_wrap}<Link Self="lk1" LinkResourceURI="file:C:/elsewhere/square.png" LinkResourceFormat="$ID/Portable Network Graphics (PNG)" StoredState="Normal"/></Image></Rectangle>
+</Spread></idPkg:Spread>"#,
+ rect_path(50.0, 60.0, 370.0, 540.0),
+ rect_path(160.0, 150.0, 260.0, 250.0)
+ );
+ let story = format!(
+ r#"<idPkg:Story {NS}><Story Self="s1"><ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{lorem}</Content></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#
+ );
+ let bytes = zip_files(&[
+ ("designmap.xml", &designmap),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", &prefs),
+ ("Spreads/Spread_sp1.xml", &spread),
+ ("Stories/Story_s1.xml", &story),
+ ]);
+ import_idml_with(&bytes, &|_| None).unwrap()
+}
+
+/// Each composed line as (x0, x1, baseline), rounded to 0.01 pt.
+fn lines(d: &Document) -> Vec<(i64, i64, i64)> {
+ let sid = *d.stories.keys().next().unwrap();
+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());
+ let r = |v: f64| (v * 100.0).round() as i64;
+ cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| (r(l.x0), r(l.x1), r(l.baseline))).collect()
+}
+
+#[test]
+fn wrap_on_a_placed_graphic_wraps_text_like_a_wrap_on_its_frame() {
+ let none = wrap_pref("None", 0.0);
+ let bbox = wrap_pref("BoundingBoxTextWrap", 6.0);
+ let on_image = wrap_doc(&none, &bbox);
+ let on_frame = wrap_doc(&bbox, &none);
+ let unwrapped = wrap_doc(&none, &none);
+ let frame = &on_image.spreads[0].items[1];
+ assert_eq!(frame.wrap.mode, designcraft_doc::WrapMode::None);
+ let g = frame.graphic().unwrap();
+ assert_eq!((g.wrap.mode, g.wrap.offsets), (designcraft_doc::WrapMode::BoundingBox, [6.0; 4]));
+ // The image fills its frame, so both wraps make the same obstacle.
+ let wrapped = lines(&on_image);
+ assert_eq!(wrapped, lines(&on_frame));
+ let plain = lines(&unwrapped);
+ assert_ne!(wrapped, plain);
+ let full = plain[0].1 - plain[0].0;
+ assert!(wrapped.iter().any(|l| l.1 - l.0 < full / 2), "some lines run beside the image: {wrapped:?}");
+}
+
+#[test]
+fn wrap_on_a_placed_graphic_follows_its_crop_and_round_trips() {
+ let none = wrap_pref("None", 0.0);
+ let d = wrap_doc(&none, &wrap_pref("BoundingBoxTextWrap", 6.0));
+ // Exported on the image element, not on the frame.
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let f = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap();
+ assert_eq!(f.wrap.mode, designcraft_doc::WrapMode::None);
+ assert_eq!(f.graphic().unwrap().wrap, d.spreads[0].items[1].graphic().unwrap().wrap);
+ // Moved half out of the bottom of its frame, the image wraps only the part the frame shows.
+ let mut moved = d.clone();
+ let sp = std::sync::Arc::make_mut(&mut moved.spreads[0]);
+ let fr = std::sync::Arc::make_mut(&mut sp.items[1]);
+ if let designcraft_doc::Content::Graphic(g) = &mut fr.content {
+ g.xf = designcraft_geom::Affine::translate((0.0, 50.0)) * g.xf;
+ }
+ let fr = &moved.spreads[0].items[1];
+ let g = fr.graphic().unwrap();
+ let image = fr.xf.transform_rect_bbox(g.xf.transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1)));
+ // In the text frame's inner space, where lines are.
+ let inv = moved.spreads[0].items[0].xf.inverse();
+ let shown = inv.transform_rect_bbox(fr.bounds().intersect(image));
+ let image = inv.transform_rect_bbox(image);
+ let sid = *moved.stories.keys().next().unwrap();
+ let cs = designcraft_compose::compose_story(&moved, sid, &Default::default());
+ let beside: Vec<_> = cs.frames[0].lines.iter().filter(|l| l.baseline > shown.y0 && l.baseline - l.ascent < shown.y1).collect();
+ assert!(!beside.is_empty());
+ for l in &beside {
+ assert!(l.x1 <= shown.x0 - 6.0 + 0.01 || l.x0 >= shown.x1 + 6.0 - 0.01, "{:?} vs {shown:?}", (l.x0, l.x1));
+ }
+ // Full lines resume below the shown part (plus the offset), not below the whole image.
+ let full = cs.frames[0].lines.iter().find(|l| l.baseline - l.ascent > shown.y1 + 6.0).unwrap();
+ assert!(full.x1 - full.x0 > 300.0 && full.baseline < image.y1, "{:?} vs {image:?}", (full.x0, full.x1, full.baseline));
+}
diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs
index 3218ffc76..66016e888 100644
--- a/crates/pdf/src/pdfx.rs
+++ b/crates/pdf/src/pdfx.rs
@@ -480,6 +480,7 @@ mod tests {
auto_fit: Fitting::FillProportionally,
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
}
diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs
index 9ac53d057..00f24ef8a 100644
--- a/crates/pdf/src/tests.rs
+++ b/crates/pdf/src/tests.rs
@@ -236,6 +236,7 @@ fn place(d: &mut Document, data: Vec<u8>, px: (u32, u32)) {
auto_fit: designcraft_doc::Fitting::FillProportionally,
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
}
diff --git a/crates/pdf/tests/support/image_content_cache_contract.rs b/crates/pdf/tests/support/image_content_cache_contract.rs
index 6a4ac91f1..ba1414b94 100644
--- a/crates/pdf/tests/support/image_content_cache_contract.rs
+++ b/crates/pdf/tests/support/image_content_cache_contract.rs
@@ -34,6 +34,7 @@ fn place_named(d: &mut Document, data: Vec<u8>, x: f64, name: &str, mime: &str,
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
}
diff --git a/crates/render/src/damage.rs b/crates/render/src/damage.rs
index 31f9e030b..eb9d05fae 100644
--- a/crates/render/src/damage.rs
+++ b/crates/render/src/damage.rs
@@ -148,7 +148,7 @@ fn item_area(it: &Item) -> Option<Rect> {
let mut ok = true;
it.walk(&mut |i| {
// Effects spill outside; text wrap reflows other frames.
- if i.effects.any() || i.wrap.mode != designcraft_doc::WrapMode::None {
+ if i.effects.any() || i.has_wrap() {
ok = false;
}
});
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index c1b288def..0aa86115d 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -1448,6 +1448,7 @@ mod tests {
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
let cache = Cache::new();
diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs
index 05a73395b..c99e0a38a 100644
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@ -71,7 +71,12 @@ pub fn sel_info(app: &DesignApp) -> Option<SelInfo> {
let sp = d.spread(loc.spread)?;
let pi = sp.page_at_x(b.center().x).unwrap_or(0);
let px = sp.pages.get(pi).map(|p| p.x).unwrap_or(0.0);
- let wrap = match first.wrap.mode {
+ // With the graphic selected (Direct Selection), the Text Wrap panel shows its own wrap.
+ let tw = match (&first.content, st.selection.content) {
+ (Content::Graphic(g), true) => &g.wrap,
+ _ => &first.wrap,
+ };
+ let wrap = match tw.mode {
WrapMode::None => "none",
WrapMode::BoundingBox => "boundingBox",
WrapMode::Contour => "contour",
@@ -97,7 +102,7 @@ pub fn sel_info(app: &DesignApp) -> Option<SelInfo> {
.and_then(|v| v.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| v.as_str().map(str::to_string)))
.unwrap_or_else(|| "solid".into()),
corner: (first.corners.corners[0].shape, first.corners.corners[0].size),
- wrap_invert: first.wrap.invert,
+ wrap_invert: tw.invert,
locked: first.locked,
})
}