A drawing app built for agent/human collaboration
Rust
Downloads for macOS, Windows and Linux
Indicode BVfaa6ba535bd4
diff --git a/.github/workflows/check.yml b/.github/workflows/check.ymlnew file mode 100644index 0000000..749bc06--- /dev/null+++ b/.github/workflows/check.yml@@ -0,0 +1,49 @@+name: check++on:+ pull_request:+ push:+ branches: [main]+ workflow_call:++env:+ CARGO_TERM_COLOR: always++jobs:+ linux:+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v4+ - name: System libraries+ run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libfontconfig1-dev+ - uses: dtolnay/rust-toolchain@stable+ with:+ components: clippy, rustfmt+ - uses: Swatinem/rust-cache@v2+ - run: cargo fmt --all --check+ - run: cargo clippy --workspace --all-targets -- -D warnings+ - run: cargo test --workspace+ - run: python3 docs/skill/drawkit.py --check++ audit:+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v4+ - uses: EmbarkStudios/cargo-deny-action@v2++ macos:+ runs-on: macos-14+ steps:+ - uses: actions/checkout@v4+ - uses: dtolnay/rust-toolchain@stable+ - uses: Swatinem/rust-cache@v2+ - run: cargo test --workspace++ windows:+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4+ - uses: dtolnay/rust-toolchain@stable+ - uses: Swatinem/rust-cache@v2+ - run: cargo build -p klad-cli+ - run: target/debug/klad.exe --versiondiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..a71c1aa--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,92 @@+name: release++on:+ push:+ tags: ["v*"]++env:+ CARGO_TERM_COLOR: always++jobs:+ check:+ uses: ./.github/workflows/check.yml++ build:+ needs: check+ strategy:+ fail-fast: false+ matrix:+ include:+ - os: macos-14+ target: aarch64-apple-darwin+ app: true+ - os: macos-14+ target: x86_64-apple-darwin+ - os: ubuntu-24.04+ target: x86_64-unknown-linux-gnu+ appimage: x86_64+ - os: ubuntu-24.04-arm+ target: aarch64-unknown-linux-gnu+ appimage: aarch64+ - os: windows-latest+ target: x86_64-pc-windows-msvc+ runs-on: ${{ matrix.os }}+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0+ - name: System libraries+ if: runner.os == 'Linux'+ run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libfontconfig1-dev libfuse2+ - uses: dtolnay/rust-toolchain@stable+ with:+ targets: ${{ matrix.target }}+ - uses: Swatinem/rust-cache@v2+ with:+ key: ${{ matrix.target }}+ - name: AppImage tool+ if: matrix.appimage+ run: |+ curl -fsSL -o appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-${{ matrix.appimage }}.AppImage"+ chmod +x appimagetool+ echo "APPIMAGETOOL=$PWD/appimagetool" >> "$GITHUB_ENV"+ - name: Archive+ shell: bash+ run: bash packaging/archive.sh ${{ matrix.target }} dist+ - name: Mac app and disk image+ if: matrix.app+ env:+ KLAD_MAC_TARGETS: aarch64-apple-darwin x86_64-apple-darwin+ run: |+ rustup target add x86_64-apple-darwin+ bash packaging/macos/app.sh dist+ - uses: actions/upload-artifact@v4+ with:+ name: klad-${{ matrix.target }}+ path: |+ dist/*.tar.gz+ dist/*.zip+ dist/*.dmg+ dist/*.AppImage++ release:+ needs: build+ runs-on: ubuntu-24.04+ permissions:+ contents: write+ steps:+ - uses: actions/checkout@v4+ - uses: actions/download-artifact@v4+ with:+ path: artefacts+ merge-multiple: true+ - name: Checksums and notes+ run: |+ cd artefacts && sha256sum * > checksums.txt && cd ..+ version="${GITHUB_REF_NAME#v}"+ awk -v v="$version" '$0 ~ "^## "v"( |$)" {on=1; next} /^## / {on=0} on' CHANGELOG.md > notes.md+ [ -s notes.md ] || echo "klad $version" > notes.md+ - name: Release+ env:+ GH_TOKEN: ${{ github.token }}+ run: gh release create "$GITHUB_REF_NAME" artefacts/* --title "klad ${GITHUB_REF_NAME#v}" --notes-file notes.mddiff --git a/.gitignore b/.gitignoreindex 1fca8d9..9a92350 100644--- a/.gitignore+++ b/.gitignore@@ -10,3 +10,4 @@ __pycache__//samples/*/*.png/samples/*/*-godot//samples/*/*.json+/distdiff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..821f0af--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,19 @@+# Changelog++## Unreleased++The first downloadable builds.++- Downloads for macOS (an app and a disk image, Apple silicon and Intel in one), Windows and Linux (archives and AppImages), each with the `klad` command line, the editor, the fonts, the licences and the agent skill.+- The editor runs on Windows and Linux (`klad open`, or `klad-editor`), with the platform's open dialog; pens that report pressure through the system (Windows) draw with it.+- On a Mac, `.draw` drawings show in Finder as one item and open in klad with a double click.+- `klad install` (and "install the klad command" in the editor's document menu) puts `klad` on the terminal's path, for you and for agents. `klad skill` prints the agent skill.+- The editor checks once a day whether a newer version is out and says so, with a link to what changed (off in the settings window).+- `klad --version` and About show the commit a build was made from.+- 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.+- Large stills render several times faster: strokes land only where they painted, and the CLI replays a drawing's tiles on every core (same pixels).++## 0.1.0 (2026-11-04)++The first public version: the `klad` command line on macOS and Linux and the editor on macOS, built from source.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex af38c63..a923e60 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -11,10 +11,10 @@ Thank you for looking. klad is young and changes fast; issues with a drawing tha## Building- Rust through [rustup](https://rustup.rs); `rust-toolchain.toml` picks the version. [`just`](https://github.com/casey/just) runs the recipes.-- macOS: the Xcode command line tools. Linux: `pkg-config`, `libfreetype-dev` and `libfontconfig1-dev`. Windows is not tested yet.+- macOS: the Xcode command line tools. Linux: `pkg-config`, `libfreetype-dev`, `libfontconfig1-dev`, `libxkbcommon-dev` and `libwayland-dev`. Windows: Visual Studio's C++ build tools; the check on every pull request builds it there.- The first build downloads a prebuilt Skia for your platform (`skia-bindings` does this), so it needs network once.- `just build`, `just test`, `just lint`. They build into `target/` on macOS and `target/linux` on Linux, so one checkout can be built from both. `just audit` needs [`cargo-deny`](https://github.com/EmbarkStudios/cargo-deny) and [`cargo-about`](https://github.com/EmbarkStudios/cargo-about) (`cargo install cargo-deny --locked` and `cargo install cargo-about --locked --features cli`).-- The editor is `klad open`. Its panels are tested headless with `egui_kittest`; `cargo test -p klad-app -- --ignored editor_picture` (the editor with a sample drawing on its canvas), `start_pictures` and `just ui-pictures` write pictures of the UI to `scratch/ui/`.+- The editor is `klad open`, or `klad-editor` on its own (the app on a Mac, the program to start on Windows). `cargo build --no-default-features -p klad-cli` builds `klad` without the editor, for servers. Its panels are tested headless with `egui_kittest`; `cargo test -p klad-app -- --ignored editor_picture` (the editor with a sample drawing on its canvas), `start_pictures` and `just ui-pictures` write pictures of the UI to `scratch/ui/`.## The rules the code follows@@ -36,3 +36,9 @@ These come from `CLAUDE.md`, which is also the guide for coding agents working o3. Describe what changed and how you checked it; for anything visual, attach a render (`klad render`) before and after.By sending a contribution you agree that Indicode BV may publish it under the licence of the project.++## Releases++1. Move the changes under "Unreleased" in `CHANGELOG.md` to a section `## x.y.z (date)` and bump `version` in the workspace `Cargo.toml`.+2. Commit, tag `vx.y.z` and push the tag. The `release` workflow runs the checks, builds the macOS app and disk image (arm64 and x86_64 in one), `klad` archives for macOS, Linux (x86_64, arm64, also as AppImages) and Windows, writes `checksums.txt` and publishes them with that section of the changelog as the notes.+3. The builds are not signed or notarised yet; the README says how to open them.diff --git a/Cargo.lock b/Cargo.lockindex bbc2713..1a3ae81 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -867,6 +867,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"dependencies = ["bitflags 2.13.2",+ "block2 0.6.2",+ "libc","objc2 0.6.5",]@@ -933,7 +935,7 @@ dependencies = ["objc2-foundation 0.3.2","parking_lot","percent-encoding",- "pollster",+ "pollster 1.0.1","profiling","raw-window-handle","send_wrapper",@@ -1036,7 +1038,7 @@ dependencies = ["image","kittest","log",- "pollster",+ "pollster 1.0.1","serde","toml","wgpu",@@ -1760,8 +1762,9 @@ dependencies = ["objc2-app-kit 0.3.2","objc2-foundation 0.3.2","png",- "pollster",+ "pollster 1.0.1","rayon",+ "rfd","serde","serde_json","zstd",@@ -2780,6 +2783,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "pollster"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"+[[package]]name = "pollster"version = "1.0.1"@@ -3009,6 +3018,30 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"+[[package]]+name = "rfd"+version = "0.17.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220"+dependencies = [+ "block2 0.6.2",+ "dispatch2",+ "js-sys",+ "libc",+ "log",+ "objc2 0.6.5",+ "objc2-app-kit 0.3.2",+ "objc2-core-foundation",+ "objc2-foundation 0.3.2",+ "percent-encoding",+ "pollster 0.4.0",+ "raw-window-handle",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "windows-sys 0.61.2",+]+[[package]]name = "rustc-hash"version = "1.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 3859e50..822ede4 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -12,5 +12,11 @@ publish = false[profile.release]debug = 1+[profile.dist]+inherits = "release"+debug = 0+strip = "symbols"+lto = "thin"+[profile.dev.package."*"]opt-level = 3diff --git a/README.md b/README.mdindex 72afdac..a7a6a76 100644--- a/README.md+++ b/README.md@@ -38,24 +38,35 @@ klad ink courier.draw lines --from shell-4,head-4,near-leg-4 --weight 5 --frameEarly, and open for testing. What works today:-- The `klad` CLI on macOS and Linux: layers, brush strokes, vector shapes, fills, inking, painting from shapes, light, effects, depth and fog, text in about fifty open fonts that come with it (and any other Google Fonts family on request), frames and clips, in-betweens, exports.-- The editor on macOS: a pen with pressure and tilt, brushes, layers, masks, a text tool, the timeline, onion skins, notes for the agent, and a start window for new and recent drawings.-- Coming next: downloadable builds for macOS, Windows and Linux, the editor on Windows and Linux, and an agent inside the editor you sign in to, so you never need a terminal.+- The `klad` CLI on macOS, Linux and Windows: layers, brush strokes, vector shapes, fills, inking, painting from shapes, light, effects, depth and fog, text in about fifty open fonts that come with it (and any other Google Fonts family on request), frames and clips, in-betweens, exports.+- The editor on macOS, and in a first version on Windows and Linux: a pen with pressure and tilt (pressure only on Windows; on Linux the mouse for now), brushes, layers, masks, a text tool, the timeline, onion skins, notes for the agent, and a start window for new and recent drawings.+- Coming next: an agent inside the editor you sign in to, so you never need a terminal.## Try it-There are no downloads yet; build it from source (about ten minutes the first time).+Download klad from the [releases page](https://github.com/klad-app/klad/releases):-1. Install Rust with [rustup](https://rustup.rs) and [`just`](https://github.com/casey/just) (`brew install just`, or `cargo install just`). On Linux also `pkg-config`, `libfreetype-dev` and `libfontconfig1-dev`.-2. `git clone https://github.com/klad-app/klad && cd klad`, then `just build` makes the `klad` binary in `target/release/` (on Linux in `target/linux/release/`).-3. On a Mac, `target/release/klad open` starts the editor on its start window: make a drawing and start painting.+- macOS: `klad-<version>-macos.dmg`. Drag klad to Applications. The app is not signed yet: the first time, right click it and choose Open. In the editor, the document menu's "install the klad command" puts `klad` on your terminal's path for you and for agents.+- Windows: `klad-<version>-windows-x86_64.zip`. Unzip it anywhere and start `klad-editor.exe`; `klad.exe install` adds the folder to your PATH.+- Linux: `klad-<version>-<arch>.AppImage` (make it executable and run it), or the `tar.gz` with `klad` and `klad-editor`; `klad install` links `klad` into `~/.local/bin`.++Every download holds the same `klad` command line tool, the editor, the fonts, the licences and the agent skill (`klad skill` prints it). The editor checks the releases page once a day for a new version and says so; it installs nothing by itself (turn it off in the settings window).++### From source++Building takes about ten minutes the first time.++1. Install Rust with [rustup](https://rustup.rs) and [`just`](https://github.com/casey/just) (`brew install just`, or `cargo install just`). On Linux also `pkg-config`, `libfreetype-dev`, `libfontconfig1-dev`, `libxkbcommon-dev` and `libwayland-dev`.+2. `git clone https://github.com/klad-app/klad && cd klad`, then `just build` makes `klad` and `klad-editor` in `target/release/` (on Linux in `target/linux/release/`).+3. `target/release/klad open` starts the editor on its start window: make a drawing and start painting.4. `just samples` builds the sample drawings in `samples/` (a lantern, a walking creature, a running courier, an underground ruin, an inn sign, a tree, a meadow, painted solids, a bowl of lemons, a bouncing ball, ink examples); open one with `target/release/klad open samples/lantern/lantern.draw`.+5. `just app` makes `klad.app` and a disk image on a Mac; `just dist` makes the archive for the machine you are on (`just dist x86_64-pc-windows-msvc` for another target).## Drawing with an agent-Any coding agent that can run commands (Claude Code, Codex and others) can draw. Give it `docs/skill/SKILL.md` as its instructions (it is written as an agent skill) and the path to a drawing, then ask:+Any coding agent that can run commands (Claude Code, Codex and others) can draw. Give it `docs/skill/SKILL.md` (or the output of `klad skill`) as its instructions (it is written as an agent skill) and the path to a drawing, then ask:```shtarget/release/klad new art.draw --width 1600 --height 1200 --background '#e9e4da' --sketchdiff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex 6e2c885..f03451b 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -3391,6 +3391,7 @@ DEALINGS IN THE SOFTWARE.### MIT LicenseUsed by:+- pollster 0.4.0 (https://github.com/zesterer/pollster)- pollster 1.0.1 (https://github.com/zesterer/pollster)```text@@ -4285,6 +4286,36 @@ SOFTWARE.### MIT License+Used by:+- rfd 0.17.2 (https://github.com/PolyMeilex/rfd)++```text+MIT License++Copyright (c) 2020 Bilal Elmoussaoui++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.++```++### MIT License+Used by:- xcursor 0.3.11 (https://github.com/esposm03/xcursor-rs)@@ -4315,6 +4346,36 @@ SOFTWARE.### MIT License+Used by:+- rfd 0.17.2 (https://github.com/PolyMeilex/rfd)++```text+MIT License++Copyright (c) 2022 Bartłomiej Maryńczak++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.++```++### MIT License+Used by:- arboard 3.7.0 (https://github.com/1Password/arboard)@@ -4452,6 +4513,7 @@ Used by:- accesskit_windows 0.35.2 (https://github.com/AccessKit/accesskit)- block2 0.5.1 (https://github.com/madsmtm/objc2)- block2 0.6.2 (https://github.com/madsmtm/objc2)+- dispatch2 0.3.1 (https://github.com/madsmtm/objc2)- dispatch 0.2.0 (http://github.com/SSheldon/rust-dispatch)- dpi 0.1.2 (https://github.com/rust-windowing/winit)- ecolor 0.37.0 (https://github.com/emilk/egui)diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.tomlindex e3750ef..8c9db11 100644--- a/crates/app/Cargo.toml+++ b/crates/app/Cargo.toml@@ -4,6 +4,7 @@ version.workspace = trueedition.workspace = truelicense-file.workspace = truepublish.workspace = true+build = "../version.rs"[dependencies]anyhow = "1.0.104"@@ -29,5 +30,8 @@ objc2 = "0.6"objc2-app-kit = { version = "0.3", features = ["NSEvent", "NSResponder", "NSGraphics", "NSApplication", "NSWindow", "NSPanel", "NSSavePanel", "NSOpenPanel"] }objc2-foundation = "0.3"+[target.'cfg(not(target_os = "macos"))'.dependencies]+rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal"] }+[dev-dependencies]egui_kittest = { version = "0.37.0", features = ["wgpu"] }diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rsindex d390f63..520134b 100644--- a/crates/app/src/commands.rs+++ b/crates/app/src/commands.rs@@ -147,6 +147,7 @@ pub enum Cmd {OpenDocument,OpenRecent,CopyPath,+ InstallCommand,About,Export,AddFont,@@ -469,7 +470,7 @@ use Repeat as R;use Trigger as T;impl Cmd {- pub const ALL: [Cmd; 151] = [+ pub const ALL: [Cmd; 152] = [Cmd::Brush,Cmd::Eraser,Cmd::Fill,@@ -613,6 +614,7 @@ impl Cmd {Cmd::OpenDocument,Cmd::OpenRecent,Cmd::CopyPath,+ Cmd::InstallCommand,Cmd::About,Cmd::Export,Cmd::AddFont,@@ -1966,6 +1968,15 @@ impl Cmd {R::No,"the version, the licence and every open source part it is built on",),+ Cmd::InstallCommand => spec(+ "file.install-command",+ "install the klad command",+ icon::DOWNLOAD,+ G::File,+ T::None,+ R::No,+ "puts klad on the terminal's path (klad install), for you and for agents",+ ),Cmd::CopyPath => spec("file.copy-path","copy this drawing's path",diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 04226e6..5fba39b 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -21,6 +21,8 @@ mod text;mod timeline;mod tweens;#[cfg(test)]+pub(crate) use commands::install_job;+#[cfg(test)]mod ui_tests;use crate::color::{self, Hsva};@@ -543,6 +545,7 @@ pub(crate) struct Editor {pub(crate) settings: Settings,pub(crate) settings_path: Option<PathBuf>,pub(crate) settings_dirty: bool,+ pub(crate) update: Option<crate::updates::Release>,pub(crate) wants: Option<Want>,view: Option<View>,canvas_rect: Rect,@@ -700,6 +703,7 @@ impl Editor {settings,settings_path,settings_dirty: false,+ update: None,wants: None,view: None,canvas_rect: Rect::NOTHING,@@ -848,7 +852,7 @@ impl Editor {vec2(w as f32, h as f32)}- fn say(&mut self, tone: Tone, text: impl Into<String>) {+ pub(crate) fn say(&mut self, tone: Tone, text: impl Into<String>) {let anchor = self.pointer;self.messages.say(tone, text, anchor, Instant::now());self.ctx.request_repaint();diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rsindex 892aac7..6c690a6 100644--- a/crates/app/src/editor/commands.rs+++ b/crates/app/src/editor/commands.rs@@ -2,6 +2,7 @@ use super::selection::Selected;use super::tweens::{self, SpanAction};use super::{Editor, Tool};use crate::commands::{Cmd, Repeat};+use crate::jobs::{Spec, Tag};use crate::layout::Pane;use crate::messages::Tone;use crate::stats::{Stats, lock};@@ -587,6 +588,7 @@ impl Editor {Cmd::ShowGaps => self.show_gaps()?,Cmd::ShowParts => self.checks.parts = !self.checks.parts,Cmd::ShowArcs => self.show_arcs()?,+ Cmd::InstallCommand => self.start_job(install_job()),Cmd::CopyPath => {let path = self.scene.bundle.root.display().to_string();self.ctx.copy_text(path.clone());@@ -909,3 +911,16 @@ impl Editor {}}}++pub(crate) fn install_job() -> Spec {+ Spec {+ tag: Tag::Install,+ name: "install the klad command".into(),+ exe: std::path::PathBuf::new(),+ args: vec!["install".into()],+ env: Vec::new(),+ reruns: 0,+ summary: |out, _| out.lines().next().unwrap_or_default().to_string(),+ failure: |_, err| err.lines().last().unwrap_or_default().to_string(),+ }+}diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rsindex c0132dc..6e70683 100644--- a/crates/app/src/editor/panels.rs+++ b/crates/app/src/editor/panels.rs@@ -263,6 +263,7 @@ impl Editor {(Cmd::Export, "export"),(Cmd::AddFont, "add a font"),(Cmd::CopyPath, "copy path"),+ (Cmd::InstallCommand, "install the klad command"),(Cmd::About, "about and licences"),].into_iter()@@ -278,10 +279,16 @@ impl Editor {));}- fn about_panel(ui: &mut egui::Ui) {+ fn about_panel(ui: &mut egui::Ui, update: Option<&crate::updates::Release>) {static LINES: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();let lines = LINES.get_or_init(|| klad_core::notices::NOTICES.lines().collect());- ui.label(RichText::new(format!("klad {}", env!("CARGO_PKG_VERSION"))).strong());+ ui.label(RichText::new(format!("klad {}", crate::VERSION)).strong());+ if let Some(release) = update {+ ui.horizontal(|ui| {+ ui.label(crate::updates::summary(release));+ ui.hyperlink_to("what changed", &release.url);+ });+ }ui.label("Source-available licence, copyright Indicode BV. Built on the open source work listed below; klad licences prints the same.");ui.add_space(6.0);ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);@@ -626,7 +633,7 @@ impl Editor {"about",(format!("{} About klad", icon::INFO), settings_at),&mut open,- Self::about_panel,+ |ui| Self::about_panel(ui, self.update.as_ref()),);self.windows.about &= open;}diff --git a/crates/app/src/editor/prefs.rs b/crates/app/src/editor/prefs.rsindex 0888d24..22e1939 100644--- a/crates/app/src/editor/prefs.rs+++ b/crates/app/src/editor/prefs.rs@@ -95,6 +95,15 @@ impl Editor {self.settings_dirty = true;}});+ let mut check = self.settings.check_updates;+ if ui+ .checkbox(&mut check, "check for a new version once a day")+ .hint("asks the release page on GitHub at most once a day; nothing is installed without you")+ .changed()+ {+ self.settings.check_updates = check;+ self.settings_dirty = true;+ }}pub(super) fn keys_section(&mut self, ui: &mut egui::Ui) {diff --git a/crates/app/src/home.rs b/crates/app/src/home.rsindex 68e5ffc..4fff1fd 100644--- a/crates/app/src/home.rs+++ b/crates/app/src/home.rs@@ -1,9 +1,11 @@use crate::editor::{Editor, Want};use crate::gpu::CanvasGpu;+use crate::messages::Tone;use crate::picker;use crate::settings::{self, Settings};use crate::start::{self, Section, Start};use crate::theme;+use crate::updates;use anyhow::{Result, anyhow};use egui::RichText;use egui_wgpu::wgpu;@@ -12,6 +14,7 @@ use std::path::{Path, PathBuf};const WIDTH: f32 = 760.0;pub fn run(path: Option<PathBuf>) -> Result<()> {+ crate::opened::listen();let options = eframe::NativeOptions {viewport: egui::ViewportBuilder::default().with_title(start::title(path.as_deref()))@@ -41,6 +44,8 @@ pub(crate) struct Home {pub(crate) settings_path: Option<PathBuf>,gpu: Option<egui_wgpu::RenderState>,themed: bool,+ pub(crate) update: Option<crate::updates::Release>,+ checking: bool,}impl Home {@@ -52,6 +57,14 @@ impl Home {let settings_path = settings::default_path();let settings = settings_path.as_deref().map(Settings::load).unwrap_or_default();let mut home = Self::with(settings, settings_path, Some(gpu));+ if updates::due(+ home.settings.check_updates,+ home.settings.updates_checked,+ updates::now(),+ ) {+ updates::start(updates::feed());+ home.checking = true;+ }home.begin(&cc.egui_ctx, path);Ok(home)}@@ -68,6 +81,8 @@ impl Home {settings_path,gpu,themed: false,+ update: None,+ checking: false,}}@@ -108,8 +123,43 @@ impl Home {Ok(())}+ fn checked(&mut self) {+ if !self.checking {+ return;+ }+ let Some(result) = updates::take() else {+ return;+ };+ self.checking = false;+ let now = updates::now();+ self.settings.updates_checked = now;+ match self.editor.as_mut() {+ Some(editor) => {+ editor.settings.updates_checked = now;+ editor.settings_dirty = true;+ }+ None => {+ if let Some(path) = &self.settings_path {+ let _ = self.settings.save(path);+ }+ }+ }+ if let Some(release) = result {+ if let Some(editor) = self.editor.as_mut() {+ editor.say(Tone::Info, updates::summary(&release));+ }+ self.update = Some(release);+ }+ }+pub(crate) fn frame(&mut self, ui: &mut egui::Ui) {let ctx = ui.ctx().clone();+ self.checked();+ if let Some(editor) = self.editor.as_mut()+ && editor.update.is_none()+ {+ editor.update.clone_from(&self.update);+ }let mut chosen = None;match self.editor.as_mut() {Some(editor) => {@@ -172,6 +222,12 @@ impl Home {ui.vertical(|ui| {ui.set_max_width(WIDTH);ui.heading(RichText::new("klad").size(26.0));+ if let Some(release) = &self.update {+ ui.horizontal(|ui| {+ ui.label(updates::summary(release));+ ui.hyperlink_to("what changed", &release.url);+ });+ }ui.add_space(12.0);chosen = start.ui(ui, &mut self.settings);});@@ -185,7 +241,7 @@ impl Home {}}}- if let Some(path) = chosen+ if let Some(path) = chosen.or_else(crate::opened::take)&& let Err(e) = self.open(&ctx, &path){let message = format!("opening {}: {e:#}", path.display());@@ -314,6 +370,36 @@ mod tests {std::fs::remove_dir_all(&dir).unwrap();}+ #[test]+ fn a_drawing_the_system_asks_to_open_opens_from_the_start_window() {+ let dir = folder("finder");+ let made = dir.join("from finder.draw");+ Bundle::blank(&made, &small(), "cli").unwrap();+ let mut first = home(&dir, &[]);+ first.begin(&egui::Context::default(), None);+ let mut h = harness(first);+ assert!(h.state().editor.is_none());+ crate::opened::push(made.clone());+ h.run_steps(2);+ assert_eq!(opened(&h), made);+ assert!(crate::opened::take().is_none());+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn a_new_version_shows_in_the_start_window_with_what_changed() {+ let dir = folder("update");+ let mut first = home(&dir, &[]);+ first.begin(&egui::Context::default(), None);+ first.update = updates::parse(+ r#"{"tag_name":"v9.0.0","html_url":"https://github.com/klad-app/klad/releases/tag/v9.0.0","body":"- Paint over"}"#,+ );+ let h = harness(first);+ assert!(h.query_by_label("klad 9.0.0 is out: Paint over").is_some());+ assert!(h.query_by_label("what changed").is_some());+ std::fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn recent_reopens_a_drawing_and_greys_out_a_moved_one() {let dir = folder("recent");@@ -458,6 +544,11 @@ mod tests {let mut h = harness(first);h.get_by_label(theme::icon::FILE).click();h.run_steps(2);+ assert!(+ h.query_by_label(&format!("{} install the klad command", theme::icon::DOWNLOAD))+ .is_some()+ );+ assert_eq!(crate::editor::install_job().args, ["install"]);h.get_by_label(&format!("{} about and licences", theme::icon::INFO)).click();h.run_steps(3);diff --git a/crates/app/src/jobs.rs b/crates/app/src/jobs.rsindex 6c8582f..c2fb32f 100644--- a/crates/app/src/jobs.rs+++ b/crates/app/src/jobs.rs@@ -17,6 +17,7 @@ pub enum Tag {Gaps,Arcs,Fonts,+ Install,}#[derive(Clone)]diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rsindex 71991c6..471f537 100644--- a/crates/app/src/lib.rs+++ b/crates/app/src/lib.rs@@ -9,18 +9,26 @@ mod jobs;mod layout;mod lift;mod messages;+mod opened;mod pen;mod picker;+mod places;mod planes;mod settings;mod start;mod stats;mod sync;mod theme;+mod updates;mod view;pub use home::run;+pub const VERSION: &str = match env!("KLAD_BUILD").is_empty() {+ true => env!("CARGO_PKG_VERSION"),+ false => concat!(env!("CARGO_PKG_VERSION"), " (", env!("KLAD_BUILD"), ")"),+};+fn background() -> &'static rayon::ThreadPool {static POOL: std::sync::OnceLock<rayon::ThreadPool> = std::sync::OnceLock::new();POOL.get_or_init(|| {diff --git a/crates/app/src/opened.rs b/crates/app/src/opened.rsnew file mode 100644index 0000000..ef0a06e--- /dev/null+++ b/crates/app/src/opened.rs@@ -0,0 +1,58 @@+use std::path::PathBuf;+use std::sync::Mutex;++static QUEUE: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());++#[cfg(any(target_os = "macos", test))]+pub fn push(path: PathBuf) {+ QUEUE.lock().unwrap_or_else(|e| e.into_inner()).push(path);+}++pub fn take() -> Option<PathBuf> {+ std::mem::take(&mut *QUEUE.lock().unwrap_or_else(|e| e.into_inner())).pop()+}++#[cfg(target_os = "macos")]+pub use mac::listen;++#[cfg(not(target_os = "macos"))]+pub fn listen() {}++#[cfg(target_os = "macos")]+mod mac {+ use objc2::runtime::{AnyClass, AnyObject, Imp, Sel};+ use objc2::{ffi, sel};+ use objc2_foundation::{NSArray, NSURL};+ use std::path::PathBuf;++ type OpenUrls = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject, *mut NSArray<NSURL>);++ unsafe extern "C-unwind" fn open_urls(+ _this: *mut AnyObject,+ _cmd: Sel,+ _app: *mut AnyObject,+ urls: *mut NSArray<NSURL>,+ ) {+ let Some(urls) = (unsafe { urls.as_ref() }) else {+ return;+ };+ urls.iter()+ .filter_map(|url| url.path())+ .for_each(|path| super::push(PathBuf::from(path.to_string())));+ }++ pub fn listen() {+ let Some(class) = AnyClass::get(c"NSObject") else {+ return;+ };+ let imp: Imp = unsafe { std::mem::transmute::<OpenUrls, Imp>(open_urls) };+ unsafe {+ ffi::class_addMethod(+ class as *const AnyClass as *mut AnyClass,+ sel!(application:openURLs:),+ imp,+ c"v@:@@".as_ptr(),+ );+ }+ }+}diff --git a/crates/app/src/pen.rs b/crates/app/src/pen.rsindex 230246b..e74d9ef 100644--- a/crates/app/src/pen.rs+++ b/crates/app/src/pen.rs@@ -38,8 +38,51 @@ pub fn device_key(device: u64) -> String {}}+fn from_touches(events: &[egui::Event], at: Instant) -> Vec<PenEvent> {+ let first = events.iter().find_map(|e| match e {+ egui::Event::Touch { id, force: Some(_), .. } => Some(*id),+ _ => None,+ });+ events+ .iter()+ .filter_map(|e| match e {+ egui::Event::Touch {+ device_id,+ id,+ phase,+ pos,+ force: Some(force),+ } if Some(*id) == first => {+ let phase = match phase {+ egui::TouchPhase::Start => Phase::Down,+ egui::TouchPhase::Move => Phase::Move,+ egui::TouchPhase::End | egui::TouchPhase::Cancel => Phase::Up,+ };+ Some(PenEvent {+ phase,+ pos: *pos,+ pressure: match phase {+ Phase::Up => 0.0,+ _ => force.clamp(0.0, 1.0),+ },+ tilt: (0.0, 0.0),+ eraser: false,+ tablet: true,+ device: device_id.0,+ at,+ })+ }+ _ => None,+ })+ .collect()+}+pub fn from_egui(events: &[egui::Event]) -> Vec<PenEvent> {let at = Instant::now();+ let touches = from_touches(events, at);+ if !touches.is_empty() {+ return touches;+ }let event = |phase, pos, pressure| PenEvent {phase,pos,@@ -271,6 +314,41 @@ mod tests {assert_eq!(pen[1].pos, egui::pos2(3.0, 4.0));}+ #[test]+ fn a_pen_reported_as_touches_with_force_draws_with_its_pressure() {+ let touch = |phase, x: f32, force| egui::Event::Touch {+ device_id: egui::TouchDeviceId(7),+ id: egui::TouchId(1),+ phase,+ pos: egui::pos2(x, 5.0),+ force,+ };+ let events = [+ touch(egui::TouchPhase::Start, 1.0, Some(0.2)),+ egui::Event::PointerButton {+ pos: egui::pos2(1.0, 5.0),+ button: egui::PointerButton::Primary,+ pressed: true,+ modifiers: egui::Modifiers::NONE,+ },+ touch(egui::TouchPhase::Move, 2.0, Some(0.7)),+ egui::Event::PointerMoved(egui::pos2(2.0, 5.0)),+ touch(egui::TouchPhase::End, 2.0, Some(0.0)),+ ];+ let pen = from_egui(&events);+ assert_eq!(+ pen.iter().map(|e| (e.phase, e.pressure)).collect::<Vec<_>>(),+ [(Phase::Down, 0.2), (Phase::Move, 0.7), (Phase::Up, 0.0)],+ "the pointer events egui makes from the same touch are not drawn twice"+ );+ assert!(pen.iter().all(|e| e.tablet && e.device == 7));+ let finger = [touch(egui::TouchPhase::Start, 1.0, None)];+ assert!(+ from_egui(&finger).is_empty(),+ "touches without force stay pointer input"+ );+ }+#[test]fn mouse_drags_without_pressure_record_full_pressure() {let mut e = from_egui(&[egui::Event::PointerMoved(egui::pos2(3.0, 4.0))])[0];diff --git a/crates/app/src/picker.rs b/crates/app/src/picker.rsindex ea086c7..735079e 100644--- a/crates/app/src/picker.rs+++ b/crates/app/src/picker.rs@@ -1,6 +1,6 @@use std::path::{Path, PathBuf};-pub const NATIVE: bool = cfg!(target_os = "macos");+pub const NATIVE: bool = cfg!(target_os = "macos") || !cfg!(test);#[cfg(target_os = "macos")]pub fn choose_folder(start: Option<&Path>, prompt: &str) -> Option<PathBuf> {@@ -37,11 +37,20 @@ fn choose(start: Option<&Path>, prompt: &str, folders: bool) -> Option<PathBuf>}#[cfg(not(target_os = "macos"))]-pub fn choose_folder(_start: Option<&Path>, _prompt: &str) -> Option<PathBuf> {- None+fn dialog(start: Option<&Path>, prompt: &str) -> rfd::FileDialog {+ let dialog = rfd::FileDialog::new().set_title(prompt);+ match start.filter(|d| d.is_dir()) {+ Some(dir) => dialog.set_directory(dir),+ None => dialog,+ }+}++#[cfg(not(target_os = "macos"))]+pub fn choose_folder(start: Option<&Path>, prompt: &str) -> Option<PathBuf> {+ dialog(start, prompt).pick_folder()}#[cfg(not(target_os = "macos"))]-pub fn choose_file(_start: Option<&Path>, _prompt: &str) -> Option<PathBuf> {- None+pub fn choose_file(start: Option<&Path>, prompt: &str) -> Option<PathBuf> {+ dialog(start, prompt).pick_file()}diff --git a/crates/app/src/places.rs b/crates/app/src/places.rsnew file mode 100644index 0000000..2095f43--- /dev/null+++ b/crates/app/src/places.rs@@ -0,0 +1,45 @@+use std::path::PathBuf;++pub fn home() -> Option<PathBuf> {+ ["HOME", "USERPROFILE"]+ .iter()+ .find_map(std::env::var_os)+ .filter(|h| !h.is_empty())+ .map(PathBuf::from)+}++pub fn config() -> Option<PathBuf> {+ if cfg!(target_os = "windows") {+ return std::env::var_os("APPDATA")+ .map(PathBuf::from)+ .or_else(|| home().map(|h| h.join("AppData/Roaming")));+ }+ let home = home()?;+ Some(match cfg!(target_os = "macos") {+ true => home.join("Library/Application Support"),+ false => std::env::var_os("XDG_CONFIG_HOME").map_or(home.join(".config"), PathBuf::from),+ })+}++pub fn drawings() -> PathBuf {+ home().map_or_else(|| PathBuf::from("Drawings"), |h| h.join("Drawings"))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn places_follow_the_platform() {+ let config = config().unwrap();+ let home = home().unwrap();+ match cfg!(target_os = "macos") {+ true => assert_eq!(config, home.join("Library/Application Support")),+ false if cfg!(target_os = "windows") => {+ assert!(config.ends_with("Roaming") || std::env::var_os("APPDATA").is_some())+ }+ false => assert!(config.ends_with(".config") || std::env::var_os("XDG_CONFIG_HOME").is_some()),+ }+ assert_eq!(drawings(), home.join("Drawings"));+ }+}diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rsindex 1069978..b85d5b2 100644--- a/crates/app/src/settings.rs+++ b/crates/app/src/settings.rs@@ -79,6 +79,14 @@ pub struct Settings {pub documents: Vec<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub drawings: Option<String>,+ #[serde(default = "yes", rename = "checkUpdates")]+ pub check_updates: bool,+ #[serde(default, rename = "updatesChecked")]+ pub updates_checked: u64,+}++fn yes() -> bool {+ true}impl Default for Settings {@@ -94,6 +102,8 @@ impl Default for Settings {defaults: Defaults::default(),documents: Vec::new(),drawings: None,+ check_updates: true,+ updates_checked: 0,}}}@@ -123,12 +133,7 @@ pub fn default_path() -> Option<PathBuf> {if let Some(path) = std::env::var_os("KLAD_SETTINGS") {return Some(PathBuf::from(path));}- let home = PathBuf::from(std::env::var_os("HOME")?);- let config = match cfg!(target_os = "macos") {- true => home.join("Library/Application Support"),- false => std::env::var_os("XDG_CONFIG_HOME").map_or(home.join(".config"), PathBuf::from),- };- Some(carried_over(&config))+ Some(carried_over(&crate::places::config()?))}pub fn carried_over(config: &Path) -> PathBuf {@@ -198,13 +203,9 @@ impl Settings {}pub fn drawings_folder(&self) -> PathBuf {- self.drawings.as_ref().map_or_else(- || {- std::env::var_os("HOME")- .map_or_else(|| PathBuf::from("Drawings"), |h| PathBuf::from(h).join("Drawings"))- },- PathBuf::from,- )+ self.drawings+ .as_ref()+ .map_or_else(crate::places::drawings, PathBuf::from)}pub fn used(&mut self, hex: &str) -> bool {diff --git a/crates/app/src/start.rs b/crates/app/src/start.rsindex fc963db..8fbbcdc 100644--- a/crates/app/src/start.rs+++ b/crates/app/src/start.rs@@ -403,8 +403,8 @@ fn fit(size: egui::Vec2) -> egui::Vec2 {}pub fn expand(text: &str) -> PathBuf {- match (text.strip_prefix("~/"), std::env::var_os("HOME")) {- (Some(rest), Some(home)) => PathBuf::from(home).join(rest),+ match (text.strip_prefix("~/"), crate::places::home()) {+ (Some(rest), Some(home)) => home.join(rest),_ => PathBuf::from(text),}}@@ -437,8 +437,10 @@ pub(crate) fn draw_binary() -> Option<PathBuf> {if exe.file_stem().is_some_and(|s| s == "klad") {return Some(exe);}- let sibling = exe.parent()?.parent()?.join("klad");- sibling.is_file().then_some(sibling)+ let name = format!("klad{}", std::env::consts::EXE_SUFFIX);+ [exe.parent()?.join(&name), exe.parent()?.parent()?.join(&name)]+ .into_iter()+ .find(|p| p.is_file())}fn modified(path: &Path) -> Option<SystemTime> {diff --git a/crates/app/src/updates.rs b/crates/app/src/updates.rsnew file mode 100644index 0000000..26027ae--- /dev/null+++ b/crates/app/src/updates.rs@@ -0,0 +1,160 @@+use serde::Deserialize;+use std::sync::{Mutex, OnceLock};+use std::time::{SystemTime, UNIX_EPOCH};++pub const FEED: &str = "https://api.github.com/repos/klad-app/klad/releases/latest";+const DAY: u64 = 24 * 60 * 60;++#[derive(Clone, Debug, PartialEq)]+pub struct Release {+ pub version: String,+ pub url: String,+ pub notes: String,+}++#[derive(Deserialize)]+struct Feed {+ tag_name: String,+ html_url: String,+ #[serde(default)]+ body: Option<String>,+}++pub fn parse(json: &str) -> Option<Release> {+ let feed: Feed = serde_json::from_str(json).ok()?;+ Some(Release {+ version: feed.tag_name.trim_start_matches('v').to_string(),+ url: feed.html_url,+ notes: feed.body.unwrap_or_default(),+ })+}++fn parts(version: &str) -> Vec<u64> {+ version+ .trim_start_matches('v')+ .split(['.', '-', '+', ' '])+ .take(3)+ .map(|p| p.parse().unwrap_or(0))+ .collect()+}++pub fn newer(current: &str, latest: &str) -> bool {+ parts(latest) > parts(current)+}++pub fn due(enabled: bool, last: u64, now: u64) -> bool {+ enabled && now.saturating_sub(last) >= DAY+}++pub fn now() -> u64 {+ SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())+}++fn fetch(feed: &str) -> Option<String> {+ match feed.starts_with("http") {+ true => std::process::Command::new("curl")+ .args([+ "-fsSL",+ "--max-time",+ "10",+ "-H",+ "Accept: application/vnd.github+json",+ feed,+ ])+ .output()+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string()),+ false => std::fs::read_to_string(feed).ok(),+ }+}++pub fn check(feed: &str, current: &str) -> Option<Release> {+ parse(&fetch(feed)?).filter(|r| newer(current, &r.version))+}++pub fn summary(release: &Release) -> String {+ let first = release+ .notes+ .lines()+ .map(|l| l.trim().trim_start_matches(['-', '*', '#']).trim())+ .find(|l| !l.is_empty());+ match first {+ Some(line) => format!("klad {} is out: {line}", release.version),+ None => format!("klad {} is out", release.version),+ }+}++type Found = Mutex<Option<Option<Release>>>;++fn found() -> &'static Found {+ static FOUND: OnceLock<Found> = OnceLock::new();+ FOUND.get_or_init(|| Mutex::new(None))+}++pub fn start(feed: String) {+ std::thread::Builder::new()+ .name("klad update check".into())+ .spawn(move || {+ let result = check(&feed, env!("CARGO_PKG_VERSION"));+ *found().lock().unwrap_or_else(|e| e.into_inner()) = Some(result);+ })+ .ok();+}++pub fn take() -> Option<Option<Release>> {+ found().lock().unwrap_or_else(|e| e.into_inner()).take()+}++pub fn feed() -> String {+ std::env::var("KLAD_UPDATE_FEED").unwrap_or_else(|_| FEED.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_newer_release_in_the_feed_is_found_once_a_day_and_never_when_off() {+ let dir = std::env::temp_dir().join(format!("klad-updates-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let feed = dir.join("latest.json");+ let write = |tag: &str| {+ std::fs::write(+ &feed,+ format!(+ r#"{{"tag_name":"{tag}","html_url":"https://github.com/klad-app/klad/releases/tag/{tag}","body":"\n- Paint over: brushwork from any picture\n- more"}}"#+ ),+ )+ .unwrap()+ };+ write("v0.2.0");+ let found = check(feed.to_str().unwrap(), "0.1.0").unwrap();+ assert_eq!(found.version, "0.2.0");+ assert_eq!(+ summary(&found),+ "klad 0.2.0 is out: Paint over: brushwork from any picture"+ );+ write("v0.1.0");+ assert!(check(feed.to_str().unwrap(), "0.1.0").is_none());+ assert!(check(dir.join("missing.json").to_str().unwrap(), "0.1.0").is_none());+ assert!(newer("0.9.3", "0.10.0") && !newer("1.2.0", "1.1.9") && newer("0.1.0", "v0.1.1"));+ assert!(due(true, 0, DAY) && !due(true, DAY, DAY + 60) && !due(false, 0, 10 * DAY));+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn the_check_runs_beside_the_ui() {+ let dir = std::env::temp_dir().join(format!("klad-updates-bg-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let feed = dir.join("latest.json");+ std::fs::write(&feed, r#"{"tag_name":"v99.0.0","html_url":"https://example.org"}"#).unwrap();+ start(feed.display().to_string());+ let found = (0..200).find_map(|_| {+ std::thread::sleep(std::time::Duration::from_millis(10));+ take()+ });+ assert_eq!(found.flatten().map(|r| r.version), Some("99.0.0".to_string()));+ std::fs::remove_dir_all(&dir).unwrap();+ }+}diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.tomlindex 498127c..8a044a4 100644--- a/crates/cli/Cargo.toml+++ b/crates/cli/Cargo.toml@@ -4,6 +4,7 @@ version.workspace = trueedition.workspace = truelicense-file.workspace = truepublish.workspace = true+build = "../version.rs"[dependencies]anyhow = "1.0.104"@@ -21,8 +22,19 @@ zstd = "0.14.3"name = "klad"path = "src/main.rs"-[target.'cfg(target_os = "macos")'.dependencies]-klad-app = { version = "0.1.0", path = "../app" }+[[bin]]+name = "klad-editor"+path = "src/bin/klad-editor.rs"+required-features = ["editor"]++[features]+default = ["editor"]+editor = ["dep:klad-app"]++[dependencies.klad-app]+version = "0.1.0"+path = "../app"+optional = true[target."cfg(unix)".dependencies]libc = "0.2.191"diff --git a/crates/cli/src/bench.rs b/crates/cli/src/bench.rsindex b49cf10..bf57010 100644--- a/crates/cli/src/bench.rs+++ b/crates/cli/src/bench.rs@@ -193,11 +193,22 @@ fn still_speed(brushes: &BrushSet, seed: u64) -> Result<()> {let points: Vec<(f32, f32, f32)> = (0..5).map(|k| {let t = k as f32 / 4.0;- (x + a.cos() * length * t, y + a.sin() * length * t, [0.2, 0.9, 1.0, 0.8, 0.1][k])+ (+ x + a.cos() * length * t,+ y + a.sin() * length * t,+ [0.2, 0.9, 1.0, 0.8, 0.1][k],+ )}).collect();- let colour = [0.3 + rng.unit() * 0.6, 0.3 + rng.unit() * 0.5, 0.3 + rng.unit() * 0.4, 1.0];- Stroke::new(i + 1, "oil", colour, size, i).with_points(&points, 8.0).into()+ let colour = [+ 0.3 + rng.unit() * 0.6,+ 0.3 + rng.unit() * 0.5,+ 0.3 + rng.unit() * 0.4,+ 1.0,+ ];+ Stroke::new(i + 1, "oil", colour, size, i)+ .with_points(&points, 8.0)+ .into()}).collect();let start = Instant::now();diff --git a/crates/cli/src/bin/klad-editor.rs b/crates/cli/src/bin/klad-editor.rsnew file mode 100644index 0000000..e4d899f--- /dev/null+++ b/crates/cli/src/bin/klad-editor.rs@@ -0,0 +1,12 @@+#![cfg_attr(windows, windows_subsystem = "windows")]++fn main() {+ let path = std::env::args_os()+ .skip(1)+ .find(|a| !a.to_string_lossy().starts_with("-psn_"))+ .map(std::path::PathBuf::from);+ if let Err(e) = klad_app::run(path) {+ eprintln!("error: {e:#}");+ std::process::exit(1);+ }+}diff --git a/crates/cli/src/install.rs b/crates/cli/src/install.rsnew file mode 100644index 0000000..98561ef--- /dev/null+++ b/crates/cli/src/install.rs@@ -0,0 +1,107 @@+use anyhow::{Context, Result, bail};+use std::path::{Path, PathBuf};+use std::process::Command;++fn on_path(dir: &Path) -> bool {+ std::env::var_os("PATH").is_some_and(|p| std::env::split_paths(&p).any(|d| d == dir))+}++fn default_dir() -> Result<PathBuf> {+ let home = ["HOME", "USERPROFILE"]+ .iter()+ .find_map(std::env::var_os)+ .map(PathBuf::from)+ .context("no home folder (HOME) to install into")?;+ Ok(match cfg!(target_os = "macos") {+ true => PathBuf::from("/usr/local/bin"),+ false => home.join(".local/bin"),+ })+}++#[cfg(unix)]+fn link(exe: &Path, dir: &Path) -> Result<PathBuf> {+ let to = dir.join("klad");+ let writable = std::fs::create_dir_all(dir).is_ok()+ && std::fs::symlink_metadata(&to).map_or(true, |_| std::fs::remove_file(&to).is_ok())+ && std::os::unix::fs::symlink(exe, &to).is_ok();+ if writable {+ return Ok(to);+ }+ if !cfg!(target_os = "macos") {+ bail!(+ "{} is not writable: give --dir with a folder of yours on the PATH",+ dir.display()+ );+ }+ let quoted = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\\\''"));+ let script = format!(+ "do shell script \"mkdir -p {} && ln -sf {} {}\" with administrator privileges",+ quoted(dir),+ quoted(exe),+ quoted(&to)+ );+ let status = Command::new("osascript").args(["-e", &script]).status()?;+ if !status.success() {+ bail!(+ "the link in {} was not made (the password prompt was cancelled?)",+ dir.display()+ );+ }+ Ok(to)+}++#[cfg(windows)]+fn link(exe: &Path, _dir: &Path) -> Result<PathBuf> {+ let folder = exe.parent().context("klad.exe has no folder")?;+ if on_path(folder) {+ return Ok(exe.to_path_buf());+ }+ let script = format!(+ "$p=[Environment]::GetEnvironmentVariable('Path','User'); if (-not ($p -split ';' -contains '{0}')) {{ [Environment]::SetEnvironmentVariable('Path', (@($p,'{0}') | Where-Object {{ $_ }}) -join ';', 'User') }}",+ folder.display().to_string().replace('\'', "''")+ );+ let status = Command::new("powershell")+ .args(["-NoProfile", "-Command", &script])+ .status()?;+ if !status.success() {+ bail!("adding {} to your PATH failed", folder.display());+ }+ Ok(exe.to_path_buf())+}++pub fn install(dir: Option<&Path>) -> Result<()> {+ let exe = std::env::current_exe()?.canonicalize()?;+ let dir = match dir {+ Some(d) => d.to_path_buf(),+ None => default_dir()?,+ };+ let made = link(&exe, &dir)?;+ match cfg!(windows) {+ true => println!("{} is on your PATH: open a new terminal and run klad", exe.display()),+ false => println!("{} -> {}", made.display(), exe.display()),+ }+ if !cfg!(windows) && !on_path(&dir) {+ println!(+ "{} is not on your PATH yet: add it in your shell's profile",+ dir.display()+ );+ }+ Ok(())+}++#[cfg(all(test, unix))]+mod tests {+ use super::*;++ #[test]+ fn install_links_klad_into_a_folder_and_replaces_an_old_link() {+ let dir = std::env::temp_dir().join(format!("klad-install-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ std::os::unix::fs::symlink("/nowhere", dir.join("klad")).unwrap();+ install(Some(&dir)).unwrap();+ let target = std::fs::read_link(dir.join("klad")).unwrap();+ assert_eq!(target, std::env::current_exe().unwrap().canonicalize().unwrap());+ std::fs::remove_dir_all(&dir).unwrap();+ }+}diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 03e7316..35da391 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -11,6 +11,7 @@ mod fonts;mod frames;mod history;mod inbetween;+mod install;mod layers;mod looks;mod marks;@@ -41,10 +42,15 @@ use marks::{fill_json, hex8, stroke_json};use std::path::{Path, PathBuf};use std::time::Instant;+const VERSION: &str = match env!("KLAD_BUILD").is_empty() {+ true => env!("CARGO_PKG_VERSION"),+ false => concat!(env!("CARGO_PKG_VERSION"), " (", env!("KLAD_BUILD"), ")"),+};+#[derive(Parser)]#[command(name = "klad",- version,+ version = VERSION,about = "klad: draw and paint with an agent, from the command line")]struct Cli {@@ -1486,6 +1492,16 @@ enum Command {alias = "licenses")]Licences,+ #[command(+ about = "Put klad on the terminal's path, for you and for agents",+ long_about = "Put klad on the terminal's path, for you and for agents. macOS: a link in /usr/local/bin (asks for your password when that folder is not yours). Linux: a link in ~/.local/bin. Windows: this folder is added to your PATH. --dir puts the link in another folder.\n\n klad install\n klad install --dir ~/bin"+ )]+ Install {+ #[arg(long)]+ dir: Option<PathBuf>,+ },+ #[command(about = "Print the agent skill: how an agent draws with klad (the same text as docs/skill/SKILL.md)")]+ Skill,#[command(about = "Measure stroke storage, brush speed, replay, cache and compositing")]Bench {#[arg(long, default_value_t = 10_000)]@@ -1495,7 +1511,7 @@ enum Command {#[arg(long, default_value_t = 1)]seed: u64,},- #[cfg(target_os = "macos")]+ #[cfg(feature = "editor")]#[command(about = "Open the editor, on a bundle or on the start window (new, open, recent)")]Open { bundle: Option<PathBuf> },}@@ -2865,8 +2881,10 @@ fn run() -> Result<()> {)?,Command::Watch { bundle, poll, seconds } => edit::watch(&bundle, poll, seconds)?,Command::Licences => print!("{}\n{}", klad_core::notices::LICENSE, klad_core::notices::NOTICES),+ Command::Install { dir } => install::install(dir.as_deref())?,+ Command::Skill => print!("{}", include_str!("../../../docs/skill/SKILL.md")),Command::Bench { strokes, size, seed } => bench::run(strokes, size, seed)?,- #[cfg(target_os = "macos")]+ #[cfg(feature = "editor")]Command::Open { bundle } => klad_app::run(bundle)?,}Ok(())diff --git a/crates/version.rs b/crates/version.rsnew file mode 100644index 0000000..debf55b--- /dev/null+++ b/crates/version.rs@@ -0,0 +1,22 @@+use std::path::Path;+use std::process::Command;++fn main() {+ let git = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.git");+ ["HEAD", "refs", "packed-refs"]+ .iter()+ .map(|p| git.join(p))+ .filter(|p| p.exists())+ .for_each(|p| println!("cargo:rerun-if-changed={}", p.display()));+ println!("cargo:rerun-if-env-changed=KLAD_BUILD");+ let described = std::env::var("KLAD_BUILD").ok().or_else(|| {+ Command::new("git")+ .args(["describe", "--tags", "--always"])+ .current_dir(env!("CARGO_MANIFEST_DIR"))+ .output()+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())+ });+ println!("cargo:rustc-env=KLAD_BUILD={}", described.unwrap_or_default());+}diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex afff5b8..c4f0e33 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-05 20:00_+_Last updated: 2026-11-05 20:26_# klad: design@@ -23,11 +23,13 @@ crates/core document model, ids, timeline, stroke format, bundle IO, op logbrush tile store, brush engine, stroke replay, checkpointsrender compositing, vector rendering, filters, overlays (Skia, CPU raster)- cli the `klad` binary- app the editor (macOS first), behind the `editor` feature+ cli the `klad` binary, and `klad-editor`+ app the editor, behind the `editor` feature (on by default)```-One binary, `klad`. `klad open [bundle]` launches the editor, on the bundle or, without one, on the start window (new, open, recent). The Linux build (agent container) has no editor; the macOS build has both.+Two binaries from one crate: `klad`, the command line, and `klad-editor`, the editor alone (a windowed program on Windows, the executable of `klad.app` on a Mac, started by the Linux AppImage). `klad open [bundle]` launches the same editor from the command line, on the bundle or, without one, on the start window (new, open, recent). `--no-default-features` builds `klad` without the editor. `klad --version` and the editor's About show the version and `git describe` of the commit it was built from (`crates/version.rs`, shared by both crates' build scripts; `KLAD_BUILD` overrides it).++**Platforms and packaging (M7).** Folders follow each platform: settings in `~/Library/Application Support/klad`, `%APPDATA%\klad` or `$XDG_CONFIG_HOME/klad`; downloaded fonts in the same places' data folder; drawings in `~/Drawings` by default. The open panel is `NSOpenPanel` on macOS and `rfd` elsewhere (the XDG portal on Linux, the common dialog on Windows). The pen: macOS reads `NSEvent`; elsewhere a pen that the system reports as a touch with force (Windows pens through `WM_POINTER`) draws with that pressure (`pen::from_egui`), and anything else draws as a mouse at full pressure; Linux tablets report no pressure through `winit` yet. `packaging/` makes the downloads: `macos/app.sh` builds `klad.app` (both binaries, lipo'd when several targets are given, the fonts, licences and skill in `Resources`, `.draw` declared as a document package of type `com.indicode.klad.drawing` so Finder shows a drawing as one item and opens it in klad) and a disk image; `archive.sh <target>` builds a `tar.gz` or `zip` with both binaries, `fonts/`, the licences and `SKILL.md`, and an AppImage on Linux when `APPIMAGETOOL` is set; `icon/` draws the icon in klad and packs `klad.icns` and `klad.ico`. Builds use the `dist` profile (no debug info, stripped, thin LTO); the samples hash the same from it. The fonts are found next to the binary (`fonts/`), in `../Resources/fonts` or `../share/klad/fonts`. On macOS a drawing opened from Finder arrives as an `application:openURLs:` message, which klad adds to `NSObject` before the event loop starts so it reaches whatever delegate `winit` installs; the paths queue up (`opened.rs`) and the start window or editor opens the last. `klad install` puts `klad` on the terminal's path (a link in `/usr/local/bin` through an administrator prompt on macOS, `~/.local/bin` on Linux, the user's `PATH` on Windows); the editor's document menu runs it as a job. `klad skill` prints the agent skill compiled into the binary. The `release` workflow (`.github/workflows`) builds all of it on a version tag and publishes it with checksums; `check` runs lint, tests and the audit on every pull request, tests on macOS and builds on Windows. The editor asks the GitHub releases API at most once a day (`updates.rs`, curl on a thread, off in the settings window) and, when a newer version is out, says so in the start window, the message line and About, with a link to what changed; it installs nothing.### Stack@@ -39,6 +41,7 @@ One binary, `klad`. `klad open [bundle]` launches the editor, on the bundle or,| Editor window and GPU display | `winit` + `wgpu` (Metal), through `eframe` | The GPU only shows CPU-made tiles: pan, zoom, rotate, overlays || Editor panels | `egui` | Fast to build, proven in pro tools (Rerun) || Pen input (macOS) | `NSEvent` local monitor through `objc2-app-kit` | `winit` only reports trackpad pressure; the monitor gives tablet pressure, tilt and the eraser end at full rate |+| File dialogs (Windows, Linux) | `rfd` | The platform's own dialog (the XDG portal on Linux); macOS keeps `NSOpenPanel` || Compression | `zstd` | Stroke files and cache tiles |klad is source-available, not open source: the PolyForm Internal Use License 1.0.0 with a personal-use permission, copyright Indicode BV (`LICENSE`). Every dependency is permissive: MIT, Apache-2.0, BSD-2/3, ISC, Zlib, BSL-1.0, Unicode-3.0, CC0-1.0, and for the fonts the editor shows its interface in, OFL-1.1 and the Ubuntu Font Licence. No GPL, LGPL or MPL unless dual licensed with one of these (two crates are, and are taken as `self_cell` under Apache-2.0 and `r-efi` under MIT). `deny.toml` holds the list, RustSec advisories, yanked versions and crates.io as the only source; `just audit` checks it with `cargo deny` and that `THIRD-PARTY-NOTICES.md` is current (`just notices` makes it with `cargo about`, plus the parts Cargo does not see: Skia's built-in libraries and the fonts, from `licenses/bundled/`). `klad licences` and the editor's About window show the same text.@@ -66,7 +69,8 @@ Direct dependencies, checked 2026-11-04 (all on their latest release; `cargo aud| `libc` | cli | default SIGPIPE handling, so piping `klad` into `head` ends quietly | MIT OR Apache-2.0 || `eframe`, `egui`, `egui-wgpu` 0.37 | app | the editor's window, GPU display and panels | MIT OR Apache-2.0 (egui's fonts: OFL-1.1, Ubuntu Font Licence) || `pollster` | app | blocking on wgpu setup | Apache-2.0 OR MIT |-| `objc2`, `objc2-app-kit`, `objc2-foundation`, `block2` | app, macOS | the pen through NSEvent, the open panel | MIT |+| `objc2`, `objc2-app-kit`, `objc2-foundation`, `block2` | app, macOS | the pen through NSEvent, the open panel, drawings opened from Finder | MIT |+| `rfd` 0.17 | app, Windows and Linux | the open panel (XDG portal, Windows common dialog) | MIT || `egui_kittest` (dev) | app tests | headless UI tests | MIT OR Apache-2.0 |Accepted warnings: `zvariant`, `zvariant_derive` and `zbus_names` (unmaintained) and `async-executor` 1.14.0 (yanked) come only through eframe's Linux accessibility (`accesskit_unix`) and wait on eframe moving to zbus 6.diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 8d20c82..8ff463e 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -5,7 +5,7 @@ description: Make and edit 2D art with the klad CLI (`klad`) in a `.draw` bundle# klad-A `.draw` 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`). 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 the document menu at the bottom of the tool strip to hand it to you. To start one yourself: `klad new art.draw --width 1600 --height 1200 --background '#e9e4da' --sketch` (one paint layer, `l1`, and a vector layer named sketch on top, `l3`).+A `.draw` 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 the document menu at the bottom of the tool strip to hand it to you. To start one yourself: `klad new art.draw --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.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 build`; the binary is `target/release/klad` on macOS and `target/linux/release/klad` on Linux.diff --git a/justfile b/justfileindex 1e39b9b..d7f7cdf 100644--- a/justfile+++ b/justfile@@ -21,6 +21,15 @@ lint:samples: buildfor s in lantern ink-shapes bounce creature courier solids lemons ruin sign tree meadow; do FORCE=1 bash samples/$s/build.sh >/dev/null && echo "samples/$s/$s.draw"; done+app:+ bash packaging/macos/app.sh++dist target=`rustc -vV | sed -n 's/^host: //p'`:+ bash packaging/archive.sh {{target}}++icon: build+ KLAD={{klad}} bash packaging/icon/build.sh+notices:bash licenses/notices.shdiff --git a/packaging/archive.sh b/packaging/archive.shnew file mode 100755index 0000000..6563f7e--- /dev/null+++ b/packaging/archive.sh@@ -0,0 +1,47 @@+#!/usr/bin/env bash+set -euo pipefail+root="$(cd "$(dirname "$0")/.." && pwd)"+target="${1:?give a target triple, for example x86_64-unknown-linux-gnu}"+out="${2:-$root/dist}"+version="$(sed -n 's/^version = "\(.*\)"/\1/p' "$root/Cargo.toml" | head -1)"+export KLAD_BUILD="${KLAD_BUILD:-$(git -C "$root" describe --tags --always 2>/dev/null || echo "$version")}"+cargo build --profile dist -p klad-cli --target "$target" --manifest-path "$root/Cargo.toml"+built="${CARGO_TARGET_DIR:-$root/target}/$target/dist"+case "$target" in+ *windows*) platform=windows; ext=.exe ;;+ *apple*) platform=macos; ext= ;;+ *) platform=linux; ext= ;;+esac+arch="${target%%-*}"+name="klad-$version-$platform-$arch"+stage="$out/$name"+rm -rf "$stage"+mkdir -p "$stage"+cp "$built/klad$ext" "$stage/"+[ -f "$built/klad-editor$ext" ] && cp "$built/klad-editor$ext" "$stage/"+mkdir -p "$stage/fonts"+(cd "$root/fonts" && tar cf - --exclude update.py .) | (cd "$stage/fonts" && tar xf -)+cp "$root/LICENSE" "$root/THIRD-PARTY-NOTICES.md" "$root/docs/skill/SKILL.md" "$stage/"+cp "$root/packaging/icon/icon.png" "$stage/klad.png"+case "$platform" in+ windows)+ (cd "$out" && rm -f "$name.zip" && (command -v 7z >/dev/null && 7z a -tzip "$name.zip" "$name" >/dev/null || powershell -NoProfile -Command "Compress-Archive -Path '$name' -DestinationPath '$name.zip'"))+ echo "$out/$name.zip"+ ;;+ *)+ (cd "$out" && tar czf "$name.tar.gz" "$name")+ echo "$out/$name.tar.gz"+ ;;+esac+if [ "$platform" = linux ] && [ -n "${APPIMAGETOOL:-}" ]; then+ app="$out/$name.AppDir"+ rm -rf "$app"+ mkdir -p "$app/usr/bin" "$app/usr/share/klad"+ cp "$stage/klad" "$stage/klad-editor" "$app/usr/bin/"+ cp -R "$stage/fonts" "$app/usr/share/klad/"+ cp "$root/packaging/linux/AppRun" "$app/AppRun"+ cp "$root/packaging/linux/klad.desktop" "$app/klad.desktop"+ cp "$root/packaging/icon/icon.png" "$app/klad.png"+ ARCH="$arch" "$APPIMAGETOOL" "$app" "$out/klad-$version-$arch.AppImage" >/dev/null+ echo "$out/klad-$version-$arch.AppImage"+fidiff --git a/packaging/icon/build.sh b/packaging/icon/build.shnew file mode 100755index 0000000..91bb55d--- /dev/null+++ b/packaging/icon/build.sh@@ -0,0 +1,14 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+klad="${KLAD:?set KLAD to the klad binary, or run just icon}"+work="$(mktemp -d)"+trap 'rm -rf "$work"' EXIT+"$klad" new "$work/icon.draw" --width 1024 --height 1024 --layers 0 >/dev/null+python3 "$here/generate.py" | "$klad" apply "$work/icon.draw" >/dev/null+"$klad" render "$work/icon.draw" --out "$here/icon.png" >/dev/null+for size in 16 24 32 48 64 128 256 512 1024; do+ "$klad" render "$work/icon.draw" --scale "$(python3 -c "print($size/1024)")" --out "$work/icon-$size.png" >/dev/null+done+python3 "$here/pack.py" "$work" "$here/klad.icns" "$here/klad.ico"+echo "$here/icon.png $here/klad.icns $here/klad.ico"diff --git a/packaging/icon/generate.py b/packaging/icon/generate.pynew file mode 100644index 0000000..b6f91f0--- /dev/null+++ b/packaging/icon/generate.py@@ -0,0 +1,32 @@+import json++INK = "#1d2230"+EMBER = "#d4612c"+++def layer(id, kind, **extra):+ return {"op": "add", "layer": {"id": id, "kind": kind, "name": id, **extra}}+++def stroke(path, size, colour, pressure, brush="oil-load"):+ return {"op": "stroke", "layer": "paint", "brush": brush, "size": size, "color": colour, "path": path,+ "pressure": pressure}+++def ops():+ paper = {"linear": {"from": [0, 100], "to": [0, 924], "stops": [[0, "#f8f1e4"], [1, "#e6d6bd"]]}}+ return [+ layer("plate", "vector"),+ {"op": "add", "node": {"type": "rect", "x": 100, "y": 100, "w": 824, "h": 824, "radius": 186, "fill": paper},+ "in": "plate"},+ {"op": "set", "id": "plate", "effects": [{"shadow": {"x": 0, "y": 14, "radius": 22, "color": "#00000044"}}]},+ layer("paint", "paint", clip=True),+ stroke("M396 226 C 390 420 402 600 388 806", 128, INK, [0.75, 1, 1, 0.95, 0.7], brush="oil"),+ stroke("M440 540 C 530 456 620 366 748 250", 108, INK, [1, 0.95, 0.75, 0.45], brush="oil"),+ stroke("M452 498 C 560 594 650 690 760 808", 118, EMBER, [1, 1, 0.9, 0.7, 0.4], brush="oil"),+ {"op": "set", "id": "paint", "effects": [{"relief": {"light": [-0.6, -0.8], "strength": 1.6, "softness": 2.2}}]},+ ]+++if __name__ == "__main__":+ print("\n".join(json.dumps(op) for op in ops()))diff --git a/packaging/icon/icon.png b/packaging/icon/icon.pngnew file mode 100644index 0000000..ea5959aBinary files /dev/null and b/packaging/icon/icon.png differdiff --git a/packaging/icon/klad.icns b/packaging/icon/klad.icnsnew file mode 100644index 0000000..90edc29Binary files /dev/null and b/packaging/icon/klad.icns differdiff --git a/packaging/icon/klad.ico b/packaging/icon/klad.iconew file mode 100644index 0000000..d9ad49fBinary files /dev/null and b/packaging/icon/klad.ico differdiff --git a/packaging/icon/pack.py b/packaging/icon/pack.pynew file mode 100644index 0000000..cf73f1d--- /dev/null+++ b/packaging/icon/pack.py@@ -0,0 +1,32 @@+import struct+import sys+from pathlib import Path++ICNS = [("icp4", 16), ("icp5", 32), ("ic07", 128), ("ic08", 256), ("ic09", 512), ("ic10", 1024), ("ic11", 32),+ ("ic12", 64), ("ic13", 256), ("ic14", 512)]+ICO = [16, 24, 32, 48, 64, 128, 256]+++def icns(pngs, out):+ chunks = b"".join(kind.encode() + struct.pack(">I", 8 + len(pngs[size])) + pngs[size] for kind, size in ICNS)+ out.write_bytes(b"icns" + struct.pack(">I", 8 + len(chunks)) + chunks)+++def ico(pngs, out):+ head = struct.pack("<HHH", 0, 1, len(ICO))+ offset = 6 + 16 * len(ICO)+ entries, data = b"", b""+ for size in ICO:+ png = pngs[size]+ side = 0 if size >= 256 else size+ entries += struct.pack("<BBBBHHII", side, side, 0, 0, 1, 32, len(png), offset + len(data))+ data += png+ out.write_bytes(head + entries + data)+++if __name__ == "__main__":+ folder = Path(sys.argv[1])+ sizes = {s for _, s in ICNS} | set(ICO)+ pngs = {s: (folder / f"icon-{s}.png").read_bytes() for s in sizes}+ icns(pngs, Path(sys.argv[2]))+ ico(pngs, Path(sys.argv[3]))diff --git a/packaging/linux/AppRun b/packaging/linux/AppRunnew file mode 100755index 0000000..54bd3d5--- /dev/null+++ b/packaging/linux/AppRun@@ -0,0 +1,11 @@+#!/bin/sh+here="$(dirname "$(readlink -f "$0")")"+export KLAD_FONTS="$here/usr/share/klad/fonts"+case "$(basename "${ARGV0:-$0}")" in+ klad) exec "$here/usr/bin/klad" "$@" ;;+esac+if [ "$1" = "klad" ]; then+ shift+ exec "$here/usr/bin/klad" "$@"+fi+exec "$here/usr/bin/klad-editor" "$@"diff --git a/packaging/linux/klad.desktop b/packaging/linux/klad.desktopnew file mode 100644index 0000000..e8667c0--- /dev/null+++ b/packaging/linux/klad.desktop@@ -0,0 +1,9 @@+[Desktop Entry]+Type=Application+Name=klad+Comment=Draw and paint, by hand and with an agent+Exec=klad-editor %f+Icon=klad+Categories=Graphics;2DGraphics;RasterGraphics;+MimeType=application/x-klad-drawing;+Terminal=falsediff --git a/packaging/macos/Info.plist b/packaging/macos/Info.plistnew file mode 100644index 0000000..ade9f6b--- /dev/null+++ b/packaging/macos/Info.plist@@ -0,0 +1,72 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleName</key>+ <string>klad</string>+ <key>CFBundleDisplayName</key>+ <string>klad</string>+ <key>CFBundleIdentifier</key>+ <string>com.indicode.klad</string>+ <key>CFBundleExecutable</key>+ <string>klad-editor</string>+ <key>CFBundleIconFile</key>+ <string>klad.icns</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>@VERSION@</string>+ <key>CFBundleVersion</key>+ <string>@BUILD@</string>+ <key>LSMinimumSystemVersion</key>+ <string>12.0</string>+ <key>LSApplicationCategoryType</key>+ <string>public.app-category.graphics-design</string>+ <key>NSHighResolutionCapable</key>+ <true/>+ <key>NSHumanReadableCopyright</key>+ <string>Copyright Indicode BV</string>+ <key>CFBundleDocumentTypes</key>+ <array>+ <dict>+ <key>CFBundleTypeName</key>+ <string>klad drawing</string>+ <key>CFBundleTypeRole</key>+ <string>Editor</string>+ <key>LSHandlerRank</key>+ <string>Owner</string>+ <key>LSTypeIsPackage</key>+ <true/>+ <key>CFBundleTypeIconFile</key>+ <string>klad.icns</string>+ <key>LSItemContentTypes</key>+ <array>+ <string>com.indicode.klad.drawing</string>+ </array>+ </dict>+ </array>+ <key>UTExportedTypeDeclarations</key>+ <array>+ <dict>+ <key>UTTypeIdentifier</key>+ <string>com.indicode.klad.drawing</string>+ <key>UTTypeDescription</key>+ <string>klad drawing</string>+ <key>UTTypeIconFile</key>+ <string>klad.icns</string>+ <key>UTTypeConformsTo</key>+ <array>+ <string>com.apple.package</string>+ <string>public.composite-content</string>+ </array>+ <key>UTTypeTagSpecification</key>+ <dict>+ <key>public.filename-extension</key>+ <array>+ <string>draw</string>+ </array>+ </dict>+ </dict>+ </array>+</dict>+</plist>diff --git a/packaging/macos/app.sh b/packaging/macos/app.shnew file mode 100755index 0000000..97d2f04--- /dev/null+++ b/packaging/macos/app.sh@@ -0,0 +1,44 @@+#!/usr/bin/env bash+set -euo pipefail+root="$(cd "$(dirname "$0")/../.." && pwd)"+out="${1:-$root/dist}"+targets="${KLAD_MAC_TARGETS:-aarch64-apple-darwin}"+version="$(sed -n 's/^version = "\(.*\)"/\1/p' "$root/Cargo.toml" | head -1)"+build="$(git -C "$root" describe --tags --always 2>/dev/null || echo "$version")"+export KLAD_BUILD="$build"+binaries=()+for target in $targets; do+ rustup target add "$target" >/dev/null 2>&1 || true+ cargo build --profile dist -p klad-cli --target "$target" --manifest-path "$root/Cargo.toml"+ binaries+=("${CARGO_TARGET_DIR:-$root/target}/$target/dist")+done+app="$out/klad.app"+rm -rf "$app"+mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources"+for exe in klad klad-editor; do+ inputs=()+ for dir in "${binaries[@]}"; do inputs+=("$dir/$exe"); done+ if [ "${#inputs[@]}" -gt 1 ]; then+ lipo -create "${inputs[@]}" -output "$app/Contents/MacOS/$exe"+ else+ cp "${inputs[0]}" "$app/Contents/MacOS/$exe"+ fi+done+sed -e "s/@VERSION@/$version/" -e "s/@BUILD@/$build/" "$root/packaging/macos/Info.plist" > "$app/Contents/Info.plist"+cp "$root/packaging/icon/klad.icns" "$app/Contents/Resources/"+rsync -a --exclude update.py "$root/fonts/" "$app/Contents/Resources/fonts/"+cp "$root/LICENSE" "$root/THIRD-PARTY-NOTICES.md" "$app/Contents/Resources/"+mkdir -p "$app/Contents/Resources/skill"+cp "$root/docs/skill/SKILL.md" "$app/Contents/Resources/skill/"+codesign --force --deep --sign - "$app" 2>/dev/null || true+echo "$app"+if [ "${KLAD_DMG:-1}" = "1" ]; then+ stage="$(mktemp -d)"+ cp -R "$app" "$stage/"+ ln -s /Applications "$stage/Applications"+ dmg="$out/klad-$version-macos.dmg"+ rm -f "$dmg"+ hdiutil create -volname "klad $version" -srcfolder "$stage" -ov -format UDZO "$dmg" >/dev/null+ rm -rf "$stage"+ echo "$dmg"+fi