Skip to content

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

Q: Gap tool

Brandon Thomas3f2d53f33013
diff --git a/ROADMAP.md b/ROADMAP.md
index 1b2d56830..6906fb5f8 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -74,6 +74,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- 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.
- Gridify: arrow keys while dragging a frame or shape tool add columns/rows (`frame.grid`), one undo step.
+- Gap tool (U, `gap.move`): drag the space between objects (or an object and the page edge) and both sides resize.
- 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 f9e6f4c4d..177bd1bf8 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!(
+ "gap.move",
+ "Move Gap",
+ [],
+ None,
+ "{at: [x, y] (spread), delta | dx/dy, spread?} — Gap tool: the gap at `at` between objects (or an object and the page edge) moves by `delta`; the objects on both sides resize → {axis, changed}",
+ has_doc,
+ gap_move
+ ),
cmd!(
"frame.grid",
"Gridify",
@@ -1288,6 +1297,79 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result<Value> {
})
}
+/// The gap at `p` on spread `sr`: (vertical gap?, edge a, edge b, ids ending at a, ids starting at b).
+pub(crate) fn find_gap(d: &Document, sr: designcraft_doc::SpreadRef, p: Point) -> Option<(bool, f64, f64, Vec<ItemId>, Vec<ItemId>)> {
+ let sp = d.spread(sr)?;
+ let page = sp.page_at_x(p.x).and_then(|i| sp.pages.get(i)).map(|pg| pg.bounds())?;
+ let items: Vec<(ItemId, Rect)> = sp
+ .items
+ .iter()
+ .filter(|it| !it.hidden && !it.locked && d.layer(it.layer).is_none_or(|l| !l.locked && l.visible))
+ .map(|it| (it.id, it.bounds()))
+ .collect();
+ if items.iter().any(|(_, b)| b.contains(p)) {
+ return None;
+ }
+ // Between left and right neighbours (a vertical gap), or above and below (horizontal).
+ let side = |vertical: bool| {
+ let (pos, lo, hi) = if vertical { (p.x, page.x0, page.x1) } else { (p.y, page.y0, page.y1) };
+ let across = |b: &Rect| if vertical { b.y0 <= p.y && p.y <= b.y1 } else { b.x0 <= p.x && p.x <= b.x1 };
+ let end = |b: &Rect| if vertical { b.x1 } else { b.y1 };
+ let start = |b: &Rect| if vertical { b.x0 } else { b.y0 };
+ let a = items.iter().filter(|(_, b)| across(b) && end(b) <= pos).map(|(_, b)| end(b)).fold(lo, f64::max);
+ let z = items.iter().filter(|(_, b)| across(b) && start(b) >= pos).map(|(_, b)| start(b)).fold(hi, f64::min);
+ let before: Vec<ItemId> = items.iter().filter(|(_, b)| across(b) && (end(b) - a).abs() < 0.5).map(|(i, _)| *i).collect();
+ let after: Vec<ItemId> = items.iter().filter(|(_, b)| across(b) && (start(b) - z).abs() < 0.5).map(|(i, _)| *i).collect();
+ (!before.is_empty() || !after.is_empty()).then_some((vertical, a, z, before, after))
+ };
+ match (side(true), side(false)) {
+ (Some(v), Some(h)) => Some(if v.2 - v.1 <= h.2 - h.1 { v } else { h }),
+ (v, h) => v.or(h),
+ }
+}
+
+fn gap_move(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "gap.move";
+ let at = p
+ .get("at")
+ .and_then(Value::as_array)
+ .and_then(|a| Some(Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?)))
+ .ok_or_else(|| bad(ID, "missing at"))?;
+ let sr = spread_param(p, "spread");
+ let (vertical, a, z, before, after) = find_gap(&s.doc()?.doc, sr, at).ok_or_else(|| bad(ID, "no gap there"))?;
+ // `delta` along the gap's axis, or a drag (dx, dy) of which the axis part counts.
+ let delta =
+ p.get("delta").and_then(Value::as_f64).unwrap_or_else(|| p.get(if vertical { "dx" } else { "dy" }).and_then(Value::as_f64).unwrap_or(0.0));
+ let _ = (a, z);
+ s.edit(|d, _| {
+ let mut n = 0;
+ for (ids, is_before) in [(&before, true), (&after, false)] {
+ for id in ids {
+ let Some(it) = d.item_mut(*id) else { continue };
+ let b = it.bounds();
+ let mut to = b;
+ match (vertical, is_before) {
+ (true, true) => to.x1 = (b.x1 + delta).max(b.x0 + 1.0),
+ (true, false) => to.x0 = (b.x0 + delta).min(b.x1 - 1.0),
+ (false, true) => to.y1 = (b.y1 + delta).max(b.y0 + 1.0),
+ (false, false) => to.y0 = (b.y0 + delta).min(b.y1 - 1.0),
+ }
+ let m = Affine::translate((to.x0, to.y0))
+ * Affine::scale_non_uniform(to.width() / b.width().max(1e-9), to.height() / b.height().max(1e-9))
+ * Affine::translate((-b.x0, -b.y0));
+ if matches!(it.content, Content::Group { .. }) {
+ it.xf = m * it.xf;
+ } else {
+ let inner = it.xf.inverse() * m * it.xf;
+ bake(it, inner);
+ }
+ n += 1;
+ }
+ }
+ Ok(json!({"axis": if vertical { "x" } else { "y" }, "changed": n}))
+ })
+}
+
/// 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> {
@@ -2011,3 +2093,22 @@ mod clipping_tests {
assert!(s.execute("object.clippingPath", &json!({"ids": [f], "threshold": 255})).is_err());
}
}
+
+#[cfg(test)]
+mod gap_tests {
+ use super::*;
+
+ #[test]
+ fn moving_a_gap_resizes_both_sides() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let a = s.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap()["id"].as_u64().unwrap();
+ let b = s.execute("frame.create", &json!({"rect": [220, 100, 320, 300]})).unwrap()["id"].as_u64().unwrap();
+ let r = s.execute("gap.move", &json!({"at": [210, 200], "delta": 30})).unwrap();
+ assert_eq!((r["axis"].as_str(), r["changed"].as_u64()), (Some("x"), Some(2)));
+ let bb = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().bounds();
+ assert_eq!((bb(&s, a).x1, bb(&s, b).x0), (230.0, 250.0), "the gap moved, its width kept");
+ assert_eq!(bb(&s, b).x1, 320.0);
+ assert!(s.execute("gap.move", &json!({"at": [150, 200], "delta": 5})).is_err(), "inside an object");
+ }
+}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 5c80e1c11..5cf4e74bf 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -390,3 +390,19 @@ fn gridify_while_drawing_frames() {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.spreads[0].items.len(), n0, "one undo step");
}
+
+#[test]
+fn gap_tool_drag_moves_the_gap() {
+ use designcraft_tools::{PointerEvent, PointerKind};
+ let mut s = session();
+ let a = s.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap()["id"].as_u64().unwrap();
+ s.set_tool("gap");
+ let v = ViewInfo { zoom: 1.0 };
+ s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 200.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 270.0, 205.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, 270.0, 205.0), v).unwrap();
+ // The gap between the frame and the page's right edge: the frame's right side moved 20.
+ let b = s.doc().unwrap().doc.item(designcraft_doc::ItemId(a)).unwrap().bounds();
+ assert_eq!(b.x1, 220.0, "{b:?}");
+ assert_eq!(s.doc().unwrap().history.undo.len(), 2, "create + one gap move");
+}
diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs
index 2c54b6047..3238f000b 100644
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@ -278,6 +278,7 @@ pub fn create(id: &str) -> Box<dyn Tool> {
"zoom" => Box::new(nav::ZoomTool::default()),
"page" => Box::new(nav::PageTool),
"typeOnPath" => Box::new(nav::PathTypeTool),
+ "gap" => Box::new(nav::GapTool::default()),
other => Box::new(NoopTool(tool_info(other).map(|t| t.id).unwrap_or("selection"))),
}
}
diff --git a/crates/tools/src/nav.rs b/crates/tools/src/nav.rs
index 50173e149..773f30394 100644
--- a/crates/tools/src/nav.rs
+++ b/crates/tools/src/nav.rs
@@ -196,3 +196,60 @@ impl Tool for PathTypeTool {
Cursor::Text
}
}
+
+/// Gap tool (U): drag the space between objects (or between an object and the page edge); the
+/// objects on both sides resize so the gap moves.
+#[derive(Default)]
+pub struct GapTool {
+ /// Spread, offset and the press point in spread coordinates.
+ start: Option<(designcraft_doc::SpreadRef, designcraft_geom::Vec2, Point)>,
+ active: bool,
+}
+
+impl Tool for GapTool {
+ fn id(&self) -> &'static str {
+ "gap"
+ }
+
+ fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
+ match ev.kind {
+ PointerKind::Down => {
+ if let Some((sr, p)) = cx.layout.spread_at(ev.pos) {
+ self.start = Some((sr, cx.layout.offset(sr), p));
+ }
+ self.active = false;
+ vec![]
+ }
+ PointerKind::Drag => {
+ let Some((sr, off, p)) = self.start else { return vec![] };
+ let d = (ev.pos - off) - p;
+ let mut out = vec![];
+ if !self.active {
+ if d.hypot() < cx.tol(2.0) {
+ return vec![];
+ }
+ self.active = true;
+ out.push(Action::Begin("Move Gap".into()));
+ }
+ out.push(Action::Preview(
+ "gap.move".into(),
+ serde_json::json!({"spread": crate::spread_json(sr), "at": [p.x, p.y], "dx": d.x, "dy": d.y}),
+ ));
+ out
+ }
+ PointerKind::Up => {
+ self.start = None;
+ if std::mem::take(&mut self.active) { vec![Action::Commit] } else { vec![] }
+ }
+ _ => vec![],
+ }
+ }
+
+ fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
+ Cursor::Crosshair
+ }
+
+ fn busy(&self) -> bool {
+ self.active
+ }
+}
diff --git a/docs/parity.md b/docs/parity.md
index bb7897d5e..00cc10cf0 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -11,14 +11,14 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
|---|---|---|---|---|---|
| P0 | 102 | 99 | 3 | 0 | 99% |
| P1 | 97 | 92 | 4 | 1 | 97% |
-| P2 | 76 | 26 | 14 | 36 | 43% |
+| P2 | 76 | 27 | 14 | 35 | 45% |
| Area | Parity |
|---|---|
| Application shell & workspace | 82% |
| Documents, pages, spreads | 87% |
| Layers | 95% |
-| Frames, shapes & paths | 98% |
+| Frames, shapes & paths | 99% |
| Transform | 100% |
| Fill, stroke, colour | 95% |
| Effects & transparency | 71% |
@@ -114,7 +114,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t
| Frames, shapes & paths | Auto-fit | P1 | D |
| Frames, shapes & paths | Step and Repeat | P1 | D |
| Frames, shapes & paths | Gridify while drawing | P2 | D |
-| Frames, shapes & paths | Gap tool | P2 | M |
+| Frames, shapes & paths | Gap tool | P2 | D |
| Frames, shapes & paths | Live Distribute | P2 | M |
| Frames, shapes & paths | Generate QR Code | P2 | D |
| Frames, shapes & paths | Placeholder text | P1 | D |