From a97bd20a688f12c7107f239608f6d5ef76b7a4c1 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 16 Oct 2026 09:05:01 +0200 Subject: [PATCH 01/10] Cargo.lock: main's, with #500's designcraft-images dependency of idml --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index afd57fddd..90c55cc62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -997,6 +997,7 @@ dependencies = [ "log", "quick-xml", "regex", + "same-file", "serde", "serde_json", "tempfile", From c708b080333751bb5711638caa8f2a319394f81f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 16 Oct 2026 09:47:56 +0200 Subject: [PATCH 02/10] Compose: a line past the breaker's estimated wrap segments is re-broken for its segment On narrow segments beside an object, the breaker's estimate of the segments ran out; the lines after it were set for the whole column and placed in one segment, running across the object. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/lib.rs | 4 +++- crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index afabb6fad..bdec0b163 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1268,7 +1268,9 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // paragraph from here, starting with this line's segments as they are. A pass // re-breaks at its first line only for a new line, whose segments it carries, so // every re-break makes progress; their number is capped too. - if (k > 0 || !continues) && rebreaks < 256 && slots.get(k).is_some_and(|&(a, b)| ((b - a) - (x1 - x0)).abs() > 0.5) { + // Past the estimated slots the breaker set the line for the whole column. + let (sa, sb) = slots.get(k).copied().unwrap_or((col.x0, col.x1)); + if (k > 0 || !continues) && rebreaks < 256 && ((sb - sa) - (x1 - x0)).abs() > 0.5 { rebreaks += 1; carry.insert(0, (x0, x1)); if !continues { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index dd038caa5..8e1999ddd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1155,3 +1155,28 @@ fn a_line_fits_when_its_baseline_does() { assert!(!overset(&mut s, 78.5), "the line is set; its descenders hang below the frame"); assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line"); } + + +/// Beside an object with text on both sides, every line stays within its segment, however many +/// lines the paragraph needs (the breaker's segment estimate can run out on narrow segments; a +/// line it set for the whole column ran across the object). +#[test] +fn every_line_beside_a_wrap_stays_within_its_segment() { + let mut s = Session::new(); + s.execute("file.new", &json!({"facingPages": false})).unwrap(); + // Placeholder text: paragraphs of a few sentences, some of them starting beside the object. + let t = s.execute("frame.create", &json!({"rect": [36, 36, 576, 756], "content": "text", "text": ""})).unwrap(); + s.execute("type.fillWithPlaceholder", &json!({})).unwrap(); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + s.execute("frame.create", &json!({"rect": [196, 160, 416, 490]})).unwrap(); + s.execute("object.textWrap", &json!({"mode": "boundingBox", "offset": 6})).unwrap(); + let d = &s.doc().unwrap().doc; + let c = s.cache.get(d, designcraft_doc::StoryId(t["story"].as_u64().unwrap()), None); + let mut beside = 0; + for l in c.frames.iter().flat_map(|f| &f.lines) { + let end = l.glyphs.iter().filter(|g| g.visible).map(|g| g.x + g.adv).fold(l.x0, f64::max); + assert!(end <= l.x1 + 0.5, "line at {} runs to {end}, past its segment {}..{}", l.baseline, l.x0, l.x1); + beside += usize::from(l.x1 < 400.0 || l.x0 > 400.0); + } + assert!(beside > 20, "lines on both sides of the object: {beside}"); +} From afa015f113239a61e83ad09266ca8d2f38051ec2 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 16 Oct 2026 09:53:40 +0200 Subject: [PATCH 03/10] Text wrap: Alpha Channel contour traced from the image, holes with Include Inside Edges, open gaps kept Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/compose/src/lib.rs | 184 ++++++++++++--- crates/compose/src/tests.rs | 27 +++ crates/doc/src/build.rs | 1 + crates/doc/src/item.rs | 26 ++- crates/doc/src/lib.rs | 23 ++ crates/engine/src/cmd/alpha_wrap.rs | 285 ++++++++++++++++++++++++ crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/cmd/object.rs | 24 +- crates/engine/src/lib.rs | 5 +- crates/engine/src/tests.rs | 1 - crates/idml/src/export.rs | 6 +- crates/idml/src/import.rs | 2 + crates/idml/src/tests.rs | 7 + crates/render/src/blendspace.rs | 3 + crates/ui-egui/src/i18n.rs | 5 + crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ka.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/uk.rs | 2 + crates/ui-egui/src/panels/mod.rs | 3 + crates/ui-egui/src/panels/properties.rs | 19 +- 25 files changed, 584 insertions(+), 49 deletions(-) create mode 100644 crates/engine/src/cmd/alpha_wrap.rs diff --git a/ROADMAP.md b/ROADMAP.md index 2aacdaf9b..739e9bb17 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -347,6 +347,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- 2026-10-16: Text Wrap › Contour › Alpha Channel follows a placed image's transparency, as InDesign's: the outline is traced from the image and follows it when it moves or is refitted; text keeps the open gaps between its parts, and enters enclosed holes with Include Inside Edges. - **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change. - **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change. - **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index bdec0b163..eda488d83 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -369,6 +369,96 @@ impl Contour { } (lo <= hi).then_some((lo - self.offset, hi + self.offset)) } + + /// Occupied intervals across the whole line band, preserving gaps between parts of a + /// concave or compound outline. Project boundary edges and the filled middle slice: any + /// area that starts or ends inside the band is bounded by those projected edges. + fn band_spans(&self, y0: f64, y1: f64) -> Vec<(f64, f64)> { + let (low, high) = (y0 - self.offset, y1 + self.offset); + if !low.is_finite() || !high.is_finite() || high < low { + return self.band_extent(y0, y1).into_iter().collect(); + } + let mut spans = rings_band_spans(&self.rings, low, high); + // Extremely fragmented imported paths use the conservative outer extent, bounding the + // work of subtracting intervals from every line. A traced 128-column mask stays below it. + if spans.len() > 128 { + return self.band_extent(y0, y1).into_iter().collect(); + } + if !self.clip.is_empty() { + let clip = rings_band_spans(&self.clip, low, high); + let mut cut = Vec::new(); + let (mut i, mut j) = (0, 0); + while let (Some(&(a, b)), Some(&(c, d))) = (spans.get(i), clip.get(j)) { + if a.max(c) < b.min(d) { + cut.push((a.max(c), b.min(d))); + } + if b < d { + i += 1; + } else { + j += 1; + } + } + spans = cut; + } + merge_spans(spans.into_iter().map(|(a, b)| (a - self.offset, b + self.offset)).collect()) + } +} + +fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { + spans.retain(|(a, b)| a.is_finite() && b.is_finite() && b - a > 1e-9); + spans.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut out: Vec<(f64, f64)> = Vec::new(); + for (a, b) in spans { + if let Some(last) = out.last_mut().filter(|last| a <= last.1 + 1e-9) { + last.1 = last.1.max(b); + } else { + out.push((a, b)); + } + } + out +} + +fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { + let mut spans = Vec::new(); + let mut crossings = Vec::new(); + let middle = y0 * 0.5 + y1 * 0.5; + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (x0, x1) = (a.x + t0 * (b.x - a.x), a.x + t1 * (b.x - a.x)); + spans.push((x0.min(x1), x0.max(x1))); + } + if (a.y <= middle && middle < b.y) || (b.y <= middle && middle < a.y) { + let x = a.x + (middle - a.y) / dy * (b.x - a.x); + if x.is_finite() { + crossings.push((x, if dy > 0.0 { 1i32 } else { -1 })); + } + } + a = b; + } + } + crossings.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut winding = 0i32; + let mut previous = None; + for (x, delta) in crossings { + if winding != 0 + && let Some(start) = previous + { + spans.push((start, x)); + } + winding += delta; + previous = Some(x); + } + merge_spans(spans) } /// The closed polylines of `path` (after `to_inner`), flattened; None if it is empty or too detailed. @@ -431,7 +521,13 @@ fn rings_band_extent(rings: &[Vec], y0: f64, y1: f64) -> Option<(f64, f64 /// The wrap exclusion of `other` (an item whose inner space maps to the spread by `xf`) for a /// frame whose inner space is reached from the spread by `inv`. `left_page` places the object on /// a left page (for the spine sides). -pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, inv: designcraft_geom::Affine, left_page: bool) -> Exclusion { +pub fn exclusion( + doc: &Document, + other: &designcraft_doc::Item, + xf: designcraft_geom::Affine, + inv: designcraft_geom::Affine, + left_page: bool, +) -> Exclusion { let o = other.wrap.offsets; let b = if other.shape == designcraft_doc::Shape::Group { (xf * other.xf.inverse()).transform_rect_bbox(other.bounds()) @@ -452,7 +548,7 @@ pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, in 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( + let contour = (other.wrap.mode == WrapMode::Contour && other.shape != designcraft_doc::Shape::Group).then(|| contour_path(doc, other)).and_then( |(path, frame)| { let c = Contour::of(&path, inv * xf, other.wrap.offsets[0])?; Some(match frame { @@ -466,11 +562,26 @@ pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, in } /// The outline a contour wrap follows, in the item's inner space, and for an outline taken from -/// the placed graphic, the frame path that clips it. 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, Option) { +/// the placed graphic, the frame path that clips it. Graphic frames follow their contour type. An +/// alpha channel follows the image's traced outline, placed where the graphic is now (so it +/// follows the image when it moves or is refitted); its transparent holes count only with Include +/// Inside Edges. Detected edges and image paths, and an alpha channel not traced (yet), follow the +/// frame's path (as other frames do). +fn contour_path(doc: &Document, it: &designcraft_doc::Item) -> (designcraft_geom::BezPath, Option) { let frame = designcraft_geom::corners::apply(&it.path, &it.corners); + if it.wrap.contour == designcraft_doc::ContourType::AlphaChannel + && let Some(g) = it.graphic() + && let Some(o) = doc.alpha_outline(g.asset, it.wrap.alpha_threshold) + && o.width > 0 + && o.height > 0 + { + let to_graphic = designcraft_geom::Affine::scale_non_uniform(g.size.0 / f64::from(o.width), g.size.1 / f64::from(o.height)); + let mut path = o.outer.to_bezpath(); + if it.wrap.inside_edges { + path.extend(o.holes.to_bezpath().iter()); + } + return (g.xf * to_graphic * path, Some(frame)); + } if it.wrap.contour == designcraft_doc::ContourType::BoundingBox && let Some(g) = it.graphic() && let Some(fb) = it.path.bounds() @@ -573,7 +684,7 @@ pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec { .page_at_x(other.bounds().center().x) .and_then(|pi| sp.pages.get(pi)) .is_some_and(|p| p.side == designcraft_doc::PageSide::Left); - let ex = exclusion(other, other.xf, inv, left); + let ex = exclusion(doc, other, other.xf, inv, left); let reach = ex.rect.intersect(item.inner_bounds()); if reach.width() > 0.0 && reach.height() > 0.0 { exclusions.push(ex); @@ -2592,39 +2703,40 @@ 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::BoundingBox | WrapMode::Contour if overlaps_band => match &ex.contour { - Some(c) => c.band_extent(y0, y1), - None => Some((r.x0, r.x1)), + Some(c) => c.band_spans(y0, y1), + None => vec![(r.x0, r.x1)], }, - _ => None, + _ => Vec::new(), }; - let Some((a, b)) = blocked.filter(|&(a, b)| a < col.x1 && b > col.x0) else { continue }; - cut = true; - // One-sided wraps also block the column on the other side of the object. - let text_left = match ex.side { - WrapSide::LeftSide => Some(true), - WrapSide::RightSide => Some(false), - WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1), - WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None, - }; - let (a, b) = match text_left { - Some(true) => (a, b.max(col.x1)), - Some(false) => (a.min(col.x0), b), - None => (a, b), - }; - let mut next = Vec::with_capacity(free.len() + 1); - for (fa, fb) in free { - if b <= fa || a >= fb { - next.push((fa, fb)); - continue; - } - if a > fa { - next.push((fa, a)); - } - if b < fb { - next.push((b, fb)); + for (a, b) in blocked.into_iter().filter(|&(a, b)| a < col.x1 && b > col.x0) { + cut = true; + // One-sided wraps also block the column on the other side of the object. + let text_left = match ex.side { + WrapSide::LeftSide => Some(true), + WrapSide::RightSide => Some(false), + WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1), + WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None, + }; + let (a, b) = match text_left { + Some(true) => (a, b.max(col.x1)), + Some(false) => (a.min(col.x0), b), + None => (a, b), + }; + let mut next = Vec::with_capacity(free.len() + 1); + for (fa, fb) in free { + if b <= fa || a >= fb { + next.push((fa, fb)); + continue; + } + if a > fa { + next.push((fa, a)); + } + if b < fb { + next.push((b, fb)); + } } + free = next; } - free = next; } if !cut { return vec![(col.x0, col.x1)]; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index d08efe034..9491afb67 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4,6 +4,33 @@ use designcraft_geom::Rect; use super::*; +#[test] +fn contour_intervals_preserve_the_gap_between_legs() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((0.0, 0.0)); + for p in [(40.0, 0.0), (40.0, 100.0), (30.0, 100.0), (30.0, 20.0), (10.0, 20.0), (10.0, 100.0), (0.0, 100.0)] { + path.line_to(p); + } + path.close_path(); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 3.0).unwrap(); + assert_eq!(c.band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 43.0)]); + assert_eq!(c.band_spans(5.0, 15.0), vec![(-3.0, 43.0)]); + let frame = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 35.0, 100.0)).to_bezpath(); + assert_eq!(c.within(&frame, designcraft_geom::Affine::IDENTITY).band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 38.0)]); +} + +#[test] +fn contour_intervals_cover_the_whole_slanted_line_band() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((0.0, 0.0)); + for p in [(2.0, 0.0), (12.0, 10.0), (10.0, 10.0)] { + path.line_to(p); + } + path.close_path(); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 0.0).unwrap(); + assert_eq!(c.band_spans(0.0, 10.0), vec![(0.0, 12.0)]); +} + const LOREM: &str = "Typography is the art and technique of arranging type to make written language legible, readable and appealing when displayed. \ The arrangement of type involves selecting typefaces, point sizes, line lengths, line spacing, and letter spacing, and adjusting the space between pairs of letters."; diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs index 9fb075553..cc37907bd 100644 --- a/crates/doc/src/build.rs +++ b/crates/doc/src/build.rs @@ -160,6 +160,7 @@ impl Document { modified: 0, next_id: 0, font_scope: 0, + alpha_outlines: Vec::new(), }; let lid = LayerId(d.alloc()); d.layers.push(Layer { diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index 2d2cea760..bfaebe2c2 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -501,7 +501,7 @@ pub enum ContourType { } /// Text Wrap panel settings. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct TextWrap { pub mode: WrapMode, @@ -515,6 +515,30 @@ pub struct TextWrap { /// item transforms it with the path; other path edits keep it as it is. #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, + /// Contour Options › Include Inside Edges: an Alpha Channel contour also lets text into the + /// transparent holes it encloses (off: holes are blocked with the shape around them). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub inside_edges: bool, + /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. + pub alpha_threshold: u8, +} + +/// InDesign's default alpha threshold for contour wraps. +pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; + +impl Default for TextWrap { + fn default() -> Self { + TextWrap { + mode: WrapMode::default(), + offsets: [0.0; 4], + invert: false, + side: WrapSide::default(), + contour: ContourType::default(), + path: None, + inside_edges: false, + alpha_threshold: DEFAULT_ALPHA_THRESHOLD, + } + } } /// Frame fitting options (Object → Fitting → Frame Fitting Options). diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c0fdc8fe2..47f752322 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -448,6 +448,21 @@ pub struct Asset { pub page: u32, } +/// The outline of a raster image's visible pixels (Text Wrap › Contour › Alpha Channel), in the +/// image's pixel space (0..width, 0..height). Derived from the image, so not saved: the engine +/// traces it again when a document opens. +#[derive(Clone, Debug, PartialEq)] +pub struct AlphaOutline { + pub asset: AssetId, + pub threshold: u8, + pub width: u32, + pub height: u32, + /// The outer boundaries of the visible areas. + pub outer: designcraft_geom::PathData, + /// The boundaries of transparent holes those areas enclose (wound the other way). + pub holes: designcraft_geom::PathData, +} + impl Asset { /// A raster image (PNG, JPEG, GIF, WebP, TIFF, BMP, PSD), as opposed to a PDF, EPS or SVG. pub fn is_raster(&self) -> bool { @@ -501,6 +516,9 @@ pub struct Document { pub sections: Vec
, #[serde(default)] pub assets: BTreeMap>, + /// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]). Not saved. + #[serde(skip)] + pub alpha_outlines: Vec>, /// Hyperlinks (Window → Interactive → Hyperlinks). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub hyperlinks: Vec, @@ -695,6 +713,11 @@ impl Document { if sec.include_prefix { format!("{}{}", sec.prefix, num) } else { num } } + /// The Alpha Channel outline of `asset` at `threshold`, once the engine has traced it. + pub fn alpha_outline(&self, asset: AssetId, threshold: u8) -> Option<&AlphaOutline> { + self.alpha_outlines.iter().map(|o| &**o).find(|o| o.asset == asset && o.threshold == threshold) + } + pub fn layer(&self, id: LayerId) -> Option<&Layer> { self.layers.iter().find(|l| l.id == id) } diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs new file mode 100644 index 000000000..5f4abae58 --- /dev/null +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -0,0 +1,285 @@ +//! Text Wrap › Contour › Alpha Channel: the outline of a placed raster's visible pixels. +//! +//! The outline is traced once per image and threshold, in the image's pixel space, and kept on +//! the document ([`designcraft_doc::AlphaOutline`]). Composition maps it through the graphic's +//! current transform, so it follows the image when it is moved, scaled or refitted. +use std::sync::Arc; + +use designcraft_doc::{AlphaOutline, AssetId, ContourType, Document, WrapMode}; +use designcraft_geom::{BezPath, PathData, Point}; + +/// Images larger than this many pixels aren't traced (their contour follows the frame). +const MAX_PIXELS: u64 = 40_000_000; +/// The finest grid an outline is traced on; coarser grids when the outline would be too long. +const MAX_GRID: u32 = 256; +/// Boundary edges an outline may have. +const MAX_EDGES: usize = 1 << 16; + +/// Trace the outlines new Alpha Channel contours need and drop the ones nothing uses. Cheap when +/// nothing changed: tracing happens only for an image and threshold not seen before. +pub(crate) fn sync(doc: &mut Document) { + let mut wanted: Vec<(AssetId, u8)> = Vec::new(); + for sp in doc.spreads.iter().chain(doc.parents.iter()) { + for it in &sp.items { + if it.wrap.mode == WrapMode::Contour + && it.wrap.contour == ContourType::AlphaChannel + && let Some(g) = it.graphic() + && !wanted.contains(&(g.asset, it.wrap.alpha_threshold)) + { + wanted.push((g.asset, it.wrap.alpha_threshold)); + } + } + } + if wanted.is_empty() && doc.alpha_outlines.is_empty() { + return; + } + doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && doc.assets.contains_key(&o.asset)); + for (asset, threshold) in wanted { + if doc.alpha_outline(asset, threshold).is_some() { + continue; + } + let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; + if let Some(o) = trace(&a.data, asset, threshold) { + doc.alpha_outlines.push(Arc::new(o)); + } + } +} + +/// The outline of the pixels of `data` more opaque than `threshold`. None for an image that +/// can't be read, is too large, or has no transparency (its contour is its rectangle). +pub(crate) fn trace(data: &[u8], asset: AssetId, threshold: u8) -> Option { + let (w, h) = designcraft_images::pixel_size(data)?; + if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { + return None; + } + let img = designcraft_images::decode_rgba(data)?; + if img.width() != w || img.height() != h { + return None; + } + let mut grid = MAX_GRID; + while grid >= 16 { + let (cols, rows) = (w.min(grid), h.min(grid)); + let (mask, transparent) = occupancy(img.as_raw(), w, h, cols, rows, threshold); + if !transparent { + return None; + } + if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize) { + let (sx, sy) = (f64::from(w) / f64::from(cols), f64::from(h) / f64::from(rows)); + let path = |rings: &[Vec<(i32, i32)>]| { + let mut p = BezPath::new(); + for ring in rings { + let mut pts = ring.iter().map(|&(x, y)| Point::new(f64::from(x) * sx, f64::from(y) * sy)); + let Some(first) = pts.next() else { continue }; + p.move_to(first); + for q in pts { + p.line_to(q); + } + p.close_path(); + } + PathData::from_bezpath(&p) + }; + return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes) }); + } + grid /= 2; + } + None +} + +/// Which cells of a `cols` × `rows` grid hold a pixel of the `w` × `h` RGBA image `rgba` more +/// opaque than `threshold` (a cell is visible when any of its pixels is), and whether the image +/// has any transparency. +fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> (Vec, bool) { + let mut mask = vec![false; (cols as usize) * (rows as usize)]; + let mut transparent = false; + for (i, px) in rgba.chunks_exact(4).enumerate() { + let alpha = px[3]; + transparent |= alpha < 255; + if alpha > threshold { + let (x, y) = ((i as u64) % u64::from(w), (i as u64) / u64::from(w)); + let (gx, gy) = (x * u64::from(cols) / u64::from(w), y * u64::from(rows) / u64::from(h)); + if let Some(c) = mask.get_mut((gy * u64::from(cols) + gx) as usize) { + *c = true; + } + } + } + (mask, transparent) +} + +/// The closed boundaries of the visible cells, split into outer boundaries and the boundaries of +/// holes (by winding: each boundary keeps the visible cells on the same side). None when the +/// outline would have more than [`MAX_EDGES`] edges. +#[allow(clippy::type_complexity)] +fn rings(mask: &[bool], cols: usize, rows: usize) -> Option<(Vec>, Vec>)> { + use std::collections::BTreeMap; + let visible = |x: i32, y: i32| { + x >= 0 && y >= 0 && (x as usize) < cols && (y as usize) < rows && mask.get(y as usize * cols + x as usize).copied().unwrap_or(false) + }; + let mut edges: BTreeMap<(i32, i32), Vec<(i32, i32)>> = BTreeMap::new(); + let mut count = 0usize; + for y in 0..rows as i32 { + for x in 0..cols as i32 { + if !visible(x, y) { + continue; + } + for (open, a, b) in [ + (!visible(x, y - 1), (x, y), (x + 1, y)), + (!visible(x + 1, y), (x + 1, y), (x + 1, y + 1)), + (!visible(x, y + 1), (x + 1, y + 1), (x, y + 1)), + (!visible(x - 1, y), (x, y + 1), (x, y)), + ] { + if open { + count += 1; + if count > MAX_EDGES { + return None; + } + edges.entry(a).or_default().push(b); + } + } + } + } + let (mut outer, mut holes) = (Vec::new(), Vec::new()); + while let Some((&start, _)) = edges.first_key_value() { + let mut ring = vec![start]; + let mut at = start; + for _ in 0..=MAX_EDGES { + let next = edges.get_mut(&at).and_then(Vec::pop)?; + if edges.get(&at).is_some_and(Vec::is_empty) { + edges.remove(&at); + } + // Drop the middle of straight runs. + if let [.., a, b] = ring[..] + && (b.0 - a.0) * (next.1 - b.1) == (b.1 - a.1) * (next.0 - b.0) + { + ring.pop(); + } + if next == start { + break; + } + ring.push(next); + at = next; + } + // Shoelace in y-down space: positive for outer boundaries, negative for holes. + let area: i64 = ring + .iter() + .zip(ring.iter().cycle().skip(1)) + .map(|(&(x0, y0), &(x1, y1))| i64::from(x0) * i64::from(y1) - i64::from(x1) * i64::from(y0)) + .sum(); + if ring.len() >= 3 { + if area > 0 { outer.push(ring) } else { holes.push(ring) } + } + } + Some((outer, holes)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + use crate::Session; + + /// A 64 × 64 PNG: visible where `on(x, y)`. + fn png(on: impl Fn(usize, usize) -> bool) -> Vec { + let mut pixels = vec![0; 64 * 64 * 4]; + for y in 0..64 { + for x in 0..64 { + let i = (y * 64 + x) * 4; + pixels[i] = 120; + pixels[i + 3] = if on(x, y) { 255 } else { 0 }; + } + } + designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png() + } + + #[test] + fn traces_outer_boundaries_and_holes_apart() { + // A ring: a square with a square hole. + let data = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y))); + let o = trace(&data, AssetId(1), 25).unwrap(); + assert_eq!((o.width, o.height), (64, 64)); + assert_eq!((o.outer.subpaths.len(), o.holes.subpaths.len()), (1, 1)); + let (a, b) = (o.outer.bounds().unwrap(), o.holes.bounds().unwrap()); + assert_eq!((a.x0, a.y0, a.x1, a.y1), (8.0, 8.0, 56.0, 56.0)); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (24.0, 24.0, 40.0, 40.0)); + // An opaque image has no alpha outline. + assert!(trace(&png(|_, _| true), AssetId(1), 25).is_none()); + } + + #[test] + fn an_alpha_channel_contour_is_traced_when_set_and_kept_out_of_the_saved_file() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let id = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); + s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 1); + // Saved and opened again: traced again on open. + let bytes = crate::cmd::file::to_bytes(d); + let back = crate::cmd::file::from_bytes(&bytes).unwrap(); + assert!(back.alpha_outlines.is_empty(), "not saved"); + let st = crate::DocState::new(back, None); + assert_eq!(st.doc.alpha_outlines.len(), 1, "traced on open"); + // Wrap off: the outline goes. + s.execute("object.textWrap", &json!({"ids": [id], "mode": "none"})).unwrap(); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); + } + + /// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no + /// offset, and a caption frame at `caption` with 8 pt "Hi". + fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + let c = s.execute("frame.create", &json!({"rect": caption, "content": "text", "text": "Hi"})).unwrap(); + s.execute("selection.set", &json!({"ids": [c["id"]]})).unwrap(); + s.execute("type.char", &json!({"size": 8})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "offset": 0})).unwrap(); + (s, image, c["story"].as_u64().unwrap()) + } + + fn overset(s: &Session, story: u64) -> bool { + s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(story), None).is_overset() + } + + use serde_json::Value; + + /// A caption fits between two legs of a cutout, and the contour follows the image when it's + /// moved within its frame (it isn't a boundary stored where it was traced). + #[test] + fn an_alpha_channel_contour_keeps_gaps_open_and_follows_the_image() { + // Legs at pixels 8..20 and 44..56: 116..140 and 188..212 on the page. + let (mut s, image, story) = page(&png(|x, _| (8..20).contains(&x) || (44..56).contains(&x)), [150.0, 120.0, 178.0, 170.0]); + assert!(overset(&s, story), "the frame's contour covers the gap"); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the gap between the legs stays open"); + // The graphic moved 30 pt right within its frame: its left leg now covers the caption. + s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap(); + s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap(); + assert!(overset(&s, story), "the contour moved with the image"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!overset(&s, story)); + } + + /// A hole enclosed by the image stays blocked unless Include Inside Edges is on. + #[test] + fn holes_are_blocked_unless_inside_edges_are_included() { + // A ring: outer 116..212, hole 148..180 on the page. + let ring = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y))); + let (mut s, image, story) = page(&ring, [152.0, 152.0, 176.0, 176.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(overset(&s, story), "the hole is blocked with the ring around it"); + s.execute("object.textWrap", &json!({"ids": [image], "insideEdges": true})).unwrap(); + assert!(!overset(&s, story), "Include Inside Edges lets text into the hole"); + for bad in [json!({"ids": [image], "threshold": 255}), json!({"ids": [image], "insideEdges": 1})] { + assert!(s.execute("object.textWrap", &bad).is_err()); + } + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 0bfb9727c..9147eef0d 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -1,5 +1,6 @@ //! The command registry. Ids follow InDesign's menu structure. +pub(crate) mod alpha_wrap; mod anchored; pub mod anchors; mod articles; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 36bd1dac0..997a209ec 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -584,7 +584,7 @@ pub fn specs() -> Vec { "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?}; offset or contour drops an imported custom wrap boundary", + "{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side, contour, insideEdges or threshold is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping|alphaChannel, insideEdges?: bool (alphaChannel: text may enter transparent holes), threshold?: 0..254 (alphaChannel: pixels more opaque count; default 25), ids?}; offset or contour drops an imported custom wrap boundary", has_selection, text_wrap ), @@ -1523,16 +1523,24 @@ fn text_wrap(s: &mut Session, p: &Value) -> Result { 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. + // Detected edges and image paths need the image's own analysis or paths, which aren't read; + // those types aren't offered. An alpha channel is traced from the image's pixels. let contour = match p.get("contour").map(|v| serde_json::from_value::(v.clone())) { - Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping))) => Some(c), + Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping | ContourType::AlphaChannel))) => Some(c), Some(_) => return Err(bad("object.textWrap", "unsupported contour type")), None => None, }; + let inside_edges = match p.get("insideEdges") { + None => None, + Some(v) => Some(v.as_bool().ok_or_else(|| bad("object.textWrap", "`insideEdges` is true or false"))?), + }; + let threshold = match p.get("threshold") { + None => None, + Some(v) => Some(v.as_u64().filter(|t| *t <= 254).ok_or_else(|| bad("object.textWrap", "`threshold` is 0..254"))? as u8), + }; let mode: Option = 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 if side.is_some() || contour.is_some() || inside_edges.is_some() || threshold.is_some() => None, None => Some(WrapMode::BoundingBox), }; let off = match p.get("offset") { @@ -1560,6 +1568,12 @@ fn text_wrap(s: &mut Session, p: &Value) -> Result { if let Some(c) = contour { i.wrap.contour = c; } + if let Some(v) = inside_edges { + i.wrap.inside_edges = v; + } + if let Some(t) = threshold { + i.wrap.alpha_threshold = t; + } // 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() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 745e45647..6fa3daa04 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -131,7 +131,9 @@ impl Drop for FontScope { static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); impl DocState { - pub fn new(doc: Document, path: Option) -> Self { + pub fn new(mut doc: Document, path: Option) -> Self { + // Alpha Channel contour outlines aren't saved: trace them for the document as opened. + crate::cmd::alpha_wrap::sync(&mut doc); let active_layer = doc.default_layer(); let doc = Arc::new(doc); DocState { @@ -589,6 +591,7 @@ impl Session { let r = f(&mut doc, &mut sel)?; crate::cmd::sync_placeholders(&mut doc); crate::cmd::flex::sync(&mut doc); + crate::cmd::alpha_wrap::sync(&mut doc); doc.sync_endnote_story(); st.doc = Arc::new(doc); st.selection = sel; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8e1999ddd..7a305c59f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1156,7 +1156,6 @@ fn a_line_fits_when_its_baseline_does() { assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line"); } - /// Beside an object with text on both sides, every line stays within its segment, however many /// lines the paragraph needs (the breaker's segment estimate can run out on narrow segments; a /// line it set for the whole column ran across the object). diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index 4e2c1bef1..ac26f5f85 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -1852,7 +1852,11 @@ impl<'a> Ex<'a> { .attr("Right", num(w.offsets[3]))]) .collect(), ) - .child(El::new("ContourOption").attr("ContourType", names::contour_type_out(w.contour)).attr("IncludeInsideEdges", "false")), + .child( + El::new("ContourOption") + .attr("ContourType", names::contour_type_out(w.contour)) + .attr("IncludeInsideEdges", if w.inside_edges { "true" } else { "false" }), + ), ); match &it.content { Content::Group { items } => { diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index ad6b6447b..6fb042e1b 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -2429,6 +2429,7 @@ impl<'r> Importer<'r> { 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")), + inside_edges: w.find("ContourOption").and_then(|c| c.get("IncludeInsideEdges")) == Some("true"), ..TextWrap::default() }; if let Some(o) = w.prop_el("TextWrapOffset") { @@ -2739,6 +2740,7 @@ impl<'r> Importer<'r> { modified: 0, next_id: self.next_id, font_scope: 0, + alpha_outlines: Vec::new(), }; Ok(d) } diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index cca7803df..355ec3e7d 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -2627,6 +2627,13 @@ fn imports_and_round_trips_text_wrap_side_and_contour_type() { 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)); + assert!(!w.inside_edges); + // An Alpha Channel contour with Include Inside Edges. + d.item_mut(id).unwrap().wrap.contour = designcraft_doc::ContourType::AlphaChannel; + d.item_mut(id).unwrap().wrap.inside_edges = true; + 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.contour, w.inside_edges), (designcraft_doc::ContourType::AlphaChannel, true)); } /// One single-column text frame at (0, 0)-(300, 200) on page 1, beside a 100 pt wide rectangle diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 4121831f7..cc861cabc 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -113,6 +113,7 @@ fn same_document(old: &Document, new: &Document) -> bool { modified, next_id, font_scope, + alpha_outlines, } = new; let same_spreads = |a: &[std::sync::Arc], b: &[std::sync::Arc]| { a.len() == b.len() && a.iter().zip(b).all(|(a, b)| std::sync::Arc::ptr_eq(a, b)) @@ -124,6 +125,8 @@ fn same_document(old: &Document, new: &Document) -> bool { && old.stories.iter().zip(stories).all(|((a, x), (b, y))| a == b && std::sync::Arc::ptr_eq(x, y)) && old.assets.len() == assets.len() && old.assets.iter().zip(assets).all(|((a, x), (b, y))| a == b && std::sync::Arc::ptr_eq(x, y)) + && old.alpha_outlines.len() == alpha_outlines.len() + && old.alpha_outlines.iter().zip(alpha_outlines).all(|(a, b)| std::sync::Arc::ptr_eq(a, b)) && old.title == *title && old.settings == *settings && old.layers == *layers diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 245a6e287..f65158e52 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -58,6 +58,11 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Cut", ["Ausschneiden", "Couper", "Cortar", "カット", "剪切"]), ("Copy", ["Kopieren", "Copier", "Copiar", "コピー", "复制"]), ("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]), + ( + "Include Inside Edges", + ["Innenkanten einschließen", "Inclure les bords intérieurs", "Incluir bordes interiores", "内側エッジを含める", "包含内边缘"], + ), + ("Alpha Channel", ["Alphakanal", "Couche alpha", "Canal alfa", "アルファチャンネル", "Alpha 通道"]), ( "Bulleted & Numbered Lists", [ diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index d1dcb7acf..984677f9b 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "قص"), ("Copy", "نسخ"), ("Paste", "لصق"), + ("Include Inside Edges", "تضمين الحواف الداخلية"), ("Bulleted & Numbered Lists", "القوائم ذات التعداد النقطي والرقمي"), ("Current Page Number", "رقم الصفحة الحالية"), ("Apply Color (,)", "تطبيق اللون (,)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0f55578b5..d4b2719f6 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Ausschneiden"), ("Copy", "Kopieren"), ("Paste", "Einfügen"), + ("Include Inside Edges", "Innenkanten einschließen"), ("Clear", "Löschen"), ("Duplicate", "Duplizieren"), ("Select All", "Alles auswählen"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 00328ac9f..12f573390 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -28,6 +28,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Taglia"), ("Copy", "Copia"), ("Paste", "Incolla"), + ("Include Inside Edges", "Includi bordi interni"), + ("Alpha Channel", "Canale alfa"), ("Bulleted & Numbered Lists", "Elenchi puntati e numerati"), ("Current Page Number", "Numero di pagina corrente"), ("Apply Color (,)", "Applica colore (,)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index fe9e213e7..8f1c5895a 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "カット"), ("Copy", "コピー"), ("Paste", "ペースト"), + ("Include Inside Edges", "内側エッジを含める"), ("Bulleted & Numbered Lists", "箇条書き"), ("Apply Color (,)", "カラーを適用 (,)"), ("Apply Gradient (.)", "グラデーションを適用 (.)"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index b3379c6d7..e540ce17a 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -31,6 +31,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "ამოჭრა"), ("Copy", "კოპირება"), ("Paste", "ჩასმა"), + ("Include Inside Edges", "შიდა კიდეების ჩართვა"), ("Reverse Path", "ტრაექტორიის შებრუნება"), ("Set Anchor", "საყრდენი წერტილის დაყენება"), ("Clear", "გასუფთავება"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 0675a2f66..2cde5eca2 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Recortar"), ("Copy", "Copiar"), ("Paste", "Colar"), + ("Include Inside Edges", "Incluir bordas internas"), + ("Alpha Channel", "Canal alfa"), ("Bulleted & Numbered Lists", "Listas com marcadores e numeradas"), ("Show Hidden Characters", "Mostrar caracteres ocultos"), ("Current Page Number", "Número da página atual"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 8f1d27f84..824086772 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вирізати"), ("Copy", "Копіювати"), ("Paste", "Вставити"), + ("Include Inside Edges", "Включити внутрішні краї"), + ("Alpha Channel", "Альфа-канал"), ("Bulleted & Numbered Lists", "Марковані й нумеровані списки"), ("Current Page Number", "Номер поточної сторінки"), ("Apply Color (,)", "Застосувати колір (,)"), diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index fa40f5bec..54216f83f 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -51,6 +51,8 @@ pub struct SelInfo { pub wrap_offsets: [f64; 4], pub wrap_side: String, pub wrap_contour: String, + /// Contour Options › Include Inside Edges (an Alpha Channel contour). + pub wrap_inside_edges: bool, pub locked: bool, } @@ -161,6 +163,7 @@ pub fn sel_info(app: &DesignApp) -> Option { wrap_offsets: first.wrap.offsets, wrap_side: serde_json::to_value(first.wrap.side).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(), wrap_contour: serde_json::to_value(first.wrap.contour).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(), + wrap_inside_edges: first.wrap.inside_edges, locked: first.locked, }) } diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 8cbaa2ea6..0b5f3fd62 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1903,11 +1903,22 @@ pub fn wrap_panel(app: &mut DesignApp, ui: &mut egui::Ui) { ]; wrap_combo(app, ui, "wrap_side", "Wrap To", &sides, &[], &i.wrap_side, "side"); if i.wrap == "contour" && i.is_graphic { - // Detected edges, alpha channels and image paths aren't offered: composition doesn't read - // the image. An imported one shows by name and wraps around the frame. - let types = [("boundingBox", "Bounding Box"), ("graphicFrame", "Graphic Frame"), ("sameAsClipping", "Same as Clipping")]; - let shown_only = [("detectEdges", "Detect Edges"), ("alphaChannel", "Alpha Channel"), ("photoshopPath", "Photoshop Path")]; + // Detected edges and image paths aren't offered: they need the image's own analysis or + // paths. An imported one shows by name and wraps around the frame. + let types = [ + ("boundingBox", "Bounding Box"), + ("alphaChannel", "Alpha Channel"), + ("graphicFrame", "Graphic Frame"), + ("sameAsClipping", "Same as Clipping"), + ]; + let shown_only = [("detectEdges", "Detect Edges"), ("photoshopPath", "Photoshop Path")]; wrap_combo(app, ui, "wrap_contour", "Contour Type", &types, &shown_only, &i.wrap_contour, "contour"); + if i.wrap_contour == "alphaChannel" { + let mut inside = i.wrap_inside_edges; + if widgets::checkbox(ui, &mut inside, crate::i18n::tr(&app.ui.language, "Include Inside Edges")).changed() { + let _ = app.run("object.textWrap", json!({"insideEdges": inside})); + } + } } } From 10134b6f29c3ca3d0c69d4f25ec02bf9f12f12b1 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Tue, 20 Oct 2026 16:49:15 +0200 Subject: [PATCH 04/10] PR-1084: trace outlines for graphic and nested wraps, and again after a relink Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/lib.rs | 22 +++++++- crates/engine/src/cmd/alpha_wrap.rs | 84 ++++++++++++++++++++++++----- 2 files changed, 92 insertions(+), 14 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2c4ecb52c..a5fec91c3 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -604,7 +604,7 @@ impl PdfCrop { /// The outline of a raster image's visible pixels (Text Wrap › Contour › Alpha Channel), in the /// image's pixel space (0..width, 0..height). Derived from the image, so not saved: the engine /// traces it again when a document opens. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug)] pub struct AlphaOutline { pub asset: AssetId, pub threshold: u8, @@ -614,6 +614,26 @@ pub struct AlphaOutline { pub outer: designcraft_geom::PathData, /// The boundaries of transparent holes those areas enclose (wound the other way). pub holes: designcraft_geom::PathData, + /// The image data it was traced from: a relink or link update replaces the asset's data + /// under the same id, and the outline is traced again. (Weak, so it doesn't keep old image + /// data alive, and its address can't be reused by new data while it's held.) + pub source: std::sync::Weak>, +} + +impl AlphaOutline { + /// Traced from `data`, the asset's current image data. + pub fn traced_from(&self, data: &Arc>) -> bool { + std::ptr::eq(self.source.as_ptr(), Arc::as_ptr(data)) + } +} + +impl PartialEq for AlphaOutline { + fn eq(&self, other: &Self) -> bool { + (self.asset, self.threshold, self.width, self.height) == (other.asset, other.threshold, other.width, other.height) + && self.outer == other.outer + && self.holes == other.holes + && self.source.ptr_eq(&other.source) + } } impl Asset { diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index ea94aaf9f..717ae8ac5 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -20,20 +20,25 @@ const MAX_EDGES: usize = 1 << 16; pub(crate) fn sync(doc: &mut Document) { let mut wanted: Vec<(AssetId, u8)> = Vec::new(); for sp in doc.spreads.iter().chain(doc.parents.iter()) { - for it in &sp.items { - if it.wrap.mode == WrapMode::Contour - && it.wrap.contour == ContourType::AlphaChannel - && let Some(g) = it.graphic() - && !wanted.contains(&(g.asset, it.wrap.alpha_threshold)) - { - wanted.push((g.asset, it.wrap.alpha_threshold)); - } + // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or + // on its placed graphic (Direct Selection sets the graphic's). + for top in &sp.items { + top.walk(&mut |it| { + let Some(g) = it.graphic() else { return }; + for w in [&it.wrap, &g.wrap] { + if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel && !wanted.contains(&(g.asset, w.alpha_threshold)) { + wanted.push((g.asset, w.alpha_threshold)); + } + } + }); } } if wanted.is_empty() && doc.alpha_outlines.is_empty() { return; } - doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && doc.assets.contains_key(&o.asset)); + // An outline traced from data the asset no longer has (relinked or updated) is traced again. + let assets = &doc.assets; + doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data))); for (asset, threshold) in wanted { if doc.alpha_outline(asset, threshold).is_some() { continue; @@ -47,7 +52,7 @@ pub(crate) fn sync(doc: &mut Document) { /// The outline of the pixels of `data` more opaque than `threshold`. None for an image that /// can't be read, is too large, or has no transparency (its contour is its rectangle). -pub(crate) fn trace(data: &[u8], asset: AssetId, threshold: u8) -> Option { +pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Option { let (w, h) = designcraft_images::pixel_size(data)?; if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { return None; @@ -78,7 +83,8 @@ pub(crate) fn trace(data: &[u8], asset: AssetId, threshold: u8) -> Option 1, "the frame is nested"); + assert_eq!(d.alpha_outlines.len(), 1, "a nested frame keeps its outline"); + // A frame placed and grouped before its wrap is set: traced too. + let second = place(&mut s, 400); + let other2 = s.execute("frame.create", &json!({"rect": [600, 100, 650, 150]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.group", &json!({"ids": [second, other2]})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [second], "mode": "contour", "contour": "alphaChannel", "threshold": 200})).unwrap(); + assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 2); + // The image data replaced under the same asset, as a relink does: traced again. + let Some(designcraft_doc::Content::Graphic(g)) = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).map(|it| it.content.clone()) + else { + panic!("a graphic") + }; + let narrower = Arc::new(png(|x, _| (24..40).contains(&x))); + s.edit(|d, _| { + let a = d.assets.get(&g.asset).unwrap(); + let mut a = (**a).clone(); + a.data = narrower.clone(); + d.assets.insert(g.asset, Arc::new(a)); + Ok(()) + }) + .unwrap(); + let d = &s.doc().unwrap().doc; + let o = d.alpha_outline(g.asset, designcraft_doc::DEFAULT_ALPHA_THRESHOLD).unwrap(); + assert!(o.traced_from(&narrower)); + let b = o.outer.bounds().unwrap(); + assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline"); + } + /// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no /// offset, and a caption frame at `caption` with 8 pt "Hi". fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) { From 65d19f87ed4345fe7b70c2dbfbd879335dcabdbf Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 11:06:31 +0200 Subject: [PATCH 05/10] Alpha text wrap: read pixels with as_chunks Clippy 1.99 (CI) prefers `as_chunks::<4>()` to `chunks_exact(4)` for a constant chunk size (`chunks_exact_to_as_chunks`). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/alpha_wrap.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 717ae8ac5..54eefe7b7 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -97,7 +97,7 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> (Vec, bool) { let mut mask = vec![false; (cols as usize) * (rows as usize)]; let mut transparent = false; - for (i, px) in rgba.chunks_exact(4).enumerate() { + for (i, px) in rgba.as_chunks::<4>().0.iter().enumerate() { let alpha = px[3]; transparent |= alpha < 255; if alpha > threshold { From 782c38e31a8bdc5e35177318803352d118d64d98 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 12:07:37 +0200 Subject: [PATCH 06/10] Alpha text wrap: an image with no outline is remembered, not traced on every edit `sync` keeps a zero-size outline for an image `trace` finds none in (opaque, unreadable, too large); composition takes it as no outline (the frame), and like a traced one it is dropped when the asset data changes. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/alpha_wrap.rs | 33 ++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 54eefe7b7..8a94ae818 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -44,12 +44,19 @@ pub(crate) fn sync(doc: &mut Document) { continue; } let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; - if let Some(o) = trace(&a.data, asset, threshold) { - doc.alpha_outlines.push(Arc::new(o)); - } + // An image with no outline (opaque, unreadable, too large) is remembered as an empty + // one, so later edits don't decode it again; the contour is then the frame's. + let o = trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold)); + doc.alpha_outlines.push(Arc::new(o)); } } +/// The empty outline standing for an image `trace` found none in: zero-size, which composition +/// takes as no outline, and dropped like a traced one when the asset's data changes. +fn no_outline(data: &Arc>, asset: AssetId, threshold: u8) -> AlphaOutline { + AlphaOutline { asset, threshold, width: 0, height: 0, outer: Default::default(), holes: Default::default(), source: Arc::downgrade(data) } +} + /// The outline of the pixels of `data` more opaque than `threshold`. None for an image that /// can't be read, is too large, or has no transparency (its contour is its rectangle). pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Option { @@ -235,6 +242,26 @@ mod tests { assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); } + /// An image with no outline (here opaque) is remembered as an empty one: later edits don't + /// trace it again, and the contour is the frame's. + #[test] + fn an_image_with_no_outline_is_not_traced_on_every_edit() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|_, _| true); + let id = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "solid.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let first = s.doc().unwrap().doc.alpha_outlines.clone(); + assert_eq!(first.len(), 1, "remembered"); + assert_eq!((first[0].width, first[0].height), (0, 0), "as no outline"); + s.execute("frame.create", &json!({"rect": [300, 300, 350, 350]})).unwrap(); + let after = &s.doc().unwrap().doc.alpha_outlines; + assert!(Arc::ptr_eq(&first[0], &after[0]), "kept, not traced again"); + } + /// Outlines are traced for a wrap set on the placed graphic and for frames inside groups, and /// traced again when the image's data changes under the same asset (relink, link update). #[test] From 8574b55bce817a3c3735469f35b0c51a5ab0fb4f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 17:00:43 +0200 Subject: [PATCH 07/10] i18n: Include Inside Edges is an interface string (the catalog check from #1576) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 7d5b13e2a..79fdc3e80 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -4893,6 +4893,7 @@ mod tests { "Equal fixed heights for the selected rows; cell text may become overset.", "Found", "Grab bag", + "Include Inside Edges", "Key Object", "Load Styles", "layer", From 5b51b16b05c2c03b4e6c712279638ca0208322e4 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:10:35 +0100 Subject: [PATCH 08/10] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 68e674b6e..591974004 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -301,7 +301,7 @@ fn interface_strings() -> HashSet<&'static str> { "Equal fixed heights for the selected rows; cell text may become overset.", "Found", "Grab bag", - "Include Inside Edges", + "Include Inside Edges", "Key Object", "Load Styles", "layer", From 9e9efb3ba3b9d047b3782a22282cd807a33c3872 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:31:11 +0100 Subject: [PATCH 09/10] Alpha text wrap: the default threshold re-exported from main's split item module Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/item.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index 1d2feb6a8..fc997825b 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -29,7 +29,7 @@ pub use paint::{ path_length_bound, }; pub use text_frame::{ - AutoSize, ColumnsKind, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, + AutoSize, ColumnsKind, DEFAULT_ALPHA_THRESHOLD, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, }; From 21267510dc2656959dffdd841ad1408be29df2a5 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 13:57:36 +0100 Subject: [PATCH 10/10] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/item.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index fc997825b..30711b5d9 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -29,8 +29,8 @@ pub use paint::{ path_length_bound, }; pub use text_frame::{ - AutoSize, ColumnsKind, DEFAULT_ALPHA_THRESHOLD, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, - TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, + AutoSize, ColumnsKind, ContourType, DEFAULT_ALPHA_THRESHOLD, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, + TextFrameOptions, TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, }; fn is_zero_usize(v: &usize) -> bool {