Merge pull request #9909 from dotCooCoo/feat/windows-thumbnail-handler

Windows: Explorer shows thumbnails of VectorCraft documents
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-28 08:03:20 -08:00
commit 8cdd897b23
14 files changed
+1127 -6

No files matched your search

Generated
+9
View File
@@ -9091,6 +9091,15 @@ dependencies = [
"vectorcraft-pathops 0.24.1",
]
[[package]]
name = "vectorcraft-thumbnail-handler"
version = "0.24.1"
dependencies = [
"png 0.18.1",
"windows",
"windows-core",
]
[[package]]
name = "vectorcraft-tools"
version = "0.24.1"
+126
View File
@@ -7,6 +7,7 @@
//! vectorcraft-cli commands
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli info FILE
//! vectorcraft-cli thumbnail [--size 256] IN OUT
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
//! vectorcraft-cli perf [--paths 50000] [--deep]
//! ```
@@ -145,6 +146,15 @@ USAGE:
read from its preview and why), title, colour mode, units, artboards, object counts by
kind, fonts.
vectorcraft-cli thumbnail [--size N] IN OUT
Open IN (any readable format) and write OUT as a PNG of its first artboard (else the art),
N pixels on its longer side (1 to 1024, default 256), with a transparent background. Linux
file managers run it for .vectorcraft, .drawcraft and .vctemplate files through
share/thumbnailers/ai.storyteller.vectorcraft.thumbnailer, and the Windows thumbnail
handler (vectorcraft_thumbnail_handler.dll) runs it for Explorer. It exits with an error
and writes nothing when IN is larger than 256 MiB, can't be opened, shows nothing, or takes
longer than 20 seconds.
vectorcraft-cli bench FILE [--size WxH] [--iters N]
Render FILE (any readable format) fitted to WxH (default 2880x1800) and print ms per frame
(warm), multithreaded and single-threaded.
@@ -217,6 +227,7 @@ fn main() -> ExitCode {
Some("commands") => commands(),
Some("convert") => convert(&args[1..]),
Some("info") => info(&args[1..]),
Some("thumbnail") => thumbnail(&args[1..]),
Some("bench") => bench(&args[1..]),
Some("perf") => perf::run(&args[1..]),
Some("-h" | "--help" | "help") | None => help(),
@@ -521,6 +532,83 @@ fn info(args: &[String]) -> Result<(), String> {
Ok(())
}
/// Largest file `thumbnail` opens, in bytes on disk.
const THUMBNAIL_MAX_FILE: u64 = 256 << 20;
/// Largest `--size` of `thumbnail`: the thumbnail standard's largest size, xx-large.
const THUMBNAIL_MAX_SIZE: u32 = 1024;
/// `--size` when it isn't given: the thumbnail standard's large size.
const THUMBNAIL_DEFAULT_SIZE: u32 = 256;
/// Longest `thumbnail` runs before it exits without writing OUT.
const THUMBNAIL_TIME: std::time::Duration = std::time::Duration::from_secs(20);
/// `thumbnail`: the PNG a Linux file manager shows for a document, run through the
/// `.thumbnailer` entry in `packaging/linux`
/// (<https://specifications.freedesktop.org/thumbnail-spec/latest/creation.html>), and the
/// picture the Windows thumbnail handler (`apps/vectorcraft-thumbnail-handler`) gives Explorer.
fn thumbnail(args: &[String]) -> Result<(), String> {
if help_requested(args, &["--size", "-s"]) {
return help();
}
let mut files = vec![];
let mut size = THUMBNAIL_DEFAULT_SIZE;
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--size" | "-s" => {
size = it
.next()
.and_then(|v| v.parse().ok())
.filter(|n| (1..=THUMBNAIL_MAX_SIZE).contains(n))
.ok_or_else(|| format!("--size needs a number of pixels from 1 to {THUMBNAIL_MAX_SIZE}"))?;
}
other if other.starts_with('-') => return Err(format!("unknown thumbnail option `{other}`")),
f => files.push(f),
}
}
let [input, output] = <[&str; 2]>::try_from(files).map_err(|_| "thumbnail needs IN and OUT")?;
// The process ends when the time is up, wherever the work is: OUT is written whole or not at all.
std::thread::spawn(|| {
std::thread::sleep(THUMBNAIL_TIME);
eprintln!("vectorcraft-cli: thumbnail: took longer than {} seconds", THUMBNAIL_TIME.as_secs());
std::process::exit(1);
});
let len = std::fs::metadata(input).map_err(|e| format!("{input}: {e}"))?.len();
if len > THUMBNAIL_MAX_FILE {
return Err(format!("{input}: larger than {} MiB", THUMBNAIL_MAX_FILE >> 20));
}
// Opened as the app opens it: the fonts it carries, its type measured, its linked files read.
let mut h = Headless::new();
h.call("app.open", json!({"path": input})).map_err(|e| format!("{input}: {e}"))?;
let doc = &h.session.doc().map_err(|e| e.to_string())?.doc;
// A picture without a visible pixel is an error, and the file manager keeps the file's icon.
let img = vectorcraft_render::encode::first_artboard(doc, size)
.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}"))?;
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 {
Cmd(String, Value),
Export(String),
@@ -770,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);
}
}
+1
View File
@@ -6,6 +6,7 @@ mod cli;
mod fileio;
mod mcp_e2e;
mod script;
mod thumbnail;
/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner.
fn bin() -> std::path::PathBuf {
+162
View File
@@ -0,0 +1,162 @@
//! `thumbnail` and the Linux `.thumbnailer` entry that runs it for file managers.
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
const THUMBNAILER: &str = include_str!("../../../../packaging/linux/ai.storyteller.vectorcraft.thumbnailer");
const MIME: &str = include_str!("../../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml");
const PACKAGE: &str = include_str!("../../../../packaging/linux/package.sh");
/// Returns a new empty folder in the temp folder, removed with everything in it when the guard drops.
fn tmp() -> tempfile::TempDir {
tempfile::tempdir().unwrap()
}
fn cli(args: &[&str]) -> Output {
Command::new(crate::bin()).args(args).output().unwrap()
}
/// Saves a `width`×`height` document with a rectangle on its artboard as `name` in `dir` and returns its path.
fn document(dir: &Path, name: &str, width: u32, height: u32) -> PathBuf {
save(dir, name, width, height, &["--cmd", "shape.rectangle", "--params", r#"{"x":10,"y":10,"width":40,"height":20}"#])
}
/// Saves a new `width`×`height` document as `name` in `dir` after the `run` arguments `steps`.
fn save(dir: &Path, name: &str, width: u32, height: u32, steps: &[&str]) -> PathBuf {
let path = dir.join(name);
let size = format!(r#"{{"width":{width},"height":{height}}}"#);
let mut args = vec!["run", "--cmd", "file.new", "--params", &size];
args.extend_from_slice(steps);
args.extend(["--export", path.to_str().unwrap()]);
let out = cli(&args);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
path
}
/// The width and height in a PNG's IHDR chunk, after checking that it is the 8-bit, non-interlaced
/// RGBA a thumbnail must be (<https://specifications.freedesktop.org/thumbnail-spec/latest/creation.html>).
fn png_size(png: &[u8]) -> (u32, u32) {
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n") && &png[12..16] == b"IHDR", "not a PNG");
assert_eq!((png[24], png[25], png[28]), (8, 6, 0), "bit depth, color type (RGBA) and interlacing");
let be = |b: &[u8]| u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
(be(&png[16..20]), be(&png[20..24]))
}
/// The value of `key` in the entry's `[Thumbnailer Entry]` group.
fn entry(key: &str) -> &'static str {
assert_eq!(THUMBNAILER.lines().next(), Some("[Thumbnailer Entry]"));
THUMBNAILER.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).unwrap_or_else(|| panic!("no {key} key"))
}
/// The file manager's command for the entry: `Exec` split at spaces, `%s` the size, `%i` the
/// input path and `%o` the output path (the codes the thumbnail factories expand).
fn exec(size: u32, input: &Path, output: &Path) -> Vec<String> {
entry("Exec")
.split(' ')
.map(|arg| match arg {
"%s" => size.to_string(),
"%i" => input.to_string_lossy().into_owned(),
"%o" => output.to_string_lossy().into_owned(),
other => {
assert!(!other.contains('%'), "a field code the CLI doesn't take: {other}");
other.to_string()
}
})
.collect()
}
/// The entry runs the CLI with the size, the document and the PNG to write, as a file manager
/// does: with no environment, and the PNG is the first artboard at that size, drawn by the
/// renderer that embeds a native file's preview.
#[test]
fn the_thumbnailer_entry_writes_the_first_artboard() {
let dir = tmp();
let doc = document(dir.path(), "wide.vectorcraft", 200, 100);
let out = dir.path().join("wide.png");
let command = exec(128, &doc, &out);
assert_eq!(command[0], entry("TryExec"));
assert_eq!(command[0], "vectorcraft-cli");
let run = Command::new(crate::bin()).args(&command[1..]).env_clear().output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let png = std::fs::read(&out).unwrap();
assert_eq!(png_size(&png), (128, 64));
let saved = vectorcraft_format::load(&std::fs::read(&doc).unwrap()).unwrap();
assert_eq!(Some(png), vectorcraft_render::encode::first_artboard_png(&saved, 128).unwrap(), "the renderer's picture");
}
/// Each type the entry lists is a native document type the app's MIME package declares, and the
/// packages install the entry where the thumbnail factories look.
#[test]
fn the_thumbnailer_entry_covers_the_native_types() {
let types: Vec<&str> = entry("MimeType").split(';').filter(|t| !t.is_empty()).collect();
assert_eq!(types, ["application/x-vectorcraft", "application/x-vectorcraft-template"]);
for t in types {
assert!(MIME.contains(&format!("<mime-type type=\"{t}\">")), "the MIME package doesn't declare {t}");
}
assert!(
PACKAGE.contains(r#"install -Dm644 "$HERE/$APP_ID.thumbnailer" "$STAGE/usr/share/thumbnailers/$APP_ID.thumbnailer""#),
"package.sh doesn't install the entry"
);
}
/// The size defaults to 256 pixels on the longer side, and a tall artboard is fitted by its height.
#[test]
fn thumbnail_fits_the_longer_side() {
let dir = tmp();
let doc = document(dir.path(), "tall.vectorcraft", 100, 400);
let out = dir.path().join("tall.png");
let run = cli(&["thumbnail", doc.to_str().unwrap(), out.to_str().unwrap()]);
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert_eq!(png_size(&std::fs::read(&out).unwrap()), (64, 256));
}
/// A size outside 1 to 1024 pixels, a missing file name and an unknown option are errors, and no
/// PNG is written.
#[test]
fn thumbnail_refuses_bad_arguments() {
let dir = tmp();
let doc = document(dir.path(), "args.vectorcraft", 100, 100);
let out = dir.path().join("args.png");
let (d, o) = (doc.to_str().unwrap(), out.to_str().unwrap());
for (args, says) in [
(vec!["thumbnail", "--size", "0", d, o], "--size"),
(vec!["thumbnail", "--size", "1025", d, o], "--size"),
(vec!["thumbnail", "--size", "big", d, o], "--size"),
(vec!["thumbnail", "--size"], "--size"),
(vec!["thumbnail", d], "IN and OUT"),
(vec!["thumbnail", "--quality", "9", d, o], "--quality"),
] {
let run = cli(&args);
assert!(!run.status.success(), "{args:?}");
assert!(String::from_utf8_lossy(&run.stderr).contains(says), "{args:?}: {}", String::from_utf8_lossy(&run.stderr));
assert!(!out.exists(), "{args:?} wrote a PNG");
}
}
/// A file that isn't a document, a damaged one, one larger than the CLI opens, a missing one and
/// an empty document get an error and no PNG, so the file manager shows the file's icon.
#[test]
fn thumbnail_writes_nothing_for_files_it_cannot_read() {
let dir = tmp();
let text = dir.path().join("notes.vectorcraft");
std::fs::write(&text, b"not a document").unwrap();
let saved = std::fs::read(document(dir.path(), "whole.vectorcraft", 100, 100)).unwrap();
let damaged = dir.path().join("damaged.vectorcraft");
std::fs::write(&damaged, &saved[..saved.len() / 2]).unwrap();
// Sparse where the file system allows it: its size is checked before anything is read.
let large = dir.path().join("large.vectorcraft");
std::fs::File::create(&large).unwrap().set_len((256 << 20) + 1).unwrap();
let missing = dir.path().join("missing.vectorcraft");
let empty = save(dir.path(), "empty.vectorcraft", 100, 100, &[]);
for (input, says) in
[(&text, None), (&damaged, None), (&large, Some("larger than 256 MiB")), (&missing, None), (&empty, Some("the document shows nothing"))]
{
let out = dir.path().join("unreadable.png");
let run = cli(&["thumbnail", input.to_str().unwrap(), out.to_str().unwrap()]);
assert!(!run.status.success(), "{input:?}");
let err = String::from_utf8_lossy(&run.stderr);
assert!(err.contains(input.to_str().unwrap()), "{input:?}: {err}");
assert!(says.is_none_or(|s| err.contains(s)), "{input:?}: {err}");
assert!(!out.exists(), "{input:?} wrote a PNG");
}
}
@@ -0,0 +1,33 @@
[package]
name = "vectorcraft-thumbnail-handler"
description = "Windows Explorer thumbnail handler for VectorCraft documents and templates"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[lints]
workspace = true
# A COM server DLL that Explorer loads; on other systems it builds the parts the tests check.
[lib]
crate-type = ["cdylib"]
# PNG decoding of the picture `vectorcraft-cli thumbnail` writes. MIT OR Apache-2.0.
[dependencies]
png = "0.18"
# IThumbnailProvider, IInitializeWithStream, the class factory, DIB sections and the registry.
# MIT OR Apache-2.0.
[target.'cfg(windows)'.dependencies]
windows = { version = "0.62", features = [
"Win32_Foundation",
"Win32_Graphics_Gdi",
"Win32_System_Com",
"Win32_System_LibraryLoader",
"Win32_System_Registry",
"Win32_System_SystemServices",
"Win32_UI_Shell",
"Win32_UI_Shell_PropertiesSystem",
] }
windows-core = "0.62"
@@ -0,0 +1,345 @@
//! The COM server: the thumbnail provider, its class factory and the functions the DLL exports
//! (`DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer` and `DllUnregisterServer`).
//!
//! COM, GDI and the registry are C APIs with no safe binding, hence the scoped `unsafe_code`
//! allowance.
#![allow(unsafe_code)]
use std::ffi::c_void;
use std::io::{self, Read};
use std::os::windows::ffi::OsStringExt;
use std::panic::AssertUnwindSafe;
use std::path::PathBuf;
use std::ptr::null_mut;
use std::sync::Mutex;
use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
use windows::Win32::Foundation::{
CLASS_E_CLASSNOTAVAILABLE, CLASS_E_NOAGGREGATION, E_FAIL, E_POINTER, ERROR_ALREADY_INITIALIZED, ERROR_FILE_NOT_FOUND, HINSTANCE, HMODULE,
S_FALSE, S_OK,
};
use windows::Win32::Graphics::Gdi::{BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDIBSection, DIB_RGB_COLORS, DeleteObject, HBITMAP};
use windows::Win32::System::Com::{CoTaskMemFree, IClassFactory, IClassFactory_Impl, IStream};
use windows::Win32::System::LibraryLoader::GetModuleFileNameW;
use windows::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RRF_RT_REG_SZ, RegDeleteTreeW, RegGetValueW, RegSetKeyValueW};
use windows::Win32::System::SystemServices::DLL_PROCESS_ATTACH;
use windows::Win32::UI::Shell::PropertiesSystem::{IInitializeWithStream, IInitializeWithStream_Impl};
use windows::Win32::UI::Shell::{
FOLDERID_LocalAppDataLow, IThumbnailProvider, IThumbnailProvider_Impl, KNOWN_FOLDER_FLAG, SHCNE_ASSOCCHANGED, SHCNF_IDLIST, SHChangeNotify,
SHGetKnownFolderPath, WTS_ALPHATYPE, WTSAT_ARGB,
};
use windows::core::{BOOL, Error, GUID, HRESULT, HSTRING, IUnknown, Interface, PCWSTR, Ref, Result, implement};
use crate::{CLI, CLSID_VALUE, DEADLINE, Document, MAX_FILE, Picture, RegistryValue};
/// The handler's class id ([`crate::CLSID`]).
const CLASS_ID: GUID = GUID::from_u128(CLSID_VALUE);
/// The registry key the values of [`crate::registry_values`] go under.
const CLASSES: &str = "Software\\Classes";
/// The longest DLL path read, in UTF-16 units (Windows' own limit).
const MAX_PATH: usize = 32_767;
/// The DLL's module handle, from `DllMain`.
static MODULE: AtomicPtr<c_void> = AtomicPtr::new(null_mut());
/// Providers and class factories alive plus `LockServer` locks held; the DLL can be unloaded at 0.
static LIVE: AtomicUsize = AtomicUsize::new(0);
/// The thumbnail provider: Explorer hands it the file's stream, then asks for the picture.
#[implement(IInitializeWithStream, IThumbnailProvider)]
struct Provider {
document: Mutex<Option<Document<StreamReader>>>,
}
impl Provider {
fn new() -> Self {
LIVE.fetch_add(1, Ordering::SeqCst);
Self { document: Mutex::new(None) }
}
}
impl Drop for Provider {
fn drop(&mut self) {
LIVE.fetch_sub(1, Ordering::SeqCst);
}
}
impl IInitializeWithStream_Impl for Provider_Impl {
fn Initialize(&self, stream: Ref<IStream>, _mode: u32) -> Result<()> {
let stream = stream.ok()?.clone();
let mut slot = self.document.lock().map_err(|_| Error::from(E_FAIL))?;
if slot.is_some() {
return Err(ERROR_ALREADY_INITIALIZED.to_hresult().into());
}
*slot = Some(Document::new(StreamReader(stream)));
Ok(())
}
}
impl IThumbnailProvider_Impl for Provider_Impl {
fn GetThumbnail(&self, cx: u32, bitmap: *mut HBITMAP, alpha: *mut WTS_ALPHATYPE) -> Result<()> {
if bitmap.is_null() || alpha.is_null() {
return Err(E_POINTER.into());
}
let mut slot = self.document.lock().map_err(|_| Error::from(E_FAIL))?;
let document = slot.as_mut().ok_or_else(|| Error::new(E_FAIL, "not initialized"))?;
// A panic must not unwind into Explorer's process.
let picture = match std::panic::catch_unwind(AssertUnwindSafe(|| thumbnail(document, cx))) {
Ok(Ok(picture)) => picture,
Ok(Err(e)) => return Err(Error::new(E_FAIL, e)),
Err(_) => return Err(Error::new(E_FAIL, "the thumbnail could not be made")),
};
drop(slot);
let made = dib_section(&picture)?;
// SAFETY: both pointers were checked for null above, and Explorer passes them writable.
unsafe {
*bitmap = made;
*alpha = WTSAT_ARGB;
}
Ok(())
}
}
/// The class factory COM asks for the provider.
#[implement(IClassFactory)]
struct Factory;
impl Factory {
fn new() -> Self {
LIVE.fetch_add(1, Ordering::SeqCst);
Self
}
}
impl Drop for Factory {
fn drop(&mut self) {
LIVE.fetch_sub(1, Ordering::SeqCst);
}
}
impl IClassFactory_Impl for Factory_Impl {
fn CreateInstance(&self, outer: Ref<IUnknown>, iid: *const GUID, object: *mut *mut c_void) -> Result<()> {
if iid.is_null() || object.is_null() {
return Err(E_POINTER.into());
}
// SAFETY: `object` was checked for null above.
unsafe { *object = null_mut() };
if !outer.is_null() {
return Err(CLASS_E_NOAGGREGATION.into());
}
let provider: IUnknown = Provider::new().into();
// SAFETY: both pointers were checked for null above.
unsafe { provider.query(iid, object) }.ok()
}
fn LockServer(&self, lock: BOOL) -> Result<()> {
if lock.as_bool() {
LIVE.fetch_add(1, Ordering::SeqCst);
} else {
LIVE.fetch_sub(1, Ordering::SeqCst);
}
Ok(())
}
}
/// `IStream` as [`Read`].
struct StreamReader(IStream);
impl Read for StreamReader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let len = u32::try_from(buf.len()).unwrap_or(u32::MAX);
let mut read = 0u32;
// SAFETY: `buf` holds at least `len` writable bytes, and `read` outlives the call.
unsafe { self.0.Read(buf.as_mut_ptr().cast(), len, Some(&mut read)) }.ok().map_err(io::Error::other)?;
usize::try_from(read).map_err(io::Error::other)
}
}
/// The picture of `document`, at most `cx` pixels on its longer side.
fn thumbnail(document: &mut Document<StreamReader>, cx: u32) -> std::result::Result<Picture, String> {
let size = crate::request_size(cx).ok_or("a thumbnail of 0 pixels")?;
let bytes = document.bytes(MAX_FILE).map_err(|e| e.to_string())?;
let dll = module_path()?;
let cli = PathBuf::from(dll).parent().ok_or("the DLL's folder is unknown")?.join(CLI);
let png = crate::render(&cli, bytes, size, &staging_folder(), DEADLINE)?;
crate::picture(&png, size)
}
/// Creates the thumbnail staging folder in LocalLow, falling back to the temp folder.
fn staging_folder() -> PathBuf {
// SAFETY: the folder ID is valid, and no token means the current user.
let Ok(folder) = (unsafe { SHGetKnownFolderPath(&FOLDERID_LocalAppDataLow, KNOWN_FOLDER_FLAG(0), None) }) else {
return std::env::temp_dir();
};
// SAFETY: the call returned a NUL-terminated path allocated by COM; copy it before freeing it.
let path = unsafe {
let path = PathBuf::from(std::ffi::OsString::from_wide(folder.as_wide()));
CoTaskMemFree(Some(folder.0.cast()));
path
};
let path = path.join("VectorCraft").join("Thumbnails");
if std::fs::create_dir_all(&path).is_ok() { path } else { std::env::temp_dir() }
}
/// `picture` as a top-down 32-bit DIB section.
fn dib_section(picture: &Picture) -> Result<HBITMAP> {
let bad = || Error::new(E_FAIL, "the picture's size is wrong");
let width = i32::try_from(picture.width).map_err(|_| bad())?;
let height = i32::try_from(picture.height).map_err(|_| bad())?;
let len = usize::try_from(u64::from(picture.width) * u64::from(picture.height) * 4).map_err(|_| bad())?;
if picture.bgra.len() != len {
return Err(bad());
}
let info = BITMAPINFO {
bmiHeader: BITMAPINFOHEADER {
biSize: size_of::<BITMAPINFOHEADER>() as u32,
biWidth: width,
// A negative height: the rows go from top to bottom.
biHeight: -height,
biPlanes: 1,
biBitCount: 32,
biCompression: BI_RGB.0,
..Default::default()
},
..Default::default()
};
let mut bits: *mut c_void = null_mut();
// SAFETY: `info` describes a 32-bit picture and `bits` outlives the call.
let bitmap = unsafe { CreateDIBSection(None, &info, DIB_RGB_COLORS, &mut bits, None, 0) }?;
if bits.is_null() {
// SAFETY: `bitmap` was just made and nothing else holds it.
unsafe {
let _ = DeleteObject(bitmap.into());
}
return Err(Error::new(E_FAIL, "the bitmap has no pixels"));
}
// SAFETY: the DIB section holds `width * height * 4` bytes, `len`, and `bgra` holds `len` bytes.
unsafe { std::ptr::copy_nonoverlapping(picture.bgra.as_ptr(), bits.cast::<u8>(), len) };
Ok(bitmap)
}
/// The path of this DLL.
fn module_path() -> std::result::Result<String, String> {
let module = HMODULE(MODULE.load(Ordering::SeqCst));
if module.0.is_null() {
return Err("the DLL's module handle is unknown".into());
}
let mut buf = vec![0u16; MAX_PATH];
// SAFETY: `module` is this DLL's handle, which stays valid while the DLL is loaded.
let len = unsafe { GetModuleFileNameW(Some(module), &mut buf) };
let path = usize::try_from(len).ok().filter(|&n| n > 0 && n < buf.len()).and_then(|n| buf.get(..n)).ok_or("the DLL's path is unknown")?;
String::from_utf16(path).map_err(|e| e.to_string())
}
/// Writes `value` under `Software\Classes` of the current user.
fn set(value: &RegistryValue) -> Result<()> {
let key = HSTRING::from(format!("{CLASSES}\\{}", value.key));
let name = value.name.map(HSTRING::from);
let name = name.as_ref().map_or(PCWSTR::null(), |n| PCWSTR(n.as_ptr()));
let data: Vec<u16> = value.data.encode_utf16().chain([0]).collect();
let bytes = u32::try_from(data.len() * 2).map_err(|_| Error::from(E_FAIL))?;
// SAFETY: `data` holds `bytes` bytes of a NUL-terminated string, and the names outlive the call.
unsafe { RegSetKeyValueW(HKEY_CURRENT_USER, &key, name, REG_SZ.0, Some(data.as_ptr().cast()), bytes) }.ok()
}
/// The default value of `key` under `Software\Classes` of the current user, when it is a string.
fn default_value(key: &str) -> Option<String> {
let key = HSTRING::from(format!("{CLASSES}\\{key}"));
let mut buf = [0u16; 128];
let mut bytes = u32::try_from(buf.len() * 2).ok()?;
// SAFETY: `buf` holds `bytes` writable bytes, and `bytes` outlives the call.
unsafe { RegGetValueW(HKEY_CURRENT_USER, &key, PCWSTR::null(), RRF_RT_REG_SZ, None, Some(buf.as_mut_ptr().cast()), Some(&mut bytes)) }
.ok()
.ok()?;
let units = buf.get(..usize::try_from(bytes / 2).ok()?)?;
String::from_utf16(units).ok().map(|s| s.trim_end_matches('\0').to_owned())
}
/// Removes `key` under `Software\Classes` of the current user with its subkeys; a key that isn't
/// there is no error.
fn remove(key: &str) -> Result<()> {
let key = HSTRING::from(format!("{CLASSES}\\{key}"));
// SAFETY: `key` outlives the call.
match unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, &key) } {
ERROR_FILE_NOT_FOUND => Ok(()),
e => e.ok(),
}
}
/// Tells Explorer that file associations changed, so it asks for thumbnails again.
fn associations_changed() {
// SAFETY: SHCNE_ASSOCCHANGED takes no items.
unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, None, None) };
}
/// Registers the handler for the current user ([`crate::registry_values`]).
fn register() -> Result<()> {
let dll = module_path().map_err(|e| Error::new(E_FAIL, e))?;
crate::registry_values(&dll).iter().try_for_each(set)
}
/// Removes the class key and each extension's thumbnail handler key that names this handler.
fn unregister() -> Result<()> {
for ext in crate::EXTENSIONS {
let key = crate::shell_ex_key(ext);
if default_value(&key).is_some_and(|v| crate::names_this_handler(&v)) {
remove(&key)?;
}
}
remove(&crate::class_key())
}
/// Keeps the DLL's module handle for [`module_path`].
#[unsafe(no_mangle)]
extern "system" fn DllMain(module: HINSTANCE, reason: u32, _reserved: *mut c_void) -> BOOL {
if reason == DLL_PROCESS_ATTACH {
MODULE.store(module.0, Ordering::SeqCst);
}
true.into()
}
/// COM's request for the class factory of class `class`.
///
/// # Safety
///
/// `class` and `iid` point to GUIDs and `object` to writable memory for an interface pointer, as
/// COM passes them.
#[unsafe(no_mangle)]
unsafe extern "system" fn DllGetClassObject(class: *const GUID, iid: *const GUID, object: *mut *mut c_void) -> HRESULT {
if class.is_null() || iid.is_null() || object.is_null() {
return E_POINTER;
}
// SAFETY: the caller passes valid pointers, checked for null above.
unsafe {
*object = null_mut();
if *class != CLASS_ID {
return CLASS_E_CLASSNOTAVAILABLE;
}
let factory: IClassFactory = Factory::new().into();
factory.query(iid, object)
}
}
/// Whether COM may unload the DLL: no provider or class factory is alive and no lock is held.
#[unsafe(no_mangle)]
extern "system" fn DllCanUnloadNow() -> HRESULT {
if LIVE.load(Ordering::SeqCst) == 0 { S_OK } else { S_FALSE }
}
/// `regsvr32`: registers the handler for the current user.
#[unsafe(no_mangle)]
extern "system" fn DllRegisterServer() -> HRESULT {
let result = register();
if result.is_err() {
let _ = unregister();
}
associations_changed();
result.map_or_else(|e| e.code(), |()| S_OK)
}
/// `regsvr32 /u`: removes the current user's registration.
#[unsafe(no_mangle)]
extern "system" fn DllUnregisterServer() -> HRESULT {
let result = unregister();
associations_changed();
result.map_or_else(|e| e.code(), |()| S_OK)
}
@@ -0,0 +1,251 @@
//! Windows: the thumbnail handler that Explorer and the file dialogs run for `.vectorcraft`,
//! `.drawcraft` and `.vctemplate` files. It is a COM server DLL whose class implements
//! `IThumbnailProvider` and `IInitializeWithStream`
//! (<https://learn.microsoft.com/windows/win32/shell/thumbnail-providers>,
//! <https://learn.microsoft.com/windows/win32/api/thumbcache/nn-thumbcache-ithumbnailprovider>).
//!
//! Explorer gives the handler the file's bytes as a stream. The handler writes them to a new file
//! in `%USERPROFILE%\AppData\LocalLow\VectorCraft\Thumbnails` (falling back to the temp folder),
//! runs `vectorcraft-cli thumbnail --size N IN OUT` from the DLL's folder on
//! it, and returns the PNG that command writes (the first artboard, else the art, drawn by
//! `vectorcraft_render::encode::first_artboard`) as a 32-bit DIB section with alpha. A file larger
//! than 256 MiB, a document that can't be opened or shows nothing, and a `vectorcraft-cli` run
//! longer than [`DEADLINE`] give Explorer an error, and Explorer shows the file's icon. Rendering
//! runs in the `vectorcraft-cli` process, so a file that makes it fail or hang ends that process.
//! The handler is not given the file's path (`IInitializeWithStream` is the only initialization
//! an isolated handler gets), so a linked image found only relative to the document's folder
//! shows the preview saved with it.
//!
//! `regsvr32 vectorcraft_thumbnail_handler.dll` registers the handler for the current user, and
//! `regsvr32 /u` removes it ([`registry_values`]). The COM parts build on Windows only; the parts
//! in this file build everywhere and their tests run on every system.
use std::ffi::OsString;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
#[cfg(windows)]
mod com;
#[cfg(test)]
mod tests;
/// The handler's class id: the key under `CLSID`, and the value of each extension's `ShellEx` key.
pub const CLSID: &str = "{1971F5DA-D761-4655-AB25-6B3825BD1748}";
/// [`CLSID`] as a number, the form COM compares.
pub const CLSID_VALUE: u128 = 0x1971_f5da_d761_4655_ab25_6b38_25bd_1748;
/// The `ShellEx` subkey that names an extension's thumbnail handler, the interface id of
/// `IThumbnailProvider` (<https://learn.microsoft.com/windows/win32/shell/thumbnail-providers>).
pub const THUMBNAIL_SHELL_EX: &str = "{e357fccd-a995-4576-b01f-234630154e96}";
/// The extensions the handler is registered for: documents, documents under their former
/// extension, and templates (the globs of `packaging/linux/ai.storyteller.vectorcraft.mime.xml`).
pub const EXTENSIONS: &[&str] = &[".vectorcraft", ".drawcraft", ".vctemplate"];
/// The description in the class key.
pub const DESCRIPTION: &str = "VectorCraft document thumbnail handler";
/// The largest file the handler reads, in bytes, the limit `vectorcraft-cli thumbnail` applies.
pub const MAX_FILE: u64 = 256 << 20;
/// The largest `--size` `vectorcraft-cli thumbnail` takes. Explorer asks for sizes up to 1024.
pub const MAX_SIDE: u32 = 1024;
/// The largest PNG the handler reads back, in bytes: an uncompressed 1024 by 1024 RGBA picture
/// with room for the chunks around it.
pub const MAX_PNG: u64 = 8 << 20;
/// How long the handler waits for `vectorcraft-cli` before it ends the process: the command's
/// own 20-second limit and 5 seconds to start.
pub const DEADLINE: Duration = Duration::from_secs(25);
/// How often the handler checks whether `vectorcraft-cli` has exited.
const POLL: Duration = Duration::from_millis(10);
/// The program the handler runs, in the DLL's folder.
pub const CLI: &str = "vectorcraft-cli.exe";
/// A picture in the layout Explorer takes: rows from top to bottom, 4 bytes per pixel in blue,
/// green, red and alpha order, with the colors premultiplied by alpha.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Picture {
pub width: u32,
pub height: u32,
pub bgra: Vec<u8>,
}
/// One registry value the handler writes, under `Software\Classes` of the current user.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegistryValue {
/// The key, relative to `Software\Classes`.
pub key: String,
/// The value's name; `None` is the key's default value.
pub name: Option<&'static str>,
/// The string the value holds.
pub data: String,
}
/// The class key, relative to `Software\Classes`.
pub fn class_key() -> String {
format!("CLSID\\{CLSID}")
}
/// The key that names `extension`'s thumbnail handler, relative to `Software\Classes`.
pub fn shell_ex_key(extension: &str) -> String {
format!("{extension}\\ShellEx\\{THUMBNAIL_SHELL_EX}")
}
/// The values that register the handler in the DLL at path `dll`: the class with its server and
/// threading model, and the class as the thumbnail handler of each of [`EXTENSIONS`], as
/// <https://learn.microsoft.com/windows/win32/shell/thumbnail-providers> describes.
pub fn registry_values(dll: &str) -> Vec<RegistryValue> {
let class = class_key();
let server = format!("{class}\\InprocServer32");
let mut values = vec![
RegistryValue { key: class, name: None, data: DESCRIPTION.into() },
RegistryValue { key: server.clone(), name: None, data: dll.into() },
RegistryValue { key: server, name: Some("ThreadingModel"), data: "Apartment".into() },
];
values.extend(EXTENSIONS.iter().map(|ext| RegistryValue { key: shell_ex_key(ext), name: None, data: CLSID.into() }));
values
}
/// Whether `value`, the default value of an extension's `ShellEx` key, names this handler: class
/// ids are compared without regard to letter case. `regsvr32 /u` removes only such keys.
pub fn names_this_handler(value: &str) -> bool {
value.trim().eq_ignore_ascii_case(CLSID)
}
/// Reads all of `r` when it holds at most `max` bytes, else returns an error.
pub fn read_bounded(r: impl Read, max: u64) -> io::Result<Vec<u8>> {
let mut bytes = Vec::new();
r.take(max.saturating_add(1)).read_to_end(&mut bytes)?;
if u64::try_from(bytes.len()).map_or(true, |n| n > max) {
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("larger than {max} bytes")));
}
Ok(bytes)
}
/// The document Explorer passed as a stream. Its bytes are read on the first request and kept, so
/// a later request on the same handler, at another size for example, gets the same document.
pub struct Document<R> {
stream: Option<R>,
bytes: Option<Vec<u8>>,
}
impl<R: Read> Document<R> {
pub fn new(stream: R) -> Self {
Self { stream: Some(stream), bytes: None }
}
/// The document's bytes, read from the stream when it holds at most `max` bytes. When the
/// first read fails, this call and every later one return an error.
pub fn bytes(&mut self, max: u64) -> io::Result<&[u8]> {
if let Some(stream) = self.stream.take() {
self.bytes = Some(read_bounded(stream, max)?);
}
self.bytes.as_deref().ok_or_else(|| io::Error::other("the document's stream could not be read"))
}
}
/// The `--size` for Explorer's request of a picture `cx` pixels on its longer side: `cx`, at most
/// [`MAX_SIDE`]; `None` for 0.
pub fn request_size(cx: u32) -> Option<u32> {
(cx > 0).then(|| cx.min(MAX_SIDE))
}
/// The arguments of `vectorcraft-cli` that write the thumbnail of `input` to `output`, `size`
/// pixels on its longer side.
pub fn arguments(size: u32, input: &Path, output: &Path) -> Vec<OsString> {
vec!["thumbnail".into(), "--size".into(), size.to_string().into(), input.into(), output.into()]
}
/// A file the handler made in the temp folder, removed when dropped.
struct TempFile(PathBuf);
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
/// Writes `bytes` to a new file `vectorcraft-thumbnail-<pid>-<n>.vectorcraft` in `dir`, with the
/// first `n` whose name no file has.
fn write_input(dir: &Path, bytes: &[u8]) -> io::Result<TempFile> {
use std::io::Write;
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
loop {
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let path = dir.join(format!("vectorcraft-thumbnail-{}-{n}.vectorcraft", std::process::id()));
match File::options().write(true).create_new(true).open(&path) {
Ok(mut file) => {
let temp = TempFile(path);
file.write_all(bytes)?;
return Ok(temp);
}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e),
}
}
}
/// Runs `cli thumbnail --size SIZE IN OUT` with `bytes` written to a new file IN in `dir` and
/// returns the PNG it writes to OUT, IN's name with `.png`. The process is ended when it runs
/// longer than `deadline`. IN and OUT are removed before this returns.
pub fn render(cli: &Path, bytes: &[u8], size: u32, dir: &Path, deadline: Duration) -> Result<Vec<u8>, String> {
let input = write_input(dir, bytes).map_err(|e| format!("{}: {e}", dir.display()))?;
let output = TempFile(input.0.with_extension("png"));
let mut command = Command::new(cli);
command.args(arguments(size, &input.0, &output.0)).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
no_console_window(&mut command);
let mut child = command.spawn().map_err(|e| format!("{}: {e}", cli.display()))?;
let end = Instant::now() + deadline;
let status = loop {
if let Some(status) = child.try_wait().map_err(|e| format!("{}: {e}", cli.display()))? {
break status;
}
if Instant::now() >= end {
let _ = child.kill();
let _ = child.wait();
return Err(format!("{} ran longer than {} seconds", cli.display(), deadline.as_secs()));
}
std::thread::sleep(POLL);
};
if !status.success() {
return Err(format!("{} exited with {status}", cli.display()));
}
let png = File::open(&output.0).and_then(|f| read_bounded(f, MAX_PNG)).map_err(|e| format!("{}: {e}", output.0.display()))?;
Ok(png)
}
/// Starts `command` without a console window (`CREATE_NO_WINDOW`,
/// <https://learn.microsoft.com/windows/win32/procthread/process-creation-flags>).
#[cfg(windows)]
fn no_console_window(command: &mut Command) {
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
#[cfg(not(windows))]
fn no_console_window(_: &mut Command) {}
/// The 8-bit RGBA PNG `png` (what `vectorcraft-cli thumbnail` writes, with straight alpha) as a
/// [`Picture`]. An error
/// when it can't be decoded, has another pixel format, or is empty or larger than `max_side`
/// pixels on a side.
pub fn picture(png: &[u8], max_side: u32) -> Result<Picture, String> {
let mut reader = png::Decoder::new(io::Cursor::new(png)).read_info().map_err(|e| e.to_string())?;
let (width, height) = (reader.info().width, reader.info().height);
if width == 0 || height == 0 || width > max_side || height > max_side {
return Err(format!("a {width} by {height} picture, not 1 to {max_side} pixels on each side"));
}
let mut buf = vec![0; reader.output_buffer_size().ok_or("the picture is too large")?];
let frame = reader.next_frame(&mut buf).map_err(|e| e.to_string())?;
if (frame.color_type, frame.bit_depth) != (png::ColorType::Rgba, png::BitDepth::Eight) {
return Err(format!("a {:?} {:?} picture, not 8-bit RGBA", frame.bit_depth, frame.color_type));
}
let rgba = buf.get(..frame.buffer_size()).ok_or("the picture is cut short")?;
let bgra = rgba.as_chunks::<4>().0.iter().flat_map(|&[r, g, b, a]| [premultiply(b, a), premultiply(g, a), premultiply(r, a), a]).collect();
Ok(Picture { width, height, bgra })
}
/// Color `c` multiplied by alpha `a`, both 0 to 255, rounded to the nearest value.
fn premultiply(c: u8, a: u8) -> u8 {
u8::try_from((u16::from(c) * u16::from(a) + 127) / 255).unwrap_or(u8::MAX)
}
@@ -0,0 +1,174 @@
use std::path::Path;
use super::*;
const MIME: &str = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml");
/// A PNG of `width`×`height` pixels with `data` as its samples.
fn png_of(width: u32, height: u32, color: png::ColorType, data: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, width, height);
encoder.set_color(color);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().unwrap();
writer.write_image_data(data).unwrap();
writer.finish().unwrap();
out
}
/// An empty folder `vectorcraft-thumbnail-handler-<pid>-<name>` in the temp folder.
#[cfg(unix)]
fn folder(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("vectorcraft-thumbnail-handler-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// The names of the files in `dir`.
#[cfg(unix)]
fn files_in(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
}
#[test]
fn the_class_id_string_and_number_are_the_same_id() {
let hex = format!("{CLSID_VALUE:032X}");
let grouped = format!("{{{}-{}-{}-{}-{}}}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..]);
assert_eq!(grouped, CLSID);
}
#[test]
fn registration_names_the_dll_and_the_handler_of_every_extension() {
let values = registry_values("C:\\Program Files\\VectorCraft\\vectorcraft_thumbnail_handler.dll");
let class = format!("CLSID\\{CLSID}");
let server = format!("{class}\\InprocServer32");
let want = vec![
RegistryValue { key: class, name: None, data: DESCRIPTION.into() },
RegistryValue { key: server.clone(), name: None, data: "C:\\Program Files\\VectorCraft\\vectorcraft_thumbnail_handler.dll".into() },
RegistryValue { key: server, name: Some("ThreadingModel"), data: "Apartment".into() },
RegistryValue { key: format!(".vectorcraft\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() },
RegistryValue { key: format!(".drawcraft\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() },
RegistryValue { key: format!(".vctemplate\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() },
];
assert_eq!(values, want);
assert_eq!(THUMBNAIL_SHELL_EX.to_ascii_uppercase(), "{E357FCCD-A995-4576-B01F-234630154E96}");
}
#[test]
fn the_extensions_are_the_globs_of_the_document_and_template_types() {
let mut globs = Vec::new();
let mut in_type = false;
for line in MIME.lines().map(str::trim) {
if let Some(rest) = line.strip_prefix("<mime-type type=\"") {
in_type = matches!(rest.split('"').next(), Some("application/x-vectorcraft" | "application/x-vectorcraft-template"));
} else if in_type && let Some(rest) = line.strip_prefix("<glob pattern=\"*") {
globs.push(rest.split('"').next().unwrap().to_owned());
}
}
assert_eq!(globs, EXTENSIONS);
}
#[test]
fn only_this_class_id_names_this_handler() {
assert!(names_this_handler(CLSID));
assert!(names_this_handler(&CLSID.to_ascii_lowercase()));
assert!(!names_this_handler("{C7657C4A-9F68-40FA-A4DF-96BC08EB3551}"));
assert!(!names_this_handler(""));
}
#[test]
fn a_stream_larger_than_the_limit_is_refused() {
assert_eq!(read_bounded(&[7u8; 10][..], 10).unwrap(), vec![7; 10]);
assert_eq!(read_bounded(&[][..], 10).unwrap(), Vec::<u8>::new());
assert_eq!(read_bounded(&[7u8; 11][..], 10).unwrap_err().kind(), io::ErrorKind::InvalidData);
assert!(read_bounded(&[7u8; 11][..], u64::MAX).is_ok());
}
#[test]
fn a_second_request_gets_the_same_document() {
let mut document = Document::new(io::Cursor::new(vec![1u8, 2, 3]));
assert_eq!(document.bytes(10).unwrap(), [1, 2, 3]);
assert_eq!(document.bytes(10).unwrap(), [1, 2, 3]);
let mut large = Document::new(&[7u8; 11][..]);
assert_eq!(large.bytes(10).unwrap_err().kind(), io::ErrorKind::InvalidData);
assert!(large.bytes(10).is_err());
}
#[test]
fn the_size_asked_of_the_command_is_at_most_its_limit() {
assert_eq!(request_size(0), None);
assert_eq!(request_size(1), Some(1));
assert_eq!(request_size(256), Some(256));
assert_eq!(request_size(MAX_SIDE), Some(MAX_SIDE));
assert_eq!(request_size(2048), Some(MAX_SIDE));
}
#[test]
fn the_command_line_is_thumbnail_size_input_output() {
let args = arguments(96, Path::new("in.vectorcraft"), Path::new("out.png"));
assert_eq!(args, ["thumbnail", "--size", "96", "in.vectorcraft", "out.png"]);
}
#[test]
fn an_rgba_png_becomes_top_down_premultiplied_bgra() {
// Two rows: opaque red and half-transparent blue, then 20% white and a clear white pixel.
let rgba = [255, 0, 0, 255, 0, 0, 255, 128, 255, 255, 255, 51, 255, 255, 255, 0];
let picture = picture(&png_of(2, 2, png::ColorType::Rgba, &rgba), 2).unwrap();
assert_eq!((picture.width, picture.height), (2, 2));
assert_eq!(picture.bgra, [0, 0, 255, 255, 128, 0, 0, 128, 51, 51, 51, 51, 0, 0, 0, 0]);
}
#[test]
fn a_png_that_is_not_an_rgba_thumbnail_is_refused() {
assert!(picture(&png_of(1, 1, png::ColorType::Rgb, &[1, 2, 3]), 8).is_err());
assert!(picture(&png_of(3, 1, png::ColorType::Rgba, &[0; 12]), 2).is_err(), "wider than asked");
assert!(picture(&png_of(1, 3, png::ColorType::Rgba, &[0; 12]), 2).is_err(), "taller than asked");
assert!(picture(b"not a picture", 8).is_err());
let png = png_of(2, 2, png::ColorType::Rgba, &[9; 16]);
assert!(picture(&png[..png.len() - 20], 8).is_err(), "cut short");
}
/// `render` runs the program with the thumbnail arguments, returns what it writes to OUT, gives
/// an error for a failed or overlong run, and leaves no file behind. The stand-ins are shell
/// scripts, all written before the first one runs.
#[cfg(unix)]
#[test]
fn render_runs_the_command_and_removes_its_files() {
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
let dir = folder("render");
let temp = dir.join("temp");
std::fs::create_dir(&temp).unwrap();
let png = png_of(1, 1, png::ColorType::Rgba, &[1, 2, 3, 4]);
std::fs::write(dir.join("picture.png"), &png).unwrap();
std::fs::write(dir.join("document"), b"document bytes").unwrap();
let script = |name: &str, body: &str| {
let path = dir.join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
};
let d = dir.display();
let writes = script(
"writes",
&format!(
"[ \"$1 $2 $3\" = \"thumbnail --size 64\" ] || exit 4\ncase \"$4\" in *.vectorcraft) ;; *) exit 5 ;; esac\n\
cmp -s \"$4\" '{d}/document' || exit 3\ncp '{d}/picture.png' \"$5\""
),
);
let fails = script("fails", "echo broken >&2\nexit 1");
let silent = script("silent", "exit 0");
let hangs = script("hangs", "exec sleep 30");
assert_eq!(render(&writes, b"document bytes", 64, &temp, DEADLINE).unwrap(), png);
assert!(render(&fails, b"x", 64, &temp, DEADLINE).unwrap_err().contains("exited with"));
assert!(render(&silent, b"x", 64, &temp, DEADLINE).is_err(), "no OUT written");
assert!(render(&hangs, b"x", 64, &temp, Duration::ZERO).unwrap_err().contains("ran longer than"));
assert!(render(&dir.join("missing"), b"x", 64, &temp, DEADLINE).is_err());
assert_eq!(files_in(&temp), Vec::<String>::new());
let _ = std::fs::remove_dir_all(&dir);
}
+1 -6
View File
@@ -318,12 +318,7 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result<V
/// The first artboard (else the art) as a PNG fitted into [`PREVIEW_MAX`] pixels (`None`: nothing
/// to show).
pub(crate) fn preview_png(doc: &Document) -> Result<Option<Vec<u8>>> {
let Some(r) = doc.artboards.first().map(|a| a.rect).or_else(|| vectorcraft_render::encode::art_bounds(doc)) else { return Ok(None) };
let scale = f64::from(PREVIEW_MAX) / r.width().max(r.height());
if vectorcraft_render::raster_size(r, scale).is_err() {
return Ok(None);
}
vectorcraft_render::Renderer::new().render_region(doc, r, scale, false).to_png().map(Some).map_err(EngineError::Other)
vectorcraft_render::encode::first_artboard_png(doc, PREVIEW_MAX).map_err(EngineError::Other)
}
/// `p` with `compress` from the Use Compression preference when it doesn't say (saves only;
+16
View File
@@ -243,6 +243,22 @@ pub fn art_bounds(doc: &Document) -> Option<Rect> {
doc.layers.iter().fold(None, |acc, l| vectorcraft_geom::union_opt(acc, drawn_bounds(&symbols, l)))
}
/// The first artboard (else the art, [`art_bounds`]) rendered with a transparent background, its
/// longer side `max_side` pixels: the picture of a native file's embedded preview, and of the
/// thumbnail `vectorcraft-cli thumbnail` writes for file managers. `None` when the document has
/// no artboard and no art, or the region can't be rendered at that size ([`crate::raster_size`]).
pub fn first_artboard(doc: &Document, max_side: u32) -> Option<Rendered> {
let r = doc.artboards.first().map(|a| a.rect).or_else(|| art_bounds(doc))?;
let scale = f64::from(max_side) / r.width().max(r.height());
crate::raster_size(r, scale).ok()?;
Some(Renderer::new().render_region(doc, r, scale, false))
}
/// [`first_artboard`] as a PNG.
pub fn first_artboard_png(doc: &Document, max_side: u32) -> Result<Option<Vec<u8>>, String> {
first_artboard(doc, max_side).map(|img| img.to_png()).transpose()
}
/// Bounds of the art an export draws ([`art_bounds`]) that is on artboard rectangle `rect`: each
/// object of a layer or sublayer whose drawn bounds overlap `rect`, with all of its bounds; a group
/// or a clipping layer counts as one object. `None` when no object overlaps `rect`.
+2
View File
@@ -1014,6 +1014,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Locked artboards:** a click in the Artboards panel's lock column locks or unlocks an artboard in one undo step (`artboard.setProps {index, locked}`), and the native format saves the lock. The Artboard tool doesn't move, copy, resize or delete a locked artboard, Rearrange and Fit to Artwork Bounds leave it as it is, and its name isn't edited on the canvas. The art on it (each object whose bounds overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, `select.set`, `select.all` and the tools pass over it, and commands that act on the selection leave it; art drawn or pasted onto it stays selected and editable until the selection leaves it out. Tests in `crates/doc/src/lib.rs`, `tests/panelcmds.rs`, `xform/artboard.rs`, `panels/artboards.rs` and `canvas.rs` cover them. Public references: [Lock artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/lock-artboards.html) and [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/).
- **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 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`.
@@ -0,0 +1,4 @@
[Thumbnailer Entry]
TryExec=vectorcraft-cli
Exec=vectorcraft-cli thumbnail --size %s %i %o
MimeType=application/x-vectorcraft;application/x-vectorcraft-template;
+2
View File
@@ -96,6 +96,7 @@ if [[ "$IS_NIGHTLY" = 1 ]]; then
mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop"
fi
install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml"
install -Dm644 "$HERE/$APP_ID.thumbnailer" "$STAGE/usr/share/thumbnailers/$APP_ID.thumbnailer"
mkdir -p "$STAGE/usr/share/metainfo"
sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$VECTORCRAFT_BUILD_DATE/g" \
"$HERE/$APP_ID.metainfo.xml.in" >"$STAGE/usr/share/metainfo/$APP_ID.metainfo.xml"
@@ -183,6 +184,7 @@ CLI_WRAPPER
"$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml"
rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml"
rm -rf "$NFPM_STAGE/usr/share/mime"
rm -rf "$NFPM_STAGE/usr/share/thumbnailers"
rm -rf "$NFPM_STAGE/usr/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/vectorcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
+1
View File
@@ -66,6 +66,7 @@ pub const TABLE: &[(&str, Class)] = &[
("js", Class::Standalone),
("apischema", Class::Standalone),
("plugin-worker", Class::Exempt),
("thumbnail-handler", Class::Exempt),
];
/// Explicit orderings *within* a layer (earlier may be used by later).