Skip to content

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

M1.7/M2: align & distribute, Pen tool, Direct Selection anchor/handle editing

Brandon Thomas362c16e050d3
diff --git a/.gitignore b/.gitignore
index 0d78b09de..6c08f4809 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,3 +5,5 @@ plan/
/corpus
/log
.DS_Store
+/.claude/
+/target-*/
diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs
index e1253f614..caf5c6435 100644
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@ -205,6 +205,28 @@ pub fn specs() -> Vec<CommandSpec> {
let name = str_param(p, "name").unwrap_or("").to_string();
set_flag(s, p, move |i| i.name = name.clone(), false)
}),
+ cmd!("path.create", "Create Path", [], None, "{spread?, anchors: [{p:[x,y], in?:[x,y], out?:[x,y]}], closed?: bool}", has_doc, path_create),
+ cmd!("path.appendAnchor", "Add Anchor", [], None, "{id, anchor: {p, in?, out?}} (spread coords)", has_doc, path_append),
+ cmd!("path.close", "Close Path", ["Object", "Paths"], None, "{id}", has_doc, path_close),
+ cmd!("path.moveAnchors", "Move Anchors", [], None, "{id, anchors: [[subpath, index]], dx, dy, handle?: in|out}", has_doc, path_move_anchors),
+ cmd!(
+ "object.align",
+ "Align",
+ ["Window", "Object & Layout", "Align"],
+ None,
+ "{edge: left|hcenter|right|top|vcenter|bottom, to?: selection|keyObject|margins|page|spread, ids?}",
+ has_selection,
+ align
+ ),
+ cmd!(
+ "object.distribute",
+ "Distribute",
+ ["Window", "Object & Layout", "Align"],
+ None,
+ "{axis: horizontal|vertical, by?: centers|spacing, spacing?: points, ids?}",
+ has_selection,
+ distribute
+ ),
cmd!("object.setLayer", "Move to Layer", [], None, "{layer, ids?}", has_selection, |s, p| {
let l = designcraft_doc::LayerId(p.get("layer").and_then(Value::as_u64).unwrap_or(0));
set_flag(s, p, move |i| i.layer = l, false)
@@ -723,3 +745,201 @@ impl RemoveKeep for Document {
Ok(Arc::unwrap_or_clone(sp.items.remove(loc.path[0])))
}
}
+
+/// Bounds of each target item (spread space) and the alignment reference rect.
+fn align_reference(d: &Document, ids: &[ItemId], to: &str, key: Option<ItemId>) -> Option<Rect> {
+ let bounds: Vec<Rect> = ids.iter().filter_map(|i| d.item(*i).map(Item::bounds)).collect();
+ let union = bounds.iter().copied().reduce(|a, b| a.union(b))?;
+ let first = ids.first().and_then(|i| d.find(*i))?;
+ let sp = d.spread(first.spread)?;
+ let page = sp.page_at_x(union.center().x).and_then(|pi| sp.pages.get(pi));
+ Some(match to {
+ "keyObject" => key.and_then(|k| d.item(k)).map(Item::bounds).unwrap_or(union),
+ "margins" => page.map(|p| p.margin_rect()).unwrap_or(union),
+ "page" => page.map(|p| p.bounds()).unwrap_or(union),
+ "spread" => sp.bounds(),
+ _ => union,
+ })
+}
+
+fn align(s: &mut Session, p: &Value) -> Result<Value> {
+ let ids = targets(s, p)?;
+ let edge = str_param(p, "edge").unwrap_or("left").to_string();
+ let to = str_param(p, "to").map(str::to_string).unwrap_or_else(|| if ids.len() > 1 { "selection".into() } else { "page".into() });
+ let key = s.doc()?.selection.key;
+ s.edit(|d, _| {
+ let r = align_reference(d, &ids, &to, key).ok_or_else(|| bad("object.align", "nothing to align"))?;
+ for id in &ids {
+ if Some(*id) == key && to == "keyObject" {
+ continue;
+ }
+ let Some(it) = d.item_mut(*id) else { continue };
+ if it.locked {
+ continue;
+ }
+ let b = it.bounds();
+ let (dx, dy) = match edge.as_str() {
+ "left" => (r.x0 - b.x0, 0.0),
+ "hcenter" => (r.center().x - b.center().x, 0.0),
+ "right" => (r.x1 - b.x1, 0.0),
+ "top" => (0.0, r.y0 - b.y0),
+ "vcenter" => (0.0, r.center().y - b.center().y),
+ "bottom" => (0.0, r.y1 - b.y1),
+ other => return Err(bad("object.align", format!("unknown edge `{other}`"))),
+ };
+ it.xf = Affine::translate((dx, dy)) * it.xf;
+ }
+ ok()
+ })
+}
+
+fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
+ let ids = targets(s, p)?;
+ if ids.len() < 3 && p.get("spacing").is_none() {
+ return Err(bad("object.distribute", "select at least three objects"));
+ }
+ let horizontal = str_param(p, "axis") != Some("vertical");
+ let by_spacing = str_param(p, "by") == Some("spacing") || p.get("spacing").is_some();
+ let fixed = p.get("spacing").and_then(Value::as_f64);
+ s.edit(|d, _| {
+ let mut items: Vec<(ItemId, Rect)> = ids.iter().filter_map(|i| d.item(*i).map(|it| (*i, it.bounds()))).collect();
+ let key = |r: &Rect| if horizontal { r.x0 } else { r.y0 };
+ items.sort_by(|a, b| key(&a.1).total_cmp(&key(&b.1)));
+ let n = items.len();
+ if n < 2 {
+ return ok();
+ }
+ let (first, last) = (items[0].1, items[n - 1].1);
+ let lo = |r: &Rect| if horizontal { r.x0 } else { r.y0 };
+ let hi = |r: &Rect| if horizontal { r.x1 } else { r.y1 };
+ let size = |r: &Rect| hi(r) - lo(r);
+ let mut targets: Vec<f64> = Vec::with_capacity(n);
+ if by_spacing {
+ let total: f64 = items.iter().map(|(_, r)| size(r)).sum();
+ let gap = fixed.unwrap_or_else(|| (hi(&last) - lo(&first) - total) / (n - 1) as f64);
+ let mut pos = lo(&first);
+ for (_, r) in &items {
+ targets.push(pos);
+ pos += size(r) + gap;
+ }
+ } else {
+ let c0 = (lo(&first) + hi(&first)) / 2.0;
+ let c1 = (lo(&last) + hi(&last)) / 2.0;
+ for (k, (_, r)) in items.iter().enumerate() {
+ targets.push(c0 + (c1 - c0) * k as f64 / (n - 1) as f64 - size(r) / 2.0);
+ }
+ }
+ for ((id, r), t) in items.iter().zip(targets) {
+ let delta = t - lo(r);
+ if let Some(it) = d.item_mut(*id) {
+ let v = if horizontal { Vec2::new(delta, 0.0) } else { Vec2::new(0.0, delta) };
+ it.xf = Affine::translate(v) * it.xf;
+ }
+ }
+ ok()
+ })
+}
+
+fn anchor_from(v: &Value) -> Option<designcraft_geom::Anchor> {
+ let pt = |k: &str| -> Option<Point> {
+ let a = v.get(k)?.as_array()?;
+ Some(Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?))
+ };
+ let p = pt("p")?;
+ let h_in = pt("in").unwrap_or(p);
+ let h_out = pt("out").unwrap_or(p);
+ let smooth = (h_in - p).hypot() > 1e-9 || (h_out - p).hypot() > 1e-9;
+ Some(designcraft_geom::Anchor {
+ p,
+ h_in,
+ h_out,
+ kind: if smooth { designcraft_geom::AnchorKind::Smooth } else { designcraft_geom::AnchorKind::Corner },
+ })
+}
+
+fn path_create(s: &mut Session, p: &Value) -> Result<Value> {
+ let anchors: Vec<designcraft_geom::Anchor> =
+ p.get("anchors").and_then(Value::as_array).map(|a| a.iter().filter_map(anchor_from).collect()).unwrap_or_default();
+ if anchors.len() < 2 {
+ return Err(bad("path.create", "a path needs at least two anchors"));
+ }
+ let closed = bool_or(p, "closed", false);
+ let sr = spread_param(p, "spread");
+ let lid = s.doc()?.active_layer;
+ s.edit(|d, sel| {
+ let id = ItemId(d.alloc());
+ let shape = if anchors.len() == 2 && !closed { Shape::GraphicLine } else { Shape::Path };
+ let mut it = Item::new(id, lid, shape, designcraft_geom::PathData::single(designcraft_geom::SubPath::new(anchors, closed)));
+ it.stroke = Stroke::default();
+ d.insert_item(sr, it, None)?;
+ *sel = Selection::items(vec![id]);
+ Ok(json!({"id": id.0}))
+ })
+}
+
+fn path_append(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = super::id_param(p, "id").ok_or_else(|| bad("path.appendAnchor", "missing id"))?;
+ let a = p.get("anchor").and_then(anchor_from).ok_or_else(|| bad("path.appendAnchor", "missing anchor"))?;
+ s.edit(|d, _| {
+ let loc = d.find(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
+ let inv = (d.parent_xf(&loc) * d.item_at(&loc).map(|i| i.xf).unwrap_or_default()).inverse();
+ let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
+ let sp = it.path.subpaths.last_mut().ok_or_else(|| bad("path.appendAnchor", "empty path"))?;
+ sp.anchors.push(a.transform(inv));
+ if it.shape == Shape::GraphicLine {
+ it.shape = Shape::Path;
+ }
+ ok()
+ })
+}
+
+fn path_close(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = super::id_param(p, "id").ok_or_else(|| bad("path.close", "missing id"))?;
+ s.edit(|d, _| {
+ let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
+ for sp in &mut it.path.subpaths {
+ sp.closed = true;
+ }
+ if it.shape == Shape::GraphicLine {
+ it.shape = Shape::Path;
+ }
+ ok()
+ })
+}
+
+fn path_move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = super::id_param(p, "id").ok_or_else(|| bad("path.moveAnchors", "missing id"))?;
+ let which: Vec<(usize, usize)> = p.get("anchors").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
+ let d0 = Vec2::new(f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0));
+ let handle = str_param(p, "handle").map(str::to_string);
+ s.edit(|d, _| {
+ let loc = d.find(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
+ let m = d.parent_xf(&loc) * d.item_at(&loc).map(|i| i.xf).unwrap_or_default();
+ // Spread-space delta → inner-space delta (linear part only).
+ let inv = m.inverse();
+ let dv = (inv * Point::new(d0.x, d0.y)) - (inv * Point::ZERO);
+ let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
+ for (si, ai) in &which {
+ let Some(a) = it.path.anchor_mut(*si, *ai) else { continue };
+ match handle.as_deref() {
+ Some("in") => {
+ a.h_in += dv;
+ if a.kind == designcraft_geom::AnchorKind::Smooth {
+ a.h_out = a.p - (a.h_in - a.p);
+ }
+ }
+ Some("out") => {
+ a.h_out += dv;
+ if a.kind == designcraft_geom::AnchorKind::Smooth {
+ a.h_in = a.p - (a.h_out - a.p);
+ }
+ }
+ _ => a.translate(dv),
+ }
+ }
+ if it.shape == Shape::Rectangle || it.shape == Shape::Oval || it.shape == Shape::Polygon {
+ it.shape = Shape::Path;
+ }
+ ok()
+ })
+}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 736b73ab9..3dd57162c 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -104,3 +104,56 @@ fn every_command_has_metadata() {
}
assert!(command_specs().len() > 60);
}
+
+#[test]
+fn align_and_distribute() {
+ let mut s = session();
+ let mut ids = vec![];
+ for (x, w) in [(10.0, 20.0), (100.0, 40.0), (300.0, 10.0)] {
+ let r = s.execute("frame.create", &json!({"rect": [x, 50.0 + x / 10.0, x + w, 100.0], "content": "unassigned"})).unwrap();
+ ids.push(r["id"].as_u64().unwrap());
+ }
+ s.execute("object.align", &json!({"ids": ids, "edge": "top"})).unwrap();
+ let st = s.doc().unwrap();
+ let tops: Vec<f64> = ids.iter().map(|i| st.doc.item(designcraft_doc::ItemId(*i)).unwrap().bounds().y0).collect();
+ assert!(tops.iter().all(|t| (*t - 51.0).abs() < 1e-9), "{tops:?}");
+ s.execute("object.distribute", &json!({"ids": ids, "by": "spacing"})).unwrap();
+ let st = s.doc().unwrap();
+ let b: Vec<designcraft_geom::Rect> = ids.iter().map(|i| st.doc.item(designcraft_doc::ItemId(*i)).unwrap().bounds()).collect();
+ assert!(((b[1].x0 - b[0].x1) - (b[2].x0 - b[1].x1)).abs() < 1e-9);
+ s.execute("object.align", &json!({"ids": [ids[0]], "edge": "left", "to": "margins"})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.item(designcraft_doc::ItemId(ids[0])).unwrap().bounds().x0, 36.0);
+}
+
+#[test]
+fn pen_draws_and_direct_selection_edits() {
+ use designcraft_tools::{PointerEvent, PointerKind};
+ let mut s = session();
+ let v = ViewInfo { zoom: 1.0 };
+ s.set_tool("pen");
+ let click = |s: &mut Session, x: f64, y: f64| {
+ s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap();
+ };
+ click(&mut s, 100.0, 100.0);
+ click(&mut s, 200.0, 100.0);
+ // A smooth point (drag).
+ s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 240.0, 200.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, 240.0, 200.0), v).unwrap();
+ click(&mut s, 100.0, 100.0); // close
+ let st = s.doc().unwrap();
+ let it = &st.doc.spreads[0].items[0];
+ assert_eq!(it.path.subpaths[0].anchors.len(), 3);
+ assert!(it.path.subpaths[0].closed);
+ assert!(it.path.subpaths[0].anchors[2].has_out());
+ let id = it.id;
+ // Direct Selection: drag the first anchor.
+ s.set_tool("directSelection");
+ s.execute("selection.set", &json!({"ids": [id.0]})).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 90.0, 80.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, 90.0, 80.0), v).unwrap();
+ let a = s.doc().unwrap().doc.item(id).unwrap().path.subpaths[0].anchors[0].p;
+ assert_eq!(a, designcraft_geom::Point::new(90.0, 80.0));
+}
diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs
index 65386d67b..167c01c17 100644
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@ -12,6 +12,7 @@ pub mod catalog;
mod frame;
pub mod layout;
mod nav;
+mod pen;
pub mod select;
mod text;
@@ -234,6 +235,7 @@ pub fn create(id: &str) -> Box<dyn Tool> {
"directSelection" => Box::new(select::SelectionTool::new(true)),
"rectangleFrame" | "ellipseFrame" | "polygonFrame" | "rectangle" | "ellipse" | "polygon" | "line" => Box::new(frame::FrameTool::new(id)),
"type" => Box::new(text::TypeTool::default()),
+ "pen" => Box::new(pen::PenTool::default()),
"hand" => Box::new(nav::HandTool::default()),
"zoom" => Box::new(nav::ZoomTool),
other => Box::new(NoopTool(tool_info(other).map(|t| t.id).unwrap_or("selection"))),
diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs
new file mode 100644
index 000000000..560c4c3d3
--- /dev/null
+++ b/crates/tools/src/pen.rs
@@ -0,0 +1,152 @@
+//! Pen tool (P): click for corner points, drag for smooth points, click the first point to close,
+//! Enter/Esc (or switching tools) to finish an open path. Each anchor is its own undo step, as in
+//! InDesign.
+
+use designcraft_doc::SpreadRef;
+use designcraft_geom::{BezPath, Point};
+use serde_json::{Value, json};
+
+use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, spread_json};
+
+#[derive(Default)]
+pub struct PenTool {
+ /// The path being drawn: (item id once created, spread, anchors in spread coords).
+ path: Option<u64>,
+ spread: Option<SpreadRef>,
+ /// Anchors as (p, in, out) in spread coordinates.
+ anchors: Vec<(Point, Point, Point)>,
+ dragging: bool,
+ hover: Point,
+}
+
+fn anchor_json(a: &(Point, Point, Point)) -> Value {
+ json!({"p": [a.0.x, a.0.y], "in": [a.1.x, a.1.y], "out": [a.2.x, a.2.y]})
+}
+
+impl PenTool {
+ fn finish(&mut self) -> Vec<Action> {
+ self.path = None;
+ self.spread = None;
+ self.anchors.clear();
+ self.dragging = false;
+ vec![]
+ }
+ fn commit_anchor(&mut self) -> Vec<Action> {
+ let Some(sr) = self.spread else { return vec![] };
+ let Some(last) = self.anchors.last() else { return vec![] };
+ match self.path {
+ None if self.anchors.len() >= 2 => {
+ let anchors: Vec<Value> = self.anchors.iter().map(anchor_json).collect();
+ vec![Action::Exec("path.create".into(), json!({"spread": spread_json(sr), "anchors": anchors, "closed": false, "notifyPen": true}))]
+ }
+ Some(id) => vec![Action::Exec("path.appendAnchor".into(), json!({"id": id, "anchor": anchor_json(last)}))],
+ None => vec![],
+ }
+ }
+}
+
+impl Tool for PenTool {
+ fn id(&self) -> &'static str {
+ "pen"
+ }
+
+ fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
+ let Some((sr, sp)) = cx.layout.spread_at(ev.pos) else { return vec![] };
+ self.hover = ev.pos;
+ // The pen continues on the spread where the path started.
+ let sp = match self.spread {
+ Some(s) if s != sr => ev.pos - cx.layout.offset(s) + designcraft_geom::Vec2::ZERO,
+ _ => sp,
+ };
+ // Pick up the item id created by path.create (the newest selected path).
+ if self.path.is_none() && self.anchors.len() >= 2 {
+ self.path = cx.selection.items.last().map(|i| i.0);
+ }
+ match ev.kind {
+ PointerKind::Down => {
+ // Close on the first anchor.
+ if self.anchors.len() >= 2
+ && let Some(first) = self.anchors.first()
+ && (first.0 - sp).hypot() <= cx.tol(6.0)
+ {
+ let out = match self.path {
+ Some(id) => vec![Action::Exec("path.close".into(), json!({"id": id}))],
+ None => vec![],
+ };
+ self.finish();
+ return out;
+ }
+ let mut p = sp;
+ if ev.mods.shift
+ && let Some(last) = self.anchors.last()
+ {
+ p = last.0 + designcraft_geom::constrain_angle(p - last.0, 45.0);
+ }
+ if self.anchors.is_empty() {
+ self.spread = Some(sr);
+ }
+ self.anchors.push((p, p, p));
+ self.dragging = true;
+ vec![]
+ }
+ PointerKind::Drag => {
+ if let Some(a) = self.anchors.last_mut() {
+ // Smooth point: out handle follows the pointer, in handle mirrors it.
+ a.2 = sp;
+ a.1 = a.0 - (sp - a.0);
+ }
+ vec![]
+ }
+ PointerKind::Up => {
+ if !self.dragging {
+ return vec![];
+ }
+ self.dragging = false;
+ self.commit_anchor()
+ }
+ _ => vec![],
+ }
+ }
+
+ fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
+ match key {
+ ToolKey::Enter | ToolKey::Escape => {
+ let had = !self.anchors.is_empty();
+ self.finish();
+ if had { vec![Action::Exec("selection.set".into(), json!({"ids": []}))] } else { vec![] }
+ }
+ _ => vec![],
+ }
+ }
+
+ fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
+ let Some(sr) = self.spread else { return vec![] };
+ let off = cx.layout.offset(sr);
+ let mut out = Vec::new();
+ if let Some(last) = self.anchors.last()
+ && !self.dragging
+ {
+ // Rubber band to the pointer.
+ out.push(Overlay::Line { a: last.0 + off, b: self.hover, color: [79, 153, 255], dashed: true });
+ }
+ if self.path.is_none() && self.anchors.len() == 1 {
+ let a = self.anchors[0];
+ out.push(Overlay::Line { a: a.1 + off, b: a.2 + off, color: [79, 153, 255], dashed: false });
+ }
+ if self.dragging
+ && let Some(a) = self.anchors.last()
+ {
+ out.push(Overlay::Line { a: a.1 + off, b: a.2 + off, color: [79, 153, 255], dashed: false });
+ let _ = BezPath::new();
+ }
+ out
+ }
+
+ fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
+ Cursor::Pen
+ }
+
+ fn busy(&self) -> bool {
+ !self.anchors.is_empty()
+ }
+}
diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs
index 4fa2642ee..84d59f978 100644
--- a/crates/tools/src/select.rs
+++ b/crates/tools/src/select.rs
@@ -17,6 +17,30 @@ enum Drag {
Move { start: Point, origin_spread: SpreadRef },
Resize { handle: usize, start: Point, from: Rect, spread: SpreadRef },
Marquee { start: Point, cur: Point },
+ Anchor { id: u64, si: usize, ai: usize, handle: Option<&'static str>, start: Point },
+}
+
+/// Anchor or handle of a selected item under `p` (canvas): (item, subpath, anchor, handle).
+pub fn anchor_at(cx: &ToolContext, p: Point) -> Option<(u64, usize, usize, Option<&'static str>)> {
+ let tol = cx.tol(5.0);
+ for id in &cx.selection.items {
+ let (Some(it), Some(xf)) = (cx.doc.item(*id), cx.item_canvas_xf(*id)) else { continue };
+ let m = xf * it.xf;
+ for (si, sp) in it.path.subpaths.iter().enumerate() {
+ for (ai, a) in sp.anchors.iter().enumerate() {
+ if ((m * a.p) - p).hypot() <= tol {
+ return Some((id.0, si, ai, None));
+ }
+ if a.has_in() && ((m * a.h_in) - p).hypot() <= tol {
+ return Some((id.0, si, ai, Some("in")));
+ }
+ if a.has_out() && ((m * a.h_out) - p).hypot() <= tol {
+ return Some((id.0, si, ai, Some("out")));
+ }
+ }
+ }
+ }
+ None
}
pub struct SelectionTool {
@@ -137,6 +161,12 @@ impl Tool for SelectionTool {
vec![]
}
PointerKind::Down => {
+ if self.direct
+ && let Some((id, si, ai, handle)) = anchor_at(cx, p)
+ {
+ self.drag = Drag::Anchor { id, si, ai, handle, start: p };
+ return vec![Action::Begin(if handle.is_some() { "Move Direction Handle".into() } else { "Move Anchor".into() })];
+ }
if let Some(h) = handle_at(cx, p).filter(|_| !self.direct)
&& let (Some(b), Some(first)) = (cx.selection_bounds(), cx.selection.items.first())
&& let Some(loc) = cx.doc.find(*first)
@@ -209,12 +239,20 @@ impl Tool for SelectionTool {
self.drag = Drag::Marquee { start, cur: p };
vec![]
}
+ Drag::Anchor { id, si, ai, handle, start } => {
+ let d = p - start;
+ let mut params = json!({"id": id, "anchors": [[si, ai]], "dx": d.x, "dy": d.y});
+ if let Some(h) = handle {
+ params["handle"] = json!(h);
+ }
+ vec![Action::Preview("path.moveAnchors".into(), params)]
+ }
Drag::None => vec![],
},
PointerKind::Up => {
let d = std::mem::replace(&mut self.drag, Drag::None);
match d {
- Drag::Move { .. } | Drag::Resize { .. } => vec![Action::Commit],
+ Drag::Move { .. } | Drag::Resize { .. } | Drag::Anchor { .. } => vec![Action::Commit],
Drag::Marquee { start, cur } => {
let r = Rect::from_points(start, cur);
// Items whose bounds intersect the marquee.
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index b9693f4ac..996972e1d 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -452,8 +452,32 @@ fn draw_selection(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Docum
painter.rect_stroke(gb, 0.0, Stroke::new(1.0, Color32::from_rgb(196, 111, 43)), StrokeKind::Middle);
}
}
+ let direct = matches!(app.session.tool_id(), "directSelection" | "pen");
+ if direct {
+ for id in &sel.items {
+ let (Some(it), Some((a, _))) = (doc.item(*id), item_canvas_xf(doc, layout, *id)) else { continue };
+ let m = a * it.xf;
+ let col = layer_color(doc, it);
+ for sp in &it.path.subpaths {
+ for an in &sp.anchors {
+ let p = xf.to_screen(m * an.p);
+ for (h, has) in [(an.h_in, an.has_in()), (an.h_out, an.has_out())] {
+ if has {
+ let hp = xf.to_screen(m * h);
+ painter.line_segment([p, hp], Stroke::new(1.0, col));
+ painter.circle_filled(hp, 2.5, col);
+ }
+ }
+ let r = Rect::from_center_size(p, vec2(5.0, 5.0));
+ painter.rect_filled(r, 0.0, Color32::WHITE);
+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, col), StrokeKind::Inside);
+ }
+ }
+ }
+ }
if let Some(u) = union
&& sel.text.is_none()
+ && !direct
{
if sel.items.len() > 1 {
painter.rect_stroke(u, 0.0, Stroke::new(1.0, color), StrokeKind::Middle);