Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Plain messages and problem reports

Indicode BV724f627b3022
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c5b6808..0e6a88e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,7 +15,8 @@ The first builds, and klad's licences.
- `klad --version`, About and the start window show the version and the commit a build was made from; `just build` counts the version up for every build.
- In-betweens blend colours evenly (in OKLab), so light can follow a turning limb when the second key is coloured for it.
- `klad arcs` follows the part of a foot on the ground: a heel-to-toe roll is no longer reported as a slide.
-- "Report a problem" copies what an issue needs.
+- Help > Report a problem shows the report before it is copied (version, system, the last messages and lines of klad's log, with your home folder hidden) and can zip the drawing to attach; `klad report` prints the same. Errors and crashes are kept in a small log for it.
+- Messages say what happened and what to do next; when klad itself goes wrong it says so, and that your work is saved.
- Bones: a layer or group gets a skeleton (`klad bone`, the bone tool J), weights from the bones or painted (`klad weights`), and poses that bend the drawing (`klad pose`, pose mode); in-betweens of two poses turn the bones. The bone tool lists the skeleton, picks a bone in every mode, and moves ends, joints and whole bones with their children (`klad bone --move` with `--by`).
- A first start: the start window welcomes, offers first steps (draw a shape, fill it, hand the drawing to an agent, ticked off as you go; Help > First steps opens them again) and six sample drawings that open as copies (`klad samples` lists and copies them).
- Menus: a menu bar (the Mac's own, an in-window one on Windows and Linux) holds every command, with its keys, ticks for what is on and greyed items for what cannot run now; File has close (cmd W) and recent drawings.
diff --git a/Cargo.lock b/Cargo.lock
index 3886eff..f08ae66 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1749,6 +1749,7 @@ dependencies = [
"anyhow",
"block2 0.6.2",
"bytemuck",
+ "crc32fast",
"eframe",
"egui",
"egui-wgpu",
diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml
index 91c6bfc..098aa94 100644
--- a/crates/app/Cargo.toml
+++ b/crates/app/Cargo.toml
@@ -18,6 +18,7 @@ egui-wgpu = "0.37.0"
half = { version = "2.7.1", features = ["bytemuck"] }
notify = "8"
png = "0.18.1"
+crc32fast = "1.5.4"
pollster = "1.0.1"
rayon = "1.12.0"
serde = { version = "1.0.229", features = ["derive"] }
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs
index 4b6eb8b..bdd36da 100644
--- a/crates/app/src/commands.rs
+++ b/crates/app/src/commands.rs
@@ -2342,7 +2342,7 @@ pub const MENUS: [Menu; 7] = [
];
#[cfg(any(target_os = "macos", test))]
-pub const IN_APP_MENU: [Cmd; 3] = [Cmd::About, Cmd::Settings, Cmd::Quit];
+pub const IN_APP_MENU: [Cmd; 2] = [Cmd::Settings, Cmd::Quit];
pub fn menu_label(cmd: Cmd) -> String {
let name = cmd.spec().name;
diff --git a/crates/app/src/composite.rs b/crates/app/src/composite.rs
index b52e467..75fcc00 100644
--- a/crates/app/src/composite.rs
+++ b/crates/app/src/composite.rs
@@ -439,7 +439,7 @@ impl FrameRequest {
let dir = self
.disk
.clone()
- .ok_or_else(|| anyhow!("no folder for frame pictures"))?;
+ .ok_or_else(|| crate::report::bug("the frame pictures have no folder"))?;
let cache = CelCache::new(&self.bundle, &self.brushes, Write::Always);
let pictured = picture_path(&dir, self.key).exists();
let planes_key = self.planes.as_ref().map(|p| p.key(&self.bundle, &self.brushes));
@@ -1460,7 +1460,7 @@ impl Scene {
pub fn preview_layer(&mut self, layer: Layer) -> Result<()> {
let Some(Loc::Layer(path)) = self.bundle.doc.locate(&layer.id) else {
- return Err(anyhow!("no layer {}", layer.id));
+ return Err(crate::report::bug(format!("layer {} is not in the scene", layer.id)));
};
*self.bundle.doc.layer_at_mut(&path) = layer;
self.rebuild_caches(None)
@@ -1548,7 +1548,7 @@ impl Scene {
if let Some(cel) = self.active_cel() {
return Ok(cel);
}
- let layer = self.active_id().ok_or_else(|| anyhow!("no active layer"))?;
+ let layer = self.active_id().ok_or_else(|| anyhow!("pick a layer first"))?;
let op = Op::AddCel {
cel: serde_json::json!({ "frame": self.frame }),
layer,
@@ -1562,7 +1562,7 @@ impl Scene {
.added
.first()
.cloned()
- .ok_or_else(|| anyhow!("no cel was added"))?;
+ .ok_or_else(|| crate::report::bug("a new drawing was not added"))?;
let (w, h) = self.size();
self.rasters.insert(cel.clone(), Raster::new(w, h));
self.cels.insert(
@@ -1589,11 +1589,11 @@ impl Scene {
let raster = self
.rasters
.get_mut(&cel)
- .ok_or_else(|| anyhow!("cel {cel} has no pixels"))?;
+ .ok_or_else(|| crate::report::bug(format!("drawing {cel} has no pixels")))?;
let data = self
.cels
.get_mut(&cel)
- .ok_or_else(|| anyhow!("cel {cel} has no strokes"))?;
+ .ok_or_else(|| crate::report::bug(format!("drawing {cel} has no strokes")))?;
Ok(data.replay.commit_stroke(raster, stroke, buffer, blend))
}
@@ -1602,11 +1602,11 @@ impl Scene {
let raster = self
.rasters
.get_mut(&cel)
- .ok_or_else(|| anyhow!("cel {cel} has no pixels"))?;
+ .ok_or_else(|| crate::report::bug(format!("drawing {cel} has no pixels")))?;
let data = self
.cels
.get_mut(&cel)
- .ok_or_else(|| anyhow!("cel {cel} has no strokes"))?;
+ .ok_or_else(|| crate::report::bug(format!("drawing {cel} has no strokes")))?;
data.replay.paint(raster, Mark::Fill(fill), brushes)
}
@@ -1649,7 +1649,7 @@ impl Scene {
.iter()
.find(|(i, _)| *i == index)
.map(|(_, t)| t)
- .ok_or_else(|| anyhow!("tile {index} was not composed"))?;
+ .ok_or_else(|| crate::report::bug(format!("tile {index} was not composed")))?;
Some([tile[at], tile[at + 1], tile[at + 2], tile[at + 3]].map(f16::to_f32))
} else {
let items: Vec<TileItem> = self.bundle.doc.layers.iter().map(TileItem::Layer).collect();
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index 3ced7b0..666dc0b 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -512,6 +512,7 @@ struct Windows {
import: bool,
about: bool,
export: bool,
+ report: bool,
font: bool,
paintover: bool,
compare: bool,
@@ -620,6 +621,7 @@ pub(crate) struct Editor {
compare: Option<compare::Compared>,
bones: bones::BoneTool,
first: first::FirstSteps,
+ report_drawing: bool,
key_ease: klad_core::keys::Ease,
bindings: crate::commands::Bindings,
capturing: Option<Cmd>,
@@ -674,7 +676,11 @@ impl Editor {
let scene = Scene::open_lazy(path)?;
let brushes = BrushSet::for_bundle(&scene.bundle)?;
let embedded = scene.bundle.brushes()?;
- let tuning = Tuning::of(brushes.def("ink").ok_or_else(|| anyhow!("no ink brush"))?);
+ let tuning = Tuning::of(
+ brushes
+ .def("ink")
+ .ok_or_else(|| crate::report::bug("the ink brush is missing from the library"))?,
+ );
let settings_path = settings::default_path();
let settings = settings_path.as_deref().map(Settings::load).unwrap_or_default();
let open = format!(
@@ -785,6 +791,7 @@ impl Editor {
compare: None,
bones: bones::BoneTool::default(),
first: first::FirstSteps::default(),
+ report_drawing: false,
key_ease: klad_core::keys::Ease::Linear,
bindings: crate::commands::Bindings::default(),
capturing: None,
@@ -880,6 +887,10 @@ impl Editor {
pub(crate) fn say(&mut self, tone: Tone, text: impl Into<String>) {
let anchor = self.pointer;
+ let text = text.into();
+ if tone == Tone::Error {
+ crate::report::log(&format!("editor: {text}"));
+ }
self.messages.say(tone, text, anchor, Instant::now());
self.ctx.request_repaint();
}
@@ -888,6 +899,13 @@ impl Editor {
self.say(Tone::Error, format!("{e:#}"));
}
+ pub(crate) fn failed(&mut self, e: anyhow::Error) {
+ match crate::report::is_bug(&e) {
+ true => self.say(Tone::Error, crate::report::bug_message(&e)),
+ false => self.error(e),
+ }
+ }
+
fn measure(&mut self, key: &'static str, text: String) {
self.measured.insert(key, text);
}
@@ -904,7 +922,7 @@ impl Editor {
if now != self.shared {
let nodes = now.1.clone();
if let Err(e) = notes::write_selection(&self.scene.bundle, now.0.clone(), nodes, self.scene.frame) {
- self.error(e);
+ self.failed(e.context("the selection could not be shared with the agent"));
}
self.shared = now;
}
@@ -1396,7 +1414,7 @@ impl Editor {
}
Ok(_) => self.lift = None,
Err(e) => {
- self.error(format!("preparing the selection: {e:#}"));
+ self.failed(e.context("the selection could not be prepared"));
if let Some(l) = self.lift.as_mut() {
l.job = None;
}
@@ -1411,7 +1429,10 @@ impl Editor {
let Some(mut state) = self.lift.take() else {
return Ok(());
};
- let commit = state.commit.take().ok_or_else(|| anyhow!("commit vanished"))?;
+ let commit = state
+ .commit
+ .take()
+ .ok_or_else(|| crate::report::bug("a shape edit lost what it was writing"))?;
let start = Instant::now();
match (result, state.ready.as_ref()) {
(Ok((hash, raster)), Some((p, _))) => {
@@ -1531,7 +1552,7 @@ impl Editor {
let (p, _) = state
.ready
.as_ref()
- .ok_or_else(|| anyhow!("lift without preparation"))?;
+ .ok_or_else(|| crate::report::bug("a drag started before its picture was ready"))?;
let job = lift::finish(p.nodes.clone(), p.index, t, canvas, self.ctx.clone());
state.commit = Some(Commit { job, ops, affine });
Ok(())
@@ -2214,7 +2235,13 @@ impl Editor {
};
let layer = doc.layer_at(&path);
if layer.locked {
- self.say(Tone::Refused, format!("layer {} is locked", layer.name));
+ self.say(
+ Tone::Refused,
+ format!(
+ "{} is locked: unlock it with the lock in the layers panel to change it",
+ layer.name
+ ),
+ );
return Ok(());
}
let cel = layer.cels()[c].id.clone();
@@ -2258,7 +2285,7 @@ impl Editor {
.scene
.apply_rendered(&commit.ops, (commit.cel, hash, raster), &self.brushes)?,
Err(e) => {
- self.error(format!("drawing the edited path: {e:#}"));
+ self.failed(e.context("the edited path could not be drawn"));
self.scene.apply(&commit.ops, &self.brushes)?
}
};
@@ -2444,10 +2471,12 @@ impl Editor {
}
fn shaped(&self) -> Result<(String, BrushDef)> {
- let base = self
- .brushes
- .def(&self.brush)
- .ok_or_else(|| anyhow!("no brush {}", self.brush))?;
+ let base = self.brushes.def(&self.brush).ok_or_else(|| {
+ anyhow!(
+ "the brush {} is not there any more: pick another one in the colour and brush panel",
+ self.brush
+ )
+ })?;
let def = match &self.custom {
Some(def) => def.clone(),
None => self.tuning.shape(base),
@@ -2470,7 +2499,7 @@ impl Editor {
.brushes
.def("eraser")
.cloned()
- .ok_or_else(|| anyhow!("no eraser brush"))?;
+ .ok_or_else(|| crate::report::bug("the eraser brush is missing from the library"))?;
let tuning = Tuning::of(&def);
("eraser".to_string(), def, tuning)
} else {
@@ -2660,7 +2689,10 @@ impl Editor {
};
let computed = ms(start);
if coverage.is_empty() {
- self.say(Tone::Refused, "nothing to fill there");
+ self.say(
+ Tone::Refused,
+ "nothing to fill there: click inside closed lines, or raise the gap so small openings close",
+ );
return Ok(());
}
if self.external.is_some() {
@@ -3132,7 +3164,7 @@ impl Editor {
let (mut ops, after) = match &picked.cut {
Some(_) => self
.picked_ops(LassoAction::Transform(MarkTransform::default()))
- .ok_or_else(|| anyhow!("the cut selection is out of date"))?,
+ .ok_or_else(|| anyhow!("the selection changed underneath: select the strokes again"))?,
None => (Vec::new(), Some(picked.clone())),
};
ops.extend(sets.into_iter().map(|(cel, id, key, value)| Op::Set {
@@ -3842,7 +3874,10 @@ impl Editor {
) {
match color::rgba_of(&text) {
Some(rgba) => picked = Some(rgba),
- None => self.say(Tone::Refused, format!("{text:?} is not #rrggbb or #rrggbbaa")),
+ None => self.say(
+ Tone::Refused,
+ format!("{text} is not a colour: type it as #rrggbb or #rrggbbaa, for example #c8a070"),
+ ),
}
}
});
diff --git a/crates/app/src/editor/buffer.rs b/crates/app/src/editor/buffer.rs
index f1b4215..82f00c4 100644
--- a/crates/app/src/editor/buffer.rs
+++ b/crates/app/src/editor/buffer.rs
@@ -164,7 +164,7 @@ impl Editor {
ms(p.since) / 1000.0
),
),
- Err(e) => self.error(format!("preparing frames: {e:#}")),
+ Err(e) => self.failed(e.context("the frames could not be prepared")),
}
}
if self.buffering.job.is_some() || !self.cacheable() {
diff --git a/crates/app/src/editor/checks.rs b/crates/app/src/editor/checks.rs
index 3250cd8..dd48677 100644
--- a/crates/app/src/editor/checks.rs
+++ b/crates/app/src/editor/checks.rs
@@ -332,7 +332,7 @@ impl Editor {
let (mut ops, after) = match &picked.cut {
Some(_) => self
.picked_ops(LassoAction::Transform(MarkTransform::default()))
- .ok_or_else(|| anyhow!("the cut selection is out of date"))?,
+ .ok_or_else(|| anyhow!("the selection changed underneath: select the strokes again"))?,
None => (Vec::new(), Some(picked.clone())),
};
let ids = after.as_ref().map_or(Vec::new(), |p| p.addresses());
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index 5e3edff..a389af9 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -107,12 +107,13 @@ impl Editor {
Some(_) => editing.or(self
.path_commit
.as_ref()
- .map(|_| "writing the last edit...".to_string())),
+ .map(|_| "the last edit is being written: try again in a moment".to_string())),
None => Some("select strokes (S), a shape (V) or points (A) first".to_string()),
},
- Cmd::FlipView | Cmd::ResetRotation => {
- self.view.is_none().then(|| "the canvas is not shown yet".to_string())
- }
+ Cmd::FlipView | Cmd::ResetRotation => self
+ .view
+ .is_none()
+ .then(|| "the canvas is not shown yet: wait a moment".to_string()),
Cmd::Corner | Cmd::Smooth => direct
.filter(|d| !d.points.is_empty())
.is_none()
@@ -120,14 +121,14 @@ impl Editor {
.or(self
.path_commit
.as_ref()
- .map(|_| "writing the last edit...".to_string())),
+ .map(|_| "the last edit is being written: try again in a moment".to_string())),
Cmd::Simplify => direct
.is_none()
.then(|| "pick a shape with A first".to_string())
.or(self
.path_commit
.as_ref()
- .map(|_| "writing the last edit...".to_string())),
+ .map(|_| "the last edit is being written: try again in a moment".to_string())),
Cmd::MakePath => match direct.and_then(|d| self.scene.bundle.doc.item(&d.node)) {
Some(klad_core::doc::Item::Node(_, _, n)) if matches!(n.shape, Shape::Path { .. }) => {
Some("it is a path already".into())
@@ -200,7 +201,8 @@ impl Editor {
if layer.is_none() {
pick_layer()
} else {
- (self.scene.bundle.doc.timeline.frames == 1).then(|| "the timeline has one frame".to_string())
+ (self.scene.bundle.doc.timeline.frames == 1)
+ .then(|| "the timeline has one frame: insert a frame first (I)".to_string())
}
}),
Cmd::NewPaintLayer | Cmd::NewVectorLayer | Cmd::NewGroupLayer | Cmd::NewAdjustLayer => self.timeline_edit(),
@@ -252,8 +254,14 @@ impl Editor {
"select from one drawing to the frame where another starts, on a paint layer".to_string()
})
})
- .or_else(|| self.tweening().then(|| "in-betweens are being made".to_string())),
- Cmd::RedoInbetweens => self.tweening().then(|| "in-betweens are being made".to_string()),
+ .or_else(|| {
+ self.tweening().then(|| {
+ "in-betweens are being made: wait for them, or cancel them in the status line".to_string()
+ })
+ }),
+ Cmd::RedoInbetweens => self
+ .tweening()
+ .then(|| "in-betweens are being made: wait for them, or cancel them in the status line".to_string()),
Cmd::NewClip => (span.is_none() && self.timeline.range.is_none())
.then(|| "select frames or mark a loop range first".to_string()),
Cmd::DeleteClip | Cmd::ClipLoops | Cmd::ClipOwnFps => need_clip(),
@@ -263,17 +271,17 @@ impl Editor {
Cmd::Refill => self
.jobs
.busy(crate::jobs::Tag::Edit)
- .then(|| "a change is being made".to_string())
+ .then(|| "a change is being made: try again in a moment".to_string())
.or(editing),
Cmd::FillLike => need_span().or_else(|| {
self.jobs
.busy(crate::jobs::Tag::Edit)
- .then(|| "a change is being made".to_string())
+ .then(|| "a change is being made: try again in a moment".to_string())
}),
Cmd::ShowGaps => self
.jobs
.busy(crate::jobs::Tag::Gaps)
- .then(|| "the gaps are being looked for".to_string()),
+ .then(|| "the gaps are being looked for: wait a moment".to_string()),
Cmd::ShowArcs if self.checks.arcs.is_some() => None,
Cmd::ShowArcs => self.track().err().map(|e| e.to_string()),
Cmd::CompareReference => super::compare::reference_image(&self.scene.bundle.root, &self.scene.bundle.doc)
@@ -281,7 +289,7 @@ impl Editor {
.then(|| "add a reference picture first: a picture layer marked as a reference".to_string()),
Cmd::ExportGodot => {
if self.jobs.busy(crate::jobs::Tag::Export) {
- Some("an export is running".into())
+ Some("an export is running: wait for it, or cancel it in the status line".into())
} else {
self.godot_folder()
.is_empty()
@@ -358,6 +366,7 @@ impl Editor {
Cmd::Numbers => layout.numbers,
Cmd::Settings => self.windows.settings,
Cmd::About => self.windows.about,
+ Cmd::ReportProblem => self.windows.report,
Cmd::Export => self.windows.export,
Cmd::AddFont => self.windows.font,
Cmd::PaintOver => self.windows.paintover,
@@ -617,14 +626,7 @@ impl Editor {
Cmd::ShowParts => self.checks.parts = !self.checks.parts,
Cmd::ShowArcs => self.show_arcs()?,
Cmd::InstallCommand => self.start_job(install_job()),
- Cmd::ReportProblem => {
- let text = self.problem_report();
- self.ctx.copy_text(text);
- self.say(
- Tone::Done,
- "copied a problem report: paste it into an issue at github.com/klad-app/klad",
- );
- }
+ Cmd::ReportProblem => self.windows.report = !self.windows.report,
Cmd::CopyPath => {
let path = self.scene.bundle.root.display().to_string();
self.ctx.copy_text(path.clone());
@@ -962,27 +964,80 @@ pub(crate) fn install_job() -> Spec {
}
impl Editor {
- pub(crate) fn problem_report(&self) -> String {
- let lines: Vec<String> = self
+ pub(crate) fn problem_report(&self, attached: Option<&std::path::Path>) -> String {
+ let messages: Vec<String> = self
.messages
.log()
.rev()
- .take(40)
+ .take(crate::report::LOG_LINES)
.map(|m| format!("{:?}: {}", m.tone, m.text))
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
- format!(
- "klad {}\n{} {}\ncanvas {}x{}, {} layers, {} frames\n\nlast messages:\n{}\n",
- crate::VERSION,
- std::env::consts::OS,
- std::env::consts::ARCH,
- self.scene.bundle.doc.canvas.width,
- self.scene.bundle.doc.canvas.height,
- self.scene.bundle.doc.all_layers().len(),
- self.scene.bundle.doc.timeline.frames,
- lines.join("\n")
+ crate::report::Report {
+ from: "from the editor",
+ folder: self.scene.bundle.root.parent().map(std::path::Path::to_path_buf),
+ drawing: Some(crate::report::summary(&self.scene.bundle.doc)),
+ attached: attached
+ .and_then(|p| p.file_name())
+ .map(|n| n.to_string_lossy().to_string()),
+ messages,
+ log: crate::report::last_lines(crate::report::LOG_LINES),
+ }
+ .text()
+ }
+
+ pub(super) fn report_panel(&mut self, ui: &mut egui::Ui) {
+ ui.add(
+ egui::Label::new(
+ "Paste this into a new issue on klad's GitHub page. It holds klad's version, your system, the last messages and the last lines of klad's log; klad sends nothing by itself.",
+ )
+ .wrap(),
+ );
+ ui.checkbox(
+ &mut self.report_drawing,
+ "include the drawing: a zip next to it, to attach to the issue",
)
+ .hint("the drawing without its cache, so whoever reads the issue sees what you see");
+ let text = self.problem_report(None);
+ egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| {
+ ui.add(egui::Label::new(RichText::new(&text).monospace().size(11.0)).wrap());
+ });
+ ui.horizontal(|ui| {
+ if ui
+ .button(format!("{} copy the report", crate::theme::icon::COPY))
+ .hint("to the clipboard, ready to paste into the issue")
+ .clicked()
+ {
+ self.copy_report();
+ }
+ ui.hyperlink_to("open klad's issues", crate::report::ISSUES)
+ .hint("a new issue on GitHub, in your browser");
+ });
+ }
+
+ fn copy_report(&mut self) {
+ let attached = match self.report_drawing {
+ true => match crate::report::zip_beside(&self.scene.bundle.root) {
+ Ok(zip) => Some(zip),
+ Err(e) => {
+ self.failed(e.context("the drawing could not be zipped for the report"));
+ return;
+ }
+ },
+ false => None,
+ };
+ self.ctx.copy_text(self.problem_report(attached.as_deref()));
+ match attached {
+ Some(zip) => self.say(
+ Tone::Done,
+ format!(
+ "copied the report: paste it into the issue and attach {}",
+ zip.display()
+ ),
+ ),
+ None => self.say(Tone::Done, "copied the report: paste it into a new issue"),
+ }
}
}
diff --git a/crates/app/src/editor/compare.rs b/crates/app/src/editor/compare.rs
index 7638037..ec21fc4 100644
--- a/crates/app/src/editor/compare.rs
+++ b/crates/app/src/editor/compare.rs
@@ -79,7 +79,7 @@ impl Editor {
self.compare = Some(Compared { report, heat });
self.windows.compare = true;
}
- Err(e) => self.say(Tone::Error, format!("the comparison could not be read: {e}")),
+ Err(e) => self.say(Tone::Error, format!("the comparison ran but its result could not be read ({e}); run it again, and if it happens again, Help > Report a problem")),
}
}
diff --git a/crates/app/src/editor/copy.rs b/crates/app/src/editor/copy.rs
index 966e4f4..153fe1b 100644
--- a/crates/app/src/editor/copy.rs
+++ b/crates/app/src/editor/copy.rs
@@ -157,7 +157,10 @@ impl Editor {
if !missing.is_empty() {
self.say(
Tone::Refused,
- format!("{word}: the layers {} are gone or locked", missing.join(", ")),
+ format!(
+ "could not {word}: the layers {} are gone or locked; unlock them, or pick another layer",
+ missing.join(", ")
+ ),
);
return Ok(());
}
@@ -172,7 +175,7 @@ impl Editor {
let (dirty, applied) = match self.scene.apply_with(&ops, &self.brushes) {
Ok(done) => done,
Err(e) => {
- self.say(Tone::Refused, format!("{word}: failed, {e:#}"));
+ self.say(Tone::Refused, format!("could not {word} here: {e:#}"));
return Ok(());
}
};
diff --git a/crates/app/src/editor/depth.rs b/crates/app/src/editor/depth.rs
index 2777357..a50d3a7 100644
--- a/crates/app/src/editor/depth.rs
+++ b/crates/app/src/editor/depth.rs
@@ -149,7 +149,7 @@ impl Editor {
})
.collect();
}
- Err(e) => self.say(Tone::Error, format!("the parallax preview: {e:#}")),
+ Err(e) => self.say(Tone::Error, format!("the parallax preview could not be made: {e:#}")),
}
}
let painter = ui.painter().with_clip_rect(rect);
diff --git a/crates/app/src/editor/first.rs b/crates/app/src/editor/first.rs
index a8692fa..8c351a8 100644
--- a/crates/app/src/editor/first.rs
+++ b/crates/app/src/editor/first.rs
@@ -52,14 +52,14 @@ impl Editor {
return;
}
let mut open = true;
- let corner = self.canvas_rect.right_top() + egui::vec2(-344.0, 12.0);
- egui::Window::new("First steps")
- .open(&mut open)
- .default_pos(corner)
- .resizable(false)
- .collapsible(false)
- .show(ctx, |ui| {
- ui.set_width(320.0);
+ let corner = self.canvas_rect.right_top() + egui::vec2(-384.0, 12.0);
+ Self::window(
+ ctx,
+ "first steps",
+ (format!("{} First steps", icon::INFO), corner),
+ &mut open,
+ |ui| {
+ ui.set_width(340.0);
step(
ui,
self.first.drew,
@@ -102,7 +102,8 @@ impl Editor {
.wrap(),
);
}
- });
+ },
+ );
if !open {
self.first.open = false;
}
diff --git a/crates/app/src/editor/make.rs b/crates/app/src/editor/make.rs
index 4b2fe96..dce6a3e 100644
--- a/crates/app/src/editor/make.rs
+++ b/crates/app/src/editor/make.rs
@@ -559,7 +559,7 @@ impl Editor {
let (src, w, h) = match klad_render::assets::import_image(&self.scene.bundle.root, bytes) {
Ok(made) => made,
Err(e) => {
- self.say(Tone::Refused, format!("{name}: {e:#}"));
+ self.say(Tone::Refused, format!("could not import {name}: {e:#}"));
return Ok(());
}
};
@@ -607,7 +607,10 @@ impl Editor {
self.check(|e| e.import_picture(&bytes, &path));
self.windows.import = false;
}
- Err(e) => self.say(Tone::Refused, format!("reading {path}: {e}")),
+ Err(e) => self.say(
+ Tone::Refused,
+ format!("could not read {path}: {}", crate::report::io_words(&e)),
+ ),
}
}
ui.small("or drop a PNG or JPEG on the canvas");
@@ -635,7 +638,10 @@ impl Editor {
});
files.into_iter().for_each(|path| match std::fs::read(&path) {
Ok(bytes) => self.check(|e| e.import_picture(&bytes, &path.display().to_string())),
- Err(e) => self.say(Tone::Refused, format!("reading {}: {e}", path.display())),
+ Err(e) => self.say(
+ Tone::Refused,
+ format!("could not read {}: {}", path.display(), crate::report::io_words(&e)),
+ ),
});
}
}
diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rs
index 23be290..9e6a209 100644
--- a/crates/app/src/editor/panels.rs
+++ b/crates/app/src/editor/panels.rs
@@ -53,7 +53,7 @@ const STRIP_TOOLS: [Cmd; 11] = [
impl Editor {
pub(super) fn check(&mut self, f: impl FnOnce(&mut Self) -> Result<()>) {
if let Err(e) = f(self) {
- self.error(e);
+ self.failed(e);
}
}
@@ -163,7 +163,9 @@ impl Editor {
if let Some(path) = &self.settings_path
&& let Err(e) = self.settings.save(path)
{
- self.error(format!("saving your settings: {e:#}"));
+ self.error(format!(
+ "your settings could not be saved ({e:#}); they apply until klad closes"
+ ));
}
self.settings_dirty = false;
}
@@ -172,18 +174,21 @@ impl Editor {
spec.exe = match crate::start::draw_binary() {
Some(exe) => exe,
None => {
- self.error("cannot find the klad binary next to the editor".to_string());
+ self.error("the klad command line tool is missing next to the editor, so this cannot run: install klad again (it ships both)".to_string());
return;
}
};
let name = spec.name.clone();
match self.jobs.start(spec) {
Ok(_) => self.say(Tone::Info, format!("{name}...")),
- Err(e) => self.error(format!("cannot run {name}: {e}")),
+ Err(e) => self.error(format!("could not start {name}: {e}")),
}
}
fn say_job(&mut self, tone: Tone, text: String) {
+ if tone == Tone::Error {
+ crate::report::log(&format!("editor: {text}"));
+ }
self.messages.say(tone, text, None, Instant::now());
}
@@ -219,7 +224,7 @@ impl Editor {
if e.tag == Tag::Inbetween {
self.between.report = super::between::report(&e.output);
}
- self.say_job(Tone::Error, format!("{} failed: {text}", e.name))
+ self.say_job(Tone::Error, crate::report::job_failed(&e.name, &text))
}
Outcome::Cancelled => self.say_job(Tone::Info, format!("{} cancelled", e.name)),
}
@@ -629,7 +634,7 @@ impl Editor {
work
}
- fn window(
+ pub(super) fn window(
ctx: &egui::Context,
id: &str,
(title, at): (String, egui::Pos2),
@@ -720,6 +725,17 @@ impl Editor {
);
self.windows.brush &= open;
}
+ if self.windows.report {
+ let mut open = true;
+ Self::window(
+ ctx,
+ "report",
+ (format!("{} Report a problem", icon::LOG), settings_at),
+ &mut open,
+ |ui| self.report_panel(ui),
+ );
+ self.windows.report &= open;
+ }
if self.windows.about {
let mut open = true;
Self::window(
diff --git a/crates/app/src/editor/selection.rs b/crates/app/src/editor/selection.rs
index bc8a292..b4d020b 100644
--- a/crates/app/src/editor/selection.rs
+++ b/crates/app/src/editor/selection.rs
@@ -195,7 +195,7 @@ impl Editor {
Ok(())
}
Err(e) => {
- self.say(Tone::Refused, format!("duplicate: {e:#}"));
+ self.say(Tone::Refused, format!("could not duplicate it: {e:#}"));
Ok(())
}
}
diff --git a/crates/app/src/editor/timeline.rs b/crates/app/src/editor/timeline.rs
index 5a767bf..25498c3 100644
--- a/crates/app/src/editor/timeline.rs
+++ b/crates/app/src/editor/timeline.rs
@@ -402,7 +402,7 @@ impl Editor {
let mut done = match result {
Ok(done) => done,
Err(e) => {
- self.error(format!("loading frame {}: {e:#}", pending.frame));
+ self.failed(e.context(format!("frame {} could not be loaded", pending.frame)));
return Ok(());
}
};
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index ddcae9a..a540da1 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -2849,17 +2849,54 @@ fn a_layer_is_keyed_from_the_inspector_and_eases_between_its_keys() {
}
#[test]
-fn a_problem_report_holds_the_version_the_system_and_the_last_messages() {
+fn a_forced_error_reads_as_a_sentence_and_lands_in_the_report_with_the_drawing() {
let path = sample("report");
- let mut h = harness(editor(&path), vec2(1280.0, 900.0));
- h.state_mut().say(Tone::Error, "the fill leaked out of the lines");
- let report = h.state().problem_report();
- assert!(report.starts_with(&format!("klad {}", crate::VERSION)));
- assert!(report.contains(std::env::consts::OS) && report.contains("the fill leaked out of the lines"));
+ let log = path.with_extension("log");
+ crate::report::log_to(Some(log.clone()));
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ h.state_mut()
+ .check(|_| Err(crate::report::bug("a test forced this").context("the frames could not be prepared")));
+ h.run_steps(2);
+ let said = h.state().messages.log().last().unwrap().text.clone();
+ assert!(
+ said.starts_with("something went wrong inside klad (the frames could not be prepared: a test forced this)")
+ && said.ends_with("Help > Report a problem copies what an issue needs"),
+ "{said}"
+ );
+ assert!(
+ crate::report::last_lines(1)[0].ends_with(&format!("editor: {said}")),
+ "errors go to klad's log"
+ );
+ h.state_mut().invoke(Cmd::ReportProblem).unwrap();
+ h.run_steps(2);
+ assert!(h.query_by_label_contains("klad sends nothing by itself").is_some());
+ h.get_by_label_contains("include the drawing").click();
+ h.run_steps(1);
+ h.get_by_label_contains("copy the report").click();
+ h.run_steps(2);
+ let zip = path.with_file_name(format!(
+ "{} for a report.zip",
+ path.file_stem().unwrap().to_string_lossy()
+ ));
+ assert!(zip.is_file(), "the drawing is zipped next to it");
+ let names = crate::report::unzip_names(&std::fs::read(&zip).unwrap());
+ assert!(names.iter().any(|(n, ok)| n.ends_with("/doc.json") && *ok));
+ let report = h.state().problem_report(Some(&zip));
+ assert!(report.starts_with(&format!("klad {}, from the editor", crate::VERSION)));
+ assert!(report.contains(&crate::report::system()));
+ assert!(report.contains("a test forced this") && report.contains("Last lines of klad's log:"));
+ assert!(report.contains(&format!(
+ "is attached as {}",
+ zip.file_name().unwrap().to_string_lossy()
+ )));
assert!(
!report.contains(&path.display().to_string()),
"the drawing's path stays private"
);
+ assert!(h.state().messages.log().last().unwrap().text.contains("attach"));
+ crate::report::log_to(None);
+ let _ = std::fs::remove_file(&zip);
+ let _ = std::fs::remove_file(&log);
let _ = std::fs::remove_dir_all(&path);
}
diff --git a/crates/app/src/home.rs b/crates/app/src/home.rs
index 3ae057b..b9f4655 100644
--- a/crates/app/src/home.rs
+++ b/crates/app/src/home.rs
@@ -17,6 +17,11 @@ const WIDTH: f32 = 760.0;
pub fn run(path: Option<PathBuf>) -> Result<()> {
crate::opened::listen();
+ let previous = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |info| {
+ crate::report::log(&format!("the editor stopped: {}", crate::report::panic_text(info)));
+ previous(info);
+ }));
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(start::title(path.as_deref()))
diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs
index 9405fa3..8a3507c 100644
--- a/crates/app/src/lib.rs
+++ b/crates/app/src/lib.rs
@@ -15,6 +15,7 @@ mod pen;
mod picker;
mod places;
mod planes;
+pub mod report;
mod settings;
mod start;
mod stats;
diff --git a/crates/app/src/lift.rs b/crates/app/src/lift.rs
index 9753acf..6fe657e 100644
--- a/crates/app/src/lift.rs
+++ b/crates/app/src/lift.rs
@@ -89,7 +89,9 @@ pub fn prepare(job: Job, ctx: egui::Context) -> Receiver<Result<Prepared>> {
let (cw, ch) = job.canvas;
let (index, nodes, lifted, lower, upper) = match job.source {
Source::Node { index, nodes } => {
- let target = nodes.get(index).ok_or_else(|| anyhow!("node index out of range"))?;
+ let target = nodes
+ .get(index)
+ .ok_or_else(|| crate::report::bug("a dragged shape is not in its layer"))?;
let [x, y, w, h] =
vector::node_box(target)?.ok_or_else(|| anyhow!("{} has nothing to draw", job.key))?;
let lifted = rasterize_region(
diff --git a/crates/app/src/report.rs b/crates/app/src/report.rs
new file mode 100644
index 0000000..32c8378
--- /dev/null
+++ b/crates/app/src/report.rs
@@ -0,0 +1,388 @@
+use anyhow::{Result, bail};
+use std::fs;
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+pub const ISSUES: &str = "https://github.com/klad-app/klad/issues/new";
+const LOG_LIMIT: u64 = 512 * 1024;
+pub const LOG_LINES: usize = 40;
+
+#[derive(Debug)]
+pub struct Bug(pub String);
+
+impl std::fmt::Display for Bug {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+impl std::error::Error for Bug {}
+
+pub fn io_words(e: &std::io::Error) -> String {
+ match e.kind() {
+ std::io::ErrorKind::NotFound => "it is not there (moved or deleted?)".to_string(),
+ std::io::ErrorKind::PermissionDenied => "klad may not read it: check the file's permissions".to_string(),
+ _ => e.to_string(),
+ }
+}
+
+pub fn job_failed(name: &str, why: &str) -> String {
+ let why = why.trim().trim_start_matches("error: ");
+ match why.split_once("klad hit a bug: ") {
+ Some((_, rest)) => {
+ let what = rest.split(". KLAD_BACKTRACE").next().unwrap_or(rest);
+ format!(
+ "something went wrong inside klad ({name}: {what}). Everything up to your last edit is saved; Help > Report a problem copies what an issue needs"
+ )
+ }
+ None => format!("{name} did not finish: {why}"),
+ }
+}
+
+pub fn bug(what: impl Into<String>) -> anyhow::Error {
+ anyhow::Error::new(Bug(what.into()))
+}
+
+pub fn is_bug(e: &anyhow::Error) -> bool {
+ e.chain().any(|c| c.downcast_ref::<Bug>().is_some())
+}
+
+pub fn bug_message(e: &anyhow::Error) -> String {
+ format!(
+ "something went wrong inside klad ({e:#}). Everything up to your last edit is saved; Help > Report a problem copies what an issue needs"
+ )
+}
+
+#[cfg(test)]
+thread_local! {
+ static TEST_LOG: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
+}
+
+#[cfg(test)]
+pub fn log_to(path: Option<PathBuf>) {
+ TEST_LOG.with(|t| *t.borrow_mut() = path);
+}
+
+pub fn log_path() -> Option<PathBuf> {
+ #[cfg(test)]
+ let chosen = TEST_LOG.with(|t| t.borrow().clone());
+ #[cfg(not(test))]
+ let chosen = std::env::var_os("KLAD_LOG")
+ .map(PathBuf::from)
+ .or_else(|| crate::places::config().map(|c| c.join("klad").join("klad.log")));
+ chosen
+}
+
+pub fn log(line: &str) {
+ let Some(path) = log_path() else {
+ return;
+ };
+ if fs::metadata(&path).is_ok_and(|m| m.len() > LOG_LIMIT) {
+ let kept = fs::read_to_string(&path).unwrap_or_default();
+ let half = kept.len() / 2;
+ let from = kept[half..].find('\n').map_or(kept.len(), |i| half + i + 1);
+ let _ = fs::write(&path, &kept[from..]);
+ }
+ if let Some(dir) = path.parent() {
+ let _ = fs::create_dir_all(dir);
+ }
+ if let Ok(mut file) = fs::OpenOptions::new().create(true).append(true).open(&path) {
+ let _ = writeln!(file, "{} {}", stamp(crate::updates::now()), line.replace('\n', " "));
+ }
+}
+
+pub fn last_lines(n: usize) -> Vec<String> {
+ let text = log_path().and_then(|p| fs::read_to_string(p).ok()).unwrap_or_default();
+ let lines: Vec<String> = text.lines().map(str::to_string).collect();
+ lines[lines.len().saturating_sub(n)..].to_vec()
+}
+
+pub fn stamp(secs: u64) -> String {
+ let days = (secs / 86_400) as i64;
+ let rest = secs % 86_400;
+ let z = days + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z - era * 146_097;
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let day = doy - (153 * mp + 2) / 5 + 1;
+ let month = if mp < 10 { mp + 3 } else { mp - 9 };
+ let year = yoe + era * 400 + i64::from(month <= 2);
+ format!(
+ "{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02}",
+ rest / 3600,
+ rest / 60 % 60,
+ rest % 60
+ )
+}
+
+fn output(program: &str, args: &[&str]) -> Option<String> {
+ let out = std::process::Command::new(program).args(args).output().ok()?;
+ let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
+ (out.status.success() && !text.is_empty()).then_some(text)
+}
+
+pub fn system() -> String {
+ let name = match std::env::consts::OS {
+ "macos" => output("sw_vers", &["-productVersion"]).map(|v| format!("macOS {v}")),
+ "linux" => fs::read_to_string("/etc/os-release").ok().and_then(|t| {
+ t.lines()
+ .find_map(|l| l.strip_prefix("PRETTY_NAME="))
+ .map(|v| v.trim_matches('"').to_string())
+ }),
+ "windows" => output("cmd", &["/c", "ver"]),
+ _ => None,
+ }
+ .unwrap_or_else(|| std::env::consts::OS.to_string());
+ format!("{name} on {}", std::env::consts::ARCH)
+}
+
+pub fn private(text: &str, folder: Option<&Path>) -> String {
+ let hidden = folder
+ .map(|f| (f.display().to_string(), "<the drawing's folder>"))
+ .into_iter()
+ .chain(crate::places::home().map(|h| (h.display().to_string(), "~")))
+ .filter(|(from, _)| from.len() > 1);
+ hidden.fold(text.to_string(), |t, (from, to)| t.replace(&from, to))
+}
+
+fn count(n: usize, one: &str) -> String {
+ match n {
+ 1 => format!("1 {one}"),
+ n => format!("{n} {one}s"),
+ }
+}
+
+pub fn summary(doc: &klad_core::doc::Document) -> String {
+ format!(
+ "{} by {} px, {}, {}",
+ doc.canvas.width,
+ doc.canvas.height,
+ count(doc.all_layers().len(), "layer"),
+ count(doc.timeline.frames as usize, "frame")
+ )
+}
+
+pub fn panic_text(info: &std::panic::PanicHookInfo) -> String {
+ let what = info
+ .payload()
+ .downcast_ref::<&str>()
+ .map(|s| s.to_string())
+ .or_else(|| info.payload().downcast_ref::<String>().cloned())
+ .unwrap_or_default();
+ let place = info
+ .location()
+ .map(|l| format!(" at {}:{}", l.file(), l.line()))
+ .unwrap_or_default();
+ format!("{}{place}", what.replace('\n', " "))
+}
+
+pub struct Report {
+ pub from: &'static str,
+ pub folder: Option<PathBuf>,
+ pub drawing: Option<String>,
+ pub attached: Option<String>,
+ pub messages: Vec<String>,
+ pub log: Vec<String>,
+}
+
+impl Report {
+ pub fn text(&self) -> String {
+ let mut out = vec![
+ format!("klad {}, {}", crate::VERSION, self.from),
+ system(),
+ String::new(),
+ "What I did, what I expected and what happened instead:".to_string(),
+ String::new(),
+ String::new(),
+ ];
+ if let Some(drawing) = &self.drawing {
+ out.push(match &self.attached {
+ Some(file) => format!("The drawing ({drawing}) is attached as {file}."),
+ None => format!("The drawing ({drawing}) is not attached."),
+ });
+ }
+ [
+ ("Last messages:", &self.messages),
+ ("Last lines of klad's log:", &self.log),
+ ]
+ .into_iter()
+ .filter(|(_, lines)| !lines.is_empty())
+ .for_each(|(title, lines)| {
+ out.push(String::new());
+ out.push(title.to_string());
+ out.extend(lines.iter().map(|l| private(l, self.folder.as_deref())));
+ });
+ out.join("\n") + "\n"
+ }
+}
+
+fn files(dir: &Path, prefix: &str, out: &mut Vec<(String, PathBuf)>) -> Result<()> {
+ let mut entries: Vec<_> = fs::read_dir(dir)?.filter_map(|e| e.ok()).collect();
+ entries.sort_by_key(|e| e.file_name());
+ entries
+ .into_iter()
+ .filter(|e| e.file_name() != ".cache")
+ .try_for_each(|e| {
+ let name = format!("{prefix}/{}", e.file_name().to_string_lossy());
+ match e.file_type()?.is_dir() {
+ true => files(&e.path(), &name, out),
+ false => {
+ out.push((name, e.path()));
+ Ok(())
+ }
+ }
+ })
+}
+
+pub fn zip_drawing(bundle: &Path, to: &Path) -> Result<()> {
+ let root = bundle
+ .file_name()
+ .map_or_else(|| "drawing.klad".to_string(), |n| n.to_string_lossy().to_string());
+ let mut listed = Vec::new();
+ files(bundle, &root, &mut listed)?;
+ let mut out: Vec<u8> = Vec::new();
+ let mut central: Vec<u8> = Vec::new();
+ let put16 = |v: &mut Vec<u8>, x: u16| v.extend_from_slice(&x.to_le_bytes());
+ let put32 = |v: &mut Vec<u8>, x: u32| v.extend_from_slice(&x.to_le_bytes());
+ listed.iter().try_for_each(|(name, path)| -> Result<()> {
+ let data = fs::read(path)?;
+ let (Ok(size), Ok(offset)) = (u32::try_from(data.len()), u32::try_from(out.len())) else {
+ bail!("the drawing is too big to zip for a report; attach its folder another way");
+ };
+ let crc = crc32fast::hash(&data);
+ let header = |v: &mut Vec<u8>| {
+ put16(v, 20);
+ put16(v, 0x0800);
+ put16(v, 0);
+ put16(v, 0);
+ put16(v, 0x21);
+ put32(v, crc);
+ put32(v, size);
+ put32(v, size);
+ put16(v, name.len() as u16);
+ put16(v, 0);
+ };
+ put32(&mut out, 0x0403_4b50);
+ header(&mut out);
+ out.extend_from_slice(name.as_bytes());
+ out.extend_from_slice(&data);
+ put32(&mut central, 0x0201_4b50);
+ put16(&mut central, 20);
+ header(&mut central);
+ [0u16, 0, 0].iter().for_each(|x| put16(&mut central, *x));
+ put32(&mut central, 0);
+ put32(&mut central, offset);
+ central.extend_from_slice(name.as_bytes());
+ Ok(())
+ })?;
+ let (Ok(start), Ok(length), Ok(count)) = (
+ u32::try_from(out.len()),
+ u32::try_from(central.len()),
+ u16::try_from(listed.len()),
+ ) else {
+ bail!("the drawing is too big to zip for a report; attach its folder another way");
+ };
+ out.extend_from_slice(&central);
+ put32(&mut out, 0x0605_4b50);
+ [0u16, 0, count, count].iter().for_each(|x| put16(&mut out, *x));
+ put32(&mut out, length);
+ put32(&mut out, start);
+ put16(&mut out, 0);
+ fs::write(to, out)?;
+ Ok(())
+}
+
+pub fn zip_beside(bundle: &Path) -> Result<PathBuf> {
+ let stem = bundle
+ .file_stem()
+ .map_or_else(|| "drawing".to_string(), |s| s.to_string_lossy().to_string());
+ let to = bundle.with_file_name(format!("{stem} for a report.zip"));
+ zip_drawing(bundle, &to)?;
+ Ok(to)
+}
+
+#[cfg(test)]
+pub fn unzip_names(bytes: &[u8]) -> Vec<(String, bool)> {
+ let mut found = Vec::new();
+ let mut at = 0;
+ while bytes.len() >= at + 30 && bytes[at..at + 4] == 0x0403_4b50u32.to_le_bytes() {
+ let read32 = |i: usize| u32::from_le_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]);
+ let read16 = |i: usize| u16::from_le_bytes([bytes[i], bytes[i + 1]]) as usize;
+ let (crc, size, name_len) = (read32(at + 14), read32(at + 18) as usize, read16(at + 26));
+ let name = String::from_utf8_lossy(&bytes[at + 30..at + 30 + name_len]).to_string();
+ let data = &bytes[at + 30 + name_len..at + 30 + name_len + size];
+ found.push((name, crc32fast::hash(data) == crc));
+ at += 30 + name_len + size;
+ }
+ found
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_failed_job_says_why_and_a_crash_points_at_the_report() {
+ assert_eq!(
+ job_failed("export to Godot", "error: no clip run in art.klad"),
+ "export to Godot did not finish: no clip run in art.klad"
+ );
+ let crashed = job_failed(
+ "pose at frame 4",
+ "error: klad hit a bug: index out of bounds at crates/core/src/rig.rs:10. KLAD_BACKTRACE=1 shows the details; please report it at https://github.com/klad-app/klad/issues",
+ );
+ assert!(crashed.starts_with(
+ "something went wrong inside klad (pose at frame 4: index out of bounds at crates/core/src/rig.rs:10)"
+ ));
+ assert!(!crashed.contains("KLAD_BACKTRACE") && crashed.contains("Help > Report a problem"));
+ }
+
+ #[test]
+ fn dates_read_as_dates() {
+ assert_eq!(stamp(0), "1970-01-01 00:00:00");
+ assert_eq!(stamp(1_793_986_200), "2026-11-06 17:30:00");
+ }
+
+ #[test]
+ fn the_log_keeps_its_last_lines_and_stays_small() {
+ let dir = std::env::temp_dir().join(format!("klad-log-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ log_to(Some(dir.join("klad.log")));
+ (0..20).for_each(|i| log(&format!("line {i}\nwrapped")));
+ let last = last_lines(3);
+ assert_eq!(last.len(), 3);
+ assert!(last[2].ends_with("line 19 wrapped"), "{last:?}");
+ fs::write(dir.join("klad.log"), "x\n".repeat(400_000)).unwrap();
+ log("after");
+ assert!(fs::metadata(dir.join("klad.log")).unwrap().len() < LOG_LIMIT);
+ assert!(last_lines(1)[0].ends_with("after"));
+ log_to(None);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn a_drawing_zips_without_its_cache_and_every_file_checks_out() {
+ let dir = std::env::temp_dir().join(format!("klad-zip-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let bundle = dir.join("rock.klad");
+ klad_core::bundle::Bundle::blank(&bundle, &klad_core::bundle::Blank::default(), "cli").unwrap();
+ fs::create_dir_all(bundle.join(".cache")).unwrap();
+ fs::write(bundle.join(".cache/thumb.png"), b"x").unwrap();
+ let zip = zip_beside(&bundle).unwrap();
+ assert_eq!(zip, dir.join("rock for a report.zip"));
+ let bytes = fs::read(&zip).unwrap();
+ let names = unzip_names(&bytes);
+ assert!(
+ names.iter().any(|(n, ok)| n == "rock.klad/doc.json" && *ok),
+ "{names:?}"
+ );
+ assert!(names.iter().all(|(n, ok)| *ok && !n.contains(".cache")));
+ assert_eq!(
+ &bytes[bytes.len() - 22..bytes.len() - 18],
+ &0x0605_4b50u32.to_le_bytes()
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 2b58d4a..830ebfd 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -1718,6 +1718,15 @@ enum Command {
#[command(hide = true, about = "Print the command reference, docs/cli.md")]
Reference,
#[cfg(feature = "editor")]
+ #[command(
+ about = "Print a problem report to paste into an issue: version, system and the last lines of klad's log",
+ long_about = "Print a problem report to paste into a new issue on klad's GitHub page: klad's version, your system and the last lines of klad's log (errors the editor showed, and crashes), with your home folder written as ~. Nothing is sent. --drawing names the drawing's size and zips it next to itself, without its cache, to attach to the issue; the editor's Help > Report a problem does the same, with its last messages. KLAD_LOG points at another log file.\n\n klad report\n klad report --drawing art.klad"
+ )]
+ Report {
+ #[arg(long, help = "A drawing to zip next to itself and attach")]
+ drawing: Option<PathBuf>,
+ },
+ #[cfg(feature = "editor")]
#[command(
about = "Check now whether a newer klad is out (the editor also checks once a day by itself)",
long_about = "Check now whether a newer klad is out, on klad's releases page (the editor also checks once a day by itself, and its About window has check now). KLAD_UPDATE_FEED points it at another feed, a URL or a JSON file shaped like GitHub's latest release.\n\n klad updates"
@@ -1851,7 +1860,15 @@ fn main() {
}
match traced {
true => unsafe { std::env::set_var("RUST_BACKTRACE", "1") },
- false => std::panic::set_hook(Box::new(|info| eprintln!("error: {}", bug(info)))),
+ false => std::panic::set_hook(Box::new(|info| {
+ #[cfg(feature = "editor")]
+ klad_app::report::log(&format!(
+ "klad {}: {}",
+ std::env::args().nth(1).unwrap_or_default(),
+ klad_app::report::panic_text(info)
+ ));
+ eprintln!("error: {}", bug(info))
+ })),
}
if let Err(e) = run() {
match traced {
@@ -3313,6 +3330,38 @@ fn run() -> Result<()> {
Command::Samples { copy, into, json } => samples(copy.as_deref(), into, json)?,
Command::Reference => print!("{}", reference()),
#[cfg(feature = "editor")]
+ Command::Report { drawing } => {
+ use klad_app::report;
+ let (summary, attached) = match &drawing {
+ Some(d) => {
+ let opened = Bundle::open(d)?;
+ (Some(report::summary(&opened.doc)), Some(report::zip_beside(d)?))
+ }
+ None => (None, None),
+ };
+ print!(
+ "{}",
+ report::Report {
+ from: "from the command line",
+ folder: drawing
+ .as_ref()
+ .and_then(|d| d.parent())
+ .map(std::path::Path::to_path_buf),
+ drawing: summary,
+ attached: attached
+ .as_ref()
+ .and_then(|p| p.file_name())
+ .map(|n| n.to_string_lossy().to_string()),
+ messages: Vec::new(),
+ log: report::last_lines(report::LOG_LINES),
+ }
+ .text()
+ );
+ if let Some(zip) = attached {
+ eprintln!("attach {} to the issue", zip.display());
+ }
+ }
+ #[cfg(feature = "editor")]
Command::Updates => {
use klad_app::updates;
let checked = updates::check(&updates::feed(), env!("CARGO_PKG_VERSION"));
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index 3c63414..f7eb0e9 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -179,3 +179,48 @@ fn samples_are_listed_and_copied_to_draw_on() {
assert!(String::from_utf8_lossy(&wrong.stderr).contains("no sample stone; there are rock"));
std::fs::remove_dir_all(&dir).unwrap();
}
+
+#[test]
+fn a_report_holds_the_version_the_log_with_home_hidden_and_zips_the_drawing() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-report-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let home = dir.join("home");
+ let log = dir.join("klad.log");
+ std::fs::write(
+ &log,
+ format!("2026-11-06 17:00:00 editor: could not read {}/x.png\n", home.display()),
+ )
+ .unwrap();
+ let bundle = dir.join("drawings/rock.klad");
+ let run = |args: &[&str]| {
+ Command::new(env!("CARGO_BIN_EXE_klad"))
+ .args(args)
+ .env("KLAD_LOG", &log)
+ .env("HOME", &home)
+ .output()
+ .unwrap()
+ };
+ assert!(
+ run(&["new", bundle.to_str().unwrap(), "--width", "64", "--height", "48"])
+ .status
+ .success()
+ );
+ let out = run(&["report", "--drawing", bundle.to_str().unwrap()]);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ let text = String::from_utf8_lossy(&out.stdout).to_string();
+ assert!(
+ text.starts_with("klad ") && text.contains("from the command line"),
+ "{text}"
+ );
+ assert!(
+ text.contains("could not read ~/x.png"),
+ "the home folder reads as ~: {text}"
+ );
+ assert!(
+ text.contains("The drawing (64 by 48 px, 1 layer, 1 frame) is attached as rock for a report.zip."),
+ "{text}"
+ );
+ assert!(dir.join("drawings/rock for a report.zip").is_file());
+ std::fs::remove_dir_all(&dir).unwrap();
+}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 9f187e4..d903e48 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-06 17:33_
+_Last updated: 2026-11-06 17:46_
# klad: design
@@ -424,6 +424,7 @@ An error is one line on stderr (`error: reading a.klad/doc.json: No such file or
| `klad compare <drawing\|png> <reference> [--frame] [--region name=x,y,w,h]... [--heat out.png] [--json]` | values, saturation, texture, edges and colour against a reference, in numbers and words |
| `klad install [--dir]`, `klad skill` | put `klad` on the terminal's path; print the agent skill |
| `klad samples [--json]`, `klad samples --copy <name> [--into <folder>]` | the sample drawings a build carries; copy one to draw on |
+| `klad report [--drawing <bundle>]` | a problem report to paste into an issue, the drawing zipped to attach |
Scripts are any language that prints edit ops as JSON lines into `klad apply`. Generators that should stay editable (scatter, repeat, symmetry) are built-in vector node kinds with parameters.
@@ -436,7 +437,8 @@ Scripts are any language that prints edit ops as JSON lines into `klad apply`. G
- Commands (M4 batch 1): every editor action is a `Cmd` in one list (`commands.rs`): an id (`tool.brush`, `drawing.new`, kept in settings), a name in plain words, a Phosphor icon, a group, its keys or the hold that triggers it, whether a held key repeats it, and a line on what it does. Keys, the strip, panel buttons, the timeline's buttons and context menu, and the palette all run commands through `Editor::invoke`, which first asks `can_run` (a reason when it cannot, shown as a refusal) and remembers the last twelve run. A key matches only with exactly its modifiers (shift K is not K); key repeats run commands that repeat (`=`, `[`, cmd Z) and frame steps only once the frame on screen caught up. cmd K opens the palette: type to filter (name start, then a key, a word, a substring, the letters in order, the group; hyphens ignored, so "inb" finds in-between), arrows and Return run, rows grey out with the reason, recent commands first; `?` opens it too. Every control has a hover hint after 0.35 s (from its command where there is one) and is at least 24 pt high; a test walks every control of every panel and window to keep it so.
- Tool options and selections (M4 batch 2): a bar over the canvas holds the active tool's settings (brush: picker, size, opacity, flow, and a "more" menu for hardness, lightest size, curve, taper, stabiliser and smoothing; fill: reference, gap, tolerance, grow, opacity; strokes: cut at the lasso edge, select all; points: corner, smooth, simplify, make it a path). The strip shows the eraser while the eraser brush or the pen's eraser end is on, and two colours (the current one over the second; X or a click swaps them; picking a colour from a swatch, the hex field or the eyedropper makes the old one the second). cmd alt drag sideways on the canvas sizes the brush (doubling every 120 pt), the circle staying where the drag began. H flips the view left-right (the view's mappings and the GPU matrix mirror; the document does not change); the status line's zoom takes a click for 100% and a double-click to fit, its rotation a click to turn upright. A selection bar sits under (or over) the selection's box: for strokes flips, quarter turns, recolour, thinner, thicker, opacity, copy, paste, duplicate in place, delete, deselect; for a shape flips (sx or sy negated and its rotation mirrored), quarter turns, duplicate in place (an `add` of the node without ids, above it), delete, deselect; for points corner, smooth, nudges, delete. Arrows nudge strokes, a shape or points by 1 px, 10 px with shift. Strokes select across layers (M5 batch 2 round 1): cmd or shift click on rows in the layers panel adds paint layers to the active one (marked with a blue edge); S then lassos, clicks and selects all on all of them, and the selection (one part per layer) moves, turns, scales, flips, recolours, cuts at the lasso edge, copies and deletes as one edit, each layer's marks staying on their layer. A selection on several layers drags as its outline (no GPU lift) and lands on release; copies of several layers paste back into their own layers, a copy of one layer into the active one. The strip's panels button lists the five panels and the timeline with a tick each, so a closed panel always has a way back. U draws rectangles and ellipses on a vector layer (shift for a square or circle, alt from the centre, rounded corners for rectangles; fill, outline and width shared with the pen, the fill in the first colour and the outline in the second, as for the pen's paths) as `rect` and `ellipse` nodes. Mirror painting (the brush bar's "mirror" and its axis) paints every stroke's mirror image as it is drawn, in a second stroke buffer landed after the first, and commits both as plain marks in one history step. Handles are drawn at 12 pt and hit within 12 pt (`grab`); shapes whose rotation is a quarter turn get edge handles too (`lift::stretched` scales their own axis). Pen events that arrive while a shape move or point edit is being written are held and replayed in order after it. The colour and brush pane shows the palette (swatches drag to reorder; the x in a hovered swatch's corner, or a right-click, removes it), recent colours, size presets and the brushes as tiles, each with a sample stroke drawn by `klad-brush` once per brush definition.
- First start (S8.7, `start.rs`, `editor/first.rs`, `klad_core::samples`): until the settings say `welcomed` (set when any drawing opens, or by "Not now"), the start window opens with a welcome offering first steps. First steps make `first steps.klad` (1280 by 800 on paper, one paint layer) in the drawings folder and open it with a small window of three steps that tick as they happen: a brush stroke is saved, a fill is saved, the request for an agent is copied (a sentence with the drawing's path asking the agent to read `klad skill`, render the drawing and add a shadow; "install the klad command" sits next to it). Help > First steps opens and closes the window on any drawing. The checklist is the editor's alone: it teaches the hands on the canvas, and an agent's first steps are `klad skill`. Revisit the third step when klad is an MCP server (S8.10). Under the recent drawings the start window shows the samples: the drawings `samples/shipped.json` names (name, bundle, a line on what it shows), each a card with its thumbnail and that line; a click copies it into the drawings folder without its `.cache` (`samples::copy`, `<name>.klad` or `<name> 2.klad`) and opens the copy, so a sample is never changed. `klad samples` lists the same set and `--copy <name> [--into folder]` copies one (default the current folder). Samples are found like the fonts: `KLAD_SAMPLES`, then `samples/` next to the binary, `../Resources/samples`, `../share/klad/samples`, and a source checkout's `samples/` up to five folders above the binary (where they exist after `just samples`; a sample not built is left out). `packaging/samples.sh` puts them in every build: it builds any that are missing with that build's `klad` (through the sample's `build.sh`, `PYTHON` naming the interpreter), copies them without caches, and renders each one's `<name>.thumb.png` next to it at 336 px, so the start window never renders into the app (a thumbnail outside the bundle is used as it is; only recent drawings' `.cache/thumb.png` are remade when the drawing changes). `app.sh` puts them in `Resources/samples`, `archive.sh` in the archive's `samples/` and the AppImage's `usr/share/klad/samples`; the six weigh about 4 MB.
-- Menus (S8.6, `commands::MENUS`, `menus.rs`): one list of menus (File, Edit, Draw, View, Layer, Frame, Help) holds every command but the holds (pan, zoom, the eyedropper, flipping, rolling, the parallax preview and sizing on the canvas, which are gestures), so the menus, the palette and the keys stay one list; a test fails when a command is in no menu or in two. Items are the commands' names with their first letter capitalised and their keys; toggles show a tick; a command that cannot run now is greyed out (its reason is the palette's). On macOS the list becomes the system menu bar (`menus::install`, rebuilt when the keys or the recent drawings change): an app menu with About, Settings, Services, hide and Quit, then the list, Window and Help. Items target one Objective-C object (`KladMenuTarget`, `define_class!`) whose `kladRun:` queues the command for the next frame (the editor runs it through `Editor::invoke` as any key would) and whose `validateMenuItem:` reads a snapshot of what is off and on that the app refreshes every 0.4 s. The item keys are shown but not claimed: the object is each menu's delegate and answers no to `menuHasKeyEquivalent:forEvent:target:action:`, so a key still reaches the editor's own dispatch (which knows holds, repeats and text fields) and nothing runs twice; only the app menu's own keys (cmd , cmd Q cmd H) and Window's cmd M are AppKit's. On Windows and Linux (and in tests) the same list is an egui menu bar over the window, hidden with the panels (Tab). File > Open recent lists the last ten drawings; File > Close the drawing (cmd W, refused while a job runs) goes back to the start window, where only new, open, recent and quit run. Settings, About and Quit sit in the app menu on macOS and in Edit, Help and File elsewhere.
+- Messages and problem reports (S8.8, `report.rs`): a message says what happened and what to do next ("nothing to fill there: click inside closed lines, or raise the gap so small openings close"); a refusal names the step that makes the command possible. Errors that mean klad itself went wrong (an invariant broken, a picture missing that should be there) are `report::Bug`s: the editor says "something went wrong inside klad (what), everything up to your last edit is saved; Help > Report a problem copies what an issue needs" instead of the bare detail; a job whose CLI crashed reads the same, and a job that failed says "<job> did not finish: <the CLI's reason>". Every error message, job failure and crash of the editor or the CLI is appended to `klad.log` next to the settings (`KLAD_LOG` overrides it; past 512 KB the older half goes), one dated line each. Help > Report a problem opens a window with the report as it will be copied: klad's version and where it ran, the system (macOS version, the Linux distribution, Windows' version, and the processor), a place for what happened, the drawing's size, the last 40 messages and the last 40 lines of the log, with the home folder written as `~` and the drawing's folder as `<the drawing's folder>`. "include the drawing" zips the drawing without its cache next to it (`<name> for a report.zip`, stored entries, written by klad itself) and the report names the file to attach; "copy the report" copies it and "open klad's issues" opens GitHub. Nothing is sent by klad. `klad report [--drawing <bundle>]` prints the same report from the command line (version, system, log, the drawing zipped).
+- Menus (S8.6, `commands::MENUS`, `menus.rs`): one list of menus (File, Edit, Draw, View, Layer, Frame, Help) holds every command but the holds (pan, zoom, the eyedropper, flipping, rolling, the parallax preview and sizing on the canvas, which are gestures), so the menus, the palette and the keys stay one list; a test fails when a command is in no menu or in two. Items are the commands' names with their first letter capitalised and their keys; toggles show a tick; a command that cannot run now is greyed out (its reason is the palette's). On macOS the list becomes the system menu bar (`menus::install`, rebuilt when the keys or the recent drawings change): an app menu with About, Settings, Services, hide and Quit, then the list, Window and Help. Items target one Objective-C object (`KladMenuTarget`, `define_class!`) whose `kladRun:` queues the command for the next frame (the editor runs it through `Editor::invoke` as any key would) and whose `validateMenuItem:` reads a snapshot of what is off and on that the app refreshes every 0.4 s. The item keys are shown but not claimed: the object is each menu's delegate and answers no to `menuHasKeyEquivalent:forEvent:target:action:`, so a key still reaches the editor's own dispatch (which knows holds, repeats and text fields) and nothing runs twice; only the app menu's own keys (cmd , cmd Q cmd H) and Window's cmd M are AppKit's. On Windows and Linux (and in tests) the same list is an egui menu bar over the window, hidden with the panels (Tab). File > Open recent lists the last ten drawings; File > Close the drawing (cmd W, refused while a job runs) goes back to the start window, where only new, open, recent and quit run. Settings and Quit sit in the app menu on macOS and in Edit and File elsewhere; About (with the licences) is in Help everywhere and also in the macOS app menu.
- Messages and jobs (M4 batch 1): every result, refusal and error goes through `Editor::say` with a tone (info, done, refused, error). Done and refused messages show for 3.5 and 6 s as a toast next to the pointer where the user acted (jobs' messages at the bottom right), errors until dismissed, info only in the status line; the status line shows the latest message (a click opens the message log, the last 200 with times), the frame, where the next stroke goes ("draws into c12 on lines, frames 4 to 7"), running jobs with a cancel button, slow internal work (preparing a selection, drawing an edited path, loading a frame), zoom and rotation. Times that used to be status text (stroke, fill, edit, undo, sync, frame step, last play, last job) are kept by name for the numbers window. Background jobs (in-betweens, Godot export) run the same `klad` binary through one job list (`jobs.rs`); when the CLI exits with code 75 (the document changed while it computed) the job runs again, up to three times, so an edit made in the editor meanwhile is never overwritten.
- Tools: brush, eraser, smudge, fill (inside lines, gap closing), lasso select and transform, move/rotate/scale handles, path point editing, eyedropper.
- Stroke select (S, M2): click picks the topmost stroke or fill on the active paint layer under the pointer, a dragged loop picks every stroke whose samples are all inside it and every fill whose pixels are, shift adds or toggles. With "a lasso cuts strokes at its edge" (on by default) the loop also takes the parts of strokes and fills crossing it: the selection shows the dashed lasso and the parts that will move, and the first edit (move, recolour, delete, ...) writes one `lasso` op that splits them, after which the selection is the moved marks. The selection shows as thin lines and a box with corner handles (uniform scale), edge handles (stretch one axis; dragging past the other edge flips) and a rotate knob; dragging moves it on the GPU (the selected marks drawn alone, over the cel replayed without them) and release writes one `transform` or `lasso` op. The inspector recolours (the current colour), makes thinner or thicker, sets opacity, flips left-right or up-down and deletes, each as one history step. The selection is shared with the agent as addresses.
diff --git a/docs/cli.md b/docs/cli.md
index 7d201d8..db663bc 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -76,6 +76,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
- [`klad install`](#klad-install): Put klad on the terminal's path, for you and for agents
- [`klad skill`](#klad-skill): Print the agent skill: how an agent draws with klad (the same text as docs/skill/SKILL.md)
- [`klad samples`](#klad-samples): List the sample drawings that come with klad, or copy one to draw on
+- [`klad report`](#klad-report): Print a problem report to paste into an issue: version, system and the last lines of klad's log
- [`klad updates`](#klad-updates): Check now whether a newer klad is out (the editor also checks once a day by itself)
- [`klad bench`](#klad-bench): Measure stroke storage, brush speed, replay, cache and compositing
- [`klad open`](#klad-open): Open the editor, on a bundle or on the start window (new, open, recent)
@@ -3324,6 +3325,24 @@ Options:
Print help (see a summary with '-h')
```
+## klad report
+
+```text
+Print a problem report to paste into a new issue on klad's GitHub page: klad's version, your system and the last lines of klad's log (errors the editor showed, and crashes), with your home folder written as ~. Nothing is sent. --drawing names the drawing's size and zips it next to itself, without its cache, to attach to the issue; the editor's Help > Report a problem does the same, with its last messages. KLAD_LOG points at another log file.
+
+ klad report
+ klad report --drawing art.klad
+
+Usage: klad report [OPTIONS]
+
+Options:
+ --drawing <DRAWING>
+ A drawing to zip next to itself and attach
+
+ -h, --help
+ Print help (see a summary with '-h')
+```
+
## klad updates
```text
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 35061b2..28fd12f 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -6,7 +6,7 @@ description: Make and edit 2D art with the klad CLI (`klad`) in a `.klad` bundle
# klad
-A `.klad` bundle is a folder: `doc.json` (layers, cels, vector nodes, palette), `strokes/<layer>/<cel>.strokes` (paint strokes and fills as data), `brushes/<id>.json` (every brush its strokes use) and `.cache/` (renders, history, notes, tiles). The `klad` CLI edits it; the user edits the same bundle in the editor (`klad open`, or the klad app). Both see each other's changes within a second. The user starts and opens drawings from the editor's start window (cmd N, cmd O, recent) and can copy a drawing's path from File (the menu bar) or the document menu at the bottom of the tool strip to hand it to you. To start one yourself: `klad new art.klad --width 1600 --height 1200 --background '#e9e4da' --sketch` (one paint layer, `l1`, and a vector layer named sketch on top, `l3`). If `klad` is not on the path, the user can run "install the klad command" from that menu (or `klad install` from the folder they unpacked); `klad skill` prints these instructions, matching the version installed. `klad samples` lists the sample drawings that come with klad, and `klad samples --copy lantern` copies one into the current folder to read, render or draw on: a quick way to see how a finished piece is layered.
+A `.klad` bundle is a folder: `doc.json` (layers, cels, vector nodes, palette), `strokes/<layer>/<cel>.strokes` (paint strokes and fills as data), `brushes/<id>.json` (every brush its strokes use) and `.cache/` (renders, history, notes, tiles). The `klad` CLI edits it; the user edits the same bundle in the editor (`klad open`, or the klad app). Both see each other's changes within a second. The user starts and opens drawings from the editor's start window (cmd N, cmd O, recent) and can copy a drawing's path from File (the menu bar) or the document menu at the bottom of the tool strip to hand it to you. To start one yourself: `klad new art.klad --width 1600 --height 1200 --background '#e9e4da' --sketch` (one paint layer, `l1`, and a vector layer named sketch on top, `l3`). If `klad` is not on the path, the user can run "install the klad command" from that menu (or `klad install` from the folder they unpacked); `klad skill` prints these instructions, matching the version installed. When klad itself fails (an error that starts "klad hit a bug"), tell the user and offer `klad report --drawing <bundle>`: it prints a report for an issue and zips the drawing to attach. `klad samples` lists the sample drawings that come with klad, and `klad samples --copy lantern` copies one into the current folder to read, render or draw on: a quick way to see how a finished piece is layered.
Working on klad itself: the repository's `CLAUDE.md`, `CONTRIBUTING.md` and `docs/DESIGN.md` are the source of truth. Build the CLI with `just compile` (`just build` also counts the version up, for the person making a build); the binary is `target/release/klad` on macOS and `target/linux/release/klad` on Linux.