diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index d60a898fd1..507caffe10 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1398097510, "producer_workflow_id": 430275079, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "signer_tooling_revision": "main", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b61d2429d0..e7ae30d3ca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,14 +89,15 @@ jobs: # 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes # the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py). # When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run - # failed jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg - # starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves - # 40 minutes for that. + # failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a + # free runner: the script fails when the leg has not started within 120 minutes, and then waits + # up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the + # script reports a leg that starts late with its own error before the job times out. cold-cache-clear: name: cold cache clear if: github.event_name == 'schedule' runs-on: ubuntu-24.04 - timeout-minutes: 200 + timeout-minutes: 290 permissions: actions: write steps: diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 3b79c61ba5..6cc6f885a2 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,12 +34,26 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: main app-name: vectorcraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} # No secrets: inherit or raw platform values in this caller. Only the isolated native # callee job may bind the release environment and export its keys; that environment must # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 989d6974dd..0e963e43e1 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: main app-name: vectorcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 @@ -32,3 +32,4 @@ jobs: # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, # #369 and #364). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]' diff --git a/ASSETS.md b/ASSETS.md index 9220086fa7..03f33d9a6e 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -33,7 +33,7 @@ Generated-in-code art is original and has no file to list. This covers the defau **Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. -**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. +**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. Desktop builds with a checkout whose opt-in `fonts/latin-manifest.txt` lists Noto Sans Condensed SemiBold (The Noto Project Authors, SIL Open Font License 1.1, from the [notofonts/latin-greek-cyrillic NotoSans-v2.015 release](https://github.com/notofonts/latin-greek-cyrillic/releases/tag/NotoSans-v2.015)) also embed that face, for document tab titles. | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| diff --git a/Cargo.lock b/Cargo.lock index 6e9dee6f4b..7492a7ccb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -613,6 +613,19 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "blake3" +version = "1.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64c0e36294adc8db531500e3f2b8ec75c4af9177271e9c6d33f93609d56e57cd" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + [[package]] name = "block" version = "0.1.6" @@ -1106,6 +1119,15 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + [[package]] name = "cookie-factory" version = "0.3.3" @@ -1452,6 +1474,22 @@ dependencies = [ "zbus", ] +[[package]] +name = "craft-doc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +dependencies = [ + "blake3", + "craft-ecproj-format", + "craft-pcraft-format", + "craft-vectorcraft-format", + "flate2", + "ruzstd", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1491,6 +1529,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-ecproj-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-eps" version = "0.1.0" @@ -1784,6 +1832,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-pcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +dependencies = [ + "flate2", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -8600,6 +8659,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "sha2 0.10.9", "thiserror 2.0.21", "tiff", "vectorcraft-color", @@ -8637,6 +8697,7 @@ dependencies = [ "chrono", "craft-cdr", "craft-codepage", + "craft-doc", "craft-docpath", "craft-image-codecs", "craft-jxl", @@ -8719,6 +8780,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", + "vectorcraft-eps", "vectorcraft-geom 0.24.1", "vectorcraft-metafile", "vectorcraft-pathops 0.24.1", @@ -8875,6 +8937,16 @@ dependencies = [ "vectorcraft-text", ] +[[package]] +name = "vectorcraft-plugin-worker" +version = "0.24.1" +dependencies = [ + "js-sys", + "vectorcraft-plugins", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "vectorcraft-plugins" version = "0.24.1" @@ -8891,6 +8963,7 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-geom 0.24.1", "vectorcraft-js", + "vectorcraft-plugins", "wasmi", "wasmparser 0.228.0", "wat", @@ -9020,6 +9093,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" diff --git a/Cargo.toml b/Cargo.toml index bb9fd22f7c..242abcfe87 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,8 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0 # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). diff --git a/NOTICE b/NOTICE index 99d05d6235..4d7c813796 100644 --- a/NOTICE +++ b/NOTICE @@ -45,6 +45,8 @@ fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.m Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest; web builds BIZ UDPGothic Regular only) under the SIL Open Font License 1.1. Their license texts ship with the release packages as OFL-.txt. +Desktop builds with a craft-fonts checkout whose fonts/latin-manifest.txt lists Noto Sans Condensed +SemiBold (Copyright 2022 The Noto Project Authors, SIL Open Font License 1.1) also embed that face. PDF import decodes CJK text with Adobe's CMap resources (https://github.com/adobe-type-tools/cmap-resources), compiled into the app through the hayro-cmap crate under the BSD 3-Clause License: diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 2416b17b89..f42a24e9b1 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -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` +/// (), 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); + } +} diff --git a/apps/vectorcraft-cli/tests/it/main.rs b/apps/vectorcraft-cli/tests/it/main.rs index d898dda20a..a820d4f7b4 100644 --- a/apps/vectorcraft-cli/tests/it/main.rs +++ b/apps/vectorcraft-cli/tests/it/main.rs @@ -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 { diff --git a/apps/vectorcraft-cli/tests/it/thumbnail.rs b/apps/vectorcraft-cli/tests/it/thumbnail.rs new file mode 100644 index 0000000000..b75d99b158 --- /dev/null +++ b/apps/vectorcraft-cli/tests/it/thumbnail.rs @@ -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 (). +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 { + 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!("")), "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"); + } +} diff --git a/apps/vectorcraft-plugin-worker/Cargo.toml b/apps/vectorcraft-plugin-worker/Cargo.toml new file mode 100644 index 0000000000..a2dfc0b944 --- /dev/null +++ b/apps/vectorcraft-plugin-worker/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "vectorcraft-plugin-worker" +description = "The web build's plug-in worker: checks plug-in modules being installed and runs filters off the page" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[lints] +workspace = true + +[[bin]] +name = "vectorcraft-plugin-worker" +path = "src/main.rs" + +[target.'cfg(target_arch = "wasm32")'.dependencies] +vectorcraft-plugins = { workspace = true } +wasm-bindgen = "0.2" +js-sys = "0.3" +web-sys = { version = "0.3", features = ["DedicatedWorkerGlobalScope", "MessageEvent"] } diff --git a/apps/vectorcraft-plugin-worker/src/main.rs b/apps/vectorcraft-plugin-worker/src/main.rs new file mode 100644 index 0000000000..4699ca2e3f --- /dev/null +++ b/apps/vectorcraft-plugin-worker/src/main.rs @@ -0,0 +1,37 @@ +//! The web build's plug-in worker ([`vectorcraft_plugins::worker`]). Trunk builds it beside the +//! app (`data-type="worker"` in `apps/vectorcraft-web/index.html`), and the page starts one for each +//! module it checks and each filter it runs, through the loader Trunk writes for it +//! (`vectorcraft-plugin-worker_loader.js`). Each message, both ways, is one `Uint8Array`. + +#[cfg(target_arch = "wasm32")] +fn main() { + use std::cell::RefCell; + use std::rc::Rc; + + use wasm_bindgen::JsCast as _; + use wasm_bindgen::prelude::Closure; + use web_sys::{DedicatedWorkerGlobalScope, MessageEvent}; + + let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into(); + let poster = scope.clone(); + let post = Rc::new(move |msg: Vec| { + let bytes = js_sys::Uint8Array::from(msg.as_slice()); + // A message that can't be posted leaves the page waiting, and its time budget ends the run. + let _ = poster.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer())); + }); + let worker = Rc::new(RefCell::new(vectorcraft_plugins::worker::Worker::new(post))); + let handler = Rc::clone(&worker); + let on_message = Closure::::new(move |e: MessageEvent| { + let msg = js_sys::Uint8Array::new(&e.data()).to_vec(); + handler.borrow_mut().handle(&msg); + }); + scope.set_onmessage(Some(on_message.as_ref().unchecked_ref())); + // The handler lives as long as the worker. + on_message.forget(); + worker.borrow().ready(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn main() { + eprintln!("vectorcraft-plugin-worker only runs in the browser, as the web build's plug-in worker"); +} diff --git a/apps/vectorcraft-thumbnail-handler/Cargo.toml b/apps/vectorcraft-thumbnail-handler/Cargo.toml new file mode 100644 index 0000000000..af502bd751 --- /dev/null +++ b/apps/vectorcraft-thumbnail-handler/Cargo.toml @@ -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" diff --git a/apps/vectorcraft-thumbnail-handler/src/com.rs b/apps/vectorcraft-thumbnail-handler/src/com.rs new file mode 100644 index 0000000000..ebd421060d --- /dev/null +++ b/apps/vectorcraft-thumbnail-handler/src/com.rs @@ -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 = 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>>, +} + +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, _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, 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 { + 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, cx: u32) -> std::result::Result { + 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 { + 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::() 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::(), len) }; + Ok(bitmap) +} + +/// The path of this DLL. +fn module_path() -> std::result::Result { + 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 = 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 { + 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) +} diff --git a/apps/vectorcraft-thumbnail-handler/src/lib.rs b/apps/vectorcraft-thumbnail-handler/src/lib.rs new file mode 100644 index 0000000000..4633bfa86d --- /dev/null +++ b/apps/vectorcraft-thumbnail-handler/src/lib.rs @@ -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` +//! (, +//! ). +//! +//! 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` (). +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, +} + +/// 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 +/// describes. +pub fn registry_values(dll: &str) -> Vec { + 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> { + 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 { + stream: Option, + bytes: Option>, +} + +impl Document { + 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 { + (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 { + 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--.vectorcraft` in `dir`, with the +/// first `n` whose name no file has. +fn write_input(dir: &Path, bytes: &[u8]) -> io::Result { + 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, 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`, +/// ). +#[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 { + 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) +} diff --git a/apps/vectorcraft-thumbnail-handler/src/tests.rs b/apps/vectorcraft-thumbnail-handler/src/tests.rs new file mode 100644 index 0000000000..5c58697a63 --- /dev/null +++ b/apps/vectorcraft-thumbnail-handler/src/tests.rs @@ -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 { + 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--` 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 { + let mut names: Vec = 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("::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::::new()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 7208bea2ab..a9a1013520 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -33,4 +33,4 @@ wasm-bindgen = "0.2" serde_json = { workspace = true } wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal", "Node", "Worker", "MessageEvent", "ErrorEvent", "Performance"] } diff --git a/apps/vectorcraft-web/index.html b/apps/vectorcraft-web/index.html index 2ccfc271b0..965bd03ebd 100644 --- a/apps/vectorcraft-web/index.html +++ b/apps/vectorcraft-web/index.html @@ -17,6 +17,8 @@ + +