A drawing app built for agent/human collaboration
Rust
The editor shows, selects and detaches what is attached to strokes
Indicode BVd368c5a9b74c
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rsindex 1c53824..6cc3f1f 100644--- a/crates/app/src/commands.rs+++ b/crates/app/src/commands.rs@@ -43,6 +43,8 @@ pub enum Cmd {Recolour,Thinner,Thicker,+ AttachedOnly,+ Detach,FlipH,FlipV,Corner,@@ -496,7 +498,7 @@ use Repeat as R;use Trigger as T;impl Cmd {- pub const ALL: [Cmd; 169] = [+ pub const ALL: [Cmd; 171] = [Cmd::Brush,Cmd::Eraser,Cmd::Fill,@@ -536,6 +538,8 @@ impl Cmd {Cmd::Recolour,Cmd::Thinner,Cmd::Thicker,+ Cmd::AttachedOnly,+ Cmd::Detach,Cmd::FlipH,Cmd::FlipV,Cmd::Corner,@@ -1021,6 +1025,24 @@ impl Cmd {R::No,"a quarter bigger",),+ Cmd::AttachedOnly => spec(+ "edit.attached-only",+ "select only what is attached",+ icon::LINK,+ G::Edit,+ T::None,+ R::No,+ "select the erasers, smudges and blends attached to the selected strokes, to move or delete them on their own",+ ),+ Cmd::Detach => spec(+ "edit.detach",+ "detach erasers, smudges and blends",+ icon::UNLINK,+ G::Edit,+ T::None,+ R::No,+ "free what is attached to the selected strokes: it stays where it is and acts on whatever is under it",+ ),Cmd::FlipH => spec("edit.flip-h","flip the selection left-right",@@ -2231,6 +2253,8 @@ impl Cmd {Cmd::Recolour => "Recolour",Cmd::Thinner => "Thinner",Cmd::Thicker => "Thicker",+ Cmd::AttachedOnly => "Attached only",+ Cmd::Detach => "Detach",Cmd::FlipH => "Flip horizontal",Cmd::FlipV => "Flip vertical",Cmd::Corner => "Corner",@@ -2442,7 +2466,17 @@ pub const MENUS: [Menu; 9] = [Run(Cmd::NudgeDown),],),- Sub("Strokes", &[Run(Cmd::Recolour), Run(Cmd::Thinner), Run(Cmd::Thicker)]),+ Sub(+ "Strokes",+ &[+ Run(Cmd::Recolour),+ Run(Cmd::Thinner),+ Run(Cmd::Thicker),+ Line,+ Run(Cmd::AttachedOnly),+ Run(Cmd::Detach),+ ],+ ),Sub("Shape", &[Run(Cmd::FillShape), Run(Cmd::OutlineShape)]),Sub("Points",diff --git a/crates/app/src/composite.rs b/crates/app/src/composite.rsindex 57b81e1..2b925c7 100644--- a/crates/app/src/composite.rs+++ b/crates/app/src/composite.rs@@ -1197,7 +1197,7 @@ impl Scene {at: (f32, f32),slack: f32,all: bool,- hidden: impl Fn(&Mark) -> bool + Copy,+ hidden: impl Fn(&[Mark], &Mark) -> bool + Copy,) -> Option<(Vec<usize>, u32)> {const SEEN: f32 = 0.05;let doc = &self.bundle.doc;@@ -1227,17 +1227,15 @@ impl Scene {Some((path, marks, seen))}).collect();- let painted = |marks: &[Mark]| klad_core::markedit::pick(marks, at, 0.0, hidden).is_some();+ let pick = |marks: &[Mark], slack: f32| klad_core::markedit::pick(marks, at, slack, |m| hidden(marks, m));layers.iter()- .find(|(_, marks, seen)| seen.map_or_else(|| painted(marks), |a| a > SEEN))- .and_then(|(path, marks, _)| {- klad_core::markedit::pick(marks, at, slack, hidden).map(|id| (path.clone(), id))- })+ .find(|(_, marks, seen)| seen.map_or_else(|| pick(marks, 0.0).is_some(), |a| a > SEEN))+ .and_then(|(path, marks, _)| pick(marks, slack).map(|id| (path.clone(), id))).or_else(|| {- layers.iter().find_map(|(path, marks, _)| {- klad_core::markedit::pick(marks, at, slack, hidden).map(|id| (path.clone(), id))- })+ layers+ .iter()+ .find_map(|(path, marks, _)| pick(marks, slack).map(|id| (path.clone(), id)))})}diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 8de8048..2044bb6 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -1694,14 +1694,25 @@ impl Editor {});}- fn erased(&self) -> impl Fn(&Mark) -> bool + Copy + '_ {- let brushes = &self.brushes;- move |m: &Mark| {- m.as_stroke().is_some_and(|s| {- brushes+ fn erased(&self) -> impl Fn(&[Mark], &Mark) -> bool + Copy + '_ {+ move |marks: &[Mark], m: &Mark| {+ let eraser = m.as_stroke().is_some_and(|s| {+ self.brushes.get(&s.brush).is_ok_and(|b| b.blend == klad_brush::brush::StrokeBlend::Erase)- })+ });+ eraser || !self.wiped(marks, &[m.id()]).is_empty()+ }+ }++ fn wiped(&self, marks: &[Mark], among: &[u32]) -> BTreeSet<u32> {+ let attached = klad_core::stroke::strokes_of(marks).any(|s| s.on.iter().any(|t| among.contains(t)));+ match attached {+ false => BTreeSet::new(),+ true => {+ let (w, h) = self.scene.size();+ klad_brush::scope::hidden(w, h, marks, &self.brushes, Some(among))+ }}}@@ -1942,15 +1953,17 @@ impl Editor {Some(polygon) => {let sides = markedit::sides(marks, polygon);let crossing = sides.iter().any(|(_, side)| *side == markedit::Side::Crossing);- let inside = sides+ let mut inside: Vec<u32> = sides.into_iter().filter(|(_, side)| *side == markedit::Side::Inside).map(|(id, _)| id).collect();+ let wiped = self.wiped(marks, &inside);+ inside.retain(|id| !wiped.contains(id));(inside, crossing)}None => (- markedit::pick(marks, (at.x, at.y), 5.0 / zoom, erased)+ markedit::pick(marks, (at.x, at.y), 5.0 / zoom, |m| erased(marks, m)).into_iter().collect(),false,@@ -3489,6 +3502,94 @@ impl Editor {self.set_picked(sets)}+ fn attached_parts(&self) -> Vec<(String, String, Vec<u32>)> {+ self.picked_parts()+ .into_iter()+ .map(|(layer, cel, marks, ids)| {+ let chosen: BTreeSet<u32> = ids.iter().copied().collect();+ let attached = klad_core::stroke::strokes_of(marks)+ .filter(|s| !chosen.contains(&s.id) && s.on.iter().any(|t| chosen.contains(t)))+ .map(|s| s.id)+ .collect();+ (layer, cel, attached)+ })+ .collect()+ }++ pub(super) fn attached_count(&self) -> usize {+ self.attached_parts().iter().map(|(_, _, ids)| ids.len()).sum()+ }++ pub(super) fn detachable(&self) -> bool {+ self.attached_count() > 0+ || self.picked_parts().iter().any(|(_, _, marks, ids)| {+ let live: BTreeSet<u32> = marks.iter().map(Mark::id).collect();+ klad_core::stroke::strokes_of(marks)+ .any(|s| ids.contains(&s.id) && s.on.iter().any(|t| live.contains(t)))+ })+ }++ fn select_attached(&mut self) -> Result<()> {+ let Some(picked) = self.picked.clone() else {+ return Ok(());+ };+ if picked.cut.is_some() {+ self.say(+ Tone::Refused,+ "the lasso cut has not happened yet: move or edit the strokes first, then select what is attached",+ );+ return Ok(());+ }+ let parts = self.attached_parts();+ let count: usize = parts.iter().map(|(_, _, ids)| ids.len()).sum();+ let mut parts = parts.into_iter();+ let Some((_, cel, ids)) = parts.next() else {+ return Ok(());+ };+ self.picked = Some(Picked {+ more: parts+ .filter(|(_, _, ids)| !ids.is_empty())+ .map(|(layer, cel, ids)| Part { layer, cel, ids })+ .collect(),+ ..Picked::whole(cel, ids)+ });+ self.say(+ Tone::Done,+ format!("{count} attached selected: they move and go on their own now, and attach to what they land on"),+ );+ Ok(())+ }++ fn detach_picked(&mut self) -> Result<()> {+ let Some(picked) = self.picked.clone() else {+ return Ok(());+ };+ let count = self.attached_count();+ let (mut ops, after) = match &picked.cut {+ Some(_) => self+ .picked_ops(LassoAction::Transform(MarkTransform::default()))+ .ok_or_else(|| anyhow!("the selection changed underneath: select the strokes again"))?,+ None => (Vec::new(), Some(picked.clone())),+ };+ let ids: Vec<String> = after+ .iter()+ .flat_map(|p| {+ std::iter::once((p.cel.clone(), p.ids.clone()))+ .chain(p.more.iter().map(|m| (m.cel.clone(), m.ids.clone())))+ })+ .flat_map(|(cel, ids)| ids.into_iter().map(move |id| address(&cel, id)))+ .collect();+ ops.push(Op::Detach { ids });+ self.apply(ops)?;+ self.picked = after;+ self.forget_missing_selection();+ self.say(+ Tone::Done,+ format!("{count} detached: they stay where they are and act on whatever is under them"),+ );+ Ok(())+ }+fn size_picked(&mut self, k: f32) -> Result<()> {let sets = self.chosen_marks().map_or(Vec::new(), |(_, chosen)| {chosen@@ -3558,8 +3659,12 @@ impl Editor {.map_or_else(String::new, |(l, c)| format!("on {}, frame {}", l.name, c.frame)),n => format!("on {} layers", n + 1),};+ let attached = match self.attached_count() {+ 0 => String::new(),+ n => format!(", {n} attached"),+ };ui.label(format!(- "{} strokes, {fills} fills selected {place}{}",+ "{} strokes, {fills} fills{attached} selected {place}{}",chosen.len() - fills,if picked.cut.is_some() {"\n(with the parts crossing the lasso edge)"diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rsindex b207598..27c37ec 100644--- a/crates/app/src/editor/commands.rs+++ b/crates/app/src/editor/commands.rs@@ -108,6 +108,18 @@ impl Editor {Cmd::SelectAll => (!self.active_paint() || self.scene.active_marks().is_empty()).then(|| "the active layer has no strokes on this frame".to_string()),Cmd::Recolour | Cmd::Thinner | Cmd::Thicker => need_strokes().or(editing),+ Cmd::AttachedOnly => need_strokes()+ .or_else(|| {+ (self.attached_count() == 0)+ .then(|| "no eraser, smudge or blend is attached to the selected strokes".to_string())+ })+ .or(editing),+ Cmd::Detach => need_strokes()+ .or_else(|| {+ (!self.detachable())+ .then(|| "no eraser, smudge or blend is attached to the selected strokes".to_string())+ })+ .or(editing),Cmd::FillShape | Cmd::OutlineShape => self.recolourable().is_none()@@ -584,6 +596,8 @@ impl Editor {}Cmd::Thinner => self.size_picked(0.8)?,Cmd::Thicker => self.size_picked(1.25)?,+ Cmd::AttachedOnly => self.select_attached()?,+ Cmd::Detach => self.detach_picked()?,Cmd::FlipH => self.flip(true)?,Cmd::FlipV => self.flip(false)?,Cmd::TurnLeft90 => self.turn(-90.0)?,diff --git a/crates/app/src/editor/selection.rs b/crates/app/src/editor/selection.rsindex 3fe323f..766f750 100644--- a/crates/app/src/editor/selection.rs+++ b/crates/app/src/editor/selection.rs@@ -270,6 +270,10 @@ impl Editor {Cmd::Deselect,],};+ let attached = match selected {+ Selected::Strokes => self.attached_count(),+ _ => 0,+ };let writing = self.writing();egui::Area::new(Id::unique("selection bar")).order(egui::Order::Foreground)@@ -280,6 +284,10 @@ impl Editor {egui::Frame::popup(ui.style()).show(ui, |ui| {ui.horizontal(|ui| {commands.iter().for_each(|cmd| {+ if *cmd == Cmd::Delete && attached > 0 {+ self.command_button(ui, Cmd::AttachedOnly, Some(&format!("{attached} attached")));+ self.command_button(ui, Cmd::Detach, None);+ }if *cmd == Cmd::Recolour {let swatch = crate::color::color32(self.color);let r = self.command_button(ui, *cmd, None);diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex f6f3e17..5fec198 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -1969,6 +1969,119 @@ fn an_eraser_drawn_in_the_editor_attaches_to_the_strokes_it_crossed() {let _ = std::fs::remove_dir_all(&path);}+fn on_screen(h: &Harness<'static, Editor>, x: f32, y: f32) -> egui::Pos2 {+ let (view, rect) = (h.state().view.unwrap(), h.state().canvas_rect);+ rect.min + view.to_screen(vec2(x, y), rect.size())+}++fn stroke_on(h: &Harness<'static, Editor>, id: u32) -> Option<klad_core::stroke::Stroke> {+ h.state()+ .scene+ .bundle+ .read_marks("l6", "c6")+ .unwrap()+ .into_iter()+ .find(|m| m.id() == id)+ .and_then(|m| m.as_stroke().cloned())+}++#[test]+fn erasers_follow_their_strokes_and_attached_only_and_detach_reach_them() {+ let path = sample("follow");+ Bundle::open(&path)+ .unwrap()+ .apply(+ &parse_lines(+ r##"{"op":"stroke","layer":"l6","path":"M300 330 L480 330","size":20}+{"op":"stroke","layer":"l6","path":"M100 360 L250 360","size":20}+{"op":"stroke","layer":"l6","brush":"eraser","path":"M390 310 L390 350","size":30}"##,+ )+ .unwrap(),+ )+ .unwrap();+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));+ activate(&mut h, "lines");+ h.run_steps(3);+ let ids: Vec<u32> = h.state().scene.marks_of("c6").iter().map(|m| m.id()).collect();+ let (line, other, eraser) = (ids[ids.len() - 3], ids[ids.len() - 2], ids[ids.len() - 1]);+ assert_eq!(stroke_on(&h, eraser).unwrap().on, vec![line]);+ h.state_mut().tool = Tool::Strokes;+ let pick = |h: &mut Harness<'static, Editor>, ids: Vec<u32>| {+ h.state_mut().picked = Some(super::Picked {+ cel: "c6".into(),+ ids,+ cut: None,+ more: Vec::new(),+ });+ h.run_steps(2);+ };+ pick(&mut h, vec![line]);+ assert_eq!(h.state().attached_count(), 1);+ let button = format!("{} 1 attached", Cmd::AttachedOnly.spec().icon);+ assert_eq!(h.query_all_by_label(&button).count(), 1, "the selection bar shows it");+ let before = stroke_on(&h, eraser).unwrap().samples[0].pos();+ h.state_mut().invoke(Cmd::NudgeRight).unwrap();+ h.run_steps(2);+ assert_eq!(+ stroke_on(&h, eraser).unwrap().samples[0].pos().0,+ before.0 + 1.0,+ "the eraser came along"+ );+ h.state_mut().invoke(Cmd::AttachedOnly).unwrap();+ assert_eq!(h.state().picked.as_ref().unwrap().ids, vec![eraser]);+ pick(&mut h, vec![other]);+ assert!(+ h.state().can_run(Cmd::Detach).is_some(),+ "nothing attached to the other line"+ );+ pick(&mut h, vec![line]);+ h.state_mut().invoke(Cmd::Delete).unwrap();+ h.run_steps(2);+ assert!(+ stroke_on(&h, line).is_none() && stroke_on(&h, eraser).is_none(),+ "nothing left behind"+ );+ let _ = std::fs::remove_dir_all(&path);+}++#[test]+fn a_stroke_its_eraser_wiped_out_cannot_be_clicked_until_detached() {+ let path = sample("wiped");+ Bundle::open(&path)+ .unwrap()+ .apply(+ &parse_lines(+ r##"{"op":"stroke","layer":"l6","path":"M300 330 L320 330","size":6}+{"op":"stroke","layer":"l6","brush":"eraser","path":"M290 330 L330 330","size":60}"##,+ )+ .unwrap(),+ )+ .unwrap();+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));+ activate(&mut h, "lines");+ h.run_steps(3);+ let ids: Vec<u32> = h.state().scene.marks_of("c6").iter().map(|m| m.id()).collect();+ let wiped = ids[ids.len() - 2];+ h.key_press(Key::S);+ h.run_steps(2);+ let at = on_screen(&h, 310.0, 330.0);+ let click = |h: &mut Harness<'static, Editor>| {+ h.state_mut().picked = None;+ click_with(h, at, Modifiers::NONE);+ h.state().picked.as_ref().map(|p| p.ids.clone()).unwrap_or_default()+ };+ assert!(!click(&mut h).contains(&wiped), "a wiped stroke is not picked");+ h.state_mut().invoke(Cmd::SelectAll).unwrap();+ h.state_mut().invoke(Cmd::Detach).unwrap();+ h.run_steps(2);+ assert_eq!(+ click(&mut h),+ vec![wiped],+ "detached, it picks again like any stroke under an eraser"+ );+ let _ = std::fs::remove_dir_all(&path);+}+#[test]fn a_checkout_under_the_open_editor_shows_the_drawing_it_brings() {let path = sample("checkout");diff --git a/crates/core/src/markedit.rs b/crates/core/src/markedit.rsindex 7f602b7..161ccda 100644--- a/crates/core/src/markedit.rs+++ b/crates/core/src/markedit.rs@@ -495,7 +495,7 @@ pub fn pick(marks: &[Mark], at: (f32, f32), slack: f32, hidden: impl Fn(&Mark) -marks.iter().rev()- .find(|m| !hidden(m) && cut::keeps(m.cuts(), at) && touches(m, at, slack))+ .find(|m| cut::keeps(m.cuts(), at) && touches(m, at, slack) && !hidden(m)).map(Mark::id)};found(0.0).or_else(|| (slack > 0.0).then(|| found(slack)).flatten())