A drawing app built for agent/human collaboration
Rust
The editor gets the CLI-only features: refill, fill like, gaps, parts, arcs, export, fonts
Indicode BVfa3fd74b13e0
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rsindex 5a15a17..7c8e16c 100644--- a/crates/app/src/commands.rs+++ b/crates/app/src/commands.rs@@ -147,6 +147,13 @@ pub enum Cmd {OpenRecent,CopyPath,About,+ Export,+ AddFont,+ Refill,+ FillLike,+ ShowGaps,+ ShowParts,+ ShowArcs,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -461,7 +468,7 @@ use Repeat as R;use Trigger as T;impl Cmd {- pub const ALL: [Cmd; 143] = [+ pub const ALL: [Cmd; 150] = [Cmd::Brush,Cmd::Eraser,Cmd::Fill,@@ -605,6 +612,13 @@ impl Cmd {Cmd::OpenRecent,Cmd::CopyPath,Cmd::About,+ Cmd::Export,+ Cmd::AddFont,+ Cmd::Refill,+ Cmd::FillLike,+ Cmd::ShowGaps,+ Cmd::ShowParts,+ Cmd::ShowArcs,];pub fn spec(self) -> Spec {@@ -1869,6 +1883,69 @@ impl Cmd {R::No,"the drawings opened lately, with thumbnails",),+ Cmd::Export => spec(+ "file.export",+ "export",+ icon::EXPORT,+ G::File,+ T::Press(const { &[cmd(Key::E)] }),+ R::No,+ "export this frame, a layer, numbered frames or a sprite sheet as PNGs, as klad export does",+ ),+ Cmd::AddFont => spec(+ "file.font",+ "add a font",+ icon::PLUS,+ G::File,+ T::None,+ R::No,+ "copy a font file into the drawing so its text can use it",+ ),+ Cmd::Refill => spec(+ "colour.refill",+ "refill this drawing",+ icon::FILL,+ G::Colour,+ T::None,+ R::No,+ "make the flood fills of the active drawing again after its lines changed",+ ),+ Cmd::FillLike => spec(+ "colour.fill-like",+ "fill like the first drawing",+ icon::COPY,+ G::Colour,+ T::None,+ R::No,+ "carry the fills of the first selected drawing to the other selected frames",+ ),+ Cmd::ShowGaps => spec(+ "colour.gaps",+ "show gaps",+ icon::SEARCH,+ G::Colour,+ T::None,+ R::No,+ "outline the closed regions no fill covers on the active layer, on this frame or the selected frames",+ ),+ Cmd::ShowParts => spec(+ "view.parts",+ "show parts",+ icon::SHAPES,+ G::View,+ T::None,+ R::No,+ "box and name each part of the active drawing",+ ),+ Cmd::ShowArcs => spec(+ "view.arcs",+ "show arcs",+ icon::TURN,+ G::View,+ T::None,+ R::No,+ "draw the path the selected mark or part takes over the clip, a dot per frame",+ ),Cmd::About => spec("file.about","about klad and licences",diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 9500a1d..bbd17b8 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -2,10 +2,12 @@ mod between;mod brushwin;mod buffer;mod cells;+mod checks;mod clips;mod commands;mod copy;mod depth;+mod export;mod history;mod layers;mod look;@@ -499,6 +501,8 @@ struct Windows {between: bool,import: bool,about: bool,+ export: bool,+ font: bool,}#[derive(Default)]@@ -589,6 +593,8 @@ pub(crate) struct Editor {pen_width: f32,thumbs: layers::Thumbs,between: between::Between,+ checks: checks::Checks,+ export: export::Form,bindings: crate::commands::Bindings,capturing: Option<Cmd>,key_filter: String,@@ -740,6 +746,8 @@ impl Editor {pen_width: 3.0,thumbs: layers::Thumbs::default(),between: between::Between::default(),+ checks: checks::Checks::default(),+ export: export::Form::default(),bindings: crate::commands::Bindings::default(),capturing: None,key_filter: String::new(),@@ -887,6 +895,8 @@ impl Editor {fn reload(&mut self) -> Result<()> {let seen = self.external.take();+ self.checks.gaps = None;+ self.checks.arcs = None;let start = Instant::now();self.brushes.refresh(&self.scene.bundle)?;self.embedded = self.scene.bundle.brushes()?;@@ -966,6 +976,8 @@ impl Editor {}fn apply(&mut self, ops: Vec<Op>) -> Result<()> {+ self.checks.gaps = None;+ self.checks.arcs = None;if ops.is_empty() {return Ok(());}@@ -2929,6 +2941,7 @@ impl Editor {painter.circle_stroke(knob, HANDLE / 2.0 + 1.0, egui::Stroke::new(1.0, accent));}self.draw_pins(&painter, |c| self.screen(view, rect, c));+ self.draw_checks(&painter, |c| self.screen(view, rect, c));if let Some(lasso) = self.lasso.as_ref().filter(|l| l.far) {let line: Vec<Pos2> = lasso.points.iter().map(|p| self.screen(view, rect, *p)).collect();let tint = if matches!(self.tool, Tool::Strokes | Tool::Select) {@@ -3157,6 +3170,31 @@ impl Editor {}));ui.small("the bar under the selection edits it; drag inside the box to move, a corner to scale, an edge to stretch (past the other edge flips), the knob to turn; arrows nudge");+ ui.separator();+ ui.label(format!("part: {}", self.picked_part_names().join(", ")));+ let mut name = false;+ ui.horizontal(|ui| {+ let label = ui.label("name");+ let field = ui+ .add(+ egui::TextEdit::singleline(&mut self.checks.part)+ .desired_width(120.0)+ .hint_text("leaf, near leg"),+ )+ .labelled_by(label.id)+ .hint("the part's name; Return or the button names the selected marks");+ name = ui+ .button("make them this part")+ .hint("name the selected marks as this part, as klad part does")+ .clicked()+ || (field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)));+ });+ ui.small(+ "in-betweens pair marks by part and klad arcs tracks them; an empty name takes the marks out of their part",+ );+ if name {+ self.name_part()?;+ }Ok(())}@@ -3843,6 +3881,10 @@ impl Editor {ui.add(egui::Slider::new(&mut f.opacity, 0.05..=1.0).text("opacity")).hint("the fill's opacity");ui.small("click inside lines to fill, drag a loop to lasso fill");+ ui.horizontal_wrapped(|ui| {+ self.command_button(ui, Cmd::Refill, Some("refill this drawing"));+ self.command_button(ui, Cmd::ShowGaps, Some("show gaps"));+ });if !self.scene.can_paint() {ui.colored_label(Color32::LIGHT_YELLOW, "pick a paint layer to fill on");}diff --git a/crates/app/src/editor/cells.rs b/crates/app/src/editor/cells.rsindex 7247036..0b6e980 100644--- a/crates/app/src/editor/cells.rs+++ b/crates/app/src/editor/cells.rs@@ -208,6 +208,7 @@ impl Editor {.on_disabled_hover_text("select frames first: drag over cells, or shift click");self.command_button(ui, Cmd::Inbetween, Some("in-between"));self.command_button(ui, Cmd::RedoInbetweens, None);+ self.command_button(ui, Cmd::FillLike, None);self.command_button(ui, Cmd::NewClip, None);if let Some(span) = &self.timeline.span {ui.label(diff --git a/crates/app/src/editor/checks.rs b/crates/app/src/editor/checks.rsnew file mode 100644index 0000000..1bc62c4--- /dev/null+++ b/crates/app/src/editor/checks.rs@@ -0,0 +1,520 @@+use super::{Editor, LassoAction, MarkTransform};+use crate::jobs::{Spec, Tag};+use crate::messages::Tone;+use crate::theme::{self, Hint};+use anyhow::{Result, anyhow, bail};+use egui::{Color32, Pos2, Rect, Stroke, Vec2, vec2};+use klad_core::markedit::bounds_of;+use klad_core::ops::Op;+use serde_json::Value;+use std::path::PathBuf;++#[derive(Clone, Debug, Default, PartialEq)]+pub(super) struct Checks {+ pub gaps: Option<Gaps>,+ pub arcs: Option<Arcs>,+ pub parts: bool,+ pub part: String,+ pub font: String,+}++#[derive(Clone, Debug, PartialEq)]+pub(super) struct Gaps {+ pub layer: String,+ pub frames: Vec<(u32, Vec<[f32; 4]>)>,+}++#[derive(Clone, Debug, PartialEq)]+pub(super) struct Arcs {+ pub track: String,+ pub lines: Vec<Vec<(u32, [f32; 2])>>,+}++pub(super) fn json_of(output: &str) -> Option<Value> {+ let start = output.find('{')?;+ serde_json::Deserializer::from_str(&output[start..])+ .into_iter::<Value>()+ .next()?+ .ok()+}++fn numbers(value: &Value) -> Vec<f32> {+ value+ .as_array()+ .map(|a| a.iter().filter_map(|v| v.as_f64().map(|v| v as f32)).collect())+ .unwrap_or_default()+}++pub(super) fn gaps_from(output: &str, layer: &str) -> Option<Gaps> {+ let found = json_of(output)?;+ let frames = found["frames"]+ .as_array()?+ .iter()+ .map(|f| {+ let pockets = f["pockets"]+ .as_array()+ .map(|all| {+ all.iter()+ .map(|p| numbers(&p["bounds"]))+ .filter(|b| b.len() == 4)+ .map(|b| [b[0], b[1], b[2], b[3]])+ .collect()+ })+ .unwrap_or_default();+ (f["frame"].as_u64().unwrap_or(0) as u32, pockets)+ })+ .collect();+ Some(Gaps {+ layer: layer.to_string(),+ frames,+ })+}++pub(super) fn arcs_from(output: &str, track: &str) -> Option<Arcs> {+ let found = json_of(output)?;+ let lines = found["tracks"]+ .as_array()?+ .iter()+ .map(|t| {+ t["frames"]+ .as_array()+ .map(|all| {+ all.iter()+ .filter_map(|f| {+ let at = numbers(&f["at"]);+ (at.len() == 2).then(|| (f["frame"].as_u64().unwrap_or(0) as u32, [at[0], at[1]]))+ })+ .collect()+ })+ .unwrap_or_default()+ })+ .collect();+ Some(Arcs {+ track: track.to_string(),+ lines,+ })+}++fn strings(parts: &[&str]) -> Vec<String> {+ parts.iter().map(|s| s.to_string()).collect()+}++pub(super) fn refill_args(bundle: &str, layer: &str, frame: u32) -> Vec<String> {+ strings(&["refill", bundle, layer, "--frame", &frame.to_string()])+}++pub(super) fn fill_like_args(bundle: &str, layer: &str, cel: &str, (from, to): (u32, u32)) -> Vec<String> {+ strings(&[+ "fill",+ bundle,+ layer,+ "--like",+ cel,+ "--frames",+ &format!("{from}-{to}"),+ ])+}++pub(super) fn gaps_args(bundle: &str, layer: &str, frames: (u32, u32)) -> Vec<String> {+ let mut args = strings(&["gaps", bundle, layer, "--json"]);+ match frames {+ (from, to) if from == to => args.extend(strings(&["--frame", &from.to_string()])),+ (from, to) => args.extend(strings(&["--sheet", &format!("{from}-{to}")])),+ }+ args+}++pub(super) fn arcs_args(bundle: &str, track: &str, (from, to): (u32, u32)) -> Vec<String> {+ strings(&[+ "arcs",+ bundle,+ "--track",+ track,+ "--from",+ &from.to_string(),+ "--to",+ &to.to_string(),+ "--json",+ ])+}++pub(super) fn font_args(bundle: &str, file: &str) -> Vec<String> {+ strings(&["font", bundle, file])+}++fn last_line(out: &str, err: &str) -> String {+ out.lines()+ .chain(err.lines())+ .rfind(|l| !l.trim().is_empty())+ .unwrap_or_default()+ .trim()+ .to_string()+}++fn quiet(_: &str, _: &str) -> String {+ String::new()+}++impl Editor {+ fn bundle_arg(&self) -> String {+ self.scene.bundle.root.to_string_lossy().to_string()+ }++ fn run_job(&mut self, tag: Tag, name: String, args: Vec<String>, summary: fn(&str, &str) -> String) {+ self.start_job(Spec {+ tag,+ name,+ exe: PathBuf::new(),+ args,+ env: Vec::new(),+ reruns: 3,+ summary,+ failure: |_, err| super::tweens::failure(err),+ });+ }++ fn active_paint_id(&self) -> Result<String> {+ match self.scene.active_layer() {+ Some(l) if self.active_paint() => Ok(l.id.clone()),+ Some(l) => bail!("{} is not a paint layer", l.name),+ None => bail!("pick a paint layer first"),+ }+ }++ pub(super) fn refill(&mut self) -> Result<()> {+ let layer = self.active_paint_id()?;+ let frame = self.scene.frame;+ let args = refill_args(&self.bundle_arg(), &layer, frame);+ self.run_job(Tag::Edit, format!("refill {layer} at frame {frame}"), args, last_line);+ Ok(())+ }++ pub(super) fn fill_like(&mut self) -> Result<()> {+ let span = self+ .timeline+ .span+ .clone()+ .ok_or_else(|| anyhow!("select frames first: shift click or shift drag over cells"))?;+ let layer = span+ .rows+ .first()+ .cloned()+ .ok_or_else(|| anyhow!("select frames on a paint layer"))?;+ let cel = self+ .scene+ .bundle+ .doc+ .layer(&layer)+ .and_then(|l| l.cel_at(span.from))+ .map(|c| c.id.clone())+ .ok_or_else(|| anyhow!("no drawing at frame {} to take the fills from", span.from))?;+ let args = fill_like_args(&self.bundle_arg(), &layer, &cel, (span.from, span.to));+ self.run_job(+ Tag::Edit,+ format!("fill frames {} to {} like {cel}", span.from, span.to),+ args,+ last_line,+ );+ Ok(())+ }++ pub(super) fn show_gaps(&mut self) -> Result<()> {+ if self.checks.gaps.take().is_some() {+ return Ok(());+ }+ let layer = self.active_paint_id()?;+ let frames = self+ .timeline+ .span+ .as_ref()+ .filter(|s| s.rows.contains(&layer))+ .map_or((self.scene.frame, self.scene.frame), |s| (s.from, s.to));+ let args = gaps_args(&self.bundle_arg(), &layer, frames);+ self.run_job(Tag::Gaps, format!("gaps on {layer}"), args, quiet);+ Ok(())+ }++ pub(super) fn track(&self) -> Result<String> {+ let (_, chosen) = self+ .chosen_marks()+ .ok_or_else(|| anyhow!("select a mark or the marks of a part with S first"))?;+ let doc = &self.scene.bundle.doc;+ let parts: Vec<Option<(String, String)>> = chosen+ .iter()+ .map(|(cel, m)| {+ let layer = doc+ .all_layers()+ .into_iter()+ .find(|l| l.cels().iter().any(|c| &c.id == cel))?;+ let cel = layer.cels().iter().find(|c| &c.id == cel)?;+ Some((layer.name.clone(), cel.part_of(m.id())?.to_string()))+ })+ .collect();+ match (parts.first(), chosen.first()) {+ (Some(Some(first)), _) if parts.iter().all(|p| p.as_ref() == Some(first)) => {+ Ok(format!("{}:{}", first.0, first.1))+ }+ (_, Some((cel, m))) if chosen.len() == 1 => Ok(klad_core::markedit::address(cel, m.id())),+ _ => bail!("select one mark, or marks that are all one part, to track"),+ }+ }++ pub(super) fn show_arcs(&mut self) -> Result<()> {+ if self.checks.arcs.take().is_some() {+ return Ok(());+ }+ let track = self.track()?;+ let frames = match self.current_clip() {+ Some(c) => (c.from, c.to),+ None => (0, self.scene.bundle.doc.timeline.frames.saturating_sub(1)),+ };+ let args = arcs_args(&self.bundle_arg(), &track, frames);+ self.run_job(Tag::Arcs, format!("arcs of {track}"), args, quiet);+ Ok(())+ }++ pub(super) fn add_font(&mut self) -> Result<()> {+ let file = self.checks.font.trim().to_string();+ if file.is_empty() {+ bail!("type the path of a font file (.ttf or .otf) first");+ }+ let args = font_args(&self.bundle_arg(), &file);+ self.run_job(Tag::Edit, format!("add the font {file}"), args, last_line);+ Ok(())+ }++ pub(super) fn choose_font(&mut self) {+ if let Some(path) = crate::picker::choose_file(None, "Add") {+ self.checks.font = path.display().to_string();+ }+ }++ pub(super) fn font_window(&mut self, ui: &mut egui::Ui) -> Result<()> {+ ui.label("copies a font file into the drawing, so its text can use it");+ ui.horizontal(|ui| {+ let label = ui.label("file");+ ui.add(+ egui::TextEdit::singleline(&mut self.checks.font)+ .desired_width(240.0)+ .hint_text("/path/to/Font.ttf"),+ )+ .labelled_by(label.id)+ .hint("a .ttf or .otf file");+ });+ let (mut choose, mut add) = (false, false);+ ui.horizontal(|ui| {+ if crate::picker::NATIVE {+ choose = ui.button("choose...").hint("pick the font file").clicked();+ }+ add = ui+ .button("add the font")+ .hint("copy it into the drawing, as klad font does")+ .clicked();+ });+ let fonts = self.fonts();+ ui.small(match fonts.is_empty() {+ true => "the drawing has no fonts yet".to_string(),+ false => format!("in the drawing: {}", fonts.join(", ")),+ });+ if choose {+ self.choose_font();+ }+ if add {+ self.add_font()?;+ }+ Ok(())+ }++ pub(super) fn name_part(&mut self) -> Result<()> {+ let Some(picked) = self.picked.clone() else {+ bail!("select strokes with S first");+ };+ 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"))?,+ None => (Vec::new(), Some(picked.clone())),+ };+ let ids = after.as_ref().map_or(Vec::new(), |p| p.addresses());+ let name = self.checks.part.trim().to_string();+ ops.push(Op::Part {+ ids,+ name: name.clone(),+ });+ self.apply(ops)?;+ self.picked = after;+ self.forget_missing_selection();+ self.say(+ Tone::Done,+ match name.is_empty() {+ true => "the marks are in no part now".to_string(),+ false => format!("the marks are part {name}"),+ },+ );+ Ok(())+ }++ pub(super) fn picked_part_names(&self) -> Vec<String> {+ let Some((_, chosen)) = self.chosen_marks() else {+ return Vec::new();+ };+ let doc = &self.scene.bundle.doc;+ let mut names: Vec<String> = chosen+ .iter()+ .map(|(cel, m)| {+ doc.all_layers()+ .into_iter()+ .flat_map(|l| l.cels().iter())+ .find(|c| &c.id == cel)+ .and_then(|c| c.part_of(m.id()))+ .unwrap_or("no part")+ .to_string()+ })+ .collect();+ names.sort();+ names.dedup();+ names+ }++ pub(super) fn job_found(&mut self, tag: Tag, name: &str, output: &str) {+ match tag {+ Tag::Gaps => {+ let layer = name.trim_start_matches("gaps on ");+ self.checks.gaps = gaps_from(output, layer);+ let count: usize = self+ .checks+ .gaps+ .as_ref()+ .map_or(0, |g| g.frames.iter().map(|(_, p)| p.len()).sum());+ self.say(+ match count {+ 0 => Tone::Done,+ _ => Tone::Refused,+ },+ match count {+ 0 => "no gaps: every closed region is filled".to_string(),+ n => format!("{n} closed regions without a fill, outlined on the canvas"),+ },+ );+ }+ Tag::Arcs => {+ let track = name.trim_start_matches("arcs of ");+ self.checks.arcs = arcs_from(output, track);+ }+ _ => {}+ }+ }++ pub(super) fn draw_checks(&self, painter: &egui::Painter, place: impl Fn(Vec2) -> Pos2) {+ let frame = self.scene.frame;+ let dark = Stroke::new(3.5, Color32::from_black_alpha(150));+ if let Some(gaps) = &self.checks.gaps {+ let warn = Color32::from_rgb(255, 80, 120);+ gaps.frames+ .iter()+ .filter(|(f, _)| *f == frame)+ .flat_map(|(_, pockets)| pockets.iter())+ .for_each(|b| {+ let r =+ Rect::from_two_pos(place(vec2(b[0], b[1])), place(vec2(b[0] + b[2], b[1] + b[3]))).expand(3.0);+ painter.rect_stroke(r, 2.0, dark, egui::StrokeKind::Middle);+ painter.rect_stroke(r, 2.0, Stroke::new(1.5, warn), egui::StrokeKind::Middle);+ });+ }+ if let Some(arcs) = &self.checks.arcs {+ arcs.lines.iter().for_each(|line| {+ let points: Vec<Pos2> = line.iter().map(|(_, p)| place(vec2(p[0], p[1]))).collect();+ painter.add(egui::Shape::line(points.clone(), dark));+ painter.add(egui::Shape::line(points, Stroke::new(1.5, theme::ACCENT)));+ line.iter().for_each(|(f, p)| {+ let at = place(vec2(p[0], p[1]));+ let here = *f == frame;+ painter.circle_filled(at, if here { 5.0 } else { 3.0 }, Color32::WHITE);+ painter.circle_stroke(at, if here { 5.0 } else { 3.0 }, Stroke::new(1.0, theme::ACCENT));+ });+ });+ }+ if self.checks.parts+ && let Some(cel) = self.scene.active_cel()+ && let Some(found) = self+ .scene+ .bundle+ .doc+ .all_layers()+ .into_iter()+ .flat_map(|l| l.cels().iter())+ .find(|c| c.id == cel)+ {+ let marks = self.scene.active_marks();+ found.parts.iter().for_each(|(name, ids)| {+ if let Some(b) = bounds_of(marks, ids) {+ let r = Rect::from_two_pos(place(vec2(b[0], b[1])), place(vec2(b[2], b[3]))).expand(2.0);+ painter.rect_stroke(r, 2.0, dark, egui::StrokeKind::Middle);+ painter.rect_stroke(r, 2.0, Stroke::new(1.5, theme::ACCENT), egui::StrokeKind::Middle);+ painter.text(+ r.left_top() + vec2(0.0, -2.0),+ egui::Align2::LEFT_BOTTOM,+ name,+ egui::FontId::proportional(12.0),+ Color32::WHITE,+ );+ }+ });+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_job_arguments_are_the_cli_commands() {+ assert_eq!(refill_args("a.draw", "l2", 4).join(" "), "refill a.draw l2 --frame 4");+ assert_eq!(+ fill_like_args("a.draw", "l2", "c7", (3, 9)).join(" "),+ "fill a.draw l2 --like c7 --frames 3-9"+ );+ assert_eq!(+ gaps_args("a.draw", "l2", (5, 5)).join(" "),+ "gaps a.draw l2 --json --frame 5"+ );+ assert_eq!(+ gaps_args("a.draw", "l2", (0, 11)).join(" "),+ "gaps a.draw l2 --json --sheet 0-11"+ );+ assert_eq!(+ arcs_args("a.draw", "lines:near leg", (12, 27)),+ [+ "arcs",+ "a.draw",+ "--track",+ "lines:near leg",+ "--from",+ "12",+ "--to",+ "27",+ "--json"+ ]+ );+ assert_eq!(font_args("a.draw", "/f/Sign.ttf").join(" "), "font a.draw /f/Sign.ttf");+ }++ #[test]+ fn gaps_and_arcs_read_the_cli_json_even_with_lines_after_it() {+ let gaps = gaps_from(+ r#"{"frames":[{"cel":"c3","frame":2,"pockets":[{"bounds":[10,20,30,40],"pixels":900}],"render":null}],"gap":4.0,"layer":"colour","ref":"lines"}+gaps rendered in 12 ms"#,+ "l2",+ )+ .unwrap();+ assert_eq!(gaps.frames, vec![(2, vec![[10.0, 20.0, 30.0, 40.0]])]);+ let arcs = arcs_from(+ r#"{"from":0,"to":1,"tracks":[{"frames":[{"at":[1.5,2.0],"frame":0},{"at":[3.0,4.0],"frame":1}]}]}"#,+ "leaf",+ )+ .unwrap();+ assert_eq!(arcs.lines, vec![vec![(0, [1.5, 2.0]), (1, [3.0, 4.0])]]);+ assert!(gaps_from("error: no layer", "l2").is_none());+ }+}diff --git a/crates/app/src/editor/clips.rs b/crates/app/src/editor/clips.rsindex 2da9aee..2ee1298 100644--- a/crates/app/src/editor/clips.rs+++ b/crates/app/src/editor/clips.rs@@ -206,7 +206,7 @@ pub(super) fn resolve(home: &Path, folder: &str) -> PathBuf {}impl Editor {- fn bundle_home(&self) -> PathBuf {+ pub(super) fn bundle_home(&self) -> PathBuf {let root = self.scene.bundle.root.components().collect::<PathBuf>();match root.parent() {Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rsindex d1ff4f0..8099d2c 100644--- a/crates/app/src/editor/commands.rs+++ b/crates/app/src/editor/commands.rs@@ -26,7 +26,7 @@ impl Editor {self.here().and_then(|(_, c)| c)}- fn active_paint(&self) -> bool {+ pub(super) fn active_paint(&self) -> bool {self.scene.active_layer().is_some_and(|l| l.kind() == LayerKind::Paint)}@@ -253,6 +253,25 @@ impl Editor {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(),+ Cmd::Refill | Cmd::ShowGaps if !self.active_paint() => {+ Some("pick a paint layer with fills first".to_string())+ }+ Cmd::Refill => self+ .jobs+ .busy(crate::jobs::Tag::Edit)+ .then(|| "a change is being made".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())+ }),+ Cmd::ShowGaps => self+ .jobs+ .busy(crate::jobs::Tag::Gaps)+ .then(|| "the gaps are being looked for".to_string()),+ Cmd::ShowArcs if self.checks.arcs.is_some() => None,+ Cmd::ShowArcs => self.track().err().map(|e| e.to_string()),Cmd::ExportGodot => {if self.jobs.busy(crate::jobs::Tag::Export) {Some("an export is running".into())@@ -317,6 +336,11 @@ impl Editor {Cmd::Numbers => layout.numbers,Cmd::Settings => self.windows.settings,Cmd::About => self.windows.about,+ Cmd::Export => self.windows.export,+ Cmd::AddFont => self.windows.font,+ Cmd::ShowGaps => self.checks.gaps.is_some(),+ Cmd::ShowParts => self.checks.parts,+ Cmd::ShowArcs => self.checks.arcs.is_some(),Cmd::BrushWindow => self.windows.brush,Cmd::MessageLog => self.windows.log,Cmd::Spin => self.spin,@@ -554,6 +578,13 @@ impl Editor {Cmd::OpenDocument => self.wants = Some(super::Want::Open),Cmd::OpenRecent => self.wants = Some(super::Want::Recent),Cmd::About => self.windows.about = !self.windows.about,+ Cmd::Export => self.windows.export = !self.windows.export,+ Cmd::AddFont => self.windows.font = !self.windows.font,+ Cmd::Refill => self.refill()?,+ Cmd::FillLike => self.fill_like()?,+ Cmd::ShowGaps => self.show_gaps()?,+ Cmd::ShowParts => self.checks.parts = !self.checks.parts,+ Cmd::ShowArcs => self.show_arcs()?,Cmd::CopyPath => {let path = self.scene.bundle.root.display().to_string();self.ctx.copy_text(path.clone());diff --git a/crates/app/src/editor/export.rs b/crates/app/src/editor/export.rsnew file mode 100644index 0000000..4a798f8--- /dev/null+++ b/crates/app/src/editor/export.rs@@ -0,0 +1,262 @@+use super::Editor;+use super::clips::resolve;+use crate::jobs::{Spec, Tag};+use crate::theme::Hint;+use anyhow::{Result, bail};+use std::path::{Path, PathBuf};++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub(super) enum What {+ #[default]+ Image,+ Frames,+ Sheet,+}++#[derive(Clone, Debug, PartialEq)]+pub(super) struct Form {+ pub what: What,+ pub layer: Option<String>,+ pub scale: f32,+ pub background: bool,+ pub deep: bool,+ pub range: String,+ pub padding: u32,+ pub max: u32,+ pub out: String,+}++impl Default for Form {+ fn default() -> Self {+ Self {+ what: What::Image,+ layer: None,+ scale: 1.0,+ background: false,+ deep: false,+ range: "all".into(),+ padding: 2,+ max: 4096,+ out: String::new(),+ }+ }+}++pub(super) fn args(bundle: &Path, home: &Path, frame: u32, form: &Form) -> Vec<String> {+ let mut args = vec!["export".to_string(), bundle.to_string_lossy().to_string()];+ let mut push = |a: &str, b: Option<String>| {+ args.push(a.to_string());+ args.extend(b);+ };+ match form.what {+ What::Image => push("--frame", Some(frame.to_string())),+ What::Frames => push("--frames", Some(form.range.trim().to_string())),+ What::Sheet => push("--sheet", Some(form.range.trim().to_string())),+ }+ if let Some(layer) = form.layer.as_ref().filter(|_| form.what != What::Frames) {+ push("--layer", Some(layer.clone()));+ }+ if form.scale != 1.0 {+ push("--scale", Some(form.scale.to_string()));+ }+ if form.deep && form.what != What::Frames {+ push("--depth", Some("16".into()));+ }+ if form.background && form.what == What::Image {+ push("--background", None);+ }+ if form.what == What::Sheet {+ push("--padding", Some(form.padding.to_string()));+ push("--max", Some(form.max.to_string()));+ }+ if !form.out.trim().is_empty() {+ push("-o", Some(resolve(home, &form.out).to_string_lossy().to_string()));+ }+ args+}++fn written(out: &str, err: &str) -> String {+ out.lines()+ .chain(err.lines())+ .map(str::trim)+ .filter(|l| l.ends_with(".png") || l.ends_with(".json") || l.contains(" in all"))+ .take(3)+ .collect::<Vec<_>>()+ .join("; ")+}++impl Editor {+ pub(super) fn export(&mut self) -> Result<()> {+ let form = self.export.clone();+ if form.what != What::Image && form.range.trim().is_empty() {+ bail!("say which frames: all, a clip's name or a range like 0-11");+ }+ let args = args(&self.scene.bundle.root, &self.bundle_home(), self.scene.frame, &form);+ let name = match form.what {+ What::Image => format!("export frame {}", self.scene.frame),+ What::Frames => format!("export frames {}", form.range.trim()),+ What::Sheet => format!("export the sheet of {}", form.range.trim()),+ };+ self.start_job(Spec {+ tag: Tag::Export,+ name,+ exe: PathBuf::new(),+ args,+ env: Vec::new(),+ reruns: 3,+ summary: written,+ failure: |_, err| super::tweens::failure(err),+ });+ Ok(())+ }++ pub(super) fn export_window(&mut self, ui: &mut egui::Ui) -> Result<()> {+ let mut run = false;+ let layers: Vec<(String, String)> = self+ .scene+ .bundle+ .doc+ .all_layers()+ .into_iter()+ .map(|l| (l.id.clone(), l.name.clone()))+ .collect();+ let clips: Vec<String> = self+ .scene+ .bundle+ .doc+ .timeline+ .clips+ .iter()+ .map(|c| c.name.clone())+ .collect();+ let form = &mut self.export;+ ui.horizontal(|ui| {+ ui.selectable_value(&mut form.what, What::Image, "image")+ .hint("this frame as one PNG");+ ui.selectable_value(&mut form.what, What::Frames, "frames")+ .hint("numbered PNGs, one per frame");+ ui.selectable_value(&mut form.what, What::Sheet, "sprite sheet")+ .hint("sheet pages and Aseprite JSON");+ });+ if form.what != What::Frames {+ let shown = form+ .layer+ .as_ref()+ .and_then(|id| layers.iter().find(|(l, _)| l == id))+ .map_or("the whole image".to_string(), |(_, n)| n.clone());+ egui::ComboBox::from_label("layer")+ .selected_text(shown)+ .show_ui(ui, |ui| {+ ui.selectable_value(&mut form.layer, None, "the whole image");+ layers.iter().for_each(|(id, name)| {+ ui.selectable_value(&mut form.layer, Some(id.clone()), name);+ });+ })+ .response+ .hint("export the whole image or one layer or group");+ }+ if form.what != What::Image {+ ui.horizontal(|ui| {+ let label = ui.label("frames");+ ui.add(+ egui::TextEdit::singleline(&mut form.range)+ .desired_width(90.0)+ .hint_text("all, a clip or 0-11"),+ )+ .labelled_by(label.id)+ .hint("which frames: all, a clip's name or a range");+ clips.iter().for_each(|c| {+ if ui.button(c).hint("export this clip's frames").clicked() {+ form.range = c.clone();+ }+ });+ });+ }+ ui.add(+ egui::Slider::new(&mut form.scale, 0.125..=4.0)+ .logarithmic(true)+ .text("scale"),+ )+ .hint("the size of the export against the canvas");+ if form.what != What::Frames {+ ui.checkbox(&mut form.deep, "16 bits per channel")+ .hint("16-bit PNGs; 8-bit ones are dithered so gradients do not band");+ }+ if form.what == What::Image {+ ui.checkbox(&mut form.background, "keep the background colour")+ .hint("off: a transparent PNG");+ }+ if form.what == What::Sheet {+ ui.add(egui::Slider::new(&mut form.padding, 0..=16).text("padding px"))+ .hint("space between the cells of the sheet");+ ui.add(egui::Slider::new(&mut form.max, 512..=8192).text("page size px"))+ .hint("the largest sheet page; more frames go on more pages");+ }+ ui.horizontal(|ui| {+ let label = ui.label("to");+ ui.add(+ egui::TextEdit::singleline(&mut form.out)+ .desired_width(220.0)+ .hint_text("next to the drawing; a path relative to its folder"),+ )+ .labelled_by(label.id)+ .hint("the file or folder to write; empty writes next to the drawing");+ });+ ui.horizontal(|ui| {+ run = ui.button("export").hint("write it, as klad export does").clicked();+ if ui+ .button("export to Godot")+ .hint("the sheet, SpriteFrames and scene into the Godot folder of the clip row")+ .clicked()+ {+ self.export_godot();+ }+ });+ if run {+ self.export()?;+ }+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_window_builds_the_cli_export() {+ let (bundle, home) = (Path::new("/w/art.draw"), Path::new("/w"));+ let image = Form {+ background: true,+ scale: 2.0,+ out: "out/hero.png".into(),+ ..Form::default()+ };+ assert_eq!(+ args(bundle, home, 3, &image).join(" "),+ "export /w/art.draw --frame 3 --scale 2 --background -o /w/out/hero.png"+ );+ let sheet = Form {+ what: What::Sheet,+ range: "walk".into(),+ layer: Some("l2".into()),+ deep: true,+ ..Form::default()+ };+ assert_eq!(+ args(bundle, home, 0, &sheet).join(" "),+ "export /w/art.draw --sheet walk --layer l2 --depth 16 --padding 2 --max 4096"+ );+ let frames = Form {+ what: What::Frames,+ range: "0-11".into(),+ layer: Some("l2".into()),+ scale: 0.5,+ ..Form::default()+ };+ assert_eq!(+ args(bundle, home, 0, &frames).join(" "),+ "export /w/art.draw --frames 0-11 --scale 0.5"+ );+ }+}diff --git a/crates/app/src/editor/make.rs b/crates/app/src/editor/make.rsindex cbb043e..a85763d 100644--- a/crates/app/src/editor/make.rs+++ b/crates/app/src/editor/make.rs@@ -275,7 +275,7 @@ impl Editor {Ok(())}- fn fonts(&self) -> Vec<String> {+ pub(super) fn fonts(&self) -> Vec<String> {let dir = self.scene.bundle.root.join(klad_render::assets::FONTS);let mut names: Vec<String> = std::fs::read_dir(dir).map(|entries| {@@ -483,7 +483,14 @@ impl Editor {});}).response- .hint("the font file, from the bundle's fonts folder (klad font adds one)");+ .hint("the font file, from the bundle's fonts folder (add a font adds one)");+ if ui+ .button("add a font")+ .hint("copy a font file into the drawing")+ .clicked()+ {+ self.windows.font = true;+ }if font != t.font {put("font", json!(font));}diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rsindex bd06cc8..6420fd5 100644--- a/crates/app/src/editor/panels.rs+++ b/crates/app/src/editor/panels.rs@@ -161,10 +161,10 @@ impl Editor {}pub(super) fn start_job(&mut self, mut spec: Spec) {- spec.exe = match std::env::current_exe() {- Ok(exe) => exe,- Err(e) => {- self.error(format!("cannot find the klad binary: {e}"));+ spec.exe = match crate::start::draw_binary() {+ Some(exe) => exe,+ None => {+ self.error("cannot find the klad binary next to the editor".to_string());return;}};@@ -192,6 +192,10 @@ impl Editor {self.check(|ed| ed.reload());self.between.report = super::between::report(&e.output);}+ if e.tag == Tag::Edit {+ self.check(|ed| ed.reload());+ }+ self.job_found(e.tag, &e.name, &e.output);let detail = if text.is_empty() {String::new()} else {@@ -252,6 +256,8 @@ impl Editor {(Cmd::NewDocument, "new drawing"),(Cmd::OpenDocument, "open"),(Cmd::OpenRecent, "recent"),+ (Cmd::Export, "export"),+ (Cmd::AddFont, "add a font"),(Cmd::CopyPath, "copy path"),(Cmd::About, "about and licences"),]@@ -263,7 +269,9 @@ impl Editor {});}).0- .hint(format!("{name}: new, open, recent drawings, copy its path"));+ .hint(format!(+ "{name}: new, open, recent drawings, export, fonts, copy its path"+ ));}fn about_panel(ui: &mut egui::Ui) {@@ -693,6 +701,28 @@ impl Editor {}self.windows.link &= open;}+ if self.windows.export {+ let mut open = true;+ Self::window(+ ctx,+ "export",+ (format!("{} Export", icon::EXPORT), near_timeline),+ &mut open,+ |ui| self.check(|e| e.export_window(ui)),+ );+ self.windows.export &= open;+ }+ if self.windows.font {+ let mut open = true;+ Self::window(+ ctx,+ "font",+ (format!("{} Add a font", icon::PLUS), near_timeline),+ &mut open,+ |ui| self.check(|e| e.font_window(ui)),+ );+ self.windows.font &= open;+ }if self.windows.between {let mut open = true;Self::window(diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex e0c9724..997341b 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -225,6 +225,17 @@ fn every_control_is_pen_sized_and_has_a_hover_hint() {h.run_steps(3);assert!(h.query_all(By::new().label_contains("pick its partner")).count() > 0);checked += audit(&h, "the in-between and clip windows");+ {+ let ed = h.state_mut();+ ed.windows.between = false;+ ed.windows.clip = false;+ ed.windows.export = true;+ ed.windows.font = true;+ ed.export.what = super::export::What::Sheet;+ }+ h.run_steps(3);+ assert!(h.query_all(By::new().label("page size px")).count() > 0);+ checked += audit(&h, "the export and font windows");assert!(checked > 150, "only {checked} controls checked");let _ = std::fs::remove_dir_all(&path);}@@ -2121,3 +2132,134 @@ fn an_imported_picture_lands_on_its_own_layer_and_can_be_a_reference() {assert!(h.state().scene.active_layer().unwrap().reference);let _ = std::fs::remove_dir_all(&path);}++fn hush(h: &mut Harness<'static, Editor>) {+ let ids: Vec<u64> = h.state().messages.log().map(|m| m.id).collect();+ ids.into_iter().for_each(|id| h.state_mut().messages.dismiss(id));+ h.run_steps(2);+}++#[test]+fn the_cli_only_features_run_from_the_editor_and_give_what_the_cli_gives() {+ use super::checks::{arcs_from, gaps_from};+ use crate::jobs::Tag;+ let klad = crate::start::draw_binary().expect("build the klad binary first (just test does)");+ let run = |args: &[&str]| {+ let out = std::process::Command::new(&klad).args(args).output().unwrap();+ assert!(+ out.status.success(),+ "{args:?}: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ String::from_utf8_lossy(&out.stdout).to_string()+ };+ let base = std::env::temp_dir().join(format!("draw-ui-cli-forms-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&base);+ std::fs::create_dir_all(&base).unwrap();+ let (ours, theirs) = (base.join("ours.draw"), base.join("theirs.draw"));+ let (o, t) = (ours.to_str().unwrap(), theirs.to_str().unwrap());+ run(&[+ "new", o, "--width", "256", "--height", "160", "--layers", "0", "--frames", "4",+ ]);+ let ops = base.join("ops.jsonl");+ std::fs::write(+ &ops,+ r##"{"op":"add","layer":{"id":"colour","kind":"paint","name":"colour"}}+{"op":"add","layer":{"id":"lines","kind":"paint","name":"lines"}}+{"op":"stroke","layer":"lines","brush":"ink","size":4,"path":"M20 20 L110 20 L110 120 L20 120 Z","taper":[0,0]}+{"op":"stroke","layer":"lines","brush":"ink","size":4,"path":"M140 20 L230 20 L230 120 L140 120 Z","taper":[0,0]}+{"op":"fill","layer":"colour","at":[60,70],"ref":"lines","color":"#c04040"}"##,+ )+ .unwrap();+ run(&["apply", o, "--file", ops.to_str().unwrap()]);+ copy_dir(&ours, &theirs);+ let mut h = harness(editor(&ours), vec2(1280.0, 1400.0));+ let idle = |tag: Tag| move |ed: &Editor| !ed.jobs.busy(tag);++ activate(&mut h, "colour");+ h.state_mut().invoke(Cmd::ShowGaps).unwrap();+ settle(&mut h, |ed| ed.checks.gaps.is_some());+ let cli = gaps_from(&run(&["gaps", t, "colour", "--json", "--frame", "0"]), "colour").unwrap();+ assert_eq!(h.state().checks.gaps.as_ref().unwrap().frames, cli.frames);+ assert_eq!(cli.frames[0].1.len(), 1, "the right box has no fill");++ activate(&mut h, "lines");+ let (cel, id) = {+ let ed = h.state();+ (ed.scene.active_cel().unwrap(), ed.scene.active_marks()[0].id())+ };+ h.state_mut().tool = Tool::Strokes;+ h.state_mut().picked = Some(Picked::whole(cel.clone(), vec![id]));+ h.state_mut().checks.part = "box".into();+ h.run_steps(2);+ hush(&mut h);+ h.get_by_role_and_label(Role::Button, "make them this part").click();+ h.run_steps(2);+ run(&["part", t, &format!("{cel}:s{id}"), "--name", "box"]);+ let parts = |path: &Path| {+ let b = Bundle::open(path).unwrap();+ b.doc.find_layer("lines").unwrap().cels()[0].parts.clone()+ };+ assert_eq!(parts(&ours), parts(&theirs));+ assert_eq!(h.state().picked_part_names(), ["box"]);++ h.state_mut().invoke(Cmd::ShowArcs).unwrap();+ settle(&mut h, |ed| ed.checks.arcs.is_some());+ let cli = arcs_from(+ &run(&["arcs", t, "--track", "lines:box", "--from", "0", "--to", "3", "--json"]),+ "x",+ )+ .unwrap();+ assert_eq!(h.state().checks.arcs.as_ref().unwrap().lines, cli.lines);+ assert_eq!(cli.lines[0].len(), 4);+ h.state_mut().invoke(Cmd::ShowParts).unwrap();+ h.run_steps(2);++ activate(&mut h, "colour");+ h.state_mut().invoke(Cmd::Refill).unwrap();+ settle(&mut h, idle(Tag::Edit));+ run(&["refill", t, "colour", "--frame", "0"]);++ let font = concat!(env!("CARGO_MANIFEST_DIR"), "/assets/Phosphor.ttf");+ h.state_mut().invoke(Cmd::AddFont).unwrap();+ h.state_mut().checks.font = font.into();+ h.run_steps(2);+ hush(&mut h);+ h.get_by_role_and_label(Role::Button, "add the font").click();+ h.run_steps(2);+ settle(&mut h, idle(Tag::Edit));+ run(&["font", t, font]);+ assert_eq!(h.state().fonts(), ["Phosphor.ttf"]);++ h.state_mut().invoke(Cmd::Export).unwrap();+ h.state_mut().export.out = base.join("ours.png").to_string_lossy().to_string();+ h.run_steps(2);+ hush(&mut h);+ h.get_by_role_and_label(Role::Button, "export").click();+ h.run_steps(2);+ settle(&mut h, idle(Tag::Export));+ run(&[+ "export",+ t,+ "--frame",+ "0",+ "-o",+ base.join("theirs.png").to_str().unwrap(),+ ]);+ assert_eq!(+ std::fs::read(base.join("ours.png")).unwrap(),+ std::fs::read(base.join("theirs.png")).unwrap()+ );++ let hash = |p: &str| run(&["hash", p, "--no-cache"]);+ assert_eq!(hash(o), hash(t));+ let errors: Vec<String> = h+ .state()+ .messages+ .log()+ .filter(|m| m.tone == Tone::Error)+ .map(|m| m.text.clone())+ .collect();+ assert!(errors.is_empty(), "{errors:?}");+ std::fs::remove_dir_all(&base).unwrap();+}diff --git a/crates/app/src/jobs.rs b/crates/app/src/jobs.rsindex 8b62974..79ed9e3 100644--- a/crates/app/src/jobs.rs+++ b/crates/app/src/jobs.rs@@ -13,6 +13,9 @@ pub const CHANGED: i32 = 75;pub enum Tag {Inbetween,Export,+ Edit,+ Gaps,+ Arcs,}#[derive(Clone)]diff --git a/crates/app/src/picker.rs b/crates/app/src/picker.rsindex aea115e..ea086c7 100644--- a/crates/app/src/picker.rs+++ b/crates/app/src/picker.rs@@ -4,15 +4,25 @@ pub const NATIVE: bool = cfg!(target_os = "macos");#[cfg(target_os = "macos")]pub fn choose_folder(start: Option<&Path>, prompt: &str) -> Option<PathBuf> {+ choose(start, prompt, true)+}++#[cfg(target_os = "macos")]+pub fn choose_file(start: Option<&Path>, prompt: &str) -> Option<PathBuf> {+ choose(start, prompt, false)+}++#[cfg(target_os = "macos")]+fn choose(start: Option<&Path>, prompt: &str, folders: bool) -> Option<PathBuf> {use objc2::MainThreadMarker;use objc2_app_kit::{NSModalResponseOK, NSOpenPanel};use objc2_foundation::{NSString, NSURL};let mtm = MainThreadMarker::new()?;let panel = NSOpenPanel::openPanel(mtm);- panel.setCanChooseDirectories(true);- panel.setCanChooseFiles(false);+ panel.setCanChooseDirectories(folders);+ panel.setCanChooseFiles(!folders);panel.setAllowsMultipleSelection(false);- panel.setCanCreateDirectories(true);+ panel.setCanCreateDirectories(folders);panel.setPrompt(Some(&NSString::from_str(prompt)));if let Some(dir) = start.and_then(Path::to_str) {panel.setDirectoryURL(Some(&NSURL::fileURLWithPath(&NSString::from_str(dir))));@@ -30,3 +40,8 @@ pub fn choose_folder(start: Option<&Path>, prompt: &str) -> Option<PathBuf> {pub fn choose_folder(_start: Option<&Path>, _prompt: &str) -> Option<PathBuf> {None}++#[cfg(not(target_os = "macos"))]+pub fn choose_file(_start: Option<&Path>, _prompt: &str) -> Option<PathBuf> {+ None+}diff --git a/crates/app/src/start.rs b/crates/app/src/start.rsindex 81728e4..fc963db 100644--- a/crates/app/src/start.rs+++ b/crates/app/src/start.rs@@ -432,7 +432,7 @@ pub fn free_name(folder: &Path) -> String {.unwrap_or_default()}-fn draw_binary() -> Option<PathBuf> {+pub(crate) fn draw_binary() -> Option<PathBuf> {let exe = std::env::current_exe().ok()?;if exe.file_stem().is_some_and(|s| s == "klad") {return Some(exe);diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex e071980..b567cad 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-04 19:51_+_Last updated: 2026-11-04 20:11_# klad: design@@ -439,6 +439,7 @@ Scripts are any language that prints edit ops as JSON lines into `klad apply`. G- Notes on the canvas (M4 batch 4, `editor/pins.rs`): every open note is a pin, those of other frames dimmed with their frame, done ones on this frame checked in green. With the note tool a click on a pin opens its popover (the text to edit and save, done, remove, close); elsewhere it opens a popover for a new note at that spot ("pin it"). A right click on any pin, of this frame or a dimmed one of another, goes to its frame and selects it (an accent ring and its popover); Delete removes the selected note. The Notes pane lists the open notes (a click goes to the frame and opens the pin) and the done ones folded, each can be opened again. The editor watches `.cache/notes.json`, so the agent's `klad notes --done` shows at once.- Settings (M4 batch 4, `settings.rs`, `editor/prefs.rs`): the settings file carries a `version` (2; files without one, the M1 to M4 ones, load with the new fields at their defaults and are stamped 2), `keys` (command id to key labels such as `shift D`, only the changed ones), `uiScale` (0.75 to 2, egui's zoom factor, so every control grows with it) and `defaults` (brush and size for new windows, the shift K exposure, onion before, after and opacity, the grey around the canvas). The window has pen calibration, defaults, keys (search, change by pressing the key, no key, reset one or all) and layout. `commands::Bindings` holds the keys: a changed command's keys replace its first ones, a key another command already uses is refused and that command named (`taken_by`), holds (Q, W, space) keep their keys, and every key lookup (dispatch, hints, the palette, the strip's letters) goes through it.- Export to Godot (M3 batch 3): the clip row has a "Godot folder" field (the document's `export.godot`; a typed folder is relative to the folder holding the bundle) and an "export to Godot" button, which runs `klad export <bundle> --godot` (with the typed folder and `--store` when it differs) as a background job of the same binary, so the CLI and the editor write the same files; its summary or error is a message.+- CLI forms in the editor (M5, S5.25, `editor/checks.rs`, `editor/export.rs`): refill this drawing and show gaps (the fill tool's options and the palette), fill like the first drawing (the timeline selection toolbar), a part name for the selected marks (the stroke inspector, the `part` op), show parts and show arcs of the selected mark or part over the clip (the palette), an export window (the document menu, cmd E: this frame, a layer, numbered frames or a sprite sheet, and Godot) and add a font (the document menu and the text inspector, with the macOS open panel). Everything but the part name runs the `klad` binary as a background job with the same arguments a person would type (`crate::start::draw_binary` finds it next to the editor, and next to the test binaries in tests), so the CLI and the editor do the same thing by construction; gaps and arcs read the command's `--json` and draw on the canvas until the next edit. The ops that draw from shapes (`ink`, `light`, `hatch`, `paint`, `scatter`) stay CLI only (principle 7).- Agent channel: the current selection and pinned notes are written to `.cache/selection.json` and `.cache/notes.json` for `klad selection` and `klad notes`; both carry the frame.- Vector layers are rasterised into tiles when opened and when their nodes change; per-tile composition then only draws one tile per layer.