Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Align and distribute shapes, in the editor and with klad align

Indicode BVd34496b7101b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b552735..05f4bf7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@
The first builds, and klad's licences.
- A new icon, painted in klad: a K in two brush strokes.
+- Align and distribute shapes. With **V**, shift click adds a shape to the selection and a loop dragged on a vector layer takes the shapes inside; several shapes move, scale, turn, flip, duplicate and delete together. The bar under them lines up their left, right, top or bottom edges or their centres and spaces three or more evenly; one shape lines up on the canvas (**Edit > Align**). From the command line: `klad align art.klad n3 n4 n7 --y middle --spread x`, with `--to canvas` or `--to <shape>` and `--gap`.
- Fixed exports of a clip moved by keys (a layer, group or shape keyed between frames, with no drawing per frame): `klad export --sheet`, `--frames` and `--godot` wrote the first pose for every frame, and `klad render --sheet` showed them as held. Each pose is now its own picture.
- A second agent skill, `klad skill drawing`: the craft of drawing and painting (planning a picture, light on form, values, edges, colour, materials, line, a painting method and a critique checklist), under the MIT licence like the first.
- Drawings are `.klad` folders in a fresh format, `klad/6` (drawings from the first builds open as they are, except their bones, which are dropped). Drawings from before (`.draw` folders) do not open and are not converted.
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs
index 6cc3f1f..2d8807f 100644
--- a/crates/app/src/commands.rs
+++ b/crates/app/src/commands.rs
@@ -47,6 +47,14 @@ pub enum Cmd {
Detach,
FlipH,
FlipV,
+ AlignLeft,
+ AlignCentre,
+ AlignRight,
+ AlignTop,
+ AlignMiddle,
+ AlignBottom,
+ DistributeAcross,
+ DistributeDown,
Corner,
Smooth,
Simplify,
@@ -498,7 +506,7 @@ use Repeat as R;
use Trigger as T;
impl Cmd {
- pub const ALL: [Cmd; 171] = [
+ pub const ALL: [Cmd; 179] = [
Cmd::Brush,
Cmd::Eraser,
Cmd::Fill,
@@ -542,6 +550,14 @@ impl Cmd {
Cmd::Detach,
Cmd::FlipH,
Cmd::FlipV,
+ Cmd::AlignLeft,
+ Cmd::AlignCentre,
+ Cmd::AlignRight,
+ Cmd::AlignTop,
+ Cmd::AlignMiddle,
+ Cmd::AlignBottom,
+ Cmd::DistributeAcross,
+ Cmd::DistributeDown,
Cmd::Corner,
Cmd::Smooth,
Cmd::Simplify,
@@ -1043,6 +1059,78 @@ impl Cmd {
R::No,
"free what is attached to the selected strokes: it stays where it is and acts on whatever is under it",
),
+ Cmd::AlignLeft => spec(
+ "edit.align-left",
+ "align left edges",
+ icon::ALIGN_LEFT,
+ G::Edit,
+ T::None,
+ R::No,
+ "line the selected shapes up on their leftmost edge; one shape goes to the left edge of the canvas",
+ ),
+ Cmd::AlignCentre => spec(
+ "edit.align-centre",
+ "align horizontal centres",
+ icon::ALIGN_CENTRE_ACROSS,
+ G::Edit,
+ T::None,
+ R::No,
+ "put the selected shapes on one vertical line through their middle; one shape goes to the middle of the canvas",
+ ),
+ Cmd::AlignRight => spec(
+ "edit.align-right",
+ "align right edges",
+ icon::ALIGN_RIGHT,
+ G::Edit,
+ T::None,
+ R::No,
+ "line the selected shapes up on their rightmost edge; one shape goes to the right edge of the canvas",
+ ),
+ Cmd::AlignTop => spec(
+ "edit.align-top",
+ "align top edges",
+ icon::ALIGN_TOP,
+ G::Edit,
+ T::None,
+ R::No,
+ "line the selected shapes up on their topmost edge; one shape goes to the top of the canvas",
+ ),
+ Cmd::AlignMiddle => spec(
+ "edit.align-middle",
+ "align vertical centres",
+ icon::ALIGN_CENTRE_DOWN,
+ G::Edit,
+ T::None,
+ R::No,
+ "put the selected shapes on one horizontal line through their middle; one shape goes to the middle of the canvas",
+ ),
+ Cmd::AlignBottom => spec(
+ "edit.align-bottom",
+ "align bottom edges",
+ icon::ALIGN_BOTTOM,
+ G::Edit,
+ T::None,
+ R::No,
+ "line the selected shapes up on their lowest edge; one shape goes to the bottom of the canvas",
+ ),
+ Cmd::DistributeAcross => spec(
+ "edit.distribute-across",
+ "distribute across",
+ icon::DISTRIBUTE_ACROSS,
+ G::Edit,
+ T::None,
+ R::No,
+ "keep the leftmost and rightmost of the selected shapes and make the gaps between them equal",
+ ),
+ Cmd::DistributeDown => spec(
+ "edit.distribute-down",
+ "distribute down",
+ icon::DISTRIBUTE_DOWN,
+ G::Edit,
+ T::None,
+ R::No,
+ "keep the top and bottom of the selected shapes and make the gaps between them equal",
+ ),
Cmd::FlipH => spec(
"edit.flip-h",
"flip the selection left-right",
@@ -2255,6 +2343,14 @@ impl Cmd {
Cmd::Thicker => "Thicker",
Cmd::AttachedOnly => "Attached only",
Cmd::Detach => "Detach",
+ Cmd::AlignLeft => "Left edges",
+ Cmd::AlignCentre => "Horizontal centres",
+ Cmd::AlignRight => "Right edges",
+ Cmd::AlignTop => "Top edges",
+ Cmd::AlignMiddle => "Vertical centres",
+ Cmd::AlignBottom => "Bottom edges",
+ Cmd::DistributeAcross => "Distribute across",
+ Cmd::DistributeDown => "Distribute down",
Cmd::FlipH => "Flip horizontal",
Cmd::FlipV => "Flip vertical",
Cmd::Corner => "Corner",
@@ -2466,6 +2562,21 @@ pub const MENUS: [Menu; 9] = [
Run(Cmd::NudgeDown),
],
),
+ Sub(
+ "Align",
+ &[
+ Run(Cmd::AlignLeft),
+ Run(Cmd::AlignCentre),
+ Run(Cmd::AlignRight),
+ Line,
+ Run(Cmd::AlignTop),
+ Run(Cmd::AlignMiddle),
+ Run(Cmd::AlignBottom),
+ Line,
+ Run(Cmd::DistributeAcross),
+ Run(Cmd::DistributeDown),
+ ],
+ ),
Sub(
"Strokes",
&[
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index 431e156..ca8d34d 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -313,6 +313,19 @@ fn edge(corners: &[Vec2; 4], side: usize) -> Vec2 {
(corners[side] + corners[(side + 1) % 4]) / 2.0
}
+fn transform_props(t: &klad_core::doc::Transform) -> Map<String, Value> {
+ [
+ ("transform.x", json!(t.x)),
+ ("transform.y", json!(t.y)),
+ ("transform.rotate", json!(t.rotate)),
+ ("transform.sx", json!(t.sx)),
+ ("transform.sy", json!(t.sy)),
+ ]
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v))
+ .collect()
+}
+
struct Drag {
grab: Grab,
node: String,
@@ -670,6 +683,7 @@ pub(crate) struct Editor {
keys_busy: bool,
key_filter: String,
selection: Option<String>,
+ group: Vec<String>,
drag: Option<Drag>,
edits: BTreeMap<String, f32>,
texts: BTreeMap<String, String>,
@@ -682,6 +696,7 @@ pub(crate) struct Editor {
shared: (Option<String>, Vec<String>, u32),
ctx: egui::Context,
sel_box: Option<(String, u64, [Vec2; 4])>,
+ group_boxes: Vec<[Vec2; 4]>,
preview: Option<PreviewState>,
outbox: Arc<Mutex<Outbox>>,
zoom_px: f32,
@@ -850,6 +865,7 @@ impl Editor {
keys_busy: false,
key_filter: String::new(),
selection: None,
+ group: Vec::new(),
drag: None,
edits: BTreeMap::new(),
texts: BTreeMap::new(),
@@ -862,6 +878,7 @@ impl Editor {
shared: (None, Vec::new(), 0),
ctx,
sel_box: None,
+ group_boxes: Vec::new(),
preview: None,
outbox: Arc::default(),
zoom_px: 1.0,
@@ -968,7 +985,7 @@ impl Editor {
fn share_selection(&mut self) {
let items: Vec<String> = self
- .selection
+ .shapes()
.iter()
.chain(self.direct.as_ref().map(|d| &d.node))
.cloned()
@@ -1038,8 +1055,26 @@ impl Editor {
Ok(())
}
+ pub(super) fn shapes(&self) -> Vec<String> {
+ match &self.selection {
+ Some(id) if self.group.len() > 1 && self.group.contains(id) => self.group.clone(),
+ Some(id) => vec![id.clone()],
+ None => Vec::new(),
+ }
+ }
+
+ pub(super) fn select_shapes(&mut self, ids: Vec<String>) {
+ self.selection = ids.last().cloned();
+ self.group = if ids.len() > 1 { ids } else { Vec::new() };
+ self.refresh_box();
+ }
+
fn forget_missing_selection(&mut self) {
let doc = &self.scene.bundle.doc;
+ self.group.retain(|id| matches!(doc.item(id), Some(Item::Node(..))));
+ if self.group.len() < 2 || !self.selection.as_ref().is_some_and(|id| self.group.contains(id)) {
+ self.group.clear();
+ }
if self
.selection
.as_ref()
@@ -1181,28 +1216,44 @@ impl Editor {
fn refresh_box(&mut self) {
let rev = self.scene.bundle.doc.rev;
- let Some(id) = self.selection.clone() else {
+ let ids = self.shapes();
+ if ids.is_empty() {
self.sel_box = None;
+ self.group_boxes.clear();
return;
- };
- if self.sel_box.as_ref().is_some_and(|(s, r, _)| *s == id && *r == rev) {
+ }
+ let key = ids.join(" ");
+ if self.sel_box.as_ref().is_some_and(|(s, r, _)| *s == key && *r == rev) {
return;
}
- self.sel_box = overlay::node_world_box(&self.scene.bundle.doc, &id)
- .ok()
- .flatten()
- .map(|[x, y, w, h]| {
- (
- id,
- rev,
- [vec2(x, y), vec2(x + w, y), vec2(x + w, y + h), vec2(x, y + h)],
- )
- });
+ let boxes: Vec<[f32; 4]> = ids
+ .iter()
+ .filter_map(|id| overlay::node_world_box(&self.scene.bundle.doc, id).ok().flatten())
+ .collect();
+ let corners = |[x, y, w, h]: [f32; 4]| [vec2(x, y), vec2(x + w, y), vec2(x + w, y + h), vec2(x, y + h)];
+ self.group_boxes = match boxes.len() {
+ 0 | 1 => Vec::new(),
+ _ => boxes.iter().map(|b| corners(*b)).collect(),
+ };
+ self.sel_box = boxes
+ .iter()
+ .copied()
+ .reduce(|a, b| {
+ let (x, y) = (a[0].min(b[0]), a[1].min(b[1]));
+ [
+ x,
+ y,
+ (a[0] + a[2]).max(b[0] + b[2]) - x,
+ (a[1] + a[3]).max(b[1] + b[3]) - y,
+ ]
+ })
+ .map(|all| (key, rev, corners(all)));
}
fn selection_corners(&self) -> Option<(String, [Vec2; 4])> {
- let (id, _, corners) = self.sel_box.as_ref()?;
- (self.selection.as_ref() == Some(id)).then(|| (id.clone(), *corners))
+ let (key, _, corners) = self.sel_box.as_ref()?;
+ let id = self.selection.clone()?;
+ (self.shapes().join(" ") == *key).then_some((id, *corners))
}
fn refresh_cut(&mut self) {
@@ -1416,29 +1467,30 @@ impl Editor {
}
fn node_ops(&self, drag: &Drag) -> Result<Option<Vec<Op>>> {
- let node = match self.scene.bundle.doc.item(&drag.node) {
- Some(Item::Node(_, _, node)) => node.clone(),
- _ => return Ok(None),
+ let ids = match self.shapes() {
+ all if all.len() > 1 && all.contains(&drag.node) => all,
+ _ => vec![drag.node.clone()],
};
+ let together = ids.len() > 1;
let affine = drag.affine();
- let t = match drag.stretch() {
- Some((axis, _, k)) => lift::stretched(&node, affine, axis, k)?,
- None => lift::committed(&node, affine, drag.scale(), drag.angle().to_degrees())?,
- };
- let props: Map<String, Value> = [
- ("transform.x", json!(t.x)),
- ("transform.y", json!(t.y)),
- ("transform.rotate", json!(t.rotate)),
- ("transform.sx", json!(t.sx)),
- ("transform.sy", json!(t.sy)),
- ]
- .into_iter()
- .map(|(k, v)| (k.to_string(), v))
- .collect();
- Ok(Some(vec![Op::Set {
- id: drag.node.clone(),
- props,
- }]))
+ let ops = ids
+ .into_iter()
+ .filter_map(|id| match self.scene.bundle.doc.item(&id) {
+ Some(Item::Node(_, _, node)) => Some((id, node.clone())),
+ _ => None,
+ })
+ .map(|(id, node)| {
+ let t = match drag.stretch().filter(|_| !together) {
+ Some((axis, _, k)) => lift::stretched(&node, affine, axis, k)?,
+ None => lift::committed(&node, affine, drag.scale(), drag.angle().to_degrees())?,
+ };
+ Ok(Op::Set {
+ id,
+ props: transform_props(&t),
+ })
+ })
+ .collect::<Result<Vec<Op>>>()?;
+ Ok((!ops.is_empty()).then_some(ops))
}
fn drag_ops(&self) -> Option<Vec<Op>> {
@@ -1664,6 +1716,7 @@ impl Editor {
fn edges(&self) -> bool {
match self.tool {
_ if self.on_marks() => true,
+ Tool::Select if self.group.len() > 1 => false,
Tool::Select => self
.selection
.as_ref()
@@ -1754,10 +1807,50 @@ impl Editor {
_ => hits.first(),
};
self.selection = next.map(|(n, _)| n.clone());
+ self.group.clear();
self.refresh_box();
Ok(())
}
+ fn toggle_shape(&mut self, at: Vec2) -> Result<bool> {
+ let Some((hit, _)) = self.shape_hits(at)?.into_iter().next() else {
+ return Ok(false);
+ };
+ let held = self.shapes();
+ let next: Vec<String> = match held.contains(&hit) {
+ true => held.into_iter().filter(|id| *id != hit).collect(),
+ false => held.into_iter().chain([hit]).collect(),
+ };
+ self.picked = None;
+ self.select_shapes(next);
+ Ok(true)
+ }
+
+ fn lasso_shapes(&mut self) -> Result<bool> {
+ let vector = self
+ .scene
+ .active_layer()
+ .is_some_and(|l| l.kind() == klad_core::doc::Kind::Vector);
+ let Some(polygon) = self
+ .lasso
+ .as_ref()
+ .filter(|l| vector && l.far && l.points.len() >= 3)
+ .map(|l| l.points.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>())
+ else {
+ return Ok(false);
+ };
+ let active = self.scene.active_id();
+ let found: Vec<String> = overlay::shapes_inside(&self.scene.bundle.doc, self.scene.frame, &polygon)?
+ .into_iter()
+ .filter(|(_, layer)| self.settings.pick_all_layers || active.as_deref() == Some(layer.as_str()))
+ .map(|(node, _)| node)
+ .collect();
+ self.lasso = None;
+ self.picked = None;
+ self.select_shapes(found);
+ Ok(true)
+ }
+
fn finish_drag(&mut self) -> Result<()> {
let Some(drag) = self.drag.take() else {
return Ok(());
@@ -1813,6 +1906,9 @@ impl Editor {
(_, None) => true,
(None, Some(_)) => false,
};
+ if !stroke_first && self.modifiers.shift && self.selection.is_some() && self.toggle_shape(c)? {
+ return Ok(());
+ }
if !stroke_first {
self.select_at(c, false)?;
if let Some((id, corners)) = self.selection_corners() {
@@ -2905,6 +3001,11 @@ impl Editor {
}
(Tool::Brush, Phase::Up) => self.finish()?,
(Tool::Select, Phase::Down) => match self.grab_at(view, rect, e.pos) {
+ Some((_, Grab::Move, _))
+ if self.modifiers.shift
+ && self.selection.is_some()
+ && !self.on_marks()
+ && self.toggle_shape(c)? => {}
Some((id, grab, corners)) => self.start_drag(id, grab, corners, c, false),
None => {
self.end_shift();
@@ -2917,6 +3018,7 @@ impl Editor {
}
self.copy_for_drag()?;
}
+ (Tool::Select, Phase::Up) if self.lasso.is_some() && self.lasso_shapes()? => {}
(Tool::Select, Phase::Up) if self.lasso.is_some() => match self.scene.active_cel() {
Some(_) => self.finish_pick()?,
None => {
@@ -3473,6 +3575,12 @@ impl Editor {
self.decorate_pen(&painter, path, hover, view, rect, accent, dark);
}
if let Some((_, corners)) = self.handles() {
+ if self.drag.is_none() && self.tool == Tool::Select && !self.on_marks() {
+ self.group_boxes.iter().for_each(|member| {
+ let outline: Vec<Pos2> = member.iter().map(|c| self.screen(view, rect, *c)).collect();
+ painter.add(egui::Shape::closed_line(outline, egui::Stroke::new(1.0, accent)));
+ });
+ }
let corners = match &self.drag {
Some(drag) => drag.preview(),
None => corners,
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index 27c37ec..704ee1f 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -17,6 +17,7 @@ use klad_core::ops::{ClipEdit, Op, PaletteEdit};
use klad_core::pathedit::PathEdit;
use klad_core::retime::Retime;
use klad_core::timing::OPEN;
+use klad_render::align::{Across, Axis, Down};
use serde_json::{Map, json};
use std::collections::BTreeSet;
@@ -136,6 +137,21 @@ impl Editor {
_ => Some("select strokes (S) or a shape (V) first".to_string()),
}
}
+ Cmd::AlignLeft
+ | Cmd::AlignCentre
+ | Cmd::AlignRight
+ | Cmd::AlignTop
+ | Cmd::AlignMiddle
+ | Cmd::AlignBottom => match self.selected() {
+ Some(Selected::Shape(_)) => editing,
+ _ => Some("select a shape with V first; shift click adds more".to_string()),
+ },
+ Cmd::DistributeAcross | Cmd::DistributeDown => match self.selected() {
+ Some(Selected::Shape(_)) if self.shapes().len() >= 3 => editing,
+ _ => {
+ Some("select three shapes or more with V: shift click adds one, a lasso takes several".to_string())
+ }
+ },
Cmd::NudgeLeft | Cmd::NudgeRight | Cmd::NudgeUp | Cmd::NudgeDown => match self.selected() {
Some(_) => editing.or(self
.path_commit
@@ -554,8 +570,11 @@ impl Editor {
self.commit_path(PathEdit::Remove { points })?;
}
_ => {
- if let Some(id) = self.selection.take() {
- self.apply(vec![Op::Remove { ids: vec![id] }])?;
+ let ids = self.shapes();
+ self.selection = None;
+ self.group.clear();
+ if !ids.is_empty() {
+ self.apply(vec![Op::Remove { ids }])?;
}
}
},
@@ -566,6 +585,7 @@ impl Editor {
Tool::Direct => self.direct = None,
Tool::Select => {
self.selection = None;
+ self.group.clear();
self.picked = None;
}
_ => self.selection = None,
@@ -603,6 +623,14 @@ impl Editor {
Cmd::TurnLeft90 => self.turn(-90.0)?,
Cmd::TurnRight90 => self.turn(90.0)?,
Cmd::DuplicateInPlace => self.duplicate_in_place()?,
+ Cmd::AlignLeft => self.align(Some(Across::Left), None, None)?,
+ Cmd::AlignCentre => self.align(Some(Across::Centre), None, None)?,
+ Cmd::AlignRight => self.align(Some(Across::Right), None, None)?,
+ Cmd::AlignTop => self.align(None, Some(Down::Top), None)?,
+ Cmd::AlignMiddle => self.align(None, Some(Down::Middle), None)?,
+ Cmd::AlignBottom => self.align(None, Some(Down::Bottom), None)?,
+ Cmd::DistributeAcross => self.align(None, None, Some(Axis::X))?,
+ Cmd::DistributeDown => self.align(None, None, Some(Axis::Y))?,
Cmd::NudgeLeft => self.nudge(-1.0, 0.0)?,
Cmd::NudgeRight => self.nudge(1.0, 0.0)?,
Cmd::NudgeUp => self.nudge(0.0, -1.0)?,
diff --git a/crates/app/src/editor/selection.rs b/crates/app/src/editor/selection.rs
index 766f750..ce22cec 100644
--- a/crates/app/src/editor/selection.rs
+++ b/crates/app/src/editor/selection.rs
@@ -1,5 +1,6 @@
-use super::{Editor, Tool};
+use super::{Editor, Tool, transform_props};
use crate::commands::Cmd;
+use crate::lift;
use crate::messages::Tone;
use crate::pen::PenEvent;
use crate::theme;
@@ -9,6 +10,7 @@ use klad_core::doc::Item;
use klad_core::markedit::{LassoAction, MarkTransform};
use klad_core::ops::{Op, Place};
use klad_core::pathedit::PathEdit;
+use klad_render::align::{Across, Axis, Down, Plan, To};
use serde_json::{Map, Value, json};
#[derive(Default)]
@@ -97,6 +99,73 @@ impl Editor {
}
}
+ fn group_nodes(&self) -> Vec<(String, klad_core::doc::Node)> {
+ self.shapes()
+ .into_iter()
+ .filter_map(|id| match self.scene.bundle.doc.item(&id) {
+ Some(Item::Node(_, _, node)) => Some((id, node.clone())),
+ _ => None,
+ })
+ .collect()
+ }
+
+ fn group_middle(&self) -> Option<egui::Vec2> {
+ self.selection_corners().map(|(_, c)| (c[0] + c[2]) / 2.0)
+ }
+
+ fn move_group(
+ &mut self,
+ affine: [f32; 6],
+ degrees: f32,
+ after: impl Fn(&mut klad_core::doc::Transform),
+ ) -> Result<()> {
+ let ops = self
+ .group_nodes()
+ .into_iter()
+ .map(|(id, node)| {
+ let mut t = lift::committed(&node, affine, 1.0, degrees)?;
+ after(&mut t);
+ Ok(Op::Set {
+ id,
+ props: transform_props(&t),
+ })
+ })
+ .collect::<Result<Vec<Op>>>()?;
+ self.apply(ops)
+ }
+
+ pub(super) fn align(&mut self, x: Option<Across>, y: Option<Down>, spread: Option<Axis>) -> Result<()> {
+ let ids = self.shapes();
+ let plan = Plan {
+ x,
+ y,
+ spread,
+ gap: None,
+ to: if ids.len() == 1 { To::Canvas } else { To::Selection },
+ };
+ match klad_render::align::ops(&self.scene.bundle.doc, &ids, &plan) {
+ Ok(ops) if ops.is_empty() => {
+ self.say(Tone::Info, "already lined up: nothing moved");
+ Ok(())
+ }
+ Ok(ops) => {
+ let moved = ops.len();
+ self.apply(ops)?;
+ let what = match (spread, ids.len()) {
+ (Some(_), _) => "spaced evenly".to_string(),
+ (None, 1) => "lined up on the canvas".to_string(),
+ (None, n) => format!("{n} shapes lined up"),
+ };
+ self.say(Tone::Done, format!("{what}, {moved} moved"));
+ Ok(())
+ }
+ Err(e) => {
+ self.say(Tone::Refused, format!("{e:#}"));
+ Ok(())
+ }
+ }
+ }
+
pub(super) fn nudge(&mut self, dx: f32, dy: f32) -> Result<()> {
let step = if self.key_shift { 10.0 } else { 1.0 };
let (dx, dy) = (dx * step, dy * step);
@@ -106,6 +175,9 @@ impl Editor {
y: dy,
..Default::default()
})),
+ Some(Selected::Shape(_)) if self.group.len() > 1 => {
+ self.move_group([1.0, 0.0, 0.0, 1.0, dx, dy], 0.0, |_| {})
+ }
Some(Selected::Shape(id)) => {
let Some(t) = self.node_transform(&id) else {
return Ok(());
@@ -136,6 +208,21 @@ impl Editor {
..Default::default()
}))
}
+ Some(Selected::Shape(_)) if self.group.len() > 1 => {
+ let Some(c) = self.group_middle() else {
+ return Ok(());
+ };
+ let (sin, cos) = degrees.to_radians().sin_cos();
+ let affine = [
+ cos,
+ -sin,
+ sin,
+ cos,
+ c.x - c.x * cos + c.y * sin,
+ c.y - c.x * sin - c.y * cos,
+ ];
+ self.move_group(affine, degrees, |_| {})
+ }
Some(Selected::Shape(id)) => {
let Some(t) = self.node_transform(&id) else {
return Ok(());
@@ -152,6 +239,22 @@ impl Editor {
true => self.flip_picked(-1.0, 1.0),
false => self.flip_picked(1.0, -1.0),
},
+ Some(Selected::Shape(_)) if self.group.len() > 1 => {
+ let Some(c) = self.group_middle() else {
+ return Ok(());
+ };
+ let affine = match horizontal {
+ true => [-1.0, 0.0, 0.0, 1.0, 2.0 * c.x, 0.0],
+ false => [1.0, 0.0, 0.0, -1.0, 0.0, 2.0 * c.y],
+ };
+ self.move_group(affine, 0.0, |t| {
+ match horizontal {
+ true => t.sx = -t.sx,
+ false => t.sy = -t.sy,
+ }
+ t.rotate = -t.rotate;
+ })
+ }
Some(Selected::Shape(id)) => {
let Some(t) = self.node_transform(&id) else {
return Ok(());
@@ -172,26 +275,33 @@ impl Editor {
Some(copied) => self.paste_copied(copied, "duplicated"),
None => Ok(()),
},
- Some(Selected::Shape(id)) => {
- let Some(Item::Node(_, _, node)) = self.scene.bundle.doc.item(&id) else {
- return Ok(());
- };
- let mut value = serde_json::to_value(node)?;
- strip_ids(&mut value);
- let op = Op::AddNode {
- node: value,
- place: Place {
- above: Some(id.clone()),
- frame: Some(self.scene.frame),
- ..Place::default()
- },
- };
- let applied = self.scene.apply_with(&[op], &self.brushes);
+ Some(Selected::Shape(_)) => {
+ let nodes = self.group_nodes();
+ let ops = nodes
+ .iter()
+ .map(|(id, node)| {
+ let mut value = serde_json::to_value(node)?;
+ strip_ids(&mut value);
+ Ok(Op::AddNode {
+ node: value,
+ place: Place {
+ above: Some(id.clone()),
+ frame: Some(self.scene.frame),
+ ..Place::default()
+ },
+ })
+ })
+ .collect::<Result<Vec<Op>>>()?;
+ let applied = self.scene.apply_with(&ops, &self.brushes);
match applied {
Ok((dirty, applied)) => {
self.dirty.extend(dirty);
- self.selection = applied.added.first().cloned();
- self.say(Tone::Done, format!("duplicated {id} in place"));
+ self.select_shapes(applied.added.clone());
+ let what = match nodes.as_slice() {
+ [(id, _)] => id.clone(),
+ many => format!("{} shapes", many.len()),
+ };
+ self.say(Tone::Done, format!("duplicated {what} in place"));
Ok(())
}
Err(e) => {
@@ -248,6 +358,19 @@ impl Editor {
Cmd::Delete,
Cmd::Deselect,
],
+ Selected::Shape(_) if self.group.len() > 1 => vec![
+ Cmd::AlignLeft,
+ Cmd::AlignCentre,
+ Cmd::AlignRight,
+ Cmd::AlignTop,
+ Cmd::AlignMiddle,
+ Cmd::AlignBottom,
+ Cmd::DistributeAcross,
+ Cmd::DistributeDown,
+ Cmd::DuplicateInPlace,
+ Cmd::Delete,
+ Cmd::Deselect,
+ ],
Selected::Shape(_) => vec![
Cmd::FlipH,
Cmd::FlipV,
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index dd59e7f..98570a3 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -1340,6 +1340,117 @@ fn strokes_and_copies_dragged_leave_the_committed_picture_on_the_canvas() {
let _ = std::fs::remove_dir_all(&path);
}
+#[test]
+fn several_shapes_select_with_shift_or_a_lasso_move_together_align_and_distribute() {
+ let path = sample("align");
+ {
+ let mut bundle = Bundle::open(&path).unwrap();
+ let shapes = bundle.doc.find_layer("shapes").unwrap().id.clone();
+ let rect = |x: u32, y: u32, w: u32| {
+ format!(
+ r##"{{"op":"add","node":{{"type":"rect","x":{x},"y":{y},"w":{w},"h":40,"fill":"#3060a0"}},"in":"{shapes}","frame":0}}"##
+ )
+ };
+ bundle
+ .apply(&parse_lines(&format!("{}\n{}", rect(300, 30, 60), rect(420, 300, 40))).unwrap())
+ .unwrap();
+ }
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ activate(&mut h, "shapes");
+ h.state_mut().tool = Tool::Select;
+ let ids: Vec<String> = h.state().scene.bundle.doc.find_layer("shapes").unwrap().cels()[0]
+ .nodes
+ .iter()
+ .map(|n| n.id.clone())
+ .collect();
+ let boxes = |h: &Harness<'static, Editor>| -> Vec<[f32; 4]> {
+ ids.iter()
+ .map(|id| {
+ klad_render::overlay::node_world_box(&h.state().scene.bundle.doc, id)
+ .unwrap()
+ .unwrap()
+ })
+ .collect()
+ };
+ assert_eq!(boxes(&h).iter().map(|b| b[0]).collect::<Vec<_>>(), [20.0, 300.0, 420.0]);
+ let at = on_screen(&h, 120.0, 30.0);
+ click_with(&mut h, at, Modifiers::NONE);
+ assert_eq!(h.state().shapes(), ids[..1], "a click takes one shape");
+ assert!(
+ h.state().can_run(Cmd::DistributeAcross).is_some(),
+ "distributing needs three"
+ );
+ let at = on_screen(&h, 330.0, 50.0);
+ click_with(&mut h, at, Modifiers::SHIFT);
+ let at = on_screen(&h, 440.0, 320.0);
+ click_with(&mut h, at, Modifiers::SHIFT);
+ assert_eq!(h.state().shapes(), ids, "shift click adds each shape");
+ assert!(
+ h.query_all(By::new().label_contains(crate::theme::icon::ALIGN_TOP))
+ .count()
+ > 0,
+ "the bar under several shapes aligns them"
+ );
+ let rev = h.state().scene.bundle.doc.rev;
+ h.state_mut().invoke(Cmd::AlignTop).unwrap();
+ h.run_steps(2);
+ assert_eq!(boxes(&h).iter().map(|b| b[1]).collect::<Vec<_>>(), [20.0, 20.0, 20.0]);
+ assert_eq!(h.state().scene.bundle.doc.rev, rev + 1, "one step for the three");
+ h.state_mut().invoke(Cmd::DistributeAcross).unwrap();
+ h.run_steps(2);
+ assert_eq!(boxes(&h).iter().map(|b| b[0]).collect::<Vec<_>>(), [20.0, 250.0, 420.0]);
+ let from = on_screen(&h, 120.0, 30.0);
+ let to = on_screen(&h, 150.0, 30.0);
+ drag(&mut h, from, to);
+ settle(&mut h, |ed| ed.drag.is_none() && ed.preview.is_none());
+ let moved = boxes(&h);
+ [50.0, 280.0, 450.0].iter().zip(&moved).for_each(|(want, b)| {
+ assert!((b[0] - want).abs() < 1.0, "the three moved together: {moved:?}");
+ });
+ assert_eq!(h.state().shapes(), ids, "and stay selected");
+ let at = on_screen(&h, 470.0, 40.0);
+ click_with(&mut h, at, Modifiers::SHIFT);
+ assert_eq!(
+ h.state().shapes(),
+ ids[..2],
+ "shift click on a selected shape lets it go"
+ );
+ h.state_mut().invoke(Cmd::Deselect).unwrap();
+ h.run_steps(1);
+ assert!(h.state().shapes().is_empty());
+ let around =
+ [(262.0, 4.0), (505.0, 4.0), (505.0, 75.0), (262.0, 75.0), (262.0, 10.0)].map(|(x, y)| on_screen(&h, x, y));
+ h.hover_at(around[0]);
+ h.run_steps(1);
+ h.drag_at(around[0]);
+ h.run_steps(1);
+ around[1..].iter().for_each(|p| {
+ h.hover_at(*p);
+ h.run_steps(1);
+ });
+ h.drop_at(around[4]);
+ h.run_steps(2);
+ assert_eq!(
+ h.state().shapes(),
+ ids[1..],
+ "a lasso on a shapes layer takes the shapes inside"
+ );
+ h.state_mut().invoke(Cmd::AlignLeft).unwrap();
+ h.run_steps(2);
+ let lined = boxes(&h);
+ assert_eq!(
+ lined[1][0], lined[2][0],
+ "two shapes line up on the left one: {lined:?}"
+ );
+ h.key_press(Key::Delete);
+ h.run_steps(2);
+ let left = h.state().scene.bundle.doc.find_layer("shapes").unwrap().cels()[0]
+ .nodes
+ .len();
+ assert_eq!(left, 1, "Delete removes every selected shape");
+ let _ = std::fs::remove_dir_all(&path);
+}
+
#[test]
fn a_tap_that_wobbles_selects_and_a_drag_past_three_points_moves() {
let path = sample("tap");
diff --git a/crates/app/src/theme.rs b/crates/app/src/theme.rs
index d4719b0..86ea9eb 100644
--- a/crates/app/src/theme.rs
+++ b/crates/app/src/theme.rs
@@ -60,6 +60,14 @@ pub mod icon {
pub const LASSO: &str = "\u{EDC6}";
pub const PALETTE: &str = "\u{E6C8}";
pub const FLIP_H: &str = "\u{ED6A}";
+ pub const ALIGN_LEFT: &str = "\u{E50E}";
+ pub const ALIGN_CENTRE_ACROSS: &str = "\u{E50A}";
+ pub const ALIGN_RIGHT: &str = "\u{E510}";
+ pub const ALIGN_TOP: &str = "\u{E512}";
+ pub const ALIGN_CENTRE_DOWN: &str = "\u{E50C}";
+ pub const ALIGN_BOTTOM: &str = "\u{E506}";
+ pub const DISTRIBUTE_ACROSS: &str = "\u{E534}";
+ pub const DISTRIBUTE_DOWN: &str = "\u{E536}";
pub const FLIP_V: &str = "\u{ED6C}";
pub const LAYERS: &str = "\u{E466}";
pub const EYE: &str = "\u{E220}";
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index dc31e0b..cc40c5c 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -540,6 +540,33 @@ enum Command {
#[command(flatten)]
flags: EditFlags,
},
+ #[command(
+ about = "Align shapes to each other, the canvas or one shape, or spread them evenly",
+ long_about = "Align shapes (the nodes of a vector layer) by their bounds on the canvas, or spread them evenly. --x lines up left edges, centres or right edges; --y lines up tops, middles or bottoms; both together stack them on one point. Without --to they line up on the bounds of the shapes together, so the outermost one stays; --to canvas uses the canvas (one shape is enough), --to <id> uses that shape, which stays where it is. --spread x or y keeps the two outer shapes and makes the gaps between neighbours equal; with --gap the first stays and each next one follows that many px after it. Aligning one way and spreading the other go together. A shape inside a group moves by the distance seen on the canvas. One history step.\n\n klad align art.klad n3 n4 n7 --y middle\n klad align art.klad n3 n4 n7 --y middle --spread x\n klad align art.klad n3 n4 n7 --spread x --gap 24\n klad align art.klad title --x centre --to canvas\n klad align art.klad n4 n7 --x left --to n3"
+ )]
+ Align {
+ bundle: PathBuf,
+ ids: Vec<String>,
+ #[arg(long, value_parser = ["left", "centre", "center", "right"], help = "Line up left edges, centres or right edges")]
+ x: Option<String>,
+ #[arg(long, value_parser = ["top", "middle", "bottom"], help = "Line up tops, middles or bottoms")]
+ y: Option<String>,
+ #[arg(long, value_parser = ["x", "y"], help = "Make the gaps between neighbours equal, across (x) or down (y)")]
+ spread: Option<String>,
+ #[arg(
+ long,
+ allow_hyphen_values = true,
+ help = "With --spread: px between neighbours, counted from the first"
+ )]
+ gap: Option<f32>,
+ #[arg(
+ long,
+ help = "What to line up on: canvas, or a shape id that stays put (default: the shapes together)"
+ )]
+ to: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
#[command(about = "Remove layers, cels or nodes")]
Rm {
bundle: PathBuf,
@@ -2376,6 +2403,44 @@ fn run() -> Result<()> {
}
agent::edit(&bundle, &[Op::Detach { ids }], &output(&flags, 0))?;
}
+ Command::Align {
+ bundle,
+ ids,
+ x,
+ y,
+ spread,
+ gap,
+ to,
+ flags,
+ } => {
+ use klad_render::align::{Across, Axis, Down, Plan, To};
+ let plan = Plan {
+ x: x.as_deref().map(|x| match x {
+ "left" => Across::Left,
+ "right" => Across::Right,
+ _ => Across::Centre,
+ }),
+ y: y.as_deref().map(|y| match y {
+ "top" => Down::Top,
+ "bottom" => Down::Bottom,
+ _ => Down::Middle,
+ }),
+ spread: spread
+ .as_deref()
+ .map(|axis| if axis == "x" { Axis::X } else { Axis::Y }),
+ gap,
+ to: match to.as_deref() {
+ None => To::Selection,
+ Some("canvas") => To::Canvas,
+ Some(id) => To::Shape(id.to_string()),
+ },
+ };
+ let ops = klad_render::align::ops(&Bundle::open(&bundle)?.doc, &ids, &plan)?;
+ match ops.is_empty() {
+ true => println!("already there: nothing moved"),
+ false => agent::edit(&bundle, &ops, &output(&flags, 0))?,
+ }
+ }
Command::Rm { bundle, ids, flags } => {
if ids.is_empty() {
return Err(anyhow!("give the ids to remove"));
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index a98de98..53ae071 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -448,6 +448,62 @@ fn a_merge_that_left_an_id_used_twice_is_repaired() {
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn shapes_align_spread_and_centre_on_the_canvas_from_the_command_line() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-align-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let bundle = dir.join("a.klad");
+ let path = bundle.to_str().unwrap();
+ let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ let draw = |args: &[&str]| {
+ let out = run(args);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).to_string()
+ };
+ draw(&["new", path, "--width", "400", "--height", "200", "--sketch"]);
+ let add = |x: &str, y: &str, w: &str| {
+ let made = draw(&[
+ "add",
+ path,
+ "rect",
+ "--in",
+ "l3",
+ &format!("x={x}"),
+ &format!("y={y}"),
+ &format!("w={w}"),
+ "h=20",
+ ]);
+ made.lines()
+ .find_map(|line| line.strip_prefix("added "))
+ .unwrap_or_else(|| panic!("an id in: {made}"))
+ .to_string()
+ };
+ let (a, b, c) = (add("10", "10", "20"), add("100", "40", "40"), add("50", "80", "10"));
+ let boxes = || {
+ [&a, &b, &c].map(|id| {
+ let node: serde_json::Value = serde_json::from_str(&draw(&["show", path, id])).unwrap();
+ [0, 1].map(|i| node["bounds"][i].as_f64().unwrap())
+ })
+ };
+ draw(&["align", path, &a, &b, &c, "--y", "top", "--spread", "x"]);
+ assert_eq!(boxes(), [[10.0, 10.0], [100.0, 10.0], [60.0, 10.0]]);
+ draw(&["align", path, &b, "--x", "centre", "--y", "middle", "--to", "canvas"]);
+ assert_eq!(boxes()[1], [180.0, 90.0]);
+ draw(&["align", path, &b, &c, "--x", "left", "--to", &a]);
+ assert_eq!(boxes().map(|at| at[0]), [10.0, 10.0, 10.0]);
+ assert!(draw(&["align", path, &b, &c, "--x", "left", "--to", &a]).contains("nothing moved"));
+ let log = draw(&["log", path]);
+ assert_eq!(
+ log.lines().filter(|line| line.contains("set n")).count(),
+ 3,
+ "one history step each: {log}"
+ );
+ let refused = run(&["align", path, &a, "--x", "left"]);
+ assert!(!refused.status.success());
+ assert!(String::from_utf8_lossy(&refused.stderr).contains("nothing to line up with"));
+ std::fs::remove_dir_all(&dir).unwrap();
+}
+
#[test]
fn recolour_moves_strokes_together_and_keeps_their_shades() {
let dir = std::env::temp_dir().join(format!("draw-binary-recolour-{}", std::process::id()));
diff --git a/crates/render/src/align.rs b/crates/render/src/align.rs
new file mode 100644
index 0000000..d8a1d1a
--- /dev/null
+++ b/crates/render/src/align.rs
@@ -0,0 +1,345 @@
+use crate::overlay;
+use anyhow::{Result, anyhow};
+use klad_core::doc::Document;
+use klad_core::ops::Op;
+use serde_json::{Map, json};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Across {
+ Left,
+ Centre,
+ Right,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Down {
+ Top,
+ Middle,
+ Bottom,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Axis {
+ X,
+ Y,
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub enum To {
+ #[default]
+ Selection,
+ Canvas,
+ Shape(String),
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Plan {
+ pub x: Option<Across>,
+ pub y: Option<Down>,
+ pub spread: Option<Axis>,
+ pub gap: Option<f32>,
+ pub to: To,
+}
+
+fn union(boxes: &[[f32; 4]]) -> [f32; 4] {
+ let low = |at: usize| boxes.iter().map(|b| b[at]).fold(f32::MAX, f32::min);
+ let high = |at: usize| boxes.iter().map(|b| b[at] + b[at + 2]).fold(f32::MIN, f32::max);
+ [low(0), low(1), high(0) - low(0), high(1) - low(1)]
+}
+
+fn spread(boxes: &[[f32; 4]], at: usize, gap: Option<f32>, within: Option<[f32; 4]>) -> Vec<f32> {
+ let mut order: Vec<usize> = (0..boxes.len()).collect();
+ order.sort_by(|a, b| boxes[*a][at].total_cmp(&boxes[*b][at]).then(a.cmp(b)));
+ let all = within.unwrap_or_else(|| union(boxes));
+ let sizes: f32 = boxes.iter().map(|b| b[at + 2]).sum();
+ let between = gap.unwrap_or_else(|| (all[at + 2] - sizes) / (boxes.len().max(2) - 1) as f32);
+ let start = match (gap, within) {
+ (Some(_), None) => boxes[order[0]][at],
+ _ => all[at],
+ };
+ let mut moves = vec![0.0; boxes.len()];
+ order.iter().fold(start, |edge, i| {
+ moves[*i] = edge - boxes[*i][at];
+ edge + boxes[*i][at + 2] + between
+ });
+ moves
+}
+
+pub fn moves(boxes: &[[f32; 4]], plan: &Plan, frame: Option<[f32; 4]>) -> Result<Vec<[f32; 2]>> {
+ if plan.x.is_none() && plan.y.is_none() && plan.spread.is_none() {
+ return Err(anyhow!(
+ "say how: --x left|centre|right, --y top|middle|bottom or --spread x|y"
+ ));
+ }
+ if boxes.is_empty() {
+ return Err(anyhow!("give the shapes to align, by id"));
+ }
+ if plan.gap.is_some() && plan.spread.is_none() {
+ return Err(anyhow!("--gap goes with --spread x or --spread y"));
+ }
+ let clash = match plan.spread {
+ Some(Axis::X) => plan.x.is_some(),
+ Some(Axis::Y) => plan.y.is_some(),
+ None => false,
+ };
+ if clash {
+ return Err(anyhow!(
+ "aligning and spreading along the same direction cancel out: align on one, spread on the other"
+ ));
+ }
+ let aligning = plan.x.is_some() || plan.y.is_some();
+ if aligning && frame.is_none() && boxes.len() < 2 {
+ return Err(anyhow!(
+ "one shape has nothing to line up with: give two or more, or align it to the canvas or to another shape"
+ ));
+ }
+ let least = if plan.gap.is_some() || frame.is_some() { 2 } else { 3 };
+ if plan.spread.is_some() && boxes.len() < least {
+ return Err(anyhow!(
+ "spreading needs {least} shapes or more: the outer two stay and the ones between move"
+ ));
+ }
+ let all = frame.unwrap_or_else(|| union(boxes));
+ let across = |b: &[f32; 4]| match plan.x {
+ Some(Across::Left) => all[0] - b[0],
+ Some(Across::Centre) => all[0] + all[2] / 2.0 - (b[0] + b[2] / 2.0),
+ Some(Across::Right) => all[0] + all[2] - (b[0] + b[2]),
+ None => 0.0,
+ };
+ let down = |b: &[f32; 4]| match plan.y {
+ Some(Down::Top) => all[1] - b[1],
+ Some(Down::Middle) => all[1] + all[3] / 2.0 - (b[1] + b[3] / 2.0),
+ Some(Down::Bottom) => all[1] + all[3] - (b[1] + b[3]),
+ None => 0.0,
+ };
+ let spaced = plan.spread.map(|axis| {
+ (
+ axis,
+ spread(boxes, if axis == Axis::X { 0 } else { 1 }, plan.gap, frame),
+ )
+ });
+ Ok(boxes
+ .iter()
+ .enumerate()
+ .map(|(i, b)| match &spaced {
+ Some((Axis::X, by)) => [by[i], down(b)],
+ Some((Axis::Y, by)) => [across(b), by[i]],
+ None => [across(b), down(b)],
+ })
+ .collect())
+}
+
+fn tidy(v: f32) -> f64 {
+ (f64::from(v) * 1000.0).round() / 1000.0
+}
+
+pub fn ops(doc: &Document, ids: &[String], plan: &Plan) -> Result<Vec<Op>> {
+ let world = |id: &str| {
+ overlay::node_world_box(doc, id)?.ok_or_else(|| {
+ anyhow!("{id} is not a shape with something to align: give shape ids, as klad ls prints them")
+ })
+ };
+ let boxes = ids.iter().map(|id| world(id)).collect::<Result<Vec<_>>>()?;
+ let frame = match &plan.to {
+ To::Selection => None,
+ To::Canvas => Some([0.0, 0.0, doc.canvas.width as f32, doc.canvas.height as f32]),
+ To::Shape(id) => Some(world(id)?),
+ };
+ let moved = moves(&boxes, plan, frame)?;
+ ids.iter()
+ .zip(moved)
+ .filter(|(_, by)| by[0].abs() > 0.0005 || by[1].abs() > 0.0005)
+ .map(|(id, by)| {
+ let (node, parent) = overlay::node_world(doc, id)?.ok_or_else(|| anyhow!("no shape {id}"))?;
+ let local = match parent.invert() {
+ Some(inverse) => inverse.map_vector((by[0], by[1])),
+ None => return Err(anyhow!("{id} sits in a group scaled to nothing and cannot be moved")),
+ };
+ let props = [
+ ("transform.x", json!(tidy(node.transform.x + local.x))),
+ ("transform.y", json!(tidy(node.transform.y + local.y))),
+ ]
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v))
+ .collect::<Map<_, _>>();
+ Ok(Op::Set { id: id.clone(), props })
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::{Layer, Node, Shape};
+
+ const BOXES: [[f32; 4]; 3] = [
+ [10.0, 10.0, 20.0, 20.0],
+ [100.0, 40.0, 40.0, 10.0],
+ [50.0, 80.0, 10.0, 30.0],
+ ];
+
+ fn plan() -> Plan {
+ Plan::default()
+ }
+
+ #[test]
+ fn edges_line_up_on_the_bounds_of_the_shapes_together() {
+ let left = moves(
+ &BOXES,
+ &Plan {
+ x: Some(Across::Left),
+ ..plan()
+ },
+ None,
+ )
+ .unwrap();
+ assert_eq!(left, vec![[0.0, 0.0], [-90.0, 0.0], [-40.0, 0.0]]);
+ let right = moves(
+ &BOXES,
+ &Plan {
+ x: Some(Across::Right),
+ ..plan()
+ },
+ None,
+ )
+ .unwrap();
+ assert_eq!(right, vec![[110.0, 0.0], [0.0, 0.0], [80.0, 0.0]]);
+ let middle = moves(
+ &BOXES,
+ &Plan {
+ y: Some(Down::Middle),
+ ..plan()
+ },
+ None,
+ )
+ .unwrap();
+ assert_eq!(middle, vec![[0.0, 40.0], [0.0, 15.0], [0.0, -35.0]]);
+ }
+
+ #[test]
+ fn one_shape_centres_on_the_canvas() {
+ let plan = Plan {
+ x: Some(Across::Centre),
+ y: Some(Down::Middle),
+ ..plan()
+ };
+ let moved = moves(&BOXES[..1], &plan, Some([0.0, 0.0, 400.0, 200.0])).unwrap();
+ assert_eq!(moved, vec![[180.0, 80.0]]);
+ assert!(moves(&BOXES[..1], &plan, None).is_err());
+ }
+
+ #[test]
+ fn spreading_keeps_the_outer_two_and_evens_the_gaps() {
+ let moved = moves(
+ &BOXES,
+ &Plan {
+ spread: Some(Axis::X),
+ ..plan()
+ },
+ None,
+ )
+ .unwrap();
+ assert_eq!(moved, vec![[0.0, 0.0], [0.0, 0.0], [10.0, 0.0]]);
+ let gaps = [60.0 - 30.0, 100.0 - 70.0];
+ assert_eq!(gaps[0], gaps[1]);
+ let fixed = moves(
+ &BOXES,
+ &Plan {
+ spread: Some(Axis::Y),
+ gap: Some(5.0),
+ ..plan()
+ },
+ None,
+ )
+ .unwrap();
+ assert_eq!(fixed, vec![[0.0, 0.0], [0.0, -5.0], [0.0, -30.0]]);
+ }
+
+ #[test]
+ fn aligning_and_spreading_one_direction_is_refused_and_two_combine() {
+ let both = Plan {
+ x: Some(Across::Left),
+ spread: Some(Axis::X),
+ ..plan()
+ };
+ assert!(moves(&BOXES, &both, None).is_err());
+ let row = Plan {
+ y: Some(Down::Top),
+ spread: Some(Axis::X),
+ ..plan()
+ };
+ assert_eq!(
+ moves(&BOXES, &row, None).unwrap(),
+ vec![[0.0, 0.0], [0.0, -30.0], [10.0, -70.0]]
+ );
+ assert!(
+ moves(
+ &BOXES[..2],
+ &Plan {
+ spread: Some(Axis::X),
+ ..plan()
+ },
+ None
+ )
+ .is_err()
+ );
+ assert!(
+ moves(
+ &BOXES,
+ &Plan {
+ gap: Some(4.0),
+ ..plan()
+ },
+ None
+ )
+ .is_err()
+ );
+ assert!(moves(&BOXES, &plan(), None).is_err());
+ }
+
+ fn rect(id: &str, x: f32, y: f32, w: f32, h: f32) -> Node {
+ Node::new(
+ id,
+ Shape::Rect {
+ x,
+ y,
+ w,
+ h,
+ radius: 0.0,
+ },
+ )
+ }
+
+ #[test]
+ fn a_shape_in_a_scaled_group_moves_by_the_distance_seen_on_the_canvas() {
+ let mut doc = Document::new(400, 200);
+ let mut group = Node::new(
+ "g",
+ Shape::Group {
+ children: vec![rect("inner", 0.0, 0.0, 10.0, 10.0)],
+ },
+ );
+ group.transform.sx = 2.0;
+ group.transform.sy = 2.0;
+ group.transform.pivot = Some([0.0, 0.0]);
+ doc.layers.push(Layer::vector(
+ "l1",
+ "shapes",
+ "c1",
+ vec![group, rect("free", 100.0, 50.0, 20.0, 20.0)],
+ ));
+ let plan = Plan {
+ x: Some(Across::Left),
+ to: To::Shape("free".into()),
+ ..plan()
+ };
+ let ops = ops(&doc, &["inner".to_string()], &plan).unwrap();
+ let Op::Set { id, props } = &ops[0] else {
+ panic!("a set")
+ };
+ assert_eq!(id, "inner");
+ assert_eq!(props["transform.x"], json!(50.0));
+ assert_eq!(props["transform.y"], json!(0.0));
+ assert!(super::ops(&doc, &["nothing".to_string()], &plan).is_err());
+ }
+}
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index 6160407..1b57fad 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod align;
pub mod assets;
pub mod effects;
pub mod export;
diff --git a/crates/render/src/overlay.rs b/crates/render/src/overlay.rs
index 93e26b3..745b488 100644
--- a/crates/render/src/overlay.rs
+++ b/crates/render/src/overlay.rs
@@ -631,6 +631,36 @@ pub fn hit(doc: &Document, frame: u32, point: (f32, f32)) -> Result<Option<(Stri
Ok(hits(doc, frame, point)?.into_iter().next())
}
+fn layer_shapes(layer: &Layer, frame: u32, polygon: &[[f32; 2]], out: &mut Vec<(String, String)>) -> Result<()> {
+ if !layer.visible || layer.locked {
+ return Ok(());
+ }
+ match layer.kind() {
+ Kind::Group => layer
+ .children()
+ .iter()
+ .try_for_each(|child| layer_shapes(child, frame, polygon, out)),
+ Kind::Vector => layer.content_at(frame).map_or(Ok(()), |cel| {
+ cel.nodes.iter().filter(|node| node.visible).try_for_each(|node| {
+ let middle = vector::node_bounds(node, &Matrix::new_identity())?.map(|r| (r.center_x(), r.center_y()));
+ if middle.is_some_and(|at| klad_core::cut::inside_polygon(polygon, at)) {
+ out.push((node.id.clone(), layer.id.clone()));
+ }
+ Ok(())
+ })
+ }),
+ Kind::Paint | Kind::Adjust | Kind::Bones => Ok(()),
+ }
+}
+
+pub fn shapes_inside(doc: &Document, frame: u32, polygon: &[[f32; 2]]) -> Result<Vec<(String, String)>> {
+ let mut out = Vec::new();
+ doc.layers
+ .iter()
+ .try_for_each(|layer| layer_shapes(layer, frame, polygon, &mut out))?;
+ Ok(out)
+}
+
pub fn node_world_box(doc: &Document, id: &str) -> Result<Option<[f32; 4]>> {
Ok(match node_world(doc, id)? {
Some((node, matrix)) => vector::node_bounds(node, &matrix)?.map(vector::to_box),
diff --git a/docs/cli.md b/docs/cli.md
index 8f98d52..c5249ab 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -29,6 +29,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
- [`klad set`](#klad-set): Change properties: klad set art.klad n4 fill=#ff0000 transform.rotate=15 (null removes)
- [`klad recolour`](#klad-recolour): Recolour strokes and fills together: the group moves to the colour and each keeps its own lighter or darker shade
- [`klad detach`](#klad-detach): Detach eraser, smudge and blender strokes from the marks they are attached to
+- [`klad align`](#klad-align): Align shapes to each other, the canvas or one shape, or spread them evenly
- [`klad rm`](#klad-rm): Remove layers, cels or nodes
- [`klad transform`](#klad-transform): Move, rotate or scale strokes and fills (<cel>:s<id>), or a whole layer or group (--layer)
- [`klad lasso`](#klad-lasso): Lasso strokes and fills on a paint layer; --cut also takes the parts crossing the edge
@@ -1002,6 +1003,64 @@ Options:
Print help (see a summary with '-h')
```
+## klad align
+
+```text
+Align shapes (the nodes of a vector layer) by their bounds on the canvas, or spread them evenly. --x lines up left edges, centres or right edges; --y lines up tops, middles or bottoms; both together stack them on one point. Without --to they line up on the bounds of the shapes together, so the outermost one stays; --to canvas uses the canvas (one shape is enough), --to <id> uses that shape, which stays where it is. --spread x or y keeps the two outer shapes and makes the gaps between neighbours equal; with --gap the first stays and each next one follows that many px after it. Aligning one way and spreading the other go together. A shape inside a group moves by the distance seen on the canvas. One history step.
+
+ klad align art.klad n3 n4 n7 --y middle
+ klad align art.klad n3 n4 n7 --y middle --spread x
+ klad align art.klad n3 n4 n7 --spread x --gap 24
+ klad align art.klad title --x centre --to canvas
+ klad align art.klad n4 n7 --x left --to n3
+
+Usage: klad align [OPTIONS] <BUNDLE> [IDS]...
+
+Arguments:
+ <BUNDLE>
+
+
+ [IDS]...
+
+
+Options:
+ --x <X>
+ Line up left edges, centres or right edges
+
+ [possible values: left, centre, center, right]
+
+ --y <Y>
+ Line up tops, middles or bottoms
+
+ [possible values: top, middle, bottom]
+
+ --spread <SPREAD>
+ Make the gaps between neighbours equal, across (x) or down (y)
+
+ [possible values: x, y]
+
+ --gap <GAP>
+ With --spread: px between neighbours, counted from the first
+
+ --to <TO>
+ What to line up on: canvas, or a shape id that stays put (default: the shapes together)
+
+ --render
+ Render a preview after the edit and print its path
+
+ --scale <SCALE>
+ Preview scale (default: longest side 1024 px)
+
+ --json
+ Print the result as JSON
+
+ --overlay <OVERLAY>
+ Draw on the preview: ids, bbox, grid or all (comma separated)
+
+ -h, --help
+ Print help (see a summary with '-h')
+```
+
## klad rm
```text
diff --git a/docs/guide/shapes-and-text.md b/docs/guide/shapes-and-text.md
index c8d5620..84d802d 100644
--- a/docs/guide/shapes-and-text.md
+++ b/docs/guide/shapes-and-text.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-10 10:30_
+_Last updated: 2026-11-10 21:45_
# Shapes, paths and text
@@ -18,6 +18,14 @@ Press **A**, click the shape and drag its points and handles. Alt click on the o
To move several points together, drag a box around them, then drag one of them. Hold **shift** while you drag the box to take the points of every shape on the layer, not only the one you clicked.
+## Line up several shapes
+
+1. Press **V** and click the first shape.
+2. Shift click the others, or drag a loop around them.
+3. In the bar under them, click an align button: left, centre or right edges, or top, middle or bottom.
+
+The two buttons with arrows space three or more shapes evenly. With one shape selected, **Edit > Align** lines it up on the canvas.
+
## Fill a shape with a gradient
Select the shape with **V**, then in layer settings switch its fill to **linear** or **radial** and edit the stops.
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index f5dec3d..5de0043 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -43,6 +43,7 @@ klad set art.klad n3 transform.rotate=-8 opacity=0.8 blur=4
- As in SVG, a node without `fill` is black; use `fill=none` for outlines only.
- Unknown keys fail with the list of valid ones. Structure (`id`, `type`, `kind`, `children`, `cels`, `nodes`) only changes through add, rm and mv.
- Ids are case sensitive; overlays print them exactly.
+- Lining shapes up: `klad align art.klad n3 n4 n7 --y middle` puts them on one line by their bounds on the canvas (`--x left|centre|right`, `--y top|middle|bottom`), `--spread x` (or `y`) makes the gaps between them equal with the outer two staying, and `--gap 24` sets the gap instead. `--to canvas` lines up on the canvas (`klad align art.klad title --x centre --to canvas`), `--to n3` on a shape that stays put. One history step. The user does the same with V, shift click and the bar under the shapes.
## Painting