Skip to content

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

O: clipping paths traced from alpha or edges

Brandon Thomas754425b1c737
diff --git a/ROADMAP.md b/ROADMAP.md
index 382882d16..28f49aade 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -72,6 +72,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Object ▸ Primary Text Frame (`object.primaryTextFrame`): any text frame's story can become (or stop being) the primary story Smart Text Reflow follows.
- Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable).
- Articles panel (`article.new/add/remove/options/delete/list`): reading order and content of EPUB and HTML exports.
+- Object ▸ Clipping Path (`object.clippingPath {type: alpha|edges, threshold, tolerance}`): traces the placed image and makes the outline the frame.
- Drag and drop text editing: drag selected text to move it (Alt copies) with its formatting (`text.release`).
- Image Import Options: place any page of a multi-page PDF (`file.place {pdfPage}`; the app asks which page), shown on screen and embedded as that page in PDF export.
- Define Lists: named numbered lists that continue across stories in page order (`list.define`, paragraph `listName` / `startAt`), round-tripped through IDML; `null` in `type.para` / `type.char` now removes an override.
diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs
index f00f9d181..d3d268476 100644
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@ -437,6 +437,15 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(json!({"sides": s.prefs.polygon_sides, "starInset": (s.prefs.star_inset * 100.0).round()}))
}
),
+ cmd!(
+ "object.clippingPath",
+ "Clipping Path…",
+ ["Object", "Clipping Path"],
+ None,
+ "{type?: alpha|edges (default alpha), threshold?: 0–255 (alpha: opaque above; edges: darker than 255 − threshold counts; default 25), tolerance?: px (2), ids?} — traces the placed graphic and makes the outline the frame (Convert Clipping Path to Frame)",
+ has_selection,
+ clipping_path
+ ),
cmd!(
"object.primaryTextFrame",
"Primary Text Frame",
@@ -1249,6 +1258,80 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result<Value> {
})
}
+/// Clipping Path: trace the graphic (its alpha channel, or edges against a white background) and
+/// give the frame that outline.
+fn clipping_path(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "object.clippingPath";
+ let ids = targets(s, p)?;
+ let edges = match str_param(p, "type").unwrap_or("alpha") {
+ "alpha" => false,
+ "edges" => true,
+ t => return Err(bad(ID, format!("unknown type `{t}` (alpha, edges)"))),
+ };
+ let threshold = p.get("threshold").and_then(Value::as_f64).unwrap_or(25.0).clamp(0.0, 255.0);
+ let tol = p.get("tolerance").and_then(Value::as_f64).unwrap_or(2.0).max(0.1);
+ // Trace each graphic (outside the edit: decoding is the slow part).
+ let mut paths: Vec<(ItemId, designcraft_geom::PathData)> = Vec::new();
+ {
+ let d = &s.doc()?.doc;
+ for id in &ids {
+ let Some(it) = d.item(*id) else { continue };
+ let Some(g) = it.graphic() else { continue };
+ let Some(asset) = d.assets.get(&g.asset) else { continue };
+ let Some(px) = designcraft_render::decode_pixmap_page(&asset.data, asset.page) else { continue };
+ let (pw, ph) = (px.width() as usize, px.height() as usize);
+ // A grid of at most 400 cells on the long side.
+ let step = (pw.max(ph) as f64 / 400.0).max(1.0);
+ let (w, h) = (((pw as f64) / step).ceil() as usize, ((ph as f64) / step).ceil() as usize);
+ let mask: Vec<bool> = (0..w * h)
+ .map(|i| {
+ let (x, y) = (((i % w) as f64 * step) as u16, ((i / w) as f64 * step) as u16);
+ let c = px.sample(x.min(pw as u16 - 1), y.min(ph as u16 - 1));
+ if edges {
+ // Un-premultiply over white: anything darker than the threshold is inside.
+ let a = c.a as f64 / 255.0;
+ let lum = (0.299 * c.r as f64 + 0.587 * c.g as f64 + 0.114 * c.b as f64) + 255.0 * (1.0 - a);
+ lum < 255.0 - threshold
+ } else {
+ c.a as f64 > threshold
+ }
+ })
+ .collect();
+ // The tolerance is in image pixels; the grid cells are `step` pixels.
+ let rings = designcraft_geom::trace::trace(&mask, w, h, tol / step, 4.0);
+ if rings.is_empty() {
+ return Err(bad(ID, "nothing to trace (the image is empty at this threshold)"));
+ }
+ let (sx, sy) = (g.size.0 / w as f64, g.size.1 / h as f64);
+ let subpaths = rings
+ .into_iter()
+ .map(|r| {
+ let pts: Vec<Point> = r.into_iter().map(|q| g.xf * Point::new(q.x * sx, q.y * sy)).collect();
+ designcraft_geom::path::SubPath::polyline(&pts, true)
+ })
+ .collect();
+ paths.push((*id, designcraft_geom::PathData::new(subpaths)));
+ }
+ }
+ if paths.is_empty() {
+ return Err(bad(ID, "select a frame with a placed graphic"));
+ }
+ s.edit(|d, _| {
+ let n = paths.len();
+ for (id, path) in paths {
+ if let Some(it) = d.item_mut(id) {
+ it.path = path;
+ it.shape = Shape::Path;
+ it.corners = Default::default();
+ if let Content::Graphic(g) = &mut it.content {
+ g.auto_fit = designcraft_doc::Fitting::None;
+ }
+ }
+ }
+ Ok(json!({"changed": n}))
+ })
+}
+
fn fitting_mode(s: &str) -> Option<designcraft_doc::Fitting> {
use designcraft_doc::Fitting as F;
Some(match s {
@@ -1867,3 +1950,34 @@ mod primary_frame_tests {
assert!(s.execute("object.primaryTextFrame", &json!({"ids": [g]})).is_err());
}
}
+
+#[cfg(test)]
+mod clipping_tests {
+ use super::*;
+
+ #[test]
+ fn clipping_path_from_alpha_traces_the_shape() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ // 40×40 image: an opaque disc on transparency.
+ let mut px = vec![0u8; 40 * 40 * 4];
+ for y in 0..40 {
+ for x in 0..40 {
+ let (dx, dy) = (x as f64 + 0.5 - 20.0, y as f64 + 0.5 - 20.0);
+ if (dx * dx + dy * dy).sqrt() < 15.0 {
+ px[(y * 40 + x) * 4..(y * 40 + x) * 4 + 4].copy_from_slice(&[200, 0, 0, 255]);
+ }
+ }
+ }
+ let png = designcraft_render::Rendered { width: 40, height: 40, pixels: px }.to_png();
+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 140, 140]})).unwrap()["id"].as_u64().unwrap();
+ s.execute("file.place", &json!({"base64": super::super::file::base64_encode(&png), "name": "disc.png", "frame": f})).unwrap();
+ s.execute("object.clippingPath", &json!({"ids": [f], "tolerance": 0.5})).unwrap();
+ let it = s.doc().unwrap().doc.item(ItemId(f)).unwrap().clone();
+ let b = it.bounds();
+ // The disc spans 5..35 of the 40 px image placed at 100..140.
+ assert!((b.x0 - 105.0).abs() < 1.5 && (b.x1 - 135.0).abs() < 1.5, "{b:?}");
+ assert_eq!(it.shape, Shape::Path);
+ assert!(s.execute("object.clippingPath", &json!({"ids": [f], "threshold": 255})).is_err());
+ }
+}
diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs
index fe3c1e22d..91f29a25e 100644
--- a/crates/geom/src/lib.rs
+++ b/crates/geom/src/lib.rs
@@ -18,6 +18,7 @@ pub mod qr;
pub mod shapes;
pub mod snap;
pub mod stroke_style;
+pub mod trace;
pub mod units;
pub mod warp;
diff --git a/crates/geom/src/trace.rs b/crates/geom/src/trace.rs
new file mode 100644
index 000000000..b2d850ea9
--- /dev/null
+++ b/crates/geom/src/trace.rs
@@ -0,0 +1,123 @@
+//! Outline tracing for clipping paths: the boundary of the "inside" pixels of a mask, as closed
+//! polygons in pixel coordinates, simplified.
+
+use std::collections::HashMap;
+
+use crate::Point;
+
+/// Closed outlines around the `true` cells of a `w`×`h` mask (row-major), simplified to within
+/// `tol` pixels; outlines enclosing less than `min_area` pixels are dropped. Holes come out
+/// with the opposite winding.
+pub fn trace(mask: &[bool], w: usize, h: usize, tol: f64, min_area: f64) -> Vec<Vec<Point>> {
+ let inside = |x: isize, y: isize| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && mask[y as usize * w + x as usize];
+ // Pixel-border edges with the inside on the right (clockwise, y down).
+ let mut next: HashMap<(isize, isize), Vec<(isize, isize)>> = HashMap::new();
+ let mut add = |a: (isize, isize), b: (isize, isize)| next.entry(a).or_default().push(b);
+ for y in 0..h as isize {
+ for x in 0..w as isize {
+ if !inside(x, y) {
+ continue;
+ }
+ if !inside(x, y - 1) {
+ add((x, y), (x + 1, y));
+ }
+ if !inside(x + 1, y) {
+ add((x + 1, y), (x + 1, y + 1));
+ }
+ if !inside(x, y + 1) {
+ add((x + 1, y + 1), (x, y + 1));
+ }
+ if !inside(x - 1, y) {
+ add((x, y + 1), (x, y));
+ }
+ }
+ }
+ let mut out = Vec::new();
+ let mut starts: Vec<(isize, isize)> = next.keys().copied().collect();
+ starts.sort();
+ for s in starts {
+ while let Some(first) = next.get_mut(&s).and_then(|v| v.pop()) {
+ let mut ring = vec![s];
+ let mut cur = first;
+ while cur != s {
+ ring.push(cur);
+ match next.get_mut(&cur).and_then(|v| v.pop()) {
+ Some(n) => cur = n,
+ None => break,
+ }
+ }
+ let pts: Vec<Point> = ring.into_iter().map(|(x, y)| Point::new(x as f64, y as f64)).collect();
+ if area(&pts).abs() >= min_area {
+ out.push(simplify_closed(&pts, tol));
+ }
+ }
+ }
+ out
+}
+
+fn area(p: &[Point]) -> f64 {
+ let n = p.len();
+ (0..n).map(|i| p[i].x * p[(i + 1) % n].y - p[(i + 1) % n].x * p[i].y).sum::<f64>() / 2.0
+}
+
+/// Ramer–Douglas–Peucker on a closed ring (split at its two farthest-apart points).
+fn simplify_closed(p: &[Point], tol: f64) -> Vec<Point> {
+ if p.len() < 4 {
+ return p.to_vec();
+ }
+ let far = (1..p.len()).max_by(|a, b| (p[*a] - p[0]).hypot().total_cmp(&(p[*b] - p[0]).hypot())).unwrap_or(p.len() / 2);
+ let mut a = rdp(&p[..=far], tol);
+ let mut back: Vec<Point> = p[far..].to_vec();
+ back.push(p[0]);
+ let b = rdp(&back, tol);
+ a.pop();
+ a.extend(b);
+ a.pop();
+ a
+}
+
+fn rdp(p: &[Point], tol: f64) -> Vec<Point> {
+ if p.len() < 3 {
+ return p.to_vec();
+ }
+ let (a, b) = (p[0], p[p.len() - 1]);
+ let d = b - a;
+ let len = d.hypot();
+ let (mut best, mut idx) = (0.0, 0);
+ for (i, q) in p.iter().enumerate().take(p.len() - 1).skip(1) {
+ let dist = if len < 1e-12 { (*q - a).hypot() } else { ((*q - a).cross(d) / len).abs() };
+ if dist > best {
+ (best, idx) = (dist, i);
+ }
+ }
+ if best <= tol {
+ return vec![a, b];
+ }
+ let mut left = rdp(&p[..=idx], tol);
+ left.pop();
+ left.extend(rdp(&p[idx..], tol));
+ left
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn traces_a_disc_and_its_hole() {
+ let (w, h) = (40, 40);
+ let mask: Vec<bool> = (0..w * h)
+ .map(|i| {
+ let (x, y) = ((i % w) as f64 + 0.5 - 20.0, (i / w) as f64 + 0.5 - 20.0);
+ let r = (x * x + y * y).sqrt();
+ r < 15.0 && r > 6.0
+ })
+ .collect();
+ let rings = trace(&mask, w, h, 0.75, 4.0);
+ assert_eq!(rings.len(), 2, "outer edge and hole");
+ let areas: Vec<f64> = rings.iter().map(|r| area(r)).collect();
+ assert!(areas.iter().any(|a| *a > 600.0) && areas.iter().any(|a| *a < -80.0), "{areas:?}");
+ assert!(rings.iter().all(|r| r.len() < 60), "simplified");
+ assert!(trace(&[false; 16], 4, 4, 1.0, 1.0).is_empty());
+ }
+}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 97dc1b7cc..c26ebecbc 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -385,6 +385,10 @@ pub const MENUS: &[(&str, &[&str])] = &[
"cmd:object.convertShape|Closed Path|{\"to\": \"closedPath\"}",
"<",
"ui:app.qrCode",
+ ">Clipping Path",
+ "cmd:object.clippingPath|Alpha Channel|{\"type\": \"alpha\"}",
+ "cmd:object.clippingPath|Detect Edges|{\"type\": \"edges\"}",
+ "<",
">Captions",
"cmd:object.caption",
"<",
diff --git a/docs/parity.md b/docs/parity.md
index 80af35663..4389beafb 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -5,20 +5,20 @@ The summary is generated by `cargo xtask parity` from the table at the bottom of
Each row of the InDesign feature catalogue is scored **D** (done), **P** (partial: works but lacks options or UI) or **M** (missing), weighted by priority (**P0** core = 3, **P1** = 2, **P2** = 1). Out-of-scope rows (Adobe cloud services, plug-ins, Typekit, Flash) are excluded.
<!-- SUMMARY -->
-**Weighted breadth parity: 90%** over 275 features.
+**Weighted breadth parity: 91%** over 275 features.
| Priority | Features | Done | Partial | Missing | Parity |
|---|---|---|---|---|---|
| P0 | 102 | 99 | 3 | 0 | 99% |
| P1 | 97 | 92 | 4 | 1 | 97% |
-| P2 | 76 | 24 | 14 | 38 | 41% |
+| P2 | 76 | 25 | 14 | 37 | 42% |
| Area | Parity |
|---|---|
| Application shell & workspace | 82% |
| Documents, pages, spreads | 87% |
| Layers | 95% |
-| Frames, shapes & paths | 95% |
+| Frames, shapes & paths | 96% |
| Transform | 100% |
| Fill, stroke, colour | 95% |
| Effects & transparency | 71% |
@@ -107,7 +107,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t
| Frames, shapes & paths | Pathfinder | P1 | D |
| Frames, shapes & paths | Compound paths | P1 | D |
| Frames, shapes & paths | Text outlines | P1 | D |
-| Frames, shapes & paths | Clipping paths | P2 | M |
+| Frames, shapes & paths | Clipping paths | P2 | D |
| Frames, shapes & paths | Frame fitting | P0 | D |
| Frames, shapes & paths | Frame Fitting Options | P1 | D |
| Frames, shapes & paths | Content grabber, select content/container | P0 | D |