Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

klad repairs ids used twice

Indicode BV91df652d0c68
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4d54f21..3148d53 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.
+- 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.
- 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/home.rs b/crates/app/src/home.rs
index 57d1e02..c141b2a 100644
--- a/crates/app/src/home.rs
+++ b/crates/app/src/home.rs
@@ -58,6 +58,10 @@ pub(crate) struct Home {
menus_shown: Option<std::time::Instant>,
}
+fn used_twice(e: &anyhow::Error) -> bool {
+ e.downcast_ref::<klad_core::repair::UsedTwice>().is_some()
+}
+
impl Home {
fn new(cc: &eframe::CreationContext, path: Option<&Path>) -> Result<Self> {
let gpu = cc
@@ -108,6 +112,7 @@ impl Home {
let mut start = Start::new(&self.settings, Section::Open);
start.path = path.display().to_string();
start.error = Some(format!("opening {}: {e:#}", path.display()));
+ start.repair = used_twice(&e).then(|| path.to_path_buf());
self.start = Some(start);
}
}
@@ -118,6 +123,9 @@ impl Home {
.as_ref()
.map_or_else(|| self.settings.clone(), |e| e.settings.clone());
let mut editor = Editor::open(ctx.clone(), path)?;
+ if let Some(words) = self.start.as_mut().and_then(|s| s.repaired.take()) {
+ editor.say(Tone::Done, words);
+ }
settings.opened(path);
editor.settings = settings.clone();
editor.settings_path = self.settings_path.clone();
@@ -350,7 +358,10 @@ impl Home {
{
let message = format!("opening {}: {e:#}", path.display());
match (self.start.as_mut(), self.editor.as_mut()) {
- (Some(start), _) => start.error = Some(message),
+ (Some(start), _) => {
+ start.error = Some(message);
+ start.repair = used_twice(&e).then(|| path.clone());
+ }
(None, Some(editor)) => editor.error(message),
(None, None) => {}
}
@@ -616,6 +627,32 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
+ #[test]
+ fn a_drawing_with_an_id_used_twice_is_offered_a_repair() {
+ let dir = folder("twice");
+ let path = dir.join("merged.klad");
+ Bundle::blank(&path, &Blank { layers: 2, ..small() }, "cli").unwrap();
+ let doc = std::fs::read_to_string(path.join("doc.json")).unwrap();
+ std::fs::write(path.join("doc.json"), doc.replace("\"l3\"", "\"l1\"")).unwrap();
+ let mut start = home(&dir, &[]);
+ start.begin(&egui::Context::default(), Some(&path));
+ assert!(start.editor.is_none());
+ let error = start.start.as_ref().unwrap().error.clone().unwrap();
+ assert!(error.contains("used twice"), "{error}");
+ let mut h = harness(start);
+ h.get_by_label("Repair and open").click();
+ h.run_steps(3);
+ assert_eq!(opened(&h), path);
+ assert!(h.state().start.is_none());
+ assert!(
+ h.query_all_by_label_contains("repaired ids used twice")
+ .next()
+ .is_some()
+ );
+ assert!(Bundle::open(&path).is_ok());
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn cmd_n_and_cmd_o_in_the_editor_switch_drawings_and_back_keeps_this_one() {
let dir = folder("switch");
diff --git a/crates/app/src/start.rs b/crates/app/src/start.rs
index 4de6557..228b76f 100644
--- a/crates/app/src/start.rs
+++ b/crates/app/src/start.rs
@@ -52,6 +52,8 @@ pub struct Start {
pub sketch: bool,
pub path: String,
pub error: Option<String>,
+ pub repair: Option<PathBuf>,
+ pub repaired: Option<String>,
pub section: Section,
pub changed: bool,
pub samples: Vec<Sample>,
@@ -60,6 +62,15 @@ pub struct Start {
thumbs: BTreeMap<String, Thumb>,
}
+fn repaired_words(done: &klad_core::bundle::Repaired) -> String {
+ let names: Vec<String> = done
+ .renamed
+ .iter()
+ .map(|r| format!("{} \"{}\" ({} is now {})", r.what, r.name, r.from, r.to))
+ .collect();
+ format!("repaired ids used twice: {}", names.join(", "))
+}
+
impl Start {
pub fn new(settings: &Settings, section: Section) -> Self {
let blank = Blank::default();
@@ -76,6 +87,8 @@ impl Start {
sketch: true,
path: String::new(),
error: None,
+ repair: None,
+ repaired: None,
section,
changed: false,
samples: samples::shipped(),
@@ -239,9 +252,22 @@ impl Start {
});
});
});
- if let Some(error) = &self.error {
+ if let Some(error) = self.error.clone() {
ui.add_space(4.0);
ui.colored_label(theme::ERROR, error);
+ if let Some(path) = self.repair.clone()
+ && ui.button("Repair and open").clicked()
+ {
+ match klad_core::bundle::Bundle::repair(&path) {
+ Ok(done) => {
+ self.repaired = Some(repaired_words(&done));
+ self.error = None;
+ self.repair = None;
+ chosen = Some(path);
+ }
+ Err(e) => self.error = Some(format!("{e:#}")),
+ }
+ }
}
ui.add_space(10.0);
chosen = chosen.take().or_else(|| self.recent_section(ui, settings));
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index e6477e3..e46c1fc 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -1709,6 +1709,14 @@ enum Command {
},
#[command(about = "Paint cels with stroke counts and file sizes")]
Info { bundle: PathBuf },
+ #[command(
+ about = "Give every layer, drawing or shape whose id is used twice (after a merge) a new id, moving its files along"
+ )]
+ Repair {
+ bundle: PathBuf,
+ #[arg(long)]
+ json: bool,
+ },
#[command(about = "List the strokes and fills of a paint layer's cel at a frame")]
Strokes {
bundle: PathBuf,
@@ -3479,6 +3487,7 @@ fn run() -> Result<()> {
scale,
} => history::diff(&bundle, step, frame, scale)?,
Command::Info { bundle } => info(&bundle)?,
+ Command::Repair { bundle, json } => repair(&bundle, json)?,
Command::Strokes {
bundle,
layer,
@@ -3709,6 +3718,27 @@ pub fn copy_tag(doc: &klad_core::doc::Document) -> String {
}
}
+fn repair(path: &Path, as_json: bool) -> Result<()> {
+ let repaired = Bundle::repair(path)?;
+ if as_json {
+ println!("{}", serde_json::to_string_pretty(&repaired)?);
+ return Ok(());
+ }
+ if repaired.renamed.is_empty() {
+ println!("nothing to repair: every id is used once");
+ return Ok(());
+ }
+ repaired
+ .renamed
+ .iter()
+ .for_each(|r| println!("{} {:?}: {} is now {}", r.what, r.name, r.from, r.to));
+ repaired
+ .files
+ .iter()
+ .for_each(|f| println!("{} {} to {}", if f.copied { "copied" } else { "moved" }, f.from, f.to));
+ Ok(())
+}
+
fn info(path: &Path) -> Result<()> {
let bundle = Bundle::open(path)?;
let doc = &bundle.doc;
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index aff51a5..5ffba55 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -384,3 +384,46 @@ fn a_checkout_under_the_cache_renders_the_drawing_it_brings() {
);
std::fs::remove_dir_all(&dir).unwrap();
}
+
+#[test]
+fn a_merge_that_left_an_id_used_twice_is_repaired() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-repair-{}", 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", "200", "--height", "100", "--layers", "2"]);
+ draw(&["stroke", path, "l1", "--path", "M10 10 L190 90"]);
+ draw(&["stroke", path, "l3", "--path", "M10 90 L190 10"]);
+ let doc = std::fs::read_to_string(bundle.join("doc.json")).unwrap();
+ std::fs::write(bundle.join("doc.json"), doc.replace("\"l3\"", "\"l1\"")).unwrap();
+ std::fs::rename(
+ bundle.join("strokes/l3/c4.strokes"),
+ bundle.join("strokes/l1/c4.strokes"),
+ )
+ .unwrap();
+ let refused = run(&["info", path]);
+ let said = String::from_utf8_lossy(&refused.stderr);
+ assert!(
+ !refused.status.success() && said.contains("id l1 is used twice") && said.contains("klad repair"),
+ "{said}"
+ );
+ let repaired = draw(&["repair", path]);
+ assert!(repaired.contains("layer \"paint 2\": l1 is now l5"), "{repaired}");
+ assert!(
+ repaired.contains("moved strokes/l1/c4.strokes to strokes/l5/c4.strokes"),
+ "{repaired}"
+ );
+ let info = draw(&["info", path]);
+ assert!(
+ info.contains("l1 c2") && info.contains("l5 c4") && info.matches("1 strokes").count() == 2,
+ "{info}"
+ );
+ assert!(draw(&["repair", path]).contains("nothing to repair"));
+ std::fs::remove_dir_all(&dir).unwrap();
+}
diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rs
index 22ae17b..cafe79b 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -5,6 +5,7 @@ use crate::history::checkpoint;
use crate::markedit::{self, LassoAction, MarkChange};
use crate::migrate::migrate;
use crate::ops::{Applied, ClipEdit, FillSpec, Op, PendingMarks, apply_all};
+use crate::repair;
use crate::stroke::{Mark, Stroke, decode_cel, encode_cel, strokes_of};
use crate::timing::{CelAction, FrameSpec};
use anyhow::{Context, Result, bail};
@@ -78,6 +79,19 @@ pub fn now_ms() -> u64 {
.map_or(0, |d| d.as_millis() as u64)
}
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
+pub struct Moved {
+ pub from: String,
+ pub to: String,
+ pub copied: bool,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
+pub struct Repaired {
+ pub renamed: Vec<repair::Renamed>,
+ pub files: Vec<Moved>,
+}
+
pub struct Bundle {
pub root: PathBuf,
pub doc: Document,
@@ -117,6 +131,15 @@ fn name_parts(doc: &mut Document, pending: &[PendingMarks]) {
impl Bundle {
pub fn open(root: impl AsRef<Path>) -> Result<Self> {
+ let bundle = Self::read(root)?;
+ bundle
+ .doc
+ .validate()
+ .with_context(|| format!("checking {}", bundle.root.join("doc.json").display()))?;
+ Ok(bundle)
+ }
+
+ fn read(root: impl AsRef<Path>) -> Result<Self> {
let root = root.as_ref().to_path_buf();
remember(&root);
let seen = here::fingerprint(&root);
@@ -128,7 +151,6 @@ impl Bundle {
let (rev, next) = (counted("rev"), counted("nextId"));
let value = migrate(raw).with_context(|| format!("opening {}", root.display()))?;
let mut doc: Document = serde_json::from_value(value).with_context(|| format!("reading {}", path.display()))?;
- doc.validate().with_context(|| format!("checking {}", path.display()))?;
let (mut state, fresh) = here::load(&root);
state.rev = state.rev.max(rev);
state.next = state.next.max(next).max(highest_number(&doc));
@@ -141,6 +163,70 @@ impl Bundle {
Ok(Self { root, doc, seen })
}
+ pub fn repair(root: impl AsRef<Path>) -> Result<Repaired> {
+ let mut bundle = Self::read(root)?;
+ let before = repair::cel_files(&bundle.doc);
+ let renamed = repair::ids(&mut bundle.doc);
+ bundle
+ .doc
+ .validate()
+ .with_context(|| format!("checking {}", bundle.root.join("doc.json").display()))?;
+ if renamed.is_empty() {
+ return Ok(Repaired::default());
+ }
+ let after = repair::cel_files(&bundle.doc);
+ let used = |layer: &str, cel: Option<&str>| {
+ after
+ .iter()
+ .any(|(l, cels)| l == layer && cel.is_none_or(|c| cels.iter().any(|x| x == c)))
+ };
+ let moves: Vec<(PathBuf, PathBuf, bool)> = before
+ .iter()
+ .zip(&after)
+ .flat_map(|((old, old_cels), (new, new_cels))| {
+ old_cels
+ .iter()
+ .zip(new_cels)
+ .map(|(from, to)| {
+ (
+ bundle.strokes_path(old, from),
+ bundle.strokes_path(new, to),
+ used(old, Some(from)),
+ )
+ })
+ .chain((old != new).then(|| (bundle.weights_path(old), bundle.weights_path(new), used(old, None))))
+ .collect::<Vec<_>>()
+ })
+ .filter(|(from, to, _)| from != to && from.is_file())
+ .collect();
+ let relative = |p: &Path| {
+ p.strip_prefix(&bundle.root)
+ .unwrap_or(p)
+ .to_string_lossy()
+ .replace('\\', "/")
+ };
+ let files = moves
+ .iter()
+ .map(|(from, to, keep)| {
+ if let Some(parent) = to.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ match keep {
+ true => fs::copy(from, to).map(|_| ())?,
+ false => fs::rename(from, to)?,
+ }
+ Ok(Moved {
+ from: relative(from),
+ to: relative(to),
+ copied: *keep,
+ })
+ })
+ .collect::<Result<Vec<_>>>()?;
+ bundle.save()?;
+ bundle.stamp("repair")?;
+ Ok(Repaired { renamed, files })
+ }
+
pub fn brush_path(&self, id: &str) -> PathBuf {
self.root.join("brushes").join(format!("{id}.json"))
}
@@ -787,6 +873,69 @@ mod tests {
fs::remove_dir_all(&dir).unwrap();
}
+ #[test]
+ fn a_drawing_with_an_id_used_twice_is_refused_then_repaired() {
+ use crate::ops::parse_lines;
+ let dir = scratch("twice");
+ let mut doc = Document::new(64, 64);
+ doc.layers.push(Layer::paint("l48qa", "mine", "c49qa"));
+ doc.layers.push(Layer::paint("l70", "theirs", "c50qa"));
+ doc.next_id = 70;
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ bundle
+ .apply(
+ &parse_lines(
+ r#"{"op":"stroke","layer":"l48qa","path":"M1 1 L60 60"}
+{"op":"stroke","layer":"l70","path":"M60 1 L1 60"}
+{"op":"stroke","layer":"l70","path":"M30 1 L30 60"}"#,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let text = fs::read_to_string(dir.join("doc.json"))
+ .unwrap()
+ .replace("\"l70\"", "\"l48qa\"");
+ fs::write(dir.join("doc.json"), text).unwrap();
+ fs::rename(
+ dir.join("strokes/l70/c50qa.strokes"),
+ dir.join("strokes/l48qa/c50qa.strokes"),
+ )
+ .unwrap();
+ let refused = Bundle::open(&dir).err().unwrap();
+ assert!(refused.downcast_ref::<repair::UsedTwice>().is_some(), "{refused:#}");
+ assert!(
+ format!("{refused:#}").contains("id l48qa is used twice: klad repair"),
+ "{refused:#}"
+ );
+ let repaired = Bundle::repair(&dir).unwrap();
+ let to = repaired.renamed[0].to.clone();
+ assert_eq!(
+ (repaired.renamed[0].what, repaired.renamed[0].name.as_str()),
+ ("layer", "theirs")
+ );
+ assert_eq!(
+ repaired.files,
+ vec![Moved {
+ from: "strokes/l48qa/c50qa.strokes".into(),
+ to: format!("strokes/{to}/c50qa.strokes"),
+ copied: false
+ }]
+ );
+ let opened = Bundle::open(&dir).unwrap();
+ assert_eq!(opened.read_marks("l48qa", "c49qa").unwrap().len(), 1);
+ assert_eq!(
+ opened.read_marks(&to, "c50qa").unwrap().len(),
+ 2,
+ "their strokes came along"
+ );
+ assert_eq!(
+ Bundle::repair(&dir).unwrap(),
+ Repaired::default(),
+ "nothing left to repair"
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn drawings_from_before_keep_their_ids_and_count_on() {
let dir = scratch("before");
diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rs
index c5b3868..45814df 100644
--- a/crates/core/src/doc.rs
+++ b/crates/core/src/doc.rs
@@ -1315,7 +1315,7 @@ impl Document {
bail!("id {id:?} may only use letters, digits, - and _");
}
if !seen.insert(id) {
- bail!("id {id} is used twice");
+ return Err(anyhow::Error::new(crate::repair::UsedTwice).context(format!("id {id} is used twice")));
}
Ok(())
})?;
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 6a3a526..1bac434 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -17,6 +17,7 @@ pub mod ops;
pub mod patch;
pub mod path;
pub mod pathedit;
+pub mod repair;
pub mod retime;
pub mod rig;
pub mod rng;
diff --git a/crates/core/src/repair.rs b/crates/core/src/repair.rs
new file mode 100644
index 0000000..bb8f983
--- /dev/null
+++ b/crates/core/src/repair.rs
@@ -0,0 +1,209 @@
+use crate::doc::{Document, Layer, LayerContent, Node};
+use serde::Serialize;
+use std::collections::BTreeSet;
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
+pub struct Renamed {
+ pub what: &'static str,
+ pub from: String,
+ pub to: String,
+ pub name: String,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct UsedTwice;
+
+impl std::fmt::Display for UsedTwice {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "klad repair gives every later one a new id")
+ }
+}
+
+impl std::error::Error for UsedTwice {}
+
+fn layers_mut(layers: &mut [Layer], f: &mut dyn FnMut(&mut Layer)) {
+ layers.iter_mut().for_each(|layer| {
+ f(layer);
+ if let Some(mask) = layer.mask.as_deref_mut() {
+ f(mask);
+ }
+ if let LayerContent::Group { children } = &mut layer.content {
+ layers_mut(children, f);
+ }
+ });
+}
+
+fn nodes_mut(nodes: &mut [Node], f: &mut dyn FnMut(&mut Node)) {
+ nodes.iter_mut().for_each(|node| {
+ f(node);
+ if let Some(children) = node.shape.children_mut() {
+ nodes_mut(children, f);
+ }
+ });
+}
+
+fn follow(slot: &mut Option<String>, renames: &[(String, String)], kept: &dyn Fn(&str) -> bool) {
+ if let Some(id) = slot.as_mut() {
+ follow_id(id, renames, kept);
+ }
+}
+
+fn follow_id(id: &mut String, renames: &[(String, String)], kept: &dyn Fn(&str) -> bool) {
+ if let Some((_, to)) = renames.iter().find(|(from, _)| from == id && !kept(from)) {
+ *id = to.clone();
+ }
+}
+
+pub fn ids(doc: &mut Document) -> Vec<Renamed> {
+ let mut taken = doc.ids();
+ let mut seen = BTreeSet::new();
+ let mut out = Vec::new();
+ let mut layers = std::mem::take(&mut doc.layers);
+ layers_mut(&mut layers, &mut |layer| {
+ if !seen.insert(layer.id.clone()) {
+ let to = doc.alloc_id_in('l', &mut taken);
+ out.push(Renamed {
+ what: "layer",
+ from: std::mem::replace(&mut layer.id, to.clone()),
+ to,
+ name: layer.name.clone(),
+ });
+ }
+ });
+ layers_mut(&mut layers, &mut |layer| {
+ let name = layer.name.clone();
+ let Some(cels) = layer.cels_mut() else {
+ return;
+ };
+ let mut renames = Vec::new();
+ cels.iter_mut().for_each(|cel| {
+ if !seen.insert(cel.id.clone()) {
+ let to = doc.alloc_id_in('c', &mut taken);
+ let from = std::mem::replace(&mut cel.id, to.clone());
+ out.push(Renamed {
+ what: "drawing",
+ from: from.clone(),
+ to: to.clone(),
+ name: format!("{name}, frame {}", cel.frame),
+ });
+ renames.push((from, to));
+ }
+ });
+ let here: BTreeSet<String> = cels.iter().map(|c| c.id.clone()).collect();
+ let kept = |id: &str| here.contains(id);
+ cels.iter_mut().for_each(|cel| {
+ follow(&mut cel.link, &renames, &kept);
+ if let Some(tween) = cel.tween.as_mut() {
+ follow_id(&mut tween.from, &renames, &kept);
+ follow_id(&mut tween.to, &renames, &kept);
+ }
+ if let Some(pose) = cel.pose.as_mut() {
+ follow_id(&mut pose.rest, &renames, &kept);
+ }
+ });
+ });
+ layers_mut(&mut layers, &mut |layer| {
+ let Some(cels) = layer.cels_mut() else {
+ return;
+ };
+ cels.iter_mut().for_each(|cel| {
+ let mut renames = Vec::new();
+ nodes_mut(&mut cel.nodes, &mut |node| {
+ if !seen.insert(node.id.clone()) {
+ let to = doc.alloc_id_in('n', &mut taken);
+ let from = std::mem::replace(&mut node.id, to.clone());
+ out.push(Renamed {
+ what: "shape",
+ from: from.clone(),
+ to: to.clone(),
+ name: match node.name.is_empty() {
+ true => node.type_name().to_string(),
+ false => node.name.clone(),
+ },
+ });
+ renames.push((from, to));
+ }
+ });
+ if renames.is_empty() {
+ return;
+ }
+ let mut here = BTreeSet::new();
+ nodes_mut(&mut cel.nodes, &mut |node| {
+ here.insert(node.id.clone());
+ });
+ nodes_mut(&mut cel.nodes, &mut |node| {
+ follow(&mut node.clip, &renames, &|id: &str| here.contains(id));
+ });
+ });
+ });
+ doc.layers = layers;
+ out
+}
+
+pub fn cel_files(doc: &Document) -> Vec<(String, Vec<String>)> {
+ doc.all_layers()
+ .iter()
+ .map(|l| (l.id.clone(), l.cels().iter().map(|c| c.id.clone()).collect()))
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::doc::{Cel, Shape};
+
+ fn square(id: &str) -> Node {
+ Node::new(
+ id,
+ Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: 4.0,
+ h: 4.0,
+ radius: 0.0,
+ },
+ )
+ }
+
+ #[test]
+ fn the_first_keeps_its_id_and_every_later_one_gets_a_new_one() {
+ let mut doc = Document::new(64, 64);
+ doc.layers.push(Layer::paint("l48qa", "mine", "c49qa"));
+ let mut theirs = Layer::paint("l48qa", "theirs", "c49qa");
+ if let Some(cels) = theirs.cels_mut() {
+ cels.push(Cel {
+ link: Some("c49qa".into()),
+ ..Cel::at("c50qa", 4)
+ });
+ }
+ doc.layers.push(theirs);
+ doc.layers.push(Layer::vector(
+ "l60",
+ "shapes",
+ "c61",
+ vec![square("n62"), square("n62")],
+ ));
+ doc.next_id = 62;
+ assert!(doc.validate().unwrap_err().to_string().contains("used twice"));
+ let renamed = ids(&mut doc);
+ doc.validate().unwrap();
+ assert_eq!(
+ renamed
+ .iter()
+ .map(|r| (r.what, r.from.as_str(), r.to.as_str()))
+ .collect::<Vec<_>>(),
+ vec![
+ ("layer", "l48qa", "l63"),
+ ("drawing", "c49qa", "c64"),
+ ("shape", "n62", "n65")
+ ]
+ );
+ assert_eq!(doc.layers[0].id, "l48qa", "the first one keeps it");
+ assert_eq!(
+ doc.layers[1].cels()[1].link.as_deref(),
+ Some("c64"),
+ "a link in its own layer follows it"
+ );
+ assert!(ids(&mut doc).is_empty(), "nothing left to repair");
+ }
+}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 2557b60..851942d 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -152,7 +152,7 @@ Committed: everything except `.cache/`. A fresh clone rebuilds the cache by repl
- **Masks.** `mask` is a paint layer kept under the layer it masks, with its own id, cels and stroke files (`strokes/<mask id>/<cel>.strokes`). Its alpha hides the layer: strokes and fills on the mask hide, the eraser shows the layer again, and an empty mask (or a frame without a mask cel) hides nothing. `visible: false` turns the mask off. A mask keeps opacity 1 and blend normal and has no mask or clip of its own. Paint, vector and group layers can have one. Internally a mask's layer path ends in `MASK`, so `locate`, `layer_at` and the history treat it as a layer.
- **Clipping.** `clip: true` shows a layer only where its base, the nearest layer below it in the same list without `clip`, has alpha. The base and the clipped layers above it draw as one group: each clipped layer blends onto the base with its own blend and opacity (masked by the base's alpha), then the group composites onto what is below with the base's blend and opacity, as in Photoshop with "blend clipped layers as group". A hidden base hides its clipped layers; the lowest layer of a list draws unclipped.
- **Lock alpha.** `lockAlpha: true` on a paint layer makes new strokes and fills land only where the layer already has alpha: they composite source-atop and leave alpha unchanged. The flag is recorded on each stroke and fill (stroke format 5), so turning it off later never changes what was drawn. An eraser stroke on a lock-alpha layer changes nothing (the editor refuses it).
-- Nothing in `doc.json` changes on a write that does not change the drawing (`klad/5`, 2026-11-09): the revision and the id counter live in `.cache/copy.json`, so a stroke edit changes its stroke file only and git diffs and merges what was edited. Each copy of a drawing (a clone or a worktree: a folder without `.cache/copy.json`) picks a two-letter tag when klad first opens it; new layer, cel and node ids end in it (`l48qa`) and new mark ids carry it in their top 10 bits (`c12:s349qa`), and its counters only go up, so copies edited apart never make the same id, even across a branch switch in one copy. The copy a drawing is made in, and samples copied out, have no tag. `klad info` names the tag. `klad/1` (2026-11-06) is the first `.klad` format and starts clean: drawings from before it (`.draw` folders, `draw-anything/0` to `/9`, stroke files marked `DAST`) are refused on open with the reason and not converted (`migrate.rs` keeps the place where later migrations go). From here on a format change bumps the number and migrates older `.klad` drawings on open; history snapshots go through the same migration when undone. `klad/2` (2026-11-07) added IK (`ik` on skeletons and in poses); a `klad/1` drawing opens as it is, renamed. `klad/3` (2026-11-08) added `bone` on paint layers, attaching a layer to one bone; older drawings open as they are. `klad/4` (2026-11-08) moved skeletons to bones layers that any paint layer joins through `rig` (follow a bone, or bend); drawings from before open with their rigs dropped (Kevin's call: rigs were new and untested), their drawings kept. History patches never carry the change, because they are diffs of documents already migrated in memory. From 1.0 the format promise holds: every change migrates and nothing is dropped; `tests/formats/<version>/` keeps small copies of the samples saved by each release (`just formats <version>`, `packaging/formats.sh`) with each frame's hash, and `crates/cli/tests/formats.rs` opens every one with today's build and compares the renders. `tests/formats/pre-1.0/` holds the samples as built before 1.0 (five drawings in `klad/1` and `klad/4`).
+- Nothing in `doc.json` changes on a write that does not change the drawing (`klad/5`, 2026-11-09): the revision and the id counter live in `.cache/copy.json`, so a stroke edit changes its stroke file only and git diffs and merges what was edited. Each copy of a drawing (a clone or a worktree: a folder without `.cache/copy.json`) picks a two-letter tag when klad first opens it; new layer, cel and node ids end in it (`l48qa`) and new mark ids carry it in their top 10 bits (`c12:s349qa`), and its counters only go up, so copies edited apart never make the same id, even across a branch switch in one copy. The copy a drawing is made in, and samples copied out, have no tag. `klad info` names the tag. A drawing that still has an id used twice (two copies with the same tag, or a doc.json merged by hand) is refused on open with `repair::UsedTwice`; `klad repair` and the start window's **Repair and open** run `Bundle::repair`: in document order the first one keeps the id and every later layer, drawing or shape gets a new id from this copy, references inside its own layer (links, in-betweens, poses) or drawing (clips) follow it unless the old id is still there, and its stroke and weights files move, or are copied when the first one still uses the same file. References from other layers (a rig's skeleton) stay with the first. It is not an undo step: the drawing before it would not open. `klad/1` (2026-11-06) is the first `.klad` format and starts clean: drawings from before it (`.draw` folders, `draw-anything/0` to `/9`, stroke files marked `DAST`) are refused on open with the reason and not converted (`migrate.rs` keeps the place where later migrations go). From here on a format change bumps the number and migrates older `.klad` drawings on open; history snapshots go through the same migration when undone. `klad/2` (2026-11-07) added IK (`ik` on skeletons and in poses); a `klad/1` drawing opens as it is, renamed. `klad/3` (2026-11-08) added `bone` on paint layers, attaching a layer to one bone; older drawings open as they are. `klad/4` (2026-11-08) moved skeletons to bones layers that any paint layer joins through `rig` (follow a bone, or bend); drawings from before open with their rigs dropped (Kevin's call: rigs were new and untested), their drawings kept. History patches never carry the change, because they are diffs of documents already migrated in memory. From 1.0 the format promise holds: every change migrates and nothing is dropped; `tests/formats/<version>/` keeps small copies of the samples saved by each release (`just formats <version>`, `packaging/formats.sh`) with each frame's hash, and `crates/cli/tests/formats.rs` opens every one with today's build and compares the renders. `tests/formats/pre-1.0/` holds the samples as built before 1.0 (five drawings in `klad/1` and `klad/4`).
### Edits
diff --git a/docs/cli.md b/docs/cli.md
index 5f65838..f4ab1c7 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -69,6 +69,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
- [`klad notes`](#klad-notes): Notes the human pinned on the canvas; --done <id> marks one as handled, --clear-done removes the handled ones
- [`klad diff`](#klad-diff): Before and after renders of a change, side by side (default: the last one)
- [`klad info`](#klad-info): Paint cels with stroke counts and file sizes
+- [`klad repair`](#klad-repair): Give every layer, drawing or shape whose id is used twice (after a merge) a new id, moving its files along
- [`klad strokes`](#klad-strokes): List the strokes and fills of a paint layer's cel at a frame
- [`klad hash`](#klad-hash): Print pixel hashes, for comparing macOS and Linux renders
- [`klad demo`](#klad-demo): Write a sample bundle (vector sky and hills, painted glow, clouds, hatching, grass)
@@ -3266,6 +3267,25 @@ Options:
Print help
```
+## klad repair
+
+```text
+Give every layer, drawing or shape whose id is used twice (after a merge) a new id, moving its files along
+
+Usage: klad repair [OPTIONS] <BUNDLE>
+
+Arguments:
+ <BUNDLE>
+
+
+Options:
+ --json
+
+
+ -h, --help
+ Print help
+```
+
## klad strokes
```text
diff --git a/docs/format.md b/docs/format.md
index 3e4198d..1beb05c 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -30,7 +30,7 @@ Writers replace files atomically (write a temporary file, then rename), so a rea
- **Coordinates** are canvas pixels, origin at the top left, y down. Angles are degrees; positive turns clockwise on screen.
- **Colours** are `"#rrggbb"` or `"#rrggbbaa"`: sRGB, straight (not premultiplied) alpha.
-- **Ids** are unique across the whole document and use letters, digits, `-` and `_`. Ids are case sensitive. klad makes new ones from a prefix (`l` layer, `c` cel, `n` node), a number, and the tag of the copy that made them: `l48qa`. Each copy of a drawing (a clone, a git worktree: any folder without `.cache/copy.json`) picks a two-letter tag the first time klad opens it and keeps it in `.cache/copy.json`, with counters that only go up, so two copies edited apart never make the same id; the copy a drawing was made in has no tag (`l48`). A folder copied by hand with its `.cache/` keeps the tag: delete `.cache/` in the copy to give it its own. Ids already in a drawing never change. Writers that make their own ids should do the same or use a long random part.
+- **Ids** are unique across the whole document and use letters, digits, `-` and `_`. Ids are case sensitive. klad makes new ones from a prefix (`l` layer, `c` cel, `n` node), a number, and the tag of the copy that made them: `l48qa`. Each copy of a drawing (a clone, a git worktree: any folder without `.cache/copy.json`) picks a two-letter tag the first time klad opens it and keeps it in `.cache/copy.json`, with counters that only go up, so two copies edited apart never make the same id; the copy a drawing was made in has no tag (`l48`). A folder copied by hand with its `.cache/` keeps the tag: delete `.cache/` in the copy to give it its own. Ids already in a drawing never change. Writers that make their own ids should do the same or use a long random part. A drawing with an id used twice does not open; `klad repair` gives every later one a new id.
- **JSON** is UTF-8, written pretty with a stable key order. Keys at their default value are left out; readers must take the defaults listed below for missing keys. Most objects reject keys they do not know, so writers must not add their own.
- **Versions.** `format` names the version of `doc.json` and everything it implies; this is `klad/5`. Each version opens the older `klad/` drawings and migrates them in memory (written back on the next change). A reader that meets a newer version than it knows should refuse to write the bundle. Drawings from before `klad/1` (`.draw` folders, formats `draw-anything/0` to `/9`) do not open.
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index f43b53d..5db4374 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -59,7 +59,7 @@ klad stroke art.klad l4 --brush ink --size 5 --taper 8,20 --path 'M100 100 L140
## Editing strokes and fills
-Every stroke and fill has an address `<cel>:s<id>` (fills share the id counter with strokes). `klad strokes art.klad <layer>` lists them with the cel id on top. In a clone or worktree of a drawing, new ids end in that copy's two-letter tag (`l48qa`, `c12:s349qa`, shown by `klad info`); use them as printed, and the `address` field in JSON.
+Every stroke and fill has an address `<cel>:s<id>` (fills share the id counter with strokes). `klad strokes art.klad <layer>` lists them with the cel id on top. In a clone or worktree of a drawing, new ids end in that copy's two-letter tag (`l48qa`, `c12:s349qa`, shown by `klad info`); use them as printed, and the `address` field in JSON. If a drawing refuses to open with "id ... is used twice" (after a git merge), run `klad repair art.klad`: it renames every later one and says what it renamed.
```
klad set art.klad c4:s12 color=#c84a3a size=6 brush=pencil