Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Modifier strokes move, go and copy with the marks they are attached to

Indicode BVdf64d0c80b55
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 403d5e5..c67a64f 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -530,6 +530,16 @@ enum Command {
#[command(flatten)]
flags: EditFlags,
},
+ #[command(
+ about = "Detach eraser, smudge and blender strokes from the marks they are attached to",
+ long_about = "Detach eraser, smudge and blender strokes from the marks they are attached to. Give the modifier strokes, or marks to detach every modifier attached to them. A detached eraser erases whatever is under it again, and none of them move with other marks any more. One history step.\n\n klad detach art.klad c9:s40\n klad detach art.klad c9:s12 c9:s13"
+ )]
+ Detach {
+ bundle: PathBuf,
+ ids: Vec<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
#[command(about = "Remove layers, cels or nodes")]
Rm {
bundle: PathBuf,
@@ -2352,6 +2362,14 @@ fn run() -> Result<()> {
let ops = recolour_ops(&bundle, &ids, &to)?;
agent::edit(&bundle, &ops, &output(&flags, 0))?;
}
+ Command::Detach { bundle, ids, flags } => {
+ if ids.is_empty() {
+ return Err(anyhow!(
+ "give the strokes to detach, or marks to detach what is attached to them"
+ ));
+ }
+ agent::edit(&bundle, &[Op::Detach { ids }], &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 8cba3cd..a2b1669 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -489,5 +489,73 @@ fn an_eraser_stroke_attaches_to_the_lines_it_crosses_and_says_so() {
assert_eq!(strokes[0]["attached"], serde_json::json!(["c2:s3"]));
assert!(strokes[1].get("attached").is_none());
assert!(draw(&["strokes", path, "l1"]).contains("on s1"));
+ draw(&["detach", path, "c2:s1"]);
+ let listed: serde_json::Value = serde_json::from_str(&draw(&["strokes", path, "l1", "--json"])).unwrap();
+ assert!(listed["strokes"][2].get("on").is_none(), "detached from its line");
+ std::fs::remove_dir_all(&dir).unwrap();
+}
+
+#[test]
+fn modifiers_move_go_and_copy_with_their_marks_and_attach_again_when_moved_alone() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-follow-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let bundle = dir.join("a.klad");
+ let path = bundle.to_str().unwrap();
+ let draw = |args: &[&str]| {
+ let out = Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).to_string()
+ };
+ let listed = |frame: &str| -> Vec<serde_json::Value> {
+ let text = draw(&["strokes", path, "l1", "--frame", frame, "--json"]);
+ let value: serde_json::Value = serde_json::from_str(&text).unwrap();
+ value["strokes"].as_array().unwrap().clone()
+ };
+ draw(&["new", path, "--width", "400", "--height", "200"]);
+ draw(&["stroke", path, "l1", "--path", "M10 40 L390 40"]);
+ draw(&["stroke", path, "l1", "--path", "M10 140 L390 140"]);
+ draw(&[
+ "stroke",
+ path,
+ "l1",
+ "--brush",
+ "eraser",
+ "--size",
+ "12",
+ "--path",
+ "M100 25 L100 55",
+ ]);
+ draw(&["transform", path, "c2:s1", "--move", "0,20"]);
+ let eraser = listed("0")[2].clone();
+ assert_eq!(eraser["on"], serde_json::json!(["c2:s1"]));
+ assert_eq!(
+ eraser["bounds"][1],
+ serde_json::json!(45.0),
+ "the eraser came along with its line"
+ );
+ draw(&["transform", path, "c2:s3", "--move", "0,80"]);
+ assert_eq!(
+ listed("0")[2]["on"],
+ serde_json::json!(["c2:s2"]),
+ "moved on its own, it attaches to what it lands on"
+ );
+ draw(&["rm", path, "c2:s2"]);
+ assert_eq!(listed("0").len(), 1, "the eraser went with the only line it was on");
+ draw(&[
+ "stroke",
+ path,
+ "l1",
+ "--brush",
+ "eraser",
+ "--size",
+ "12",
+ "--path",
+ "M200 45 L200 75",
+ ]);
+ let map = draw(&["copy", path, "c2:s1", "--frame", "4"]);
+ assert_eq!(map.matches("->").count(), 2, "the line and its eraser: {map}");
+ let copies = listed("4");
+ assert_eq!(copies.len(), 2);
+ assert_eq!(copies[1]["on"], serde_json::json!([copies[0]["address"]]));
std::fs::remove_dir_all(&dir).unwrap();
}
diff --git a/crates/core/src/attach.rs b/crates/core/src/attach.rs
index 2f6a9a3..46d1a00 100644
--- a/crates/core/src/attach.rs
+++ b/crates/core/src/attach.rs
@@ -1,4 +1,5 @@
use crate::brushes::{BrushBlend, BrushDef, Curve, PaintDef};
+use crate::doc::MarkIds;
use crate::fill::Fill;
use crate::stroke::{Mark, Sample, Stroke};
use std::collections::{BTreeMap, BTreeSet};
@@ -241,6 +242,109 @@ pub fn attached(marks: &[Mark]) -> BTreeMap<u32, Vec<u32>> {
map
}
+pub fn following(marks: &[Mark]) -> BTreeSet<u32> {
+ let live: BTreeSet<u32> = marks.iter().map(Mark::id).collect();
+ crate::stroke::strokes_of(marks)
+ .filter(|s| s.on.iter().any(|id| live.contains(id)))
+ .map(|s| s.id)
+ .collect()
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Followed {
+ pub moving: Vec<u32>,
+ pub alone: Vec<u32>,
+}
+
+pub fn follow(marks: &mut Vec<Mark>, chosen: &[u32], ids: MarkIds) -> Followed {
+ let live: BTreeSet<u32> = marks.iter().map(Mark::id).collect();
+ let picked: BTreeSet<u32> = chosen.iter().copied().collect();
+ let mut next = ids.next(marks);
+ let mut followed = Followed {
+ moving: chosen.to_vec(),
+ alone: Vec::new(),
+ };
+ let out = std::mem::take(marks).into_iter().flat_map(|mark| {
+ let Mark::Stroke(mut stroke) = mark else {
+ return vec![mark];
+ };
+ let targets: Vec<u32> = stroke.on.iter().copied().filter(|id| live.contains(id)).collect();
+ let held: Vec<u32> = targets.iter().copied().filter(|id| picked.contains(id)).collect();
+ let whole = held.len() == targets.len();
+ match (picked.contains(&stroke.id), targets.is_empty(), held.is_empty(), whole) {
+ (_, true, ..) | (false, _, true, _) | (true, _, _, true) => {}
+ (true, ..) => followed.alone.push(stroke.id),
+ (false, _, _, true) => followed.moving.push(stroke.id),
+ (false, ..) => {
+ let copy = Stroke {
+ id: next,
+ on: held.clone(),
+ ..stroke.clone()
+ };
+ next += 1;
+ followed.moving.push(copy.id);
+ stroke.on = targets.into_iter().filter(|id| !held.contains(id)).collect();
+ return vec![Mark::Stroke(stroke), Mark::Stroke(copy)];
+ }
+ }
+ vec![Mark::Stroke(stroke)]
+ });
+ *marks = out.collect();
+ followed
+}
+
+pub fn prune(marks: &mut Vec<Mark>, before: &BTreeSet<u32>) {
+ let live: BTreeSet<u32> = marks.iter().map(Mark::id).collect();
+ let gone = |id: &u32| before.contains(id) && !live.contains(id);
+ marks.retain(|m| match m {
+ Mark::Stroke(s) if s.on.iter().any(gone) => s.on.iter().any(|id| live.contains(id)),
+ _ => true,
+ });
+ marks.iter_mut().for_each(|m| {
+ if let Mark::Stroke(s) = m {
+ s.on.retain(|id| !gone(id));
+ }
+ });
+}
+
+pub fn join(marks: &mut [Mark], pieces: &[(u32, u32)]) {
+ marks.iter_mut().for_each(|m| {
+ if let Mark::Stroke(s) = m {
+ let more: Vec<u32> = pieces
+ .iter()
+ .filter(|(from, _)| s.on.contains(from))
+ .map(|(_, part)| *part)
+ .collect();
+ s.on.extend(more);
+ }
+ });
+}
+
+pub fn detach(marks: &mut [Mark], ids: &[u32]) -> usize {
+ marks
+ .iter_mut()
+ .filter_map(|m| match m {
+ Mark::Stroke(s) if !s.on.is_empty() && (ids.contains(&s.id) || s.on.iter().any(|t| ids.contains(t))) => {
+ s.on.clear();
+ Some(())
+ }
+ _ => None,
+ })
+ .count()
+}
+
+pub fn remap(copied: &mut [Mark], made: &[crate::markedit::Copied]) {
+ let to: BTreeMap<(&str, u32), u32> = made.iter().map(|c| ((c.cel.as_str(), c.from), c.to)).collect();
+ copied.iter_mut().zip(made).for_each(|(m, c)| {
+ if let Mark::Stroke(s) = m {
+ s.on =
+ s.on.iter()
+ .filter_map(|id| to.get(&(c.cel.as_str(), *id)).copied())
+ .collect();
+ }
+ });
+}
+
pub fn attach<'a>(marks: &mut [Mark], at: usize, def_of: impl Fn(&str) -> Option<&'a BrushDef>) {
let on = match marks.get(at).and_then(Mark::as_stroke) {
Some(stroke) if stroke.on.is_empty() => targets(marks, at, stroke, &def_of),
@@ -352,6 +456,181 @@ mod tests {
);
}
+ fn crossed() -> Vec<Mark> {
+ let mut eraser = line(3, "eraser", 12.0, (100.0, 30.0), (100.0, 110.0));
+ if let Mark::Stroke(s) = &mut eraser {
+ s.on = vec![1, 2];
+ }
+ vec![
+ line(1, "ink", 6.0, (10.0, 50.0), (200.0, 50.0)),
+ line(2, "ink", 6.0, (10.0, 90.0), (200.0, 90.0)),
+ eraser,
+ ]
+ }
+
+ fn edit(marks: &mut Vec<Mark>, mut change: crate::markedit::MarkChange) -> Vec<u32> {
+ crate::markedit::apply_following(marks, &mut change, "c1", MarkIds::default()).unwrap()
+ }
+
+ fn moved(x: f32) -> crate::markedit::MarkTransform {
+ crate::markedit::MarkTransform {
+ x,
+ ..Default::default()
+ }
+ }
+
+ fn on(marks: &[Mark], at: usize) -> (u32, Vec<u32>) {
+ let s = marks[at].as_stroke().unwrap();
+ (s.id, s.on.clone())
+ }
+
+ fn start_x(marks: &[Mark], at: usize) -> f32 {
+ marks[at].as_stroke().unwrap().samples[0].pos().0
+ }
+
+ #[test]
+ fn moving_every_mark_of_a_modifier_takes_it_along_and_moving_some_splits_it() {
+ let mut marks = crossed();
+ edit(
+ &mut marks,
+ crate::markedit::MarkChange::Transform {
+ ids: vec![1, 2],
+ transform: moved(40.0),
+ },
+ );
+ assert_eq!(marks.len(), 3);
+ assert_eq!(start_x(&marks, 2), 140.0, "the eraser came along");
+ let mut marks = crossed();
+ edit(
+ &mut marks,
+ crate::markedit::MarkChange::Transform {
+ ids: vec![1],
+ transform: moved(40.0),
+ },
+ );
+ assert_eq!(marks.len(), 4);
+ assert_eq!(
+ on(&marks, 2),
+ (3, vec![2]),
+ "the original stays with the line that stayed"
+ );
+ assert_eq!(
+ on(&marks, 3),
+ (4, vec![1]),
+ "a copy right after it goes with the moved line"
+ );
+ assert_eq!((start_x(&marks, 2), start_x(&marks, 3)), (100.0, 140.0));
+ }
+
+ #[test]
+ fn a_turn_is_about_the_chosen_marks_not_the_ones_that_follow() {
+ let mut marks = crossed();
+ edit(
+ &mut marks,
+ crate::markedit::MarkChange::Transform {
+ ids: vec![1, 2],
+ transform: crate::markedit::MarkTransform {
+ rotate: 180.0,
+ ..Default::default()
+ },
+ },
+ );
+ let first = marks[0].as_stroke().unwrap().samples[0].pos();
+ assert!(
+ (first.0 - 200.0).abs() < 0.1 && (first.1 - 90.0).abs() < 0.1,
+ "{first:?}"
+ );
+ }
+
+ #[test]
+ fn deleting_marks_drops_them_from_modifiers_and_a_modifier_left_with_none_goes() {
+ let mut marks = crossed();
+ edit(&mut marks, crate::markedit::MarkChange::Remove { id: 1 });
+ assert_eq!(on(&marks, 1), (3, vec![2]));
+ edit(&mut marks, crate::markedit::MarkChange::Remove { id: 2 });
+ assert!(marks.is_empty(), "the eraser went with its last line");
+ let mut loose = vec![
+ line(1, "ink", 6.0, (0.0, 0.0), (9.0, 0.0)),
+ line(2, "eraser", 6.0, (0.0, 0.0), (9.0, 0.0)),
+ ];
+ edit(&mut loose, crate::markedit::MarkChange::Remove { id: 1 });
+ assert_eq!(loose.len(), 1, "an unattached eraser stays, as before");
+ }
+
+ #[test]
+ fn a_lasso_takes_plain_marks_and_their_modifiers_follow() {
+ let mut marks = crossed();
+ let around_first = vec![[0.0, 40.0], [220.0, 40.0], [220.0, 60.0], [0.0, 60.0]];
+ assert_eq!(crate::markedit::lassoed(&marks, &around_first), vec![1]);
+ let around_eraser = vec![[90.0, 20.0], [110.0, 20.0], [110.0, 120.0], [90.0, 120.0]];
+ assert!(
+ crate::markedit::lassoed(&marks, &around_eraser).is_empty(),
+ "an attached eraser is not picked on its own"
+ );
+ let mut change = crate::markedit::MarkChange::Lasso {
+ polygon: around_first,
+ cut: false,
+ action: crate::markedit::LassoAction::Transform(moved(40.0)),
+ chosen: Vec::new(),
+ };
+ crate::markedit::apply_following(&mut marks, &mut change, "c1", MarkIds::default()).unwrap();
+ assert_eq!(on(&marks, 3), (4, vec![1]));
+ assert_eq!(start_x(&marks, 3), 140.0);
+ }
+
+ #[test]
+ fn a_piece_cut_off_by_the_lasso_joins_the_modifiers_of_its_mark() {
+ let mut marks = crossed();
+ let left_half = vec![[0.0, 40.0], [60.0, 40.0], [60.0, 60.0], [0.0, 60.0]];
+ let mut change = crate::markedit::MarkChange::Lasso {
+ polygon: left_half,
+ cut: true,
+ action: crate::markedit::LassoAction::Transform(moved(0.0)),
+ chosen: Vec::new(),
+ };
+ crate::markedit::apply_following(&mut marks, &mut change, "c1", MarkIds::default()).unwrap();
+ let ids: Vec<u32> = marks.iter().map(Mark::id).collect();
+ assert_eq!(
+ ids,
+ vec![1, 4, 2, 3, 5],
+ "the piece sits after its mark, the eraser's copy after the eraser"
+ );
+ assert_eq!(on(&marks, 3), (3, vec![1, 2]));
+ assert_eq!(on(&marks, 4), (5, vec![4]));
+ }
+
+ #[test]
+ fn a_modifier_moved_on_its_own_is_reported_for_attaching_again() {
+ let mut marks = crossed();
+ let alone = edit(
+ &mut marks,
+ crate::markedit::MarkChange::Transform {
+ ids: vec![3],
+ transform: moved(300.0),
+ },
+ );
+ assert_eq!(alone, vec![3]);
+ assert_eq!(marks.len(), 3);
+ }
+
+ #[test]
+ fn detaching_a_modifier_or_its_marks_leaves_it_where_it_is() {
+ let mut marks = crossed();
+ edit(&mut marks, crate::markedit::MarkChange::Detach { ids: vec![1] });
+ assert_eq!(on(&marks, 2), (3, vec![]));
+ let mut marks = crossed();
+ edit(&mut marks, crate::markedit::MarkChange::Detach { ids: vec![3] });
+ assert_eq!(on(&marks, 2), (3, vec![]));
+ edit(
+ &mut marks,
+ crate::markedit::MarkChange::Transform {
+ ids: vec![1, 2],
+ transform: moved(40.0),
+ },
+ );
+ assert_eq!(start_x(&marks, 2), 100.0, "a detached eraser stays put");
+ }
+
#[test]
fn attach_fills_in_a_stroke_already_in_the_list() {
let defs = defs();
diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rs
index e9e24b0..9aa50ed 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -491,9 +491,15 @@ impl Bundle {
true => Ok(()),
false => bail!("{} does not exist", markedit::address(&source.cel, *id)),
})?;
+ let chosen: BTreeSet<u32> = source.ids.iter().copied().collect();
+ let taken: BTreeSet<u32> = strokes_of(&from)
+ .filter(|s| s.on.iter().any(|id| chosen.contains(id)))
+ .map(|s| s.id)
+ .chain(chosen.iter().copied())
+ .collect();
Ok(from
.into_iter()
- .filter(|m| source.ids.contains(&m.id()))
+ .filter(|m| taken.contains(&m.id()))
.map(|m| (source.cel.clone(), m))
.collect::<Vec<_>>())
})
@@ -509,8 +515,28 @@ impl Bundle {
markedit::apply(marks, change, cel, doc.mark_ids(cel))?;
self.attach_added(marks, from)
}
- _ => markedit::apply(marks, change, cel, doc.mark_ids(cel)),
+ _ => {
+ let alone = markedit::apply_following(marks, change, cel, doc.mark_ids(cel))?;
+ self.reattach(marks, &alone)
+ }
+ }
+ }
+
+ fn reattach(&self, marks: &mut [Mark], alone: &[u32]) -> Result<()> {
+ if alone.is_empty() {
+ return Ok(());
}
+ let defs = self.brush_defs(strokes_of(marks).map(|s| s.brush.as_str()))?;
+ marks.iter_mut().for_each(|m| {
+ if let Mark::Stroke(s) = m
+ && alone.contains(&s.id)
+ {
+ s.on.clear();
+ }
+ });
+ let at: Vec<usize> = (0..marks.len()).filter(|&i| alone.contains(&marks[i].id())).collect();
+ at.into_iter().for_each(|i| attach::attach(marks, i, |id| defs.get(id)));
+ Ok(())
}
pub fn brush_defs<'a>(&self, ids: impl IntoIterator<Item = &'a str>) -> Result<BTreeMap<String, BrushDef>> {
@@ -626,6 +652,7 @@ pub fn summarize(ops: &[Op]) -> String {
Op::Fill(spec) => format!("fill on {}", spec.layer),
Op::Palette(_) => "palette".to_string(),
Op::Transform { ids, .. } => format!("transform {}", ids.join(" ")),
+ Op::Detach { ids } => format!("detach {}", ids.join(" ")),
Op::Shift(spec) => format!("transform {}", spec.layer),
Op::Path { id, .. } => format!("path {id}"),
Op::Copy(spec) => format!(
diff --git a/crates/core/src/markedit.rs b/crates/core/src/markedit.rs
index a10d0dc..7f602b7 100644
--- a/crates/core/src/markedit.rs
+++ b/crates/core/src/markedit.rs
@@ -1,3 +1,4 @@
+use crate::attach;
use crate::color::{parse_hex, to_u16};
use crate::cut::{self, Cut, Keep, inside_polygon};
use crate::doc::MarkIds;
@@ -5,6 +6,7 @@ use crate::fill::{Coverage, Fill, FillSource};
use crate::stroke::{Mark, POS_SCALE, Sample, Stroke};
use anyhow::{Result, anyhow, bail};
use serde_json::{Map, Value};
+use std::collections::BTreeSet;
pub type Affine = [f32; 6];
@@ -143,6 +145,9 @@ pub enum MarkChange {
count: usize,
ids: Vec<u32>,
},
+ Detach {
+ ids: Vec<u32>,
+ },
}
#[derive(Clone, Debug, PartialEq)]
@@ -169,6 +174,7 @@ impl MarkChange {
MarkChange::Lasso { chosen, .. } => chosen.clone(),
MarkChange::Paste { made, .. } => made.iter().map(|c| c.to).collect(),
MarkChange::Put(marks) => marks.iter().map(Mark::id).collect(),
+ MarkChange::Detach { ids } => ids.clone(),
MarkChange::Copy { .. } | MarkChange::Part { .. } => Vec::new(),
}
}
@@ -560,8 +566,10 @@ pub fn sides(marks: &[Mark], polygon: &[[f32; 2]]) -> Vec<(u32, Side)> {
if polygon.len() < 3 {
return Vec::new();
}
+ let following = attach::following(marks);
marks
.iter()
+ .filter(|m| !following.contains(&m.id()))
.map(|m| (m.id(), side(m, polygon)))
.filter(|(_, side)| *side != Side::Outside)
.collect()
@@ -589,6 +597,7 @@ pub fn split(marks: &mut Vec<Mark>, polygon: &[[f32; 2]], cut: bool, ids: MarkId
.filter(|(_, s)| *s == Side::Crossing)
.map(|(id, _)| *id)
.collect();
+ let mut pieces: Vec<(u32, u32)> = Vec::new();
let sliced = std::mem::take(marks).into_iter().flat_map(|mut mark| {
if !crossing.contains(&mark.id()) {
return vec![mark];
@@ -596,6 +605,7 @@ pub fn split(marks: &mut Vec<Mark>, polygon: &[[f32; 2]], cut: bool, ids: MarkId
let mut part = mark.clone();
part.set_id(next);
chosen.push(next);
+ pieces.push((mark.id(), next));
next += 1;
mark.cuts_mut().push(Cut {
keep: Keep::Outside,
@@ -608,6 +618,7 @@ pub fn split(marks: &mut Vec<Mark>, polygon: &[[f32; 2]], cut: bool, ids: MarkId
vec![mark, part]
});
*marks = sliced.collect();
+ attach::join(marks, &pieces);
chosen
}
@@ -624,6 +635,12 @@ fn position(marks: &[Mark], cel: &str, id: u32) -> Result<usize> {
}
pub fn apply(marks: &mut Vec<Mark>, change: &mut MarkChange, cel: &str, ids: MarkIds) -> Result<()> {
+ apply_following(marks, change, cel, ids).map(|_| ())
+}
+
+pub fn apply_following(marks: &mut Vec<Mark>, change: &mut MarkChange, cel: &str, ids: MarkIds) -> Result<Vec<u32>> {
+ let before: BTreeSet<u32> = marks.iter().map(Mark::id).collect();
+ let mut alone = Vec::new();
match change {
MarkChange::Add(added) => {
let next = ids.next(marks);
@@ -645,8 +662,14 @@ pub fn apply(marks: &mut Vec<Mark>, change: &mut MarkChange, cel: &str, ids: Mar
MarkChange::Remove { id } => {
let at = position(marks, cel, *id)?;
marks.remove(at);
+ attach::prune(marks, &before);
+ }
+ MarkChange::Transform { ids: chosen, transform } => {
+ let pivot = pivot_of(marks, chosen, transform, cel)?;
+ let followed = attach::follow(marks, chosen, ids);
+ transform_marks(marks, &followed.moving, transform.affine(pivot), cel)?;
+ alone = followed.alone;
}
- MarkChange::Transform { ids, transform } => transform_marks(marks, ids, transform, cel)?,
MarkChange::Lasso {
polygon,
cut,
@@ -668,8 +691,16 @@ pub fn apply(marks: &mut Vec<Mark>, change: &mut MarkChange, cel: &str, ids: Mar
);
}
match action {
- LassoAction::Transform(transform) => transform_marks(marks, chosen, transform, cel)?,
- LassoAction::Remove => marks.retain(|m| !chosen.contains(&m.id())),
+ LassoAction::Transform(transform) => {
+ let pivot = pivot_of(marks, chosen, transform, cel)?;
+ let followed = attach::follow(marks, chosen, ids);
+ transform_marks(marks, &followed.moving, transform.affine(pivot), cel)?;
+ alone = followed.alone;
+ }
+ LassoAction::Remove => {
+ marks.retain(|m| !chosen.contains(&m.id()));
+ attach::prune(marks, &before);
+ }
}
}
MarkChange::Put(put) => *marks = put.clone(),
@@ -686,8 +717,12 @@ pub fn apply(marks: &mut Vec<Mark>, change: &mut MarkChange, cel: &str, ids: Mar
bail!("{cel} copies the marks of {from}; copies are resolved by the bundle")
}
MarkChange::Paste { .. } => bail!("{cel} takes copies of other marks; copies are resolved by the bundle"),
+ MarkChange::Detach { ids } => {
+ ids.iter().try_for_each(|id| position(marks, cel, *id).map(|_| ()))?;
+ attach::detach(marks, ids);
+ }
}
- Ok(())
+ Ok(alone)
}
pub fn paste(
@@ -720,6 +755,7 @@ pub fn paste(
)
})
.unzip();
+ attach::remap(&mut copied, &made);
if let Some(t) = transform {
let pivot = match t.pivot {
Some(p) => p,
@@ -736,17 +772,20 @@ pub fn paste(
Ok(made)
}
-fn transform_marks(marks: &mut [Mark], ids: &[u32], transform: &MarkTransform, cel: &str) -> Result<()> {
+fn pivot_of(marks: &[Mark], ids: &[u32], transform: &MarkTransform, cel: &str) -> Result<[f32; 2]> {
let at: Vec<usize> = ids.iter().map(|id| position(marks, cel, *id)).collect::<Result<_>>()?;
- let pivot = match transform.pivot {
+ Ok(match transform.pivot {
Some(p) => p,
None => {
let chosen: Vec<&Mark> = at.iter().map(|&i| &marks[i]).collect();
let [x0, y0, x1, y1] = union(&chosen).ok_or_else(|| anyhow!("nothing to transform"))?;
[(x0 + x1) / 2.0, (y0 + y1) / 2.0]
}
- };
- let a = transform.affine(pivot);
+ })
+}
+
+fn transform_marks(marks: &mut [Mark], ids: &[u32], a: Affine, cel: &str) -> Result<()> {
+ let at: Vec<usize> = ids.iter().map(|id| position(marks, cel, *id)).collect::<Result<_>>()?;
at.iter().for_each(|&i| transform_mark(&mut marks[i], a));
Ok(())
}
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index c239c42..96a8164 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -124,6 +124,9 @@ pub enum Op {
ids: Vec<String>,
transform: MarkTransform,
},
+ Detach {
+ ids: Vec<String>,
+ },
Shift(ShiftSpec),
Path {
id: String,
@@ -1495,6 +1498,17 @@ impl Op {
transform: MarkTransform::parse(&mut map)?,
}
}
+ "detach" => {
+ let mut ids: Vec<String> = match map.remove("ids") {
+ Some(v) => serde_json::from_value(v).map_err(|_| anyhow!("ids must be a list of strings"))?,
+ None => Vec::new(),
+ };
+ ids.extend(take_str(&mut map, "id")?);
+ if ids.is_empty() {
+ bail!("detach needs an id or ids (strokes and fills, <cel>:s<id>)");
+ }
+ Op::Detach { ids }
+ }
"path" => Op::Path {
id: take_str(&mut map, "id")?.ok_or_else(|| anyhow!("path needs the id of a path, rect or ellipse"))?,
edit: PathEdit::parse(&mut map)?,
@@ -3400,6 +3414,24 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
})?;
out.changed.extend(ids.iter().cloned());
}
+ Op::Detach { ids } => {
+ let mut cels: Vec<(String, Vec<u32>)> = Vec::new();
+ ids.iter().try_for_each(|id| {
+ let (cel, mark) = parse_address(id)
+ .ok_or_else(|| anyhow!("detach takes strokes and fills (<cel>:s<id>), not {id}"))?;
+ match cels.iter_mut().find(|(c, _)| c == cel) {
+ Some((_, marks)) => marks.push(mark),
+ None => cels.push((cel.to_string(), vec![mark])),
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ cels.into_iter().try_for_each(|(cel, marks)| {
+ let layer = mark_owner(doc, &cel)?;
+ out.push(&layer, &cel, MarkChange::Detach { ids: marks });
+ Ok::<_, anyhow::Error>(())
+ })?;
+ out.changed.extend(ids.iter().cloned());
+ }
Op::Shift(spec) => shift(doc, spec, out)?,
Op::Move { id, place } => {
move_item(doc, id, place).with_context(|| format!("mv {id}"))?;
diff --git a/crates/core/src/tween.rs b/crates/core/src/tween.rs
index a23dff7..7bacd65 100644
--- a/crates/core/src/tween.rs
+++ b/crates/core/src/tween.rs
@@ -1970,6 +1970,27 @@ mod tests {
assert_eq!(forced.alone_a, [1]);
}
+ #[test]
+ fn an_in_between_keeps_what_its_eraser_is_attached_to() {
+ let eraser = |x: f32| {
+ let mut e = stroke(2, &[(x, -10.0), (x, 10.0)], 8.0);
+ if let Mark::Stroke(s) = &mut e {
+ s.brush = "eraser".into();
+ s.on = vec![1];
+ }
+ e
+ };
+ let a = vec![stroke(1, &[(0.0, 0.0), (100.0, 0.0)], 4.0), eraser(50.0)];
+ let b = vec![stroke(1, &[(0.0, 40.0), (100.0, 40.0)], 4.0), eraser(60.0)];
+ let between = plan(&a, &b, Match::Id, &[]).at(0.5);
+ let on: Vec<Vec<u32>> = between
+ .iter()
+ .filter_map(Mark::as_stroke)
+ .map(|s| s.on.clone())
+ .collect();
+ assert_eq!(on, vec![vec![], vec![1]]);
+ }
+
#[test]
fn line_ends_that_touch_in_both_keys_touch_in_between() {
let bar = |dy: f32| stroke(1, &[(0.0, 100.0 + dy), (200.0, 100.0 + dy)], 6.0);
diff --git a/docs/cli.md b/docs/cli.md
index 8de5f65..9d961dd 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -28,6 +28,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
- [`klad add`](#klad-add): Add a layer, cel or shape
- [`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 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
@@ -967,6 +968,40 @@ Options:
Print help (see a summary with '-h')
```
+## klad detach
+
+```text
+Detach eraser, smudge and blender strokes from the marks they are attached to. Give the modifier strokes, or marks to detach every modifier attached to them. A detached eraser erases whatever is under it again, and none of them move with other marks any more. One history step.
+
+ klad detach art.klad c9:s40
+ klad detach art.klad c9:s12 c9:s13
+
+Usage: klad detach [OPTIONS] <BUNDLE> [IDS]...
+
+Arguments:
+ <BUNDLE>
+
+
+ [IDS]...
+
+
+Options:
+ --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