A drawing app built for agent/human collaboration
Rust
Recolouring several strokes keeps each one's shade
Indicode BV99e47dad59d7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3148d53..8b7236a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,7 +5,7 @@The first builds, and klad's licences.- Drawings are `.klad` folders in a fresh format, `klad/5` (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.-- Drawings live well in git: an edit changes only the files of what it edits (`doc.json` keeps no revision or id counter), and copies of a drawing edited apart, in a clone or a worktree, never make the same id, so edits to different layers merge. New ids end in the copy's two-letter tag (`l48qa`, `c12:s349qa`); `klad info` shows it. The editor follows a `git checkout` of an open drawing, and klad never renders an old picture from its cache after one. If a merge still leaves an id used twice, `klad repair` (or **Repair and open** when the drawing won't open) gives every later one a new id and moves its stroke files along.+- Drawings live well in git: an edit changes only the files of what it edits (`doc.json` keeps no revision or id counter), and copies of a drawing edited apart, in a clone or a worktree, never make the same id, so edits to different layers merge. New ids end in the copy's two-letter tag (`l48qa`, `c12:s349qa`); `klad info` shows it. The editor follows a `git checkout` of an open drawing, and klad never renders an old picture from its cache after one. Recolouring several strokes or fills at once (the selection bar in the editor, or `klad recolour`) moves them to the new colour together and keeps each one's own shade, so a painted-over area stays painted. If a merge still leaves an id used twice, `klad repair` (or **Repair and open** when the drawing won't open) gives every later one a new id and moves its stroke files along.- klad is source-available, not open source: the app is under the PolyForm Internal Use License 1.0.0, with permission for personal use (building from source is free for it), to propose contributions and to share the drawings you make (`LICENSE`). Companies with 100,000 euros or more in revenue a year buy a licence for each person who uses klad; a bought build is that licence, under the same terms. The file format (`docs/format.md`), the command reference (`docs/cli.md`), the agent skill and the new `klad-client` crate are MIT (`LICENSE-MIT`), so any program or agent can read, write and make klad drawings. Contributions come in under a contributor licence agreement (`CLA.md`).- `klad-client`: run klad from Rust, apply edits as JSON ops, read drawings back as JSON, render them.- Builds for macOS (an app, Apple silicon and Intel in one) and Windows, sold on itch.io; Linux from source. Each has the `klad` command line, the editor, the fonts, the licences and the agent skill.diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 18519eb..5f6aaf7 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -3465,11 +3465,13 @@ impl Editor {}fn recolour_picked(&mut self) -> Result<()> {- let hex = color::hex(self.color);+ let target = self.color;let sets = self.chosen_marks().map_or(Vec::new(), |(_, chosen)| {- chosen- .iter()- .map(|(cel, m)| (cel.clone(), m.id(), "color", json!(hex)))+ let colours: Vec<_> = chosen.iter().map(|(_, m)| m.color()).collect();+ klad_core::color::recolour(&colours, target)+ .into_iter()+ .zip(&chosen)+ .map(|(c, (cel, m))| (cel.clone(), m.id(), "color", json!(klad_core::color::to_hex(c)))).collect()});self.set_picked(sets)diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 4639714..3e1c387 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -1889,6 +1889,52 @@ fn v_picks_and_drags_the_stroke_under_the_pen_and_alt_drags_a_copy() {let _ = std::fs::remove_dir_all(&path);}+#[test]+fn recolouring_several_strokes_keeps_each_ones_shade() {+ let path = sample("recolour");+ Bundle::open(&path)+ .unwrap()+ .apply(+ &parse_lines(+ r##"{"op":"stroke","layer":"l6","path":"M100 100 L300 100","color":"#2f5a30","size":20}+{"op":"stroke","layer":"l6","path":"M100 200 L300 200","color":"#a8dc84","size":20}"##,+ )+ .unwrap(),+ )+ .unwrap();+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));+ h.run_steps(3);+ let ids: Vec<u32> = h+ .state()+ .scene+ .marks_of("c6")+ .iter()+ .rev()+ .take(2)+ .map(|m| m.id())+ .collect();+ h.state_mut().tool = Tool::Strokes;+ h.state_mut().picked = Some(super::Picked {+ cel: "c6".into(),+ ids: ids.clone(),+ cut: None,+ more: Vec::new(),+ });+ h.state_mut().color = klad_core::color::parse_hex("#e3962f").unwrap();+ h.state_mut().invoke(Cmd::Recolour).unwrap();+ h.run_steps(2);+ let after: Vec<[f32; 3]> = ids+ .iter()+ .map(|id| {+ let marks = h.state().scene.bundle.read_marks("l6", "c6").unwrap();+ klad_core::color::to_oklab(marks.iter().find(|m| m.id() == *id).unwrap().color())+ })+ .collect();+ assert!(after[0][0] > after[1][0], "the light stroke stays lighter: {after:?}");+ assert!(after.iter().all(|lab| lab[2] > 0.05), "both turned warm: {after:?}");+ 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/cli/src/main.rs b/crates/cli/src/main.rsindex e46c1fc..0b9d62b 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -518,6 +518,18 @@ enum Command {#[command(flatten)]flags: EditFlags,},+ #[command(+ about = "Recolour strokes and fills together: the group moves to the colour and each keeps its own lighter or darker shade",+ long_about = "Recolour strokes and fills together. The group's average colour moves to --to and every mark keeps its own difference from that average (in OKLab: lighter, darker, warmer, cooler), so painted strokes stay painted. One mark takes the colour as it is. One history step.\n\n klad recolour art.klad c9:s12 c9:s13 c9:s40 --to '#e3962f'\n klad recolour art.klad c9:s12 c9:s13 --to skin"+ )]+ Recolour {+ bundle: PathBuf,+ ids: Vec<String>,+ #[arg(long, help = "The colour: #rrggbb or a palette name")]+ to: String,+ #[command(flatten)]+ flags: EditFlags,+ },#[command(about = "Remove layers, cels or nodes")]Rm {bundle: PathBuf,@@ -2336,6 +2348,10 @@ fn run() -> Result<()> {};agent::edit(&bundle, &[op], &output(&flags, frame))?;}+ Command::Recolour { bundle, ids, to, flags } => {+ let ops = recolour_ops(&bundle, &ids, &to)?;+ agent::edit(&bundle, &ops, &output(&flags, 0))?;+ }Command::Rm { bundle, ids, flags } => {if ids.is_empty() {return Err(anyhow!("give the ids to remove"));@@ -3718,6 +3734,44 @@ pub fn copy_tag(doc: &klad_core::doc::Document) -> String {}}+fn recolour_ops(path: &Path, ids: &[String], to: &str) -> Result<Vec<Op>> {+ if ids.is_empty() {+ return Err(anyhow!("give the strokes and fills to recolour, as <cel>:s<id>"));+ }+ let bundle = Bundle::open(path)?;+ let target = klad_core::color::parse_hex(&bundle.doc.resolve_color(to)?)?;+ let owner = |cel: &str| {+ bundle+ .doc+ .all_layers()+ .iter()+ .find(|l| l.cels().iter().any(|c| c.id == cel))+ .map(|l| l.id.clone())+ .ok_or_else(|| anyhow!("no drawing {cel}"))+ };+ let colours = ids+ .iter()+ .map(|id| {+ let (cel, mark) = klad_core::markedit::parse_address(id)+ .ok_or_else(|| anyhow!("{id} is not a stroke or fill: use <cel>:s<id>"))?;+ let marks = bundle.read_marks(&owner(cel)?, cel)?;+ marks+ .iter()+ .find(|m| m.id() == mark)+ .map(klad_core::stroke::Mark::color)+ .ok_or_else(|| anyhow!("{id} does not exist"))+ })+ .collect::<Result<Vec<_>>>()?;+ Ok(klad_core::color::recolour(&colours, target)+ .into_iter()+ .zip(ids)+ .map(|(c, id)| Op::Set {+ id: id.clone(),+ props: serde_json::Map::from_iter([("color".to_string(), serde_json::json!(klad_core::color::to_hex(c)))]),+ })+ .collect())+}+fn repair(path: &Path, as_json: bool) -> Result<()> {let repaired = Bundle::repair(path)?;if as_json {diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex 5ffba55..66c2438 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -427,3 +427,33 @@ fn a_merge_that_left_an_id_used_twice_is_repaired() {assert!(draw(&["repair", path]).contains("nothing to repair"));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()));+ 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()+ };+ draw(&["new", path, "--width", "200", "--height", "100"]);+ draw(&["stroke", path, "l1", "--path", "M10 10 L190 10", "--color", "#2f5a30"]);+ draw(&["stroke", path, "l1", "--path", "M10 50 L190 50", "--color", "#a8dc84"]);+ draw(&["recolour", path, "c2:s1", "c2:s2", "--to", "#e3962f"]);+ let listed: serde_json::Value = serde_json::from_str(&draw(&["strokes", path, "l1", "--json"])).unwrap();+ let colours: Vec<String> = listed["strokes"]+ .as_array()+ .unwrap()+ .iter()+ .map(|s| s["color"].as_str().unwrap().to_string())+ .collect();+ let lab = |hex: &str| klad_core::color::to_oklab(klad_core::color::parse_hex(hex).unwrap());+ assert!(lab(&colours[0])[0] < lab(&colours[1])[0], "{colours:?}");+ assert!(colours.iter().all(|c| lab(c)[2] > 0.05), "both warm now: {colours:?}");+ let log = draw(&["log", path]);+ assert_eq!(log.matches("cli").count(), 3, "one history step: {log}");+ std::fs::remove_dir_all(&dir).unwrap();+}diff --git a/crates/core/src/color.rs b/crates/core/src/color.rsindex e621776..710a0b7 100644--- a/crates/core/src/color.rs+++ b/crates/core/src/color.rs@@ -82,10 +82,57 @@ pub fn value_step(c: Rgba, by: f32) -> Rgba {from_oklab([(l + by).clamp(0.0, 1.0), a + by * 0.03, b + by * 0.15], c[3])}+pub fn recolour(colours: &[Rgba], target: Rgba) -> Vec<Rgba> {+ let n = colours.len().max(1) as f32;+ let labs: Vec<[f32; 4]> = colours+ .iter()+ .map(|c| {+ let [l, a, b] = to_oklab(*c);+ [l, a, b, c[3]]+ })+ .collect();+ let mean = labs.iter().fold([0.0; 4], |m, v| [0, 1, 2, 3].map(|i| m[i] + v[i] / n));+ let [gl, ga, gb] = to_oklab(target);+ let goal = [gl, ga, gb, target[3]];+ labs.iter()+ .map(|v| {+ let [l, a, b, alpha] = [0, 1, 2, 3].map(|i| goal[i] + v[i] - mean[i]);+ from_oklab([l.clamp(0.0, 1.0), a, b], alpha.clamp(0.0, 1.0)).map(|c| c.clamp(0.0, 1.0))+ })+ .collect()+}+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn a_recolour_moves_the_group_and_keeps_each_shade() {+ let greens = ["#3f6a3a", "#79b85a", "#a8dc84"].map(|h| parse_hex(h).unwrap());+ let amber = parse_hex("#e3962f").unwrap();+ let moved = recolour(&greens, amber);+ let light = |c: &Rgba| to_oklab(*c)[0];+ assert!(+ light(&moved[0]) < light(&moved[1]) && light(&moved[1]) < light(&moved[2]),+ "the shades keep their order"+ );+ let mean = moved+ .iter()+ .map(|c| to_oklab(*c))+ .fold([0.0; 3], |m, l| [0, 1, 2].map(|i| m[i] + l[i] / 3.0));+ let goal = to_oklab(amber);+ assert!(+ (0..3).all(|i| (mean[i] - goal[i]).abs() < 0.02),+ "the group's middle lands on the colour: {mean:?} {goal:?}"+ );+ assert!(moved.iter().all(|c| to_oklab(*c)[2] > 0.05), "every stroke turned warm");+ assert_eq!(+ to_hex(recolour(&greens[..1], amber)[0]),+ "#e3962f",+ "one mark takes the colour as it is"+ );+ }+#[test]fn parses_short_and_alpha_forms() {assert_eq!(parse_hex("#ff0000").unwrap(), [1.0, 0.0, 0.0, 1.0]);diff --git a/crates/core/src/stroke.rs b/crates/core/src/stroke.rsindex 8775dbf..4e10d76 100644--- a/crates/core/src/stroke.rs+++ b/crates/core/src/stroke.rs@@ -322,6 +322,13 @@ impl From<Fill> for Mark {}impl Mark {+ pub fn color(&self) -> Rgba {+ match self {+ Mark::Stroke(s) => s.color(),+ Mark::Fill(f) => f.color(),+ }+ }+pub fn id(&self) -> u32 {match self {Mark::Stroke(s) => s.id,diff --git a/docs/cli.md b/docs/cli.mdindex f4ab1c7..8de5f65 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -27,6 +27,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it- [`klad show`](#klad-show): One layer, cel, node, stroke or fill (<cel>:s<id>) in full (JSON)- [`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 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@@ -929,6 +930,43 @@ Options:Print help (see a summary with '-h')```+## klad recolour++```text+Recolour strokes and fills together. The group's average colour moves to --to and every mark keeps its own difference from that average (in OKLab: lighter, darker, warmer, cooler), so painted strokes stay painted. One mark takes the colour as it is. One history step.++ klad recolour art.klad c9:s12 c9:s13 c9:s40 --to '#e3962f'+ klad recolour art.klad c9:s12 c9:s13 --to skin++Usage: klad recolour [OPTIONS] --to <TO> <BUNDLE> [IDS]...++Arguments:+ <BUNDLE>+++ [IDS]...+++Options:+ --to <TO>+ The colour: #rrggbb or a palette name++ --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```textdiff --git a/docs/guide/selecting.md b/docs/guide/selecting.mdindex 690883f..da42d8c 100644--- a/docs/guide/selecting.md+++ b/docs/guide/selecting.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-08 14:50_+_Last updated: 2026-11-09 12:23_# Changing strokes@@ -18,7 +18,7 @@ To pick on every layer instead of only the active one, switch the bar over the c## Change what you selected-Drag inside the box to move it, a corner to scale it and the knob to turn it. The bar next to the selection recolours it with the current colour, makes strokes thinner or thicker, duplicates it (**cmd D**) and deletes it (**Backspace**).+Drag inside the box to move it, a corner to scale it and the knob to turn it. The bar next to the selection recolours it with the current colour, makes strokes thinner or thicker, duplicates it (**cmd D**) and deletes it (**Backspace**). Recolouring several strokes keeps each one's own lighter or darker shade, so a painted area stays painted.## Bend a strokediff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 5db4374..368e130 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -64,6 +64,7 @@ Every stroke and fill has an address `<cel>:s<id>` (fills share the id counter w```klad set art.klad c4:s12 color=#c84a3a size=6 brush=pencilklad set art.klad c4:s7 color=skin opacity=0.8+klad recolour art.klad c4:s12 c4:s13 c4:s40 --to '#e3962f' # several at once, each keeps its shadeklad rm art.klad c4:s12 c4:s13klad transform art.klad c4:s3 c4:s5 --move 40,-10 --rotate 15 --scale 1.2klad transform art.klad --layer figure --move -120,0 # a whole layer or group: every drawing, its shapes, bones and poses