diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 64700704b8..f42a24e9b1 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -585,7 +585,28 @@ fn thumbnail(args: &[String]) -> Result<(), String> { .filter(|img| img.pixels.as_chunks::<4>().0.iter().any(|px| px[3] != 0)) .ok_or_else(|| format!("{input}: the document shows nothing"))?; let png = img.to_png().map_err(|e| format!("{input}: {e}"))?; - vectorcraft_format::write_atomic(Path::new(output), &png).map_err(|e| format!("{output}: {e}")) + write_whole(Path::new(output), &png, |tmp, out| std::fs::rename(tmp, out)).map_err(|e| format!("{output}: {e}")) +} + +/// Writes `bytes` to a temporary file beside `out` and moves it over `out` with `rename`. When the +/// temporary file can't be written or `rename` fails, this returns the error, removes the temporary +/// file and leaves `out` unchanged; it never copies into `out`. +fn write_whole(out: &Path, bytes: &[u8], rename: impl FnOnce(&Path, &Path) -> std::io::Result<()>) -> std::io::Result<()> { + let name = out.file_name().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a file name"))?; + let mut tmp_name = std::ffi::OsString::from("."); + tmp_name.push(name); + tmp_name.push(format!(".{}.tmp", std::process::id())); + let tmp = out.with_file_name(tmp_name); + // A file already at `tmp` is not this run's: the error leaves it in place. + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?; + let written = f.write_all(bytes).and_then(|()| vectorcraft_format::sync_file(&f)); + drop(f); + let written = written.and_then(|()| rename(&tmp, out)); + if written.is_err() { + // Best effort: the temporary file is all there is to clean up. + let _ = std::fs::remove_file(&tmp); + } + written } enum Step { @@ -837,3 +858,41 @@ fn bench(args: &[String]) -> Result<(), String> { } Ok(()) } + +#[cfg(test)] +mod write_whole_tests { + use super::write_whole; + + #[test] + fn a_failed_rename_leaves_out_unchanged_and_no_temporary_file() { + let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}")); + let out = dir.path().join("out.png"); + std::fs::write(&out, b"old").unwrap_or_else(|e| panic!("{e}")); + let refused = write_whole(&out, b"new picture", |_, _| Err(std::io::Error::other("refused"))); + assert!(refused.is_err()); + assert_eq!(std::fs::read(&out).unwrap_or_else(|e| panic!("{e}")), b"old"); + let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap_or_else(|e| panic!("{e}")).flatten().map(|e| e.file_name()).collect(); + assert_eq!(names, ["out.png"]); + } + + #[test] + fn a_file_already_at_the_temporary_name_is_kept() { + let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}")); + let out = dir.path().join("out.png"); + let tmp = dir.path().join(format!(".out.png.{}.tmp", std::process::id())); + std::fs::write(&tmp, b"someone else's").unwrap_or_else(|e| panic!("{e}")); + assert!(write_whole(&out, b"new picture", |tmp, out| std::fs::rename(tmp, out)).is_err()); + assert_eq!(std::fs::read(&tmp).unwrap_or_else(|e| panic!("{e}")), b"someone else's"); + assert!(!out.exists()); + } + + #[test] + fn a_rename_replaces_out() { + let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}")); + let out = dir.path().join("out.png"); + std::fs::write(&out, b"old").unwrap_or_else(|e| panic!("{e}")); + write_whole(&out, b"new picture", |tmp, out| std::fs::rename(tmp, out)).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(std::fs::read(&out).unwrap_or_else(|e| panic!("{e}")), b"new picture"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap_or_else(|e| panic!("{e}")).count(), 1); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9bbdc5294d..e6e3d1d66c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1007,7 +1007,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Linux RPM packaging:** 64-bit runtime capabilities replace Fedora-specific required package names (#1275); glibc 2.35, libm and libgcc_s are declared alongside dynamically loaded xkbcommon and Vulkan/EGL. Generated x86_64/aarch64 metadata and isolated synthetic-provider resolution checked; real-distro install/start-up QA remains pending. - **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, HP-GL, `.cdr` and `.cmx`, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. - **Linux file manager thumbnails:** the deb, rpm and tar.gz packages install `share/thumbnailers/ai.storyteller.vectorcraft.thumbnailer`, a [thumbnailer entry](https://gitlab.gnome.org/GNOME/gnome-desktop/-/raw/master/libgnome-desktop/gnome-desktop-thumbnail.c) for VectorCraft documents and templates, so file managers that read these entries show a thumbnail of the first artboard. The entry runs `vectorcraft-cli thumbnail --size N IN OUT`, which opens the document as the app does and writes an 8-bit RGBA PNG of the first artboard, N pixels (at most 1024) on its longer side, as the [thumbnail standard](https://specifications.freedesktop.org/thumbnail-spec/latest/creation.html) asks. A file larger than 256 MiB, one that can't be opened, a document that shows nothing, or a run longer than 20 seconds gets no PNG and a non-zero exit status, and the file manager keeps the file's icon. The Nightly deb and rpm leave the entry out, as they leave out the MIME package; a Flatpak install doesn't provide it. Tests in `apps/vectorcraft-cli/tests/it/thumbnail.rs` cover all of it except the 20-second limit. -- **Windows Explorer thumbnails:** `apps/vectorcraft-thumbnail-handler` builds `vectorcraft_thumbnail_handler.dll`, a [thumbnail handler](https://learn.microsoft.com/windows/win32/shell/thumbnail-providers) (`IThumbnailProvider` with `IInitializeWithStream`) for `.vectorcraft`, `.drawcraft` and `.vctemplate` files. Explorer passes it the file's bytes; it writes them to a file in `%USERPROFILE%\AppData\LocalLow\VectorCraft\Thumbnails` (falling back to the temp folder), runs `vectorcraft-cli thumbnail --size N` from its own folder on that file, and returns the PNG as a top-down 32-bit bitmap with premultiplied alpha, at most 1024 pixels on its longer side. A file larger than 256 MiB, a failed `vectorcraft-cli` run, or a run longer than 25 seconds gives Explorer an error, and Explorer shows the file's icon. Explorer gives the handler the file's bytes and not its path, so a linked image that is found only relative to the document's folder shows the preview saved with it. `regsvr32 vectorcraft_thumbnail_handler.dll` registers it for the current user (`HKCU\Software\Classes`: the class, its `InprocServer32` with `ThreadingModel` `Apartment`, and `ShellEx\{e357fccd-a995-4576-b01f-234630154e96}` under each extension), and `regsvr32 /u` removes the class and each extension's key that names it. The Windows packages don't build, ship or register the DLL yet, and a portable install has nothing that registers it. Tests in `apps/vectorcraft-thumbnail-handler/src/tests.rs` cover the registration values, the PNG conversion and the `vectorcraft-cli` run. +- **Windows Explorer thumbnails:** `apps/vectorcraft-thumbnail-handler` builds `vectorcraft_thumbnail_handler.dll`, a [thumbnail handler](https://learn.microsoft.com/windows/win32/shell/thumbnail-providers) (`IThumbnailProvider` with `IInitializeWithStream`) for `.vectorcraft`, `.drawcraft` and `.vctemplate` files. Explorer passes it the file's bytes; it writes them to a file in `%USERPROFILE%\AppData\LocalLow\VectorCraft\Thumbnails` (falling back to the temp folder), runs `vectorcraft-cli thumbnail --size N` from its own folder on that file, and returns the PNG as a top-down 32-bit bitmap with premultiplied alpha, at most 1024 pixels on its longer side. A file larger than 256 MiB, a failed `vectorcraft-cli` run, or a run longer than 25 seconds gives Explorer an error, and Explorer shows the file's icon. Explorer gives the handler the file's bytes and not its path, so a linked image that is found only relative to the document's folder shows the preview saved with it. `regsvr32 vectorcraft_thumbnail_handler.dll` registers it for the current user (`HKCU\Software\Classes`: the class, its `InprocServer32` with `ThreadingModel` `Apartment`, and `ShellEx\{e357fccd-a995-4576-b01f-234630154e96}` under each extension), and `regsvr32 /u vectorcraft_thumbnail_handler.dll` removes the class and each extension's key that names it. The Windows packages don't build, ship or register the DLL yet, and a portable install has nothing that registers it. Tests in `apps/vectorcraft-thumbnail-handler/src/tests.rs` cover the registration values, the PNG conversion and the `vectorcraft-cli` run. - **Architecture:** 19+ crates with enforced layering (`cargo xtask layers`). Every action is a command (~400 engine + ~50 UI). Undo is unlimited via structural sharing. `command.batch` runs several commands as one transaction. - **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document (a value nested past the schema's 16 levels is such a parameter error, and only a schema that is wrong in itself is an internal error); saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`.