Merge main into feat/scripts-page-item-blending-mode

# Conflicts:
#	crates/engine/src/tests/script_dom.rs
#	docs/mcp.md
#	docs/target-app-parity.md
This commit is contained in:
dotCooCoo committed 2026-11-28 14:17:28 -08:00
commit 5728ff39cd
335 files changed
+27813 -1674

No files matched your search

+3 -3
View File
@@ -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",
+16 -2
View File
@@ -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.
+3 -2
View File
@@ -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"]'
Generated
+71
View File
@@ -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",
@@ -8902,6 +8963,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-geom 0.24.1",
"vectorcraft-js",
"vectorcraft-plugins",
"wasmi",
"wasmparser 0.228.0",
"wat",
@@ -9031,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"
+2
View File
@@ -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).
+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);
}
+111
View File
@@ -7,11 +7,17 @@
//! fails in a Flatpak sandbox (`XCURSOR_PATH` unset, no cursor theme in the runtime) and where the
//! `default` theme is a dangling symlink; the desktop's own setting names a theme that loads.
//!
//! Where no cursor theme can be found at all (KDE or sway without gsettings), the env fix does
//! nothing: [`shell_caps`] leaves out [`Caps::SYSTEM_CURSOR`], and the framework keeps the system
//! pointer and paints no tool cursor beside it (#5311).
//!
//! This reads the desktop's cursor theme and size and sets what the user left unset, once, before
//! any thread starts and before the window opens.
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
use craft::host::target::Caps;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
/// Where a Flatpak sandbox mounts the host's cursor themes (user and system).
const FLATPAK_HOST_ICONS: [&str; 2] = ["/run/host/user-share/icons", "/run/host/share/icons"];
@@ -48,6 +54,74 @@ pub fn plan(var: impl Fn(&str) -> Option<OsString>, host_icons: &[&str], desktop
out
}
/// Xcursor's default search path when `XCURSOR_PATH` is unset (relative entries are in `$HOME`).
const DEFAULT_ICON_DIRS: [&str; 5] = ["~/.local/share/icons", "~/.icons", "/usr/share/icons", "/usr/share/pixmaps", "/usr/X11R6/lib/X11/icons"];
/// The themes `index.theme` lists after `Inherits=`.
fn inherits(index: &str) -> Vec<String> {
index
.lines()
.find_map(|l| l.trim().strip_prefix("Inherits="))
.map(|v| v.split([',', ';']).map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect())
.unwrap_or_default()
}
/// Can Xcursor load a pointer for the environment's theme (`XCURSOR_THEME`, else `default`)? It does
/// when the theme, or one it inherits from, has a `default` or `left_ptr` cursor file in a folder of
/// `XCURSOR_PATH` (else Xcursor's default folders). `read` returns a file's text, `exists` tells
/// whether a file is there.
pub fn theme_usable(
var: impl Fn(&str) -> Option<OsString>,
home: Option<&Path>,
read: impl Fn(&Path) -> Option<String>,
exists: impl Fn(&Path) -> bool,
) -> bool {
let dirs: Vec<PathBuf> = match var("XCURSOR_PATH").filter(|v| !v.is_empty()) {
Some(v) => std::env::split_paths(&v).collect(),
None => DEFAULT_ICON_DIRS
.iter()
.filter_map(|d| match d.strip_prefix("~/") {
Some(rest) => home.map(|h| h.join(rest)),
None => Some(PathBuf::from(d)),
})
.collect(),
};
let first = var("XCURSOR_THEME").and_then(|v| v.into_string().ok()).filter(|t| !t.is_empty()).unwrap_or_else(|| "default".into());
let mut todo = vec![first];
let mut seen: Vec<String> = Vec::new();
while let Some(theme) = todo.pop() {
// Bounded: themes inherit in short chains, and a cycle must end.
if seen.contains(&theme) || seen.len() >= 16 {
continue;
}
for dir in &dirs {
let base = dir.join(&theme);
if ["default", "left_ptr"].iter().any(|c| exists(&base.join("cursors").join(c))) {
return true;
}
if let Some(index) = read(&base.join("index.theme")) {
todo.extend(inherits(&index));
}
}
seen.push(theme);
}
false
}
/// On this machine, after [`apply`]: is there no cursor theme Xcursor can load? Then winit never
/// sets a pointer, and a hidden system pointer does not come back (#2450).
pub fn theme_missing() -> bool {
let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(PathBuf::from);
!theme_usable(|n| std::env::var_os(n), home.as_deref(), |p| std::fs::read_to_string(p).ok(), |p| p.exists())
}
/// The shell's capabilities `caps`, without [`Caps::SYSTEM_CURSOR`] when the window opens on
/// Wayland and `theme_missing` finds no cursor theme. The framework then keeps the system pointer
/// and paints no tool cursor beside it (#5311). `theme_missing` runs only on Wayland.
pub fn shell_caps(caps: Caps, wayland: bool, theme_missing: impl FnOnce() -> bool) -> Caps {
if wayland && theme_missing() { caps.difference(Caps::SYSTEM_CURSOR) } else { caps }
}
/// The value of a `gsettings get` line: `'Adwaita'` becomes `Adwaita`, `24` stays `24`.
fn gsettings_value(output: &str) -> &str {
output.trim().trim_matches('\'')
@@ -113,6 +187,43 @@ mod tests {
assert!(plan(env(&[("WAYLAND_DISPLAY", "wayland-0")]), &[], odd).is_empty());
}
#[test]
fn a_theme_is_usable_directly_or_through_inherits_and_missing_otherwise() {
let files = ["/i/Bibata/cursors/left_ptr", "/i/Breeze/index.theme", "/i/Loop/index.theme"];
// Compared as paths, so the joins match on Windows too, where they use `\`.
let exists = |p: &Path| files.iter().any(|f| Path::new(f) == p);
let read = |p: &Path| {
if p == Path::new("/i/Breeze/index.theme") {
Some("[Icon Theme]\nInherits=Other, Bibata\n".to_owned())
} else if p == Path::new("/i/Loop/index.theme") {
Some("Inherits=Loop\n".to_owned())
} else {
None
}
};
let with = |theme: &'static str| {
move |n: &str| (n == "XCURSOR_PATH").then(|| OsString::from("/i")).or((n == "XCURSOR_THEME").then(|| OsString::from(theme)))
};
assert!(theme_usable(with("Bibata"), None, read, exists));
assert!(theme_usable(with("Breeze"), None, read, exists));
// No such theme, a theme without cursors, an inheritance loop: nothing to load.
assert!(!theme_usable(with("Nope"), None, read, exists));
assert!(!theme_usable(with("Loop"), None, read, exists));
// Unset: Xcursor's default folders and the `default` theme.
assert!(!theme_usable(|_| None, Some(Path::new("/home/u")), read, exists));
}
#[test]
fn without_a_cursor_theme_on_wayland_the_system_pointer_stays_alone() {
let native = Caps::native(craft::host::target::Os::Linux);
assert!(native.contains(Caps::SYSTEM_CURSOR));
let without = shell_caps(native, true, || true);
assert!(!without.contains(Caps::SYSTEM_CURSOR), "Wayland with no cursor theme: no painted cursor beside the system pointer");
assert_eq!(without.union(Caps::SYSTEM_CURSOR), native, "only the system cursor is left out");
assert_eq!(shell_caps(native, true, || false), native, "Wayland with a theme");
assert_eq!(shell_caps(native, false, || panic!("the theme is looked up only on Wayland")), native, "X11 and XWayland");
}
#[test]
fn gsettings_output_is_unquoted() {
assert_eq!(gsettings_value("'Adwaita'\n"), "Adwaita");
+5
View File
@@ -667,6 +667,11 @@ fn main() -> std::process::ExitCode {
// framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and
// Preferences › User Interface › System Title Bar.
let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() };
// On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted
// beside it (#2450, #5311).
let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland;
let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing);
let shell_info = shell_info.caps(caps);
let titlebar_pref =
if engine_pref("systemTitleBar").and_then(|v| v.as_bool()).unwrap_or(false) { TitleBarPref::System } else { TitleBarPref::Integrated };
let decision = decide_for(Prefix::new("VECTORCRAFT"), shell_info.backend, titlebar_pref);
+111 -2
View File
@@ -175,7 +175,16 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>,
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
let target = chosen.join(name);
match std::fs::symlink_metadata(&target) {
Ok(metadata) if !metadata.is_dir() => {
return Err(format!("the nightly {label} must be a directory inside its selected profile"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
let child = canonical_future(&target)?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
@@ -192,11 +201,86 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
}
Ok(())
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(all(windows, feature = "wgpu"))]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT) || info.dwFileAttributes.has(co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(all(windows, not(feature = "wgpu")))]
{
use std::os::windows::fs::MetadataExt as _;
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
if metadata.file_attributes() & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
return Err("the nightly profile file must not be an alias or directory".into());
}
}
let _ = (path, metadata);
Ok(())
}
const PROFILE_FOLDERS: [&str; 18] = [
"Data Recovery",
"Fonts",
"logs",
"Launch",
"Color Profiles",
"Plug-ins",
"Scripts",
"Startup Scripts",
"Metadata Templates",
"New Document Profiles",
"Proof Setups",
"Script Data",
"PDF Presets",
"Swatches",
"Graphic Styles",
"Symbols",
"Brushes",
"Libraries",
];
/// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to
/// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated
/// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile.
@@ -557,6 +641,31 @@ mod tests {
assert!(result.unwrap_err().contains("not writable"));
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in PLATFORMS {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
#[test]
fn the_platform_case_rules_are_the_file_systems_ones() {
let fixture = Fixture::new();
+131 -16
View File
@@ -121,14 +121,125 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter.
const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474;
/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its
/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's
/// [`crate::track::seed_of`]).
pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) {
let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT);
/// Mixed into a stroke's seed for its saturation jitter, so its amounts do not follow the hue
/// jitter's and the hue jitter's amounts stay as they were without it.
const SATURATION_JITTER_SALT: u64 = 0x7361_745f_6a69_7474;
/// Mixed into a stroke's seed for its brightness jitter, so its amounts follow neither the hue
/// jitter's nor the saturation jitter's, and theirs stay as they were without it.
const BRIGHTNESS_JITTER_SALT: u64 = 0x6272_695f_6a69_7474;
/// Recolor each of `copies` (a scatter brush's copies, in order along the path) with `adjust`,
/// given that copy's own amount between −`amount` and `amount`, drawn from `seed` (the stroke's
/// [`crate::track::seed_of`]) mixed with `salt`. `adjust` gives `None` for a color it leaves as it
/// is.
fn jitter_copies(copies: &mut [Node], amount: f64, seed: u64, salt: u64, adjust: fn(&Color, f32) -> Option<Color>) {
let mut rng = crate::track::Rng::new(seed ^ salt);
for n in copies {
let turn = rng.range(-amount, amount) as f32;
turn_hues(n, turn);
let by = rng.range(-amount, amount) as f32;
recolor_solids(n, &|c| adjust(c, by));
}
}
/// Turn the hue of each of `copies` by its own amount between −`amount` and `amount` degrees (see
/// [`jitter_copies`]).
pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) {
jitter_copies(copies, amount, seed, HUE_JITTER_SALT, turned);
}
/// Move the saturation of each of `copies` by its own amount between −`amount` and `amount`
/// percentage points (see [`jitter_copies`]).
pub(crate) fn jitter_saturations(copies: &mut [Node], amount: f64, seed: u64) {
jitter_copies(copies, amount, seed, SATURATION_JITTER_SALT, saturated);
}
/// Move the brightness of each of `copies` by its own amount between −`amount` and `amount`
/// percentage points (see [`jitter_copies`]).
pub(crate) fn jitter_brightnesses(copies: &mut [Node], amount: f64, seed: u64) {
jitter_copies(copies, amount, seed, BRIGHTNESS_JITTER_SALT, brightened);
}
/// `c` with its brightness moved by `points` percentage points, worked out on its own components
/// so its hue and saturation stay: RGB in HSB of its values, Gray by taking that much ink off or
/// adding it, CMYK by changing its K over the brightness its C, M and Y leave (C, M and Y change
/// only to go brighter than they show with no K), Lab by moving its lightness by `points` units
/// with a and b kept. The result stays between black and full brightness. White, black and grays
/// move too. `None` when the brightness stays as it is.
fn brightened(c: &Color, points: f32) -> Option<Color> {
if !points.is_finite() {
return None;
}
let by = points / 100.0;
match *c {
Color::Rgb { r, g, b } => {
let [h, s, v] = vectorcraft_color::rgb_to_hsb([r, g, b]);
let to = (v + by).clamp(0.0, 1.0);
(to != v).then(|| {
let [r, g, b] = vectorcraft_color::hsb_to_rgb([h, s, to]);
Color::rgb(r, g, b)
})
}
Color::Gray { k } => {
let to = (k - by).clamp(0.0, 1.0);
(to != k).then_some(Color::gray(to))
}
Color::Cmyk { c, m, y, k } => {
// `v` is the brightness C, M and Y leave; with its K the color shows `v` × (1 − K).
let [h, s, v] = vectorcraft_color::rgb_to_hsb([1.0 - c, 1.0 - m, 1.0 - y]);
let shown = v * (1.0 - k);
let to = (shown + by).clamp(0.0, 1.0);
if to == shown {
None
} else if to <= v {
// v > 0 here: to < shown would need shown > 0, and to > shown leaves to > 0.
Some(Color::cmyk(c, m, y, (1.0 - to / v).clamp(0.0, 1.0)))
} else {
let [r, g, b] = vectorcraft_color::hsb_to_rgb([h, s, to]);
Some(Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, 0.0))
}
}
Color::Lab { l, a, b } => {
let to = (l + points).clamp(0.0, 100.0);
(to != l).then_some(Color::lab(to, a, b))
}
}
}
/// The largest a or b a Lab color takes.
const LAB_AB_MAX: f64 = 127.0;
/// `c` with its saturation moved by `points` percentage points, worked out on its own components
/// so its hue and brightness stay: RGB in HSB of its values, CMYK over C, M and Y with K kept, Lab
/// by moving its chroma (the length of a and b) by `points` with its lightness and hue angle kept.
/// The result stays between no saturation and full. `None` for a color without a hue (white,
/// black and grays, which have no saturation to move) and for one whose saturation stays as it is
/// (already at the end it would move past), so such a color keeps its swatch link.
fn saturated(c: &Color, points: f32) -> Option<Color> {
if !points.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() {
return None;
}
let by = points / 100.0;
let move_by = |v: [f32; 3]| {
let [h, s, b] = vectorcraft_color::rgb_to_hsb(v);
let to = (s + by).clamp(0.0, 1.0);
(s > 0.0 && to != s).then(|| vectorcraft_color::hsb_to_rgb([h, to, b]))
};
match *c {
Color::Rgb { r, g, b } => move_by([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)),
Color::Cmyk { c, m, y, k } => move_by([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)),
Color::Gray { .. } => None,
Color::Lab { l, a, b } => {
let (a, b) = (f64::from(a), f64::from(b));
let chroma = a.hypot(b);
if chroma <= 0.0 {
return None;
}
// A longer chroma is cut back along the same hue angle until a and b fit; one that
// already reaches past that does not grow.
let fit = (LAB_AB_MAX / a.abs().max(b.abs())).max(1.0);
let scale = ((chroma + f64::from(points)).max(0.0) / chroma).min(fit);
(scale != 1.0).then(|| Color::lab(l, (a * scale) as f32, (b * scale) as f32))
}
}
}
@@ -156,32 +267,36 @@ fn turned(c: &Color, degrees: f32) -> Option<Color> {
}
}
fn turn_paint(p: &mut Paint, degrees: f32) {
/// Replace a solid paint's color with what `adjust` gives for it, dropping its swatch link. A
/// color that comes back unchanged (an amount too small to move its components) keeps the paint
/// and its link.
fn recolor_paint(p: &mut Paint, adjust: &dyn Fn(&Color) -> Option<Color>) {
if let Paint::Solid { color, .. } = p
&& let Some(c) = turned(color, degrees)
&& let Some(c) = adjust(color)
&& c != *color
{
*p = Paint::solid(c);
}
}
/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A
/// Recolor the solid fills and strokes under `n` with `adjust`, its type's characters included. A
/// mask's colors are its values, so they stay.
fn turn_hues(n: &mut Node, degrees: f32) {
fn recolor_solids(n: &mut Node, adjust: &dyn Fn(&Color) -> Option<Color>) {
for it in &mut n.appearance.items {
match it {
AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees),
AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees),
AppearanceItem::Fill(f) => recolor_paint(&mut f.paint, adjust),
AppearanceItem::Stroke(s) => recolor_paint(&mut s.paint, adjust),
}
}
if let NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
turn_paint(&mut r.style.fill, degrees);
turn_paint(&mut r.style.stroke, degrees);
recolor_paint(&mut r.style.fill, adjust);
recolor_paint(&mut r.style.stroke, adjust);
}
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
turn_hues(Arc::make_mut(c), degrees);
recolor_solids(Arc::make_mut(c), adjust);
}
}
}
+4
View File
@@ -173,6 +173,8 @@ pub fn defaults() -> &'static [Brush] {
rotation_relative_to_path: false,
colorization: Colorization::Tints,
hue_jitter: 0.0,
saturation_jitter: 0.0,
brightness_jitter: 0.0,
modes: None,
}),
},
@@ -187,6 +189,8 @@ pub fn defaults() -> &'static [Brush] {
rotation_relative_to_path: true,
colorization: Colorization::None,
hue_jitter: 0.0,
saturation_jitter: 0.0,
brightness_jitter: 0.0,
modes: None,
}),
},
+86 -9
View File
@@ -324,6 +324,22 @@ pub struct Scatter {
/// 0 (brushes saved before there was hue jitter) leaves the colors as they are.
#[serde(skip_serializing_if = "is_zero")]
pub hue_jitter: f64,
/// Saturation jitter in percent, 0 to 100: each copy moves the saturation of the solid colors it
/// draws, after the colorization and the hue jitter, by its own amount between
/// −`saturation_jitter` and `saturation_jitter` percentage points, keeping their hue and
/// brightness. The stroke's path and the brush name fix the amounts, so a stroke draws the same
/// colors every time. 0 (brushes saved before there was saturation jitter) leaves the colors as
/// they are.
#[serde(skip_serializing_if = "is_zero")]
pub saturation_jitter: f64,
/// Brightness jitter in percent, 0 to 100: each copy moves the brightness of the solid colors
/// it draws, after the colorization and the hue and saturation jitter, by its own amount
/// between −`brightness_jitter` and `brightness_jitter` percentage points, keeping their hue
/// and saturation. White, black and grays move too. The stroke's path and the brush name fix
/// the amounts, so a stroke draws the same colors every time. 0 (brushes saved before there
/// was brightness jitter) leaves the colors as they are.
#[serde(skip_serializing_if = "is_zero")]
pub brightness_jitter: f64,
/// How size, spacing, scatter and rotation vary between their two values: Fixed takes the
/// first, Random any value between them, Pressure the first at the lightest pen pressure and
/// the second at the heaviest, Tilt the first with the pen lying flat and the second upright,
@@ -346,6 +362,8 @@ impl Default for Scatter {
rotation_relative_to_path: false,
colorization: Colorization::None,
hue_jitter: 0.0,
saturation_jitter: 0.0,
brightness_jitter: 0.0,
modes: None,
}
}
@@ -356,6 +374,10 @@ impl Scatter {
pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)];
/// The range of [`Scatter::hue_jitter`] (°).
pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0);
/// The range of [`Scatter::saturation_jitter`] (%).
pub const SATURATION_JITTER_RANGE: (f64, f64) = (0.0, 100.0);
/// The range of [`Scatter::brightness_jitter`] (%).
pub const BRIGHTNESS_JITTER_RANGE: (f64, f64) = (0.0, 100.0);
/// Size, spacing, scatter and rotation, each as its (first, second) values.
pub fn values(&self) -> [(f64, f64); 4] {
@@ -549,6 +571,15 @@ pub struct PatternBrush {
pub end_swatch: Option<String>,
/// Scale in percent.
pub scale: f64,
/// How the scale varies along a stroke: `None` (Fixed) always `scale`; a mode that follows the
/// pen goes from `scale` to [`Self::scale_max`] over the ranges [`Variation`] gives, as an Art
/// brush's width does ([`ArtBrush::width_mode`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scale_mode: Option<Variation>,
/// The second scale (%) of a mode that follows the pen: at the heaviest pressure, upright, at
/// 180° or at the wheel's far end (`scale` without one).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scale_max: Option<f64>,
/// Space between tiles in percent of the tile width.
pub spacing: f64,
pub fit: PatternFit,
@@ -561,6 +592,15 @@ impl PatternBrush {
/// The ranges of the scale and of the spacing (%).
pub const SCALE_RANGE: (f64, f64) = (1.0, 10000.0);
pub const SPACING_RANGE: (f64, f64) = (0.0, 10000.0);
/// The scales (%) where the pen reads 0 and 1 for the scale's mode (the lightest and the
/// heaviest pressure, for Pressure): `scale` for both unless the scale follows the pen.
pub fn scale_range(&self) -> (f64, f64) {
match self.scale_mode {
Some(m) if m.follows_pen() => (self.scale, self.scale_max.unwrap_or(self.scale)),
_ => (self.scale, self.scale),
}
}
}
impl Default for PatternBrush {
@@ -584,6 +624,8 @@ impl Default for PatternBrush {
end_frame: None,
end_swatch: None,
scale: 100.0,
scale_mode: None,
scale_max: None,
spacing: 0.0,
fit: PatternFit::Stretch,
flip_along: false,
@@ -750,6 +792,8 @@ impl Brush {
s.scatter = within_pair(s.scatter, scatter, 0.0);
s.rotation = within_pair(s.rotation, rotation, 0.0);
s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0);
s.saturation_jitter = within(s.saturation_jitter, Scatter::SATURATION_JITTER_RANGE, 0.0);
s.brightness_jitter = within(s.brightness_jitter, Scatter::BRIGHTNESS_JITTER_RANGE, 0.0);
s.colorization.sanitize();
}
BrushKind::Art(a) => {
@@ -767,6 +811,11 @@ impl Brush {
}
BrushKind::Pattern(p) => {
p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0);
// The scale follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed.
if !p.scale_mode.is_some_and(Variation::follows_pen) {
p.scale_mode = None;
}
p.scale_max = p.scale_max.map(|s| within(s, PatternBrush::SCALE_RANGE, p.scale));
p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0);
for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] {
if frame.is_some_and(|f| !valid_tile_frame(f)) {
@@ -801,6 +850,9 @@ struct ScatterOptions {
modes: Option<[Variation; 4]>,
rotation_relative_to_path: bool,
colorization: Colorization,
hue_jitter: f64,
saturation_jitter: f64,
brightness_jitter: f64,
}
/// The Art brush fields a stroke can set for itself.
@@ -819,6 +871,8 @@ struct ArtOptions {
#[derive(Serialize, Deserialize)]
struct PatternOptions {
scale: f64,
scale_mode: Option<Variation>,
scale_max: Option<f64>,
spacing: f64,
fit: PatternFit,
flip_along: bool,
@@ -833,9 +887,20 @@ impl BrushKind {
pub fn stroke_option_keys(&self) -> &'static [&'static str] {
match self {
BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"],
BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"],
BrushKind::Scatter(_) => &[
"size",
"spacing",
"scatter",
"rotation",
"modes",
"rotation_relative_to_path",
"colorization",
"hue_jitter",
"saturation_jitter",
"brightness_jitter",
],
BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"],
BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"],
BrushKind::Pattern(_) => &["scale", "scale_mode", "scale_max", "spacing", "fit", "flip_along", "flip_across", "colorization"],
BrushKind::Bristle(_) => &[],
}
}
@@ -858,6 +923,9 @@ impl BrushKind {
modes: s.modes,
rotation_relative_to_path: s.rotation_relative_to_path,
colorization: s.colorization,
hue_jitter: s.hue_jitter,
saturation_jitter: s.saturation_jitter,
brightness_jitter: s.brightness_jitter,
}),
BrushKind::Art(a) => serde_json::to_value(ArtOptions {
width: a.width,
@@ -870,6 +938,8 @@ impl BrushKind {
}),
BrushKind::Pattern(p) => serde_json::to_value(PatternOptions {
scale: p.scale,
scale_mode: p.scale_mode,
scale_max: p.scale_max,
spacing: p.spacing,
fit: p.fit,
flip_along: p.flip_along,
@@ -890,6 +960,7 @@ impl BrushKind {
let o: ScatterOptions = serde_json::from_value(v)?;
(s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes);
(s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization);
(s.hue_jitter, s.saturation_jitter, s.brightness_jitter) = (o.hue_jitter, o.saturation_jitter, o.brightness_jitter);
}
BrushKind::Art(a) => {
let o: ArtOptions = serde_json::from_value(v)?;
@@ -898,8 +969,8 @@ impl BrushKind {
}
BrushKind::Pattern(p) => {
let o: PatternOptions = serde_json::from_value(v)?;
(p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) =
(o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization);
(p.scale, p.scale_mode, p.scale_max, p.spacing) = (o.scale, o.scale_mode, o.scale_max, o.spacing);
(p.fit, p.flip_along, p.flip_across, p.colorization) = (o.fit, o.flip_along, o.flip_across, o.colorization);
}
BrushKind::Bristle(_) => {}
}
@@ -1123,17 +1194,23 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name),
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
BrushKind::Pattern(p) => warp::pattern(p, bp, w, stroke),
};
let colorization = brush.kind.colorization();
for n in &mut out {
colorize(n, colorization, &stroke.paint);
}
// One piece per copy, in the order the copies run along the path.
if let BrushKind::Scatter(s) = &brush.kind
&& s.hue_jitter > 0.0
{
colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name));
if let BrushKind::Scatter(s) = &brush.kind {
if s.hue_jitter > 0.0 {
colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name));
}
if s.saturation_jitter > 0.0 {
colorize::jitter_saturations(&mut out, s.saturation_jitter, track::seed_of(bp, &brush.name));
}
if s.brightness_jitter > 0.0 {
colorize::jitter_brightnesses(&mut out, s.brightness_jitter, track::seed_of(bp, &brush.name));
}
}
leave_out_brushed(doc, &mut out, &mut Known::new());
out
+665
View File
@@ -1249,6 +1249,380 @@ fn hue_jitter_turns_type_every_colorization_and_linked_colors() {
}
}
/// A stroke's own hue, saturation and brightness jitter replace the brush's, as its other scatter
/// settings do, and are kept within their ranges.
#[test]
fn a_strokes_own_jitter_replaces_the_brushs() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
let pink = Color::rgb(0.8, 0.4, 0.4);
let b = sat_jittered(pink, Colorization::None, 0.0, 0.0);
let own =
stroke_pieces(&doc, &b, &path, &with_options(serde_json::json!({"hue_jitter": 30.0, "saturation_jitter": 40.0, "brightness_jitter": 20.0})));
let brushed = stroke_pieces(&doc, &bri_jittered(sat_jittered(pink, Colorization::None, 30.0, 40.0), 20.0), &path, &stroke(1.0));
assert_eq!(fill_colors(&own), fill_colors(&brushed));
assert!(fill_colors(&own).iter().any(|c| *c != pink));
// The brightness is part of what the stroke's own options give.
let without = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 30.0, 40.0), &path, &stroke(1.0));
assert_ne!(fill_colors(&own), fill_colors(&without));
for (key, given, kept) in [("saturation_jitter", 500.0, 100.0), ("brightness_jitter", 500.0, 100.0)] {
let options = serde_json::Map::from_iter([(key.to_string(), serde_json::json!(given))]);
assert_eq!(b.stroke_options_that_differ(&options).unwrap(), serde_json::Map::from_iter([(key.to_string(), serde_json::json!(kept))]));
}
// A stroke that sets 0 on a jittered brush draws the art's own color.
let still =
stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 40.0), &path, &with_options(serde_json::json!({"saturation_jitter": 0.0})));
assert!(!still.is_empty() && fill_colors(&still).iter().all(|c| *c == pink));
}
/// A scatter brush of rectangles filled `fill`, with `colorization`, `hue_jitter` and
/// `saturation_jitter`.
fn sat_jittered(fill: Color, colorization: Colorization, hue_jitter: f64, saturation_jitter: f64) -> Brush {
let mut b = jittered(fill, colorization, hue_jitter);
if let BrushKind::Scatter(s) = &mut b.kind {
s.saturation_jitter = saturation_jitter;
}
b
}
/// The HSB of an RGB color's own values.
fn rgb_hsb(c: &Color) -> [f32; 3] {
let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") };
vectorcraft_color::rgb_to_hsb([r, g, b])
}
#[test]
fn saturation_jitter_moves_each_copy_the_same_every_time() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
// A red at 50% saturation and 80% brightness.
let pink = Color::rgb(0.8, 0.4, 0.4);
let b = sat_jittered(pink, Colorization::None, 0.0, 40.0);
let out = stroke_pieces(&doc, &b, &path, &stroke(1.0));
assert_eq!(out.len(), 20);
assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors");
let colors = fill_colors(&out);
let hsb: Vec<[f32; 3]> = colors.iter().map(rgb_hsb).collect();
// Each copy's saturation is within 40 points of 50%; its hue and brightness stay.
assert!(hsb.iter().all(|[h, s, v]| hue_gap(*h, 0.0) < 1e-3 && (s - 0.5).abs() <= 0.4001 && near(f64::from(*v), 0.8, 1e-4)), "{hsb:?}");
assert!(hsb.iter().any(|[_, s, _]| *s > 0.55) && hsb.iter().any(|[_, s, _]| *s < 0.45), "the copies move both ways: {hsb:?}");
let distinct: std::collections::HashSet<String> = colors.iter().map(Color::to_hex).collect();
assert!(distinct.len() > 10, "each copy moves by its own amount: {distinct:?}");
// The copies stay where they were, at their size and angle.
let plain = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 0.0), &path, &stroke(1.0));
let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::<Vec<_>>();
assert_eq!(boxes(&out), boxes(&plain));
// Another path draws other amounts.
let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0)));
assert_ne!(other, colors);
// At 100 the copies reach gray or full saturation and go no further.
let full: Vec<f32> = fill_colors(&stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 100.0), &path, &stroke(1.0)))
.iter()
.map(|c| rgb_hsb(c)[1])
.collect();
assert!(full.iter().all(|s| (0.0..=1.0).contains(s)), "{full:?}");
assert!(full.iter().any(|s| *s < 1e-6) && full.iter().any(|s| *s > 1.0 - 1e-6), "{full:?}");
// Saturation jitter leaves the hue jitter's amounts as they were.
let red = Color::rgb(1.0, 0.0, 0.0);
let hue_only = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 0.0), &path, &stroke(1.0)));
let both = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 50.0), &path, &stroke(1.0)));
assert_eq!(both.len(), hue_only.len());
assert_ne!(both, hue_only);
for (b, h) in both.iter().zip(&hue_only) {
assert!(hue_gap(rgb_hsb(b)[0], rgb_hsb(h)[0]) < 0.01, "{b:?} from {h:?}");
}
}
#[test]
fn saturation_jitter_of_zero_changes_nothing() {
let pink = Color::rgb(0.8, 0.4, 0.4);
let out = stroke_pieces(&Document::new(1.0, 1.0), &sat_jittered(pink, Colorization::None, 0.0, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0));
assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == pink));
// A brush without saturation jitter is saved as before, and one saved before reads as 0.
let v = serde_json::to_value(sat_jittered(pink, Colorization::None, 0.0, 0.0)).unwrap();
assert!(v.get("saturation_jitter").is_none(), "{v}");
let mut old = serde_json::to_value(sat_jittered(pink, Colorization::None, 0.0, 25.0)).unwrap();
assert_eq!(old.as_object_mut().unwrap().remove("saturation_jitter"), Some(serde_json::json!(25.0)));
let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.saturation_jitter, 0.0, "a brush saved without the key reads as 0");
let mut with = v.clone();
with["saturation_jitter"] = serde_json::json!(25.0);
let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.saturation_jitter, 25.0);
// Values outside 0..100 are clamped.
for (given, kept) in [(250.0, 100.0), (-5.0, 0.0)] {
let mut v = v.clone();
v["saturation_jitter"] = serde_json::json!(given);
let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.saturation_jitter, kept, "{given}");
}
}
#[test]
fn saturation_jitter_moves_after_the_colorization_in_each_model() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
// Tints: black art takes the blue stroke color, whose saturation then moves.
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
let hsb: Vec<[f32; 3]> =
fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 30.0), &path, &blue)).iter().map(rgb_hsb).collect();
assert!(!hsb.is_empty() && hsb.iter().all(|[h, s, _]| hue_gap(*h, 240.0) < 1e-3 && *s >= 0.6999), "{hsb:?}");
assert!(hsb.iter().any(|[_, s, _]| *s < 0.97), "{hsb:?}");
// Black, white and grays have no saturation to move, in every model.
for key in
[Color::rgb(0.5, 0.5, 0.5), Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4), Color::lab(60.0, 0.0, 0.0)]
{
let key = StrokeLayer::new(Paint::solid(key), 1.0);
let moved = stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 100.0), &path, &key);
let still = stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 0.0), &path, &key);
assert_eq!(fill_colors(&moved), fill_colors(&still), "{key:?}");
}
// A process color stays a process color with its K kept, moved over its C, M and Y.
let cmyk = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::cmyk(0.0, 0.6, 0.6, 0.25), Colorization::None, 0.0, 30.0), &path, &stroke(1.0)));
assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 0.6, 0.6, 0.25)), "{cmyk:?}");
for c in &cmyk {
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
// No cyan, as before, and magenta equal to yellow: the hue stays; the ink is within 30 points.
assert!(k == 0.25 && near(f64::from(c), 0.0, 1e-5) && near(f64::from(m), f64::from(y), 1e-5), "{c} {m} {y} {k}");
assert!((m - 0.6).abs() <= 0.3001, "{m}");
}
// A Lab color keeps its lightness and hue angle; its chroma moves within 20 of its 50.
let lab = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 0.0, 20.0), &path, &stroke(1.0)));
assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}");
for c in &lab {
let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") };
let chroma = f64::from(a.hypot(b));
assert!(l == 50.0 && (chroma - 50.0).abs() <= 20.001 && near(f64::from(b.atan2(a)), 30f64.atan2(40.0), 1e-4), "{c:?}");
}
// A chroma that grows stops where a and b reach their largest.
let vivid = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::lab(50.0, 120.0, 0.0), Colorization::None, 0.0, 100.0), &path, &stroke(1.0)));
assert!(vivid.iter().all(|c| matches!(*c, Color::Lab { a, b, .. } if (0.0..=127.0001).contains(&a) && b.abs() < 1e-4)), "{vivid:?}");
assert!(vivid.iter().any(|c| matches!(*c, Color::Lab { a, .. } if a > 126.999)), "{vivid:?}");
}
/// Saturation jitter moves type's characters and a color linked to a swatch (which loses the
/// link); a pattern paint stays.
#[test]
fn saturation_jitter_moves_type_and_linked_colors() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let typed = |saturation_jitter| Brush {
name: "s".into(),
kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), saturation_jitter, ..Default::default() }),
};
let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0)));
let moved = run_paints(&stroke_pieces(&doc, &typed(60.0), &path, &stroke(1.0)));
assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}");
assert_eq!(moved.len(), still.len());
assert!(moved.iter().any(|p| *p != (red.clone(), red.clone())), "the characters move: {moved:?}");
assert!(moved.iter().all(|(f, s)| f == s), "a copy's character fill and stroke move by the same amount: {moved:?}");
let linked = Paint::Solid { color: Color::rgb(0.8, 0.4, 0.4), swatch: Some("Rose".into()), tint: 1.0 };
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
let mut art = rect_art(10.0, 4.0);
art.appearance.set_fill(linked.clone());
art.appearance.set_stroke(pattern.clone());
let b = |saturation_jitter| Brush {
name: "s".into(),
kind: BrushKind::Scatter(Scatter { art: art.clone(), saturation_jitter, ..Default::default() }),
};
let moved = stroke_pieces(&doc, &b(50.0), &path, &stroke(1.0));
assert!(!moved.is_empty());
assert!(moved.iter().any(|n| n.appearance.fill_paint().color() != Some(Color::rgb(0.8, 0.4, 0.4))), "the linked color moves");
for n in &moved {
assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint());
assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern));
}
}
/// `b` (a scatter brush) with `brightness_jitter`.
fn bri_jittered(mut b: Brush, brightness_jitter: f64) -> Brush {
if let BrushKind::Scatter(s) = &mut b.kind {
s.brightness_jitter = brightness_jitter;
}
b
}
#[test]
fn brightness_jitter_moves_each_copy_the_same_every_time() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
// A red at 50% saturation and 80% brightness.
let pink = Color::rgb(0.8, 0.4, 0.4);
let b = bri_jittered(sat_jittered(pink, Colorization::None, 0.0, 0.0), 15.0);
let out = stroke_pieces(&doc, &b, &path, &stroke(1.0));
assert_eq!(out.len(), 20);
assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors");
let colors = fill_colors(&out);
let hsb: Vec<[f32; 3]> = colors.iter().map(rgb_hsb).collect();
// Each copy's brightness is within 15 points of 80%; its hue and saturation stay.
assert!(hsb.iter().all(|[h, s, v]| hue_gap(*h, 0.0) < 1e-3 && near(f64::from(*s), 0.5, 1e-4) && (v - 0.8).abs() <= 0.1501), "{hsb:?}");
assert!(hsb.iter().any(|[_, _, v]| *v > 0.85) && hsb.iter().any(|[_, _, v]| *v < 0.75), "the copies move both ways: {hsb:?}");
let distinct: std::collections::HashSet<String> = colors.iter().map(Color::to_hex).collect();
assert!(distinct.len() > 10, "each copy moves by its own amount: {distinct:?}");
// The copies stay where they were, at their size and angle.
let plain = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 0.0), &path, &stroke(1.0));
let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::<Vec<_>>();
assert_eq!(boxes(&out), boxes(&plain));
// Another path draws other amounts.
let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0)));
assert_ne!(other, colors);
// At 100 the copies reach black or full brightness and go no further.
let full: Vec<f32> =
fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(pink, Colorization::None, 0.0, 0.0), 100.0), &path, &stroke(1.0)))
.iter()
.map(|c| rgb_hsb(c)[2])
.collect();
assert!(full.iter().all(|v| (0.0..=1.0).contains(v)), "{full:?}");
assert!(full.iter().any(|v| *v < 1e-6) && full.iter().any(|v| *v > 1.0 - 1e-6), "{full:?}");
// Brightness jitter leaves the hue and saturation jitter's amounts as they were.
let red = Color::rgb(1.0, 0.0, 0.0);
let hue_sat = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 50.0), &path, &stroke(1.0)));
let all = fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(red, Colorization::None, 90.0, 50.0), 30.0), &path, &stroke(1.0)));
assert_eq!(all.len(), hue_sat.len());
assert_ne!(all, hue_sat);
for (a, h) in all.iter().zip(&hue_sat) {
let ([ha, sa, _], [hh, sh, _]) = (rgb_hsb(a), rgb_hsb(h));
assert!(hue_gap(ha, hh) < 0.01 && (sa - sh).abs() < 1e-4, "{a:?} from {h:?}");
}
}
#[test]
fn brightness_jitter_of_zero_changes_nothing() {
let pink = Color::rgb(0.8, 0.4, 0.4);
let plain = sat_jittered(pink, Colorization::None, 0.0, 0.0);
let out = stroke_pieces(&Document::new(1.0, 1.0), &bri_jittered(plain.clone(), 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0));
assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == pink));
// A brush without brightness jitter is saved as before, and one saved before reads as 0.
let v = serde_json::to_value(&plain).unwrap();
assert!(v.get("brightness_jitter").is_none(), "{v}");
let mut old = serde_json::to_value(bri_jittered(plain.clone(), 25.0)).unwrap();
assert_eq!(old.as_object_mut().unwrap().remove("brightness_jitter"), Some(serde_json::json!(25.0)));
let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.brightness_jitter, 0.0, "a brush saved without the key reads as 0");
let mut with = v.clone();
with["brightness_jitter"] = serde_json::json!(25.0);
let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.brightness_jitter, 25.0);
// Values outside 0..100 are clamped.
for (given, kept) in [(250.0, 100.0), (-5.0, 0.0)] {
let mut v = v.clone();
v["brightness_jitter"] = serde_json::json!(given);
let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.brightness_jitter, kept, "{given}");
}
}
#[test]
fn brightness_jitter_moves_after_the_colorization_in_each_model() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
let jittered_fills = |art: Color, colorization: Colorization, amount: f64, key: &StrokeLayer| {
fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(art, colorization, 0.0, 0.0), amount), &path, key))
};
// Tints: black art takes the blue stroke color, whose brightness then moves.
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
let hsb: Vec<[f32; 3]> = jittered_fills(Color::BLACK, Colorization::Tints, 30.0, &blue).iter().map(rgb_hsb).collect();
assert!(!hsb.is_empty() && hsb.iter().all(|[h, s, v]| hue_gap(*h, 240.0) < 1e-3 && near(f64::from(*s), 1.0, 1e-4) && *v >= 0.6999), "{hsb:?}");
assert!(hsb.iter().any(|[_, _, v]| *v < 0.97), "{hsb:?}");
// White, black and grays move too, and stay neutral. RGB white gets darker.
let white: Vec<[f32; 3]> = jittered_fills(Color::WHITE, Colorization::None, 30.0, &stroke(1.0)).iter().map(rgb_hsb).collect();
assert!(white.iter().all(|[_, s, v]| *s == 0.0 && *v >= 0.6999) && white.iter().any(|[_, _, v]| *v < 0.95), "{white:?}");
// A gray's ink moves within 20 points of its 40%.
let gray = StrokeLayer::new(Paint::solid(Color::gray(0.4)), 1.0);
let grays = jittered_fills(Color::BLACK, Colorization::Tints, 20.0, &gray);
assert!(grays.iter().all(|c| matches!(*c, Color::Gray { k } if (k - 0.4).abs() <= 0.2001)), "{grays:?}");
assert!(grays.iter().any(|c| *c != Color::gray(0.4)), "{grays:?}");
// Black ink alone stays black ink alone, lighter by its K.
let k_only = jittered_fills(Color::cmyk(0.0, 0.0, 0.0, 1.0), Colorization::None, 30.0, &stroke(1.0));
assert!(k_only.iter().all(|c| matches!(*c, Color::Cmyk { c, m, y, k } if c == 0.0 && m == 0.0 && y == 0.0 && k >= 0.6999)), "{k_only:?}");
assert!(k_only.iter().any(|c| matches!(*c, Color::Cmyk { k, .. } if k < 0.97)), "{k_only:?}");
// A process color with room in its K moves by its K and keeps its C, M and Y.
let cmyk = jittered_fills(Color::cmyk(0.0, 0.6, 0.6, 0.25), Colorization::None, 20.0, &stroke(1.0));
assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 0.6, 0.6, 0.25)), "{cmyk:?}");
for c in &cmyk {
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
assert!(c == 0.0 && m == 0.6 && y == 0.6 && (k - 0.25).abs() <= 0.2001, "{c} {m} {y} {k}");
}
// One brighter than its C, M and Y show with no K loses its K and takes less ink, its hue and
// saturation kept (full magenta and yellow, cyan the brightness).
let deep = jittered_fills(Color::cmyk(0.4, 1.0, 1.0, 0.0), Colorization::None, 30.0, &stroke(1.0));
let mut ways = (false, false);
for c in &deep {
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
assert!(near(f64::from(m), 1.0, 1e-5) && near(f64::from(y), 1.0, 1e-5), "{c} {m} {y} {k}");
if k > 0.0 {
assert!(c == 0.4 && k <= 0.5001, "darker: {c} {k}");
ways.0 = true;
} else {
assert!((0.0999..=0.4).contains(&c), "brighter: {c}");
ways.1 |= c < 0.4;
}
}
assert!(ways.0 && ways.1, "the copies move both ways: {deep:?}");
// A Lab color keeps its a and b; its lightness moves within 20 of its 50.
let lab = jittered_fills(Color::lab(50.0, 40.0, 30.0), Colorization::None, 20.0, &stroke(1.0));
assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}");
assert!(lab.iter().all(|c| matches!(*c, Color::Lab { l, a, b } if a == 40.0 && b == 30.0 && (l - 50.0).abs() <= 20.001)), "{lab:?}");
}
/// A swatch-linked color already at the end a copy's saturation or brightness moves toward stays as
/// it is and keeps its link; the copies that move it lose the link.
#[test]
fn jitter_at_a_limit_keeps_the_swatch_link() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
// Full red (full saturation and brightness), full magenta and yellow ink, and a Lab red whose a
// is at its largest: saturation that grows and brightness that grows leave them as they are.
for (color, saturation_jitter, brightness_jitter) in [
(Color::rgb(1.0, 0.0, 0.0), 50.0, 0.0),
(Color::cmyk(0.0, 1.0, 1.0, 0.0), 50.0, 0.0),
(Color::lab(50.0, 127.0, 0.0), 50.0, 0.0),
(Color::rgb(1.0, 0.0, 0.0), 0.0, 50.0),
(Color::lab(100.0, 20.0, 10.0), 0.0, 50.0),
] {
let linked = Paint::Solid { color, swatch: Some("Spot".into()), tint: 1.0 };
let mut art = rect_art(10.0, 4.0);
art.appearance.set_fill(linked.clone());
let mut s = Scatter { art, saturation_jitter, ..Default::default() };
s.brightness_jitter = brightness_jitter;
let out = stroke_pieces(&doc, &Brush { name: "s".into(), kind: BrushKind::Scatter(s) }, &path, &stroke(1.0));
let (mut kept, mut moved) = (0, 0);
for n in &out {
match n.appearance.fill_paint() {
p if p == linked => kept += 1,
Paint::Solid { color: c, swatch: None, .. } if c != color => moved += 1,
p => panic!("{color:?}: {p:?}"),
}
}
assert!(kept > 0 && moved > 0, "{color:?}: {kept} kept, {moved} moved");
}
}
/// A hue or saturation jitter too small to move a Lab color's components gives each copy the color
/// it had, and the copies keep the swatch link.
#[test]
fn jitter_too_small_to_change_a_color_keeps_the_swatch_link() {
let linked = Paint::Solid { color: Color::lab(50.0, 64.0, 0.0), swatch: Some("Spot".into()), tint: 1.0 };
// 1e-50 degrees turns a and b by less than an f32 holds; 1e-6 points scales the chroma by
// 1 + 1.6e-8, which rounds back to the same f32 components.
type Jitter = fn(&mut [Node], f64, u64);
let jitters: [(&str, Jitter, f64); 2] = [("hue", crate::colorize::jitter_hues, 1e-50), ("saturation", crate::colorize::jitter_saturations, 1e-6)];
for (name, jitter, amount) in jitters {
let mut copies: Vec<Node> = (0..8)
.map(|_| {
let mut art = rect_art(10.0, 4.0);
art.appearance.set_fill(linked.clone());
art
})
.collect();
jitter(&mut copies, amount, 7);
for n in &copies {
assert_eq!(n.appearance.fill_paint(), linked, "{name}");
}
}
}
/// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its
/// swatch links.
#[test]
@@ -2031,6 +2405,297 @@ fn art_brush_width_follows_tilt_bearing_and_rotation() {
assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]);
}
/// A pattern brush with `scale`, `scale_mode` and `scale_max`, its 10 × 4 pt side tile on `fit`.
fn scaled_pattern(fit: PatternFit, corners: bool, scale: f64, mode: Option<Variation>, max: Option<f64>) -> Brush {
let mut b = pattern_brush(fit, corners);
if let BrushKind::Pattern(p) = &mut b.kind {
(p.scale, p.scale_mode, p.scale_max) = (scale, mode, max);
}
b
}
/// The bounds of each piece, left to right.
fn piece_spans(out: &[Node]) -> Vec<Rect> {
let mut spans: Vec<Rect> = out.iter().filter_map(Node::geometric_bounds).collect();
spans.sort_by(|a, b| a.x0.total_cmp(&b.x0));
spans
}
/// Pattern Brush Options: with Scale on Pressure the tiles go from Scale at the lightest pen
/// pressure to the second scale at the heaviest, taller and longer along the stroke where the pen
/// pressed harder, and each Fit still fits them to the path.
#[test]
fn pattern_brush_scale_follows_the_pressure() {
let bp = line(0.0, 0.0, 200.0, 0.0);
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
// 4 pt tall tiles at 50 %: 1 pt either side at the lightest; at 300 %: 6 pt at the heaviest.
let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp);
assert!(near(half_width(&out, 0.0, 1.0), 1.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
assert!(near(half_width(&out, 199.0, 200.0), 6.0, 0.2), "{}", half_width(&out, 199.0, 200.0));
assert!(near(half_width(&out, 99.0, 101.0), 3.5, 0.2), "{}", half_width(&out, 99.0, 101.0));
// Stretch to Fit fills the path, and the tiles grow longer along it.
let spans = piece_spans(&out);
assert!(near(bounds(&out).x0, 0.0, 1e-6) && near(bounds(&out).x1, 200.0, 1e-6), "{:?}", bounds(&out));
assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{spans:?}");
assert!(spans.last().unwrap().width() > 4.0 * spans[0].width(), "{spans:?}");
// The stroke weight scales it.
let out =
draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &StrokeLayer { width: 2.0, ..ramp.clone() });
assert!(near(half_width(&out, 199.0, 200.0), 12.0, 0.4), "{}", half_width(&out, 199.0, 200.0));
// Without recorded pressure, half way between the two scales.
let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &stroke(1.0));
assert!(near(bounds(&out).height(), 7.0, 1e-6), "{:?}", bounds(&out));
// With an even pressure, Add Space with spacing places as many tiles as the one scale that
// pressure gives: the spacing counts when the tiles are counted again.
let even = pressed(vec![(0.0, 0.5), (1.0, 0.5)]);
let spaced = |mode: Option<Variation>, max: Option<f64>| {
let mut b = scaled_pattern(PatternFit::AddSpace, false, if max.is_some() { 50.0 } else { 100.0 }, mode, max);
if let BrushKind::Pattern(p) = &mut b.kind {
p.spacing = 100.0;
}
piece_spans(&draw(&b, &even)).len()
};
assert_eq!(spaced(Some(Variation::Pressure), Some(150.0)), spaced(None, None));
// With spacing, Stretch to Fit still fills the path and Approximate Path still centers the
// tiles, with the gaps between them counted and none after the last.
for fit in [PatternFit::Stretch, PatternFit::Approximate] {
let mut b = scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0));
if let BrushKind::Pattern(p) = &mut b.kind {
p.spacing = 50.0;
}
let spans = piece_spans(&draw(&b, &ramp));
let (first, last) = (spans[0], spans[spans.len() - 1]);
assert!(spans.len() > 1 && near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{fit:?}: {spans:?}");
if fit == PatternFit::Stretch {
assert!(near(first.x0, 0.0, 1e-6) && near(last.x1, 200.0, 1e-6), "{spans:?}");
}
}
// Add Space to Fit keeps the tiles apart within the path; Approximate Path centers them on it.
for fit in [PatternFit::AddSpace, PatternFit::Approximate] {
let out = draw(&scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp);
let spans = piece_spans(&out);
assert!(spans.len() > 1 && spans.windows(2).all(|w| w[1].x0 >= w[0].x1 - 1e-6), "{fit:?}: {spans:?}");
assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{fit:?}: {spans:?}");
let (first, last) = (spans[0], spans[spans.len() - 1]);
if fit == PatternFit::AddSpace {
assert!(first.x0 >= -1e-6 && last.x1 <= 200.0 + 1e-6, "{spans:?}");
} else {
assert!(near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{spans:?}");
}
}
}
/// Pattern Brush Options: Scale on Tilt, Bearing, Rotation or Stylus Wheel reads only its own
/// input, half way without it; Fixed, a mode without a second scale and equal scales draw as a
/// brush without the setting does.
#[test]
fn pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel() {
let bp = line(0.0, 0.0, 100.0, 0.0);
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
let brush = |mode: Variation| scaled_pattern(PatternFit::Stretch, false, 50.0, Some(mode), Some(300.0));
let wheel = |v: f64| StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, v), (1.0, v)] }), ..stroke(1.0) };
// 4 pt tiles: 2 pt tall at 50 %, 12 pt at 300 %.
for (mode, st, height) in [
(Variation::Tilt, posed(Some(0.0), None, None), 12.0),
(Variation::Tilt, posed(Some(1.0), None, None), 2.0),
(Variation::Bearing, posed(Some(0.5), Some(90.0), None), 9.5),
(Variation::Rotation, posed(None, None, Some(-90.0)), 4.5),
(Variation::StylusWheel, wheel(1.0), 12.0),
(Variation::StylusWheel, wheel(0.0), 2.0),
// Without its own input, half way.
(Variation::Tilt, posed(None, Some(90.0), Some(90.0)), 7.0),
(Variation::Bearing, posed(Some(0.0), None, Some(90.0)), 7.0),
(Variation::Rotation, posed(Some(0.0), Some(90.0), None), 7.0),
(Variation::StylusWheel, pressed(vec![(0.0, 1.0), (1.0, 1.0)]), 7.0),
(Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0)), 7.0),
] {
let h = bounds(&draw(&brush(mode), &st)).height();
assert!(near(h, height, 1e-6), "{mode:?}: {h}");
}
// Fixed, a mode without a second scale, and a second scale equal to the first draw what the
// brush draws without them.
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
let plain = draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &ramp);
for (mode, max) in [(None, Some(300.0)), (Some(Variation::Pressure), None), (Some(Variation::Pressure), Some(50.0))] {
assert_eq!(draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, mode, max), &ramp), plain, "{mode:?} {max:?}");
}
let saved = serde_json::to_value(scaled_pattern(PatternFit::Stretch, false, 50.0, None, None)).unwrap();
assert!(saved.get("scale_mode").is_none() && saved.get("scale_max").is_none(), "{saved}");
// A mode the scale does not take is read as Fixed, and the second scale is kept within range.
let lib = parse_library(&serde_json::json!([
{"name": "a", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "random", "scale_max": 1e308},
{"name": "b", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "stylusWheel", "scale_max": 0.0},
]));
let [BrushKind::Pattern(a), BrushKind::Pattern(b)] = [&lib[0].kind, &lib[1].kind] else { panic!("{lib:?}") };
assert_eq!((a.scale_mode, a.scale_max, b.scale_mode, b.scale_max), (None, Some(10000.0), Some(Variation::StylusWheel), Some(1.0)));
// A stroke sets its own mode and second scale.
let mut own = serde_json::Map::new();
own.insert("scale_mode".into(), serde_json::json!("pressure"));
own.insert("scale_max".into(), serde_json::json!(300.0));
let edited = scaled_pattern(PatternFit::Stretch, false, 100.0, None, None).with_stroke_options(&own).unwrap();
assert!(matches!(&edited.kind, BrushKind::Pattern(p) if p.scale_range() == (100.0, 300.0)), "{edited:?}");
}
/// A pattern brush whose scale follows the pen keeps its start, end and corner tiles at the scale
/// where they are, on open and closed paths, and stays finite at the ends of the scale's range.
#[test]
fn pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles() {
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
let doc = Document::new(1.0, 1.0);
// Start and end tiles, 6 × 4 pt: the start tile at the light end is smaller than the end tile.
let mut ends = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0));
if let BrushKind::Pattern(p) = &mut ends.kind {
(p.start, p.end) = (Some(rect_art(6.0, 4.0)), Some(rect_art(6.0, 4.0)));
}
let out = stroke_pieces(&doc, &ends, &line(0.0, 0.0, 200.0, 0.0), &ramp);
let (start, end) = (out[0].geometric_bounds().unwrap(), out[1].geometric_bounds().unwrap());
assert!(near(start.x0, 0.0, 1e-6) && near(end.x1, 200.0, 1e-6), "{start:?} {end:?}");
assert!(start.width() < 3.5 && end.width() > 17.0 && start.height() < end.height() / 4.0, "{start:?} {end:?}");
// A closed rectangle with corner tiles, on each Fit, and the scale's range at its ends.
let mut rect = BezPath::new();
rect.move_to((0.0, 0.0));
rect.line_to((100.0, 0.0));
rect.line_to((100.0, 60.0));
rect.line_to((0.0, 60.0));
rect.close_path();
for fit in [PatternFit::Stretch, PatternFit::AddSpace, PatternFit::Approximate] {
for (scale, max) in [(50.0, 300.0), (1.0, 10000.0), (10000.0, 1.0)] {
for bp in [&rect, &line(0.0, 0.0, 3.0, 0.0)] {
let b = scaled_pattern(fit, true, scale, Some(Variation::Pressure), Some(max));
let out = stroke_pieces(&doc, &b, bp, &ramp);
assert!(!out.is_empty(), "{fit:?} {scale} {max}");
let r = bounds(&out);
assert!([r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()), "{fit:?} {scale} {max}: {r:?}");
}
}
}
// On the rectangle the corner tiles grow with the pressure: the first corner's tile is smaller
// than the last one's.
let b = scaled_pattern(PatternFit::Stretch, true, 50.0, Some(Variation::Pressure), Some(300.0));
let out = stroke_pieces(&doc, &b, &rect, &ramp);
let fixed = stroke_pieces(&doc, &scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &rect, &ramp);
assert_ne!(out, fixed);
let corner = |n: &Node| n.geometric_bounds().map_or(0.0, |r| r.width().max(r.height()));
let corners: Vec<f64> = out.iter().take(4).map(corner).collect();
assert!(corners[0] < corners[3], "{corners:?}");
// The side tiles start half the corner tile beside them away from the corner: 1.5 pt from the
// first corner, where the 6 pt corner tile is drawn at 50 %, not half the largest corner tile.
let first_side = out.get(4).and_then(Node::geometric_bounds);
assert!(first_side.is_some_and(|r| near(r.x0, 1.5, 1e-3)), "{first_side:?}");
}
/// A start or end tile whose scale follows the pen is placed where it is as long as the scale at
/// its middle, even when the scale rises again further along and the tile would not fit at the
/// whole run's length.
#[test]
fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_falls_back() {
let doc = Document::new(1.0, 1.0);
let bp = line(0.0, 0.0, 100.0, 0.0);
// From 100 % to 10000 %: 300 % from 5 to 20 pt, 10000 % from 50 pt on; mirrored for the end.
let q = 2.0 / 99.0;
for (start, points, span) in [
(true, vec![(0.0, 0.0), (0.05, q), (0.2, q), (0.5, 1.0), (1.0, 1.0)], (0.0, 18.0)),
(false, vec![(0.0, 1.0), (0.5, 1.0), (0.8, q), (0.95, q), (1.0, 0.0)], (82.0, 100.0)),
] {
let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(10000.0));
if let BrushKind::Pattern(p) = &mut b.kind {
let tile = Some(rect_art(6.0, 4.0));
(p.start, p.end) = if start { (tile, None) } else { (None, tile) };
}
// The 6 pt tile at 300 %: 18 pt long, its middle where the scale is 300 %.
let out = stroke_pieces(&doc, &b, &bp, &pressed(points));
let r = out.first().and_then(Node::geometric_bounds);
assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}");
}
// 400 % at the start, 100 % from 15 to 20 pt, 400 % from 40 pt on, mirrored for the end: a 30 pt
// tile at 100 % fits at its middle, although at the scale at its first length's middle it is as
// long as that length.
for (start, points, span) in [
(true, vec![(0.0, 1.0), (0.15, 0.0), (0.2, 0.0), (0.4, 1.0), (1.0, 1.0)], (0.0, 30.0)),
(false, vec![(0.0, 1.0), (0.6, 1.0), (0.8, 0.0), (0.85, 0.0), (1.0, 1.0)], (70.0, 100.0)),
] {
let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(400.0));
if let BrushKind::Pattern(p) = &mut b.kind {
let tile = Some(rect_art(30.0, 4.0));
(p.start, p.end) = if start { (tile, None) } else { (None, tile) };
}
let out = stroke_pieces(&doc, &b, &bp, &pressed(points));
let r = out.first().and_then(Node::geometric_bounds);
assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}");
}
}
/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale
/// recorded at the end of the stroke there, where the tile is drawn.
#[test]
fn pattern_brush_scale_from_the_pen_wraps_before_a_closed_paths_start() {
let doc = Document::new(1.0, 1.0);
let b = scaled_pattern(PatternFit::Approximate, false, 50.0, Some(Variation::Pressure), Some(300.0));
// Light over the first 90 % of the stroke, heavy at its end.
let st = pressed(vec![(0.0, 0.0), (0.9, 0.0), (1.0, 1.0)]);
let mut before = 0;
for r in (100..=120).map(f64::from) {
// A circle of radius `r` as 720 sides, from (r, 0) on towards +y.
let mut bp = BezPath::new();
bp.move_to((r, 0.0));
for i in 1..720 {
let a = std::f64::consts::TAU * f64::from(i) / 720.0;
bp.line_to((r * a.cos(), r * a.sin()));
}
bp.close_path();
let out = stroke_pieces(&doc, &b, &bp, &st);
let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("{r}: no tiles") };
if first.y0 < -0.5 {
// The 4 pt tall tile is 2 pt tall at the light 50 % and nearly 12 pt at the heavy end.
before += 1;
assert!(first.x1 > r + 3.0, "{r}: {first:?}");
}
}
assert!(before > 0, "no first tile starts before the path's start");
}
/// On a closed path, a tile over the path's start follows the scale on both sides of the start,
/// even when the scale is the same at the tile's ends, its middle and every pen sample within it.
#[test]
fn pattern_brush_scale_from_the_pen_changes_where_a_closed_path_wraps_round() {
let doc = Document::new(1.0, 1.0);
let mut b = scaled_pattern(PatternFit::Approximate, false, 100.0, Some(Variation::Pressure), Some(300.0));
if let BrushKind::Pattern(p) = &mut b.kind {
p.side = rect_art(54.0, 4.0);
}
// A closed path 256 pt long without corners, from (0, 0) along +x: its sides in each quarter
// turn, and the same turned three more times.
let quarter = [(28.0, 0.0), (12.0, 5.0), (4.0, 3.0), (3.0, 4.0), (5.0, 12.0)];
let mut bp = BezPath::new();
let mut at = (0.0, 0.0);
bp.move_to(at);
for turn in 0..4 {
for &(x, y) in &quarter {
let (dx, dy) = match turn {
0 => (x, y),
1 => (-y, x),
2 => (-x, -y),
_ => (y, -x),
};
at = (at.0 + dx, at.1 + dy);
if at != (0.0, 0.0) {
bp.line_to(at);
}
}
}
bp.close_path();
// 100 % up to 4 pt before the end, rising to 300 % at the end. Approximate Path places five
// 54 pt tiles, the first from 7 pt before the start: at 100 % at both its ends, its middle and
// the samples at 4 pt before the start and at the start, but larger from 4 pt before it.
let st = pressed(vec![(0.0, 0.0), (252.0 / 256.0, 0.0), (1.0, 1.0)]);
let out = stroke_pieces(&doc, &b, &bp, &st);
let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("no tiles") };
// The 4 pt tall tile is 2 pt either side of the path at 100 %, and 5 pt at 1 pt before the
// start, where the scale is 250 %.
assert!(first.y0 < -3.5, "{first:?}");
}
/// Definitions from files and commands are kept within their ranges.
#[test]
fn sanitize_keeps_values_within_their_ranges() {
+284 -11
View File
@@ -649,6 +649,253 @@ fn tile_on(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, cross: f64) -> Opti
bend(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), cross)
}
/// A tile placed on [s0, s1] of the track, `k(s)` across at arc length `s` when the scale varies
/// (`marks`: the arc lengths of the recorded pen samples in order, between which the scale runs
/// in a straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it
/// is too when the scale is the same at both ends of the span, at every sample within it and, at
/// a closed track's start within it, on both sides of the start.
fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) -> f64, marks: Option<&[f64]>) -> Option<Node> {
let mid = k((s0 + s1) / 2.0);
// Only the samples within the span are looked at.
let within = |marks: &[f64]| {
let from = marks.partition_point(|&s| s <= s0);
let to = from + marks[from..].partition_point(|&s| s < s1);
marks[from..to].iter().all(|&s| k(s) == mid)
};
// A closed track's scale goes from the one at its end to the one at its start where it wraps
// round, so a span over its start (or a track's length before or after it) takes both.
let l = t.len();
let seam = t.closed && l > 0.0 && (s0 / l).ceil() <= (s1 / l).floor();
let ends = || !seam || (k(0.0) == mid && k(l) == mid);
let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && within(marks) && ends();
if mid <= 0.0 || marks.is_none_or(even) {
return tile_on(t, tile, s0, s1, mid);
}
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid)
}
/// The most side tiles a run of a pattern brush places.
const MAX_TILES: usize = 20000;
/// How many times a pattern brush whose scale varies measures its side tiles again where the fit
/// puts them.
const REFITS: usize = 3;
/// How many times a pattern brush whose scale varies halves the range a start or end tile's
/// length lies in.
const END_SOLVE_STEPS: usize = 48;
/// How many evenly spaced lengths a pattern brush whose scale varies tries for a start or end
/// tile before it halves the range the tile's length lies in.
const END_SCAN_STEPS: usize = 64;
/// The side tiles of a pattern brush on a run `avail` long from `a` when the scale varies along
/// it: each tile's length and the gap after it, as `natural` gives them at the tile's start, and
/// how many tiles fit whole and what fraction of the next one fits after them. The tiles include
/// that next one when there is room for part of it.
fn varied_tiles(a: f64, avail: f64, natural: &dyn Fn(f64) -> (f64, f64)) -> (Vec<(f64, f64)>, f64) {
let mut tiles = vec![];
let mut pos = 0.0;
while tiles.len() < MAX_TILES {
let (w, g) = natural(a + pos);
if !(w > 1e-9 && w.is_finite() && g.is_finite() && g >= 0.0) {
break;
}
tiles.push((w, g));
if pos + w > avail {
let whole = (tiles.len() - 1) as f64;
return (tiles, whole + ((avail - pos + g) / (w + g)).clamp(0.0, 1.0));
}
pos += w + g;
}
let whole = tiles.len() as f64;
(tiles, whole)
}
/// The size factor of a pattern brush's tiles at `weight` where its scale's pen input is `p`
/// (0 at the first scale, 1 at the second).
fn pattern_scale_at(pb: &PatternBrush, weight: f64, p: f64) -> f64 {
let (light, heavy) = pb.scale_range();
weight * (light + (heavy - light) * p).max(1.0) / 100.0
}
/// A pattern brush's size factor on `stroke` at `weight`, and whether it varies along the stroke.
/// A stroke with no recording of the input the scale follows is drawn at one scale, the one that
/// input's missing value gives.
fn pattern_scale(pb: &PatternBrush, weight: f64, stroke: &StrokeLayer) -> (f64, bool) {
let (light, heavy) = pb.scale_range();
match pb.scale_mode {
Some(m) if light != heavy && pen_recorded(stroke, m) => (weight * pb.scale.max(1.0) / 100.0, true),
Some(m) if light != heavy => (pattern_scale_at(pb, weight, PenAt::of(stroke, 0.0).control(m).unwrap_or(0.5)), false),
_ => (weight * pb.scale.max(1.0) / 100.0, false),
}
}
/// The length of a start or end tile `width` wide at its art's size, at the scale `k_mid(w)` at
/// the middle of the tile when it is `w` long: the shortest length that is as long as the scale at
/// its own middle. The scale can rise and fall along the stroke, so the lengths up to `room` are
/// tried in order (evenly spaced ones, and `breaks`, the lengths whose middle falls on a recorded
/// pen sample), and the range between the last one the tile is too long for and the first one it
/// fits is halved. A tile that fits at no length up to `room` gets the length it needs at `room`,
/// longer than `room`. `breaks` is `None` when the scale is the same along the whole track, and
/// the tile then takes its length at that scale.
fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64, breaks: Option<&[f64]>) -> f64 {
let length = |w: f64| width * k_mid(w);
let first = length(0.0);
let Some(breaks) = breaks.filter(|_| !room.is_nan() && room > 0.0) else {
return first;
};
let mut tries: Vec<f64> = (1..=END_SCAN_STEPS).map(|i| room * i as f64 / END_SCAN_STEPS as f64).collect();
tries.extend(breaks.iter().copied().filter(|&w| w > 0.0 && w < room));
tries.sort_by(f64::total_cmp);
let Some(i) = tries.iter().position(|&w| length(w) <= w) else {
return length(room);
};
let (mut short, mut long) = (if i == 0 { 0.0 } else { tries[i - 1] }, tries[i]);
for _ in 0..END_SOLVE_STEPS {
let mid = (short + long) / 2.0;
if length(mid) > mid {
short = mid;
} else {
long = mid;
}
}
long
}
/// Where along a track `l` long `stroke` recorded the pen input `mode` follows: each sample at its
/// arc length, and again a track's length before and after it, for tiles of a closed track that
/// wrap round, in order.
fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec<f64> {
let points = match mode {
Variation::Fixed | Variation::Random => None,
Variation::Pressure => stroke.pressure.as_ref().map(|p| &p.points),
Variation::Tilt => stroke.tilt.as_ref().map(|p| &p.points),
Variation::Bearing => stroke.bearing.as_ref().map(|p| &p.points),
Variation::Rotation => stroke.rotation.as_ref().map(|p| &p.points),
Variation::StylusWheel => stroke.wheel.as_ref().map(|p| &p.points),
};
let mut marks: Vec<f64> = points.into_iter().flatten().flat_map(|&(f, _)| [f * l - l, f * l, f * l + l]).collect();
marks.sort_by(f64::total_cmp);
marks
}
/// Whether `stroke` recorded the pen input `mode` follows.
fn pen_recorded(stroke: &StrokeLayer, mode: Variation) -> bool {
match mode {
Variation::Fixed | Variation::Random => false,
Variation::Pressure => stroke.pressure.is_some(),
Variation::Tilt => stroke.tilt.is_some(),
Variation::Bearing => stroke.bearing.is_some(),
Variation::Rotation => stroke.rotation.is_some(),
Variation::StylusWheel => stroke.wheel.is_some(),
}
}
/// Leaves out or adds tiles at the end of `tiles` (each a length and the gap after it) once they
/// have been measured again: with `add_space` as many as fit in `avail` with the gaps between
/// them, at least one, otherwise the count whose lengths and gaps between them come nearest to
/// `avail`. An added tile is
/// `natural(s)` long at `s` from the run's start.
fn recount(tiles: &mut Vec<(f64, f64)>, avail: f64, add_space: bool, natural: &dyn Fn(f64) -> (f64, f64)) {
let mut length: f64 = tiles.iter().map(|t| t.0).sum();
let mut gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum());
// How much of the run the tiles and the spacing between them take.
let run = |length: f64, gaps: f64| length + gaps;
while let [.., (_, before), (w, _)] = tiles.as_slice() {
let (w, before) = (*w, *before);
let (now, without) = (run(length, gaps), run(length - w, gaps - before));
let drop = if add_space { now > avail } else { (without - avail).abs() < (now - avail).abs() };
if !drop {
break;
}
tiles.pop();
length -= w;
gaps -= before;
}
while tiles.len() < MAX_TILES {
let last_gap = tiles.last().map_or(0.0, |t| t.1);
let now = run(length, gaps);
let (w, g) = natural(run(length, gaps + last_gap));
if w.is_nan() || w <= 1e-9 {
break;
}
let with = run(length + w, gaps + last_gap);
let add = if add_space { with <= avail } else { (with - avail).abs() < (now - avail).abs() };
if !add {
break;
}
tiles.push((w, g));
length += w;
gaps += last_gap;
}
}
/// A pattern brush's side tiles on the run `avail` long from `a` of `t` (`marks` as
/// [`tile_scaled`] takes them), at the scale `k(s)` at
/// arc length `s` ([`varied_tiles`]), fitted as `pb.fit` says: Stretch scales the lengths and gaps
/// to fill the run, Add Space keeps the lengths and shares out what is left between the tiles
/// (around a lone tile), and Approximate keeps both and centers the tiles on the run.
fn varied_side_tiles(
out: &mut Budget,
t: &Track,
pb: &PatternBrush,
side: &(Node, Rect),
(a, avail): (f64, f64),
k: &dyn Fn(f64) -> f64,
marks: &[f64],
) {
let tw = side.1.width();
// Each side tile and the gap after it as long as the scale at the tile's middle.
let natural = |s: f64| {
let w = tw * k(s + tw * k(s) / 2.0);
(w, w * pb.spacing.max(0.0) / 100.0)
};
let (tiles, count) = varied_tiles(a, avail, &natural);
let n = match pb.fit {
PatternFit::AddSpace => count.floor(),
PatternFit::Stretch | PatternFit::Approximate => count.round(),
}
.max(1.0) as usize;
let mut tiles = tiles[..n.min(tiles.len())].to_vec();
// How far the fit stretches the tiles and gaps, where the first tile starts, and the space
// between tiles when the fit sets it.
let fitted = |tiles: &[(f64, f64)]| {
let length: f64 = tiles.iter().map(|t| t.0).sum();
// The gaps between the tiles: after every tile but the last.
let gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum());
match pb.fit {
PatternFit::Stretch => (avail / (length + gaps), 0.0, None),
PatternFit::AddSpace if tiles.len() > 1 => (1.0, 0.0, Some(((avail - length) / (tiles.len() - 1) as f64).max(0.0))),
PatternFit::AddSpace => (1.0, (avail - tiles.first().map_or(0.0, |t| t.0)) / 2.0, None),
PatternFit::Approximate => (1.0, (avail - length - gaps) / 2.0, None),
}
};
// The fit moves the tiles from where they were measured, so each is measured again at the
// middle of where the fit puts it, and the fit worked out again, a few times over.
for _ in 0..REFITS {
let (stretch, lead, space) = fitted(&tiles);
let mut s0 = a + lead;
for tile in &mut tiles {
let placed = tile.0 * stretch;
let w = tw * k(s0 + placed / 2.0);
s0 += placed + space.unwrap_or(tile.1 * stretch);
*tile = (w, w * pb.spacing.max(0.0) / 100.0);
}
recount(&mut tiles, avail, pb.fit == PatternFit::AddSpace, &|s| natural(a + s));
}
let (stretch, lead, space) = fitted(&tiles);
let mut s0 = a + lead;
for &(w, g) in &tiles {
let w = w * stretch;
out.take(tile_scaled(t, side, s0, s0 + w, k, Some(marks)));
if out.full() {
break;
}
s0 += w + space.unwrap_or(g * stretch);
}
}
/// What a pattern brush draws at a corner: corner tile art (oriented, with its bounds), or what
/// [`CornerSource`] gives.
#[derive(Clone, Copy)]
@@ -803,10 +1050,15 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option<Node> {
Some(Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(n)], clip: true }))
}
pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node> {
/// A pattern brush's tiles along `bp`. With a scale that follows the pen (its pressure, tilt,
/// bearing, rotation or wheel), the tiles are as tall as what `stroke` recorded at each point gives
/// (half way without a recording), each tile and the gap after it as long as the scale at its
/// middle, and each corner tile at the scale at its corner.
pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec<Node> {
let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across);
let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] };
let k = weight * pb.scale.max(1.0) / 100.0;
let scale_at = |p: f64| pattern_scale_at(pb, weight, p);
let (k, varies) = pattern_scale(pb, weight, stroke);
let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame));
let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame));
let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame));
@@ -825,6 +1077,17 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
if l <= 1e-9 {
continue;
}
// The scale at arc length `s` of the track; on a closed track a point before its start or
// past its end wraps round as `Track::frame` places it (its end itself keeps the scale at
// the end), and on an open track a point past either end takes the scale at that end.
let ks = |s: f64| {
if !varies {
return k;
}
let at = if t.closed && !(0.0..=l).contains(&s) { s.rem_euclid(l) } else { s.clamp(0.0, l) };
scale_at(pb.scale_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5))
};
let marks = pb.scale_mode.filter(|_| varies).map(|m| pen_marks(stroke, m, l));
let corners = t.corner_positions();
// Corner tiles, centred on the corner and turned to the bisector. The path on each side of
// a corner is shortened by `trims` (`None`: half the widest corner tile art).
@@ -848,17 +1111,18 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
};
before.min(after)
};
for (ci, &(i, _)) in corners.iter().enumerate() {
for (ci, &(i, at)) in corners.iter().enumerate() {
if out.full() {
break;
}
let kc = ks(at);
let (a, b) = t.in_out(i);
// Turning towards the left normal puts the tile's +y side on the inside.
let tile = if a.cross(b) > 0.0 { inner_tile.or(outer.as_ref().map(Corner::Art)) } else { outer_tile.or(inner.as_ref().map(Corner::Art)) };
let (art, bb) = match tile {
Some(Corner::Art(tile)) => tile,
Some(Corner::Source(source)) => {
let (pieces, trim) = auto_corner(&t, i, source, &side, k, room(ci));
let (pieces, trim) = auto_corner(&t, i, source, &side, kc, room(ci));
for n in pieces {
out.take(Some(n));
}
@@ -870,8 +1134,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
continue;
}
};
trims.push(None);
corner_half = corner_half.max(bb.width() * k / 2.0);
// With a scale that varies, each corner's tile is its own size, so the path beside it
// is shortened by half of that tile.
trims.push(varies.then_some(bb.width() * kc / 2.0));
corner_half = corner_half.max(bb.width() * kc / 2.0);
// Inner and outer corner art is the corner that joins a side tile on its right to one
// below it, so its arms point along +x and +y (as the flips leave them). The tile is
// turned so that the line halving its arms lies on the line halving the sides at the
@@ -881,7 +1147,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 });
let sides = b - a;
let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x);
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2());
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(kc) * Affine::translate(-bb.center().to_vec2());
let mut n = art.clone();
n.transform(xf, true);
out.take(Some(n));
@@ -914,9 +1180,11 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
&& ri == 0
&& let Some(st) = &start
{
let w = st.1.width() * k;
// As long as the scale at its middle.
let breaks: Option<Vec<f64>> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (m - a)).collect());
let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0), breaks.as_deref());
if b - a > w {
out.take(tile_on(&t, st, a, a + w, k));
out.take(tile_scaled(&t, st, a, a + w, &ks, marks.as_deref()));
a += w;
}
}
@@ -924,9 +1192,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
&& ri + 1 == nruns
&& let Some(en) = &end
{
let w = en.1.width() * k;
let breaks: Option<Vec<f64>> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (b - m)).collect());
let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0), breaks.as_deref());
if b - a > w {
out.take(tile_on(&t, en, b - w, b, k));
out.take(tile_scaled(&t, en, b - w, b, &ks, marks.as_deref()));
b -= w;
}
}
@@ -934,6 +1203,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
if avail <= 1e-6 {
continue;
}
if let Some(marks) = &marks {
varied_side_tiles(&mut out, &t, pb, &side, (a, avail), &ks, marks);
continue;
}
let unit = tw + gap;
match pb.fit {
PatternFit::Stretch => {
+22
View File
@@ -0,0 +1,22 @@
use std::cell::Cell;
thread_local! {
static USED: Cell<u64> = const { Cell::new(0) };
}
pub(crate) fn initial_used() -> u64 {
USED.with(Cell::get)
}
pub(crate) fn with_used<T>(used: u64, action: impl FnOnce() -> T) -> T {
struct Reset<'a>(&'a Cell<u64>, u64);
impl Drop for Reset<'_> {
fn drop(&mut self) {
self.0.set(self.1);
}
}
USED.with(|value| {
let _reset = Reset(value, value.replace(used));
action()
})
}
+3 -1
View File
@@ -588,6 +588,9 @@ impl<'a> Walk<'a> {
clip_tests: 0,
warnings: vec![],
nest: 0,
#[cfg(test)]
symbol_nodes: crate::expansion_test::initial_used(),
#[cfg(not(test))]
symbol_nodes: 0,
generated: 0,
scratch: None,
@@ -740,7 +743,6 @@ impl<'a> Walk<'a> {
}
Some(None) => {}
None => {
self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES;
self.warn(SYMBOLS_LEFT_OUT);
}
}
+25
View File
@@ -870,6 +870,31 @@ fn symbols_nested_too_deep_are_left_out_with_a_warning() {
assert_eq!(text(&out), "IN;PU;SP0;");
}
#[test]
fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() {
let mut d = doc_with(|_| vec![]);
let leaf = stroked(&mut d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK);
let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) });
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) });
let mut first = None;
for name in ["big", "small"] {
let id = d.alloc_id();
first.get_or_insert(id);
let layer = d.layers[0].id;
d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap();
}
let mut expected = d.clone();
expected.remove(first.unwrap()).unwrap();
crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || {
let actual = plot(&d, &opts(&d));
let control = plot(&expected, &opts(&expected));
assert!(actual.warnings.iter().any(|w| w == SYMBOLS_LEFT_OUT), "{:?}", actual.warnings);
assert_ne!(text(&control), "IN;PU;SP0;");
assert_eq!(text(&actual), text(&control), "HP-GL keeps the later fitting instance");
});
}
/// A symbol instance stained by its fill draws in the stained color.
#[test]
fn a_stained_symbol_instance_takes_its_stain() {
+2
View File
@@ -23,6 +23,8 @@
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
mod aci;
#[cfg(test)]
mod expansion_test;
pub mod hpgl;
pub mod import;
mod scene;
+4 -3
View File
@@ -561,8 +561,10 @@ impl<'a> Scene<'a> {
extents: None,
opacity: 1.0,
nest: 0,
// Tests spend all but a million of it up front.
symbol_nodes: if cfg!(test) { vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000 } else { 0 },
#[cfg(test)]
symbol_nodes: crate::expansion_test::initial_used(),
#[cfg(not(test))]
symbol_nodes: 0,
}
}
@@ -711,7 +713,6 @@ impl<'a> Scene<'a> {
}
Some(None) => {}
None => {
self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES;
self.warn(SYMBOLS_LEFT_OUT);
}
}
+26 -1
View File
@@ -1503,11 +1503,36 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
let art = Node::group(d.alloc_id(), children);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) });
}
let out = export(&d, &opts(&d)).unwrap();
let out = crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000, || export(&d, &opts(&d)).unwrap());
assert!(entities(&out).is_empty());
assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings);
}
#[test]
fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() {
let mut d = doc_with(|_| vec![]);
let leaf = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 40.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) });
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) });
let mut first = None;
for name in ["big", "small"] {
let id = d.alloc_id();
first.get_or_insert(id);
let layer = d.layers[0].id;
d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap();
}
let mut expected = d.clone();
expected.remove(first.unwrap()).unwrap();
crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || {
let actual = export(&d, &opts(&d)).unwrap();
let control = export(&expected, &opts(&expected)).unwrap();
assert!(actual.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", actual.warnings);
assert!(!entities(&control).is_empty());
assert_eq!(kinds(&actual), kinds(&control), "DXF keeps the later fitting instance");
});
}
#[test]
fn export_bytes_match_shared_writer_goldens() {
use std::path::PathBuf;
+443
View File
@@ -0,0 +1,443 @@
//! Color text in the forms CSS Color 4 defines: hex colors with or without an alpha
//! (<https://www.w3.org/TR/css-color-4/#hex-notation>), `rgb()` and `rgba()`
//! (<https://www.w3.org/TR/css-color-4/#rgb-functions>), `hsl()` and `hsla()`
//! (<https://www.w3.org/TR/css-color-4/#the-hsl-notation>) and `oklch()`
//! (<https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch>). The functions take the
//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also
//! take the comma-separated legacy form (<https://www.w3.org/TR/css-color-4/#legacy-color-syntax>).
//! Hues take the angle units of CSS Values 4 (<https://www.w3.org/TR/css-values-4/#angles>). A hex
//! color may leave out its `#`.
//!
//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages,
//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`,
//! `var()`, `color-mix()`, relative color syntax and every other nested function are refused, as are
//! named colors and the other color spaces and functions (`hwb()`, `lab()`, `oklab()`, `color()`).
use crate::oklab::{self, CHROMA_FULL};
/// The most characters a color text may have, spaces around it not counted.
pub const MAX_CHARS: usize = 48;
/// The space a parsed color's red, green and blue are in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Space {
/// The numbers as written: a hex color, `rgb()` or `hsl()`.
Srgb,
/// sRGB converted from `oklch()`.
Oklch,
}
/// A color read from CSS text.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CssColor {
/// Red, green and blue from 0 to 1.
pub rgb: [f32; 3],
/// The alpha from 0 to 1, when the text gives one (CSS reads a missing alpha as 1).
pub alpha: Option<f32>,
pub space: Space,
}
/// The color `text` gives, or `None` when it is not one of the module's forms or has more than
/// [`MAX_CHARS`] characters. Values are clamped where CSS clamps them when it parses them: red, green
/// and blue to 0..=255 (0..=100 %), alpha to 0..=1, a negative HSL saturation to 0, OKLCH lightness
/// to 0..=1 and chroma to 0 or more. `none` reads as 0, as CSS reads a missing component when it
/// converts a color. Spaces, tabs, line breaks and form feeds may surround the text and its
/// arguments; other whitespace is not CSS whitespace and makes the text invalid. An `hsl()` color whose red, green or
/// blue falls outside 0..=1 has that channel clipped, and an `oklch()` color outside sRGB keeps its
/// lightness and hue and takes the largest chroma that fits ([`oklab::from_oklch`]); CSS maps such
/// colors into the gamut by its own rules instead. An `hsl()` color whose saturation and lightness
/// are so large that a channel overflows to an infinity is refused.
pub fn parse(text: &str) -> Option<CssColor> {
let text = css_trim(text);
if text.chars().nth(MAX_CHARS).is_some() {
return None;
}
match text.find('(') {
None => hex(text),
Some(open) => {
// CSS allows no space between a function's name and its `(`.
let name = text.get(..open)?.to_ascii_lowercase();
let args = text.get(open + 1..)?.strip_suffix(')')?;
if args.contains(['(', ')']) {
return None;
}
match name.as_str() {
"rgb" | "rgba" => rgb(args),
"hsl" | "hsla" => hsl(args),
"oklch" => oklch(args),
_ => None,
}
}
}
}
/// `s` without the CSS whitespace (spaces, tabs, line breaks and form feeds, which CSS reads as line
/// breaks) around it (<https://www.w3.org/TR/css-syntax-3/#whitespace>,
/// <https://www.w3.org/TR/css-syntax-3/#input-preprocessing>).
fn css_trim(s: &str) -> &str {
s.trim_matches(|c: char| c.is_ascii_whitespace())
}
/// `#rrggbb` of red, green and blue from 0 to 1, each rounded to the nearest of 256 steps.
pub fn hex_of(rgb: [f32; 3]) -> String {
let [r, g, b] = rgb.map(byte);
format!("#{r:02x}{g:02x}{b:02x}")
}
/// `v` (0 to 1) as one of 256 steps.
fn byte(v: f32) -> u8 {
(v.clamp(0.0, 1.0) * 255.0).round() as u8
}
/// A hex color of 3, 4, 6 or 8 digits, with or without `#`.
fn hex(text: &str) -> Option<CssColor> {
let digits = text.strip_prefix('#').unwrap_or(text);
if !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let nibbles: Vec<u8> = digits.bytes().filter_map(|b| (b as char).to_digit(16)).map(|d| d as u8).collect();
let values: Vec<u8> = match nibbles.len() {
3 | 4 => nibbles.iter().map(|n| n * 17).collect(),
6 | 8 => nibbles.chunks(2).map(|p| p.iter().fold(0, |v, n| v * 16 + n)).collect(),
_ => return None,
};
let unit = |i: usize| values.get(i).map(|v| f32::from(*v) / 255.0);
Some(CssColor { rgb: [unit(0)?, unit(1)?, unit(2)?], alpha: unit(3), space: Space::Srgb })
}
/// One argument of a color function.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Arg {
Number(f64),
Percent(f64),
/// An angle, in degrees.
Angle(f64),
None,
}
/// The arguments of a color function, `args` being the text inside its parentheses: the three
/// components and the alpha, if any, and whether they were separated by commas (the legacy form).
fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option<Arg>, bool)> {
let (parts, alpha, legacy): (Vec<&str>, Option<&str>, bool) = if args.contains(',') {
if !legacy_allowed || args.contains('/') {
return None;
}
let mut parts: Vec<&str> = args.split(',').map(css_trim).collect();
let alpha = if parts.len() == 4 { parts.pop() } else { None };
(parts, alpha, true)
} else {
let mut halves = args.split('/');
let colors = halves.next().unwrap_or_default();
let alpha = halves.next();
if halves.next().is_some() {
return None;
}
(colors.split_ascii_whitespace().collect(), alpha.map(css_trim), false)
};
let [a, b, c] = parts.as_slice() else { return None };
let one = |s: &str| {
let arg = arg(s)?;
// The legacy form has no `none`.
(!(legacy && arg == Arg::None)).then_some(arg)
};
let alpha = match alpha {
Some(s) => Some(one(s)?),
None => None,
};
Some(([one(a)?, one(b)?, one(c)?], alpha, legacy))
}
/// One argument: `none`, a number, a percentage or an angle (`deg`, `grad`, `rad`, `turn`), with no
/// spaces inside it.
fn arg(s: &str) -> Option<Arg> {
if s.eq_ignore_ascii_case("none") {
return Some(Arg::None);
}
let end = number_end(s)?;
let n: f64 = s.get(..end)?.parse().ok().filter(|n: &f64| n.is_finite())?;
let unit = s.get(end..)?.to_ascii_lowercase();
let arg = match unit.as_str() {
"" => Arg::Number(n),
"%" => Arg::Percent(n),
"deg" => Arg::Angle(n),
"grad" => Arg::Angle(n * 0.9),
"rad" => Arg::Angle(n.to_degrees()),
"turn" => Arg::Angle(n * 360.0),
_ => return None,
};
match arg {
Arg::Angle(a) if !a.is_finite() => None,
_ => Some(arg),
}
}
/// The byte length of the CSS number at the start of `s`: an optional sign, digits with an
/// optional fraction (at least one digit, and digits after a `.`), and an optional exponent.
fn number_end(s: &str) -> Option<usize> {
let b = s.as_bytes();
let digits = |from: usize| b.get(from..).map_or(0, |rest| rest.iter().take_while(|c| c.is_ascii_digit()).count());
let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-')));
let whole = digits(i);
i += whole;
let mut fraction = 0;
if b.get(i) == Some(&b'.') {
fraction = digits(i + 1);
if fraction == 0 {
return None;
}
i += 1 + fraction;
}
if whole + fraction == 0 {
return None;
}
if matches!(b.get(i), Some(b'e' | b'E')) {
let sign = usize::from(matches!(b.get(i + 1), Some(b'+' | b'-')));
let exp = digits(i + 1 + sign);
if exp > 0 {
i += 1 + sign + exp;
}
}
Some(i)
}
/// The alpha argument from 0 to 1.
fn alpha(a: Option<Arg>) -> Option<Option<f32>> {
let v = match a {
None => return Some(None),
Some(Arg::Number(n)) => n,
Some(Arg::Percent(p)) => p / 100.0,
Some(Arg::None) => 0.0,
Some(Arg::Angle(_)) => return None,
};
Some(Some(v.clamp(0.0, 1.0) as f32))
}
/// A hue argument in degrees from 0 to 360.
fn hue(a: Arg) -> Option<f64> {
match a {
Arg::Number(d) | Arg::Angle(d) => Some(d.rem_euclid(360.0)).filter(|d| d.is_finite()),
Arg::None => Some(0.0),
Arg::Percent(_) => None,
}
}
fn rgb(args: &str) -> Option<CssColor> {
let (comps, a, legacy) = split(args, true)?;
let percents = comps.iter().filter(|c| matches!(c, Arg::Percent(_))).count();
if legacy && percents != 0 && percents != 3 {
return None;
}
let unit = |c: Arg| match c {
Arg::Number(n) => Some(n / 255.0),
Arg::Percent(p) => Some(p / 100.0),
Arg::None => Some(0.0),
Arg::Angle(_) => None,
};
let [r, g, b] = comps;
let rgb = [unit(r)?, unit(g)?, unit(b)?].map(|v| v.clamp(0.0, 1.0) as f32);
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb })
}
fn hsl(args: &str) -> Option<CssColor> {
let (comps, a, legacy) = split(args, true)?;
let [h, s, l] = comps;
let percent = |c: Arg| match c {
Arg::Percent(v) => Some(v),
Arg::Number(v) if !legacy => Some(v),
Arg::None => Some(0.0),
_ => None,
};
// CSS clamps a negative saturation to 0 and nothing else.
let (h, s, l) = (hue(h)?, percent(s)?.max(0.0) / 100.0, percent(l)? / 100.0);
// CSS Color 4's hslToRgb (https://www.w3.org/TR/css-color-4/#hsl-to-rgb); a channel outside
// 0..=1 is clipped.
let f = |n: f64| {
let k = (n + h / 30.0) % 12.0;
let amount = s * l.min(1.0 - l);
l - amount * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
};
// Huge saturation and lightness values overflow to an infinity or NaN, which is refused.
let rgb = [f(0.0), f(8.0), f(4.0)];
if rgb.iter().any(|v| !v.is_finite()) {
return None;
}
let rgb = rgb.map(|v| v.clamp(0.0, 1.0) as f32);
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb })
}
fn oklch(args: &str) -> Option<CssColor> {
let (comps, a, _) = split(args, false)?;
let [l, c, h] = comps;
let l = match l {
Arg::Number(v) => v,
Arg::Percent(p) => p / 100.0,
Arg::None => 0.0,
Arg::Angle(_) => return None,
};
let c = match c {
Arg::Number(v) => v,
Arg::Percent(p) => p / 100.0 * CHROMA_FULL,
Arg::None => 0.0,
Arg::Angle(_) => return None,
};
let (rgb, _) = oklab::from_oklch(l.clamp(0.0, 1.0), c.max(0.0), hue(h)?);
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Oklch })
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
fn bytes(text: &str) -> ([u8; 3], Option<u8>) {
let c = parse(text).unwrap_or_else(|| panic!("{text} should parse"));
(c.rgb.map(byte), c.alpha.map(|a| (a * 255.0).round() as u8))
}
#[test]
fn hex_colors_take_three_four_six_or_eight_digits_with_or_without_the_hash() {
assert_eq!(bytes("#336699"), ([0x33, 0x66, 0x99], None));
assert_eq!(bytes("33669980"), ([0x33, 0x66, 0x99], Some(0x80)));
assert_eq!(bytes("#369"), ([0x33, 0x66, 0x99], None));
assert_eq!(bytes("#3698"), ([0x33, 0x66, 0x99], Some(0x88)));
assert_eq!(bytes(" #AbCdEf "), ([0xab, 0xcd, 0xef], None));
for bad in ["", "#", "#12", "#12345", "#1234567", "#123456789", "#ggg", "##123", "#+12", "#12 3", "123"] {
assert_eq!(parse(bad), None, "{bad:?}");
}
}
#[test]
fn rgb_reads_the_modern_and_the_legacy_forms() {
assert_eq!(bytes("rgb(51 102 153)"), ([51, 102, 153], None));
assert_eq!(bytes("rgb(51 102 153 / 50%)"), ([51, 102, 153], Some(128)));
assert_eq!(bytes("RGBA(51 102 153/0.5)"), ([51, 102, 153], Some(128)));
assert_eq!(bytes("rgb(20% 40% 60%)"), ([51, 102, 153], None));
assert_eq!(bytes("rgb(20% 102 none)"), ([51, 102, 0], None), "the modern form mixes numbers and percentages");
assert_eq!(bytes("rgb(51, 102, 153)"), ([51, 102, 153], None));
assert_eq!(bytes("rgba(51,102,153,.5)"), ([51, 102, 153], Some(128)));
assert_eq!(bytes("rgb(51, 102, 153, 50%)"), ([51, 102, 153], Some(128)));
assert_eq!(bytes("rgb(300 -20 1e2)"), ([255, 0, 100], None), "components are clamped");
assert_eq!(bytes("rgb(0 0 0 / 2)"), ([0, 0, 0], Some(255)), "the alpha is clamped");
assert_eq!(bytes("rgb(0 0 0 / none)"), ([0, 0, 0], Some(0)));
for bad in [
"rgb(51, 102%, 153)",
"rgb(51, 102, none)",
"rgb(51 102)",
"rgb(51 102 153 0.5)",
"rgb(51, 102 153)",
"rgb(51, 102, 153 / 0.5)",
"rgb(51 102 153 / 0.5 / 1)",
"rgb(51 102 153deg)",
"rgb(1. 2 3)",
"rgb(1e999 0 0)",
"rgb(51 102 153",
"rgb(51 102 153))",
"rgb(51 102 153) x",
"rgb(calc(1) 2 3)",
"rgb(,,)",
"rgb (1 2 3)",
"rgb()",
"rgbx(1 2 3)",
] {
assert_eq!(parse(bad), None, "{bad:?}");
}
}
#[test]
fn only_spaces_tabs_and_line_breaks_are_whitespace() {
assert_eq!(bytes("\t rgb(51,\n102 ,\t153)\r\n"), ([51, 102, 153], None));
assert_eq!(bytes("rgb(51 102 153 /\t0.5 )"), ([51, 102, 153], Some(128)));
assert_eq!(bytes("\u{c}#336699\u{c}"), ([51, 102, 153], None), "CSS reads a form feed as a line break");
assert_eq!(bytes("rgb(51\u{c}102\u{c}153)"), ([51, 102, 153], None));
for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)", "\u{b}#336699"] {
assert_eq!(parse(bad), None, "{bad:?}");
}
}
#[test]
fn hsl_reads_hues_in_every_angle_unit() {
assert_eq!(bytes("hsl(210 50% 40%)"), ([51, 102, 153], None));
assert_eq!(bytes("hsl(210deg 50 40 / 25%)"), ([51, 102, 153], Some(64)));
assert_eq!(bytes("hsla(210, 50%, 40%, 0.5)"), ([51, 102, 153], Some(128)));
assert_eq!(bytes("hsl(-150 50% 40%)"), ([51, 102, 153], None), "a hue is normalized");
assert_eq!(bytes("hsl(0.5turn 100% 50%)"), ([0, 255, 255], None));
assert_eq!(bytes("hsl(200grad 100% 50%)"), ([0, 255, 255], None));
assert_eq!(bytes("hsl(3.14159265rad 100% 50%)"), ([0, 255, 255], None));
assert_eq!(bytes("hsl(120 -20% 50%)"), ([128, 128, 128], None), "a negative saturation is 0");
assert_eq!(bytes("hsl(15 150% 50%)"), ([255, 32, 0], None), "a saturation over 100 % is kept and the channels are clipped");
assert_eq!(bytes("hsl(0 50% 150%)"), ([255, 255, 255], None));
assert_eq!(bytes("hsl(none 0% 100%)"), ([255, 255, 255], None));
for bad in
["hsl(210, 50, 40)", "hsl(210% 50% 40%)", "hsl(210 50% 40% 1)", "hsl(210deg, 50%, none)", "hsl(1e999deg 0% 0%)", "hsl(1e306turn 0% 0%)"]
{
assert_eq!(parse(bad), None, "{bad:?}");
}
// Saturation and lightness this large overflow to an infinity or NaN.
for bad in ["hsl(90 1e308% 1e308%)", "hsl(90 1e308 -1e308)"] {
assert_eq!(parse(bad), None, "{bad:?}");
}
}
#[test]
fn oklch_converts_through_srgb_and_has_no_legacy_form() {
let c = parse("oklch(62.8% 0.2577 29.23)").unwrap();
assert_eq!((c.rgb.map(byte), c.alpha, c.space), ([255, 0, 0], None, Space::Oklch));
let c = parse("oklch(0.628 64.4% 29.23 / 0.5)").unwrap();
assert_eq!((c.rgb.map(byte), c.alpha), ([255, 0, 0], Some(0.5)));
assert_eq!(parse("oklch(1 0 0)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]));
assert_eq!(parse("oklch(2 -1 none)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]), "L and C are clamped");
let wide = parse("oklch(0.7 0.4 150)").unwrap();
assert!(wide.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a color outside sRGB is brought inside: {:?}", wide.rgb);
let huge = parse("oklch(0.5 1e308 30)").unwrap();
assert!(huge.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a huge chroma is brought inside: {:?}", huge.rgb);
for bad in ["oklch(0.6, 0.1, 30)", "oklch(0.6 0.1 30% )", "oklch(0.6deg 0.1 30)", "oklch(0.6 0.1)"] {
assert_eq!(parse(bad), None, "{bad:?}");
}
}
#[test]
fn text_longer_than_the_limit_is_refused() {
let at_limit = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 15));
assert_eq!(at_limit.chars().count(), MAX_CHARS);
assert!(parse(&at_limit).is_some());
let over = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 14));
assert_eq!(parse(&over), None);
assert_eq!(parse(&format!(" {at_limit} ")).map(|c| c.rgb.map(byte)), Some([51, 102, 153]), "spaces around it are not counted");
assert_eq!(parse(&"(".repeat(100_000)), None);
}
#[test]
fn hex_of_rounds_each_component() {
assert_eq!(hex_of([0.2, 0.4, 0.6]), "#336699");
assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00");
}
proptest! {
#[test]
fn random_text_never_panics(text in "\\PC{0,60}") {
// `contains` is false for NaN, so these also check that every channel is finite.
if let Some(c) = parse(&text) {
prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));
prop_assert!(c.alpha.is_none_or(|a| (0.0..=1.0).contains(&a)));
}
}
#[test]
fn function_shaped_text_never_panics(
name in "(rgb|rgba|hsl|hsla|oklch|RGB)",
args in "[-+0-9.eE%a-z ,/]{0,40}",
) {
if let Some(c) = parse(&format!("{name}({args})")) {
prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));
}
}
#[test]
fn eight_digit_hex_round_trips(r: u8, g: u8, b: u8, a: u8) {
let c = parse(&format!("#{r:02x}{g:02x}{b:02x}{a:02x}")).unwrap();
prop_assert_eq!(c.rgb.map(byte), [r, g, b]);
prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a));
prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}"));
}
}
}
+1
View File
@@ -6,6 +6,7 @@
pub mod blend;
pub mod cms;
pub mod css;
pub mod freeform;
pub mod gradient;
pub mod harmony;
+2
View File
@@ -28,6 +28,8 @@ tiff = { workspace = true }
craft-stream-codecs = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
# The hash of a generated art object's art, which its file holds (`generated`).
sha2 = { version = "0.10", default-features = false }
thiserror = { workspace = true }
chrono = { workspace = true }
+6 -1
View File
@@ -192,14 +192,18 @@ pub enum Arrowhead {
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
/// the other heads.
LineArrow,
/// A slender filled head, a little over half as wide as it is long, whose sides bend in
/// halfway back, with a V-shaped notch in its back: the arrow of mathematical diagrams.
NotchedArrow,
/// A head the user drew, with its art.
Custom(Arc<CustomArrowhead>),
}
impl Arrowhead {
/// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks).
pub const ALL: [Arrowhead; 41] = [
pub const ALL: [Arrowhead; 42] = [
Arrowhead::Arrow,
Arrowhead::NotchedArrow,
Arrowhead::ArrowOpen,
Arrowhead::LineArrow,
Arrowhead::Barbed,
@@ -322,6 +326,7 @@ impl Arrowhead {
Arrowhead::TriangleBar => "Triangle to Bar",
Arrowhead::Oval => "Oval",
Arrowhead::LineArrow => "Line Arrow",
Arrowhead::NotchedArrow => "Notched Arrow",
Arrowhead::Custom(_) => "Custom",
}
}
+2 -1
View File
@@ -316,7 +316,7 @@ fn profile_presets_round_trip_their_ids() {
#[test]
fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
// Saved files store these names: they may only ever be appended to.
const SAVED: [&str; 41] = [
const SAVED: [&str; 42] = [
"Triangle",
"TriangleOpen",
"Circle",
@@ -358,6 +358,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
"TriangleBar",
"Oval",
"LineArrow",
"NotchedArrow",
];
for name in SAVED {
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
+109 -13
View File
@@ -394,6 +394,11 @@ pub enum DimensionSource {
/// it is vertical. Versions without this source do not open the file.
Extent {
node: NodeId,
/// Placed with Use Preview Bounds on: the points are moved out to the outside of the
/// strokes the path paints ([`preview_extents`]), the width or height that W and H show.
/// Versions without it measure between the outermost points themselves.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
preview: bool,
},
}
@@ -402,7 +407,7 @@ impl DimensionSource {
match self {
Self::Segment { edge } | Self::Arc { edge } => vec![edge.node],
Self::Angle { first, second } => vec![first.node, second.node],
Self::Circle { node } | Self::Extent { node } => vec![*node],
Self::Circle { node } | Self::Extent { node, .. } => vec![*node],
Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex]
.into_iter()
.filter_map(|p| p.as_ref().map(|r| r.node))
@@ -425,10 +430,18 @@ impl DimensionSource {
})
}
/// Whether a path it measures differs between `before` and `after`, or is in only one of them.
/// A node without a path, or missing from both, counts as changed.
/// A node without a path, or missing from both, counts as changed. For a dimension of a whole
/// path placed with Use Preview Bounds on, so does a change to the strokes the path paints
/// ([`stroked_by`]): their appearance, the node they come from, or which arrowheads they draw
/// on it, and the path being made into a guide or released from one.
pub fn art_changed(&self, before: &Document, after: &Document) -> bool {
let strokes = matches!(self, Self::Extent { preview: true, .. });
self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) {
(Some(old), Some(new)) => old.path_data().is_none() || (!std::ptr::eq(old, new) && old.path_data() != new.path_data()),
(Some(old), Some(new)) => {
old.path_data().is_none()
|| (!std::ptr::eq(old, new) && old.path_data() != new.path_data())
|| (strokes && (old.is_guide() != new.is_guide() || stroked_by(before, id) != stroked_by(after, id)))
}
_ => true,
})
}
@@ -845,7 +858,9 @@ impl Dimension {
let (a, b) = (self.a.to_vec2().dot(n), self.b.to_vec2().dot(n));
let (low, high) = (a.min(b), a.max(b));
match (doc, &self.source) {
(Some(doc), Some(DimensionSource::Extent { node })) => reach(doc, *node, n).map_or((low, high), |(l, h)| (low.min(l), high.max(h))),
(Some(doc), Some(DimensionSource::Extent { node, preview })) => {
reach(doc, *node, n, *preview).map_or((low, high), |(l, h)| (low.min(l), high.max(h)))
}
_ => (low, high),
}
}
@@ -891,8 +906,8 @@ impl Dimension {
};
}
next.orientation = orientation;
if let Some(DimensionSource::Extent { node }) = &next.source {
(next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?;
if let Some(DimensionSource::Extent { node, preview }) = &next.source {
(next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical, *preview).ok_or("Measured path no longer exists")?;
}
// Along the new normal, relative to the new first point, so that the result is the offset.
let n = next.normal();
@@ -1020,8 +1035,8 @@ impl Dimension {
let (center, radius) = arc(doc, edge).ok_or("Choose a circle or a perfect arc")?;
self.set_radial(center, radius);
}
Some(DimensionSource::Extent { node }) => {
let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?;
Some(DimensionSource::Extent { node, preview }) => {
let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical, *preview).ok_or("Measured path no longer exists")?;
self.a = a;
self.b = b;
self.length = self.measured();
@@ -1176,14 +1191,86 @@ fn same_extents(before: &Document, after: &Document, id: NodeId) -> bool {
}
/// [`extents`] along one axis: the leftmost and the rightmost points, or with `vertical` the
/// topmost and the bottommost.
pub fn extent(doc: &Document, id: NodeId, vertical: bool) -> Option<(Point, Point)> {
extents(doc, id).map(|ends| ends[usize::from(vertical)])
/// topmost and the bottommost. With `preview`, the points of [`preview_extents`].
pub fn extent(doc: &Document, id: NodeId, vertical: bool, preview: bool) -> Option<(Point, Point)> {
let ends = if preview { preview_extents(doc, id) } else { extents(doc, id) };
ends.map(|ends| ends[usize::from(vertical)])
}
/// [`extents`] moved out to the box the path paints, its strokes included ([`painted_box`]), as Use
/// Preview Bounds measures it: the leftmost and the rightmost points move out to that box's left
/// and right sides at the same height, and the topmost and the bottommost to its top and bottom at
/// the same place across. A path that paints no stroke keeps the points of [`extents`]. None for a
/// node without a path or without segments.
pub fn preview_extents(doc: &Document, id: NodeId) -> Option<[(Point, Point); 2]> {
let [(left, right), (top, bottom)] = extents(doc, id)?;
let Some(b) = painted_box(doc, id) else { return Some([(left, right), (top, bottom)]) };
Some([
(Point::new(left.x.min(b.x0), left.y), Point::new(right.x.max(b.x1), right.y)),
(Point::new(top.x, top.y.min(b.y0)), Point::new(bottom.x, bottom.y.max(b.y1))),
])
}
/// The node whose strokes a path paints with: the compound path that holds it, or the path itself.
fn painter(doc: &Document, id: NodeId) -> Option<&crate::Node> {
let n = doc.node(id)?;
match doc.parent_of(id).and_then(|p| doc.node(p)) {
Some(c) if matches!(c.kind, crate::NodeKind::Compound { .. }) => Some(c),
_ => Some(n),
}
}
/// What the strokes a path paints with depend on, besides its own shape: the node they come from
/// ([`painter`]), its appearance, and which arrowheads they draw on the path ([`heads_on`]).
fn stroked_by(doc: &Document, id: NodeId) -> Option<(NodeId, &crate::Appearance, (bool, bool))> {
painter(doc, id).map(|p| (p.id, &*p.appearance, heads_on(p, id)))
}
/// The box a path paints, its strokes included, measured along its own shape as
/// [`crate::Node::visual_bounds`] measures a path: a member of a compound path is stroked with the
/// compound path's strokes, with only the arrowheads the compound path paints on it. None for a
/// node without a path or without anything drawn, and for a path made into a guide, which paints
/// no strokes.
fn painted_box(doc: &Document, id: NodeId) -> Option<vectorcraft_geom::Rect> {
let n = doc.node(id)?;
if n.is_guide() {
return None;
}
let path = n.path_data()?;
let painter = painter(doc, id)?;
let a = &painter.appearance;
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
let dots = a.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
let b = path.drawn_bounds(dots).or_else(|| n.geometric_bounds())?;
let (start, end) = heads_on(painter, id);
let mut shape = None;
Some(a.stroked_bounds_by(b, |s| {
let bp = shape.get_or_insert_with(|| n.stroke_path().unwrap_or_default());
if (s.start_arrow.is_some() && !start) || (s.end_arrow.is_some() && !end) {
let mut s = s.clone();
s.start_arrow = s.start_arrow.filter(|_| start);
s.end_arrow = s.end_arrow.filter(|_| end);
s.bounds_on(bp, b)
} else {
s.bounds_on(bp, b)
}
}))
}
/// Whether the start and the end arrowheads of `painter`'s strokes can be drawn on its member
/// `id`. A compound path's strokes put the start head on its first subpath and the end head on its
/// last, so a member gets the start head only when it holds the first subpath with anchors and
/// the end head only when it holds the last one. A path that is its own painter gets both.
fn heads_on(painter: &crate::Node, id: NodeId) -> (bool, bool) {
let Some(members) = painter.children().filter(|_| painter.id != id) else { return (true, true) };
let drawn = |c: &&std::sync::Arc<crate::Node>| c.path_data().is_some_and(|p| p.subpaths.iter().any(|sp| !sp.anchors.is_empty()));
(members.iter().find(drawn).is_some_and(|c| c.id == id), members.iter().rfind(drawn).is_some_and(|c| c.id == id))
}
/// How far a path's outline reaches along the unit direction `u`: the lowest and the highest
/// `p · u` over the points of its segments. None for a node without a path or without segments.
pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> {
/// `p · u` over the points of its segments, and with `preview` over the corners of the box it
/// paints too ([`painted_box`]). None for a node without a path or without segments.
pub fn reach(doc: &Document, id: NodeId, u: Vec2, preview: bool) -> Option<(f64, f64)> {
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema};
let path = doc.node(id)?.path_data()?;
// Turns `u` onto the x axis, so the turned curve's extrema include those along `u`.
@@ -1204,6 +1291,15 @@ pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> {
}
}
}
if preview
&& let Some((low, high)) = span.as_mut()
&& let Some(b) = painted_box(doc, id)
{
for corner in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] {
let v = corner.to_vec2().dot(u);
(*low, *high) = (low.min(v), high.max(v));
}
}
span
}
+597
View File
@@ -0,0 +1,597 @@
//! Generated art objects: a group whose children a generator plug-in drew from its parameters
//! (`plugin.generate`). The group keeps the plug-in's id and name, the parameters it was drawn with
//! and the transform its art has had since, so `plugin.editGenerated` can run the plug-in again and
//! replace the art. Its children are ordinary objects for every renderer and exporter, so the art
//! draws, prints and exports whether or not the plug-in is installed.
//!
//! A file holds the fields beside a SHA-256 of the art as it was written ([`art_hash`]). Reading
//! never runs a plug-in. A field that can't be read (an id that is not a plug-in id, parameters
//! that are not an object or are past [`MAX_PARAMS_BYTES`], a transform that is not one) marks the
//! object [`State::Damaged`], and art that doesn't match the hash marks it [`State::Changed`]: the
//! art stays as it was read either way. A damaged object is saved with `damaged: true`, so it stays
//! damaged when the file is opened again.
//!
//! A generated art object inside another one's art (anywhere in its children or their opacity
//! masks) is written and read as plain art: its settings are left out of the file, and a file that
//! has them there anyway loses them when it is read, its outer object marked [`State::Changed`]
//! without hashing. So each object's art is written and hashed once, whatever the nesting.
use std::cell::Cell;
use std::sync::Arc;
use serde::Serialize;
use serde_json::{Map, Value};
use vectorcraft_geom::Affine;
use crate::Effect;
use crate::node::{Node, NodeKind, Scaling};
/// Most bytes a generated art object's parameters take, written as JSON.
pub const MAX_PARAMS_BYTES: usize = 64 << 10;
/// Most bytes the art of a generated art object takes when a generator draws it, written as JSON.
pub const MAX_ART_BYTES: usize = 16 << 20;
/// Longest plug-in id, in bytes, as plug-in manifests limit it.
pub const MAX_ID: usize = 64;
/// Longest plug-in name kept, in characters, as plug-in manifests limit it.
pub const MAX_NAME: usize = 64;
/// How the fields of a generated art object were read.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum State {
/// Made in this session, or read with every field and the art's hash intact.
#[default]
Intact,
/// A field could not be read: the plug-in id is not one, or the parameters or the transform
/// are not usable. The art can't be drawn again.
Damaged,
/// The fields were read, but the art doesn't match the hash the file gave for it.
Changed,
}
/// The settings of a generated art object ([`crate::NodeExtras::generated`]).
#[derive(Clone, Debug, PartialEq)]
pub struct GeneratedArt {
/// The id of the plug-in that drew it.
pub plugin: String,
/// The plug-in's name when it drew it, to name the plug-in while it is not installed.
pub name: String,
/// The plug-in's parameters it was drawn with, each one given.
pub params: Map<String, Value>,
/// The transform its art has had since it was drawn (moves, scales, rotations, reflections
/// and shears).
pub transform: Affine,
/// What its art's stroke weights and dashes have been scaled by since it was drawn (the
/// transforms made with Scale Strokes & Effects on).
pub stroke_scale: f64,
/// What its art's effect distances have been scaled by since it was drawn.
pub effect_scale: f64,
/// The transform its art's pattern tiles have had since it was drawn (the transforms made with
/// Transform Patterns on).
pub pattern_transform: Affine,
/// How it was read; not written to files.
pub state: State,
}
impl GeneratedArt {
/// The settings of art drawn by plug-in `plugin` (named `name`) with `params`, not transformed
/// since.
pub fn new(plugin: &str, name: &str, params: Map<String, Value>) -> Self {
Self {
plugin: plugin.into(),
name: name.chars().take(MAX_NAME).collect(),
params,
transform: Affine::IDENTITY,
stroke_scale: 1.0,
effect_scale: 1.0,
pattern_transform: Affine::IDENTITY,
state: State::Intact,
}
}
/// Its art transformed by `a`, with what `sc` says scales besides its geometry.
pub fn transform(&mut self, a: Affine, sc: &Scaling) {
self.transform = a * self.transform;
if let Some(k) = Scaling::factor(a)
&& sc.strokes
{
self.stroke_scale *= k;
if sc.effects.is_some() {
self.effect_scale *= k;
}
}
if sc.patterns {
self.pattern_transform = a * self.pattern_transform;
}
}
/// Places `art`, drawn by the generator as it is drawn untransformed, as the object's art has
/// been transformed since it was drawn: its geometry, stroke weights, effect distances and
/// pattern tiles. `scale` scales an effect's distance parameters (the effects catalogue's).
pub fn place(&self, art: &mut Node, scale: fn(&mut Effect, f64)) {
if self.transform != Affine::IDENTITY {
art.transform(self.transform, false);
}
self.restyle(art, scale);
}
/// Scales the strokes and effects of `n` and its descendants, and transforms their pattern
/// tiles, as [`Self::place`] says.
fn restyle(&self, n: &mut Node, scale: fn(&mut Effect, f64)) {
if self.stroke_scale != 1.0 {
n.appearance.scale_strokes(self.stroke_scale);
}
if self.effect_scale != 1.0 {
n.appearance.scale_effects(self.effect_scale, scale);
}
if self.pattern_transform != Affine::IDENTITY {
crate::pattern::transform_pattern_paints(n, self.pattern_transform);
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
self.restyle(std::sync::Arc::make_mut(c), scale);
}
}
}
/// Can its art be drawn again: are its fields intact or only its art changed?
pub fn redrawable(&self) -> bool {
self.state != State::Damaged
}
}
/// Is `id` shaped as a plug-in id: 1 to [`MAX_ID`] characters from `A-Z a-z 0-9 . _ -`?
pub fn valid_id(id: &str) -> bool {
(1..=MAX_ID).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
}
std::thread_local! {
/// Is a generated art object's art being written on this thread ([`Inside`])?
static INSIDE: Cell<bool> = const { Cell::new(false) };
}
#[cfg(test)]
std::thread_local! {
/// The bytes [`art_hash`] has hashed on this thread.
static HASHED: Cell<usize> = const { Cell::new(0) };
}
/// While it lives, objects written on this thread are part of a generated art object's art, and
/// the generated art objects among them are written as plain art ([`written`]).
pub(crate) struct Inside(bool);
impl Inside {
pub(crate) fn enter() -> Self {
Self(INSIDE.with(|i| i.replace(true)))
}
}
impl Drop for Inside {
fn drop(&mut self) {
INSIDE.with(|i| i.set(self.0));
}
}
/// The settings `g` an object writes: none while a generated art object's art is being written.
pub(crate) fn written(g: Option<&GeneratedArt>) -> Option<&GeneratedArt> {
g.filter(|_| !INSIDE.with(Cell::get))
}
/// The SHA-256 of `children` written as JSON, in lower-case hexadecimal: what a file holds as the
/// hash of a generated art object's art. Generated art objects among them are written as plain
/// art.
pub fn art_hash(children: &[Arc<Node>]) -> String {
use sha2::{Digest, Sha256};
let bytes = {
let _inside = Inside::enter();
serde_json::to_vec(children).unwrap_or_default()
};
#[cfg(test)]
HASHED.with(|h| h.set(h.get() + bytes.len()));
Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect()
}
/// The bytes `children` take written as JSON, generated art objects among them as plain art
/// ([`MAX_ART_BYTES`]).
pub fn art_bytes(children: &[Arc<Node>]) -> usize {
let _inside = Inside::enter();
serde_json::to_vec(children).map_or(usize::MAX, |b| b.len())
}
/// Drops the settings of the generated art objects in `nodes`, among their descendants and in
/// their opacity masks' art, which become plain art; returns whether there were any. It doesn't
/// look among the children of such an object, which reading it already made plain art, only at
/// its opacity mask's art.
fn plain_art(nodes: &mut [Arc<Node>]) -> bool {
let mut found = false;
for a in nodes {
let generated = a.extras().generated.is_some();
if !generated && a.children().is_none_or(Vec::is_empty) && a.extras().mask.is_none() {
continue;
}
let n = Arc::make_mut(a);
if generated {
n.extras_mut().generated = None;
found = true;
} else if let Some(ch) = n.children_mut() {
found |= plain_art(ch);
}
if n.extras().mask.is_some()
&& let Some(m) = n.extras_mut().mask.as_mut()
{
found |= plain_art(std::slice::from_mut(&mut m.art));
}
}
found
}
/// How a file holds a generated art object's settings, borrowed from the node.
#[derive(Serialize)]
pub(crate) struct Wire<'a> {
plugin: &'a str,
name: &'a str,
params: &'a Map<String, Value>,
#[serde(skip_serializing_if = "is_identity")]
transform: &'a Affine,
#[serde(rename = "strokeScale", skip_serializing_if = "is_one")]
stroke_scale: f64,
#[serde(rename = "effectScale", skip_serializing_if = "is_one")]
effect_scale: f64,
#[serde(rename = "patternTransform", skip_serializing_if = "is_identity")]
pattern_transform: &'a Affine,
hash: String,
#[serde(skip_serializing_if = "std::ops::Not::not")]
damaged: bool,
}
fn is_identity(a: &&Affine) -> bool {
**a == Affine::IDENTITY
}
fn is_one(k: &f64) -> bool {
*k == 1.0
}
impl<'a> Wire<'a> {
/// The settings `g` of node `n`, with the hash of its art.
pub(crate) fn of(g: &'a GeneratedArt, n: &Node) -> Self {
let hash = art_hash(n.children().map_or(&[][..], Vec::as_slice));
Wire {
plugin: &g.plugin,
name: &g.name,
params: &g.params,
transform: &g.transform,
stroke_scale: g.stroke_scale,
effect_scale: g.effect_scale,
pattern_transform: &g.pattern_transform,
hash,
damaged: g.state == State::Damaged,
}
}
}
/// A saved transform `t` (absent: none): `None` when it is not six finite numbers.
fn read_affine(t: Option<Value>) -> Option<Affine> {
match t {
None => Some(Affine::IDENTITY),
Some(t) => serde_json::from_value::<Affine>(t).ok().filter(|a| a.as_coeffs().iter().all(|c| c.is_finite())),
}
}
/// A saved scale `k` (absent: 1): `None` when it is not a finite number of 0 or more. A transform
/// that flattens the art to a line or a point scales its strokes and effects by 0.
fn read_scale(k: Option<Value>) -> Option<f64> {
match k {
None => Some(1.0),
Some(k) => k.as_f64().filter(|k| k.is_finite() && *k >= 0.0),
}
}
/// The settings a file gives (`v`, its `generated` field) for a node of `kind`: `None` for anything
/// but a group, else what could be read, marked [`State::Damaged`] or [`State::Changed`] when a
/// field or the art's hash doesn't hold up. A field that can't be read is kept empty: an id is
/// kept only when it is a plug-in id, a name at most [`MAX_NAME`] characters long. Generated art
/// objects in the group's art become plain art ([`plain_art`]), and the art is then not hashed.
pub(crate) fn read(v: Value, kind: &mut NodeKind) -> Option<Box<GeneratedArt>> {
let NodeKind::Group { children, .. } = kind else { return None };
let nested = plain_art(children);
let Value::Object(mut o) = v else {
return Some(Box::new(GeneratedArt { state: State::Damaged, ..GeneratedArt::new("", "", Map::new()) }));
};
let mut damaged = !matches!(o.remove("damaged"), None | Some(Value::Bool(false)));
let plugin = match o.remove("plugin") {
Some(Value::String(id)) if valid_id(&id) => id,
_ => {
damaged = true;
String::new()
}
};
let name: String = match o.remove("name") {
Some(Value::String(n)) => n.chars().filter(|c| !c.is_control()).take(MAX_NAME).collect(),
_ => String::new(),
};
let params = match o.remove("params") {
Some(Value::Object(p)) if serde_json::to_vec(&p).is_ok_and(|b| b.len() <= MAX_PARAMS_BYTES) => p,
_ => {
damaged = true;
Map::new()
}
};
let mut affine = |key: &str| {
read_affine(o.remove(key)).unwrap_or_else(|| {
damaged = true;
Affine::IDENTITY
})
};
let transform = affine("transform");
let pattern_transform = affine("patternTransform");
let mut scale = |key: &str| {
read_scale(o.remove(key)).unwrap_or_else(|| {
damaged = true;
1.0
})
};
let stroke_scale = scale("strokeScale");
let effect_scale = scale("effectScale");
let intact = !nested && matches!(o.get("hash"), Some(Value::String(h)) if *h == art_hash(children));
let state = if damaged {
State::Damaged
} else if intact {
State::Intact
} else {
State::Changed
};
Some(Box::new(GeneratedArt { plugin, name, params, transform, stroke_scale, effect_scale, pattern_transform, state }))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::node::NodeId;
use serde_json::json;
use std::sync::Arc;
use vectorcraft_geom::{Rect, shapes};
fn art() -> Node {
let square = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default());
let mut g = Node::group(NodeId(1), vec![Arc::new(square)]);
let mut params = Map::new();
params.insert("size".into(), json!(10));
g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", params)));
g
}
fn reread(v: &Value) -> Node {
serde_json::from_value(v.clone()).unwrap()
}
/// `depth` generated art objects, each the only child of the one around it, the innermost
/// [`art`].
fn nested(depth: usize) -> Node {
let mut n = art();
for i in 1..depth {
let mut g = Node::group(NodeId(10 + i as u64), vec![Arc::new(n)]);
g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", Map::new())));
n = g;
}
n
}
/// The bytes [`art_hash`] hashes while `f` runs.
fn hashed<T>(f: impl FnOnce() -> T) -> (T, usize) {
HASHED.with(|h| h.set(0));
let out = f();
(out, HASHED.with(Cell::get))
}
/// The generated art objects in `n` and below it, outermost first, as (depth, state).
fn generated_in(n: &Node) -> Vec<(usize, State)> {
let mut out = vec![];
let mut at = Some((n, 0));
while let Some((n, d)) = at {
if let Some(g) = &n.extras().generated {
out.push((d, g.state));
}
at = n.children().and_then(|c| c.first()).map(|c| (&**c, d + 1));
}
out
}
/// Generated art objects nested in one another are written with the outermost one's settings
/// alone, so writing and reading them hash each object's art once, however deep they nest; a
/// file that has settings on the inner ones anyway loses them, without hashing.
#[test]
fn nested_generated_art_is_written_and_read_with_its_art_hashed_once() {
crate::depth::with_deep_stack(|| {
for depth in [16, 200] {
let n = nested(depth);
let (bytes, writing) = hashed(|| serde_json::to_vec(&n).unwrap());
assert!(writing <= bytes.len(), "{depth} deep: {writing} bytes hashed to write {}", bytes.len());
assert_eq!(String::from_utf8_lossy(&bytes).matches("\"generated\"").count(), 1, "{depth} deep");
let v = serde_json::to_value(&n).unwrap();
let (back, reading) = hashed(|| reread(&v));
assert!(reading <= bytes.len(), "{depth} deep: {reading} bytes hashed to read {}", bytes.len());
assert_eq!(generated_in(&back), vec![(0, State::Intact)], "{depth} deep");
// Settings on every level, each with a hash: none is hashed, the inner ones are
// dropped, and the outermost reads as changed.
let mut crafted = v.clone();
let settings = v["generated"].clone();
let mut at = crafted.pointer_mut("/kind/children/0");
while let Some(c) = at {
if c.pointer("/kind/children/0").is_some() {
c["generated"] = settings.clone();
}
at = c.pointer_mut("/kind/children/0");
}
let (crafted_back, reading) = hashed(|| reread(&crafted));
assert!(reading <= bytes.len(), "{depth} deep, crafted: {reading} bytes hashed to read {}", bytes.len());
assert_eq!(generated_in(&crafted_back), vec![(0, State::Changed)], "{depth} deep, crafted");
assert_eq!(crafted_back.children(), back.children(), "{depth} deep, crafted");
}
});
}
/// A generated art object inside another one's art, whose opacity mask's art is a generated art
/// object too, reads as plain art with plain mask art.
#[test]
fn a_nested_generated_art_objects_mask_art_reads_as_plain_art() {
let mut inner = art();
inner.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(art(), true)));
let mut outer = Node::group(NodeId(20), vec![Arc::new(inner)]);
outer.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", Map::new())));
let v = serde_json::to_value(&outer).unwrap();
assert!(v.pointer("/kind/children/0/generated").is_none() && v.pointer("/kind/children/0/mask/art/generated").is_none());
let mut crafted = v.clone();
let settings = v["generated"].clone();
crafted["kind"]["children"][0]["generated"] = settings.clone();
crafted["kind"]["children"][0]["mask"]["art"]["generated"] = settings;
let back = reread(&crafted);
assert_eq!(back.extras().generated.as_ref().map(|g| g.state), Some(State::Changed));
let inner = &back.children().unwrap()[0];
assert!(inner.extras().generated.is_none());
assert!(inner.extras().mask.as_ref().is_some_and(|m| m.art.extras().generated.is_none()));
assert_eq!(back.children(), reread(&v).children());
}
/// A generated art object inside plain groups is still checked against its hash: intact as
/// written, changed when its art is tampered with.
#[test]
fn a_generated_art_object_deep_in_plain_groups_keeps_its_hash_check() {
crate::depth::with_deep_stack(|| {
let mut n = art();
for i in 1..200 {
n = Node::group(NodeId(10 + i as u64), vec![Arc::new(n)]);
}
let v = serde_json::to_value(&n).unwrap();
let state = |v: &Value| generated_in(&reread(v)).into_iter().map(|(_, s)| s).collect::<Vec<_>>();
assert_eq!(state(&v), vec![State::Intact]);
let mut tampered = v.clone();
let mut at = tampered.pointer_mut("/kind/children/0");
while let Some(c) = at {
if c.get("generated").is_some() {
c["kind"]["children"][0]["name"] = json!("tampered");
break;
}
at = c.pointer_mut("/kind/children/0");
}
assert_eq!(state(&tampered), vec![State::Changed]);
});
}
/// A generated art object writes its plug-in, name, parameters and the hash of its art, and
/// reads back the same, intact.
#[test]
fn a_generated_art_object_round_trips_with_the_hash_of_its_art() {
let g = art();
let v = serde_json::to_value(&g).unwrap();
let saved = &v["generated"];
assert_eq!((&saved["plugin"], &saved["name"], &saved["params"]), (&json!("org.example.gen"), &json!("Squares"), &json!({"size": 10})));
assert_eq!(saved["hash"], json!(art_hash(g.children().unwrap())));
assert!(saved.get("transform").is_none());
let back = reread(&v);
assert_eq!(back, g);
assert_eq!(back.extras().generated.as_ref().map(|a| a.state), Some(State::Intact));
// A moved object keeps its transform.
let mut moved = g.clone();
moved.transform(Affine::translate((5.0, 0.0)), false);
let back = reread(&serde_json::to_value(&moved).unwrap());
assert_eq!(back.extras().generated.as_ref().map(|a| (a.transform, a.state)), Some((Affine::translate((5.0, 0.0)), State::Intact)));
// A scale with Scale Strokes & Effects and Transform Patterns keeps what it scaled.
let mut scaled = g.clone();
let sc = Scaling { strokes: true, patterns: true, ..Scaling::default() };
scaled.transform(Affine::scale(2.0), sc);
scaled.transform(Affine::scale(3.0), false);
let back = reread(&serde_json::to_value(&scaled).unwrap());
let a = back.extras().generated.as_deref().unwrap();
assert_eq!((a.stroke_scale, a.effect_scale, a.pattern_transform, a.state), (2.0, 1.0, Affine::scale(2.0), State::Intact));
assert_eq!(a.transform, Affine::scale(6.0));
// A transform that flattens it to a point, with Scale Strokes & Effects on, scales its
// strokes and effects by 0, and it reads back intact with those scales.
let mut flat = g.clone();
flat.transform(Affine::new([0.0; 6]), Scaling { strokes: true, effects: Some(|_, _| {}), ..Scaling::default() });
let back = reread(&serde_json::to_value(&flat).unwrap());
let a = back.extras().generated.as_deref().unwrap();
assert_eq!((a.stroke_scale, a.effect_scale, a.state), (0.0, 0.0, State::Intact));
}
/// Art that doesn't match the file's hash, and fields that can't be read, keep the art and say
/// how the object was read; a garbled id is never kept.
#[test]
fn damaged_fields_and_changed_art_keep_the_art() {
let g = art();
let v = serde_json::to_value(&g).unwrap();
let state = |v: &Value| reread(v).extras().generated.as_ref().map(|a| (a.plugin.clone(), a.state));
// The art edited, with the hash of the art before.
let mut edited = g.clone();
if let Some(c) = edited.children_mut().and_then(|c| c.first_mut()) {
Arc::make_mut(c).transform(Affine::translate((1.0, 0.0)), false);
}
let mut changed = serde_json::to_value(&edited).unwrap();
changed["generated"]["hash"] = v["generated"]["hash"].clone();
assert_eq!(state(&changed), Some(("org.example.gen".into(), State::Changed)));
let mut no_hash = v.clone();
no_hash["generated"].as_object_mut().unwrap().remove("hash");
assert_eq!(state(&no_hash), Some(("org.example.gen".into(), State::Changed)));
for (field, bad) in [
("plugin", json!("../evil")),
("plugin", json!("x".repeat(65))),
("plugin", json!("")),
("plugin", json!("a\u{0}b")),
("plugin", json!(7)),
("params", json!([1, 2])),
("params", json!({"blob": "x".repeat(MAX_PARAMS_BYTES)})),
("transform", json!("sideways")),
("transform", Value::Null),
("strokeScale", json!(-2.0)),
("strokeScale", Value::Null),
("strokeScale", json!("big")),
("effectScale", json!(-0.5)),
("patternTransform", json!([1, 0, 0, 1, 0])),
("patternTransform", Value::Null),
("effectScale", Value::Null),
("damaged", json!(true)),
("damaged", json!("no")),
] {
let mut w = v.clone();
w["generated"][field] = bad;
let back = reread(&w);
let a = back.extras().generated.as_ref().unwrap();
assert_eq!(a.state, State::Damaged, "{field}");
assert!(a.plugin.is_empty() || a.plugin == "org.example.gen", "{field}: {}", a.plugin);
assert_eq!(back.children(), g.children(), "{field}");
// Saved again and read back, it stays damaged.
let again = reread(&serde_json::to_value(&back).unwrap());
assert_eq!(again.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged), "{field} saved again");
}
// Not an object at all.
let mut w = v.clone();
w["generated"] = json!("art");
assert_eq!(state(&w), Some((String::new(), State::Damaged)));
// A null field is read as a field that can't be read, not as an absent one, from a value
// and from a file's text; the art stays, and saved again the object stays damaged.
let mut w = v.clone();
w["generated"] = Value::Null;
assert_eq!(state(&w), Some((String::new(), State::Damaged)));
let back: Node = serde_json::from_str(&w.to_string()).unwrap();
assert_eq!(back.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged));
assert_eq!(back.children(), g.children());
let again = reread(&serde_json::to_value(&back).unwrap());
assert_eq!(again.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged));
// On a path the field is dropped, and the path stays as it was.
let path = g.children().unwrap()[0].clone();
let mut p = serde_json::to_value(&*path).unwrap();
p["generated"] = v["generated"].clone();
let back = reread(&p);
assert!(back.extras().generated.is_none());
assert_eq!(back, *path);
// A name is cut to its limit and loses control characters.
let mut w = v.clone();
w["generated"]["name"] = json!(format!("A\u{202e}\n{}", "n".repeat(100)));
let back = reread(&w);
let name = &back.extras().generated.as_ref().unwrap().name;
assert_eq!(name.chars().count(), MAX_NAME);
assert!(!name.chars().any(char::is_control));
}
}
+1
View File
@@ -18,6 +18,7 @@ pub mod decode;
pub mod depth;
pub mod dimension;
pub mod flare;
pub mod generated;
pub mod graph;
mod halftone_radii;
pub mod hit;
+139 -18
View File
@@ -385,26 +385,53 @@ fn find_type(n: &Node, typed: &mut std::collections::HashSet<usize>) -> bool {
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box. Type
/// that draws nothing has its laid-out box with `blank_type_box`, and no box without it.
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine, blank_type_box: bool) -> Option<Rect> {
let mut typed = std::collections::HashSet::new();
find_type(n, &mut typed);
let mut typed = Typed::default();
find_type(n, &mut typed.holds);
content_box_in(n, stroked, to, &typed, blank_type_box)
}
/// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]).
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>, blank_type_box: bool) -> Option<Rect> {
// `n` in the axes of `to`.
let moved = || {
if to == Affine::IDENTITY {
return std::borrow::Cow::Borrowed(&**n);
}
let mut m = (**n).clone();
m.transform(to, true);
std::borrow::Cow::Owned(m)
};
let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() };
if !typed.contains(&(Arc::as_ptr(n) as usize)) {
return own(&moved());
/// The objects in an envelope's contents that hold type ([`find_type`]), by address, and the
/// boxes [`content_box_in`] has measured for them with their strokes, so that measuring a
/// container's own strokes along its members ([`container_strokes_in`]) does not measure them
/// again.
#[derive(Default)]
struct Typed {
holds: std::collections::HashSet<usize>,
stroked: std::cell::RefCell<std::collections::HashMap<usize, Option<Rect>>>,
}
/// `n` in the axes of `to`, with its strokes scaled as [`Node::transform`] scales them.
fn moved_into(n: &Node, to: Affine) -> std::borrow::Cow<'_, Node> {
if to == Affine::IDENTITY {
return std::borrow::Cow::Borrowed(n);
}
let mut m = n.clone();
m.transform(to, true);
std::borrow::Cow::Owned(m)
}
/// [`content_box`], with the objects in `n` that hold type ([`Typed`]).
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &Typed, blank_type_box: bool) -> Option<Rect> {
let key = Arc::as_ptr(n) as usize;
if !typed.holds.contains(&key) {
let m = moved_into(n, to);
return if stroked { m.visual_bounds() } else { m.geometric_bounds() };
}
if !stroked {
return typed_box_in(n, false, to, typed, blank_type_box);
}
if let Some(b) = typed.stroked.borrow().get(&key) {
return *b;
}
let b = typed_box_in(n, true, to, typed, blank_type_box);
typed.stroked.borrow_mut().insert(key, b);
b
}
/// [`content_box_in`] of `n`, which holds type.
fn typed_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &Typed, blank_type_box: bool) -> Option<Rect> {
let moved = || moved_into(n, to);
let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() };
match &n.kind {
NodeKind::Text(t) => {
// Type in perspective: its outlines as its projection draws them.
@@ -445,11 +472,16 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
let members = n.editing_children().iter();
if stroked {
// The container's own strokes, scaled by `to` as `Node::transform` scales them,
// without copying its members.
// measured along its members as in `Node::visual_bounds`.
let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false });
own_strokes.appearance = n.appearance.clone();
own_strokes.transform(to, true);
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed, blank_type_box)))
let painted = own_strokes.appearance.painted_strokes().next().is_some();
members.fold(None, |acc, c| {
let b = content_box_in(c, true, to, typed, blank_type_box);
let own = if painted { container_strokes_in(c, &own_strokes.appearance, Some(b), to, typed, blank_type_box) } else { None };
vectorcraft_geom::union_opt(vectorcraft_geom::union_opt(acc, b), own)
})
} else {
members
.filter(|c| c.visible || !layer)
@@ -460,6 +492,44 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
}
}
/// The box the strokes of `appearance`, the appearance of a group or layer that holds `n` scaled
/// by `to`, paint along `n` in the axes of `to`, as [`Node::painted_by_container`] measures them;
/// `measured` is the box [`content_box_in`] gives `n` with its strokes, when known. Type, alone or
/// in a clip group, has that box grown by the farthest the strokes can reach
/// ([`crate::Appearance::outset`]); the strokes paint nothing round hidden members and guides.
fn container_strokes_in(
n: &Arc<Node>,
appearance: &crate::Appearance,
measured: Option<Option<Rect>>,
to: Affine,
typed: &Typed,
blank_type_box: bool,
) -> Option<Rect> {
if !n.visible || n.is_guide() {
return None;
}
if !typed.holds.contains(&(Arc::as_ptr(n) as usize)) {
if to == Affine::IDENTITY {
return n.painted_by_container(appearance, None);
}
// Moved with its own strokes scaled, as `content_box_in` moves it, for a member measured
// by its visual box.
let mut m = (**n).clone();
m.transform(to, true);
return m.painted_by_container(appearance, None);
}
match &n.kind {
NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } if !n.is_compound_shape() => n
.editing_children()
.iter()
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, container_strokes_in(c, appearance, None, to, typed, blank_type_box))),
_ => {
let o = appearance.outset();
measured.unwrap_or_else(|| content_box_in(n, true, to, typed, blank_type_box)).map(|b| b.inflate(o, o))
}
}
}
/// The lengths the top, bottom, left and right [`EnvelopeOptions::bounds_margin`] of content with
/// geometric bounds `plain` are shares of: its height for the top and bottom and its width for the
/// left and right. A side shorter than 1e-6 pt takes the other side's length, so a stroked straight
@@ -881,6 +951,57 @@ mod tests {
assert!(content_box(&nested, false, Affine::IDENTITY, true).is_some());
}
/// A group of type and a square with its own 10 pt miter-joined stroke reaches 5 pt past the
/// square in a scaled frame, as the group moved into the frame does ([`Node::visual_bounds`]),
/// not the 50 pt a miter spike could reach. Round a clip group they reach that far past its
/// box, with the clipping path's own stroke scaled into the frame, and in nested groups too.
#[test]
fn a_groups_own_miter_stroke_is_measured_along_its_members_with_type() {
let paint = |fill, stroke, w| crate::Appearance::basic(fill, stroke, w);
let path = |id, r: Rect| {
let square = vectorcraft_geom::shapes::rectangle(r);
Arc::new(Node::path(NodeId(id), square, paint(vectorcraft_color::Paint::solid(Color::BLACK), vectorcraft_color::Paint::None, 0.0)))
};
let text = type_node(1, "Type");
let mut group = Node::group(NodeId(2), vec![text, path(3, Rect::new(100.0, 100.0, 200.0, 200.0))]);
group.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into();
assert_eq!(group.appearance.outset(), 50.0, "a 10 pt miter-joined stroke can reach 50 pt");
let group = Arc::new(group);
let to = Affine::scale(0.5);
let mut moved = (*group).clone();
moved.transform(to, true);
let want = moved.visual_bounds();
// The square's lower right corner, 100 pt in the frame, with half the 5 pt scaled stroke.
assert_eq!(want.map(|b| (b.x1, b.y1)), Some((102.5, 102.5)));
assert_eq!(content_box(&group, true, to, true), want);
// A clip group whose clipping path has a 40 pt stroke, which the group's own strokes grow
// by their reach, measured with that stroke scaled into the frame.
let mut clip = (*path(5, Rect::new(300.0, 300.0, 400.0, 400.0))).clone();
clip.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 40.0).into();
let clipped =
Node::new(NodeId(4), NodeKind::Group { children: vec![Arc::new(clip), path(6, Rect::new(320.0, 320.0, 380.0, 380.0))], clip: true });
let mut group = Node::group(NodeId(2), vec![type_node(1, "Type"), Arc::new(clipped)]);
group.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into();
let group = Arc::new(group);
let mut moved = (*group).clone();
moved.transform(to, true);
let want = moved.visual_bounds();
// 200 pt in the frame, with half the 20 pt scaled clip stroke and the 25 pt scaled reach.
assert_eq!(want.map(|b| (b.x1, b.y1)), Some((235.0, 235.0)));
assert_eq!(content_box(&group, true, to, true), want);
// Stroked groups of type nested in plain groups, each measured once.
let mut nested = group;
for i in 0..50 {
let plain = Arc::new(Node::group(NodeId(100 + 2 * i), vec![nested]));
let mut stroked = Node::group(NodeId(101 + 2 * i), vec![type_node(1, "Type"), plain]);
stroked.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into();
nested = Arc::new(stroked);
}
let mut moved = (*nested).clone();
moved.transform(to, true);
assert_eq!(content_box(&nested, true, to, true), moved.visual_bounds());
}
/// A warp envelope of `style` at `bend` with map `version` around a 200×100 rectangle at
/// (100, 50).
fn warp_node(style: &str, bend: f64, h: f64, version: u32) -> Node {
+4
View File
@@ -286,6 +286,10 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
.map_or(0, |m| ALLOC + size_of::<crate::color_mask::ColorMask>() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3);
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
b += e.flare.as_ref().map_or(0, |f| ALLOC + size_of::<crate::flare::FlareSpec>() + json_bytes(&f.params));
b += e
.generated
.as_ref()
.map_or(0, |g| ALLOC + size_of::<crate::generated::GeneratedArt>() + g.plugin.capacity() + g.name.capacity() + map_bytes(&g.params));
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
if e.intertwine_tiers.capacity() > 0 {
b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>();
+4
View File
@@ -96,6 +96,9 @@ pub struct NodeExtras {
/// (top left, top right, bottom right, bottom left in pixel space) stand on the page when they
/// do not make a parallelogram, which its transform alone could place ([`crate::image_quad`]).
pub image_quad: Option<Box<[Point; 4]>>,
/// Generated art object: the generator plug-in and parameters its group's children were drawn
/// with (`plugin.generate`); its ordinary group children hold its art ([`crate::generated`]).
pub generated: Option<Box<crate::generated::GeneratedArt>>,
}
/// No extras: what [`Node::extras`] gives for a node without any.
@@ -129,6 +132,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
warp_piece: false,
clip_pieces: false,
image_quad: None,
generated: None,
};
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
+81 -18
View File
@@ -463,14 +463,76 @@ impl Node {
self.visual(Some(symbols))
}
/// The visual box of a group or layer without a clipping path, from the visual boxes of its
/// [`Node::editing_children`]: for a walk that measures the members as well.
/// A box round a group or layer without a clipping path, from boxes round its
/// [`Node::editing_children`], grown by the farthest its own strokes can reach from any path
/// ([`Appearance::outset`]): for boxes measured where the members' shapes are not at hand.
/// [`Node::visual_of_measured_members`] measures the strokes along the members.
pub fn visual_of_members(&self, members: impl Iterator<Item = Option<Rect>>) -> Option<Rect> {
// The container's own strokes paint around its members.
let o = self.appearance.outset();
members.fold(None, vectorcraft_geom::union_opt).map(|b| b.inflate(o, o))
}
/// The visual box of a group or layer without a clipping path, from its
/// [`Node::editing_children`] paired with their visual boxes: for a walk that measures the
/// members as well. The container's own strokes are measured along the shape of each member
/// path and compound path, at any depth in its groups; they paint nothing round images, symbol
/// instances, guides and hidden members, and grow the box of any other member by the farthest
/// they can reach ([`Appearance::outset`]), measured with `symbols` as in
/// [`Node::visual_bounds_with`].
pub fn visual_of_measured_members<'a>(
&self,
members: impl Iterator<Item = (&'a Node, Option<Rect>)>,
symbols: Option<&SymbolBoxes>,
) -> Option<Rect> {
let stroked = self.appearance.painted_strokes().next().is_some();
members.fold(None, |acc, (c, b)| {
let own = if stroked { c.strokes_of_container(&self.appearance, Some(b), symbols) } else { None };
vectorcraft_geom::union_opt(vectorcraft_geom::union_opt(acc, b), own)
})
}
/// The box the strokes of `appearance`, the appearance of a group or layer that holds this
/// object, paint along it, measured with `symbols` as in [`Node::visual_bounds_with`]: the box
/// [`Node::visual_of_measured_members`] takes in for this member besides its own visual box.
pub fn painted_by_container(&self, appearance: &Appearance, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
appearance.painted_strokes().next()?;
self.strokes_of_container(appearance, None, symbols)
}
/// The box the strokes of `appearance`, a container's, paint along this member, whose visual
/// box is `measured` when known: along the shape of a path or compound path, as it measures its
/// own strokes ([`Appearance::stroked_bounds`]); along the members of a group or layer without
/// a clipping path that is not a compound shape; nothing for a hidden member, a guide, an image
/// or a symbol instance, which the strokes do not paint; and the member's visual box grown by
/// the farthest the strokes can reach ([`Appearance::outset`]) for anything else.
fn strokes_of_container(&self, appearance: &Appearance, measured: Option<Option<Rect>>, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
if !self.visible || self.is_guide() {
return None;
}
match &self.kind {
NodeKind::Path { .. } | NodeKind::Compound { .. } => self.stroked_by(appearance, symbols),
NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } if !self.is_compound_shape() => self
.editing_children()
.iter()
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.strokes_of_container(appearance, None, symbols))),
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => None,
_ => {
let o = appearance.outset();
measured.unwrap_or_else(|| self.visual(symbols)).map(|b| b.inflate(o, o))
}
}
}
/// The visual box of this path or compound path painted with the strokes of `appearance`,
/// measured along its shape ([`Appearance::stroked_bounds`]).
fn stroked_by(&self, appearance: &Appearance, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
let dots = appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?;
Some(appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default()))
}
/// The box of [`Node::visual_bounds`], or of [`Node::visual_bounds_with`] when `symbols` is
/// given.
pub(crate) fn visual(&self, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
@@ -485,7 +547,9 @@ impl Node {
}
}
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))),
NodeKind::Layer { .. } | NodeKind::Group { .. } => self.visual_of_members(self.editing_children().iter().map(|c| c.visual(symbols))),
NodeKind::Layer { .. } | NodeKind::Group { .. } => {
self.visual_of_measured_members(self.editing_children().iter().map(|c| (c.as_ref(), c.visual(symbols))), symbols)
}
NodeKind::Blend { children, spec } => {
let b = children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols)));
let o = crate::live::max_outset(children, symbols);
@@ -495,12 +559,7 @@ impl Node {
let o = crate::live::max_outset(content, symbols);
self.geometric(symbols).map(|b| b.inflate(o, o))
}
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
let dots = self.appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?;
Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default()))
}
NodeKind::Path { .. } | NodeKind::Compound { .. } => self.stroked_by(&self.appearance, symbols),
NodeKind::SymbolInstance { symbol, xf } => {
let b = match symbols.and_then(|s| Some((s, s.art(symbol)?))) {
Some((s, art)) if !s.art_strokes() => xf.transform_rect_bbox(art.geometric),
@@ -552,19 +611,23 @@ impl Node {
self.children()?.iter().find(|c| c.id == r.path)?.path_data()
}
fn transform_scaled(&mut self, a: Affine, sc: &Scaling) {
// A dimension's measurement moves with it.
if let Some(e) = self.extras_if_any()
&& let Some(dimension) = &mut e.dimension
{
/// Moves what `a` moves in the node's extras: a dimension's measurement, a flare's center and
/// end point, and the place a generator's art is drawn again at, with what `sc` scales.
fn transform_extras(&mut self, a: Affine, sc: &Scaling) {
let Some(e) = self.extras_if_any() else { return };
if let Some(dimension) = &mut e.dimension {
dimension.transform(a);
}
// So does a flare's center and end point.
if let Some(e) = self.extras_if_any()
&& let Some(flare) = &mut e.flare
{
if let Some(flare) = &mut e.flare {
flare.transform(a);
}
if let Some(generated) = &mut e.generated {
generated.transform(a, sc);
}
}
fn transform_scaled(&mut self, a: Affine, sc: &Scaling) {
self.transform_extras(a, sc);
// The path the objects are attached to, before it is transformed.
let on_path_before = self.on_path_data().cloned();
// A distorted image's placement nearest its corners, before they are transformed (`None`
+46
View File
@@ -537,6 +537,52 @@ fn visual_of_members_unions_the_members_and_grows_by_the_group_stroke() {
assert_eq!(g.visual_of_members([].into_iter()), None);
}
/// A group's or layer's own miter-joined stroke is measured along its members' shapes, as a
/// path's is: a 10 pt stroke round a square reaches 5 pt past it, not the 50 pt a miter spike
/// could reach, through nested groups and in a turned frame too. It paints nothing round a hidden
/// member or an image.
#[test]
fn a_containers_own_miter_stroke_is_measured_along_its_members() {
use vectorcraft_color::{Color, Paint};
let path = |id, r: Rect| Arc::new(Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)));
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0);
assert_eq!(stroke.outset(), 50.0, "a 10 pt miter-joined stroke can reach 50 pt");
let stroked = |mut n: Node| {
n.appearance = stroke.clone().into();
n
};
let square = Rect::new(100.0, 100.0, 200.0, 200.0);
let around = Some(Rect::new(95.0, 95.0, 205.0, 205.0));
assert_eq!(stroked(Node::group(NodeId(1), vec![path(2, square)])).visual_bounds(), around, "a group");
let nested = Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(3), vec![path(2, square)]))]);
assert_eq!(stroked(nested.clone()).visual_bounds(), around, "a nested group");
// Measured in a turned frame, as a box square to a turned selection is.
let turned = stroked(nested).bounds_in(&crate::Document::new(400.0, 400.0).symbol_boxes(), Affine::rotate(std::f64::consts::FRAC_PI_2), true);
let want = Rect::new(-205.0, 95.0, -95.0, 205.0);
assert!(
turned.is_some_and(|b| (b.x0 - want.x0).abs() + (b.y0 - want.y0).abs() + (b.x1 - want.x1).abs() + (b.y1 - want.y1).abs() < 1e-9),
"{turned:?}"
);
let mut layer = Node::layer(NodeId(1), "Layer 1", LayerColor::Preset(0));
if let NodeKind::Layer { children, .. } = &mut layer.kind {
children.push(path(2, square));
}
assert_eq!(stroked(layer).visual_bounds(), around, "a layer");
let mut hidden = (*path(3, Rect::new(100.0, 300.0, 200.0, 400.0))).clone();
hidden.visible = false;
let image = ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: Affine::translate((500.0, 100.0)),
link: None,
placement: Default::default(),
pixels: None,
};
let kids = vec![path(2, square), Arc::new(hidden), Arc::new(Node::new(NodeId(4), NodeKind::Image(Box::new(image))))];
assert_eq!(stroked(Node::group(NodeId(1), kids)).visual_bounds(), Some(Rect::new(95.0, 95.0, 510.0, 400.0)), "a hidden member and an image");
}
/// Type's visual bounds grow by how far its character strokes paint past the glyphs: half the
/// weight centred, the whole weight outside, nothing inside; scaled with the type.
#[test]
+15 -1
View File
@@ -18,6 +18,7 @@ impl Serialize for Node {
use crate::skip::{is_default, is_one, is_true};
use serde::ser::SerializeStruct;
let e = self.extras();
let generated = crate::generated::written(e.generated.as_deref());
// As the derive did: the fields written, then each field written or skipped in order.
let skips = [
false,
@@ -61,6 +62,7 @@ impl Serialize for Node {
is_default(&e.warp_piece),
is_default(&e.clip_pieces),
e.image_quad.is_none(),
generated.is_none(),
];
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
let mut skip = skips.into_iter();
@@ -87,6 +89,8 @@ impl Serialize for Node {
field!("type_outlines", &e.type_outlines);
field!("pixelated", &e.pixelated);
field!("shaper", &e.shaper);
// A generated art object's art, written while this lives, holds plain art only.
let _inside = generated.map(|_| crate::generated::Inside::enter());
field!("kind", &self.kind);
field!("graphic_style", &e.graphic_style);
field!("attrs", &e.attrs);
@@ -110,6 +114,7 @@ impl Serialize for Node {
field!("warp_piece", &e.warp_piece);
field!("clip_pieces", &e.clip_pieces);
field!("image_quad", &e.image_quad);
field!("generated", &generated.map(|g| crate::generated::Wire::of(g, self)));
st.end()
}
}
@@ -265,6 +270,14 @@ pub(super) struct NodeWire {
clip_pieces: bool,
#[serde(default, deserialize_with = "image_corners")]
image_quad: Option<Box<[vectorcraft_geom::Point; 4]>>,
/// Read as it is and checked against the node's kind and art ([`crate::generated`]).
#[serde(default, deserialize_with = "present_value")]
generated: Option<serde_json::Value>,
}
/// A field's value as a file holds it, a null included: only an absent field is none.
fn present_value<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<serde_json::Value>, D::Error> {
serde_json::Value::deserialize(d).map(Some)
}
/// A distorted image's corners as a file holds them: a list of exactly four points, else none (the
@@ -455,7 +468,7 @@ fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Box<[v
}
impl From<NodeWire> for Node {
fn from(w: NodeWire) -> Self {
fn from(mut w: NodeWire) -> Self {
// Corners an image cannot take are dropped, so a later transform cannot make them its own.
let image_quad = match &w.kind {
NodeKind::Image(im) => w.image_quad.filter(|q| crate::image_quad::check_for(im, q).is_ok()),
@@ -491,6 +504,7 @@ impl From<NodeWire> for Node {
warp_piece: w.warp_piece,
clip_pieces: w.clip_pieces,
image_quad,
generated: w.generated.and_then(|g| crate::generated::read(g, &mut w.kind)),
};
Node {
id: w.id,
+10 -4
View File
@@ -121,10 +121,16 @@ impl Node {
pub fn bounds_in(&self, symbols: &SymbolBoxes, a: Affine, visual: bool) -> Option<Rect> {
match &self.kind {
NodeKind::Group { clip: false, .. } => {
let b = self.editing_children().iter().fold(None, |acc, c| union_opt(acc, c.bounds_in(symbols, a, visual)));
// The group's own strokes paint around its members (as in `visual_bounds`).
let o = if visual { self.appearance.outset() } else { 0.0 };
b.map(|b| b.inflate(o, o))
// The group's own strokes paint along its members, placed by `a` (as in `visual_bounds`).
let stroked = visual && self.appearance.painted_strokes().next().is_some();
self.editing_children().iter().fold(None, |acc, c| {
let own = stroked.then(|| {
let mut placed = (**c).clone();
placed.transform(a, false);
placed.painted_by_container(&self.appearance, Some(symbols))
});
union_opt(union_opt(acc, c.bounds_in(symbols, a, visual)), own.flatten())
})
}
NodeKind::Group { children, clip: true } => {
let clip = children.first()?;
+5 -1
View File
@@ -425,9 +425,13 @@ pub fn uses_pattern(n: &Node, name: Option<&str>) -> bool {
}
/// Transform Patterns without Transform Objects: `m` moves the pattern tiles of `n` and of
/// everything inside it, and the art stays where it is.
/// everything inside it, and the art stays where it is. A generated art object keeps the move, so
/// its art drawn again has its tiles moved too.
pub fn transform_patterns_only(n: &mut Node, m: Affine) {
transform_pattern_paints(n, m);
if let Some(g) = n.extras_if_any().and_then(|e| e.generated.as_deref_mut()) {
g.pattern_transform = m * g.pattern_transform;
}
for c in n.children_mut().into_iter().flatten() {
transform_patterns_only(Arc::make_mut(c), m);
}
+27 -8
View File
@@ -600,21 +600,40 @@ pub const SLANT_INSTANCES: usize = 4096;
impl crate::Node {
/// Does a visible stroke of this object, of an object in it or of an object in a symbol
/// instance's art from `symbols`, placed by `a`, stop at the corners of a segment at a slant
/// ([`Appearance::has_slanted_stroke_corners`])? Past [`SLANT_INSTANCES`] instances it answers
/// yes.
/// ([`Appearance::has_slanted_stroke_corners`])? The strokes of a group or layer without a
/// clipping path count along the paths and compound paths in it, which they paint along
/// ([`crate::Node::painted_by_container`]). Past [`SLANT_INSTANCES`] instances it answers yes.
pub fn has_slanted_stroke_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES), &[])
}
/// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into.
fn slanted_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
/// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into, and the
/// appearances of the groups and layers around this object whose strokes paint along it in
/// `around`.
fn slanted_corners(
&self,
symbols: &crate::SymbolBoxes,
a: vectorcraft_geom::Affine,
left: &std::cell::Cell<usize>,
around: &[&Appearance],
) -> bool {
if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind {
let Some(l) = left.get().checked_sub(1) else { return true };
left.set(l);
return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left)).unwrap_or(false);
return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left, &[])).unwrap_or(false);
}
(self.appearance.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_stroke_corners(&bp, a)))
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left)))
let slanted = |ap: &Appearance| ap.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| ap.has_slanted_stroke_corners(&bp, a));
let shaped = matches!(self.kind, crate::NodeKind::Path { .. } | crate::NodeKind::Compound { .. });
if slanted(&self.appearance) || shaped && around.iter().any(|ap| slanted(ap)) {
return true;
}
let plain =
matches!(self.kind, crate::NodeKind::Group { clip: false, .. } | crate::NodeKind::Layer { clip: false, .. }) && !self.is_compound_shape();
let mut inner: Vec<&Appearance> = if plain { around.to_vec() } else { vec![] };
if plain && self.appearance.has_cornered_stroke() {
inner.push(&self.appearance);
}
self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left, &inner)))
}
}
+42
View File
@@ -187,6 +187,48 @@ impl Selection {
self.key_anchor = None;
}
}
/// Select `id` itself in place of the selected object around it, keeping the rest of that
/// object selected. The outermost selected object that holds `id` (a group, or a compound path
/// selected whole) and every selected object between it and `id` leave the selection. In their
/// place go, at the outermost one's position, the objects inside them on the way down to `id`,
/// level by level: at each level the objects beside the one that holds `id`, and at the last
/// level `id` and the objects beside it, each level in stacking order. A Shaper Group's
/// original shapes, and objects that are hidden, locked or on a locked artboard
/// ([`Document::is_editable`]), are not taken in.
///
/// When `id` is also selected itself, it keeps its place in the selection.
///
/// Returns whether the selection changed. It does not change when `id` is not inside a selected
/// object, is inside one that is partly selected (anchors or segments), is one of a selected
/// Shaper Group's original shapes, or is hidden, locked or on a locked artboard itself.
pub fn expand_to(&mut self, doc: &Document, id: NodeId) -> bool {
let Some(chain) = doc.ancestry(id) else { return false };
let Some(top) = chain.iter().position(|a| self.contains(*a)) else { return false };
let holder = chain[top];
if self.anchors.contains_key(&holder) || self.segments.contains_key(&holder) {
return false;
}
let editable = doc.editable();
let mut members = Vec::new();
for pair in chain[top..].windows(2) {
let Some(n) = doc.node(pair[0]) else { return false };
let originals = usize::from(n.extras().shaper.is_some());
let children = n.children().map(Vec::as_slice).unwrap_or_default();
if children.iter().take(originals).any(|c| c.id == pair[1]) {
return false;
}
members.extend(children.iter().skip(originals).map(|c| c.id).filter(|c| editable(*c) && (*c == id || *c != pair[1])));
}
if !members.contains(&id) {
return false;
}
let around: HashSet<NodeId> = chain[top..chain.len() - 1].iter().copied().collect();
let at = self.objects.iter().take_while(|o| **o != holder).filter(|o| !around.contains(o)).count();
self.remove_all(around);
let selected: HashSet<NodeId> = self.objects.iter().copied().collect();
self.objects.splice(at..at, members.into_iter().filter(|m| !selected.contains(m)));
true
}
/// [`Self::add`] for each of `ids` in order, going through the selected objects once.
pub fn add_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.each(ids, false);
+74
View File
@@ -45,6 +45,80 @@ fn remove_all_does_what_removing_each_does() {
assert_eq!(none, s);
}
/// `expand_to` selects a member of a selected group in the group's place, beside the group's other
/// objects at each level down to it, and leaves a selection it cannot open alone.
#[test]
fn expand_to_selects_a_member_in_place_of_its_selected_group() {
let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
let mut d = Document::new(100.0, 100.0);
let l = d.layers[0].id;
let [x, g, e, h, b, c, dd] = [(); 7].map(|_| d.alloc_id());
let path = |id| Arc::new(Node::path(id, rect(), crate::Appearance::default_art()));
let inner = Node::group(h, vec![path(b), path(c)]);
let group = Node::group(g, vec![path(e), Arc::new(inner), path(dd)]);
d.insert(Some(l), 0, Node::path(x, rect(), crate::Appearance::default_art())).unwrap();
d.insert(Some(l), 1, group).unwrap();
let mut s = Selection::default();
s.set([x, g]);
s.key = Some(g);
assert!(s.expand_to(&d, b));
assert_eq!(s.objects, [x, e, dd, b, c], "the group's objects beside the inner group, then the inner group's");
assert_eq!(s.key, None, "the group leaves the selection with its key");
assert!(!s.expand_to(&d, b), "a member selected itself with nothing selected around it");
assert!(!s.expand_to(&d, x), "an object inside nothing selected");
// A member selected beside the group around it keeps its place.
let mut with_member = Selection::default();
with_member.set([b, g]);
assert!(with_member.expand_to(&d, b));
assert_eq!(with_member.objects, [b, e, dd, c]);
// An inner group selected beside the group leaves the selection too.
let mut both = Selection::default();
both.set([h, g]);
assert!(both.expand_to(&d, b));
assert_eq!(both.objects, [e, dd, b, c]);
// A group with anchors recorded for it is left as it is.
let mut partly = Selection::default();
partly.set([g]);
partly.anchors.insert(g, BTreeSet::from([(0, 0)]));
let before = partly.clone();
assert!(!partly.expand_to(&d, b));
assert_eq!(partly, before);
// A Shaper Group opens to its faces and never to its original shapes.
let [shaper, sources, o1, o2, face] = [(); 5].map(|_| d.alloc_id());
let mut sources_group = Node::group(sources, vec![path(o1), path(o2)]);
sources_group.name = Some(crate::shaper::SOURCES.into());
let mut shaper_group = Node::group(shaper, vec![Arc::new(sources_group), path(face)]);
shaper_group.extras_mut().shaper = Some(Box::default());
d.insert(Some(l), 2, shaper_group).unwrap();
let mut shaped = Selection::default();
shaped.set([shaper]);
let before = shaped.clone();
assert!(!shaped.expand_to(&d, o1), "an original shape");
assert_eq!(shaped, before);
assert!(shaped.expand_to(&d, face));
assert_eq!(shaped.objects, [face]);
// Hidden and locked objects beside the member stay out of the selection.
let [k, shown, hidden, locked, last] = [(); 5].map(|_| d.alloc_id());
let mut hidden_path = Node::path(hidden, rect(), crate::Appearance::default_art());
hidden_path.visible = false;
let mut locked_path = Node::path(locked, rect(), crate::Appearance::default_art());
locked_path.locked = true;
let kept = Node::group(k, vec![path(shown), Arc::new(hidden_path), Arc::new(locked_path), path(last)]);
d.insert(Some(l), 3, kept).unwrap();
let mut with_locked = Selection::default();
with_locked.set([k]);
assert!(with_locked.expand_to(&d, last));
assert_eq!(with_locked.objects, [shown, last]);
// A locked or hidden member itself does not open the group.
for target in [locked, hidden] {
let mut s = Selection::default();
s.set([k]);
let before = s.clone();
assert!(!s.expand_to(&d, target), "{target:?}");
assert_eq!(s, before);
}
}
/// A selection with every field set: objects 1 to 6 with 3 listed twice, anchors, segments, a key,
/// a key anchor, a target, slices, guides, a key guide, new art, a symbol part and an on-path member.
fn seeded() -> Selection {
+5
View File
@@ -289,6 +289,8 @@ fn local_stop(kind: &Arrowhead) -> Stop {
Arrowhead::DoubleSlash => Stop::At(1.05),
Arrowhead::DoubleArrow => Stop::At(1.7),
Arrowhead::HalfCircle => Stop::At(1.0),
// Between the bend in its sides and its notch, where it is wider than the line at 100 %.
Arrowhead::NotchedArrow => Stop::At(2.7),
Arrowhead::Concave => Stop::At(2.6),
Arrowhead::Hexagon => Stop::At(HEX / 2.0),
_ => Stop::At(2.0),
@@ -395,6 +397,9 @@ fn local(kind: &Arrowhead) -> BezPath {
let t = FRAC_1_SQRT_2;
poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]);
}
// Barbs 1.2 out at the back; each side bends in at (2.1, ±0.5), as wide as the line at
// 100 %, so the sides are concave; the notch reaches 0.7 into the back.
Arrowhead::NotchedArrow => poly(&mut p, &[(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)]),
Arrowhead::Custom(c) => p = c.path.to_bezpath(),
// The first ten are drawn by `shape`.
Arrowhead::Triangle
+58 -5
View File
@@ -4,20 +4,26 @@
use kurbo::{BezPath, PathEl, Point, Shape};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer};
use vectorcraft_doc::{ArrowAlign, Arrowhead, LineCap, StrokeLayer};
use super::stroke_pieces;
use super::{line_outline, stroke_pieces};
/// A 2 pt line along +x ending at (100, 0) with `kind` at its end, tip on the end point: heads
/// of weight 2, so 8 long and 8 wide.
fn head(kind: Arrowhead) -> super::Arrow {
head_and_line(kind, LineCap::Butt).0
}
/// [`head`] and the outline of the line under it, drawn with `cap`.
fn head_and_line(kind: Arrowhead, cap: LineCap) -> (super::Arrow, BezPath) {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
st.end_arrow = Some(kind);
st.arrow_align = ArrowAlign::Tip;
(st.end_arrow, st.arrow_align, st.cap) = (Some(kind), ArrowAlign::Tip, cap);
let mut l = BezPath::new();
l.move_to((0.0, 0.0));
l.line_to((100.0, 0.0));
stroke_pieces(&l, &st).heads.remove(0)
let mut p = stroke_pieces(&l, &st);
let line = line_outline(&p.line, &st, st.width, 1e-3);
(p.heads.remove(0), line)
}
/// The outline's closed contours as polygons (curves flattened).
@@ -105,6 +111,53 @@ fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() {
}
}
#[test]
fn the_notched_arrow_is_slender_with_concave_sides_and_a_v_notch() {
// Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt.
let h = head(Arrowhead::NotchedArrow);
let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y);
// Six corners: the tip, a bend in each side, a barb on each side and the notch between them.
let pts: Vec<Point> = contours(&h.outline).concat();
let corners = [(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)].map(|(x, y)| at(x, y));
assert_eq!(pts.len(), corners.len(), "{pts:?}");
for c in corners {
assert!(pts.iter().any(|p| p.distance(c) < 1e-9), "corner {c:?} in {pts:?}");
}
for side in [1.0, -1.0] {
// Concave: at the bend, the straight line from the tip to the barb (0.63 out) is outside.
assert_eq!(h.outline.winding(at(2.1, side * 0.6)), 0, "side {side}");
assert_ne!(h.outline.winding(at(2.1, side * 0.45)), 0, "side {side}");
// Slender: 2.4 units across at the barbs, not the 4 of the other arrows.
assert_eq!(h.outline.winding(at(3.9, side * 1.2)), 0, "side {side}");
assert_ne!(h.outline.winding(at(3.9, side * 1.1)), 0, "side {side}");
}
// Open in the notch, solid in front of it.
assert_eq!(h.outline.winding(at(3.5, 0.0)), 0);
assert_ne!(h.outline.winding(at(3.1, 0.0)), 0);
// The line stops between the bend and the notch, 2.7 units back from the tip.
assert!((h.inset - 5.4).abs() < 1e-9, "inset {}", h.inset);
}
#[test]
fn the_line_under_the_notched_arrow_stays_inside_it_in_front_of_the_notch() {
// With every cap, no part of the 2 pt line between the notch and the tip shows beside the
// head, though the head is barely wider than the line at its bends.
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
let (h, line) = head_and_line(Arrowhead::NotchedArrow, cap);
let mut covered = 0;
for i in 0..=132 {
for j in -25..=25 {
let p = Point::new(100.0 - 6.6 + f64::from(i) * 0.05, f64::from(j) * 0.04);
if line.winding(p) != 0 {
assert_ne!(h.outline.winding(p), 0, "{cap:?}: the line shows at {p:?}");
covered += 1;
}
}
}
assert!(covered > 500, "{cap:?}: the line reaches under the head ({covered} samples)");
}
}
#[test]
fn half_arrows_barb_on_their_own_side() {
// Pointing along +x on a y-down page, left is −y.
+4
View File
@@ -43,6 +43,8 @@ vectorcraft-metafile = { workspace = true }
vectorcraft-plugins = { workspace = true }
vectorcraft-affinity = { workspace = true }
craft-cdr = { workspace = true }
# `.pcraft` documents opened and placed as images (cmd/fileio/pcraftread.rs).
craft-doc = { workspace = true }
vectorcraft-scriptcheck = { workspace = true }
vectorcraft-js = { workspace = true }
# The commands' parameter schemas (schemas.rs).
@@ -120,6 +122,8 @@ vectorcraft-testkit = { workspace = true }
proptest = { workspace = true }
# A variable font built in code (no font file is committed).
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
# Holds the installed plug-ins steady while a test counts what a cache keeps.
vectorcraft-plugins = { workspace = true, features = ["test-steady"] }
# How many times an open reads a PDF, and the work its import takes.
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
# The work `.ai` blends take to be checked and made live, and how many included EPS open checks
+4
View File
@@ -77,6 +77,7 @@ pub mod perspgrid;
pub mod place;
pub mod plugin;
pub(crate) mod plugin_call;
pub mod plugin_generated;
mod preflight;
pub mod prefscmds;
pub mod print;
@@ -405,6 +406,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(printpresets::specs());
v.extend(printtiling::specs());
v.extend(plugin::specs());
v.extend(plugin_generated::specs());
v.extend(scripts::specs());
v.extend(cut::specs());
v.extend(halftone::specs());
@@ -863,6 +865,8 @@ pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location
pub use select::SIMILAR;
pub(crate) use vectorcraft_doc::range::parse_range;
#[cfg(test)]
pub(crate) use paint::PAINTS_READ;
/// What the fill and stroke proxies read from the selected objects, kept with the selection
/// ([`crate::doc_state::SelectionRecord`]).
pub(crate) use paint::SelectionPaints;
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Parametric Shape",
[],
None,
"{center: [x, y], kind?: \"rectangle\"|\"ellipse\"|\"polygon\" (default)|\"star\"|\"ring\"|\"arrow\"|\"cross\"|\"heart\"|\"gear\"|\"bubble\" (a speech bubble), width?, height?: 0.01..16384 pt (100), rotation?: degrees clockwise (0: upright), count?: 3..1000 (a polygon's sides, a star's points, a gear's teeth), a?, b?: the kind's own values (star: inner radius 0.01..1 of the outer, 0.5; ring: hole 0.01..0.99 of the size, 0.5; arrow: head length and shaft width 0.05..0.95, 0.4 and 0.4; cross: bar offset −0.9..0.9 (0, − up) and arm thickness 0.05..0.95 (1/3); heart: notch depth and point roundness 0..1 (0.4 and 0); gear: tooth height 0.01..0.9 (0.2); bubble: tail height 0.05..0.9 (0.25) and tail tip −1..1 across (−0.4)), radius?: corner radius 0..16384 pt (0; no corner rounds past the middle of a side)} draw a parametric shape with the current paint, selected, as one undo step; it stays editable with addon.pathtools.shape.set until its anchors are edited (moving, turning or scaling it keeps it) → {id, shape}",
"{center: [x, y], kind?: \"rectangle\"|\"ellipse\"|\"polygon\" (default)|\"star\"|\"ring\"|\"arrow\"|\"cross\"|\"heart\"|\"gear\"|\"bubble\" (a speech bubble), width?, height?: 0.01..16384 pt (100), rotation?: degrees clockwise (0: upright), count?: 3..1000 (a polygon's sides, a star's points, a gear's teeth), a?, b?: the kind's own values (star: inner radius 0.01..1 of the outer, 0.5; ring: hole 0.01..0.99 of the size, 0.5; arrow: head length and shaft width 0.05..0.95, 0.4 and 0.4; cross: bar offset −0.9..0.9 (0, − up) and arm thickness 0.05..0.95 (1/3); heart: notch depth and point roundness 0..1 (0.4 and 0); gear: tooth height 0.01..0.9 (0.2); bubble: tail height 0.05..0.9 (0.25) and tail tip −1..1 across (−0.4)), radius?: corner radius 0..16384 pt (0; no corner rounds past the middle of a side), sliceStart?, sliceEnd?: 0..360 degrees clockwise from the shape's top (measured as if it were as high as it is wide; 0 and 0: whole; a rectangle, ellipse, polygon, star or ring is cut from the start clockwise to the end and back through the center, a ring back along its hole; other kinds ignore them)} draw a parametric shape with the current paint, selected, as one undo step; it stays editable with addon.pathtools.shape.set until its anchors are edited (moving, turning or scaling it keeps it) → {id, shape}",
has_doc,
create
),
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Parametric Shape",
[],
None,
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; a new center, size or rotation moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with it, and with `strokes` its strokes and effects scale; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, sliceStart?, sliceEnd?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; a new center, size or rotation moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with it, and with `strokes` its strokes and effects scale; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
has_doc,
set
),
@@ -606,6 +606,42 @@ fn set_takes_a_linked_mask_and_placed_gradient_with_the_shape() {
refuses(&mut s, "addon.pathtools.shape.set", &[json!({"id": id.0, "width": 50, "strokes": "yes"})]);
}
#[test]
fn a_slice_cuts_the_shape_through_its_center_in_one_step() {
let mut s = session();
let n = steps(&s);
let r = s
.execute(
"addon.pathtools.shape.create",
&json!({"kind": "ellipse", "center": [200, 150], "width": 100, "height": 60, "sliceStart": 0, "sliceEnd": 90}),
)
.unwrap();
let id = id_of(&r);
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!((r["shape"]["sliceStart"].clone(), r["shape"]["sliceEnd"].clone()), (json!(0.0), json!(90.0)));
// The top right quarter, from the center.
let b = path(&s, id).bounds().unwrap();
assert!((b.x0 - 200.0).abs() < 1e-9 && (b.x1 - 250.0).abs() < 1e-9 && (b.y0 - 120.0).abs() < 1e-9 && (b.y1 - 150.0).abs() < 1e-9, "{b:?}");
assert_eq!(path(&s, id).subpaths[0].anchors[0].p, Point::new(200.0, 150.0));
// Turned the other way round: the three quarters left, one more step; moving keeps the slice.
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "sliceStart": 90, "sliceEnd": 0})).unwrap();
assert_eq!(steps(&s), n + 2);
let b = path(&s, id).bounds().unwrap();
assert!((b.x0 - 150.0).abs() < 1e-9 && (b.y1 - 180.0).abs() < 1e-9, "{b:?}");
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
assert_eq!(shape_of(&s, id).map(|g| (g.slice_start, g.slice_end)), Some((90.0, 0.0)));
// The same start and end: the whole ellipse again.
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "sliceEnd": 90})).unwrap();
assert_eq!(path(&s, id).anchor_count(), 4);
s.execute("edit.undo", &json!({})).unwrap();
assert!(path(&s, id).anchor_count() > 4, "undo brings the slice back");
refuses(
&mut s,
"addon.pathtools.shape.set",
&[json!({"id": id.0, "sliceStart": -10}), json!({"id": id.0, "sliceEnd": 361}), json!({"id": id.0, "sliceEnd": "90"})],
);
}
#[test]
fn bad_shape_params_are_refused() {
let mut s = session();
+3 -1
View File
@@ -253,6 +253,8 @@ pub(crate) fn item_target(s: &Session, p: &Value, cmd: &str) -> Result<ItemTarge
/// [`item_target`] read from param `key` (e.g. `fromItem`).
pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<ItemTarget> {
let aligned = aligned(p, cmd)?;
// Read `target` whatever names the objects, so that a bad one is refused with `ids` or `id` too.
let contents = targets_contents(p)?;
match p.get(key) {
Some(Value::Null) => Ok(ItemTarget::Top),
Some(v) => v
@@ -260,7 +262,7 @@ pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Re
.map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned })
.ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))),
// The active item is a row of the first selected object's own stack.
None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top),
None if p.get("ids").is_some() || p.get("id").is_some() || contents => Ok(ItemTarget::Top),
// A row of a graph design's art in a series stands for nothing: the commands leave that art out.
None if s.active().and_then(|st| st.selection.subjects().first().map(|id| super::graph::is_design_art(&st.doc, *id))) == Some(true) => {
Ok(ItemTarget::Top)
+2 -2
View File
@@ -170,7 +170,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Options…",
[],
None,
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
has_doc,
brush_options
),
@@ -179,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Options of Selected Object…",
[],
None,
"{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}",
"{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization, hue_jitter, saturation_jitter, brightness_jitter; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, scale_mode, scale_max, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}",
has_doc,
brush_object_options
),
+24 -14
View File
@@ -33,9 +33,12 @@ pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result<Value> {
let name = name_param(p, "brush.get")?;
let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?;
let mut v = serde_json::to_value(&b).unwrap_or_default();
// A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way.
// A scatter brush saves its hue, saturation and brightness jitter only when they are not 0;
// brush.get shows them either way.
if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) {
o.entry("hue_jitter").or_insert(json!(sc.hue_jitter));
o.entry("saturation_jitter").or_insert(json!(sc.saturation_jitter));
o.entry("brightness_jitter").or_insert(json!(sc.brightness_jitter));
}
Ok(v)
}
@@ -580,7 +583,7 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result<Value>
merged.insert(k.clone(), next);
}
keep_drawn_modes(b, &was, &params, &mut merged);
keep_largest_width(b, &was, &params, &mut merged);
keep_second_value(b, &was, &params, &mut merged);
b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))?
};
options.get_or_insert_with(|| next.clone());
@@ -643,27 +646,34 @@ fn keep_drawn_modes(
merged.insert("modes".into(), Value::Array(kept));
}
/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when
/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is
/// the width, so without this a changed width would also change the largest width.
fn keep_largest_width(
/// Keep the second value a stroke of brush `b` draws with (with its own settings `was`) when
/// `params` sets the first and not the second: an art brush's `width` and `width_max`, a pattern
/// brush's `scale` and `scale_max`. Without a second value of its own the second value is the
/// first, so without this a changed first value would also change the second.
fn keep_second_value(
b: &Brush,
was: &serde_json::Map<String, Value>,
params: &serde_json::Map<String, Value>,
merged: &mut serde_json::Map<String, Value>,
) {
if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) {
let (first, second) = match b.kind {
BrushKind::Art(_) => ("width", "width_max"),
BrushKind::Pattern(_) => ("scale", "scale_max"),
_ => return,
};
if params.get(first).is_none_or(Value::is_null) || params.get(second).is_some_and(|m| !m.is_null()) {
return;
}
let art = |o: &serde_json::Map<String, Value>| match b.with_stroke_options(o).ok().map(|b| b.kind) {
Some(BrushKind::Art(a)) => Some(a),
// The first value, the second value of its own, and whether the value follows the pen.
let values = |o: &serde_json::Map<String, Value>| match b.with_stroke_options(o).ok().map(|b| b.kind) {
Some(BrushKind::Art(a)) => Some((a.width, a.width_max, a.width_mode.is_some_and(|m| m.follows_pen()))),
Some(BrushKind::Pattern(p)) => Some((p.scale, p.scale_max, p.scale_mode.is_some_and(|m| m.follows_pen()))),
_ => None,
};
let (Some(before), Some(after)) = (art(was), art(merged)) else { return };
let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen());
// Only a width that followed the pen has a largest width, and only one that still does uses it.
if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width {
merged.insert("width_max".into(), json!(before.width));
let (Some(before), Some(after)) = (values(was), values(merged)) else { return };
// Only a value that followed the pen has a second value, and only one that still does uses it.
if before.1.is_none() && before.2 && after.2 && after.0 != before.0 {
merged.insert(second.into(), json!(before.0));
}
}
+10 -5
View File
@@ -758,14 +758,21 @@ impl Relink {
}
}
}
/// Relink a node tree (the mirror of [`node_refs`]).
/// Relink a node tree (the mirror of [`node_refs`]). A pie's legend labels in wedges that now show a color of the
/// other darkness take the contrast a redraw sets there.
fn node(&self, n: &mut Node) {
let shades = crate::cmd::graph::wedge_shades(n);
self.links(n);
crate::cmd::graph::follow_wedge_shades(n, &shades);
}
/// [`Self::node`] without the legend labels' contrast.
fn links(&self, n: &mut Node) {
self.appearance(&mut n.appearance);
if !self.keep_styles {
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
self.node(Arc::make_mut(&mut m.art));
self.links(Arc::make_mut(&mut m.art));
}
if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) {
self.name(Res::Image, &mut cm.key);
@@ -831,7 +838,7 @@ impl Relink {
_ => {}
}
for c in n.children_mut().into_iter().flatten() {
self.node(Arc::make_mut(c));
self.links(Arc::make_mut(c));
}
}
}
@@ -1183,9 +1190,7 @@ impl Imported {
/// other darkness take the contrast a redraw sets there. Fonts the copy carries are bound to the faces `d` holds.
pub(crate) fn apply(&mut self, n: &mut Node, d: &Document) {
if self.relinks {
let shades = super::super::graph::wedge_shades(n);
self.relink.node(n);
super::super::graph::follow_wedge_shades(n, &shades);
}
for note in vectorcraft_text::FontDb::global().bind_node_file_fonts(n, &|key| d.images.get(key)) {
if !self.warnings.contains(&note) {
+25
View File
@@ -13,6 +13,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::cms::Model;
use vectorcraft_color::css;
use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony};
use vectorcraft_color::wcag::{self, Category};
use vectorcraft_color::{BlendMode, Color, Paint, keep_model};
@@ -136,6 +137,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
harmony
),
cmd!(
query "color.parse",
"Parse Color",
[],
None,
"{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in the comma-separated legacy form, or oklch(), as CSS Color 4 defines them: https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch; this is a subset of CSS: a function's arguments are literal numbers, percentages, angles (deg, grad, rad or turn) and none, so calc(), var(), color-mix() and every other function, named colors and the other color spaces are errors; at most 48 characters, the spaces, tabs, line breaks and form feeds around it not counted)} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB",
always,
parse_color
),
cmd!(
query "color.contrast",
"Contrast",
@@ -148,6 +158,21 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
fn parse_color(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.parse";
let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?;
let parsed = css::parse(text).ok_or_else(|| {
bad(C, "`text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters")
})?;
if parsed.space == css::Space::Oklch && !vectorcraft_color::cms::active().rgb_is_srgb() {
return Err(bad(C, "OKLCH needs sRGB as the working RGB space"));
}
let [r, g, b] = parsed.rgb;
// As paint.proxies answers an opacity: a percentage to two places.
let opacity = parsed.alpha.map(|a| (f64::from(a) * 10_000.0).round() / 100.0);
Ok(json!({ "color": Color::rgb(r, g, b), "hex": css::hex_of(parsed.rgb), "opacity": opacity }))
}
/// The RGB inverse of `c`, expressed in `c`'s colour model.
pub(crate) fn invert(c: Color) -> Color {
c.invert_keep_model()
+1 -1
View File
@@ -14,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Dimension",
[],
None,
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: extent, node} (linear only: a whole path between its outermost points, leftmost and rightmost when horizontal or aligned, topmost and bottommost when vertical)|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: extent, node, preview?: bool} (linear only: a whole path between its outermost points, leftmost and rightmost when horizontal or aligned, topmost and bottommost when vertical; preview, default false, moves them out to the outside of the path's strokes, as Use Preview Bounds measures)|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
has_doc,
create
),
+1 -1
View File
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste",
["Edit"],
Some("Cmd+V"),
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
has_clipboard,
|s, p| paste(s, p, PasteMode::Offset)
),
+34 -1
View File
@@ -79,7 +79,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Effect Options",
[],
None,
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (as effect.apply)} → {ids}",
"{index: int, params?: {…} (merged into the current parameters; without a type, style or visibility setting, validated 3D values equal to their current values including defaults change nothing and add no undo step), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (as effect.apply)} → {ids}",
has_doc,
set_params
),
@@ -896,6 +896,15 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
// Supplying the current 3D values, including omitted defaults and numeric JSON representations,
// must not rewrite the effect or make an otherwise unchanged preview into an Undo step.
if kind.is_none() && warp_id.is_none() && visible.is_none() {
let d = &s.doc()?.doc;
let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect();
if !fx.is_empty() && fx.iter().all(|e| three_d_edit_changes_nothing(e, &params)) {
return Ok(json!({ "ids": [] }));
}
}
// The effect edited, when every target has one at `index` and all are the same: a dialog's
// preview names its step after it.
let one = edited.first().filter(|e| edited.len() == targets.len() && edited.iter().all(|other| other == *e)).cloned().unwrap_or_default();
@@ -937,6 +946,30 @@ fn bevel_effect(id: &str) -> bool {
id == effects::EXTRUDE || id == effects::CLASSIC_EXTRUDE
}
/// Whether validated parameters leave a 3D effect unchanged, including values supplied by its defaults.
fn three_d_edit_changes_nothing(effect: &Effect, params: &Value) -> bool {
if !effects::is_three_d(&effect.id) {
return false;
}
let upgraded = effects::upgrade_params(&effect.id, params);
let Some(given) = upgraded.as_object() else { return true };
let current = effects::merged_params(&effect.id, &effect.params);
given.iter().all(|(key, value)| current.get(key).is_some_and(|stored| same_three_d_value(stored, value)))
}
/// JSON numbers compare by value; arrays and objects keep their structure and every component.
fn same_three_d_value(stored: &Value, given: &Value) -> bool {
if stored == given {
return true;
}
match (stored, given) {
(Value::Number(a), Value::Number(b)) if a.is_f64() || b.is_f64() => a.as_f64() == b.as_f64(),
(Value::Array(a), Value::Array(b)) => a.len() == b.len() && a.iter().zip(b).all(|(a, b)| same_three_d_value(a, b)),
(Value::Object(a), Value::Object(b)) => a.len() == b.len() && a.iter().all(|(key, a)| b.get(key).is_some_and(|b| same_three_d_value(a, b))),
_ => false,
}
}
/// Does merging `params` into Pathfinder effect `e` leave it drawing as it does: the same Pathfinder
/// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their
/// defaults is unchanged), each option given equal to the one it stores (a precision that Scale
@@ -22,6 +22,27 @@ fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn unchanged_three_d_parameters_preserve_the_document_revision_and_history() {
for effect_id in ["threeD.extrude", "threeD.classicExtrude"] {
let (mut s, id) = setup(effect_id, json!({"rotationX": 12.345}));
let before = s.doc().unwrap().doc.clone();
let history = undo_len(&s);
let revision = s.doc().unwrap().revision;
let current = effect(&s, id).1;
let params = vectorcraft_render::effects::merged_params(effect_id, &current);
let result = s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": params})).unwrap();
assert_eq!(result["ids"], json!([]), "an unchanged effect is not an edit");
assert_eq!(s.doc().unwrap().doc, before, "default values need not be written into the stored effect");
assert_eq!(s.doc().unwrap().revision, revision);
assert_eq!(undo_len(&s), history);
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"rotationX": 25.0}})).unwrap();
assert_eq!(undo_len(&s), history + 1, "a changed option saves once");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
}
}
#[test]
fn three_d_type_turns_the_effect_in_place_keeping_shared_settings_in_one_undo_step() {
let types = [("plane", "threeD.rotate"), ("extrude", "threeD.extrude"), ("revolve", "threeD.revolve"), ("inflate", "threeD.inflate")];
+6 -2
View File
@@ -182,7 +182,7 @@ impl Expandable {
n.walk(&mut |c| {
let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
e.text |= matches!(c.kind, NodeKind::Text(_));
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some();
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some() || c.extras().generated.is_some();
e.effects |= !c.appearance.effects.is_empty();
e.envelope |= matches!(c.kind, NodeKind::Envelope { .. });
e.blends |= matches!(c.kind, NodeKind::Blend { .. });
@@ -503,7 +503,8 @@ fn end_dimension_links(s: &mut Session, ended: &mut Vec<EndedLink>) -> Result<()
Ok(())
}
/// Makes the live shapes in `n` plain paths, and the flares plain groups of their parts.
/// Makes the live shapes in `n` plain paths, and the flares and generated art objects plain groups
/// of their parts.
fn drop_live(n: &mut Node) {
if let NodeKind::Path { live, .. } = &mut n.kind {
*live = None;
@@ -511,6 +512,9 @@ fn drop_live(n: &mut Node) {
if n.extras().flare.is_some() {
n.extras_mut().flare = None;
}
if n.extras().generated.is_some() {
n.extras_mut().generated = None;
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
drop_live(Arc::make_mut(c));
+4
View File
@@ -51,6 +51,8 @@ mod jp2read;
mod metafile;
mod naming;
mod native;
mod pcraftread;
pub(crate) use pcraftread::is_pcraft;
mod pcxread;
pub mod pdf;
mod pdfimport;
@@ -264,6 +266,8 @@ mod tests_heifread;
#[cfg(test)]
mod tests_jp2read;
#[cfg(test)]
mod tests_pcraftread;
#[cfg(test)]
mod tests_pcxread;
#[cfg(test)]
mod tests_pxrread;
+8 -2
View File
@@ -558,6 +558,9 @@ pub const FORMATS: &[Format] = &[
Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS },
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
// Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size
// composite, the layers combined, or the preview with a note. Exports don't write them.
reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true),
];
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
@@ -618,6 +621,7 @@ pub const OPEN_EXTS: &[&str] = &[
"cdr",
"cdt",
"cmx",
"pcraft",
];
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
@@ -625,10 +629,11 @@ pub const OPEN_EXTS: &[&str] = &[
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
/// The packaging declares no type for HP-GL plot files or PICT pictures either.
/// The packaging declares no type for HP-GL plot files, PICT pictures or layered raster `.pcraft`
/// documents either.
pub const UNASSOCIATED_EXTS: &[&str] = &[
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict",
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft",
];
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
@@ -718,6 +723,7 @@ pub const PLACE_EXTS: &[&str] = &[
"cdr",
"cdt",
"cmx",
"pcraft",
"txt",
"rtf",
"docx",
+56 -18
View File
@@ -74,6 +74,9 @@ pub struct RasterImage {
/// a DCS file's (nonzero, [`crate::cmd::place::dcs`]), or a PSD or PSB file's (even-odd,
/// [`psdread::clipping_path`]).
pub clip: Option<(vectorcraft_geom::PathData, vectorcraft_geom::FillRule)>,
/// What the image leaves out of its file, for Open, Place and the Links commands to warn of: a
/// `.pcraft` document read as its reduced preview ([`super::pcraftread`]).
pub note: Option<String>,
}
pub(super) fn err(e: impl std::fmt::Display) -> EngineError {
@@ -92,6 +95,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if vectorcraft_affinity::is_affinity(bytes) {
return format("affinity");
}
if super::pcraftread::is_pcraft(bytes) {
return format("pcraft");
}
if super::cdr::is_cdr(bytes) {
// A template keeps its meaning from the extension.
return by_name.filter(|f| f.id == "cdt").or_else(|| format("cdr"));
@@ -262,16 +268,26 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions)
if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data {
return None;
}
let private = opened.illustrator_data()?;
Some(editing_copy_alone(&private, opts))
Some(editing_copy_alone(&decoded_copy(opened)?, opts))
}
/// [`from_editing_data_alone`] of `private`, the editor's copy already read.
fn editing_copy_alone(private: &[u8], opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
vectorcraft_eps::ai_alone_with(private, opts.legacy_names)
/// [`from_editing_data_alone`] of `decoded`, the editor's copy already read and decoded, or why it
/// can't be decoded.
fn editing_copy_alone(decoded: &std::result::Result<Vec<u8>, String>, opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
decoded
.as_ref()
.map_err(Clone::clone)
.and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names))
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
}
/// The editor's own copy of its art that `opened` carries, read from its streams one after the
/// other and decoded as it is read ([`vectorcraft_eps::decode_ai_private`]): the decoded data or why
/// it can't be decoded, `None` as for [`vectorcraft_pdf::Opened::illustrator_data`].
fn decoded_copy(opened: &vectorcraft_pdf::Opened) -> Option<std::result::Result<Vec<u8>, String>> {
opened.read_illustrator_data(|private| vectorcraft_eps::decode_ai_private(private))
}
/// Does a file opened with `opts` read the editor's own copy of its art: no pages picked, and
/// layers and the editing data on?
fn reads_editing_copy(opts: &LoadOptions) -> bool {
@@ -286,10 +302,10 @@ fn reads_layers_alone(opts: &LoadOptions) -> bool {
reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines
}
/// The editor's own copy of its art that `opened` carries (as [`vectorcraft_pdf::illustrator_data`]
/// reads it), when `opts` read it ([`reads_editing_copy`]).
fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<Vec<u8>> {
reads_editing_copy(opts).then(|| opened.illustrator_data()).flatten()
/// The editor's own copy of its art that `opened` carries, decoded ([`decoded_copy`]), when `opts`
/// read it ([`reads_editing_copy`]).
fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<std::result::Result<Vec<u8>, String>> {
reads_editing_copy(opts).then(|| decoded_copy(opened)).flatten()
}
/// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's
@@ -301,8 +317,12 @@ fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: EngineError) -> Result<
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
return Err(e);
}
let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part(bytes, opts.password.as_deref())
.and_then(|private| private.map(|p| vectorcraft_eps::ai_alone_on_page(&p.data, p.trim, p.user_unit, opts.legacy_names)).transpose());
let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part_with(bytes, opts.password.as_deref(), |private| {
vectorcraft_eps::decode_ai_private(private)
})
.and_then(|private| {
private.map(|p| p.data.and_then(|data| vectorcraft_eps::ai_alone_on_page_decoded(&data, p.trim, p.user_unit, opts.legacy_names))).transpose()
});
match read {
Ok(Some((doc, warnings))) => {
let notes =
@@ -460,7 +480,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
{
let pages = o.trim_pages();
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names) {
match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names) {
Ok((mut doc, warnings)) => {
doc.setup.bleed = pages.bleed;
editing_data = true;
@@ -496,7 +516,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
let (doc, warnings, read) = match alone {
Some((doc, warnings)) => (doc, warnings, true),
None => {
let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode));
let layers = layers.or_else(|| private.map(vectorcraft_eps::AiLayers::decoded));
through_editing_data(layers, opts, r.document, r.warnings, r.user_unit)
}
};
@@ -524,9 +544,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// A restored document opens on the artboard that the editing copy beside it names as
// active, as a file read from that copy does (the restored document never holds one).
if read.2
&& let Some(private) = opened.as_ref().ok().and_then(|o| o.illustrator_data())
&& let Some(Ok(data)) = opened.as_ref().ok().and_then(decoded_copy)
{
read.0.opened_artboard = vectorcraft_eps::ai_opened_artboard(&private, &read.0);
read.0.opened_artboard = vectorcraft_eps::ai_opened_artboard_decoded(&data, &read.0);
}
read
}
@@ -566,6 +586,14 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
},
// A `.pcraft` document opens as its full-size image, its layers combined, or its preview
// with a note that says so.
"pcraft" => {
let mut img = raster_image(bytes)?;
img.blob = crate::cmd::links::readable_and_kept(img.blob, true, false)?;
let note = img.note.take();
(image_doc(&title, img)?, note.into_iter().collect(), false)
}
_ if format.raster => (raster_doc(&title, bytes)?, vec![], false),
_ => return Err(err(format!("{} files can't be opened yet", format.label))),
};
@@ -627,6 +655,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
doc.title = title;
}
warnings.extend(doc.images.values().filter_map(|b| size_note(&b.bytes)));
// Generated art that can't be drawn again keeps its art; opening runs no plug-in.
warnings.extend(crate::cmd::plugin_generated::open_notes(&doc));
Ok(Loaded { doc, format, warnings, restored, converted, preview_only, editing_data, native_pdf_compatible })
}
@@ -1136,8 +1166,11 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported
/// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes
/// it) is read with that path.
/// it) is read with that path. A `.pcraft` document is read by [`super::pcraftread::image`].
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
if super::pcraftread::is_pcraft(bytes) {
return super::pcraftread::image(bytes);
}
let ppi = super::ppi::resolution(bytes);
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
@@ -1321,7 +1354,7 @@ fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi:
}
let blob = ImageBlob::new(mime, bytes);
let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd));
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip })
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip, note: None })
}
/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from
@@ -1404,7 +1437,12 @@ pub(crate) fn preview_with_clip(mut blob: ImageBlob) -> ImageBlob {
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
let RasterImage { key, blob, width, height, ppi, clip } = raster_image(bytes)?;
image_doc(name, raster_image(bytes)?)
}
/// [`raster_doc`] of an image already read.
fn image_doc(name: &str, img: RasterImage) -> Result<Document> {
let RasterImage { key, blob, width, height, ppi, clip, note: _ } = img;
let (sx, sy) = crate::cmd::place::pt_per_px(ppi);
let mut d = Document::new(width as f64 * sx, height as f64 * sy);
let layer = d.layers[0].id;
+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;
+378
View File
@@ -0,0 +1,378 @@
//! `.pcraft` documents (a layered raster document in a ZIP bundle) for File › Open and File ›
//! Place, read with craft-doc and stored as PNG. The image is, in this order:
//!
//! 1. the bundle's full-size composite, when its manifest names one;
//! 2. the canvas combined from its layers, when the document is RGB at 8 or 16 bits and every
//! visible layer is a raster layer that blends Normal ([`combine`]);
//! 3. otherwise its composite preview, with a note that names the preview's size, the canvas's
//! and why the layers were not combined, unless the preview is the canvas's size.
//!
//! A full-size composite or preview that the manifest names but the bundle does not hold, or that
//! does not decode, is an error, as is a full-size composite of another size than the canvas. The
//! image is sized by the document's resolution, so a preview places at the canvas's size (at
//! 1 ppi when that would take less).
use std::fmt;
use craft_doc::{Limits, RenditionKind, Samples};
use serde::Deserialize;
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
use super::super::Result;
use super::load::{MAX_RASTER_ALLOC, RasterImage, as_png, err, raster_image};
/// Whether `bytes` are a `.pcraft` bundle: a ZIP archive holding the manifest craft-doc reads.
pub(crate) fn is_pcraft(bytes: &[u8]) -> bool {
craft_doc::sniff(bytes).is_some_and(|kind| kind.extension() == "pcraft")
}
/// The image of `.pcraft` bundle `bytes` (see the module documentation), with
/// [`RasterImage::note`] saying so when only a preview smaller than the canvas was read.
pub(super) fn image(bytes: &[u8]) -> Result<RasterImage> {
let limits = limits();
let canvas: Canvas = craft_doc::pcraft_document(bytes, &limits).map_err(err)?;
let (w, h) = (canvas.size.width, canvas.size.height);
if w == 0 || h == 0 {
return Err(err(format!("the .pcraft document's canvas of {w} × {h} pixels is empty")));
}
let composite = craft_doc::rendition(bytes, RenditionKind::Composite, &limits).map_err(err)?;
if let Some(full) = composite.as_ref().filter(|c| c.is_full_composite) {
let img = stored_png(&full.bytes, canvas.ppi(), "full-size image")?;
if (img.width, img.height) != (w, h) {
return Err(err(format!("the .pcraft document's full-size image is {} × {} pixels, not {w} × {h} as its canvas", img.width, img.height)));
}
return Ok(img);
}
let reason = match combine(bytes, &canvas, &limits)? {
Ok(img) => return Ok(img),
Err(reason) => reason,
};
let Some(preview) = composite else {
return Err(err(format!("the .pcraft document has no full-size image or preview, and its layers can't be combined: {reason}")));
};
let (pw, ph) = vectorcraft_doc::header_size(&preview.bytes).ok_or_else(|| err("the .pcraft document's preview isn't a PNG image"))?;
// The preview covers the canvas: its resolution is the document's (72 ppi without a usable
// one) scaled by its size, and at least 1 ppi, the least a stored image's resolution reads as.
let (x, y) = canvas.ppi().unwrap_or((72.0, 72.0));
let ppi = ((x * f64::from(pw) / f64::from(w)).max(1.0), (y * f64::from(ph) / f64::from(h)).max(1.0));
let mut img = stored_png(&preview.bytes, Some(ppi), "preview")?;
let reduced = (img.width, img.height) != (w, h);
let (pw, ph) = (img.width, img.height);
img.note = reduced.then(|| format!("only the {pw} × {ph} preview of this {w} × {h} pixel .pcraft document was read: {reason}"));
Ok(img)
}
/// The limits of one read: the decoded allowance for an entry, and twice that for everything one
/// call reads and decodes.
fn limits() -> Limits {
let mut limits = Limits::default();
limits.max_entry = MAX_RASTER_ALLOC;
limits.max_total = MAX_RASTER_ALLOC.saturating_mul(2);
limits
}
/// PNG `png` from the bundle (its `what`) as a stored image whose PNG records resolution `ppi`. The
/// image's resolution is the one read back from the PNG, as the Links commands read it later.
fn stored_png(png: &[u8], ppi: Option<(f64, f64)>, what: &str) -> Result<RasterImage> {
if craft_image_codecs::detect(png) != Some(craft_image_codecs::Format::Png) {
return Err(err(format!("the .pcraft document's {what} isn't a PNG image")));
}
match ppi {
Some(r) => raster_image(&super::ppi::with_png_resolution(png, r)),
None => raster_image(png),
}
}
/// The document members that size the image and decide whether its layers can be combined.
#[derive(Deserialize)]
struct Canvas {
size: Size,
resolution_dpi: f32,
mode: String,
depth: String,
#[serde(default)]
icc_profile: Option<IgnoredAny>,
}
#[derive(Deserialize)]
struct Size {
width: u32,
height: u32,
}
impl Canvas {
/// The document's resolution, when it is a usable one.
fn ppi(&self) -> Option<(f64, f64)> {
let dpi = f64::from(self.resolution_dpi);
(dpi.is_finite() && (1.0..=100_000.0).contains(&dpi)).then_some((dpi, dpi))
}
}
/// The document's layers, bottom first.
#[derive(Deserialize)]
struct Layers {
layers: Vec<Layer>,
}
/// The members of a layer that change how it draws. Members that don't (its name, locks, label,
/// id, links, XMP and the blocks kept for PSD files) are skipped; any other member is kept in
/// `unknown`, so a layer with a setting this reader doesn't know is not combined.
#[derive(Default)]
struct Layer {
visible: bool,
blend: String,
opacity: f32,
fill_opacity: f32,
clipped: bool,
mask: Option<Mask>,
vector_mask: Option<Toggle>,
effects: Option<Effects>,
kind: String,
frame: bool,
advanced_blending: bool,
unknown: Option<String>,
}
#[derive(Deserialize)]
struct Mask {
enabled: bool,
density: f32,
feather: f32,
}
#[derive(Deserialize)]
struct Toggle {
#[serde(default = "yes")]
enabled: bool,
}
fn yes() -> bool {
true
}
#[derive(Deserialize)]
struct Effects {
#[serde(default)]
enabled: bool,
#[serde(default)]
items: Vec<IgnoredAny>,
}
/// A layer's `content`: its kind. A group's children are skipped: a visible group is not combined.
#[derive(Deserialize)]
struct Content {
kind: String,
}
impl<'de> Deserialize<'de> for Layer {
fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
struct LayerVisitor;
impl<'de> Visitor<'de> for LayerVisitor {
type Value = Layer;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a layer object")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> std::result::Result<Layer, A::Error> {
let mut l = Layer { fill_opacity: 1.0, ..Layer::default() };
let (mut visible, mut blend, mut opacity, mut kind) = (None, None, None, None);
while let Some(key) = map.next_key::<String>()? {
match key.as_str() {
"visible" => visible = Some(map.next_value()?),
"blend" => blend = Some(map.next_value()?),
"opacity" => opacity = Some(map.next_value()?),
"fill_opacity" => l.fill_opacity = map.next_value()?,
"clipped" => l.clipped = map.next_value()?,
"mask" => l.mask = map.next_value()?,
"vector_mask" => l.vector_mask = map.next_value()?,
"effects" => l.effects = map.next_value()?,
"content" => kind = Some(map.next_value::<Content>()?.kind),
"frame" => l.frame = map.next_value::<Option<IgnoredAny>>()?.is_some(),
"excluded_channels" => l.advanced_blending |= map.next_value::<u32>()? != 0,
"blend_if" | "advanced" => l.advanced_blending |= map.next_value::<Option<IgnoredAny>>()?.is_some(),
"id" | "name" | "locks" | "label" | "psd_blocks" | "psd_id" | "fill_cache" | "link_group" | "video" | "xmp" => {
map.next_value::<IgnoredAny>()?;
}
_ => {
map.next_value::<IgnoredAny>()?;
l.unknown.get_or_insert(key);
}
}
}
l.visible = visible.ok_or_else(|| serde::de::Error::missing_field("visible"))?;
l.blend = blend.ok_or_else(|| serde::de::Error::missing_field("blend"))?;
l.opacity = opacity.ok_or_else(|| serde::de::Error::missing_field("opacity"))?;
l.kind = kind.ok_or_else(|| serde::de::Error::missing_field("content"))?;
Ok(l)
}
}
d.deserialize_map(LayerVisitor)
}
}
/// Why visible layer `l` can't be combined by [`combine`], or `None` when it can.
fn unsupported(l: &Layer) -> Option<String> {
let unit = |v: f32| v.is_finite() && (0.0..=1.0).contains(&v);
if let Some(key) = &l.unknown {
return Some(format!("a visible layer has a setting this version doesn't read (`{key}`)"));
}
if l.kind != "raster" {
let kind = match l.kind.as_str() {
"group" => "a visible layer group",
"text" => "a visible type layer",
"shape" => "a visible shape layer",
"smart" => "a visible smart object",
"adjustment" => "a visible adjustment layer",
"fill" => "a visible fill layer",
_ => "a visible layer of a kind this version doesn't read",
};
return Some(format!("the document has {kind}"));
}
let reason = if l.blend != "Normal" {
"a visible layer blends in a mode other than Normal"
} else if !unit(l.opacity) || !unit(l.fill_opacity) {
"a visible layer's opacity is out of range"
} else if l.clipped {
"a visible layer is clipped to the layer below it"
} else if l.effects.as_ref().is_some_and(|e| e.enabled && !e.items.is_empty()) {
"a visible layer has layer effects"
} else if l.vector_mask.as_ref().is_some_and(|v| v.enabled) {
"a visible layer has a vector mask"
} else if l.mask.as_ref().is_some_and(|m| m.enabled && (m.feather != 0.0 || !unit(m.density))) {
"a visible layer has a feathered layer mask"
} else if l.advanced_blending {
"a visible layer uses advanced blending options"
} else if l.frame {
"a visible layer has a frame"
} else {
return None;
};
Some(reason.into())
}
/// The canvas of `.pcraft` bundle `bytes` combined from its layers, or why it can't be: the
/// document must be RGB at 8 or 16 bits, the canvas's pixels as 32-bit floating-point RGBA within
/// [`MAX_RASTER_ALLOC`], and each visible layer a raster layer that blends Normal at an opacity and
/// fill opacity between 0 and 1, with no clipping, layer effects, vector mask, frame or advanced
/// blending options, and a layer mask that is off or not feathered. Hidden layers are not read.
/// Each layer is laid over the layers below it as the straight-alpha Normal blend lays a source
/// over a backdrop, its alpha scaled by its opacity, its fill opacity and its layer mask (the mask
/// value scaled toward opaque by the mask's density). An RGB ICC profile the document names is
/// kept in the PNG; another profile is a reason not to combine. A visible layer without saved
/// pixels, or with samples other than 8 or 16 bits, is a reason too.
fn combine(bytes: &[u8], canvas: &Canvas, limits: &Limits) -> Result<std::result::Result<RasterImage, String>> {
let no = |reason: &str| Ok(Err(reason.to_string()));
if canvas.mode != "Rgb" {
return Ok(Err(format!("the document's color mode is {}, not RGB", canvas.mode)));
}
let deep = match canvas.depth.as_str() {
"U8" => false,
"U16" => true,
_ => return no("the document stores 32-bit samples"),
};
let (w, h) = (canvas.size.width, canvas.size.height);
let pixels = u64::from(w) * u64::from(h);
if pixels.saturating_mul(16) > MAX_RASTER_ALLOC {
return no("the canvas is too large to combine its layers");
}
let Layers { layers } = craft_doc::pcraft_document(bytes, limits).map_err(err)?;
let visible: Vec<usize> = layers.iter().enumerate().filter(|(_, l)| l.visible).map(|(i, _)| i).collect();
if let Some(reason) = visible.iter().find_map(|&i| unsupported(&layers[i])) {
return Ok(Err(reason));
}
let icc = match canvas.icc_profile {
Some(_) => craft_doc::pcraft_icc_profile(bytes, limits).map_err(err)?,
None => None,
};
if icc.as_deref().is_some_and(|icc| vectorcraft_doc::cmyk::icc_color_space(icc) != Some(*b"RGB ")) {
return no("the document's color profile isn't an RGB profile");
}
let n = usize::try_from(pixels).map_err(err)?;
let mut out = vec![[0.0f32; 4]; n];
for i in visible {
let l = &layers[i];
let Some(px) = craft_doc::pcraft_layer_rgba(bytes, &[i], limits).map_err(err)? else {
return no("a visible layer has no saved pixels");
};
if (px.width, px.height) != (w, h) || px.rgba.len() != n * 4 {
return Err(err("a layer of the .pcraft document doesn't cover its canvas"));
}
let Some(rgba) = Levels::of(&px.rgba) else { return no("a visible layer stores 32-bit samples") };
let mask = match px.mask.as_ref().filter(|m| m.enabled) {
Some(m) => match Levels::of(&m.alpha).filter(|_| m.alpha.len() == n) {
Some(levels) => Some((levels, m.density)),
None => return no("a visible layer's mask stores 32-bit samples"),
},
None => None,
};
let opacity = l.opacity * l.fill_opacity;
for (p, b) in out.iter_mut().enumerate() {
let coverage = mask.as_ref().map_or(1.0, |(m, density)| 1.0 - density * (1.0 - m.at(p)));
let s = [rgba.at(p * 4), rgba.at(p * 4 + 1), rgba.at(p * 4 + 2), rgba.at(p * 4 + 3)];
*b = over(*b, s, opacity * coverage);
}
}
let img: image::DynamicImage = if deep {
let samples = out.iter().flat_map(|p| level16(*p)).collect();
image::ImageBuffer::from_raw(w, h, samples)
.map(image::DynamicImage::ImageRgba16)
.ok_or_else(|| err("the combined layers don't fit the canvas"))?
} else {
let samples = out.iter().flat_map(|p| level8(*p)).collect();
image::ImageBuffer::from_raw(w, h, samples)
.map(image::DynamicImage::ImageRgba8)
.ok_or_else(|| err("the combined layers don't fit the canvas"))?
};
drop(out);
as_png(img, icc, canvas.ppi()).map(Ok)
}
/// 8- or 16-bit samples read as levels from 0 to 1.
enum Levels<'a> {
U8(&'a [u8]),
U16(&'a [u16]),
}
impl<'a> Levels<'a> {
fn of(s: &'a Samples) -> Option<Self> {
match s {
Samples::U8(v) => Some(Levels::U8(v)),
Samples::U16(v) => Some(Levels::U16(v)),
_ => None,
}
}
fn at(&self, i: usize) -> f32 {
match self {
Levels::U8(v) => v.get(i).map_or(0.0, |&v| f32::from(v) / 255.0),
Levels::U16(v) => v.get(i).map_or(0.0, |&v| f32::from(v) / 65535.0),
}
}
}
/// Straight-alpha source `s` laid over backdrop `b` with the Normal blend, the source's alpha
/// scaled by `k`.
fn over(b: [f32; 4], s: [f32; 4], k: f32) -> [f32; 4] {
let sa = s[3] * k;
if sa <= 0.0 {
return b;
}
let kb = b[3] * (1.0 - sa);
let a = sa + kb;
if a <= 0.0 {
return [0.0; 4];
}
let mix = |c: usize| (kb * b[c] + sa * s[c]) / a;
[mix(0), mix(1), mix(2), a]
}
fn level8(p: [f32; 4]) -> [u8; 4] {
let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
if p[3] <= 0.0 { [0; 4] } else { [q(p[0]), q(p[1]), q(p[2]), q(p[3])] }
}
fn level16(p: [f32; 4]) -> [u16; 4] {
let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16;
if p[3] <= 0.0 { [0; 4] } else { [q(p[0]), q(p[1]), q(p[2]), q(p[3])] }
}
@@ -82,6 +82,60 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() {
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]);
}
/// The sample `.ai` with its private data `private` cut into streams of `size` bytes, each
/// deflated on its own, and `content` more in its page's content stream dictionary.
fn deflated_streams(private: &[u8], size: usize, content: &str) -> Vec<u8> {
let parts: Vec<Vec<u8>> = private
.chunks(size)
.map(|part| {
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
e.write_all(part).unwrap();
e.finish().unwrap()
})
.collect();
let parts: Vec<&[u8]> = parts.iter().map(Vec::as_slice).collect();
ai::ai_with_parts(&parts, ai::page_pdf(), content, "/Filter /FlateDecode ")
}
/// A `.ai` whose private data streams are cut inside the compression's marker and inside the
/// compressed data opens with its layers.
#[test]
fn ai_private_data_cut_anywhere_opens_with_its_layers() {
let private = compressed(&ai::sample_data());
for size in [7, 1000] {
let mut s = Session::new();
let r = open(&mut s, "art.ai", &deflated_streams(&private, size, ""), json!({})).unwrap();
assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("weren't read")), "{r}");
check_sample(&s);
}
}
/// A `.ai` whose private data streams hold more than 256 MiB, once their own compression is undone,
/// opens with its layers when the editing data they hold is within the limit on it, also when its
/// PDF part can't be read (#4366): the streams are read one after the other as the data is
/// decoded, without a limit of their own.
#[cfg(target_pointer_width = "64")]
#[test]
fn ai_private_data_past_256_mib_opens_with_its_layers() {
let data = ai::sample_data();
let at = data.windows(13).position(|w| w == b"%%PageTrailer").unwrap();
// A comment line the reader skips, so the data stays valid while it grows past 256 MiB.
let mut program = Vec::with_capacity(data.len() + (257 << 20));
program.extend_from_slice(&data[..at]);
program.push(b'%');
program.resize(at + (257 << 20), b'x');
program.push(b'\n');
program.extend_from_slice(&data[at..]);
for content in ["", REFUSED_CONTENT] {
let file = deflated_streams(&program, 64 << 20, content);
assert!(file.len() < 4 << 20, "the filler deflates");
let mut s = Session::new();
let r = open(&mut s, "art.ai", &file, json!({})).unwrap();
assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("weren't read")), "{content}: {r}");
check_sample(&s);
}
}
/// Opening a `.ai` or a PDF whose PDF part reads, or a `.ai` saved without PDF compatibility,
/// reads and checks the file once, on any thread, for the document it may carry, its pages, its
/// editing data and its File Info, with pages picked or not.
@@ -0,0 +1,326 @@
//! Reading `.pcraft` documents built here from scratch (a hand-written manifest, PNG previews
//! encoded here and layers whose surfaces are one default pixel, in a stored ZIP archive): the
//! full-size composite is the image when the bundle has one; otherwise visible Normal raster layers
//! are combined at the canvas's size; otherwise the preview is read, with a note when it is smaller
//! than the canvas. Damaged and unreadable bundles are refused with a message.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use super::*;
/// A surface of one `pixel` (hex of its bytes) everywhere, in `sample` (U8 or U16).
fn surface(sample: &str, mode: &str, alpha: bool, pixel: &str) -> String {
format!(r#"{{"format":{{"mode":"{mode}","sample":"{sample}","alpha":{alpha}}},"default":"{pixel}","tiles":[]}}"#)
}
/// An 8-bit RGBA surface of one pixel everywhere.
fn rgba8(p: [u8; 4]) -> String {
surface("U8", "Rgb", true, &p.iter().map(|b| format!("{b:02x}")).collect::<String>())
}
/// Effects that are on, with none in the list.
const NO_EFFECTS: &str = r#"{"enabled":true,"items":[],"psd_raw":null}"#;
/// A layer: `visible`, `blend`, `opacity`, `content`, its `mask` and `effects` (JSON), and `extra`
/// members (each `,"key":value`).
fn layer_with(visible: bool, blend: &str, opacity: f32, content: &str, mask: &str, effects: &str, extra: &str) -> String {
format!(
r#"{{"id":1,"name":"L","visible":{visible},"locks":{{}},"blend":"{blend}","opacity":{opacity},"fill_opacity":1.0,"clipped":false,
"mask":{mask},"effects":{effects},"label":"None","content":{content},"psd_blocks":[],"psd_id":null,"fill_cache":null{extra}}}"#
)
}
/// [`layer_with`] without a mask or effects.
fn layer(visible: bool, blend: &str, opacity: f32, content: &str, extra: &str) -> String {
layer_with(visible, blend, opacity, content, "null", NO_EFFECTS, extra)
}
fn raster(surface: &str) -> String {
format!(r#"{{"kind":"raster","surface":{surface}}}"#)
}
/// A visible Normal raster layer of `pixel` at `opacity`.
fn plain(pixel: [u8; 4], opacity: f32) -> String {
layer(true, "Normal", opacity, &raster(&rgba8(pixel)), "")
}
/// A `w` × `h` PNG of `pixel`.
fn png(w: u32, h: u32, pixel: [u8; 4]) -> Vec<u8> {
let mut out = vec![];
image::RgbaImage::from_pixel(w, h, image::Rgba(pixel)).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
/// What a test bundle holds besides its layers.
struct Bundle<'a> {
size: (u32, u32),
dpi: f32,
depth: &'a str,
version: u32,
layers: Vec<String>,
/// The full-size composite's entry, when the manifest names it (`None` bytes: not in the archive).
full: Option<Option<Vec<u8>>>,
/// The preview's entry, likewise.
preview: Option<Option<Vec<u8>>>,
}
impl Bundle<'_> {
fn new(layers: Vec<String>) -> Self {
Bundle { size: (300, 200), dpi: 150.0, depth: "U8", version: 1, layers, full: None, preview: Some(Some(png(30, 20, [9, 9, 9, 255]))) }
}
fn bytes(&self) -> Vec<u8> {
let (w, h) = self.size;
let named = |m: &Option<Option<Vec<u8>>>, path: &str| if m.is_some() { format!(r#""{path}""#) } else { "null".into() };
let mut manifest = format!(
r#"{{"format_version":{},"generator":"test 0.1.0",
"document":{{"id":1,"name":"Untitled","size":{{"width":{w},"height":{h}}},"resolution_dpi":{},"mode":"Rgb","depth":"{}",
"icc_profile":null,"layers":[{}],"channels":[],"guides":{{}},"selection":null,"metadata":{{}},"global_light":{{}}}},
"thumbnail":null,"composite":{}"#,
self.version,
self.dpi,
self.depth,
self.layers.join(","),
named(&self.preview, "composite/preview.png"),
);
if self.full.is_some() {
manifest.push_str(r#","full_composite":"composite/full.png""#);
}
manifest.push('}');
let mut files: Vec<(&str, Vec<u8>)> = vec![("manifest.json", manifest.into_bytes())];
if let Some(Some(b)) = &self.preview {
files.push(("composite/preview.png", b.clone()));
}
if let Some(Some(b)) = &self.full {
files.push(("composite/full.png", b.clone()));
}
super::zip::store(&files).unwrap()
}
}
/// Place `file` (named `art.pcraft`) in a new document: the reply and the placed image's (natural
/// width in points, its stored pixels).
fn place(file: &[u8]) -> (Value, f64, image::DynamicImage) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap();
let r = s.execute("file.place", &json!({"name": "art.pcraft", "dataBase64": vectorcraft_format::base64_encode(file)})).unwrap();
let doc = &s.doc().unwrap().doc;
let node = doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
let NodeKind::Image(im) = &node.kind else { panic!("an image, got {:?}", node.kind) };
let width = node.geometric_bounds().map(|b| b.width()).unwrap();
let pixels = image::load_from_memory(&doc.images[&im.key].bytes).unwrap();
(r, width, pixels)
}
fn warnings(r: &Value) -> Vec<String> {
r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect()
}
fn place_error(file: &[u8]) -> String {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap();
s.execute("file.place", &json!({"name": "art.pcraft", "dataBase64": vectorcraft_format::base64_encode(file)})).unwrap_err().to_string()
}
#[test]
fn the_full_size_composite_is_placed_rather_than_the_layers_or_the_preview() {
// The red layer could be combined, and the preview the manifest names is not in the archive.
let mut b = Bundle::new(vec![plain([255, 0, 0, 255], 1.0)]);
b.full = Some(Some(png(300, 200, [0, 200, 0, 255])));
b.preview = Some(None);
let file = b.bytes();
assert!(super::pcraftread::is_pcraft(&file));
assert_eq!(detect("art.zip", &file).map(|f| f.id), Some("pcraft"), "by its content");
let (r, width, pixels) = place(&file);
assert_eq!(r["format"], "pcraft");
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!((pixels.width(), pixels.height()), (300, 200));
assert_eq!(pixels.to_rgba8().get_pixel(5, 5).0, [0, 200, 0, 255]);
// Sized by the document's resolution: 300 px at 150 ppi are 144 pt (the PNG keeps the
// resolution in whole pixels per meter).
assert!((width - 144.0).abs() < 0.5, "{width}");
}
#[test]
fn visible_normal_raster_layers_are_combined_at_the_canvas_size() {
let file = Bundle::new(vec![
plain([255, 0, 0, 255], 1.0),
// Half its alpha and half its opacity: a quarter over the red.
plain([0, 0, 255, 128], 0.5),
// Hidden layers draw nothing, whatever they are.
layer(false, "Normal", 1.0, &raster(&rgba8([0, 255, 0, 255])), ""),
layer(false, "Screen", 1.0, r#"{"kind":"text","text":"A","cache":null}"#, r#","advanced":{"knockout":"deep"}"#),
])
.bytes();
let (r, width, pixels) = place(&file);
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!((pixels.width(), pixels.height()), (300, 200), "the canvas's size, not the 30 × 20 preview's");
let [red, green, blue, alpha] = pixels.to_rgba8().get_pixel(150, 100).0;
assert!(red > blue && blue > 0 && green == 0 && alpha == 255, "{:?}", [red, green, blue, alpha]);
assert!((width - 144.0).abs() < 0.5, "{width}");
// A 16-bit document's layers combine into 16-bit samples.
let mut b = Bundle::new(vec![layer(true, "Normal", 1.0, &raster(&surface("U16", "Rgb", true, "ffff000000000080")), "")]);
b.depth = "U16";
let (_, _, pixels) = place(&b.bytes());
assert!(matches!(pixels, image::DynamicImage::ImageRgba16(_)), "{:?}", pixels.color());
}
#[test]
fn a_layer_mask_hides_by_its_density_unless_it_is_off() {
// A mask that hides everything, at half density.
let mask = |enabled: bool, feather: f32| {
format!(r#"{{"surface":{},"enabled":{enabled},"linked":true,"density":0.5,"feather":{feather}}}"#, surface("U8", "Grayscale", false, "00"))
};
let blue_at = |mask: &str| {
let top = layer_with(true, "Normal", 1.0, &raster(&rgba8([0, 0, 255, 255])), mask, NO_EFFECTS, "");
let (r, _, pixels) = place(&Bundle::new(vec![plain([255, 0, 0, 255], 1.0), top]).bytes());
(warnings(&r), pixels.to_rgba8().get_pixel(0, 0).0)
};
let (w, [red, _, blue, _]) = blue_at(&mask(true, 0.0));
assert!(w.is_empty() && red > 100 && blue > 100, "half hidden: {red} {blue}");
let (w, [red, _, blue, _]) = blue_at(&mask(false, 0.0));
assert!(w.is_empty() && red == 0 && blue == 255, "a mask that is off hides nothing: {red} {blue}");
let (w, [red, ..]) = blue_at(&mask(true, 4.0));
assert!(w.iter().any(|w| w.contains("feathered layer mask")) && red == 9, "a feathered mask leaves the preview: {w:?}");
}
#[test]
fn layers_that_cant_be_combined_leave_the_preview_with_a_note() {
let file = Bundle::new(vec![plain([255, 0, 0, 255], 1.0), layer(true, "Multiply", 1.0, &raster(&rgba8([0, 0, 255, 255])), "")]).bytes();
let (r, width, pixels) = place(&file);
assert_eq!((pixels.width(), pixels.height()), (30, 20));
let w = warnings(&r);
assert!(w.len() == 1 && w[0].contains("30 × 20 preview") && w[0].contains("300 × 200") && w[0].contains("Normal"), "{w:?}");
// The preview covers the canvas, at the same size as the full image.
assert!((width - 144.0).abs() < 0.5, "{width}");
// Each other setting that changes how a layer draws leaves the preview too.
let pixels = raster(&rgba8([0; 4]));
let shadow = r#"{"enabled":true,"items":[{"DropShadow":{}}],"psd_raw":null}"#;
for (content, effects, extra, said) in [
(pixels.as_str(), shadow, "", "layer effects"),
(&pixels, NO_EFFECTS, r#","blend_if":{"ranges":[1]}"#, "advanced blending"),
(&pixels, NO_EFFECTS, r#","excluded_channels":2"#, "advanced blending"),
(&pixels, NO_EFFECTS, r#","vector_mask":{"enabled":true,"path":{}}"#, "vector mask"),
(&pixels, NO_EFFECTS, r#","frame":{"path":{}}"#, "frame"),
(&pixels, NO_EFFECTS, r#","a_new_setting":true"#, "a_new_setting"),
(r#"{"kind":"group","children":[],"expanded":true}"#, NO_EFFECTS, "", "layer group"),
(r#"{"kind":"text","text":"A","cache":null}"#, NO_EFFECTS, "", "type layer"),
] {
let l = layer_with(true, "Normal", 1.0, content, "null", effects, extra);
let (r, _, pixels) = place(&Bundle::new(vec![l]).bytes());
let w = warnings(&r);
assert!(pixels.width() == 30 && w.len() == 1 && w[0].contains(said), "{said}: {w:?}");
}
// A preview of the canvas's own size is not reduced, so nothing is said.
let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]);
b.size = (30, 20);
let (r, _, pixels) = place(&b.bytes());
assert!(warnings(&r).is_empty() && pixels.width() == 30, "{r}");
}
/// A linked preview keeps its size when it is read again: the resolution it was placed at is the
/// one its stored PNG gives back, at least 1 ppi when the canvas is far larger than the preview.
#[test]
fn a_linked_preview_keeps_its_size_when_it_is_updated() {
let dir = vectorcraft_testkit::TempDir::new("pcraft-preview-size");
for (size, dpi) in [((300, 200), 150.0), ((300, 200), 72.0), ((3000, 2000), 10.0)] {
let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]);
(b.size, b.dpi) = (size, dpi);
let path = dir.join("art.pcraft");
std::fs::write(&path, b.bytes()).unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap();
let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap();
let id = NodeId(r["ids"][0].as_u64().unwrap());
let width = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().width();
let placed = width(&s);
for preserve in ["transforms", "bounds"] {
s.execute("links.relink", &json!({"ids": [id.0], "path": path.to_string_lossy(), "preserve": preserve})).unwrap();
s.execute("links.update", &json!({"ids": [id.0]})).unwrap();
assert!((width(&s) - placed).abs() < 1e-6, "{size:?} at {dpi} ppi, {preserve}: {} then {placed}", width(&s));
}
// The 30 px preview places at the canvas's width, or at 1 ppi when that would take less.
let ppi = (f64::from(dpi) * 30.0 / f64::from(size.0)).max(1.0);
assert!((placed - 30.0 * 72.0 / ppi).abs() < 0.5, "{size:?} at {dpi} ppi: {placed}");
}
}
#[test]
fn damaged_or_unreadable_bundles_are_refused() {
let multiply = || vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")];
// The full-size composite the manifest names is missing, or not the canvas's size: never the preview.
let mut b = Bundle::new(multiply());
b.full = Some(None);
assert!(place_error(&b.bytes()).contains("composite/full.png"));
b.full = Some(Some(png(30, 20, [0; 4])));
assert!(place_error(&b.bytes()).contains("not 300 × 200"));
b.full = Some(Some(b"not a png".to_vec()));
assert!(place_error(&b.bytes()).contains("isn't a PNG"));
// No preview and layers that can't be combined.
let mut b = Bundle::new(multiply());
b.preview = None;
assert!(place_error(&b.bytes()).contains("no full-size image or preview"));
// A newer format version.
let mut b = Bundle::new(multiply());
b.version = 99;
assert!(place_error(&b.bytes()).contains("newer"));
}
#[test]
fn pcraft_files_open_and_place_linked_and_updates_read_them_again() {
let b64 = vectorcraft_format::base64_encode;
let red = Bundle::new(vec![plain([255, 0, 0, 255], 1.0)]).bytes();
let blue = Bundle::new(vec![plain([0, 0, 255, 255], 1.0)]).bytes();
let mut s = Session::new();
let r = s.execute("document.open", &json!({"name": "art.pcraft", "dataBase64": b64(&red)})).unwrap();
assert_eq!((&r["format"], &r["warnings"]), (&json!("pcraft"), &json!([])), "{r}");
let multiply = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]).bytes();
let r = s.execute("document.open", &json!({"name": "art.pcraft", "dataBase64": b64(&multiply)})).unwrap();
assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("preview")), "Open says so too: {r}");
let dir = vectorcraft_testkit::TempDir::new("pcraft-link");
let path = dir.join("art.pcraft");
std::fs::write(&path, &red).unwrap();
s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap();
let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap();
let id = r["ids"][0].as_u64().unwrap();
let shown = |s: &Session| {
let doc = &s.doc().unwrap().doc;
let NodeKind::Image(im) = &doc.node(NodeId(id)).unwrap().kind else { panic!("an image") };
assert!(im.link.is_some(), "linked");
image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgba8().get_pixel(0, 0).0
};
assert_eq!(shown(&s), [255, 0, 0, 255]);
std::fs::write(&path, &blue).unwrap();
s.execute("links.update", &json!({"ids": [id]})).unwrap();
assert_eq!(shown(&s), [0, 0, 255, 255], "the update reads the file again");
// A file that now has only its preview to show says so.
std::fs::write(&path, &multiply).unwrap();
let r = s.execute("links.update", &json!({"ids": [id]})).unwrap();
let w = warnings(&r);
assert!(w.len() == 1 && w[0].starts_with("art.pcraft: only the 30 × 20 preview"), "{r}");
// A preview whose header reads but whose pixels don't is not taken: the link counts as missing.
let mut damaged = png(30, 20, [9, 9, 9, 255]);
let n = damaged.len();
damaged[40..n - 12].fill(0xff);
let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]);
b.preview = Some(Some(damaged));
let damaged = b.bytes();
let e = s.execute("document.open", &json!({"name": "art.pcraft", "dataBase64": b64(&damaged)})).unwrap_err();
assert!(e.to_string().contains("pixels can't be read"), "{e}");
std::fs::write(&path, damaged).unwrap();
let r = s.execute("links.update", &json!({"ids": [id]})).unwrap();
assert_eq!(r["missing"], json!([id]), "{r}");
let r = s.execute("links.replaceEmbedded", &json!({"ids": [id], "dataBase64": b64(&multiply)})).unwrap();
assert!(warnings(&r).iter().any(|w| w.contains("preview")), "{r}");
// The dialogs list it; the desktop packaging doesn't associate it; nothing writes it.
assert!(OPEN_EXTS.contains(&"pcraft") && PLACE_EXTS.contains(&"pcraft") && UNASSOCIATED_EXTS.contains(&"pcraft"));
let r = s.execute("document.formats", &json!({})).unwrap();
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pcraft").unwrap().clone();
assert_eq!((f["read"].as_bool(), f["write"].as_bool()), (Some(true), Some(false)));
}
+24 -1
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Layer Options…",
["Window", "Layers"],
None,
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step",
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given",
has_doc,
set_props
),
@@ -400,6 +400,18 @@ fn apply_options(n: &mut Node, p: &Value, xml_id: bool) {
}
}
/// Whether Layer Options `p` ([`apply_options`]) would change row `n`: its name, eye, lock or
/// layer options.
fn changes_options(n: &Node, p: &Value, xml_id: bool) -> bool {
let mut after = n.clone();
apply_options(&mut after, p, xml_id);
let options = |n: &Node| match &n.kind {
NodeKind::Layer { color, template, printable, preview, dim_images, .. } => Some((*color, *template, *printable, *preview, *dim_images)),
_ => None,
};
after.name != n.name || after.visible != n.visible || after.locked != n.locked || options(&after) != options(n)
}
/// Bad values in Layer Options params, as an error for `cmd`.
/// `xml_id`: Preferences › Units › Identify Objects By › XML ID — a non-empty `name` must be a
/// valid XML id.
@@ -706,6 +718,17 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
let name = if xml_id { vectorcraft_doc::xml_id::to_object_name(v) } else { v.to_string() };
super::buildcmds::check_part_name(&s.doc()?.doc, &ids, &name)?;
}
// When every row already has every option given, the document and its undo history stay as
// they are.
let d = &s.doc()?.doc;
if ids.iter().all(|id| d.node(*id).is_some_and(|n| !changes_options(n, p, xml_id))) {
// Hidden or locked rows' art can't stay selected.
let flag = |k: &str| p.get(k).and_then(Value::as_bool);
if flag("visible") == Some(false) || flag("locked") == Some(true) || flag("template") == Some(true) {
s.select(|d, sel| sel.deselect_uneditable(d))?;
}
return ok();
}
s.edit("Layer Options", |d, sel| {
for id in &ids {
apply_options(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, p, xml_id);
+31 -7
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Links",
[],
None,
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. An image changed by Perspective Distort or Free Distort keeps its corners, with the file's pixels between them, and its Placement Options do not apply; the clipping path its file names is drawn through the corners, and a clip group of the old file's clipping path gets the new one, or becomes a plain group when the file names none. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. An image changed by Perspective Distort or Free Distort keeps its corners, with the file's pixels between them, and its Placement Options do not apply; the clipping path its file names is drawn through the corners, and a clip group of the old file's clipping path gets the new one, or becomes a plain group when the file names none. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns; a .pcraft file read only as its reduced preview, after the file's name]}",
has_doc,
update
),
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Image",
[],
None,
"{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}",
"{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids], warnings?: [a .pcraft document read only as its reduced preview]}",
has_doc,
replace_embedded
),
@@ -636,11 +636,12 @@ pub(crate) fn store_image(d: &mut Document, key: &str, full: ImageBlob, linked:
d.images.insert(key.to_string(), blob);
}
/// Whether `bytes` are a PNG, JPEG, GIF or WebP file: the formats [`fileio::raster_image`] keeps
/// as they are after reading only their header.
/// Whether `bytes` are a PNG, JPEG, GIF or WebP file, the formats [`fileio::raster_image`] keeps
/// as they are after reading only their header, or a `.pcraft` document, whose full-size composite
/// or preview it keeps the same way.
pub(crate) fn kept_unread(bytes: &[u8]) -> bool {
use craft_image_codecs::Format as F;
matches!(craft_image_codecs::detect(bytes), Some(F::Png | F::Jpeg | F::Gif | F::WebP))
matches!(craft_image_codecs::detect(bytes), Some(F::Png | F::Jpeg | F::Gif | F::WebP)) || fileio::is_pcraft(bytes)
}
/// `blob`, an image [`fileio::raster_image`] read from a file, ready to keep. When `unread` (the
@@ -1275,8 +1276,13 @@ fn replace_embedded(s: &mut Session, p: &Value) -> Result<Value> {
let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?;
let mut img = fileio::raster_image(&bytes)?;
img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?;
let note = img.note.clone();
s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?;
Ok(json!({ "replaced": ids_json(&ids) }))
let mut out = json!({ "replaced": ids_json(&ids) });
if let Some(note) = note {
out["warnings"] = json!([note]);
}
Ok(out)
}
/// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels
@@ -2089,7 +2095,8 @@ fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -
}
}
let updated: Vec<u64> = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect();
let warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read));
let mut warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read));
warnings.extend(file_notes(reads.iter().map(|(_, read)| read)));
if !reads.is_empty() {
s.edit("Update Links", |d, _| {
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))
@@ -2102,6 +2109,22 @@ fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -
Ok(out)
}
/// The notes of the images in `reads` that leave part of their file out ([`RasterImage::note`], a
/// `.pcraft` document read as its reduced preview), each after its file's name, once per file.
fn file_notes<'a>(reads: impl Iterator<Item = &'a Read>) -> Vec<String> {
let mut out: Vec<String> = vec![];
for read in reads {
let Read::Image((link, img)) = read else { continue };
let Some(note) = &img.note else { continue };
let name = Path::new(&link.path).file_name().map_or_else(|| link.path.clone(), |n| n.to_string_lossy().into_owned());
let note = format!("{name}: {note}");
if !out.contains(&note) {
out.push(note);
}
}
out
}
/// The warnings for the spot plates of the DCS files in `reads` whose ink a swatch of `d` already
/// names in another color, or as a process color ([`super::place::dcs::swatch_notes`]), or that an
/// earlier file of `reads` adds as a spot swatch in another color, each once.
@@ -2354,6 +2377,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
let unpreserved = preserve.and_then(|_| unpreserved_note(&doc, &reads));
drop(doc);
let mut warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read));
warnings.extend(file_notes(reads.iter().map(|(_, read)| read)));
warnings.extend(unpreserved);
if !reads.is_empty() {
s.edit("Relink", |d, _| editing_brush_art(d, |d| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None))))?;
+38 -15
View File
@@ -9,7 +9,7 @@ use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::marks::{MarkStyle, TrimMarks};
use vectorcraft_doc::{Appearance, ImageObject, LiveShape, Node, NodeId, NodeKind, RasterColorModel, RasterEffectsSettings, Scaling};
use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, Vec2};
use vectorcraft_geom::{Affine, Anchor, Homography, PathData, Point, Rect, Vec2};
use vectorcraft_render::AntiAlias;
use vectorcraft_render::encode::{RasterExportOptions, RasterFormat};
@@ -133,7 +133,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Object Mosaic…",
["Object"],
None,
"{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it, both growing or shrinking in proportion to keep the sizes within 0.1..1000000), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles colored by the selected image's average tile colors → {id, tiles, columns, rows}",
"{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it, both growing or shrinking in proportion to keep the sizes within 0.1..1000000), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles colored by the selected image's average tile colors; on an image changed by Perspective Distort or Free Distort each tile is its cell placed between the image's corners, a four-sided shape, and spacing is measured at the mean length of the image's sides → {id, tiles, columns, rows}",
has_image,
object_mosaic
),
@@ -981,6 +981,9 @@ struct MosaicPlan {
cols: u32,
rows: u32,
xf: Affine,
/// For a distorted image, the map from its pixels to the page that places the tiles instead of
/// `xf`.
warp: Option<Homography>,
tile: (f64, f64),
gap: (f64, f64),
gray: bool,
@@ -1001,9 +1004,6 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result<MosaicPlan> {
.ok_or_else(|| bad(C, "select an image"))?;
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
if node.is_distorted_image() {
return Err(super::xform::distorted_image_error(C, id));
}
if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) {
return Err(bad(C, "the image has no embedded pixels"));
}
@@ -1062,11 +1062,21 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result<MosaicPlan> {
};
let resize = Affine::translate(b.origin().to_vec2()) * Affine::scale_non_uniform(nw / bw, nh / bh) * Affine::translate(-b.origin().to_vec2());
let xf = resize * im.xf;
// Points per image pixel along each of the image's axes (the image may be turned).
let ppx = (xf * Point::new(1.0, 0.0) - xf * Point::ZERO).hypot().max(1e-9);
let ppy = (xf * Point::new(0.0, 1.0) - xf * Point::ZERO).hypot().max(1e-9);
let (sx, sy) = (f64_or(p, "spacingX", 0.0).max(0.0), f64_or(p, "spacingY", 0.0).max(0.0));
let (iw, ih) = (im.width as f64, im.height as f64);
// A distorted image's tiles are its cells mapped between its corners, resized the same way.
let warp = node.image_map().filter(|_| node.is_distorted_image()).map(|h| Homography::from_affine(resize).then_after(&h));
// Points per image pixel along each of the image's axes (the image may be turned). A distorted
// image's sides change length along the way: each axis takes the mean of its two sides.
let (ppx, ppy) = match &warp {
Some(h) => {
let corner = |x: f64, y: f64| h.apply(Point::new(x, y)).ok_or_else(|| super::xform::distorted_image_error(C, id));
let [a, b, c, d] = [corner(0.0, 0.0)?, corner(iw, 0.0)?, corner(iw, ih)?, corner(0.0, ih)?];
((a.distance(b) + d.distance(c)) / (2.0 * iw.max(1.0)), (a.distance(d) + b.distance(c)) / (2.0 * ih.max(1.0)))
}
None => ((xf * Point::new(1.0, 0.0) - xf * Point::ZERO).hypot(), (xf * Point::new(0.0, 1.0) - xf * Point::ZERO).hypot()),
};
let (ppx, ppy) = (ppx.max(1e-9), ppy.max(1e-9));
let (sx, sy) = (f64_or(p, "spacingX", 0.0).max(0.0), f64_or(p, "spacingY", 0.0).max(0.0));
// Use Ratio: square tiles as drawn, spacing taken off, from the count on the kept side,
// measured along the image's axes.
match use_ratio {
@@ -1078,7 +1088,7 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result<MosaicPlan> {
// Spacing is in points; convert to image pixels along each axis.
let gap = ((sx / ppx).min(tw * 0.9), (sy / ppy).min(th * 0.9));
let delete = switch_or(p, "deleteRaster", false, C)?;
Ok(MosaicPlan { id, im: im.as_ref().clone(), cols, rows, xf, tile: (tw, th), gap, gray, delete })
Ok(MosaicPlan { id, im: im.as_ref().clone(), cols, rows, xf, warp, tile: (tw, th), gap, gray, delete })
}
/// The tile counts (columns, rows) `object.createObjectMosaic` would use with `p`, Use Ratio
@@ -1089,10 +1099,26 @@ pub fn mosaic_counts(s: &Session, p: &Value) -> Result<(u32, u32)> {
fn object_mosaic(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.createObjectMosaic";
let MosaicPlan { id, im, cols, rows, xf, tile: (tw, th), gap: (gx, gy), gray, delete } = mosaic_plan(s, p)?;
let MosaicPlan { id, im, cols, rows, xf, warp, tile: (tw, th), gap: (gx, gy), gray, delete } = mosaic_plan(s, p)?;
let blob = s.doc()?.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image has no embedded pixels"))?;
let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?;
let colors = vectorcraft_trace::mosaic(&raster, cols, rows);
// Each tile's corners on the page, its cell less the spacing, through `warp` or `xf`.
let mut quads = Vec::with_capacity(colors.len());
for r in 0..rows {
for c in 0..cols {
let x0 = c as f64 * tw + gx / 2.0;
let y0 = r as f64 * th + gy / 2.0;
let cell = [Point::new(x0, y0), Point::new(x0 + tw - gx, y0), Point::new(x0 + tw - gx, y0 + th - gy), Point::new(x0, y0 + th - gy)];
let mut quad = cell.map(|q| xf * q);
if let Some(h) = &warp {
for (to, q) in quad.iter_mut().zip(cell) {
*to = h.apply(q).ok_or_else(|| super::xform::distorted_image_error(C, id))?;
}
}
quads.push(quad);
}
}
let (gid, n) = s.edit("Create Object Mosaic", |d, sel| {
let mut tiles = vec![];
for r in 0..rows {
@@ -1101,10 +1127,7 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result<Value> {
if ca == 0 {
continue;
}
let x0 = c as f64 * tw + gx / 2.0;
let y0 = r as f64 * th + gy / 2.0;
let quad = [Point::new(x0, y0), Point::new(x0 + tw - gx, y0), Point::new(x0 + tw - gx, y0 + th - gy), Point::new(x0, y0 + th - gy)]
.map(|q| xf * q);
let quad = quads[(r * cols + c) as usize];
let color = if gray {
let l = (0.299 * cr as f32 + 0.587 * cg as f32 + 0.114 * cb as f32) / 255.0;
Color::rgb(l, l, l)
+1 -1
View File
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
+11 -3
View File
@@ -443,10 +443,18 @@ fn changed_aligned(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<Node
/// After an edit that replaces object `id`'s geometry: snap it, or the pixel-aligned compound path
/// that holds it, to the pixel grid again when it is pixel-aligned.
pub(crate) fn resnap(d: &mut Document, id: NodeId) {
if let Some(n) = d.node_mut(id) {
snap_if_aligned(n);
resnap_with(d, id, Scaling::default());
}
/// [`resnap`] with `sc`: the patterns of an object that the snap moves move with it when `sc`
/// transforms patterns.
pub(crate) fn resnap_with(d: &mut Document, id: NodeId, sc: Scaling) {
if let Some(n) = d.node_mut(id)
&& n.extras().pixel_aligned
{
snap_object(n, sc);
}
keep_compound_aligned(d, id, Scaling::default());
keep_compound_aligned(d, id, sc);
}
/// After an edit of `n`'s strokes: when `n` is pixel-aligned, round its stroke weights and snap it to
+128 -45
View File
@@ -2,9 +2,10 @@ use vectorcraft_doc::AnchorRef;
use vectorcraft_geom::PathData;
use super::spans::Span;
use super::transform::{scaling_options, transform_patterns};
use super::{
BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches,
convert_radii_relative, ok, selected_roots, set_corners, targets,
Affine, BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Scaling, Session, Value, bad, check_numbers,
check_switches, convert_radii_relative, ok, selected_roots, set_corners, targets,
};
use crate::MAX_COORD;
@@ -129,8 +130,51 @@ fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<Live
(changed && new != *l).then_some(new)
}
/// The transform that takes live shape `old` to `new` where they differ only in place, angle and
/// size (a new Rectangle, Ellipse or Polygon Angle, Polygon Radius, Side Length, Make Sides Equal,
/// Line Length or Line Angle): what moves, turns and scales the rest of the object (a linked
/// opacity mask, gradients and patterns placed on it) with the new shape. A line takes the turn
/// and even scale that take its old ends to its new ones. None when the shape keeps its place,
/// angle and size (a new side count or pie), for a line whose ends met, and when no finite
/// transform takes one to the other.
fn carry(old: &LiveShape, new: &LiveShape) -> Option<Affine> {
let ratio = |was: f64, now: f64| if was == now { 1.0 } else { now / was };
let xf = match (old, new) {
(LiveShape::Rectangle { w, h, xf, .. }, LiveShape::Rectangle { w: w2, h: h2, xf: xf2, .. })
| (LiveShape::Ellipse { w, h, xf, .. }, LiveShape::Ellipse { w: w2, h: h2, xf: xf2, .. }) => {
if xf == xf2 && w == w2 && h == h2 {
return None;
}
*xf2 * Affine::scale_non_uniform(ratio(*w, *w2), ratio(*h, *h2)) * xf.inverse()
}
(LiveShape::Polygon { radius, xf, .. }, LiveShape::Polygon { radius: r2, xf: xf2, .. }) => {
if xf == xf2 && radius == r2 {
return None;
}
*xf2 * Affine::scale(ratio(*radius, *r2)) * xf.inverse()
}
(LiveShape::Line { a, b }, LiveShape::Line { a: a2, b: b2 }) => {
let (d, d2) = (*b - *a, *b2 - *a2);
let len2 = d.hypot2();
if (a == a2 && b == b2) || len2 <= 0.0 {
return None;
}
// `d2` divided by `d` as complex numbers: the turn and even scale between them.
let (c, s) = ((d2.x * d.x + d2.y * d.y) / len2, (d2.y * d.x - d2.x * d.y) / len2);
let turn = Affine::new([c, s, -s, c, 0.0, 0.0]);
Affine::translate(*a2 - turn * *a) * turn
}
_ => return None,
};
xf.as_coeffs().iter().all(|c| c.is_finite()).then_some(xf)
}
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii"], "object.setLiveShape")?;
check_switches(
p,
&["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii", "strokes", "patterns"],
"object.setLiveShape",
)?;
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
let items = match p.get("items").filter(|v| !v.is_null()) {
@@ -317,50 +361,87 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return ok();
}
// The live shapes that the polygon, rectangle, ellipse and line values change: each as it is and
// as it becomes.
let mut reshaped = std::collections::BTreeMap::new();
for id in &ids {
let Some(NodeKind::Path { live: Some(old), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue };
let mut new = (**old).clone();
let mut edited = false;
if let l @ LiveShape::Polygon { .. } = &mut new
&& (sides.is_some() || polygon_angle.is_some() || polygon_radius.is_some() || side.is_some() || equal)
{
if let Some(n) = sides {
l.set_sides(n);
}
if equal {
l.make_sides_equal();
}
if let Some(a) = polygon_angle {
l.set_polygon_angle(a);
}
// A side length sets the radius that gives it (with the new side count).
if let Some(r) = side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius) {
l.set_polygon_radius(r);
}
edited = true;
}
if let Some(a) = rectangle_angle
&& let l @ LiveShape::Rectangle { .. } = &mut new
{
l.set_shape_angle(a);
edited = true;
}
if let l @ LiveShape::Ellipse { .. } = &mut new
&& (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some())
{
if let Some(a) = ellipse_angle {
l.set_shape_angle(a);
}
if let LiveShape::Ellipse { pie, .. } = l {
*pie = pie_of(*pie);
}
edited = true;
}
if let Some(line) = lines.get(id) {
new = line.clone();
edited = true;
}
if edited {
reshaped.insert(*id, ((**old).clone(), new));
}
}
// A shape that moves, turns or scales takes the rest of the object along as a transform does:
// Scale Strokes & Effects and Transform Patterns come from `strokes` and `patterns` or the
// preferences, and are noted in the journal so a replay does the same. Corner radii in the rest
// of the object keep their size, as the shape's own do; Scale Corners does not apply.
let carried: Vec<NodeId> = reshaped.iter().filter(|(_, (old, new))| carry(old, new).is_some()).map(|(id, _)| *id).collect();
let scales = reshaped.values().any(|(old, new)| carry(old, new).is_some_and(|xf| Scaling::factor(xf).is_some()));
let base = if scales {
let sc = scaling_options(s, p);
s.note_journal("strokes", serde_json::json!(sc.strokes));
sc
} else {
Scaling::default()
};
let sc = Scaling { patterns: !carried.is_empty() && transform_patterns(s, p, &carried)?, keep_corners: true, ..base };
s.edit("Live Shape", |d, sel| {
// Each object once, however often `ids` or `items` names it.
for (id, (old, new)) in &reshaped {
let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
if let Some(xf) = carry(old, new) {
// The bounding box keeps its angle: a shape angle is the shape's own.
let bbox_angle = n.bbox_angle;
n.transform(xf, sc);
n.bbox_angle = bbox_angle;
}
if let NodeKind::Path { path, live, .. } = &mut n.kind {
*live = Some(Box::new(new.clone()));
*path = new.to_path();
}
}
for id in &ids {
let Some(NodeKind::Path { path, live, .. }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
if let Some(l @ LiveShape::Polygon { .. }) = live.as_deref_mut()
&& (sides.is_some() || polygon_angle.is_some() || polygon_radius.is_some() || side.is_some() || equal)
{
if let Some(n) = sides {
l.set_sides(n);
}
if equal {
l.make_sides_equal();
}
if let Some(a) = polygon_angle {
l.set_polygon_angle(a);
}
// A side length sets the radius that gives it (with the new side count).
if let Some(r) = side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius) {
l.set_polygon_radius(r);
}
*path = l.to_path();
}
if let Some(a) = rectangle_angle
&& let Some(l @ LiveShape::Rectangle { .. }) = live.as_deref_mut()
{
l.set_shape_angle(a);
*path = l.to_path();
}
if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut()
&& (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some())
{
if let Some(a) = ellipse_angle {
l.set_shape_angle(a);
}
if let LiveShape::Ellipse { pie, .. } = l {
*pie = pie_of(*pie);
}
*path = l.to_path();
}
if let Some(new) = lines.get(id)
&& let Some(l) = live.as_deref_mut()
{
*l = new.clone();
*path = l.to_path();
}
if let Some(on) = relative_radii
&& let Some(l) = live.as_deref_mut()
{
@@ -385,8 +466,10 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
};
recut(path, live, partial, &picked, radius, kind);
}
// The snap to the pixel grid moves the patterns of a carried shape when the carry did.
for id in &ids {
super::pixelgrid::resnap(d, *id);
let snap = Scaling { patterns: sc.patterns && carried.contains(id), ..Scaling::default() };
super::pixelgrid::resnap_with(d, *id, snap);
}
// A shape named in `ids` and not selected is not checked after the edit: one that a turn or
// a new radius would take past the coordinate limit is an error here, and nothing changes.
+68 -34
View File
@@ -1,5 +1,5 @@
use super::shape::scale_across;
use super::{Affine, Document, Node, NodeId, NodeKind, OrientedBox, Point, Rect};
use super::{Affine, Appearance, Document, Node, NodeId, NodeKind, OrientedBox, Point, Rect};
/// One axis of an object that [`set_bounds`] sizes, square to its frame: the geometric box runs
/// from `lo` to `hi`, and the visual box reaches past each end (before, after) by a margin that
@@ -47,27 +47,47 @@ impl Spans {
(true, true) => n.visual_bounds_with(s),
(false, _) => n.bounds_in(s, to_local, visual),
};
// The box the strokes of the plain groups around `n` paint along it, square to `frame`
// (`Node::painted_by_container`).
let painted = |n: &Node, groups: &[&Appearance], s: &vectorcraft_doc::SymbolBoxes| {
if groups.is_empty() {
return None;
}
let placed;
let n = if frame.angle == 0.0 {
n
} else {
let mut m = n.clone();
m.transform(to_local, false);
placed = m;
&placed
};
groups.iter().fold(None, |acc, a| vectorcraft_geom::union_opt(acc, n.painted_by_container(a, Some(s))))
};
let roots: Vec<&Node> = ids.iter().filter_map(|id| d.node(*id)).collect();
let mut parts = vec![];
if !roots.iter().all(|n| open(n, 0.0, d, &symbols, to_local, &mut parts)) {
parts = roots.iter().map(|n| Part::Object(n, 0.0)).collect();
if !roots.iter().all(|n| open(n, &[], d, &symbols, to_local, &mut parts)) {
parts = roots.iter().map(|n| Part::Object(n, vec![])).collect();
}
let mut out = Self { x: vec![], y: vec![], strokes };
for part in parts {
let (g, v, vs) = match part {
Part::Object(n, grow) => {
Part::Object(n, groups) => {
let Some(g) = measure(n, &symbols, false) else { continue };
let v = measure(n, &symbols, true).unwrap_or(g).inflate(grow, grow);
let vs = if strokes { measure(n, &without, true).unwrap_or(g).inflate(grow, grow) } else { g };
let v = vectorcraft_geom::union_opt(measure(n, &symbols, true), painted(n, &groups, &symbols)).unwrap_or(g);
let vs =
if strokes { vectorcraft_geom::union_opt(measure(n, &without, true), painted(n, &groups, &without)).unwrap_or(g) } else { g };
(g, v, vs)
}
// Measured as the instance's own box measures its art (`Node::visual_bounds_with`):
// the strokes at their own weight, and the instances in it by their art boxes.
// the strokes at their own weight, those of the plain groups around it in the art
// included, and the instances in it by their art boxes.
Part::Art(n, xf, grow, kept) => {
let mut placed = n.clone();
placed.transform(xf, false);
let Some(g) = placed.geometric_bounds_with(&art) else { continue };
let v = placed.visual_bounds_with(&art).map_or(g, |v| v.union(g)).inflate(kept + grow, kept + grow);
let v = placed.visual_bounds_with(&art).map_or(g, |v| v.union(g));
let v = kept.iter().fold(v, |v, a| placed.painted_by_container(a, Some(&art)).map_or(v, |p| v.union(p))).inflate(grow, grow);
let vs = if strokes { g.inflate(grow, grow) } else { g };
(g, v, vs)
}
@@ -155,29 +175,40 @@ const MAX_SPANS: usize = 4096;
/// What [`Spans::measure`] measures as one span.
enum Part<'a> {
/// An object of the selection, or a member of a plain group in it, and the outset of the
/// strokes of the plain groups around it, which scale with its own.
Object(&'a Node, f64),
/// An object of the selection, or a member of a plain group in it, and the appearances of the
/// plain groups around it, whose strokes paint along it and scale with its own.
Object(&'a Node, Vec<&'a Appearance>),
/// An object in the art of a symbol instance and the transform that places it square to the
/// frame. The outset of the strokes of the instance and of the plain groups around the instance
/// scales with the strokes; the outset of the strokes of the plain groups around the object in
/// the art stays, as the strokes in the art do.
Art(&'a Node, Affine, f64, f64),
/// frame. The outset of the strokes of the instance scales with the strokes; the strokes of the
/// plain groups around the object in the art, given by their appearances, paint along it and
/// stay, as the strokes in the art do. The strokes of the plain groups around the instance paint
/// nothing round it.
Art(&'a Node, Affine, f64, Vec<&'a Appearance>),
}
/// Adds the parts that [`Spans::measure`] measures `n` by to `parts`, `grow` being the outset of
/// the strokes of the plain groups around it ([`Part::Object`]). A plain group ([`opens`]) adds the
/// parts of each member. A symbol instance without effects or an opacity mask of its own adds the
/// objects of its art, with plain groups there opened too ([`Part::Art`]), when its symbol's art
/// Adds the parts that [`Spans::measure`] measures `n` by to `parts`, `groups` being the
/// appearances of the plain groups around it ([`Part::Object`]); hidden members and guides stop
/// those groups' strokes. A plain group ([`opens`]) adds the parts of each member. A symbol
/// instance without effects or an opacity mask of its own adds the objects of its art, with plain
/// groups there opened too ([`Part::Art`]), when its symbol's art
/// measures it, it is not in perspective, and its transform keeps the art square to the frame (a
/// turned or slanted instance is measured by the box around its turned art box). Anything else is
/// one part. Returns false when the parts pass [`MAX_SPANS`].
fn open<'a>(n: &'a Node, grow: f64, d: &'a Document, symbols: &vectorcraft_doc::SymbolBoxes, to_local: Affine, parts: &mut Vec<Part<'a>>) -> bool {
fn open<'a>(
n: &'a Node,
groups: &[&'a Appearance],
d: &'a Document,
symbols: &vectorcraft_doc::SymbolBoxes,
to_local: Affine,
parts: &mut Vec<Part<'a>>,
) -> bool {
let groups = if n.visible && !n.is_guide() { groups } else { &[] };
if opens(n) {
match &n.kind {
NodeKind::Group { children, .. } => {
let grow = grow + n.appearance.outset();
return children.iter().all(|c| open(c, grow, d, symbols, to_local, parts));
let mut groups = groups.to_vec();
groups.push(&n.appearance);
return children.iter().all(|c| open(c, &groups, d, symbols, to_local, parts));
}
NodeKind::SymbolInstance { symbol, xf } => {
let xf = to_local * *xf;
@@ -186,38 +217,41 @@ fn open<'a>(n: &'a Node, grow: f64, d: &'a Document, symbols: &vectorcraft_doc::
&& symbols.art_bounds(symbol).is_some()
&& let Some(art) = d.symbols.iter().find(|s| s.name == *symbol)
{
return open_art(&art.art, xf, grow + n.appearance.outset(), 0.0, parts);
return open_art(&art.art, xf, n.appearance.outset(), &[], parts);
}
}
_ => {}
}
}
parts.push(Part::Object(n, grow));
parts.push(Part::Object(n, groups.to_vec()));
parts.len() <= MAX_SPANS
}
/// [`open`] for `n` in symbol art that `xf` places square to the frame: a plain group adds the parts
/// of each member, and anything else, a symbol instance included, is one part. `kept` is the outset
/// of the strokes of the plain groups around `n` in the art, and `grow` that of the instance and the
/// plain groups around it.
fn open_art<'a>(n: &'a Node, xf: Affine, grow: f64, kept: f64, parts: &mut Vec<Part<'a>>) -> bool {
/// of each member, and anything else, a symbol instance included, is one part. `kept` holds the
/// appearances of the plain groups around `n` in the art, stopped at hidden members and guides,
/// and `grow` is the outset of the strokes of the instance.
fn open_art<'a>(n: &'a Node, xf: Affine, grow: f64, kept: &[&'a Appearance], parts: &mut Vec<Part<'a>>) -> bool {
let kept = if n.visible && !n.is_guide() { kept } else { &[] };
if let NodeKind::Group { children, .. } = &n.kind
&& opens(n)
{
let kept = kept + n.appearance.outset();
return children.iter().all(|c| open_art(c, xf, grow, kept, parts));
let mut kept = kept.to_vec();
kept.push(&n.appearance);
return children.iter().all(|c| open_art(c, xf, grow, &kept, parts));
}
parts.push(Part::Art(n, xf, grow, kept));
parts.push(Part::Art(n, xf, grow, kept.to_vec()));
parts.len() <= MAX_SPANS
}
/// Whether [`open`] opens `n`: a group without a clip, a Shaper construction, effects or an opacity
/// mask of its own, or a symbol instance without effects or an opacity mask of its own.
/// Whether [`open`] opens `n`: a group that is not a compound shape and has no clip, Shaper
/// construction, effects or opacity mask of its own, or a symbol instance without effects or an
/// opacity mask of its own.
fn opens(n: &Node) -> bool {
let visible = |effects: &[vectorcraft_doc::Effect]| effects.iter().any(|e| e.visible);
let effects = visible(&n.appearance.effects) || n.appearance.items.iter().any(|i| visible(i.effects()));
let kind = match n.kind {
NodeKind::Group { clip, .. } => !clip && n.extras().shaper.is_none(),
NodeKind::Group { clip, .. } => !clip && !n.is_compound_shape() && n.extras().shaper.is_none(),
NodeKind::SymbolInstance { .. } => true,
_ => false,
};
+14 -3
View File
@@ -63,15 +63,15 @@ pub(super) fn scaling_options(s: &Session, p: &Value) -> Scaling {
}
/// Transform Patterns: do the pattern fills and strokes of `ids` transform with them (`patterns`
/// param, else General › Transform Pattern Tiles)? Noted in the journal when they use a pattern,
/// so a replay moves their tiles alike whatever the preference is then.
/// param, else General › Transform Pattern Tiles)? Noted in the journal when they or the art of
/// their linked opacity masks use a pattern, so a replay moves their tiles alike whatever the preference is then.
pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<bool> {
let on = bool_or(p, "patterns", s.prefs.transform_pattern_tiles);
let d = &s.doc()?.doc;
let mut uses = false;
let paths = d.index_paths(ids.iter().copied());
for n in ids.iter().filter_map(|id| paths.get(id)).filter_map(|p| d.node_at(p)) {
n.walk(&mut |c| uses |= vectorcraft_doc::pattern::uses_pattern(c, None));
uses |= uses_pattern_with_masks(n);
}
if uses {
s.note_journal("patterns", json!(on));
@@ -79,6 +79,17 @@ pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) ->
Ok(on)
}
/// Whether `n`, a descendant or the art of a linked opacity mask among them (and theirs) has a
/// pattern fill or stroke: what Transform Patterns moves when `n` is transformed.
fn uses_pattern_with_masks(n: &vectorcraft_doc::Node) -> bool {
let mut uses = false;
n.walk(&mut |c| {
uses |= vectorcraft_doc::pattern::uses_pattern(c, None)
|| c.extras().mask.as_deref().is_some_and(|m| m.linked && uses_pattern_with_masks(&m.art));
});
uses
}
/// Transform Objects (`objects` param, on unless it is false): off, a transform leaves the art
/// where it is and, with Transform Patterns, moves only its pattern tiles.
pub(crate) fn transforms_objects(p: &Value) -> bool {
+95 -4
View File
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill",
[],
None,
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o Line truncated
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o Line truncated
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -394,6 +394,64 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'
}
}
#[cfg(test)]
thread_local! {
/// Tests: how many fills [`SelectionPaints`] read or took out on this thread.
pub(crate) static PAINTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The objects that reading objects `ids` meets, one item each ([`SelectionPaints::reads_no_more_than`]):
/// each id, and the contents of a group, a layer, a Live Paint group or a container inside a group,
/// as [`painted`] expands them. An id with no object and a ruler guide count once each.
struct Reads<'a> {
doc: &'a Document,
ids: std::slice::Iter<'a, NodeId>,
/// The contents not counted yet of the objects met, innermost last.
left: Vec<std::slice::Iter<'a, std::sync::Arc<Node>>>,
}
impl<'a> Reads<'a> {
fn new(doc: &'a Document, ids: &'a [NodeId]) -> Self {
Self { doc, ids: ids.iter(), left: vec![] }
}
}
impl Iterator for Reads<'_> {
type Item = ();
fn next(&mut self) -> Option<()> {
loop {
let (n, top) = match self.left.last_mut() {
Some(contents) => match contents.next() {
Some(c) => (&**c, false),
None => {
self.left.pop();
continue;
}
},
None => match self.doc.node(*self.ids.next()?) {
Some(n) => (n, true),
None => return Some(()),
},
};
// A ruler guide has no paints, but reading meets it, so it counts once.
if n.is_ruler_guide() {
return Some(());
}
// A Live Paint group is a group too, so it expands without looking for its parts.
let expand = match n.kind {
NodeKind::Group { .. } | NodeKind::Layer { .. } => true,
NodeKind::Compound { .. } => false,
_ => !top && n.is_container(),
};
if let Some(contents) = n.children().filter(|_| expand) {
self.left.push(contents.iter());
}
return Some(());
}
}
}
/// What the proxies read from selected objects: the first fill, stroke and stroke weight met, and
/// whether another one differs ([`DocState::proxy_mixed`] without an active Appearance item or
/// picked mesh points, and [`super::stroke::StrokeMixed::weight`]), and whether an object lies in a
@@ -489,6 +547,23 @@ impl SelectionPaints {
self.may_hold_mesh > 0
}
/// Does reading objects `ids` of `doc` meet no more objects than reading objects `others`?
/// Each id counts once, and a group, a layer, a Live Paint group or a container inside a group
/// also counts its contents, as [`painted`] expands them. The two counts go up one object at a
/// time in turn and stop when either side runs out, so the check meets at most twice as many
/// objects as the smaller side holds.
pub(crate) fn reads_no_more_than(doc: &Document, ids: &[NodeId], others: &[NodeId]) -> bool {
let (mut these, mut those) = (Reads::new(doc, ids), Reads::new(doc, others));
loop {
if these.next().is_none() {
return true;
}
if those.next().is_none() {
return false;
}
}
}
/// Read objects `ids` of `doc` too: ids that are not read yet, each named once.
pub(crate) fn add(&mut self, doc: &Document, ids: &[NodeId]) {
self.each(doc, ids, true);
@@ -517,6 +592,8 @@ impl SelectionPaints {
painted(n, true, false, &mut fills);
painted(n, true, true, &mut strokes);
}
#[cfg(test)]
PAINTS_READ.with(|c| c.set(c.get() + fills.len()));
for n in fills {
meet(&mut self.fill, proxy_paint(n, false, None));
}
@@ -834,6 +911,11 @@ fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
}
}
/// Whether `p` gives `key` a value other than null.
fn names(p: &Value, key: &str) -> bool {
p.get(key).is_some_and(|v| !v.is_null())
}
/// The error for an `opacity` that would go to type characters, which have no opacity of their own.
fn characters_have_no_opacity(cmd: &str) -> EngineError {
bad(cmd, "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke")
@@ -863,13 +945,22 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option<Paint>, opacity
let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
let for_tool = tool_color_params(s, p, cmd, !fill)?;
let p = for_tool.as_ref().unwrap_or(p);
// A bad `target` or `aligned` is refused for every kind of target: selected characters take
// the paint before `item_target` reads either.
super::appearance::aligned(p, cmd)?;
super::appearance::targets_contents(p)?;
let focus = switch_or(p, "focus", true, cmd)?;
// An opacity alone places no gradient, so `span` may only be "object" with it.
let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?;
// Characters selected with the Type tool take the paint, not the whole type object (#1063). A
// null `ids` or `id` names no object, as `given_nodes` reads it.
if ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null))
&& p.get("item").is_none()
let on_characters = !names(p, "ids") && !names(p, "id") && p.get("item").is_none();
// An opacity for the characters is refused before their typing session ends, so the session
// and its undo step stay as they are.
if on_characters && opacity.is_some() && super::textedit::selected_range(s).is_some_and(|(_, a, b)| a != b) {
return Err(characters_have_no_opacity(cmd));
}
if on_characters
&& let Some((id, a, b)) = super::textedit::editing_range(s)?
&& a != b
{
@@ -1378,7 +1469,7 @@ impl DocState {
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result<Option<(NodeId, Vec<u32>)>> {
if p.get("ids").is_some() || p.get("id").is_some() || p.get("item").is_some() {
if names(p, "ids") || names(p, "id") || p.get("item").is_some() {
return Ok(None);
}
let part = super::brushsym::selected_part(s)?;
+90 -1
View File
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Anchors",
[],
None,
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
"{dx, dy (a move by 0 changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
has_selection,
move_anchors
),
@@ -54,6 +54,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
set_handle
),
cmd!(
"path.moveHandles",
"Move Direction Handles",
[],
None,
"{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused",
has_doc,
move_handles
),
cmd!(
"path.moveAnchor",
"Move Anchor Point",
@@ -262,6 +271,10 @@ fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result<Value> {
check_switches(p, &["patterns", "interpolate"], C)?;
// An object selected in a symbol instance's art stays where the symbol puts it.
super::edit::refuse_symbol_part(s)?;
// A move by 0 changes nothing, and the document and its undo history stay as they are.
if d == Vec2::ZERO {
return ok();
}
let st = s.doc()?;
let mut sel = st.selection.clone();
let (held, bends) = if bend { held_segments(&st.doc, &mut sel, d) } else { (false, vec![]) };
@@ -584,6 +597,82 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// `path.moveHandles`: the listed direction handles move by `(dx, dy)` together, as one undo step.
/// Each anchor with one listed handle places it as `path.setHandle` does; an anchor with both
/// listed moves both and becomes a corner. A move by nothing, with no anchor to make a corner,
/// records no undo step.
fn move_handles(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.moveHandles";
let list = match p.get("handles") {
None | Some(Value::Null) => return Err(bad(C, "missing handles")),
Some(v) => v.as_array().ok_or_else(|| bad(C, "`handles` must be an array"))?,
};
if list.is_empty() {
return Err(bad(C, "`handles` is empty"));
}
let d = Vec2::new(f64_req(p, "dx", C)?, f64_req(p, "dy", C)?);
if !(d.x.abs() < 1e9 && d.y.abs() < 1e9) {
return Err(bad(C, "dx and dy must be finite"));
}
let independent = switch_or(p, "independent", false, C)?;
if s.script_running() {
return Err(EngineError::Busy);
}
// Each anchor with the sides of it listed: (incoming, outgoing).
let mut anchors: BTreeMap<(NodeId, usize, usize), (bool, bool)> = BTreeMap::new();
let doc = &s.doc()?.doc;
for (i, h) in list.iter().enumerate() {
if !h.is_object() {
return Err(bad(C, format!("handles[{i}] must be an object")));
}
let id = object_param(h, "id", C)?.ok_or_else(|| bad(C, format!("handles[{i}]: missing id")))?;
let si = usize_opt(h, "subpath", C)?.unwrap_or(0);
let ai = index_opt(h, "anchor", C)?.ok_or_else(|| bad(C, format!("handles[{i}]: missing anchor")))?;
let out = match str_param(h, "which") {
Some("out") => true,
Some("in") => false,
_ => return Err(bad(C, format!("handles[{i}]: `which` must be \"in\" or \"out\""))),
};
let n = doc.node(id).ok_or(EngineError::NoNode(id))?;
let NodeKind::Path { path, .. } = &n.kind else { return Err(bad(C, format!("handles[{i}]: object {id} is not a path"))) };
if path.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)).is_none() {
return Err(bad(C, format!("handles[{i}]: object {id} has no anchor {ai} in subpath {si}")));
}
let e = anchors.entry((id, si, ai)).or_default();
if out { e.1 = true } else { e.0 = true }
}
// A move by nothing changes only the kind of anchors that become corners: those with both
// handles listed, or every listed one with `independent`.
if d == Vec2::ZERO {
let corners = anchors.iter().any(|(&(id, si, ai), &(inn, out))| {
(independent || (inn && out))
&& doc
.node(id)
.and_then(|n| n.path_data())
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai))
.is_some_and(|a| a.kind != AnchorKind::Corner)
});
if !corners {
return ok();
}
}
s.edit("Reshape", |doc, _| {
for (&(id, si, ai), &(inn, out)) in &anchors {
let a = path_mut(doc, id)?.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
if inn && out {
a.kind = AnchorKind::Corner;
a.h_in += d;
a.h_out += d;
} else {
let h = if out { a.h_out } else { a.h_in };
a.set_handle(out, h + d, independent);
}
}
Ok(())
})?;
ok()
}
/// `path.setHandle` with `link` (the Anchor Point tool's Alt-drag on a handle): the handle goes to
/// (x, y) and the anchor becomes smooth, its other handle turned in line at its own length. A
/// retracted other handle is pulled out to the moved handle's length when a segment leaves the
+1 -1
View File
@@ -329,7 +329,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
let (sx, sy) = pt_per_px(img.ppi);
let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy);
let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes));
let mut warnings: Vec<String> = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect();
let mut warnings: Vec<String> = unread.into_iter().chain(img.note.clone()).chain(fileio::size_note(&img.blob.bytes)).collect();
*slices_out = psd_slices(slices_from, natural, &mut warnings);
let clip = img.clip.clone().map(|(path, _)| path);
return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None });
+1 -1
View File
@@ -105,7 +105,7 @@ pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result<DcsArt> {
let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref())
.ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?;
let clip = clip.map(|path| (path, vectorcraft_geom::FillRule::NonZero));
let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip };
let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip, note: None };
let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect();
Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings })
}
+8 -2
View File
@@ -111,7 +111,7 @@ pub fn describe(p: &Plugin) -> Value {
v["place"] = json!(true);
}
}
Kind::Filter => {}
Kind::Filter | Kind::Generator => {}
}
if m.budget == Budget::Heavy {
v["budget"] = json!("heavy");
@@ -156,6 +156,9 @@ pub fn describe(p: &Plugin) -> Value {
}
entry["menu"] = menu;
}
if !c.context.is_empty() {
entry["menu"]["context"] = json!(c.context);
}
entry
})
.collect();
@@ -274,6 +277,9 @@ impl FilterRun {
format!("`{}` is an importer: open a file with document.open {{\"importer\": \"{}\"}}", m.id, export::format_id(&m.id)),
));
}
Kind::Generator => {
return Err(bad(C, format!("`{}` is a generator: draw its art with plugin.generate {{\"id\": \"{}\"}}", m.id, m.id)));
}
}
Self::prepare_with(s, plugin, None, C, p)
}
@@ -2402,7 +2408,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -154,6 +154,7 @@ pub(super) const ALLOWED: &[&str] = &[
"color.convert",
"color.gamutCheck",
"color.harmony",
"color.parse",
"color.plates",
"color.used",
"dataset.capture",
@@ -473,6 +474,7 @@ pub(super) const ALLOWED: &[&str] = &[
"path.mirrorCut",
"path.moveAnchor",
"path.moveAnchors",
"path.moveHandles",
"path.quickPen",
"path.quickPenLength",
"path.rectCut",
@@ -545,6 +547,7 @@ pub(super) const ALLOWED: &[&str] = &[
"select.object.strayPoints",
"select.object.textObjects",
"select.recall",
"select.remove",
"select.reselect",
"select.same.appearance",
"select.same.appearanceAttribute",
+275
View File
@@ -0,0 +1,275 @@
//! Generated art objects: art a generator plug-in draws from its parameters alone
//! ([`vectorcraft_plugins::generate`]), kept in a group with the parameters it was drawn with
//! ([`vectorcraft_doc::generated`]).
//!
//! `plugin.generate` runs a generator and adds its art as a new generated art object, one undo
//! step. `plugin.editGenerated` runs the object's generator again with changed parameters and
//! replaces the art, one undo step (none when nothing changes), placed as the object has been
//! moved, scaled, rotated, reflected or sheared since it was drawn. Object › Expand makes it an
//! ordinary group of its art. `plugin.generatedInfo` describes one.
//!
//! The plug-in runs only when one of these commands asks it to, with its own permissions and budget:
//! opening, placing, pasting, drawing and exporting a document never run it. A generated art object
//! whose plug-in isn't installed, whose saved fields are damaged, or whose art doesn't match the hash
//! its file gave keeps its art as it is, and opening the file says so ([`open_notes`]).
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_doc::generated::{GeneratedArt, MAX_ART_BYTES, State, art_bytes};
use vectorcraft_doc::{Document, Node, NodeId};
use vectorcraft_plugins::objects::{self, OutObject};
use vectorcraft_plugins::permissions::{self, display_text};
use vectorcraft_plugins::{Plugin, generate, registry};
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, str_param};
const GENERATE: &str = "plugin.generate";
const EDIT: &str = "plugin.editGenerated";
const INFO: &str = "plugin.generatedInfo";
/// The undo step of `plugin.editGenerated`.
pub const EDIT_LABEL: &str = "Edit Generated Art";
/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing.
fn err(e: vectorcraft_plugins::Error) -> EngineError {
match e {
vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled,
e => EngineError::Other(e.to_string()),
}
}
/// The error of a plug-in's bad parameters for command `c`, others as [`err`] gives them.
fn params_err(c: &str) -> impl Fn(vectorcraft_plugins::Error) -> EngineError + '_ {
move |e| match e {
vectorcraft_plugins::Error::Params(why) => bad(c, why),
e => err(e),
}
}
/// The limits a generator runs under: its own, with the Plug-in Instruction Budget in force.
fn limits(s: &Session, plugin: &Plugin) -> vectorcraft_plugins::Limits {
match s.prefs.plugin_instruction_budget {
crate::PluginBudget::Normal => plugin.limits().clone(),
crate::PluginBudget::Large => plugin.large_limits(),
}
}
/// The plug-in of generated art `g` as a message shows it: its name (its id when it has none) and
/// its id, each as a prompt shows a manifest string.
fn shown(g: &GeneratedArt) -> (String, String) {
let id = display_text(&g.plugin, permissions::MAX_SHOWN_FIELD);
let name = if g.name.trim().is_empty() { id.clone() } else { display_text(g.name.trim(), permissions::MAX_SHOWN_NAME) };
(name, id)
}
/// Generated art whose plug-in, by its saved id, isn't installed.
fn not_installed(g: &GeneratedArt) -> String {
let (name, id) = shown(g);
format!("“{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is")
}
/// Generated art whose saved fields can't be read.
const DAMAGED: &str = "a generated art object's plug-in id or parameters are damaged, so its art can't be drawn again: the art stays as it is";
/// Generated art that doesn't match the hash its file gave.
fn changed(g: &GeneratedArt) -> String {
let (name, id) = shown(g);
format!("the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is")
}
/// What opening `doc` says about its generated art objects, each note once: those whose plug-in
/// isn't installed or is installed as a plug-in of another kind, those whose saved fields are
/// damaged, and those whose art doesn't match its file's hash. Opening runs no plug-in.
pub fn open_notes(doc: &Document) -> Vec<String> {
let mut notes: Vec<String> = vec![];
let mut visit = |n: &Node| {
let Some(g) = n.extras().generated.as_deref() else { return };
let note = match g.state {
State::Damaged => DAMAGED.to_string(),
state => match generate::named(&g.plugin) {
Err(vectorcraft_plugins::Error::NotFound(_)) => not_installed(g),
Err(e) => e.to_string(),
Ok(_) if state == State::Changed => changed(g),
Ok(_) => return,
},
};
if !notes.contains(&note) {
notes.push(note);
}
};
for layer in &doc.layers {
vectorcraft_doc::swatches::walk_with_masks(layer, &mut visit);
}
for symbol in &doc.symbols {
vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut visit);
}
for pattern in &doc.patterns {
for art in &pattern.art {
vectorcraft_doc::swatches::walk_with_masks(art, &mut visit);
}
}
for design in &doc.graph_designs {
vectorcraft_doc::swatches::walk_with_masks(&design.art, &mut visit);
}
notes
}
/// Draws the art `out` in generated art object `gid`, in place of the art it holds, placed as
/// `settings` says its art has been transformed ([`GeneratedArt::place`]). The objects go through a
/// filter's checks; art past [`MAX_ART_BYTES`] is refused.
fn draw(d: &mut Document, gid: NodeId, out: Vec<OutObject>, settings: &GeneratedArt) -> Result<()> {
if let Some(ch) = d.node_mut(gid).and_then(Node::children_mut) {
ch.clear();
}
let admit = |fx: &[vectorcraft_doc::Effect], n: &Node| super::plugin::admit_effects_for(GENERATE, fx, n);
let ids = objects::apply_output(d, &[], out, Some(gid), &admit).map_err(err)?;
let g = d.node_mut(gid).ok_or(EngineError::NoNode(gid))?;
if let Some(ch) = g.children_mut() {
for c in ch.iter_mut() {
settings.place(Arc::make_mut(c), vectorcraft_render::effects::scale_effect);
}
}
if art_bytes(g.children().map_or(&[][..], Vec::as_slice)) > MAX_ART_BYTES {
return Err(err(vectorcraft_plugins::Error::Output(format!(
"the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps"
))));
}
if !super::super::sanity::objects_in_range(d, &ids) {
return Err(EngineError::Other("result would exceed the canvas (coordinates out of range)".into()));
}
Ok(())
}
/// `plugin.generate {id, params?}`: runs generator `id` with its parameters (checked first: missing
/// ones take their defaults) and adds its art as a new generated art object in the current layer,
/// selected, as one undo step named after the plug-in → `{id, plugin}`.
fn generate_art(s: &mut Session, p: &Value) -> Result<Value> {
let id = str_param(p, "id").ok_or_else(|| bad(GENERATE, "missing `id` (see plugin.list)"))?;
let plugin = generate::named(id).map_err(params_err(GENERATE))?;
let given = p.get("params").cloned().unwrap_or(Value::Null);
let params = generate::resolve(&plugin, &given).map_err(params_err(GENERATE))?;
let parent = s.doc()?.target_parent()?;
let out = generate::run(&plugin, &params, &limits(s, &plugin)).map_err(err)?;
let m = plugin.manifest();
let label = m.name.trim_end_matches('…').to_string();
let gid = s.edit(&label, |d, sel| {
let gid = d.alloc_id();
let mut g = Node::group(gid, vec![]);
g.name = Some(m.name.trim_end_matches('…').to_string());
let settings = GeneratedArt::new(&m.id, &m.name, params);
g.extras_mut().generated = Some(Box::new(settings.clone()));
d.insert(parent, usize::MAX, g)?;
draw(d, gid, out, &settings)?;
sel.set([gid]);
Ok(gid)
})?;
Ok(json!({"id": gid.0, "plugin": m.id}))
}
/// The generated art object `p` names (`id`), else the one selected → its id and settings. A
/// locked or hidden one, and a selection that holds none or more than one, are errors.
fn target(s: &Session, c: &str, p: &Value) -> Result<(NodeId, GeneratedArt)> {
let st = s.doc()?;
let one = |id: NodeId| st.doc.node(id).and_then(|n| n.extras().generated.as_deref().cloned()).map(|g| (id, g));
let found = match super::given_objects(s, p, c)? {
Some(ids) if ids.len() == 1 => one(ids[0]),
Some(_) => None,
None => match st.selection.objects.as_slice() {
[id] => one(*id),
_ => None,
},
};
let select = || bad(c, "select one generated art object");
let (id, g) = found.ok_or_else(select)?;
if !st.doc.is_editable(id) {
return Err(select());
}
Ok((id, g))
}
/// The installed generator of generated art `g`, which must be able to draw it again.
fn generator_of(c: &str, g: &GeneratedArt) -> Result<Arc<Plugin>> {
if g.state == State::Damaged {
return Err(bad(c, DAMAGED));
}
match registry::get(&g.plugin) {
None => Err(bad(c, not_installed(g))),
Some(_) => generate::named(&g.plugin).map_err(params_err(c)),
}
}
/// `plugin.editGenerated {id?, params}`: runs the generator of generated art object `id` (else the
/// selected one) again with its saved parameters changed by `params` (checked against the plug-in's
/// manifest; saved ones it no longer declares are left out) and replaces its art, placed as the
/// object has been transformed since it was drawn, as one undo step. Parameters that change nothing
/// run nothing and make no undo step → `{id, plugin, changed}`.
fn edit_generated(s: &mut Session, p: &Value) -> Result<Value> {
let (id, g) = target(s, EDIT, p)?;
let plugin = generator_of(EDIT, &g)?;
let m = plugin.manifest();
let given = match p.get("params") {
None | Some(Value::Null) => Value::Object(Map::new()),
Some(v @ Value::Object(_)) => v.clone(),
Some(_) => return Err(bad(EDIT, "`params` must be an object")),
};
let params = generate::resolve_over(&plugin, &g.params, &given).map_err(params_err(EDIT))?;
if params == g.params {
return Ok(json!({"id": id.0, "plugin": g.plugin, "changed": false}));
}
let out = generate::run(&plugin, &params, &limits(s, &plugin)).map_err(err)?;
let settings = GeneratedArt { params, state: State::Intact, name: m.name.chars().take(vectorcraft_doc::generated::MAX_NAME).collect(), ..g };
s.edit(EDIT_LABEL, |d, _| {
draw(d, id, out, &settings)?;
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
n.extras_mut().generated = Some(Box::new(settings));
Ok(())
})?;
Ok(json!({"id": id.0, "plugin": m.id, "changed": true}))
}
/// `plugin.generatedInfo {id?}`: generated art object `id` (else the selected one) → `{id, plugin,
/// name, params, state, installed}`.
fn info(s: &mut Session, p: &Value) -> Result<Value> {
let (id, g) = target(s, INFO, p)?;
let state = match g.state {
State::Intact => "intact",
State::Damaged => "damaged",
State::Changed => "changed",
};
let installed = g.state != State::Damaged && generate::named(&g.plugin).is_ok();
Ok(json!({"id": id.0, "plugin": g.plugin, "name": g.name, "params": g.params, "state": state, "installed": installed}))
}
/// This module's commands: `plugin.generate`, `plugin.editGenerated` and `plugin.generatedInfo`.
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"plugin.generate",
"Generate Art",
[],
None,
"{id: a generator plug-in (plugin.list kind \"generator\"), params?: {…} (its parameters; missing ones take their defaults, see plugin.info; a bad one is an error)} run the generator and add its art to the current layer as a new generated art object (a group that keeps the plug-in's id and name and the parameters, at most 64 KiB of JSON), selected, as one undo step named after the plug-in; its objects go through a filter's checks and the art may take at most 16 MiB of JSON. Edit it with plugin.editGenerated; Object › Expand makes it an ordinary group → {id, plugin}",
has_doc,
generate_art
),
cmd!(
"plugin.editGenerated",
"Edit Generated Art",
[],
None,
"{id?: a generated art object (default: the one selected), params: {…} (the parameters to change; the others keep their saved values)} run the object's generator again and replace its art, placed as the object has been moved, scaled, rotated, reflected or sheared since it was drawn, as one undo step; parameters that change nothing run nothing and make no undo step. An object whose plug-in isn't installed, or whose saved plug-in id, parameters, transforms or scales are damaged, is an error, and its art stays as it is (Object › Expand keeps it as ordinary art) → {id, plugin, changed}",
has_doc,
edit_generated
),
cmd!(
query "plugin.generatedInfo",
"Generated Art Info",
[],
None,
"{id?: a generated art object (default: the one selected)} → {id, plugin (its generator's id), name (the generator's name when it drew the art), params, state: \"intact\" | \"damaged\" (its saved plug-in id, parameters, transforms or scales can't be read: it can't be drawn again) | \"changed\" (its art doesn't match the hash its file gave), installed (its generator is installed)}",
has_doc,
info
),
]
}
+1 -1
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Script",
[],
None,
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that l Line truncated
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s resul Line truncated
always,
run
),
+37 -1
View File
@@ -77,6 +77,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
toggle
),
cmd!(
"select.remove",
"Remove from Selection",
[],
None,
"{id} or {ids: [id…]}: each one leaves the selection; one inside a selected group or compound path (Direct Selection's Shift-click on it) leaves it too, and the rest of that group stays selected: the outermost selected object around it gives way to the objects inside it on the way down, leaving out hidden and locked objects; an id that is neither selected nor inside a selected object is left alone; all ids must be non-negative integers naming existing objects → {count, ids} (resulting selection)",
has_doc,
remove
),
cmd!(
"select.key",
"Cancel Key Object",
@@ -556,6 +565,25 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
selection_result(s)
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "select.remove";
let ids = if p.get("ids").is_some() {
checked_ids_param(s, p, "ids", C)?
} else {
let value = p.get("id").ok_or_else(|| bad(C, "missing id or ids"))?;
vec![checked_id(s, value, C)?]
};
s.select(|d, sel| {
for id in ids {
sel.expand_to(d, id);
if sel.contains(id) {
sel.remove(id);
}
}
})?;
selection_result(s)
}
fn selection_result(s: &Session) -> Result<Value> {
let selection = &s.doc()?.selection;
Ok(json!({ "count": selection.len(), "ids": selection.objects }))
@@ -930,7 +958,15 @@ fn anchors(s: &mut Session, p: &Value) -> Result<Value> {
}
// A path selected as a whole has every anchor selected: toggle and add start from them all,
// but only when no partial anchor selection is active and only on a single isolated object.
let whole = sel.contains(id) && sel.partial(id).is_none() && sel.anchors.is_empty() && sel.objects.len() <= 1;
// A toggle on a path inside a selected group selects the path itself in the group's place,
// beside the group's other objects, and starts from all its anchors. A toggle on a group
// member that is itself selected whole (as an earlier toggle in the group leaves the other
// members) starts from all its anchors whatever else is selected.
let toggle = mode == "toggle";
let inside = toggle && sel.expand_to(d, id);
let own = sel.contains(id) && sel.partial(id).is_none();
let in_group = || d.ancestry(id).is_some_and(|c| c.len() >= 2 && d.node(c[c.len() - 2]).is_some_and(|n| !n.is_layer()));
let whole = inside || (own && ((sel.anchors.is_empty() && sel.objects.len() <= 1) || (toggle && in_group())));
sel.add(id);
// A segment pick's endpoints aren't selected anchors: start from none of them.
if sel.segments.remove(&id).is_some() {
+1 -1
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
["Window", "Stroke"],
None,
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
+12 -7
View File
@@ -163,7 +163,7 @@ pub fn specs() -> Vec<CommandSpec> {
"charStyle.edit",
"Edit Character Style",
&[],
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings",
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; [Normal Character Style] takes only `to` equal to `name`; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings",
|s, p| edit_style(s, p, Kind::Char),
true,
));
@@ -178,7 +178,7 @@ pub fn specs() -> Vec<CommandSpec> {
"paraStyle.edit",
"Edit Paragraph Style",
&[],
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position",
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; [Normal Paragraph Style] takes only `to` equal to `name`; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position",
|s, p| edit_style(s, p, Kind::Para),
true,
));
@@ -1018,8 +1018,9 @@ fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let d = &s.doc()?.doc;
let old = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?;
let attrs = attrs_param(d, p, kind, "edit", Some(&old))?.ok_or_else(|| bad(&c, "missing `attrs`"))?;
if name == kind.normal() {
return Err(bad(&c, format!("`{name}` can't be edited this way")));
// The Normal style takes new attributes but keeps its name.
if name == kind.normal() && to != name {
return Err(bad(&c, format!("`{name}` can't be renamed")));
}
if to.is_empty() {
return Err(bad(&c, "give the style a name"));
@@ -1031,9 +1032,13 @@ fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
return ok();
}
s.edit(if kind == Kind::Char { "Character Style Options" } else { "Paragraph Style Options" }, |d, _| {
if let Some(def) = kind.defs_mut(d).iter_mut().find(|def| def.name == name) {
def.name = to.clone();
def.attrs = attrs.clone();
// A Normal style that was never redefined has no definition yet.
match kind.defs_mut(d).iter_mut().find(|def| def.name == name) {
Some(def) => {
def.name = to.clone();
def.attrs = attrs.clone();
}
None => kind.defs_mut(d).push(TextStyleDef { name: to.clone(), attrs: attrs.clone() }),
}
update_users(d, kind, &name, &old, &attrs)?;
if to != name {
+45 -3
View File
@@ -37,6 +37,48 @@ fn character_style_attributes_refuse_a_glyph_choice() {
assert!(err.to_string().contains("glyphAlternate"), "{err}");
}
/// `charStyle.edit` and `paraStyle.edit` give a Normal style that was never redefined its first definition, in one
/// undo step: the type set in it takes the new attributes and keeps its overrides. The Normal style keeps its name,
/// and an edit that changes nothing records no undo step.
#[test]
fn style_options_edit_defines_a_normal_style_in_one_undo_step() {
let (mut s, id) = session_with_text("One\nTwo");
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 7, "size": 30.0})).unwrap();
s.execute("text.setFormat", &json!({"id": id, "start": 4, "end": 4, "leftIndent": 20.0})).unwrap();
for (command, normal, attrs) in [
("charStyle.edit", NORMAL_CHAR, json!({"size": 18.0, "tracking": 40.0})),
("paraStyle.edit", NORMAL_PARA, json!({"left_indent": 12.0, "space_before": 6.0})),
] {
assert!(Kind::Char.defs(&s.doc().unwrap().doc).iter().chain(Kind::Para.defs(&s.doc().unwrap().doc)).all(|d| d.name != normal));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
s.execute(command, &json!({"name": normal, "to": normal, "attrs": attrs})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{command}: one undo step");
let d = &s.doc().unwrap().doc;
let defs = if command == "charStyle.edit" { &d.char_styles } else { &d.para_styles };
assert_eq!(defs.iter().find(|def| def.name == normal).map(|def| json!(def.attrs)), Some(attrs.clone()), "{command}: the definition");
let changed = s.doc().unwrap().doc.clone();
s.execute(command, &json!({"name": normal, "to": normal, "attrs": attrs})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{command}: the same attributes record nothing");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before, "{command}: undo");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, changed, "{command}: redo");
}
let r = runs(&s, id);
assert_eq!(
r.iter().map(|r| (r.style.style_name.as_deref(), r.style.size, r.style.tracking)).collect::<Vec<_>>(),
[(None, 18.0, 40.0), (None, 30.0, 40.0)],
"the type in Normal takes the new size and tracking and keeps its own size"
);
let p = paras(&s, id);
assert_eq!(
p.iter().map(|p| (p.style_name.as_deref(), p.left_indent, p.space_before)).collect::<Vec<_>>(),
[(None, 12.0, 6.0), (None, 20.0, 6.0)],
"the paragraphs in Normal take the new indent and space and keep their own indent"
);
}
fn session_with_text(text: &str) -> (Session, u64) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
@@ -557,7 +599,7 @@ fn character_style_options_edit_validates_names_and_allows_case_changes() {
s.execute("charStyle.new", &json!({"name":"Body","attrs":{"size":24.0}})).unwrap();
s.execute("charStyle.new", &json!({"name":"Other","attrs":{}})).unwrap();
for (name, to, message) in
[(super::NORMAL_CHAR, "New", "can't be edited this way"), ("Body", " ", "give the style a name"), ("Body", "Other", "already exists")]
[(super::NORMAL_CHAR, "New", "can't be renamed"), ("Body", " ", "give the style a name"), ("Body", "Other", "already exists")]
{
let error = s.execute("charStyle.edit", &json!({"name":name,"to":to,"attrs":{}})).unwrap_err().to_string();
assert!(error.contains(message), "{error}");
@@ -1672,13 +1714,13 @@ fn paragraph_style_options_edit_applies_to_users_and_is_one_saved_undo_step() {
assert_eq!(s.doc().unwrap().doc, before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, changed);
// The Normal style, an empty or a taken name and an unknown style are errors.
// Renaming the Normal style, an empty or a taken name and an unknown style are errors.
s.execute("paraStyle.new", &json!({"name": "Other"})).unwrap();
for (params, why) in [
(json!({"name": "Text", "to": " ", "attrs": {}}), "give the style a name"),
(json!({"name": "Text", "to": "Other", "attrs": {}}), "already exists"),
(json!({"name": "Missing", "to": "Missing", "attrs": {}}), "no style `Missing`"),
(json!({"name": NORMAL_PARA, "to": NORMAL_PARA, "attrs": {}}), "can't be edited"),
(json!({"name": NORMAL_PARA, "to": "Basic", "attrs": {}}), "can't be renamed"),
] {
let error = s.execute("paraStyle.edit", &params).unwrap_err().to_string();
assert!(error.contains(why), "{params}: {error}");
+43 -2
View File
@@ -3,6 +3,44 @@ use super::history::{History, HistoryEntry};
use super::interaction::{Interaction, LastTransform, UndoGroup};
use super::{Arc, Document, NodeId, NodeKind, Selection, Value, cmd, file_access};
/// A document's window as the desktop app shows it ([`crate::Session::window_views`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowView {
/// The document point at the centre of the canvas.
pub center: vectorcraft_geom::Point,
/// The zoom is 1 at the window's displayed 100%.
pub zoom: f64,
/// The camera uses this scale at the window's displayed 100%.
pub zoom_baseline: f64,
/// The view's rotation in degrees, clockwise on screen.
pub rotation: f64,
/// The canvas's width and height in document points at a zoom of 1.
pub size: [f64; 2],
/// View › Screen Mode: 0 Normal, 1 Full Screen Mode with Menu Bar, 2 Full Screen Mode, 3
/// Presentation Mode (`view.screenMode`).
pub screen_mode: u8,
}
impl WindowView {
/// The physical camera scale stays within these limits.
pub const ZOOM_RANGE: (f64, f64) = (0.0313, 640.0);
/// `zoom_range` returns this window's allowed displayed zoom ratios.
pub fn zoom_range(&self) -> (f64, f64) {
let (min, max) = Self::ZOOM_RANGE;
(min / self.zoom_baseline, max / self.zoom_baseline)
}
/// The part of the document the canvas shows: the box around its four corners, which a
/// rotated view turns.
pub fn visible(&self) -> vectorcraft_geom::Rect {
let (sin, cos) = self.rotation.to_radians().sin_cos();
let (w, h) = (self.size[0] / self.zoom / 2.0, self.size[1] / self.zoom / 2.0);
let (x, y) = (w * cos.abs() + h * sin.abs(), w * sin.abs() + h * cos.abs());
vectorcraft_geom::Rect::new(self.center.x - x, self.center.y - y, self.center.x + x, self.center.y + y)
}
}
/// Per-document editing state.
#[derive(Clone, Debug)]
pub struct DocState {
@@ -501,7 +539,9 @@ impl DocState {
/// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same
/// document: the objects that leave the selection are taken out of its paints and the objects
/// that join it are read into them, unless that reads more objects than reading the selection
/// again would, or the paints left can't be told apart without reading them again.
/// again would, counting the contents of groups and containers on both sides
/// ([`cmd::SelectionPaints::reads_no_more_than`]), or the paints left can't be told apart
/// without reading them again.
pub(crate) fn record_selection(&mut self, record: Option<SelectionRecord>, guides_locked: bool) {
if !objects_only(&self.selection) {
self.selection_record = None;
@@ -514,7 +554,8 @@ impl DocState {
let (kept, removed) = kept_from(&r.objects, objects);
let gone = left_out(&removed, objects);
let joined = left_out(&objects[kept..], &r.objects);
if gone.len() + joined.len() > objects.len() || !p.remove(&self.doc, &gone) {
let changed = [gone.as_slice(), joined.as_slice()].concat();
if !cmd::SelectionPaints::reads_no_more_than(&self.doc, &changed, objects) || !p.remove(&self.doc, &gone) {
r.paints = None;
} else {
p.add(&self.doc, &joined);
+6 -1
View File
@@ -375,6 +375,11 @@ pub struct Session {
pub(crate) script_high_water: std::collections::HashMap<u64, u64>,
/// While a slice of a script runs in this session.
pub(crate) script_in_run: bool,
/// The desktop app supplies each window by (document uid, runtime window identity) while a
/// script runs. Scripts read them as `Document.views`, and the app applies their zoom, center,
/// and screen mode. This list is empty without windows (headless).
/// View state: not saved, not undoable, and a run that fails keeps what it changed.
pub window_views: Vec<((u64, u64), WindowView)>,
/// Write recovery copies of the unsaved documents before a run, and don't start without them.
pub script_copy_first: bool,
/// While the active tool's actions run: their commands aren't "a command from outside the
@@ -499,7 +504,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
#[cfg(test)]
use command_sets::given_ids;
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit};
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection, WindowView};
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
#[cfg(test)]
use history::history_budget_for;
+218 -11
View File
@@ -21,8 +21,9 @@ use std::collections::VecDeque;
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError};
use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind};
use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep};
use super::{Host, console};
/// The most bytes (UTF-8) of a dialog's message.
@@ -48,6 +49,8 @@ pub enum DialogKind {
Alert,
Confirm,
Prompt,
/// A ScriptUI dialog's `show()` ([`super::scriptui`]).
Window,
}
impl DialogKind {
@@ -57,6 +60,7 @@ impl DialogKind {
Self::Alert => "alert",
Self::Confirm => "confirm",
Self::Prompt => "prompt",
Self::Window => "window",
}
}
}
@@ -85,6 +89,8 @@ pub enum DialogAnswer {
Confirm(bool),
/// OK with the field's text, or Cancel (`None`), for `prompt`.
Prompt(Option<String>),
/// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask.
Window(Vec<UiStep>),
}
impl DialogAnswer {
@@ -93,13 +99,14 @@ impl DialogAnswer {
Self::Ok => DialogKind::Alert,
Self::Confirm(_) => DialogKind::Confirm,
Self::Prompt(_) => DialogKind::Prompt,
Self::Window(_) => DialogKind::Window,
}
}
/// What the function returns.
fn data(&self) -> Data {
match self {
Self::Ok => Data::Undefined,
Self::Ok | Self::Window(_) => Data::Undefined,
Self::Confirm(b) => Data::Bool(*b),
Self::Prompt(Some(t)) => Data::String(t.clone()),
Self::Prompt(None) => Data::Null,
@@ -112,6 +119,7 @@ impl DialogAnswer {
Self::Ok => json!("ok"),
Self::Confirm(b) => json!(b),
Self::Prompt(t) => json!(t),
Self::Window(steps) => json!(steps.len()),
}
}
}
@@ -148,8 +156,9 @@ pub fn cut_to(text: &str, max: usize) -> &str {
}
/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value:
/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter
/// took before dialogs existed, is an empty list.
/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}`
/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an
/// empty list.
pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, String> {
let list = match v {
None => return Ok(Vec::new()),
@@ -166,11 +175,18 @@ pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, Stri
list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect()
}
fn answer(a: &Value) -> Result<DialogAnswer, &'static str> {
let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") };
fn answer(a: &Value) -> Result<DialogAnswer, String> {
let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`".into()) };
if o.len() != 2 || !o.contains_key("value") {
return Err("must have exactly `kind` and `value`");
return Err("must have exactly `kind` and `value`".into());
}
if o.get("kind").and_then(Value::as_str) == Some("window") {
return super::scriptui::parse_steps(&o["value"]).map(DialogAnswer::Window);
}
known_answer(o).map_err(String::from)
}
fn known_answer(o: &Map<String, Value>) -> Result<DialogAnswer, &'static str> {
match (o.get("kind").and_then(Value::as_str), &o["value"]) {
(Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok),
(Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""),
@@ -180,7 +196,7 @@ fn answer(a: &Value) -> Result<DialogAnswer, &'static str> {
(Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))),
(Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"),
(Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"),
_ => Err("must have `kind` alert, confirm or prompt"),
_ => Err("must have `kind` alert, confirm, prompt or window"),
}
}
@@ -199,6 +215,15 @@ pub(crate) struct Dialogs {
record_bytes: Cell<usize>,
count: Cell<u64>,
truncated: Cell<bool>,
/// The ScriptUI dialog whose `show()` is running.
window: RefCell<Option<Showing>>,
/// Where that dialog's record is in `records`, kept from when it opened so a dialog a handler
/// opens is listed after it; `None` when the list had stopped at its limit.
window_slot: Cell<Option<usize>>,
/// That dialog waits for what the person does.
window_waiting: Cell<bool>,
/// The `show()` calls the run has made.
shows: Cell<u64>,
}
impl Dialogs {
@@ -213,6 +238,10 @@ impl Dialogs {
record_bytes: Cell::new(0),
count: Cell::new(0),
truncated: Cell::new(false),
window: RefCell::default(),
window_slot: Cell::new(None),
window_waiting: Cell::new(false),
shows: Cell::new(0),
}
}
@@ -222,7 +251,176 @@ impl Dialogs {
}
pub(crate) fn is_waiting(&self) -> bool {
self.waiting.borrow().is_some()
self.waiting.borrow().is_some() || self.window_waiting.get()
}
/// The ScriptUI dialog that waits for what the person does.
pub(crate) fn waiting_window(&self) -> Option<ScriptUiDialog> {
if !self.window_waiting.get() {
return None;
}
self.window.borrow().as_ref().map(|s| s.dialog.clone())
}
/// The ScriptUI dialog whose `show()` is running, as it last waited, also while a handler runs.
pub(crate) fn showing_window(&self) -> Option<ScriptUiDialog> {
self.window.borrow().as_ref().map(|s| s.dialog.clone())
}
/// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog.
pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> {
if !self.window_waiting.get() {
return Err("no script dialog waits".into());
}
let event = {
let mut window = self.window.borrow_mut();
let Some(showing) = window.as_mut() else { return Err("no script dialog waits".into()) };
let event = scriptui::check_event(&showing.dialog, event)?;
showing.events = showing.events.saturating_add(1);
event
};
self.window_waiting.set(false);
if let Err(e) = realm.answer(event.data()) {
*self.failed.borrow_mut() = Some(e);
}
Ok(())
}
fn cannot_wait(&self) -> Result<(), HostError> {
if self.framed && !self.can_wait.get() {
return Err(HostError::Error(
"show: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code"
.into(),
));
}
Ok(())
}
/// `show()` opens `dialog`. A run with nobody to ask takes its next answer, which must be a
/// `window` answer.
pub(crate) fn window_open(&self, mut dialog: ScriptUiDialog) -> Result<(), HostError> {
self.cannot_wait()?;
self.shows.set(self.shows.get().saturating_add(1));
dialog.shown = self.shows.get();
let mut showing = Showing { dialog, steps: None, events: 0 };
if !self.framed {
let next = self.answers.borrow_mut().pop_front();
match next {
Some(DialogAnswer::Window(steps)) => showing.steps = Some(steps.into()),
Some(a) => {
self.push_record(showing.record(json!("missing")));
return Err(HostError::Abort(format!("show: the next answer in `answers` is for {}, not window", a.kind().id())));
}
None => {
self.push_record(showing.record(json!("missing")));
return Err(HostError::Abort("show: `answers` has no answer left for this dialog".into()));
}
}
}
self.window_slot.set(self.reserve_record());
*self.window.borrow_mut() = Some(showing);
Ok(())
}
/// Keeps a place in the list for the ScriptUI dialog that opens now, counted; its bytes count
/// once the dialog ends. → the place, or `None` when the list stopped at its limit.
fn reserve_record(&self) -> Option<usize> {
self.count.set(self.count.get().saturating_add(1));
let mut records = self.records.borrow_mut();
if self.truncated.get() || records.len() >= MAX_RECORDS {
self.truncated.set(true);
return None;
}
records.push(Value::Null);
Some(records.len() - 1)
}
/// Puts the record of the ScriptUI dialog `showing`, with its `answer`, in the place it took
/// in the list when it opened. When the dialogs a handler opened left no room for it, the list
/// drops the last of them until it fits, or stops before the dialog when it does not fit
/// alone, so it still holds the first dialogs in the order they opened, and is marked as
/// stopped at its limit.
fn end_record(&self, showing: &Showing, answer: Value) {
let Some(i) = self.window_slot.take() else { return };
let size = |r: &Value| serde_json::to_vec(r).map_or(usize::MAX, |b| b.len());
let r = showing.record(answer);
let bytes = size(&r);
let mut records = self.records.borrow_mut();
if i >= records.len() {
return;
}
while self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES && records.len() > i + 1 {
let last = records.pop().map_or(0, |r| size(&r));
self.record_bytes.set(self.record_bytes.get().saturating_sub(last));
self.truncated.set(true);
}
if self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES {
records.truncate(i);
self.truncated.set(true);
return;
}
self.record_bytes.set(self.record_bytes.get() + bytes);
if let Some(slot) = records.get_mut(i) {
*slot = r;
}
}
/// The dialog that is showing waits, as `dialog` now is. A run with nobody to ask takes the
/// next step of its answer.
pub(crate) fn window_wait(&self, mut dialog: ScriptUiDialog) -> Result<Data, HostError> {
self.cannot_wait()?;
let mut window = self.window.borrow_mut();
let Some(showing) = window.as_mut() else { return Err(HostError::Error("show: no dialog is showing".into())) };
dialog.shown = showing.dialog.shown;
showing.dialog = dialog;
let Some(steps) = showing.steps.as_mut() else {
drop(window);
self.window_waiting.set(true);
return Err(HostError::Wait);
};
let failure = match steps.pop_front() {
None => "show: the dialog's answer in `answers` has no step left".to_string(),
Some(step) => match scriptui::step_event(&showing.dialog, &step) {
Ok(event) => {
showing.events = showing.events.saturating_add(1);
return Ok(event.data());
}
Err(e) => format!("show: a step of the dialog's answer in `answers` cannot be taken: {e}"),
},
};
if let Some(showing) = window.take() {
self.end_record(&showing, json!("missing"));
}
Err(HostError::Abort(failure))
}
/// `show()` ends with `result`, or with an error when not `normal`. A run with nobody to ask
/// must have used every step of the dialog's answer.
pub(crate) fn window_end(&self, result: f64, normal: bool) -> Result<(), HostError> {
self.window_waiting.set(false);
let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) };
let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len);
let steps = if left == 1 { "step" } else { "steps" };
let unused = format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use");
if normal && left > 0 {
self.end_record(&showing, json!("missing"));
return Err(HostError::Abort(unused));
}
// A show that a handler's error ended still ends the run when steps are left: the script
// can catch that error, and the run must not finish as if it took every step.
if left > 0 {
let mut failed = self.failed.borrow_mut();
if failed.is_none() {
*failed = Some(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message: unused, line: 0, column: 0, authored: false });
}
}
let answer = match result {
_ if !normal => json!("error"),
r if r.fract() == 0.0 && r.abs() < 9.0e15 => json!(r as i64),
r => json!(r),
};
self.end_record(&showing, answer);
Ok(())
}
/// The error that ended the run when its answer could not reach the script.
@@ -257,10 +455,13 @@ impl Dialogs {
if let Some(d) = self.waiting.borrow_mut().take() {
self.record(&d, json!("stop"));
}
self.window_waiting.set(false);
if let Some(showing) = self.window.borrow_mut().take() {
self.end_record(&showing, json!("stop"));
}
}
fn record(&self, d: &ScriptDialog, answer: Value) {
self.count.set(self.count.get().saturating_add(1));
let mut r = Map::new();
r.insert("kind".into(), json!(d.kind.id()));
r.insert("message".into(), json!(d.message));
@@ -269,9 +470,14 @@ impl Dialogs {
DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)),
DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)),
DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)),
DialogKind::Window => None,
};
r.insert("answer".into(), answer);
let r = Value::Object(r);
self.push_record(Value::Object(r));
}
fn push_record(&self, r: Value) {
self.count.set(self.count.get().saturating_add(1));
let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len());
let mut records = self.records.borrow_mut();
if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES {
@@ -325,6 +531,7 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) };
(text(args, 2), false, false, preset)
}
DialogKind::Window => return Err(HostError::Error("a ScriptUI dialog opens with show()".into())),
};
if message.len() > MAX_MESSAGE_BYTES {
return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB")));
+226 -4
View File
@@ -2,8 +2,10 @@
//! them, as the help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Application/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Documents/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> describe them.
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Views/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/View/> describe them.
//!
//! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the
//! document's [`crate::DocState::uid`] and, for art and layers, the object's id and the document's
@@ -46,6 +48,15 @@
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
//! in the object.
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
//! in view-number order, and none without one. View objects keep their window's identity when
//! windows are renumbered. The screen mode is the app's:
//! setting it on one view sets it on every view. Its `zoom` is 1 at the window's displayed 100%;
//! the physical camera scale ranges from 0.0313 to 640, and the allowed zoom ratios account for
//! the window's display density with Display Print Size at 100% Zoom enabled. `screenMode` reads
//! Presentation Mode as `ScreenMode.FULLSCREEN`. Changing a view runs no command, is not
//! undoable and stays when the run fails.
//! A center outside the canvas after coordinate conversion throws a `RangeError`.
//! - Members the help pages list that are not here yet throw an error that says so, and `reflect`
//! leaves them out.
//! - Assigning `hidden`, `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or
@@ -78,7 +89,7 @@ use vectorcraft_js::{
};
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
use crate::{DocState, Document, NodeId, NodeKind, Session};
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
mod tags;
mod variables;
@@ -104,6 +115,8 @@ pub const STALE_ITEM: &str = "Stale page item";
pub const STALE_DOCUMENT: &str = "Stale document";
/// The error of `index` and `getByName` when nothing matches.
pub const NOT_FOUND: &str = "Not found";
/// The error for a view whose document no longer has a window, or that came from an earlier run.
pub const STALE_VIEW: &str = "Stale view";
/// The most objects one read of a selection gives, and the most a selection assignment takes.
pub const MAX_LISTED: usize = 10_000;
/// The longest name an object or a path query may have, in bytes.
@@ -837,6 +850,13 @@ fn path_key(p: &str) -> String {
if windows { p.to_lowercase() } else { p }
}
/// `app.redraw()`: returns without changing anything. The app draws a frame between the run's
/// slices on its own, and it draws the documents as they were before the run until the run ends,
/// so there is nothing for the call to draw. It adds no undo step.
fn app_redraw(_: &Host, _: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is
/// compared as text with the documents' files and is not resolved; a document whose file the
/// automation read roots do not allow does not count, and that check can look the file up on disk.
@@ -1483,6 +1503,179 @@ fn doc_selection(h: &Host, a: &[Data]) -> Answer {
selection_of(h, doc.uid)
}
fn doc_views(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
Ok(host_ref("Views", &[float(h.run), float(doc.uid)]))
}
// ---- Views and View ----
fn views_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "Views")
}
fn window_of(h: &Host, doc: Doc, id: u64) -> Option<WindowView> {
h.session.borrow().window_views.iter().find(|((uid, window), _)| *uid == doc.uid && *window == id).map(|(_, v)| *v)
}
fn views_length(h: &Host, a: &[Data]) -> Answer {
let doc = views_doc(h, a)?;
Ok(num(h.session.borrow().window_views.iter().filter(|((uid, _), _)| *uid == doc.uid).count() as f64))
}
fn views_typename(h: &Host, a: &[Data]) -> Answer {
views_doc(h, a)?;
Ok(text("Views"))
}
fn views_parent(h: &Host, a: &[Data]) -> Answer {
let doc = views_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
}
fn views_to_string(h: &Host, a: &[Data]) -> Answer {
views_doc(h, a)?;
Ok(text("[Views]"))
}
fn views_at(h: &Host, a: &[Data]) -> Answer {
let doc = views_doc(h, a)?;
let index = match arg(a, 1) {
Data::Number(n) => whole(*n).and_then(|n| usize::try_from(n).ok()),
_ => None,
};
let Some(index) = index else { return Ok(Data::Undefined) };
let key = h.session.borrow().window_views.iter().filter(|((uid, _), _)| *uid == doc.uid).nth(index).map(|(key, _)| *key);
Ok(key.map_or(Data::Undefined, |(uid, id)| host_ref("View", &[float(h.run), float(uid), float(id)])))
}
/// `views.index(key)`: the view at index `key`. A view has no name, so a name finds nothing.
fn views_index(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => {
views_doc(h, a)?;
Err(HostError::Error(NOT_FOUND.into()))
}
Data::Number(_) => match views_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
_ => Err(HostError::Type("give a name or an index".into())),
}
}
/// The document of a `View` and its window, which must still be shown.
fn this_view(h: &Host, a: &[Data]) -> std::result::Result<(Doc, u64, WindowView), HostError> {
let Some(handle) = handle_of(arg(a, 0), "View") else { return Err(HostError::Type("this is not a View".into())) };
let &[run, uid, id] = handle.as_slice() else { return Err(HostError::Type("this is not a View".into())) };
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
let id = whole(id).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?;
let v = window_of(h, doc, id).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?;
Ok((doc, id, v))
}
/// Reads the view with `f`, given the document's script coordinates.
fn read_view(h: &Host, a: &[Data], f: impl FnOnce(&Frame, Coords, &WindowView) -> Data) -> Answer {
let (doc, _, v) = this_view(h, a)?;
with_doc(h, doc, |_, st| Ok(f(&frame(st)?, h.dom.coords.get(), &v)))
}
/// Changes the window of `doc` with `f`. No command runs: the change is not undoable, does not
/// join the run's undo step and stays when the run fails.
fn set_window(h: &Host, doc: Doc, id: u64, f: impl FnOnce(&mut WindowView)) -> Answer {
let mut s = h.session.borrow_mut();
let v = s
.window_views
.iter_mut()
.find(|((uid, window), _)| *uid == doc.uid && *window == id)
.map(|(_, v)| v)
.ok_or_else(|| HostError::Error(STALE_VIEW.into()))?;
f(v);
Ok(Data::Undefined)
}
fn view_typename(h: &Host, a: &[Data]) -> Answer {
this_view(h, a)?;
Ok(text("View"))
}
fn view_parent(h: &Host, a: &[Data]) -> Answer {
let (doc, _, _) = this_view(h, a)?;
Ok(doc_ref(h, doc.uid))
}
fn view_to_string(h: &Host, a: &[Data]) -> Answer {
this_view(h, a)?;
Ok(text("[View]"))
}
/// `bounds`: `[left, top, right, bottom]` of the part of the document the canvas shows.
fn view_bounds(h: &Host, a: &[Data]) -> Answer {
read_view(h, a, |f, c, v| f.bounds(c, v.visible()))
}
fn view_center(h: &Host, a: &[Data]) -> Answer {
read_view(h, a, |f, c, v| pair(f.to_script(c, v.center)))
}
fn view_set_center(h: &Host, a: &[Data]) -> Answer {
let (doc, id, _) = this_view(h, a)?;
let p = point(arg(a, 1), "centerPoint")?;
let to = with_doc(h, doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), p)))?;
if to.x.abs() > crate::MAX_COORD || to.y.abs() > crate::MAX_COORD {
return Err(HostError::Range("centerPoint is outside the canvas".into()));
}
set_window(h, doc, id, |v| v.center = to)
}
fn view_zoom(h: &Host, a: &[Data]) -> Answer {
let (_, _, v) = this_view(h, a)?;
Ok(num(v.zoom))
}
fn view_set_zoom(h: &Host, a: &[Data]) -> Answer {
let (doc, id, v) = this_view(h, a)?;
let z = number(arg(a, 1), "zoom")?;
let (min, max) = v.zoom_range();
if !(min..=max).contains(&z) {
return Err(HostError::Range(format!("zoom must be from {min} to {max}")));
}
set_window(h, doc, id, |v| v.zoom = z)
}
/// The `ScreenMode` value of each of the app's screen modes: Presentation Mode reads as
/// `FULLSCREEN`.
fn screen_mode_name(mode: u8) -> &'static str {
match mode {
0 => "ScreenMode.MULTIWINDOW",
1 => "ScreenMode.DESKTOP",
_ => "ScreenMode.FULLSCREEN",
}
}
fn view_screen_mode(h: &Host, a: &[Data]) -> Answer {
let (_, _, v) = this_view(h, a)?;
Ok(text(screen_mode_name(v.screen_mode)))
}
fn view_set_screen_mode(h: &Host, a: &[Data]) -> Answer {
let (_, _, v) = this_view(h, a)?;
let mode = match arg(a, 1) {
Data::String(s) if s == "ScreenMode.MULTIWINDOW" => 0,
Data::String(s) if s == "ScreenMode.DESKTOP" => 1,
Data::String(s) if s == "ScreenMode.FULLSCREEN" => 2,
_ => return Err(HostError::Type("give a ScreenMode value".into())),
};
if screen_mode_name(v.screen_mode) == screen_mode_name(mode) {
return Ok(Data::Undefined);
}
// The screen mode is the app's, so every view shows the new one.
for (_, v) in &mut h.session.borrow_mut().window_views {
v.screen_mode = mode;
}
Ok(Data::Undefined)
}
/// The selection of the document `uid`: a new list of the selected objects, topmost first as
/// `pageItems` lists them, empty when nothing is selected.
fn selection_of(h: &Host, uid: u64) -> Answer {
@@ -2381,6 +2574,7 @@ const ENUMS: &[(&str, &[&str])] = &[
("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]),
("DocumentColorSpace", &["CMYK", "RGB"]),
("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]),
("ScreenMode", &["DESKTOP", "FULLSCREEN", "MULTIWINDOW"]),
("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]),
("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]),
("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]),
@@ -2432,6 +2626,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
("selection", property(l, app_selection, app_set_selection), typed("*")),
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
("redraw", method(l, app_redraw), returns("undefined", &[])),
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
("toString", class_text("Application"), returns("string", &[])),
]);
@@ -2504,16 +2699,43 @@ fn classes(link: &Link) -> Vec<HostClass> {
),
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
("toString", method(l, doc_to_string), returns("string", &[])),
]);
document.extend(
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"]
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "activeLayer", "saveAs", "close"]
.into_iter()
.map(|m| later(l, "Document", m)),
);
document.extend(variables::document_members(l));
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
classes.push(class("Document", None, document, None));
classes.push(class(
"Views",
None,
named(vec![
("typename", get(l, views_typename), typed("string")),
("length", get(l, views_length), typed("number")),
("parent", get(l, views_parent), typed("Document")),
("index", method(l, views_index), returns("View", &[("itemKey", "*")])),
("toString", method(l, views_to_string), returns("string", &[])),
]),
Some(function(l, views_at)),
));
classes.push(class(
"View",
None,
named(vec![
("typename", get(l, view_typename), typed("string")),
("parent", get(l, view_parent), typed("Views")),
("bounds", get(l, view_bounds), typed("Array")),
("centerPoint", property(l, view_center, view_set_center), typed("Array")),
("zoom", property(l, view_zoom, view_set_zoom), typed("number")),
("screenMode", property(l, view_screen_mode, view_set_screen_mode), typed("ScreenMode")),
("toString", method(l, view_to_string), returns("string", &[])),
]),
None,
));
classes.push(class(
"PageItems",
None,
+37 -2
View File
@@ -53,8 +53,10 @@ pub mod dialogs;
pub mod dollar;
pub mod dom;
pub mod include;
pub mod scriptui;
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
@@ -135,7 +137,7 @@ impl Written {
/// The version `vc.api.version` gives.
pub const API_VERSION: &str = "1.0";
/// The features `vc.api.has` knows.
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"];
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar", "scriptui"];
/// The most commands a run's report lists in `slowestCommands`.
pub const SLOWEST_COMMANDS: usize = 5;
@@ -1642,7 +1644,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
/// `e`'s message, with what to do about a failure that comes from a script written for another
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
fn explained(e: &RunError) -> String {
const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"];
const HOST_OBJECTS: &[&str] = &["BridgeTalk"];
let message = &e.message;
let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next());
let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f));
@@ -1908,6 +1910,32 @@ impl Session {
with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false)
}
/// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run
/// asked to stop no longer waits: the next [`Session::script_pump`] ends it.
pub fn script_window(&self) -> Option<ScriptUiDialog> {
if self.script_stop.is_set() {
return None;
}
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten()
}
/// The ScriptUI dialog whose `show()` the running script is in, whether it waits at it or runs
/// one of its handlers. A run asked to stop is in none.
pub fn script_window_showing(&self) -> Option<ScriptUiDialog> {
if self.script_stop.is_set() {
return None;
}
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.showing_window())).flatten()
}
/// Gives the ScriptUI dialog the running script waits at `event`; the next
/// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still
/// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]).
pub fn script_window_answer(&mut self, event: UiEvent) -> std::result::Result<(), String> {
let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return Err("no script dialog waits".into()) };
with_job(k, |j| j.host.dialogs.window_answer(&mut j.realm, event)).unwrap_or_else(|| Err("no script dialog waits".into()))
}
/// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects'
/// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no
/// longer waits.
@@ -2200,6 +2228,7 @@ impl Session {
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
.and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) })
.and_then(|()| if fresh { scriptui::install(&mut realm, &link) } else { Ok(()) })
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
.and_then(|()| {
@@ -2288,6 +2317,12 @@ impl Session {
}
job.host.calls_this_slice.set(0);
let outcome = run_slice(self, &mut job);
// A failure a dialog recorded in the slice (steps a show left unused) ends the run, even
// when the script went on.
let outcome = match (outcome, job.host.dialogs.take_failure()) {
(Ok(Ok(_)), Some(e)) => Ok(Err(e)),
(outcome, _) => outcome,
};
match outcome {
Err(panic) => {
let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false };
+736
View File
@@ -0,0 +1,736 @@
//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run
//! gives when it shows one, checked and laid out here before the app draws it, and the events the
//! person or `script.run`'s `answers` give back.
//!
//! A description lists the dialog first and each control after the container that holds it. It is
//! refused with an error thrown at `show()` when a control's container comes after it or is not a
//! group or panel, when it holds more than [`MAX_CONTROLS`] controls, nests deeper than
//! [`MAX_DEPTH`], has more than [`MAX_ITEMS`] list items or a text longer than [`MAX_TEXT_BYTES`],
//! names an orientation or an alignment that does not exist, or gives a slider a minimum above its
//! maximum. Sizes, places, spacing and margins are clamped to [`MAX_EXTENT`] pixels, and a slider's
//! or progress bar's value to its range.
//!
//! The layout follows each container's `orientation` (row, column or stack), `alignChildren`,
//! `spacing` and `margins`, a control's `alignment`, `preferredSize` (or `size`), `minimumSize`,
//! `maximumSize` and `bounds` (left, top, right and bottom in its container); a width or height of
//! 0 or less in a size leaves that side to the layout. A control's size comes from its text, items and kind, by
//! VectorCraft's own estimates of a 7-pixel character and a 16-pixel line. The layout is worked out
//! with loops over the list, from the last control to the first for sizes and from the first to the
//! last for places, so a description's nesting takes no native stack.
//!
//! A run with nobody to ask takes one answer from `answers` for each `show()`: `{kind: "window",
//! value: [step, ...]}`, where a step is `{control, event: "click"}`, `{control, event: "change",
//! value}` or `{event: "close"}`. `control` is a control's `name`, or else its text; `value` is an
//! edit field's text, a slider's number, or a list's item index or `null`. Each time the dialog
//! waits it takes the next step; a dialog that waits with no step left, a step for a control the
//! dialog does not hold or cannot take it, and steps left when the dialog closes end the run.
//!
//! The limits here are VectorCraft's own: [`MAX_EXTENT`], and the js crate's [`MAX_CONTROLS`],
//! [`MAX_DEPTH`], [`MAX_ITEMS`] and [`MAX_TEXT_BYTES`].
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError};
pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES};
use super::Host;
/// The largest size or place, in pixels, of a dialog or a control in it.
pub const MAX_EXTENT: f32 = 8192.0;
/// A character's width and a line's height in VectorCraft's size estimates, in pixels.
const CHAR: f32 = 7.0;
const LINE: f32 = 16.0;
/// A dialog's element.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UiKind {
Dialog,
Group,
Panel,
StaticText,
EditText,
Button,
CheckBox,
RadioButton,
DropDownList,
ListBox,
Slider,
ProgressBar,
}
impl UiKind {
fn parse(s: &str) -> Option<Self> {
Some(match s {
"dialog" => Self::Dialog,
"group" => Self::Group,
"panel" => Self::Panel,
"statictext" => Self::StaticText,
"edittext" => Self::EditText,
"button" => Self::Button,
"checkbox" => Self::CheckBox,
"radiobutton" => Self::RadioButton,
"dropdownlist" => Self::DropDownList,
"listbox" => Self::ListBox,
"slider" => Self::Slider,
"progressbar" => Self::ProgressBar,
_ => return None,
})
}
/// Does it hold controls?
pub fn container(self) -> bool {
matches!(self, Self::Dialog | Self::Group | Self::Panel)
}
/// Does a click reach it?
pub fn clicks(self) -> bool {
matches!(self, Self::Button | Self::CheckBox | Self::RadioButton)
}
}
/// How a container places its controls.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Orientation {
Row,
Column,
Stack,
}
/// Where a control goes across its container: left or top, right or bottom, the middle, or the
/// whole width or height.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Align {
Start,
End,
Center,
Fill,
}
/// A control's place and size in the dialog, from its top left corner.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct UiRect {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
}
/// One element of a [`ScriptUiDialog`].
#[derive(Clone, Debug, PartialEq)]
pub struct UiNode {
pub kind: UiKind,
/// A number no other element of the run has, which stays with the element while the script
/// adds and removes controls; its index in the description when the description gives none.
pub id: u64,
/// The index of its container; the dialog's own is 0.
pub parent: usize,
pub name: String,
pub text: String,
/// It and every container around it are enabled.
pub enabled: bool,
/// It and every container around it are visible.
pub visible: bool,
/// A check box's or radio button's value.
pub checked: bool,
/// A slider's or progress bar's value, within `min` to `max`.
pub value: f64,
pub min: f64,
pub max: f64,
pub items: Vec<String>,
/// How many times the script replaced a list's items (removed or added some), which tells a
/// list from one that holds the same texts again.
pub items_revision: u64,
pub selection: Option<usize>,
pub multiline: bool,
pub readonly: bool,
pub rect: UiRect,
orientation: Orientation,
align_children: (Option<Align>, Option<Align>),
alignment: (Option<Align>, Option<Align>),
spacing: f32,
margins: [f32; 4],
size: [Option<f32>; 2],
min_size: [Option<f32>; 2],
max_size: [Option<f32>; 2],
bounds: Option<UiRect>,
/// The characters an edit field or static text reserves room for in its width.
characters: Option<f32>,
}
impl UiNode {
/// How much of a progress bar is done, from 0 to 1.
pub fn fraction(&self) -> f32 {
if self.max <= self.min || self.value <= self.min {
return 0.0;
}
if self.value >= self.max {
return 1.0;
}
let span = self.max - self.min;
// A range wider than the largest number is measured at half scale.
let part =
if span.is_finite() { (self.value - self.min) / span } else { (self.value / 2.0 - self.min / 2.0) / (self.max / 2.0 - self.min / 2.0) };
part.clamp(0.0, 1.0) as f32
}
}
/// A dialog a run shows, checked and laid out.
#[derive(Clone, Debug, PartialEq)]
pub struct ScriptUiDialog {
/// The dialog first, then each control after the container that holds it.
pub nodes: Vec<UiNode>,
/// The button Enter clicks and the one Escape clicks.
pub default_element: Option<usize>,
pub cancel_element: Option<usize>,
/// Which `show()` of the run this is, counted from 1; 0 before it shows.
pub shown: u64,
}
impl ScriptUiDialog {
/// The dialog's title.
pub fn title(&self) -> &str {
self.nodes.first().map_or("", |n| n.text.as_str())
}
/// The size of the dialog's content.
pub fn size(&self) -> (f32, f32) {
self.nodes.first().map_or((0.0, 0.0), |n| (n.rect.w, n.rect.h))
}
/// The first control whose name is `control`, or else the first control without a name
/// whose text is `control`.
pub fn find(&self, control: &str) -> Option<usize> {
let by = |name: bool| {
let hit = |n: &UiNode| if name { !control.is_empty() && n.name == control } else { n.name.is_empty() && n.text == control };
self.nodes.iter().enumerate().skip(1).find(|(_, n)| hit(n)).map(|(i, _)| i)
};
by(true).or_else(|| by(false))
}
}
/// A value a control takes in a change.
#[derive(Clone, Debug, PartialEq)]
pub enum UiValue {
Text(String),
Number(f64),
Index(Option<usize>),
}
/// What the person did with a dialog.
#[derive(Clone, Debug, PartialEq)]
pub enum UiEvent {
/// A click on a button, check box or radio button.
Click(usize),
/// A new value for an edit field, a slider or a list.
Change(usize, UiValue),
/// The dialog's close box.
Close,
}
impl UiEvent {
/// The event as `show()` takes it.
pub(crate) fn data(&self) -> Data {
let event = |e: &str| ("event".to_string(), Data::String(e.into()));
let id = |i: usize| ("id".to_string(), Data::Number(i as f64));
match self {
Self::Click(i) => Data::Object(vec![event("click"), id(*i)]),
Self::Change(i, v) => {
let value = match v {
UiValue::Text(t) => Data::String(t.clone()),
UiValue::Number(n) => Data::Number(*n),
UiValue::Index(Some(k)) => Data::Number(*k as f64),
UiValue::Index(None) => Data::Null,
};
Data::Object(vec![event("change"), id(*i), ("value".into(), value)])
}
Self::Close => Data::Object(vec![event("close")]),
}
}
}
/// Checks `event` against `dialog`. → the event as the dialog takes it: a slider's value clamped
/// to its range.
pub fn check_event(dialog: &ScriptUiDialog, event: UiEvent) -> Result<UiEvent, String> {
let id = match &event {
UiEvent::Close => return Ok(event),
UiEvent::Click(i) | UiEvent::Change(i, _) => *i,
};
let Some(n) = dialog.nodes.get(id).filter(|_| id > 0) else { return Err(format!("the dialog has no control {id}")) };
if !n.enabled || !n.visible {
return Err(format!("the control {} is disabled or hidden", label(n)));
}
match event {
UiEvent::Click(_) if n.kind.clicks() => Ok(event),
UiEvent::Click(_) => Err(format!("the control {} cannot be clicked", label(n))),
UiEvent::Change(_, UiValue::Text(t)) if n.kind == UiKind::EditText && !n.readonly => {
if t.len() > MAX_TEXT_BYTES {
return Err("the text is longer than 16 KiB".into());
}
Ok(UiEvent::Change(id, UiValue::Text(t)))
}
UiEvent::Change(_, UiValue::Number(v)) if n.kind == UiKind::Slider && v.is_finite() => {
Ok(UiEvent::Change(id, UiValue::Number(v.clamp(n.min, n.max))))
}
UiEvent::Change(_, UiValue::Index(k)) if matches!(n.kind, UiKind::DropDownList | UiKind::ListBox) => match k {
Some(k) if k >= n.items.len() => Err(format!("the list {} has no item {k}", label(n))),
k => Ok(UiEvent::Change(id, UiValue::Index(k))),
},
UiEvent::Change(..) => Err(format!("the control {} cannot take that change", label(n))),
UiEvent::Close => Ok(UiEvent::Close),
}
}
fn label(n: &UiNode) -> String {
let shown = if n.name.is_empty() { &n.text } else { &n.name };
super::dialogs::cut_to(shown, 64).to_string()
}
/// A step of a `window` answer in `script.run`'s `answers`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UiStep {
/// The control's name or text; none for a close.
pub control: Option<String>,
pub event: String,
pub value: Option<Value>,
}
/// The steps of a `window` answer: `[{control, event: "click"} | {control, event: "change", value}
/// | {event: "close"}]`, where `control` is a string of at most 16 KiB and `value` a string, a
/// number or null.
pub(crate) fn parse_steps(v: &Value) -> Result<Vec<UiStep>, String> {
let Some(list) = v.as_array() else { return Err("is a window's answer, whose `value` must be a list of steps".into()) };
list.iter().enumerate().map(|(i, s)| step(s).ok_or_else(|| format!("has a step {i} that is not a valid click, change or close"))).collect()
}
fn step(s: &Value) -> Option<UiStep> {
let o = s.as_object()?;
if o.keys().any(|k| !matches!(k.as_str(), "control" | "event" | "value")) {
return None;
}
let control = match o.get("control") {
None => None,
Some(Value::String(c)) if c.len() <= MAX_TEXT_BYTES => Some(c.clone()),
Some(_) => return None,
};
let value = o.get("value").cloned();
let event = o.get("event").and_then(Value::as_str)?;
let fits = match event {
"close" => control.is_none() && value.is_none(),
"click" => control.is_some() && value.is_none(),
"change" => control.is_some() && matches!(value, Some(Value::String(_) | Value::Number(_) | Value::Null)),
_ => false,
};
fits.then(|| UiStep { control, event: event.to_string(), value })
}
/// The event `step` is for `dialog`.
pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result<UiEvent, String> {
let Some(control) = &step.control else { return Ok(UiEvent::Close) };
let Some(id) = dialog.find(control) else { return Err(format!("the dialog has no control named {}", super::dialogs::cut_to(control, 64))) };
let event = match (step.event.as_str(), &step.value) {
("click", _) => UiEvent::Click(id),
(_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())),
(_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match list_index(n) {
Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))),
None => return Err("a list's `value` must be an item index or null".into()),
},
(_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))),
(_, Some(Value::Null)) => UiEvent::Change(id, UiValue::Index(None)),
_ => return Err("a change's `value` must be a string, a number or null".into()),
};
check_event(dialog, event)
}
/// A list's item index written as a JSON number: a whole number of 0 or more, as an integer or as
/// a float such as `1.0`; an index past the end stays past it. `None` for a fraction or a negative
/// number.
pub fn list_index(n: &serde_json::Number) -> Option<usize> {
if let Some(k) = n.as_u64() {
return Some(usize::try_from(k).unwrap_or(usize::MAX));
}
let f = n.as_f64()?;
// `as` saturates a whole number too large for usize at usize::MAX.
(f >= 0.0 && f.fract() == 0.0).then_some(f as usize)
}
fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data {
fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v)
}
fn bad(what: &str) -> HostError {
HostError::Type(format!("show: the dialog's description {what}"))
}
/// A finite number.
fn number(d: &Data) -> Option<f64> {
match d {
Data::Number(n) if n.is_finite() => Some(*n),
_ => None,
}
}
fn text(d: &Data, what: &str) -> Result<String, HostError> {
match d {
Data::String(s) if s.len() <= MAX_TEXT_BYTES => Ok(s.clone()),
Data::String(_) => Err(HostError::Range(format!("show: {what} is longer than 16 KiB"))),
_ => Err(bad(&format!("has no {what}"))),
}
}
fn extent(n: f64) -> f32 {
(n as f32).clamp(-MAX_EXTENT, MAX_EXTENT)
}
fn align_name(s: &str, horizontal: Option<bool>) -> Result<(Option<Align>, Option<Align>), HostError> {
let a = match (s, horizontal) {
("left", Some(true) | None) => (Some(Align::Start), None),
("right", Some(true) | None) => (Some(Align::End), None),
("top", Some(false) | None) => (None, Some(Align::Start)),
("bottom", Some(false) | None) => (None, Some(Align::End)),
("center", _) => (Some(Align::Center), Some(Align::Center)),
("fill", _) => (Some(Align::Fill), Some(Align::Fill)),
_ => return Err(HostError::Error(format!("show: there is no alignment {}", super::dialogs::cut_to(s, 64)))),
};
Ok(match horizontal {
Some(true) => (a.0, None),
Some(false) => (None, a.1),
None => a,
})
}
fn alignment(d: &Data) -> Result<(Option<Align>, Option<Align>), HostError> {
match d {
Data::Null | Data::Undefined => Ok((None, None)),
Data::String(s) => align_name(s, None),
Data::Array(a) if a.len() == 2 => {
let part = |d: &Data, h: bool| match d {
Data::String(s) => align_name(s, Some(h)),
_ => Err(bad("has an alignment that is not a name")),
};
Ok((part(&a[0], true)?.0, part(&a[1], false)?.1))
}
_ => Err(bad("has an alignment that is not a name or a pair of names")),
}
}
fn numbers<const N: usize>(d: &Data) -> Result<Option<[f64; N]>, HostError> {
match d {
Data::Null | Data::Undefined => Ok(None),
Data::Array(a) if a.len() == N => {
let mut out = [0.0; N];
for (o, v) in out.iter_mut().zip(a) {
*o = number(v).ok_or_else(|| bad("has a size that is not a number"))?;
}
Ok(Some(out))
}
_ => Err(bad("has a size with the wrong count of numbers")),
}
}
/// Reads, checks and lays out a dialog's description.
pub fn parse(d: &Data) -> Result<ScriptUiDialog, HostError> {
let Data::Object(top) = d else { return Err(bad("is not an object")) };
let Data::Array(list) = field(top, "nodes") else { return Err(bad("has no list of controls")) };
if list.is_empty() {
return Err(bad("has no dialog"));
}
if list.len() > MAX_CONTROLS + 1 {
return Err(HostError::Range(format!("show: a dialog can hold at most {MAX_CONTROLS} controls")));
}
let mut nodes: Vec<UiNode> = Vec::with_capacity(list.len());
let mut depth: Vec<usize> = Vec::with_capacity(list.len());
let mut items_total = 0usize;
for (i, n) in list.iter().enumerate() {
let Data::Object(f) = n else { return Err(bad("has a control that is not an object")) };
let kind = match field(f, "kind") {
Data::String(k) => UiKind::parse(k).ok_or_else(|| bad("has a control of a kind that does not exist"))?,
_ => return Err(bad("has a control without a kind")),
};
let parent = number(field(f, "parent")).ok_or_else(|| bad("has a control without its container"))?;
let parent = if i == 0 {
if kind != UiKind::Dialog || parent != -1.0 {
return Err(bad("does not start with the dialog"));
}
0
} else {
let p = parent as usize;
if parent < 0.0 || parent.fract() != 0.0 || p >= i || kind == UiKind::Dialog {
return Err(bad("has a control before its container"));
}
if !nodes[p].kind.container() {
return Err(bad("has a control inside a control that holds none"));
}
p
};
let level = if i == 0 { 0 } else { depth[parent] + 1 };
if level > MAX_DEPTH {
return Err(HostError::Range(format!("show: controls can be nested at most {MAX_DEPTH} deep")));
}
depth.push(level);
let flag = |name: &str| matches!(field(f, name), Data::Bool(true));
let (parent_enabled, parent_visible) = if i == 0 { (true, true) } else { (nodes[parent].enabled, nodes[parent].visible) };
let items = match field(f, "items") {
Data::Array(a) => a.iter().map(|t| text(t, "a list item's text")).collect::<Result<Vec<_>, _>>()?,
_ => Vec::new(),
};
items_total = items_total.saturating_add(items.len());
if items_total > MAX_ITEMS {
return Err(HostError::Range(format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all")));
}
let selection = number(field(f, "selection")).map(|k| k as usize).filter(|k| *k < items.len());
let (min, max) = (number(field(f, "minvalue")).unwrap_or(0.0), number(field(f, "maxvalue")).unwrap_or(100.0));
if min > max {
return Err(HostError::Range("show: a slider's or progress bar's minvalue is larger than its maxvalue".into()));
}
let orientation = match field(f, "orientation") {
Data::String(s) if s == "row" => Orientation::Row,
Data::String(s) if s == "column" => Orientation::Column,
Data::String(s) if s == "stack" => Orientation::Stack,
Data::Undefined => Orientation::Column,
_ => return Err(HostError::Error("show: a container's orientation must be row, column or stack".into())),
};
let bounds = numbers::<4>(field(f, "bounds"))?.map(|[l, t, r, b]| {
let (l, t) = (extent(l), extent(t));
UiRect { x: l, y: t, w: (extent(r) - l).clamp(0.0, MAX_EXTENT), h: (extent(b) - t).clamp(0.0, MAX_EXTENT) }
});
// A width or height of 0 or less leaves that side to the layout.
let sides = |name: &str| -> Result<[Option<f32>; 2], HostError> {
Ok(numbers::<2>(field(f, name))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))]))
};
let (size, min_size, max_size) = (sides("size")?, sides("min")?, sides("max")?);
let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0)));
nodes.push(UiNode {
kind,
id: number(field(f, "id")).filter(|n| *n >= 0.0 && n.fract() == 0.0 && *n < 9.0e15).map_or(i as u64, |n| n as u64),
parent,
name: text(field(f, "name"), "a control's name")?,
text: text(field(f, "text"), "a control's text")?,
enabled: flag("enabled") && parent_enabled,
visible: flag("visible") && parent_visible,
checked: flag("value"),
value: number(field(f, "value")).unwrap_or(0.0).clamp(min, max),
min,
max,
items,
items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64),
selection,
multiline: flag("multiline"),
readonly: flag("readonly"),
rect: UiRect::default(),
orientation,
align_children: alignment(field(f, "alignChildren"))?,
alignment: alignment(field(f, "alignment"))?,
spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)),
margins,
size,
min_size,
max_size,
bounds,
// At most as many characters as the longest text holds.
characters: number(field(f, "characters")).filter(|c| *c > 0.0).map(|c| (c as f32).min(MAX_TEXT_BYTES as f32)),
});
}
let target = |name: &str| number(field(top, name)).map(|k| k as usize).filter(|k| nodes.get(*k).is_some_and(|n| n.kind == UiKind::Button));
let (default_element, cancel_element) = (target("defaultElement"), target("cancelElement"));
let mut dialog = ScriptUiDialog { nodes, default_element, cancel_element, shown: 0 };
layout(&mut dialog);
Ok(dialog)
}
/// A control's own size, by VectorCraft's estimates.
fn own_size(n: &UiNode) -> [f32; 2] {
let chars = |s: &str| s.chars().count() as f32;
let widest = |lines: &mut dyn Iterator<Item = &str>| lines.map(chars).fold(0.0, f32::max);
let lines = |s: &str| s.lines().count().max(1) as f32;
let longest_item = n.items.iter().map(|t| chars(t)).fold(0.0, f32::max);
// `characters` reserves room for that many characters, however long the text is now.
let reserved = n.characters.unwrap_or(0.0);
match n.kind {
UiKind::StaticText => [widest(&mut n.text.lines()).max(reserved) * CHAR + 4.0, lines(&n.text) * LINE + 4.0],
UiKind::Button => [(chars(&n.text) * CHAR + 24.0).max(80.0), 24.0],
UiKind::CheckBox | UiKind::RadioButton => [chars(&n.text) * CHAR + 24.0, 20.0],
UiKind::EditText if n.multiline => {
[(widest(&mut n.text.lines()).max(reserved) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0]
}
UiKind::EditText => [(chars(&n.text).max(reserved) * CHAR + 12.0).max(80.0), 24.0],
UiKind::DropDownList => [(longest_item * CHAR + 40.0).max(100.0), 24.0],
UiKind::ListBox => [(longest_item * CHAR + 24.0).max(120.0), (n.items.len() as f32).clamp(3.0, 10.0) * 18.0 + 6.0],
UiKind::Slider => [160.0, 20.0],
UiKind::ProgressBar => [160.0, 12.0],
UiKind::Dialog | UiKind::Group | UiKind::Panel => [0.0, 0.0],
}
}
/// Lays the dialog out: each control's size from the last to the first, then each place from the
/// first to the last.
fn layout(d: &mut ScriptUiDialog) {
let n = d.nodes.len();
let mut kids: Vec<Vec<usize>> = vec![Vec::new(); n];
for (i, node) in d.nodes.iter().enumerate().skip(1) {
kids[node.parent].push(i);
}
let mut size = vec![[0.0f32; 2]; n];
for i in (0..n).rev() {
let node = &d.nodes[i];
let mut s = if node.kind.container() {
let [l, t, r, b] = node.margins;
let (mut main, mut cross, mut count, mut reach) = (0.0f32, 0.0f32, 0usize, [0.0f32; 2]);
for &k in &kids[i] {
// A hidden control, and everything in it, takes no room.
if !d.nodes[k].visible {
continue;
}
if let Some(bounds) = d.nodes[k].bounds {
reach = [reach[0].max(bounds.x + bounds.w), reach[1].max(bounds.y + bounds.h)];
continue;
}
let [w, h] = size[k];
count += 1;
match node.orientation {
Orientation::Row => (main, cross) = (main + w, cross.max(h)),
Orientation::Column => (main, cross) = (main + h, cross.max(w)),
Orientation::Stack => (main, cross) = (main.max(w), cross.max(h)),
}
}
if node.orientation != Orientation::Stack {
main += node.spacing * count.saturating_sub(1) as f32;
}
let (w, h) = match node.orientation {
Orientation::Row | Orientation::Stack => (main, cross),
Orientation::Column => (cross, main),
};
[(w + l + r).max(reach[0]), (h + t + b).max(reach[1])]
} else {
own_size(node)
};
for axis in 0..2 {
if let Some(v) = node.size[axis] {
s[axis] = v;
}
if let Some(v) = node.min_size[axis] {
s[axis] = s[axis].max(v);
}
if let Some(v) = node.max_size[axis] {
s[axis] = s[axis].min(v);
}
}
if let Some(b) = node.bounds {
s = [b.w, b.h];
}
size[i] = [s[0].clamp(0.0, MAX_EXTENT), s[1].clamp(0.0, MAX_EXTENT)];
}
d.nodes[0].rect = UiRect { x: 0.0, y: 0.0, w: size[0][0], h: size[0][1] };
for i in 0..n {
if !d.nodes[i].kind.container() {
continue;
}
let node = d.nodes[i].clone();
let [l, t, r, b] = node.margins;
let (x, y) = (node.rect.x + l, node.rect.y + t);
let (cw, ch) = ((node.rect.w - l - r).max(0.0), (node.rect.h - t - b).max(0.0));
let mut cursor = 0.0f32;
for &k in &kids[i] {
let kid = &d.nodes[k];
let rect = if !kid.visible {
UiRect { x, y, w: 0.0, h: 0.0 }
} else if let Some(bounds) = kid.bounds {
UiRect { x: node.rect.x + bounds.x, y: node.rect.y + bounds.y, w: bounds.w, h: bounds.h }
} else {
let [w, h] = size[k];
let h_align = kid.alignment.0.or(node.align_children.0).unwrap_or(Align::Center);
let v_align = kid.alignment.1.or(node.align_children.1).unwrap_or(Align::Center);
let max = kid.max_size;
// A control that fills its container's room stays within its maximum.
let place = |align: Align, own: f32, room: f32, axis: usize| match align {
Align::Start => (0.0, own),
Align::End => ((room - own).max(0.0), own),
Align::Center => (((room - own) / 2.0).max(0.0), own),
Align::Fill => (0.0, max[axis].map_or(room.max(own), |m| room.max(own).min(m.max(own)))),
};
match node.orientation {
Orientation::Row => {
let (dy, kh) = place(v_align, h, ch, 1);
let r = UiRect { x: x + cursor, y: y + dy, w, h: kh };
cursor += w + node.spacing;
r
}
Orientation::Column => {
let (dx, kw) = place(h_align, w, cw, 0);
let r = UiRect { x: x + dx, y: y + cursor, w: kw, h };
cursor += h + node.spacing;
r
}
Orientation::Stack => {
let (dx, kw) = place(h_align, w, cw, 0);
let (dy, kh) = place(v_align, h, ch, 1);
UiRect { x: x + dx, y: y + dy, w: kw, h: kh }
}
}
};
d.nodes[k].rect = UiRect {
x: rect.x.clamp(-MAX_EXTENT, MAX_EXTENT),
y: rect.y.clamp(-MAX_EXTENT, MAX_EXTENT),
w: rect.w.clamp(0.0, MAX_EXTENT),
h: rect.h.clamp(0.0, MAX_EXTENT),
};
}
}
}
/// The dialog of one `show()`: the steps left for a run with nobody to ask, and how many events it
/// took.
pub(crate) struct Showing {
pub(crate) dialog: ScriptUiDialog,
pub(crate) steps: Option<std::collections::VecDeque<UiStep>>,
pub(crate) events: u64,
}
impl Showing {
/// The report's record of the dialog, with its `answer`: the result of `show()`, `"stop"`,
/// `"missing"` or `"error"`.
pub(crate) fn record(&self, answer: Value) -> Value {
let mut r = Map::new();
r.insert("kind".into(), json!("window"));
r.insert("title".into(), json!(super::dialogs::cut_to(self.dialog.title(), super::dialogs::MAX_TITLE_BYTES)));
r.insert("controls".into(), json!(self.dialog.nodes.len().saturating_sub(1)));
r.insert("events".into(), json!(self.events));
r.insert("answer".into(), answer);
Value::Object(r)
}
}
/// The host function `name` of `Window`, for the run `link` holds.
fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> HostItem {
let l = link.clone();
HostItem::Function(Rc::new(move |a| f(&*super::current(&l)?, &a)))
}
/// Adds `Window` to the realm, for the run `link` holds.
pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> {
realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))])
}
fn described(host: &Host, args: &[Data]) -> Result<ScriptUiDialog, HostError> {
host.charge_call(args.iter().map(super::data_size).sum())?;
parse(args.first().unwrap_or(&Data::Undefined))
}
fn open(host: &Host, args: &[Data]) -> Result<Data, HostError> {
let dialog = described(host, args)?;
host.dialogs.window_open(dialog)?;
Ok(Data::Undefined)
}
fn wait(host: &Host, args: &[Data]) -> Result<Data, HostError> {
let dialog = described(host, args)?;
host.dialogs.window_wait(dialog)
}
fn end(host: &Host, args: &[Data]) -> Result<Data, HostError> {
let result = number(args.first().unwrap_or(&Data::Undefined)).unwrap_or(0.0);
let normal = matches!(args.get(1), Some(Data::Bool(true)));
host.dialogs.window_end(result, normal)?;
Ok(Data::Undefined)
}
+1
View File
@@ -190,6 +190,7 @@ impl Session {
startup_failures: vec![],
script_high_water: Default::default(),
script_in_run: false,
window_views: vec![],
script_copy_first: cfg!(target_arch = "wasm32"),
}
}
+64
View File
@@ -184,6 +184,7 @@ mod script_folder;
mod script_include;
mod script_io;
mod script_run;
mod script_scriptui;
mod script_tags;
mod script_variables;
mod script_xmp;
@@ -4519,6 +4520,69 @@ fn object_mosaic_tiles_follow_the_image_colours() {
assert!(!st.doc.layers[0].children().unwrap().iter().any(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Image(_))));
}
/// On an image changed by Perspective Distort, each tile is its cell placed between the image's corners: its four
/// anchors are the cell's corners mapped as the image's pixels are, in one undo step. A new size resizes the warped
/// tiles as it resizes the image's bounds, and spacing is measured at the mean length of the image's sides.
#[test]
fn object_mosaic_tiles_of_a_distorted_image_follow_its_corners() {
use vectorcraft_geom::Point;
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [a.0]})).unwrap();
s.execute("paint.setStroke", &json!({"none": true, "ids": [a.0]})).unwrap();
let b = rect(&mut s, 50.0, 0.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": [b.0]})).unwrap();
s.execute("paint.setStroke", &json!({"none": true, "ids": [b.0]})).unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
s.execute("object.distort", &json!({"corners": [[20, 0], [80, 0], [100, 50], [0, 50]]})).unwrap();
let image = s.doc().unwrap().selection.objects.clone();
let node = s.doc().unwrap().doc.node(image[0]).unwrap().clone();
assert!(node.is_distorted_image());
let vectorcraft_doc::NodeKind::Image(im) = &node.kind else { panic!("not an image") };
let (w, h) = (f64::from(im.width), f64::from(im.height));
let map = node.image_map().unwrap();
let at = |x: f64, y: f64| map.apply(Point::new(x, y)).unwrap();
let anchors = |n: &vectorcraft_doc::Node| n.path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect::<Vec<_>>();
let near = |got: &[Point], want: &[Point]| got.len() == want.len() && got.iter().zip(want).all(|(g, w)| g.distance(*w) < 1e-6);
let tiles_of = |s: &Session, r: &serde_json::Value| {
s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().children().unwrap().iter().map(|t| (**t).clone()).collect::<Vec<_>>()
};
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("object.createObjectMosaic", &json!({"columns": 2, "rows": 2})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
let tiles = tiles_of(&s, &r);
assert_eq!(tiles.len(), 4);
for (i, t) in tiles.iter().enumerate() {
let (x0, y0) = ((i % 2) as f64 * w / 2.0, (i / 2) as f64 * h / 2.0);
let want = [at(x0, y0), at(x0 + w / 2.0, y0), at(x0 + w / 2.0, y0 + h / 2.0), at(x0, y0 + h / 2.0)];
assert!(near(&anchors(t), &want), "tile {i}: {:?} against {want:?}", anchors(t));
}
// The first tile starts at the image's top left corner and its right side halves the top edge; the row line is
// nearer the narrow top, as the perspective puts the image's middle row there.
assert!(anchors(&tiles[0])[0].distance(Point::new(20.0, 0.0)) < 1e-6, "{:?}", anchors(&tiles[0]));
assert!((anchors(&tiles[0])[1].x - 50.0).abs() < 1e-6, "{:?}", anchors(&tiles[0]));
assert!(anchors(&tiles[0])[2].y < 24.0, "{:?}", anchors(&tiles[0]));
let fill = |n: &vectorcraft_doc::Node| n.appearance.fill_paint();
assert_eq!(fill(&tiles[0]), vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)));
assert_eq!(fill(&tiles[1]), vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)));
// Twice the width: the warped tiles stretch from the left of the image's bounds.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({ "ids": image })).unwrap();
let r = s.execute("object.createObjectMosaic", &json!({"columns": 2, "rows": 2, "width": 200, "percentages": true})).unwrap();
let tiles = tiles_of(&s, &r);
let stretched = |p: Point| Point::new(p.x * 2.0, p.y);
assert!(near(&anchors(&tiles[3]), &[at(w / 2.0, h / 2.0), at(w, h / 2.0), at(w, h), at(w / 2.0, h)].map(stretched)), "{:?}", anchors(&tiles[3]));
// 8 pt between columns: the image's top and bottom sides are 60 and 100 pt long, so a pixel is 80 / w pt across
// and the gap is w / 10 pixels, half of it on each side of a tile.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({ "ids": image })).unwrap();
let r = s.execute("object.createObjectMosaic", &json!({"columns": 2, "rows": 1, "spacingX": 8})).unwrap();
let tiles = tiles_of(&s, &r);
let g = w / 20.0;
assert!(near(&anchors(&tiles[0]), &[at(g, 0.0), at(w / 2.0 - g, 0.0), at(w / 2.0 - g, h), at(g, h)]), "{:?}", anchors(&tiles[0]));
}
/// Columns and rows that are not whole numbers (a fraction, a negative number, a string or another value) are an
/// error naming the key, and no mosaic is made; 2.0 columns are two columns.
#[test]
+140
View File
@@ -242,6 +242,70 @@ fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_chang
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0)));
}
/// The scales (%) the first stroke of `id`, painted with Stitches, draws with where the pen reads 0
/// and 1.
fn stitches_scale_range(s: &Session, id: NodeId) -> (f64, f64) {
let lib = vectorcraft_brush::library(&s.doc().unwrap().doc);
let b = lib.iter().find(|b| b.name == "Stitches").unwrap();
match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind {
vectorcraft_brush::BrushKind::Pattern(p) => p.scale_range(),
k => panic!("not a pattern brush: {k:?}"),
}
}
#[test]
fn options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes() {
let mut s = session();
let a = line(&mut s);
let b = line(&mut s);
s.execute("brush.apply", &json!({"name": "Stitches", "ids": [a.0, b.0]})).unwrap();
// Both scales follow the pressure; the first path's second scale is its scale, the second
// path's is its own.
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100, "scale_mode": "pressure"}})).unwrap();
s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"scale": 100, "scale_mode": "pressure", "scale_max": 150}})).unwrap();
assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((100.0, 100.0), (100.0, 150.0)));
// The scale the path has already changes nothing.
let steps = undo_steps(&s);
assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100}})).unwrap()["changed"], json!([]));
assert_eq!(own_options(&s, a), json!({"scale_mode": "pressure"}));
assert_eq!(undo_steps(&s), steps);
// A new first scale leaves each path's second scale as it was.
s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 50}})).unwrap();
assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((50.0, 100.0), (50.0, 150.0)));
// A second scale the params give is set on each path, and the brush keeps its own.
s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 40, "scale_max": 120}})).unwrap();
assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((40.0, 120.0), (40.0, 120.0)));
let def = s.execute("brush.get", &json!({"name": "Stitches"})).unwrap();
assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}");
// A mode that is not one is refused, and nothing changes.
let steps = undo_steps(&s);
assert!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale_mode": "sideways"}})).is_err());
assert_eq!(undo_steps(&s), steps);
}
/// Pattern Brush Options' Scale mode and second scale go through `brush.new`, `brush.options`
/// and `brush.get`; a partial edit keeps the other fields, and Fixed leaves both out.
#[test]
fn pattern_brush_scale_mode_goes_through_the_brush_commands() {
let mut s = session();
let side = rect(&mut s, 0.0, 0.0, 40.0, 8.0);
let params = json!({"scale": 50, "scale_mode": "tilt", "scale_max": 300});
s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "params": params, "ids": [side.0]})).unwrap();
let get = |s: &mut Session| s.execute("brush.get", &json!({"name": "Rail"})).unwrap();
let def = get(&mut s);
assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(300.0)));
s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_max": 200, "spacing": 10}})).unwrap();
let def = get(&mut s);
assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(200.0)));
s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "stylusWheel", "scale_max": 1e9}})).unwrap();
let def = get(&mut s);
assert_eq!((&def["scale_mode"], &def["scale_max"]), (&json!("stylusWheel"), &json!(10000.0)));
s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": null, "scale_max": null}})).unwrap();
let def = get(&mut s);
assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}");
assert!(s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "sideways"}})).is_err());
}
#[test]
fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() {
let mut s = session();
@@ -1810,6 +1874,82 @@ fn scatter_hue_jitter_saves_and_exports() {
assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain);
}
/// Scatter Brush Options' `saturation_jitter`: shown by `brush.get`, set by `brush.options` (a value
/// past 100 clamped), saved with the document, and the moved colors drawn the same after Open and
/// written by SVG export.
#[test]
fn scatter_saturation_jitter_saves_and_exports() {
let mut s = session();
let r = rect(&mut s, 10.0, 200.0, 8.0, 8.0);
s.execute("paint.setFill", &json!({"color": "#cc6666"})).unwrap();
let name = s.execute("brush.new", &json!({"type": "scatter", "name": "Confetti", "ids": [r.0]})).unwrap()["name"].as_str().unwrap().to_string();
let id = line(&mut s);
select(&mut s, &[id]);
s.execute("brush.apply", &json!({ "name": name })).unwrap();
let plain = piece_fills(&s.doc().unwrap().doc, id);
assert!(plain.len() > 10 && plain.iter().all(|c| c == "#cc6666"), "{plain:?}");
let get = |s: &mut Session| s.execute("brush.get", &json!({ "name": name })).unwrap()["saturation_jitter"].clone();
assert_eq!(get(&mut s), json!(0.0), "brush.get shows the option at 0");
s.execute("brush.options", &json!({"name": name, "params": {"saturation_jitter": 250}})).unwrap();
assert_eq!(get(&mut s), json!(100.0), "a value past 100 is clamped");
s.execute("brush.options", &json!({"name": name, "params": {"saturation_jitter": 40}})).unwrap();
assert_eq!(get(&mut s), json!(40.0));
let doc = s.doc().unwrap().doc.clone();
let moved = piece_fills(&doc, id);
assert_eq!(moved.len(), plain.len());
let distinct: std::collections::HashSet<&String> = moved.iter().collect();
assert!(distinct.len() > 5, "{moved:?}");
// Saved and opened again, the stroke draws the same colors.
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
assert_eq!(piece_fills(&back, id), moved);
// SVG export writes each copy's moved color.
let svg = vectorcraft_svg::export(&doc, &Default::default());
for c in &distinct {
assert!(svg.contains(&format!("fill=\"{c}\"")), "{c} missing from the SVG");
}
// Back to 0, the copies draw the art's own color.
s.execute("brush.options", &json!({"name": name, "params": {"saturation_jitter": 0}})).unwrap();
assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain);
}
/// Scatter Brush Options' `brightness_jitter`: shown by `brush.get`, set by `brush.options` (a value
/// past 100 clamped), saved with the document, and the moved colors drawn the same after Open and
/// written by SVG export.
#[test]
fn scatter_brightness_jitter_saves_and_exports() {
let mut s = session();
let r = rect(&mut s, 10.0, 200.0, 8.0, 8.0);
s.execute("paint.setFill", &json!({"color": "#cc6666"})).unwrap();
let name = s.execute("brush.new", &json!({"type": "scatter", "name": "Confetti", "ids": [r.0]})).unwrap()["name"].as_str().unwrap().to_string();
let id = line(&mut s);
select(&mut s, &[id]);
s.execute("brush.apply", &json!({ "name": name })).unwrap();
let plain = piece_fills(&s.doc().unwrap().doc, id);
assert!(plain.len() > 10 && plain.iter().all(|c| c == "#cc6666"), "{plain:?}");
let get = |s: &mut Session| s.execute("brush.get", &json!({ "name": name })).unwrap()["brightness_jitter"].clone();
assert_eq!(get(&mut s), json!(0.0), "brush.get shows the option at 0");
s.execute("brush.options", &json!({"name": name, "params": {"brightness_jitter": 250}})).unwrap();
assert_eq!(get(&mut s), json!(100.0), "a value past 100 is clamped");
s.execute("brush.options", &json!({"name": name, "params": {"brightness_jitter": 15}})).unwrap();
assert_eq!(get(&mut s), json!(15.0));
let doc = s.doc().unwrap().doc.clone();
let moved = piece_fills(&doc, id);
assert_eq!(moved.len(), plain.len());
let distinct: std::collections::HashSet<&String> = moved.iter().collect();
assert!(distinct.len() > 5, "{moved:?}");
// Saved and opened again, the stroke draws the same colors.
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
assert_eq!(piece_fills(&back, id), moved);
// SVG export writes each copy's moved color.
let svg = vectorcraft_svg::export(&doc, &Default::default());
for c in &distinct {
assert!(svg.contains(&format!("fill=\"{c}\"")), "{c} missing from the SVG");
}
// Back to 0, the copies draw the art's own color.
s.execute("brush.options", &json!({"name": name, "params": {"brightness_jitter": 0}})).unwrap();
assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain);
}
/// The bounds of the brush art `id`'s strokes draw.
fn brushed_bounds(s: &Session, id: NodeId) -> Rect {
let st = s.doc().unwrap();
+81
View File
@@ -847,6 +847,87 @@ fn pie_legend_labels_follow_wedges_that_take_the_documents_swatch() {
assert_eq!(north, Some(Paint::solid(Color::WHITE)), "in an opacity mask");
}
/// A pie in the art of a symbol or a pattern that a paste brings in follows the document's swatch as a pasted pie does:
/// with Merge, its legend label in the wedge that turned dark is white, and pasting again uses the symbol or pattern the
/// first paste added. With Add the label stays black.
#[test]
fn pie_legend_labels_in_a_pasted_symbol_or_pattern_follow_wedges_that_take_the_documents_swatch() {
let csv = ",North,South\nP,1,1";
/// A pie with Legends in Wedges whose first wedge is filled with the global swatch "Brand", light yellow.
fn branded_pie(s: &mut Session, csv: &str) -> NodeId {
if doc(s).swatch("Brand").is_none() {
s.execute("swatch.new", &json!({"name": "Brand", "color": "#ffff66", "global": true})).unwrap();
}
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
let mut wedges = vec![];
for c in node(s, g).children().unwrap().iter().filter(|c| c.extras().series_index == Some(0)) {
c.walk(&mut |m| {
if matches!(m.kind, NodeKind::Path { .. }) {
wedges.push(m.id.0);
}
});
}
assert!(!wedges.is_empty());
s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Brand"})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
g
}
/// The fill of the legend label that says `name` in `art`.
fn label_in(art: &[std::sync::Arc<Node>], name: &str) -> Paint {
let mut out = None;
for a in art {
a.walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == name
{
out = Some(t.first_style().fill.clone());
}
});
}
out.unwrap()
}
let symbol_art = |s: &Session| vec![doc(s).symbols.iter().find(|x| x.name == "Chart").unwrap().art.clone()];
let pattern_art = |s: &Session| doc(s).pattern("Chart").unwrap().art.clone();
let mut s = session();
let g = branded_pie(&mut s, csv);
sel(&mut s, &[g]);
let instance = id_of(&s.execute("symbol.new", &json!({"name": "Chart"})).unwrap());
assert_eq!(label_in(&symbol_art(&s), "North"), Paint::solid(Color::BLACK), "black on the light wedge");
copy(&mut s, &[instance]);
for (choice, north) in [("merge", Color::WHITE), ("add", Color::BLACK)] {
new_doc(&mut s);
s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap();
s.execute("edit.paste", &json!({"swatchConflict": choice})).unwrap();
assert_eq!(label_in(&symbol_art(&s), "North"), Paint::solid(north), "symbol {choice}");
assert_eq!(label_in(&symbol_art(&s), "South"), Paint::solid(Color::BLACK), "symbol {choice}");
// Pasting again uses the symbol the first paste added.
s.execute("edit.paste", &json!({"swatchConflict": choice})).unwrap();
let names: Vec<&str> = doc(&s).symbols.iter().map(|x| x.name.as_str()).collect();
assert_eq!(names, ["Chart"], "symbol {choice}");
}
let mut s = session();
let g = branded_pie(&mut s, csv);
s.execute("object.pattern.make", &json!({"name": "Chart", "edit": false, "ids": [g.0]})).unwrap();
assert_eq!(label_in(&pattern_art(&s), "North"), Paint::solid(Color::BLACK), "black on the light wedge");
let r = rect(&mut s, 300.0, 300.0, 100.0, 100.0);
s.execute("paint.setFill", &json!({"ids": [r.0], "swatch": "Chart"})).unwrap();
copy(&mut s, &[r]);
for (choice, north) in [("merge", Color::WHITE), ("add", Color::BLACK)] {
new_doc(&mut s);
s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap();
s.execute("edit.paste", &json!({"swatchConflict": choice})).unwrap();
assert_eq!(label_in(&pattern_art(&s), "North"), Paint::solid(north), "pattern {choice}");
assert_eq!(label_in(&pattern_art(&s), "South"), Paint::solid(Color::BLACK), "pattern {choice}");
// Pasting again uses the pattern the first paste added.
s.execute("edit.paste", &json!({"swatchConflict": choice})).unwrap();
let names: Vec<&str> = doc(&s).patterns.iter().map(|x| x.name.as_str()).collect();
assert_eq!(names, ["Chart"], "pattern {choice}");
}
}
/// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph
/// is pasted without formatting.
#[test]
+42
View File
@@ -357,6 +357,48 @@ fn convert_to_oklch_answers_lightness_chroma_and_hue() {
assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}");
}
/// `color.parse` reads each notation into an RGB color, its hex and the alpha as a percentage (null
/// when the text gives none), and answers an error for anything else.
#[test]
fn parse_reads_hex_with_alpha_and_css_colors() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let mut parse = |text: &str| s.execute("color.parse", &json!({ "text": text }));
for (text, opacity) in [
("#33669980", json!(50.2)),
("33669980", json!(50.2)),
("#3698", json!(53.33)),
("#336699", Value::Null),
("#369", Value::Null),
("rgb(51 102 153 / 50%)", json!(50.0)),
("rgba(51, 102, 153, 0.25)", json!(25.0)),
("rgb(20% 40% 60%)", Value::Null),
("hsl(210 50% 40%)", Value::Null),
("hsla(210deg, 50%, 40%, 1)", json!(100.0)),
] {
let r = parse(text).unwrap();
assert_eq!(r["hex"], "#336699", "{text}: {r}");
assert_eq!(r["opacity"], opacity, "{text}: {r}");
let c: Color = serde_json::from_value(r["color"].clone()).unwrap();
let Color::Rgb { r: red, g, b } = c else { panic!("{text}: {c:?}") };
assert_eq!([red, g, b].map(|v| (v * 255.0).round() as u8), [0x33, 0x66, 0x99], "{text}");
}
let red = parse("oklch(62.8% 0.2577 29.23 / 0.5)").unwrap();
assert_eq!((&red["hex"], &red["opacity"]), (&json!("#ff0000"), &json!(50.0)), "{red}");
let message = "`text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters";
let long = format!("rgb(1 2 3{})", " ".repeat(40));
for bad in ["", "#12345", "#gggggg", "rgb(1, 2%, 3)", "rgb(1 2)", "oklch(0.5, 0.1, 30)", "cmyk 0 100 100 0", "red", long.as_str()] {
let e = parse(bad).unwrap_err().to_string();
assert!(e.ends_with(message), "{bad:?}: {e}");
}
assert!(parse_err(&mut s, json!({})).ends_with("missing `text`"));
assert!(parse_err(&mut s, json!({"text": 5})).ends_with("`text` must be a string"));
}
fn parse_err(s: &mut Session, p: Value) -> String {
s.execute("color.parse", &p).unwrap_err().to_string()
}
#[test]
fn assign_profile_is_stored_and_undoable() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+18
View File
@@ -4045,6 +4045,24 @@ fn move_anchors_reshape_and_close_refuse_a_number_given_as_text() {
assert!(after.subpaths[0].closed && moved == Some(before.subpaths[0].anchors[1].p.x + 10.0), "{after:?}");
}
/// Move Anchors by 0, with anchors or whole paths selected, changes nothing and records no undo
/// step; a move by 10 records one.
#[test]
fn move_anchors_by_zero_records_no_undo_step() {
let mut s = session();
let id = curve(&mut s);
for select in [json!({"id": id.0, "anchors": [[0, 1]]}), json!({"id": id.0, "anchors": [[0, 0], [0, 1]]})] {
s.execute("select.anchors", &select).unwrap();
let (before, undo) = (path(&s, id), s.doc().unwrap().history.undo.len());
for p in [json!({}), json!({"dx": 0, "dy": 0}), json!({"dx": null, "dy": -0.0})] {
s.execute("path.moveAnchors", &p).unwrap();
assert_eq!((path(&s, id), s.doc().unwrap().history.undo.len()), (before.clone(), undo), "{select} {p}");
}
s.execute("path.moveAnchors", &json!({"dx": 10})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{select}");
}
}
/// Close Path, Set Handle, Move Anchors and the Pencil, Curvature, Reshape Segment and Blob Brush
/// commands refuse an on/off option given as text or as another value that is not true or false,
/// naming the key, and change nothing; true, false and null still work.
Loaded 100 of 335 files, more files were not shown because too many files have changed in this diff. Show more