A drawing app built for agent/human collaboration
Rust
Drawings that live in git: klad/5
Indicode BVd30f7a7361dd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7ecee6e..4d54f21 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,8 @@The first builds, and klad's licences.-- Drawings are `.klad` folders in a fresh format, `klad/4` (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 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.- 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/composite.rs b/crates/app/src/composite.rsindex 4165b40..57b81e1 100644--- a/crates/app/src/composite.rs+++ b/crates/app/src/composite.rs@@ -14,7 +14,7 @@ use klad_core::look::Effect;use klad_core::ops::{Applied, Op, apply_all};use klad_core::patch::{Patch, diff};use klad_core::rng::{FNV_OFFSET, fnv};-use klad_core::stroke::{Mark, Stroke, decode_cel, encode_cel, next_id};+use klad_core::stroke::{Mark, Stroke, decode_cel, encode_cel};use klad_render::onion::{self, Ghost, Onion, Onions};use klad_render::{Rasters, Swap, SwapTiles, TileItem, TileJob, compose_tile, fill_reference, flatten_with, rasterize_nodes,@@ -1281,6 +1281,7 @@ impl Scene {rev: doc.rev,bundle: Bundle {root: self.bundle.root.clone(),+ seen: self.bundle.seen,doc: doc.clone(),},rasters,@@ -1642,7 +1643,8 @@ impl Scene {}pub fn next_mark_id(&self) -> u32 {- next_id(self.active_marks())+ let cel = self.active_cel().unwrap_or_default();+ self.bundle.doc.mark_ids(&cel).next(self.active_marks())}pub fn commit_stroke(@@ -1817,6 +1819,7 @@ impl Scene {Some(FrameJob {bundle: Bundle {root: self.bundle.root.clone(),+ seen: self.bundle.seen,doc: doc.clone(),},paint: paint.into_iter().filter(|(_, c)| !self.cels.contains_key(c)).collect(),@@ -1981,6 +1984,7 @@ impl Scene {rev: doc.rev,bundle: Bundle {root: self.bundle.root.clone(),+ seen: self.bundle.seen,doc: doc.clone(),},rasters,@@ -2013,6 +2017,7 @@ impl Scene {rev: doc.rev,bundle: Bundle {root: self.bundle.root.clone(),+ seen: self.bundle.seen,doc: doc.clone(),},rasters: Rasters::new(),@@ -2240,16 +2245,12 @@ impl Scene {let bytes = encode_cel(data.marks())?;write_atomic(&self.bundle.strokes_path(&layer, &cel), &bytes)?;data.file_hash = fnv(FNV_OFFSET, &bytes);+ self.bundle.doc.note_marks(&cel, data.marks());self.bundle.save()?;self.bundle.stamp("editor")?;Ok(bytes.len())}- pub fn disk_rev(&self) -> Option<u64> {- let text = fs::read_to_string(self.bundle.root.join("doc.json")).ok()?;- serde_json::from_str::<serde_json::Value>(&text).ok()?["rev"].as_u64()- }-pub fn reload(&mut self, brushes: &BrushSet) -> Result<Vec<usize>> {let old = self.bundle.doc.clone();self.bundle.reload()?;@@ -2360,6 +2361,7 @@ impl Scene {rev: self.bundle.doc.rev,bundle: Bundle {root: self.bundle.root.clone(),+ seen: self.bundle.seen,doc: self.bundle.doc.clone(),},frame: self.frame,@@ -3237,12 +3239,11 @@ mod tests {assert_eq!(other.rasters["cb"].hash(), scene.rasters["cb"].hash());assert!(scene.step(klad_core::history::Stack::Undo, &brushes).unwrap().is_some());assert_eq!(scene.rasters["cb"].hash(), before);- let rev = scene.bundle.doc.rev;let mut outside = Bundle::open(&dir).unwrap();let ops =klad_core::ops::parse_lines(r#"{"op":"stroke","layer":"a","path":"M10 10 L200 100","size":12}"#).unwrap();outside.apply(&ops).unwrap();- assert_eq!(scene.disk_rev(), Some(rev + 1));+ assert!(scene.bundle.changed_on_disk());let dirty = scene.reload(&brushes).unwrap();assert!(!dirty.is_empty() && dirty.len() < scene.all_tiles().len(), "{dirty:?}");assert_eq!(scene.cels["ca"].marks().len(), 31);diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 8488bae..18519eb 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -988,7 +988,7 @@ impl Editor {{return Ok(());}- if self.scene.disk_rev() == Some(self.scene.bundle.doc.rev) {+ if !self.scene.bundle.changed_on_disk() {self.external = None;return Ok(());}@@ -1197,10 +1197,10 @@ impl Editor {fn refresh_cut(&mut self) {let rev = self.scene.bundle.doc.rev;- let Some((key, polygon, ids, more)) = self.picked.as_ref().and_then(|p| {+ let Some((key, cel, polygon, ids, more)) = self.picked.as_ref().and_then(|p| {p.cut.clone()- .map(|polygon| (p.key(), polygon, p.ids.clone(), p.more.clone()))+ .map(|polygon| (p.key(), p.cel.clone(), polygon, p.ids.clone(), p.more.clone()))}) else {self.cut_view = None;return;@@ -1208,9 +1208,10 @@ impl Editor {if self.cut_view.as_ref().is_some_and(|v| v.key == key && v.rev == rev) {return;}- let split = |source: &[Mark], ids: Vec<u32>| {+ let doc = &self.scene.bundle.doc;+ let split = |cel: &str, source: &[Mark], ids: Vec<u32>| {let mut marks = source.to_vec();- let lassoed = markedit::split(&mut marks, &polygon, true);+ let lassoed = markedit::split(&mut marks, &polygon, true, doc.mark_ids(cel));let chosen: Vec<u32> = lassoed.iter().copied()@@ -1218,11 +1219,11 @@ impl Editor {.collect();(marks, lassoed, chosen)};- let (marks, lassoed, chosen) = split(self.scene.active_marks(), ids);+ let (marks, lassoed, chosen) = split(&cel, self.scene.active_marks(), ids);let more = more.into_iter().map(|p| {- let (marks, lassoed, chosen) = split(self.scene.marks_of(&p.cel), p.ids);+ let (marks, lassoed, chosen) = split(&p.cel, self.scene.marks_of(&p.cel), p.ids);PartView {layer: p.layer,cel: p.cel,diff --git a/crates/app/src/editor/between.rs b/crates/app/src/editor/between.rsindex c3a46b0..63e6d18 100644--- a/crates/app/src/editor/between.rs+++ b/crates/app/src/editor/between.rs@@ -387,8 +387,9 @@ impl Editor {self.say(Tone::Done,format!(- "{}:s{} pairs with {cel}:s{id}; making the in-betweens again",- pick.cel, pick.id+ "{} pairs with {}; making the in-betweens again",+ klad_core::markedit::address(&pick.cel, pick.id),+ klad_core::markedit::address(&cel, id)),);self.make_inbetweens(request);diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 98a9e43..4639714 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -1889,6 +1889,26 @@ fn v_picks_and_drags_the_stroke_under_the_pen_and_alt_drags_a_copy() {let _ = std::fs::remove_dir_all(&path);}+#[test]+fn a_checkout_under_the_open_editor_shows_the_drawing_it_brings() {+ let path = sample("checkout");+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));+ h.run_steps(3);+ let file = path.join("strokes/l6/c6.strokes");+ let before = std::fs::read(&file).unwrap();+ let marks = h.state().scene.marks_of("c6").len();+ Bundle::open(&path)+ .unwrap()+ .apply(&parse_lines(r#"{"op":"stroke","layer":"l6","path":"M100 100 L300 300"}"#).unwrap())+ .unwrap();+ settle(&mut h, |ed| ed.scene.marks_of("c6").len() == marks + 1);+ std::fs::write(&file, &before).unwrap();+ settle(&mut h, |ed| {+ ed.scene.marks_of("c6").len() == marks && !ed.scene.bundle.changed_on_disk()+ });+ let _ = std::fs::remove_dir_all(&path);+}+#[test]fn an_agent_edit_while_the_editor_is_open_shows_in_the_history_and_keeps_its_author() {let path = sample("agent-row");@@ -1902,8 +1922,7 @@ fn an_agent_edit_while_the_editor_is_open_shows_in_the_history_and_keeps_its_aut.apply(&parse_lines(r#"{"op":"stroke","layer":"l6","path":"M100 100 L300 300"}"#).unwrap()).unwrap();settle(&mut h, |ed| {- ed.scene.bundle.read_marks("l6", "c6").unwrap().len() == 3- && ed.scene.disk_rev() == Some(ed.scene.bundle.doc.rev)+ ed.scene.bundle.read_marks("l6", "c6").unwrap().len() == 3 && !ed.scene.bundle.changed_on_disk()});h.run_steps(2);let first = |h: &mut Harness<'static, Editor>| {diff --git a/crates/app/src/preview.rs b/crates/app/src/preview.rsindex 9b5609a..bb0cc17 100644--- a/crates/app/src/preview.rs+++ b/crates/app/src/preview.rs@@ -110,10 +110,10 @@ impl Job {.ok_or_else(|| anyhow!("cel {} is not in memory", pending.cel))?;let mut replay = replay.clone();let mut marks = replay.marks().to_vec();- pending- .changes- .iter_mut()- .try_for_each(|change| snap.bundle.apply_change(&plan, &mut marks, change, &pending.cel))?;+ pending.changes.iter_mut().try_for_each(|change| {+ snap.bundle+ .apply_change(&snap.bundle.doc, &plan, &mut marks, change, &pending.cel)+ })?;let mut raster = rasters.get(&pending.cel).cloned().unwrap_or_else(|| Raster::new(w, h));changed.extend(replay.update(&mut raster, marks, &snap.brushes)?.tiles);rasters.insert(pending.cel.clone(), raster);diff --git a/crates/app/src/sync.rs b/crates/app/src/sync.rsindex 48d7a2a..807a176 100644--- a/crates/app/src/sync.rs+++ b/crates/app/src/sync.rs@@ -12,7 +12,11 @@ pub struct Watch {pub fn relevant(path: &Path) -> bool {let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");!name.contains(".tmp-")- && (name == "doc.json" || name == "sync.json" || name == "notes.json" || name.ends_with(".strokes"))+ && (name == "doc.json"+ || name == "sync.json"+ || name == "notes.json"+ || name.ends_with(".strokes")+ || name.ends_with(".weights"))}pub fn watch(root: &Path, ctx: egui::Context) -> Result<Watch> {@@ -42,6 +46,7 @@ mod tests {assert!(relevant(Path::new("a.klad/.cache/sync.json")));assert!(relevant(Path::new("a.klad/.cache/notes.json")));assert!(relevant(Path::new("a.klad/strokes/l1/c0.strokes")));+ assert!(relevant(Path::new("a.klad/weights/l1.weights")));assert!(!relevant(Path::new("a.klad/doc.json.tmp-123")));assert!(!relevant(Path::new("a.klad/.cache/tiles/l1.raster")));}diff --git a/crates/brush/src/replay.rs b/crates/brush/src/replay.rsindex 9356794..25a6341 100644--- a/crates/brush/src/replay.rs+++ b/crates/brush/src/replay.rs@@ -556,7 +556,7 @@ mod tests {let mut out = marks.to_vec();changes.into_iter()- .for_each(|mut c| markedit::apply(&mut out, &mut c, "c1").unwrap());+ .for_each(|mut c| markedit::apply(&mut out, &mut c, "c1", Default::default()).unwrap());out}@@ -790,7 +790,7 @@ mod tests {let polygon = vec![[300.0, 200.0], [620.0, 220.0], [600.0, 520.0], [280.0, 480.0]];let before = replay(W, H, &all, &brushes()).unwrap().raster;let mut split = all.clone();- let chosen = markedit::split(&mut split, &polygon, true);+ let chosen = markedit::split(&mut split, &polygon, true, Default::default());assert!(chosen.len() > all.len() / 10, "{} chosen", chosen.len());let unmoved = replay(W, H, &split, &brushes()).unwrap().raster;let far = |x: usize, y: usize| !(270..=630).contains(&x) || !(190..=530).contains(&y);diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rsindex 94da176..0e3ca41 100644--- a/crates/cli/src/agent.rs+++ b/crates/cli/src/agent.rs@@ -197,7 +197,7 @@ pub fn render_path(bundle: &Bundle, frame: u32, view: View, tag: &str) -> PathBubundle.cache_dir().join("renders")- .join(format!("r{}{frame}{region}{scale}{tag}.png", bundle.doc.rev))+ .join(format!("r{:016x}{frame}{region}{scale}{tag}.png", bundle.seen))}#[derive(Default)]@@ -895,6 +895,7 @@ pub fn ls(path: &Path, frame: u32, as_json: bool) -> Result<()> {"canvas": doc.canvas,"timeline": doc.timeline,"rev": doc.rev,+ "copy": doc.here.tag,"frame": frame,"layers": layers,});@@ -913,8 +914,11 @@ pub fn ls(path: &Path, frame: u32, as_json: bool) -> Result<()> {.as_deref().map_or(String::new(), |b| format!(" background {b}"));println!(- "{}x{} rev {}{timing}{background}",- doc.canvas.width, doc.canvas.height, doc.rev+ "{}x{} rev {}{timing}{background}{}",+ doc.canvas.width,+ doc.canvas.height,+ doc.rev,+ crate::copy_tag(doc));layers.iter().rev().for_each(|l| print_layer(l, 0, t.frames));Ok(())diff --git a/crates/cli/src/colour.rs b/crates/cli/src/colour.rsindex a46d7e4..4148375 100644--- a/crates/cli/src/colour.rs+++ b/crates/cli/src/colour.rs@@ -8,7 +8,7 @@ use klad_core::doc::{Document, Kind};use klad_core::fill::{Fill, FillRef, FillSource};use klad_core::markedit::address;use klad_core::ops::FillSpec;-use klad_core::stroke::{Author, Mark, next_id};+use klad_core::stroke::{Author, Mark};use klad_render::{Rasters, View, compose, fill_reference};use rayon::prelude::*;use serde_json::json;@@ -160,7 +160,7 @@ pub fn like(bundle: &Bundle, spec: &mut FillSpec) -> Result<Vec<String>> {}let id = match place {Some(_) => fill.id,- None if out.iter().any(|m| m.id() == fill.id) => next_id(&out),+ None if out.iter().any(|m| m.id() == fill.id) => bundle.doc.mark_ids(cel).next(&out),None => fill.id,};let made = Mark::Fill(Fill {@@ -334,7 +334,7 @@ fn gap_render(bundle: &Bundle, found: &FrameGaps, rasters_from: &BrushSet) -> Relet path = bundle.cache_dir().join("renders")- .join(format!("r{}-gaps-f{}.png", doc.rev, found.frame));+ .join(format!("r{:016x}-gaps-f{}.png", bundle.seen, found.frame));write_atomic(&path, &image.png()?)?;Ok(path)}diff --git a/crates/cli/src/edit.rs b/crates/cli/src/edit.rsindex 597a3a7..bee618b 100644--- a/crates/cli/src/edit.rs+++ b/crates/cli/src/edit.rs@@ -2,7 +2,7 @@ use anyhow::{Context, Result, bail};use klad_core::bundle::{Blank, Bundle, now_ms};use klad_core::color::parse_hex;use klad_core::doc::{Cel, Kind};-use klad_core::stroke::{Mark, marks, next_id};+use klad_core::stroke::{Mark, marks};use klad_core::synth::Synth;use notify::{Config, PollWatcher, RecursiveMode, Watcher};use std::path::Path;@@ -103,7 +103,7 @@ pub fn scribble(path: &Path, opts: Scribble) -> Result<()> {.id.clone();let mut strokes = bundle.read_marks(&layer, &cel)?;- let next = next_id(&strokes);+ let next = bundle.doc.mark_ids(&cel).next(&strokes);let (w, h) = (bundle.doc.canvas.width as f32, bundle.doc.canvas.height as f32);let mut synth = Synth::canvas(w, h);synth.brushes = vec!["ink".into()];diff --git a/crates/cli/src/fills.rs b/crates/cli/src/fills.rsindex 1e557c9..07afb2b 100644--- a/crates/cli/src/fills.rs+++ b/crates/cli/src/fills.rs@@ -83,11 +83,10 @@ impl Running<'_> {}let stored = self.stored[&pending.cel].clone();let mut marks = stored.clone();- pending- .changes- .clone()- .iter_mut()- .try_for_each(|c| self.bundle.apply_change(&applied.marks, &mut marks, c, &pending.cel))?;+ pending.changes.clone().iter_mut().try_for_each(|c| {+ self.bundle+ .apply_change(&self.bundle.doc, &applied.marks, &mut marks, c, &pending.cel)+ })?;let before = self.painted.get(&pending.cel).cloned().unwrap_or(stored);let (w, h) = (doc.canvas.width, doc.canvas.height);let raster = selfdiff --git a/crates/cli/src/inbetween.rs b/crates/cli/src/inbetween.rsindex d459406..9907910 100644--- a/crates/cli/src/inbetween.rs+++ b/crates/cli/src/inbetween.rs@@ -708,6 +708,7 @@ fn compute(let accept = accept_colours(bundle, keys, &brushes)?;let view = Bundle {root: bundle.root.clone(),+ seen: bundle.seen,doc: staged.clone(),};let frames: BTreeSet<u32> = jobs.iter().map(|j| j.frame).collect();diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 7e92996..e6477e3 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -3702,12 +3702,25 @@ fn hash(path: &Path, frame: u32, use_cache: bool) -> Result<()> {Ok(())}+pub fn copy_tag(doc: &klad_core::doc::Document) -> String {+ match doc.here.tag.as_str() {+ "" => String::new(),+ tag => format!(" copy {tag} (new ids end in {tag})"),+ }+}+fn info(path: &Path) -> Result<()> {let bundle = Bundle::open(path)?;let doc = &bundle.doc;println!(- "{}x{} rev {} {} {} frames at {} fps",- doc.canvas.width, doc.canvas.height, doc.rev, doc.format, doc.timeline.frames, doc.timeline.fps+ "{}x{} rev {} {} {} frames at {} fps{}",+ doc.canvas.width,+ doc.canvas.height,+ doc.rev,+ doc.format,+ doc.timeline.frames,+ doc.timeline.fps,+ copy_tag(doc));doc.all_layers().iter()@@ -3757,11 +3770,10 @@ fn strokes(path: &Path, layer: &str, frame: u32, after: u32, as_json: bool) -> Rreturn Ok(());}println!(- "cel {}: address a stroke or fill as {}:s<id>, for example {}:s{}",- cel.id,+ "cel {}: address a stroke or fill as {}:s<id>, for example {}",cel.id,cel.id,- marks.first().map_or(1, |m| m.id())+ klad_core::markedit::address(&cel.id, marks.first().map_or(1, |m| m.id())));if !strokes.is_empty() {println!("id author brush size samples ms Hz pressure tilt bounds");@@ -3781,7 +3793,7 @@ fn strokes(path: &Path, layer: &str, frame: u32, after: u32, as_json: bool) -> Rlet [x0, y0, x1, y1] = s.bounds().unwrap_or_default();println!("{:<6} {:<6} {:<7} {:>5.1} {:>8} {:>5} {:>5.0} {lo:.2}-{hi:.2} {tilt:>7.2} {x0:.0},{y0:.0} {:.0}x{:.0}{}{part}",- format!("s{}", s.id),+ klad_core::doc::mark_name(s.id),s.author.name(),s.brush,s.size,@@ -3812,7 +3824,7 @@ fn strokes(path: &Path, layer: &str, frame: u32, after: u32, as_json: bool) -> Rlet [x0, y0, x1, y1] = f.bounds().unwrap_or_default();println!(" {:<6} {:<6} {} {source:<35} {:>7} {x0:.0},{y0:.0} {:.0}x{:.0}{}{part}",- format!("s{}", f.id),+ klad_core::doc::mark_name(f.id),f.author.name(),hex8(f.color()),f.coverage.pixels(),diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex b1b0012..aff51a5 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -336,3 +336,51 @@ fn a_chain_and_its_ik_are_set_up_and_posed_from_the_command_line() {assert!(json[0]["poses"][0]["solved"]["thigh"].is_number());std::fs::remove_dir_all(&dir).unwrap();}++#[test]+fn a_checkout_under_the_cache_renders_the_drawing_it_brings() {+ let dir = std::env::temp_dir().join(format!("draw-binary-checkout-{}", 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 render = || {+ let printed = draw(&["render", path]);+ std::fs::read(printed.lines().last().unwrap().trim()).unwrap()+ };+ let files = || ["doc.json", "strokes/l1/c2.strokes"].map(|f| std::fs::read(bundle.join(f)).ok());+ let put = |kept: &[Option<Vec<u8>>; 2]| {+ ["doc.json", "strokes/l1/c2.strokes"]+ .iter()+ .zip(kept)+ .for_each(|(f, bytes)| match bytes {+ Some(bytes) => std::fs::write(bundle.join(f), bytes).unwrap(),+ None => {+ let _ = std::fs::remove_file(bundle.join(f));+ }+ });+ };+ draw(&["new", path, "--width", "200", "--height", "100"]);+ let base = files();+ draw(&["stroke", path, "l1", "--path", "M10 10 L190 90", "--size", "8"]);+ let one = files();+ let first = render();+ put(&base);+ draw(&["stroke", path, "l1", "--path", "M10 90 L190 10", "--size", "8"]);+ let other = render();+ assert_ne!(+ first, other,+ "the other branch, after as many edits, is not the first one's render"+ );+ put(&one);+ assert_eq!(+ render(),+ first,+ "checking the first branch out again renders it, not the cached other"+ );+ std::fs::remove_dir_all(&dir).unwrap();+}diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rsindex b7f4885..22ae17b 100644--- a/crates/core/src/bundle.rs+++ b/crates/core/src/bundle.rs@@ -1,5 +1,6 @@use crate::brushes::{self, BrushDef};use crate::doc::{Document, Layer, Loc};+use crate::here;use crate::history::checkpoint;use crate::markedit::{self, LassoAction, MarkChange};use crate::migrate::migrate;@@ -47,41 +48,28 @@ impl Default for Blank {}#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub struct Changed {- pub disk: u64,- pub here: u64,-}+pub struct Changed;impl std::fmt::Display for Changed {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {write!(f,- "the document changed while this edit was being made (rev {} on disk, {} when it started); nothing was written, run it again",- self.disk, self.here+ "the drawing changed on disk while this edit was being made; nothing was written, run it again")}}impl std::error::Error for Changed {}-pub fn disk_rev(root: &Path) -> Option<u64> {- let path = root.join("doc.json");- let mut head = vec![0u8; 4096];- let read = {- use std::io::Read;- fs::File::open(&path).ok()?.read(&mut head).ok()?- };- let text = String::from_utf8_lossy(&head[..read]);- let quick = text.find("\"rev\"").and_then(|at| {- let rest = text[at + 5..].trim_start().strip_prefix(':')?.trim_start();- let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();- let end = rest[digits.len()..].chars().next()?;- (!digits.is_empty() && matches!(end, ',' | '\n' | ' ' | '\r' | '}')).then(|| digits.parse().ok())?- });- quick.or_else(|| {- let text = fs::read_to_string(&path).ok()?;- serde_json::from_str::<serde_json::Value>(&text).ok()?["rev"].as_u64()- })+fn highest_number(doc: &Document) -> u64 {+ doc.ids()+ .iter()+ .filter_map(|id| {+ let digits: String = id.chars().skip(1).take_while(char::is_ascii_digit).collect();+ digits.parse().ok()+ })+ .max()+ .unwrap_or(0)}pub fn now_ms() -> u64 {@@ -93,6 +81,7 @@ pub fn now_ms() -> u64 {pub struct Bundle {pub root: PathBuf,pub doc: Document,+ pub seen: u64,}fn name_parts(doc: &mut Document, pending: &[PendingMarks]) {@@ -130,15 +119,26 @@ impl Bundle {pub fn open(root: impl AsRef<Path>) -> Result<Self> {let root = root.as_ref().to_path_buf();remember(&root);+ let seen = here::fingerprint(&root);let path = root.join("doc.json");let text = fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;let raw: serde_json::Value =serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;+ let counted = |key: &str| raw.get(key).and_then(serde_json::Value::as_u64).unwrap_or(0);+ let (rev, next) = (counted("rev"), counted("nextId"));let value = migrate(raw).with_context(|| format!("opening {}", root.display()))?;- let doc: Document = serde_json::from_value(value).with_context(|| format!("reading {}", path.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 bundle = Self { root, doc };- Ok(bundle)+ let (mut state, fresh) = here::load(&root);+ state.rev = state.rev.max(rev);+ state.next = state.next.max(next).max(highest_number(&doc));+ if fresh {+ let _ = here::write(&root, &state);+ }+ doc.rev = state.rev;+ doc.next_id = state.next;+ doc.here = state.here();+ Ok(Self { root, doc, seen })}pub fn brush_path(&self, id: &str) -> PathBuf {@@ -221,7 +221,9 @@ impl Bundle {remember(&root);fs::create_dir_all(&root)?;write_atomic(&root.join(".gitignore"), b".cache/\n")?;- let mut bundle = Self { root, doc };+ let mut doc = doc;+ doc.here = here::start().here();+ let mut bundle = Self { root, doc, seen: 0 };bundle.save()?;Ok(bundle)}@@ -251,10 +253,24 @@ impl Bundle {}pub fn save(&mut self) -> Result<()> {- self.doc.rev += 1;+ let disk = here::read(&self.root).filter(|s| s.tag == self.doc.here.tag);+ self.doc.rev = disk.as_ref().map_or(0, |s| s.rev).max(self.doc.rev) + 1;let mut text = serde_json::to_string_pretty(&self.doc)?;text.push('\n');- write_atomic(&self.root.join("doc.json"), text.as_bytes())+ write_atomic(&self.root.join("doc.json"), text.as_bytes())?;+ let state = here::write(&self.root, &here::State::of(&self.doc))?;+ self.doc.next_id = state.next;+ self.doc.here = state.here();+ self.settle();+ Ok(())+ }++ pub fn settle(&mut self) {+ self.seen = here::fingerprint(&self.root);+ }++ pub fn changed_on_disk(&self) -> bool {+ here::fingerprint(&self.root) != self.seen}pub fn strokes_path(&self, layer: &str, cel: &str) -> PathBuf {@@ -316,7 +332,7 @@ impl Bundle {pending.changes.iter_mut()- .try_for_each(|change| self.apply_change(&plan, &mut marks, change, &pending.cel))?;+ .try_for_each(|change| self.apply_change(&doc, &plan, &mut marks, change, &pending.cel))?;Ok((pending.layer.clone(), pending.cel.clone(), marks))}).collect::<Result<Vec<_>>>()?;@@ -336,6 +352,7 @@ impl Bundle {}Ok(())})?;+ written.iter().for_each(|(_, cel, marks)| doc.note_marks(cel, marks));let touched: Vec<PathBuf> = written.iter().map(|(layer, cel, _)| self.strokes_path(layer, cel))@@ -350,15 +367,16 @@ impl Bundle {weights.iter().try_for_each(|(layer, w)| write_atomic(&self.weights_path(layer), &w.encode()?))?;- self.save()?;applied.dropped_cels.iter().for_each(|(layer, cel)| {let _ = fs::remove_file(self.strokes_path(layer, cel));});+ self.save()?;Ok(applied)}pub fn apply_change(&self,+ doc: &Document,plan: &[PendingMarks],marks: &mut Vec<Mark>,change: &mut MarkChange,@@ -366,7 +384,7 @@ impl Bundle {) -> Result<()> {match change {MarkChange::Copy { layer, cel, upto } => {- *marks = self.marks_after(plan, layer, cel, *upto)?;+ *marks = self.marks_after(doc, plan, layer, cel, *upto)?;Ok(())}MarkChange::Paste {@@ -378,7 +396,7 @@ impl Bundle {let copies = sources.iter().map(|source| {- let from = self.marks_after(plan, &source.layer, &source.cel, source.upto)?;+ let from = self.marks_after(doc, plan, &source.layer, &source.cel, source.upto)?;source.ids.iter()@@ -396,21 +414,28 @@ impl Bundle {.into_iter().flatten().collect();- *made = markedit::paste(marks, copies, transform.as_ref(), cut.as_deref())?;+ *made = markedit::paste(marks, copies, transform.as_ref(), cut.as_deref(), doc.mark_ids(cel))?;Ok(())}- _ => markedit::apply(marks, change, cel),+ _ => markedit::apply(marks, change, cel, doc.mark_ids(cel)),}}- fn marks_after(&self, plan: &[PendingMarks], layer: &str, cel: &str, upto: usize) -> Result<Vec<Mark>> {+ fn marks_after(+ &self,+ doc: &Document,+ plan: &[PendingMarks],+ layer: &str,+ cel: &str,+ upto: usize,+ ) -> Result<Vec<Mark>> {let mut marks = self.read_marks(layer, cel)?;if let Some(pending) = plan.iter().find(|p| p.layer == layer && p.cel == cel) {pending.changes.iter().take(upto)- .try_for_each(|c| self.apply_change(plan, &mut marks, &mut c.clone(), cel))?;+ .try_for_each(|c| self.apply_change(doc, plan, &mut marks, &mut c.clone(), cel))?;}Ok(marks)}@@ -418,6 +443,7 @@ impl Bundle {pub fn replace_marks(&mut self, layer: &str, cel: &str, marks: &[Mark], author: &str, summary: &str) -> Result<()> {checkpoint(self, &self.doc, author, summary, &[self.strokes_path(layer, cel)])?;self.write_marks(layer, cel, marks)?;+ self.doc.note_marks(cel, marks);self.save()}@@ -426,18 +452,18 @@ impl Bundle {}pub fn reload(&mut self) -> Result<()> {- self.doc = Self::open(&self.root)?.doc;+ let rev = self.doc.rev;+ let opened = Self::open(&self.root)?;+ self.doc = opened.doc;+ self.doc.rev = self.doc.rev.max(rev + 1);+ self.seen = opened.seen;Ok(())}pub fn ensure_unchanged(&self) -> Result<()> {- match disk_rev(&self.root) {- Some(disk) if disk != self.doc.rev => Err(Changed {- disk,- here: self.doc.rev,- }- .into()),- _ => Ok(()),+ match self.changed_on_disk() {+ true => Err(Changed.into()),+ false => Ok(()),}}@@ -623,25 +649,163 @@ mod tests {doc.layers.push(Layer::paint("l1", "ink", "c1"));doc.next_id = 10;let mut first = Bundle::create(&dir, doc).unwrap();- assert_eq!(disk_rev(&dir), Some(first.doc.rev));let mut second = Bundle::open(&dir).unwrap();assert!(first.ensure_unchanged().is_ok());second.apply(&parse_lines(r#"{"op":"stroke","layer":"l1","path":"M1 1 L60 60"}"#).unwrap()).unwrap();- assert_eq!(disk_rev(&dir), Some(second.doc.rev));let refused = first.ensure_unchanged().unwrap_err();- assert_eq!(- refused.downcast_ref::<Changed>(),- Some(&Changed {- disk: second.doc.rev,- here: first.doc.rev- })- );+ assert_eq!(refused.downcast_ref::<Changed>(), Some(&Changed));+ let rev = first.doc.rev;first.reload().unwrap();assert!(first.ensure_unchanged().is_ok());- fs::write(dir.join("doc.json"), "{\n \"rev\":\n 99, \"format\": \"x\"}").unwrap();- assert_eq!(disk_rev(&dir), Some(99));+ assert!(first.doc.rev > rev, "a reload is a new revision for the caches");+ let checked_out = fs::read(first.strokes_path("l1", "c1")).unwrap();+ write_atomic(&first.strokes_path("l1", "c1"), &checked_out).unwrap();+ assert!(+ first.ensure_unchanged().is_err(),+ "a stroke file replaced from outside, as git checkout does, with doc.json untouched"+ );+ fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn edits_leave_the_lines_of_doc_json_they_did_not_change() {+ use crate::ops::parse_lines;+ let dir = scratch("lines");+ let mut bundle = Bundle::blank(+ &dir,+ &Blank {+ layers: 2,+ ..Blank::default()+ },+ "cli",+ )+ .unwrap();+ let read = || fs::read_to_string(dir.join("doc.json")).unwrap();+ assert!(!read().contains("\"rev\"") && !read().contains("nextId"), "{}", read());+ let before = read();+ bundle+ .apply(&parse_lines(r#"{"op":"stroke","layer":"l1","path":"M1 1 L60 60"}"#).unwrap())+ .unwrap();+ assert_eq!(read(), before, "a stroke changes its stroke file only");+ bundle+ .apply(&parse_lines(r#"{"op":"set","id":"l3","opacity":0.5}"#).unwrap())+ .unwrap();+ let after = read();+ let new: Vec<&str> = after.lines().filter(|l| !before.lines().any(|b| b == *l)).collect();+ assert_eq!(new, vec![" \"opacity\": 0.5,"], "only the opacity line: {after}");+ assert!(after.lines().count() - before.lines().count() <= 1);+ fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn copies_of_a_drawing_never_make_the_same_id() {+ use crate::ops::parse_lines;+ let made = scratch("copy-ids");+ let mut doc = Document::new(64, 64);+ doc.layers.push(Layer::paint("l1", "ink", "c1"));+ doc.next_id = 1;+ Bundle::create(&made, doc).unwrap();+ let edit = r#"{"op":"add","layer":{"kind":"paint","name":"more"}}+{"op":"stroke","layer":"l1","path":"M1 1 L60 60"}+{"op":"stroke","layer":"l1","path":"M2 1 L50 60"}"#;+ let copy = |n: usize| {+ let to = scratch(&format!("copy-ids-{n}"));+ fs::create_dir_all(to.join("strokes")).unwrap();+ fs::copy(made.join("doc.json"), to.join("doc.json")).unwrap();+ to+ };+ let ids = |dir: &Path| {+ let mut bundle = Bundle::open(dir).unwrap();+ bundle.apply(&parse_lines(edit).unwrap()).unwrap();+ let marks: Vec<u32> = bundle.read_marks("l1", "c1").unwrap().iter().map(Mark::id).collect();+ (bundle.doc.ids(), marks, bundle.doc.here.tag.clone())+ };+ let (mine, my_marks, my_tag) = ids(&made);+ assert_eq!(my_tag, "", "the copy it was made in keeps plain ids");+ assert!(mine.contains("l2") && my_marks == vec![1, 2], "{mine:?} {my_marks:?}");+ (0..40).for_each(|n| {+ let dir = copy(n);+ let (theirs, their_marks, tag) = ids(&dir);+ let fresh: Vec<&String> = theirs.difference(&mine).collect();+ assert_eq!(fresh.len(), 2, "{theirs:?}");+ assert!(+ fresh.iter().all(|id| id.ends_with(&tag) && !mine.contains(*id)),+ "{fresh:?} against {mine:?}"+ );+ assert!(their_marks.iter().all(|id| !my_marks.contains(id)), "{their_marks:?}");+ assert_eq!(+ their_marks+ .iter()+ .map(|id| markedit::address("c1", *id))+ .collect::<Vec<_>>(),+ vec![format!("c1:s1{tag}"), format!("c1:s2{tag}")]+ );+ let again = ids(&dir);+ assert_eq!(again.2, tag, "a copy keeps its tag");+ fs::remove_dir_all(&dir).unwrap();+ });+ fs::remove_dir_all(&made).unwrap();+ }++ #[test]+ fn a_copy_keeps_counting_after_a_branch_switch() {+ use crate::ops::parse_lines;+ let dir = scratch("branch");+ let mut doc = Document::new(64, 64);+ doc.layers.push(Layer::paint("l1", "ink", "c1"));+ doc.next_id = 1;+ let mut bundle = Bundle::create(&dir, doc).unwrap();+ let main_doc = fs::read(dir.join("doc.json")).unwrap();+ bundle+ .apply(+ &parse_lines(+ r#"{"op":"add","layer":{"kind":"paint","name":"branch"}}+{"op":"stroke","layer":"l1","path":"M1 1 L60 60"}"#,+ )+ .unwrap(),+ )+ .unwrap();+ fs::write(dir.join("doc.json"), &main_doc).unwrap();+ fs::remove_file(bundle.strokes_path("l1", "c1")).unwrap();+ let mut back = Bundle::open(&dir).unwrap();+ back.apply(+ &parse_lines(+ r#"{"op":"add","layer":{"kind":"paint","name":"main"}}+{"op":"stroke","layer":"l1","path":"M1 1 L60 60"}"#,+ )+ .unwrap(),+ )+ .unwrap();+ assert!(+ !back.doc.ids().contains("l2"),+ "l2 went to the other branch: {:?}",+ back.doc.ids()+ );+ assert_eq!(back.read_marks("l1", "c1").unwrap()[0].id(), 2);+ fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn drawings_from_before_keep_their_ids_and_count_on() {+ let dir = scratch("before");+ fs::create_dir_all(&dir).unwrap();+ fs::write(+ dir.join("doc.json"),+ r#"{"format": "klad/4", "rev": 31, "canvas": {"width": 64, "height": 64},+"layers": [{"id": "l6", "kind": "paint", "name": "ink", "cels": [{"id": "c12", "frame": 0}]}], "nextId": 12}"#,+ )+ .unwrap();+ let mut bundle = Bundle::open(&dir).unwrap();+ assert_eq!((bundle.doc.rev, bundle.doc.next_id), (31, 12));+ let id = bundle.doc.alloc_id('l');+ assert!(id.starts_with("l13") && id.len() == 5, "{id}");+ assert!(bundle.doc.locate("l6").is_some() && bundle.doc.locate("c12").is_some());+ bundle.save().unwrap();+ let text = fs::read_to_string(dir.join("doc.json")).unwrap();+ assert!(text.contains(crate::doc::FORMAT) && !text.contains("nextId"), "{text}");+ assert_eq!(Bundle::open(&dir).unwrap().doc.rev, 32);fs::remove_dir_all(&dir).unwrap();}diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rsindex e0f1586..c5b3868 100644--- a/crates/core/src/doc.rs+++ b/crates/core/src/doc.rs@@ -6,14 +6,15 @@ use serde::{Deserialize, Serialize};use std::borrow::Cow;use std::collections::{BTreeMap, BTreeSet};-pub const FORMAT: &str = "klad/4";+pub const FORMAT: &str = "klad/5";pub const MAX_SIZE: u32 = 16384;pub const MASK: usize = usize::MAX;-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[derive(Clone, Debug, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Document {pub format: String,+ #[serde(skip)]pub rev: u64,pub canvas: Canvas,#[serde(default)]@@ -25,8 +26,28 @@ pub struct Document {pub export: Exports,#[serde(default, skip_serializing_if = "Option::is_none")]pub atmosphere: Option<Atmosphere>,- #[serde(default)]+ #[serde(skip)]pub next_id: u64,+ #[serde(skip)]+ pub here: Here,+}++impl PartialEq for Document {+ fn eq(&self, other: &Self) -> bool {+ self.format == other.format+ && self.canvas == other.canvas+ && self.timeline == other.timeline+ && self.palette == other.palette+ && self.layers == other.layers+ && self.export == other.export+ && self.atmosphere == other.atmosphere+ }+}++#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Here {+ pub tag: String,+ pub marks: BTreeMap<String, u32>,}#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]@@ -793,6 +814,66 @@ fn find_in(layers: &[Layer], id: &str, path: &mut Vec<usize>) -> Option<Loc> {})}+pub const TAG_SHIFT: u32 = 22;+pub const MARK_NUMBER: u32 = (1 << TAG_SHIFT) - 1;++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct MarkIds {+ pub tag: u32,+ pub floor: u32,+}++impl MarkIds {+ pub fn next(&self, marks: &[crate::stroke::Mark]) -> u32 {+ let top = marks+ .iter()+ .map(crate::stroke::Mark::id)+ .filter(|id| id >> TAG_SHIFT == self.tag)+ .map(|id| id & MARK_NUMBER)+ .max()+ .unwrap_or(0);+ (self.tag << TAG_SHIFT) | (top.max(self.floor) + 1)+ }+}++pub fn tag_index(tag: &str) -> u32 {+ match tag.as_bytes() {+ [a, b] if a.is_ascii_lowercase() && b.is_ascii_lowercase() => 1 + (a - b'a') as u32 * 26 + (b - b'a') as u32,+ _ => 0,+ }+}++pub fn tag_letters(index: u32) -> Option<String> {+ (1..=26 * 26).contains(&index).then(|| {+ let i = index - 1;+ [b'a' + (i / 26) as u8, b'a' + (i % 26) as u8]+ .iter()+ .map(|&c| c as char)+ .collect()+ })+}++pub fn mark_name(id: u32) -> String {+ match tag_letters(id >> TAG_SHIFT) {+ Some(tag) => format!("s{}{tag}", id & MARK_NUMBER),+ None => format!("s{id}"),+ }+}++pub fn parse_mark(text: &str) -> Option<u32> {+ let rest = text.strip_prefix('s')?;+ let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len();+ let (number, tag) = rest.split_at(digits);+ let number: u32 = number.parse().ok()?;+ match tag {+ "" => Some(number),+ tag => {+ let index = tag_index(tag);+ (index > 0 && number <= MARK_NUMBER).then_some((index << TAG_SHIFT) | number)+ }+ }+}+pub fn valid_id(id: &str) -> bool {!id.is_empty() && id.len() <= 64 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')}@@ -943,6 +1024,7 @@ impl Document {export: Exports::default(),atmosphere: None,next_id: 0,+ here: Here::default(),}}@@ -974,13 +1056,34 @@ impl Document {pub fn alloc_id_in(&mut self, prefix: char, taken: &mut BTreeSet<String>) -> String {loop {self.next_id += 1;- let id = format!("{prefix}{}", self.next_id);+ let id = format!("{prefix}{}{}", self.next_id, self.here.tag);if taken.insert(id.clone()) {return id;}}}+ pub fn mark_ids(&self, cel: &str) -> MarkIds {+ MarkIds {+ tag: tag_index(&self.here.tag),+ floor: self.here.marks.get(cel).copied().unwrap_or(0),+ }+ }++ pub fn note_marks(&mut self, cel: &str, marks: &[crate::stroke::Mark]) {+ let ids = self.mark_ids(cel);+ let top = marks+ .iter()+ .map(crate::stroke::Mark::id)+ .filter(|id| id >> TAG_SHIFT == ids.tag)+ .map(|id| id & MARK_NUMBER)+ .max()+ .unwrap_or(0);+ if top > ids.floor {+ self.here.marks.insert(cel.to_string(), top);+ }+ }+pub fn locate(&self, id: &str) -> Option<Loc> {find_in(&self.layers, id, &mut Vec::new())}diff --git a/crates/core/src/here.rs b/crates/core/src/here.rsnew file mode 100644index 0000000..e9c1278--- /dev/null+++ b/crates/core/src/here.rs@@ -0,0 +1,217 @@+use crate::bundle::write_atomic;+use crate::doc::{Document, Here, tag_letters};+use crate::rng::{FNV_OFFSET, fnv};+use anyhow::Result;+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use std::fs;+use std::path::{Path, PathBuf};+use std::time::{SystemTime, UNIX_EPOCH};++#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct State {+ #[serde(default)]+ pub tag: String,+ #[serde(default)]+ pub rev: u64,+ #[serde(default)]+ pub next: u64,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub marks: BTreeMap<String, u32>,+}++impl State {+ pub fn of(doc: &Document) -> Self {+ Self {+ tag: doc.here.tag.clone(),+ rev: doc.rev,+ next: doc.next_id,+ marks: doc.here.marks.clone(),+ }+ }++ pub fn here(&self) -> Here {+ Here {+ tag: self.tag.clone(),+ marks: self.marks.clone(),+ }+ }+}++pub fn path(root: &Path) -> PathBuf {+ root.join(".cache").join("copy.json")+}++pub fn read(root: &Path) -> Option<State> {+ serde_json::from_str(&fs::read_to_string(path(root)).ok()?).ok()+}++pub fn new_tag(root: &Path) -> String {+ let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos());+ let hash = fnv(+ fnv(fnv(FNV_OFFSET, &nanos.to_le_bytes()), &std::process::id().to_le_bytes()),+ root.to_string_lossy().as_bytes(),+ );+ tag_letters(1 + (hash % (26 * 26)) as u32).unwrap_or_default()+}++pub fn load(root: &Path) -> (State, bool) {+ match read(root) {+ Some(state) => (state, false),+ None => (+ State {+ tag: new_tag(root),+ ..State::default()+ },+ true,+ ),+ }+}++pub fn start() -> State {+ State::default()+}++pub fn write(root: &Path, state: &State) -> Result<State> {+ let merged = match read(root) {+ Some(disk) if disk.tag == state.tag => State {+ rev: disk.rev.max(state.rev),+ next: disk.next.max(state.next),+ marks: disk+ .marks+ .into_iter()+ .chain(state.marks.clone())+ .fold(BTreeMap::new(), |mut all, (cel, top)| {+ let at: &mut u32 = all.entry(cel).or_default();+ *at = (*at).max(top);+ all+ }),+ ..state.clone()+ },+ _ => state.clone(),+ };+ write_atomic(&path(root), serde_json::to_string_pretty(&merged)?.as_bytes())?;+ Ok(merged)+}++fn files(dir: &Path, rel: &str, out: &mut Vec<(String, fs::Metadata)>) {+ let Ok(entries) = fs::read_dir(dir) else {+ return;+ };+ entries.filter_map(|e| e.ok()).for_each(|entry| {+ let name = entry.file_name().to_string_lossy().to_string();+ if name.contains(".tmp-") {+ return;+ }+ let rel = format!("{rel}/{name}");+ match entry.metadata() {+ Ok(meta) if meta.is_dir() => files(&entry.path(), &rel, out),+ Ok(meta) => out.push((rel, meta)),+ Err(_) => {}+ }+ });+}++fn stamp(meta: &fs::Metadata) -> Vec<u8> {+ let nanos = |t: std::io::Result<SystemTime>| {+ t.ok()+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())+ .map_or(0, |d| d.as_nanos())+ };+ let mut out = meta.len().to_le_bytes().to_vec();+ out.extend(nanos(meta.modified()).to_le_bytes());+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt;+ out.extend(meta.ino().to_le_bytes());+ out.extend(meta.ctime().to_le_bytes());+ out.extend(meta.ctime_nsec().to_le_bytes());+ }+ #[cfg(not(unix))]+ out.extend(nanos(meta.created()).to_le_bytes());+ out+}++pub fn fingerprint(root: &Path) -> u64 {+ let mut found = Vec::new();+ if let Ok(meta) = fs::metadata(root.join("doc.json")) {+ found.push(("doc.json".to_string(), meta));+ }+ ["strokes", "weights"]+ .iter()+ .for_each(|dir| files(&root.join(dir), dir, &mut found));+ found.sort_by(|a, b| a.0.cmp(&b.0));+ found.iter().fold(FNV_OFFSET, |hash, (rel, meta)| {+ fnv(fnv(hash, rel.as_bytes()), &stamp(meta))+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn folder(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("klad-here-{name}-{}", std::process::id()));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(dir.join("strokes/l1")).unwrap();+ fs::write(dir.join("doc.json"), "{}").unwrap();+ dir+ }++ #[test]+ fn any_write_to_the_drawing_changes_the_fingerprint_and_the_cache_does_not() {+ let dir = folder("print");+ let first = fingerprint(&dir);+ assert_eq!(fingerprint(&dir), first, "reading changes nothing");+ write_atomic(&dir.join(".cache/renders/r1.png"), b"x").unwrap();+ write_atomic(&dir.join("strokes/l1/c1.strokes.tmp-1-1"), b"x").unwrap();+ assert_eq!(+ fingerprint(&dir),+ first,+ "the cache and half-written files are not the drawing"+ );+ write_atomic(&dir.join("strokes/l1/c1.strokes"), b"x").unwrap();+ let stroked = fingerprint(&dir);+ assert_ne!(stroked, first, "a new stroke file");+ write_atomic(&dir.join("strokes/l1/c1.strokes"), b"x").unwrap();+ assert_ne!(+ fingerprint(&dir),+ stroked,+ "the same bytes written again, as a checkout does"+ );+ fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn a_copy_gets_its_own_tag_and_keeps_counting() {+ let dir = folder("tag");+ let made = write(&dir, &start()).unwrap();+ assert_eq!(made.tag, "", "the copy a drawing is made in has no tag");+ assert_eq!(load(&dir), (made.clone(), false));+ write(+ &dir,+ &State {+ next: 40,+ ..made.clone()+ },+ )+ .unwrap();+ write(+ &dir,+ &State {+ next: 12,+ ..made.clone()+ },+ )+ .unwrap();+ assert_eq!(read(&dir).unwrap().next, 40, "counters never go back");+ fs::remove_dir_all(dir.join(".cache")).unwrap();+ let (cloned, fresh) = load(&dir);+ assert!(+ fresh && cloned.tag.len() == 2,+ "a clone or worktree has no .cache: a new copy: {cloned:?}"+ );+ fs::remove_dir_all(&dir).unwrap();+ }+}diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rsindex b5d686d..6a3a526 100644--- a/crates/core/src/lib.rs+++ b/crates/core/src/lib.rs@@ -6,6 +6,7 @@ pub mod cut;pub mod doc;pub mod fill;pub mod generators;+pub mod here;pub mod history;pub mod keys;pub mod look;diff --git a/crates/core/src/markedit.rs b/crates/core/src/markedit.rsindex 54babc2..a10d0dc 100644--- a/crates/core/src/markedit.rs+++ b/crates/core/src/markedit.rs@@ -1,7 +1,8 @@use crate::color::{parse_hex, to_u16};use crate::cut::{self, Cut, Keep, inside_polygon};+use crate::doc::MarkIds;use crate::fill::{Coverage, Fill, FillSource};-use crate::stroke::{Mark, POS_SCALE, Sample, Stroke, next_id};+use crate::stroke::{Mark, POS_SCALE, Sample, Stroke};use anyhow::{Result, anyhow, bail};use serde_json::{Map, Value};@@ -14,12 +15,12 @@ pub const TRANSFORM_KEYS: &[&str] = &["x", "y", "rotate", "sx", "sy", "pivot"];pub fn parse_address(text: &str) -> Option<(&str, u32)> {let (cel, mark) = text.split_once(':')?;- let id = mark.strip_prefix('s')?.parse().ok()?;+ let id = crate::doc::parse_mark(mark)?;crate::doc::valid_id(cel).then_some((cel, id))}pub fn address(cel: &str, id: u32) -> String {- format!("{cel}:s{id}")+ format!("{cel}:{}", crate::doc::mark_name(id))}pub fn apply_affine(a: Affine, (x, y): (f32, f32)) -> (f32, f32) {@@ -572,9 +573,9 @@ pub enum LassoAction {Remove,}-pub fn split(marks: &mut Vec<Mark>, polygon: &[[f32; 2]], cut: bool) -> Vec<u32> {+pub fn split(marks: &mut Vec<Mark>, polygon: &[[f32; 2]], cut: bool, ids: MarkIds) -> Vec<u32> {let found = sides(marks, polygon);- let mut next = next_id(marks);+ let mut next = ids.next(marks);let mut chosen: Vec<u32> = found.iter().filter(|(_, s)| *s == Side::Inside)@@ -622,10 +623,10 @@ fn position(marks: &[Mark], cel: &str, id: u32) -> Result<usize> {.ok_or_else(|| anyhow!("{} does not exist", address(cel, id)))}-pub fn apply(marks: &mut Vec<Mark>, change: &mut MarkChange, cel: &str) -> Result<()> {+pub fn apply(marks: &mut Vec<Mark>, change: &mut MarkChange, cel: &str, ids: MarkIds) -> Result<()> {match change {MarkChange::Add(added) => {- let next = next_id(marks);+ let next = ids.next(marks);added.iter_mut().enumerate()@@ -655,7 +656,7 @@ pub fn apply(marks: &mut Vec<Mark>, change: &mut MarkChange, cel: &str) -> Resulif polygon.len() < 3 {bail!("a lasso needs at least 3 points");}- *chosen = split(marks, polygon, *cut);+ *chosen = split(marks, polygon, *cut, ids);if chosen.is_empty() {bail!("the lasso holds no strokes or fills of {cel}{}",@@ -694,8 +695,9 @@ pub fn paste(copies: Vec<(String, Mark)>,transform: Option<&MarkTransform>,cut: Option<&[[f32; 2]]>,+ ids: MarkIds,) -> Result<Vec<Copied>> {- let mut next = next_id(marks);+ let mut next = ids.next(marks);let (made, mut copied): (Vec<Copied>, Vec<Mark>) = copies.into_iter().map(|(cel, mut mark)| {@@ -830,7 +832,7 @@ mod tests {id: 1,props: props(json!({"color":"#ff0000","size":4,"brush":"pencil","taper":null})),};- apply(&mut marks, &mut set, "c1").unwrap();+ apply(&mut marks, &mut set, "c1", MarkIds::default()).unwrap();let s = marks[0].as_stroke().unwrap();assert_eq!((s.color, s.size, s.brush.as_str(), s.taper),@@ -840,17 +842,19 @@ mod tests {id: 2,props: props(json!({"opacity":0.5})),};- apply(&mut marks, &mut fill, "c1").unwrap();+ apply(&mut marks, &mut fill, "c1", MarkIds::default()).unwrap();assert_eq!(marks[1].as_fill().unwrap().opacity, 0.5);let mut typo = MarkChange::Set {id: 2,props: props(json!({"size":3})),};- let err = apply(&mut marks, &mut typo, "c1").unwrap_err().to_string();+ let err = apply(&mut marks, &mut typo, "c1", MarkIds::default())+ .unwrap_err()+ .to_string();assert!(err.contains("c1:s2") && err.contains("color, opacity"), "{err}");let mut missing = MarkChange::Remove { id: 9 };assert!(- apply(&mut marks, &mut missing, "c1")+ apply(&mut marks, &mut missing, "c1", MarkIds::default()).unwrap_err().to_string().contains("c1:s9")@@ -868,7 +872,7 @@ mod tests {..Default::default()},};- apply(&mut marks, &mut moved, "c1").unwrap();+ apply(&mut marks, &mut moved, "c1", MarkIds::default()).unwrap();assert_eq!(marks[0].as_stroke().unwrap().samples[0].pos(), (15.0, 7.5));let mut turned = MarkChange::Transform {ids: vec![1],@@ -879,7 +883,7 @@ mod tests {..Default::default()},};- apply(&mut marks, &mut turned, "c1").unwrap();+ apply(&mut marks, &mut turned, "c1", MarkIds::default()).unwrap();let s = marks[0].as_stroke().unwrap();let (a, b) = (s.samples[0].pos(), s.samples[1].pos());assert!((a.0 - 25.0).abs() < 0.07 && (a.1 + 12.5).abs() < 0.07, "{a:?}");@@ -898,7 +902,7 @@ mod tests {..Default::default()},};- apply(&mut marks, &mut moved, "c1").unwrap();+ apply(&mut marks, &mut moved, "c1", MarkIds::default()).unwrap();let f = marks[0].as_fill().unwrap();assert_eq!((f.coverage.x, f.coverage.y, f.coverage.width, f.coverage.height),@@ -915,7 +919,7 @@ mod tests {..Default::default()},};- apply(&mut marks, &mut doubled, "c1").unwrap();+ apply(&mut marks, &mut doubled, "c1", MarkIds::default()).unwrap();let f = marks[0].as_fill().unwrap();assert_eq!((f.coverage.x, f.coverage.y), (20, 20));assert_eq!((f.coverage.width, f.coverage.height), (40, 20));@@ -966,7 +970,7 @@ mod tests {chosen: Vec::new(),};let mut plain = marks.clone();- apply(&mut plain, &mut whole, "c1").unwrap();+ apply(&mut plain, &mut whole, "c1", MarkIds::default()).unwrap();assert_eq!(whole.ids(), vec![2]);assert_eq!(plain[0], marks[0]);let mut change = MarkChange::Lasso {@@ -978,7 +982,7 @@ mod tests {}),chosen: Vec::new(),};- apply(&mut marks, &mut change, "c1").unwrap();+ apply(&mut marks, &mut change, "c1", MarkIds::default()).unwrap();assert_eq!(marks.iter().map(Mark::id).collect::<Vec<_>>(), [1, 3, 2]);assert_eq!(change.ids(), vec![2, 3]);let (stay, part) = (marks[0].as_stroke().unwrap(), marks[1].as_stroke().unwrap());@@ -998,7 +1002,7 @@ mod tests {action: LassoAction::Remove,chosen: Vec::new(),};- apply(&mut gone, &mut rm, "c1").unwrap();+ apply(&mut gone, &mut rm, "c1", MarkIds::default()).unwrap();assert_eq!(gone.len(), 1);assert_eq!(gone[0].cuts()[0].keep, Keep::Outside);let mut empty = MarkChange::Lasso {@@ -1007,7 +1011,7 @@ mod tests {action: LassoAction::Remove,chosen: Vec::new(),};- assert!(apply(&mut gone, &mut empty, "c1").is_err());+ assert!(apply(&mut gone, &mut empty, "c1", MarkIds::default()).is_err());}#[test]@@ -1025,7 +1029,7 @@ mod tests {..Default::default()},};- apply(&mut marks, &mut flip, "c1").unwrap();+ apply(&mut marks, &mut flip, "c1", MarkIds::default()).unwrap();let s = marks[0].as_stroke().unwrap();assert_eq!(s.samples[0].pos(), (60.0, 30.0));assert_eq!(s.size, 4.0);@@ -1036,7 +1040,7 @@ mod tests {fn adds_take_the_next_ids() {let mut marks = vec![line(4)];let mut add = MarkChange::Add(vec![line(0), square(0)]);- apply(&mut marks, &mut add, "c1").unwrap();+ apply(&mut marks, &mut add, "c1", MarkIds::default()).unwrap();assert_eq!(marks.iter().map(Mark::id).collect::<Vec<_>>(), [4, 5, 6]);assert_eq!(add.ids(), [5, 6]);}@@ -1070,7 +1074,7 @@ mod tests {id: 1,props: serde_json::from_str(r#"{"path":"M0 0 C 30 -40 70 40 100 0"}"#).unwrap(),};- apply(&mut marks, &mut change, "c1").unwrap();+ apply(&mut marks, &mut change, "c1", MarkIds::default()).unwrap();let Mark::Stroke(curved) = &marks[0] else { panic!() };assert!(curved.samples[5].pos().1 < -5.0, "{:?}", curved.samples[5].pos());assert!(reshape(&mut curved.clone(), "").is_err());diff --git a/crates/core/src/migrate.rs b/crates/core/src/migrate.rsindex 7117bc1..be25e6e 100644--- a/crates/core/src/migrate.rs+++ b/crates/core/src/migrate.rs@@ -10,13 +10,13 @@ pub fn migrate(value: Value) -> Result<Value> {.to_string();match format.as_str() {FORMAT => Ok(value),+ "klad/4" => Ok(uncount(value)),"klad/1" | "klad/2" | "klad/3" => {let mut value = value;- value["format"] = Value::from(FORMAT);if let Some(layers) = value.get_mut("layers").and_then(Value::as_array_mut) {layers.iter_mut().for_each(unrig);}- Ok(value)+ Ok(uncount(value))}old if old.starts_with("draw-anything/") => bail!("a drawing in the old .draw format ({old}); this klad opens {FORMAT} drawings (.klad) only and does not convert old ones"@@ -26,6 +26,15 @@ pub fn migrate(value: Value) -> Result<Value> {}}+fn uncount(mut value: Value) -> Value {+ value["format"] = Value::from(FORMAT);+ if let Some(map) = value.as_object_mut() {+ map.remove("rev");+ map.remove("nextId");+ }+ value+}+fn unrig(layer: &mut Value) {let Some(map) = layer.as_object_mut() else {return;@@ -62,6 +71,12 @@ mod tests {let first = json!({"format": "klad/1", "rev": 3, "layers": [{"id": "l1", "kind": "paint", "cels": [{"id": "c1", "frame": 0}]}]});let mut moved = first.clone();moved["format"] = json!(FORMAT);+ moved.as_object_mut().unwrap().remove("rev");+ assert_eq!(+ migrate(json!({"format": "klad/4", "rev": 9, "nextId": 40, "layers": []})).unwrap(),+ json!({"format": FORMAT, "layers": []}),+ "klad/5 keeps no counters in doc.json: they live in the copy's .cache"+ );assert_eq!(migrate(first).unwrap(),moved,diff --git a/crates/core/src/patch.rs b/crates/core/src/patch.rsindex 4722e46..a496f42 100644--- a/crates/core/src/patch.rs+++ b/crates/core/src/patch.rs@@ -102,6 +102,7 @@ fn doc_shell(doc: &Document) -> Document {export: doc.export.clone(),atmosphere: doc.atmosphere.clone(),next_id: doc.next_id,+ here: doc.here.clone(),}}@@ -333,8 +334,12 @@ fn merge_layer(layer: &mut Layer, old: &Value, new: &Value) -> Result<()> {fn merge_doc(doc: &mut Document, old: &Value, new: &Value) -> Result<()> {let layers = std::mem::take(&mut doc.layers);+ let here = std::mem::take(&mut doc.here);*doc = Document {layers,+ rev: doc.rev,+ next_id: doc.next_id,+ here,..merge(&*doc, old, new)?};Ok(())diff --git a/crates/core/src/samples.rs b/crates/core/src/samples.rsindex 3dcdfa4..6fb3d56 100644--- a/crates/core/src/samples.rs+++ b/crates/core/src/samples.rs@@ -72,6 +72,7 @@ pub fn copy(sample: &Sample, folder: &Path) -> Result<PathBuf> {fs::create_dir_all(folder).with_context(|| format!("making {}", folder.display()))?;let to = free_path(folder, &sample.name);copy_dir(&sample.path, &to).with_context(|| format!("copying {} to {}", sample.name, to.display()))?;+ crate::here::write(&to, &crate::here::start())?;Ok(to)}@@ -117,6 +118,11 @@ mod tests {assert_eq!(second, mine.join("rock 2.klad"));assert!(Bundle::open(&second).is_ok());assert!(!first.join(".cache/thumb.png").exists(), "the cache stays behind");+ assert_eq!(+ Bundle::open(&first).unwrap().doc.here.tag,+ "",+ "a sample copied out is a new drawing"+ );fs::remove_dir_all(&dir).unwrap();}}diff --git a/crates/core/src/stroke.rs b/crates/core/src/stroke.rsindex e27c15c..8775dbf 100644--- a/crates/core/src/stroke.rs+++ b/crates/core/src/stroke.rs@@ -405,10 +405,6 @@ pub fn fills_of(marks: &[Mark]) -> impl Iterator<Item = &Fill> {marks.iter().filter_map(Mark::as_fill)}-pub fn next_id(marks: &[Mark]) -> u32 {- marks.iter().map(Mark::id).max().map_or(1, |m| m + 1)-}-fn encode_mark(out: &mut Vec<u8>, mark: &Mark) {match mark {Mark::Stroke(s) => {@@ -549,7 +545,10 @@ mod tests {assert_eq!(strokes_of(&back).count(), 2);assert_eq!(fills_of(&back).next(), Some(&fill));assert_eq!(back[1].bounds(), Some([30.0, 40.0, 200.0, 90.0]));- assert_eq!(next_id(&back), strokes[0].id.max(strokes[1].id).max(7) + 1);+ assert_eq!(+ crate::doc::MarkIds::default().next(&back),+ strokes[0].id.max(strokes[1].id).max(7) + 1+ );}#[test]diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 9ce5886..2557b60 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-07 16:20_+_Last updated: 2026-11-09 09:02_# klad: design@@ -101,12 +101,11 @@ art.klad/Committed: everything except `.cache/`. A fresh clone rebuilds the cache by replaying strokes and fills.-### doc.json (format `klad/4`)+### doc.json (format `klad/5`)```json{- "format": "klad/4",- "rev": 42,+ "format": "klad/5","canvas": { "width": 2048, "height": 2048, "background": "#f4efe6" },"timeline": { "fps": 12, "frames": 24, "origin": [1024, 1800],"clips": [{ "name": "run", "from": 0, "to": 11, "loop": true, "fps": 24 }, { "name": "jump", "from": 12, "to": 23 }] },@@ -134,8 +133,7 @@ Committed: everything except `.cache/`. A fresh clone rebuilds the cache by repl{ "id": "n7", "type": "path", "d": "M380 560 L560 560 L530 600 L410 600 Z", "fill": "#2b1d14","stroke": { "paint": "#000000", "width": 3 } } ] }] }] }- ],- "nextId": 7+ ]}```@@ -154,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).-- `rev` increments on every write. `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. `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@@ -492,9 +490,9 @@ Every change, from the CLI or the editor, first stores a history entry in `.cachThe agent may run in a Linux container while the editor runs on the macOS host, sharing the folder through a bind mount.- Every change is an op appended to the op log in `.cache/`, with the author and `rev`.-- Writers write files atomically (temp file plus rename) and bump `rev`.-- Before a CLI edit writes, it checks that `doc.json` on disk still has the `rev` it loaded (`Bundle::ensure_unchanged`, reading only the head of the file); when another writer got there first it writes nothing, says "the document changed while this edit was being made", and exits with code 75. Edits computed before the transaction (in-betweens, fills like another drawing) are the ones with a real window; the editor's job list runs them again. `DRAW_TEST_WRITE_DELAY_MS` makes the CLI wait that long before its check, for the test that edits in the middle.-- The editor watches the bundle. When `rev` moves past its own, it applies the new ops from the log to its in-memory document.+- Writers write files atomically (temp file plus rename) and bump `rev` in `.cache/copy.json`.+- Before a CLI edit writes, it checks that the drawing's files are the ones it read (`Bundle::ensure_unchanged`: the size, modified time, inode and change time of `doc.json`, the stroke files and the weights, taken before reading; a few milliseconds for 400 files, no file is read); when another writer or a `git checkout` got there first it writes nothing, says "the document changed while this edit was being made", and exits with code 75. Edits computed before the transaction (in-betweens, fills like another drawing) are the ones with a real window; the editor's job list runs them again. `DRAW_TEST_WRITE_DELAY_MS` makes the CLI wait that long before its check, for the test that edits in the middle.+- The editor watches the bundle. When its files differ from the ones it last read or wrote, it reloads, whoever changed them: the CLI, an agent or a `git checkout`. Disk caches are keyed by those files (render names) or by the bytes of each stroke file (tiles), never by a counter, so nothing stale is drawn after a checkout.- Undo and redo work on the shared log, so the human can undo an agent edit and the other way round.- M0 verifies file events and atomic renames across the OrbStack mount in both directions.diff --git a/docs/format.md b/docs/format.mdindex 4f9b872..3e4198d 100644--- a/docs/format.md+++ b/docs/format.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-08 (format `klad/4`, stroke files `KLST` version 1, brushes `klad-brush/1`)_+_Last updated: 2026-11-09 (format `klad/5`, stroke files `KLST` version 1, brushes `klad-brush/1`)_# The klad drawing format@@ -20,26 +20,25 @@ klad is the reference: when this text and klad's renders disagree, klad is right| `fonts/<file>` | fonts used by `text` nodes, with their licence files | for every `font` || `weights/<owner>.weights` | how much each bone of a skeleton moves each part of the drawing | for every bones layer with `bones` || `.gitignore` | `.cache/`, so a drawing can live in a git repository | no |-| `.cache/` | rebuildable pixels, the undo history, the editor's selection and pinned notes | no: never read it as data |+| `.cache/` | rebuildable pixels, the undo history, the editor's selection and pinned notes, and `copy.json`: this copy's tag and id counters | no: never read it as data |Everything outside `.cache/` is the drawing. Copy, version or zip those files and the drawing renders the same on another machine. Read the selection and the notes through `klad selection --json` and `klad notes --json`, not from `.cache/`.-Writers replace files atomically (write a temporary file, then rename), so a reader that watches the folder never sees half a file. `rev` in `doc.json` grows by one on every write.+Writers replace files atomically (write a temporary file, then rename), so a reader that watches the folder never sees half a file. Nothing in the drawing changes unless the drawing does: `doc.json` holds no revision or id counter, so an edit to one stroke changes its stroke file and nothing else, and git diffs and merges only what was edited. A program that wants to know whether a drawing changed compares the files (their size and modified time, or their bytes).## Conventions- **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 `_`. klad makes new ones from a prefix (`l` layer, `c` cel, `n` node) and `nextId`. Ids are case sensitive.+- **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.- **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/4`. 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.+- **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.## doc.json```json{- "format": "klad/4",- "rev": 42,+ "format": "klad/5","canvas": { "width": 2048, "height": 2048, "background": "#f4efe6" },"timeline": { "fps": 12, "frames": 24, "origin": [1024, 1800],"clips": [{ "name": "run", "from": 0, "to": 11, "loop": true, "fps": 24 }] },@@ -53,8 +52,7 @@ Writers replace files atomically (write a temporary file, then rename), so a rea{ "id": "n5", "type": "rect", "x": 0, "y": 0, "w": 2048, "h": 900,"fill": { "linear": { "from": [0, 0], "to": [0, 900], "stops": [[0, "#121d31"], [1, "#4a6a8c"]] } } }] }] }- ],- "nextId": 7+ ]}```@@ -62,15 +60,13 @@ Writers replace files atomically (write a temporary file, then rename), so a rea| Key | Type | Default | Meaning ||---|---|---|---|-| `format` | string | | `"klad/4"` |-| `rev` | integer | | grows by one on every write |+| `format` | string | | `"klad/5"` || `canvas` | object | | `width`, `height` (px), `background` (a colour; none is transparent) || `timeline` | object | 12 fps, 1 frame | see below || `palette` | array | `[]` | swatches: `color`, optional `name` (unique, not starting with `#`) || `layers` | array | | the layers, **bottom first** || `export` | object | `{}` | `godot`: the folder Godot exports go to, relative to the folder holding the bundle || `atmosphere` | object | none | fog by depth: `color` (`#9aa8b8`), `top` (a colour higher up), `density` (0.5), `blur` (1), `desaturate` (0.15) |-| `nextId` | integer | 0 | the counter new ids are made from |Strokes and fills store their colour, so the palette is a list of names for colours, never a reference: renaming or recolouring a swatch changes nothing drawn.@@ -228,7 +224,7 @@ Constraints are solved parent first, by the position of the limb's top bone (A f## Stroke files-`strokes/<layer>/<cel>.strokes` holds the marks of one paint drawing, in the order they are drawn: brush strokes and fills. Every mark has an id, unique within its drawing, from one counter shared by strokes and fills. A mark's address is `<cel>:s<id>`.+`strokes/<layer>/<cel>.strokes` holds the marks of one paint drawing, in the order they are drawn: brush strokes and fills. Every mark has an id, unique within its drawing, shared by strokes and fills. A mark's address is `<cel>:s<id>`. An id is a `u32`: its top 10 bits name the copy that made it (0 for none, else 1 + 26 × first letter + second letter, with `a` as 0) and its low 22 bits are a number counted per copy, so `s349qa` is 349 made by the copy tagged `qa`, stored as `(1 + 16 × 26 + 0) << 22 | 349`. Ids from before `klad/5`, and those of the copy a drawing was made in, are plain numbers: `s348`. Addresses accept the number in either form.The file is one zstd frame (any level; klad uses 3). Inside:@@ -338,3 +334,4 @@ Drawing a stroke: walk the samples, interpolate between them, stamp the tip ever| `klad/2` | skeletons get `ik` constraints and poses their `ik` targets (2026-11-07). `klad/1` drawings open unchanged. || `klad/3` | paint layers under a skeleton get `bone`, attaching them to one bone (2026-11-08). `klad/1` and `klad/2` drawings open unchanged. || `klad/4` | skeletons move to bones layers, and paint layers join one with `rig` (2026-11-08). Older drawings open without their bones, IK, weights links and the `pose` of their cels; the drawings themselves, posed ones too, stay. |+| `klad/5` | `rev` and `nextId` leave `doc.json`, and new ids carry the tag of the copy that made them, so drawings diff and merge in git (2026-11-09). Older drawings open with their ids unchanged; their counters move to `.cache/copy.json`. |diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex d1ebbf7..f43b53d 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.+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.```klad set art.klad c4:s12 color=#c84a3a size=6 brush=pencil