mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 17:05:55 +01:00
Merge remote-tracking branch 'origin/main' into feat/4943-more-indian-languages
# Conflicts: # docs/type-parity.md # docs/ui-parity.md
This commit is contained in:
commit
ee02b1c395
320 files changed
+24753
-1756
No files matched your search
Generated
+21
@@ -1035,6 +1035,17 @@ dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
"toml",
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -6356,6 +6367,13 @@ dependencies = [
|
||||
"ruzstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-apischema"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-brush"
|
||||
version = "0.21.0"
|
||||
@@ -6463,6 +6481,7 @@ dependencies = [
|
||||
"cfb",
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"craft-proof",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"hayro-jpeg2000",
|
||||
@@ -6480,8 +6499,10 @@ dependencies = [
|
||||
"ruzstd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-affinity",
|
||||
"vectorcraft-apischema",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-cad",
|
||||
"vectorcraft-color",
|
||||
|
||||
@@ -16,6 +16,7 @@ craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
|
||||
@@ -54,6 +55,7 @@ vectorcraft-plugins = { path = "crates/plugins" }
|
||||
vectorcraft-affinity = { path = "crates/affinity" }
|
||||
vectorcraft-scriptcheck = { path = "crates/scriptcheck" }
|
||||
vectorcraft-js = { path = "crates/js" }
|
||||
vectorcraft-apischema = { path = "crates/apischema" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
|
||||
+5
-5
@@ -15,7 +15,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -83,11 +83,11 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so
|
||||
| Strokes, brushes, width profiles | 88% | 8–15 |
|
||||
| Appearance, transparency, graphic styles, masks | 97% | 1–2 |
|
||||
| Live vector effects | 85% | 4–8 |
|
||||
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 85% | 1–2 |
|
||||
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 88% | — |
|
||||
| 3D and Materials | ~25% | 30–55 |
|
||||
| Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 |
|
||||
| Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 |
|
||||
| Symbols, blends, envelopes, Repeat, perspective | 87% | 5–9 |
|
||||
| Symbols, blends, envelopes, Repeat, perspective | 88% | 4–7 |
|
||||
| Image Trace, graphs, image tools | 75% | 5–8 |
|
||||
| Layers, artboards, document setup | 78% | 5–8 |
|
||||
| View & navigation | 70% | 9–14 |
|
||||
@@ -131,8 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h.
|
||||
3. **Launch and stability on real machines** (G10): 20–35 h.
|
||||
4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h.
|
||||
5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h.
|
||||
6. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3).
|
||||
5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2).
|
||||
|
||||
## Progress log
|
||||
|
||||
@@ -226,6 +225,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
|
||||
| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. |
|
||||
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
|
||||
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
|
||||
|
||||
@@ -78,7 +78,7 @@ USAGE:
|
||||
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
|
||||
does not take --connect.
|
||||
|
||||
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
|
||||
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
|
||||
(vectorcraft --control 7979), falling back to a headless in-process session.
|
||||
--automation-read-root / --automation-write-root confine the files the agent's commands read
|
||||
@@ -86,8 +86,18 @@ USAGE:
|
||||
DIR, links followed; each may be given more than once, a path inside any of its folders being
|
||||
allowed, and a kind left out grants none of its access. They imply --headless: a running app
|
||||
enforces its own (vectorcraft --control PORT --automation-read-root DIR …).
|
||||
--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect in this session,
|
||||
so whoever sends the commands can give a plug-in the permissions it lists, and a heavy budget,
|
||||
with nobody approving them. Without it they are refused, and a plug-in that lists permissions
|
||||
installs only when its hash is already recorded in grants.json, by a person's approval in the
|
||||
desktop app or by a grant accepted under this flag. A grant accepted under this flag stays
|
||||
recorded and counts as approved in later sessions. It implies --headless. It can't be used
|
||||
with --automation-read-root or --automation-write-root: a server confined to folders has no
|
||||
plug-in store, so it reads no grants.json, and a plug-in that lists permissions or asks for a
|
||||
heavy budget does not install there. With VECTORCRAFT_NO_PREFS set there is no store either,
|
||||
and a grant accepted under this flag lasts for that session only.
|
||||
|
||||
vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N]
|
||||
vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] [--allow-plugin-grants]
|
||||
Headless batch: open FILE (any readable format) or start a new document, run commands in
|
||||
order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE
|
||||
is a template, written as file.saveAsTemplate writes it). Raster exports use the document's
|
||||
@@ -97,6 +107,8 @@ USAGE:
|
||||
--cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for
|
||||
\"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps.
|
||||
Errors name the step, counting from 0 as \"$N\" references do.
|
||||
--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect in this run, as
|
||||
for mcp.
|
||||
|
||||
vectorcraft-cli commands
|
||||
Print the command catalogue as JSON.
|
||||
@@ -224,12 +236,22 @@ fn main() -> ExitCode {
|
||||
}
|
||||
|
||||
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
|
||||
/// ICC profiles loaded and the plug-ins installed (#2168, #2174, #2541), in the folders next to the preferences that the desktop
|
||||
/// app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541) and the custom dictionary's words (#4936), in the folders
|
||||
/// and files next to the preferences that the desktop app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply
|
||||
/// as they do there.
|
||||
fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_profile_store(&mut h.session);
|
||||
prefs_dir::attach_plugin_store(&mut h.session);
|
||||
prefs_dir::attach_pdf_preset_store(&mut h.session);
|
||||
prefs_dir::attach_custom_dictionary(&mut h.session);
|
||||
h
|
||||
}
|
||||
|
||||
/// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`).
|
||||
fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
|
||||
if allow {
|
||||
h.session.allow_plugin_grants_from_requests();
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
@@ -241,6 +263,7 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
}
|
||||
let mut connect: Option<String> = None;
|
||||
let mut headless = false;
|
||||
let mut allow_grants = false;
|
||||
let (mut read_roots, mut write_roots): (Vec<String>, Vec<String>) = (vec![], vec![]);
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
@@ -252,6 +275,7 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
match flag {
|
||||
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?),
|
||||
"--headless" => headless = true,
|
||||
"--allow-plugin-grants" => allow_grants = true,
|
||||
"--automation-read-root" | "--automation-write-root" => {
|
||||
let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?;
|
||||
if flag == "--automation-read-root" { read_roots.push(dir) } else { write_roots.push(dir) }
|
||||
@@ -262,6 +286,12 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
if headless && connect.is_some() {
|
||||
return Err("use either --connect or --headless".into());
|
||||
}
|
||||
if allow_grants && connect.is_some() {
|
||||
return Err("--allow-plugin-grants applies to the headless server; in a running app a person approves each plug-in".into());
|
||||
}
|
||||
if allow_grants && !(read_roots.is_empty() && write_roots.is_empty()) {
|
||||
return Err("--allow-plugin-grants can't be used with --automation-read-root or --automation-write-root: a server confined to folders has no plug-in store to record a grant in".into());
|
||||
}
|
||||
if safe_mode && connect.is_some() {
|
||||
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
|
||||
}
|
||||
@@ -276,9 +306,9 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
// Every thread of this process, not only the server's: nothing reaches past the roots.
|
||||
file_access::confine_process(roots.clone());
|
||||
eprintln!("vectorcraft-cli: files confined: {}", roots.describe());
|
||||
Box::new(Headless::with_document().with_automation_roots(Some(roots)))
|
||||
} else if headless || safe_mode {
|
||||
Box::new(with_stores(Headless::with_document()))
|
||||
Box::new(accepting_grants(Headless::with_document().with_automation_roots(Some(roots)), allow_grants))
|
||||
} else if headless || safe_mode || allow_grants {
|
||||
Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants))
|
||||
} else if let Some(addr) = connect {
|
||||
// Explicit address: fail loudly if the app isn't there.
|
||||
Box::new(Remote::connect(&addr).map_err(|e| format!("cannot connect to {addr}: {e}"))?)
|
||||
@@ -561,6 +591,7 @@ fn run(args: &[String]) -> Result<(), String> {
|
||||
let mut stdin_read = false;
|
||||
let mut scale = None::<f64>;
|
||||
let mut ppi = None::<f64>;
|
||||
let mut allow_grants = false;
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
let mut val = |what: &str| it.next().cloned().ok_or_else(|| format!("{a} needs {what}"));
|
||||
@@ -595,6 +626,7 @@ fn run(args: &[String]) -> Result<(), String> {
|
||||
steps.push(Step::Export(val("a file")?));
|
||||
params_for = None;
|
||||
}
|
||||
"--allow-plugin-grants" => allow_grants = true,
|
||||
"--scale" | "-s" => {
|
||||
let raw = val("a number")?;
|
||||
scale = Some(raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?);
|
||||
@@ -612,7 +644,7 @@ fn run(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
let mut h = with_stores(Headless::new());
|
||||
let mut h = accepting_grants(with_stores(Headless::new()), allow_grants);
|
||||
let mut out = std::io::stdout().lock();
|
||||
// A reader that stopped early (a closed pipe) isn't an error, and the batch goes on: its later
|
||||
// steps (an export…) still run, unprinted.
|
||||
|
||||
@@ -19,6 +19,77 @@ fn empty_dir(dir: std::path::PathBuf) -> std::path::PathBuf {
|
||||
dir
|
||||
}
|
||||
|
||||
/// `run` and `mcp --headless` refuse `plugin.install` with this param unless the process was started
|
||||
/// with `--allow-plugin-grants`.
|
||||
fn approval_param_needs_the_start_up_flag(key: &str, value: Value) {
|
||||
let module = vectorcraft_format::base64_encode(include_bytes!("../../../../crates/plugins/tests/fixtures/desaturate.wasm"));
|
||||
let steps = tmp(&format!("{key}.json"));
|
||||
std::fs::write(&steps, json!([{"command": "plugin.install", "params": {"dataBase64": module, key: value}}]).to_string()).unwrap();
|
||||
let config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-{key}-{}", std::process::id())));
|
||||
let run = |extra: &[&str]| {
|
||||
Command::new(BIN).env("VECTORCRAFT_CONFIG_DIR", &config).args(["run", "--commands", steps.to_str().unwrap()]).args(extra).output().unwrap()
|
||||
};
|
||||
let out = run(&[]);
|
||||
assert!(!out.status.success());
|
||||
let shown = String::from_utf8_lossy(&out.stderr).into_owned() + &String::from_utf8_lossy(&out.stdout);
|
||||
assert!(shown.contains("--allow-plugin-grants"), "{shown}");
|
||||
let out = run(&["--allow-plugin-grants"]);
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
|
||||
let mcp_config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-mcp-{key}-{}", std::process::id())));
|
||||
let mcp_install = |extra: &[&str]| -> Value {
|
||||
let mut child = Command::new(BIN)
|
||||
.env("VECTORCRAFT_CONFIG_DIR", &mcp_config)
|
||||
.args(["mcp", "--headless"])
|
||||
.args(extra)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
{
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
let params = json!({"dataBase64": module, key: value});
|
||||
for m in [
|
||||
json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}),
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized"}),
|
||||
json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"run_command","arguments":{"command":"plugin.install","params":params}}}),
|
||||
] {
|
||||
writeln!(stdin, "{m}").unwrap();
|
||||
}
|
||||
}
|
||||
let out = child.wait_with_output().unwrap();
|
||||
assert!(out.status.success());
|
||||
let replies: Vec<Value> = String::from_utf8(out.stdout).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
replies.into_iter().find(|r| r["id"] == 2).unwrap()["result"].take()
|
||||
};
|
||||
let refused = mcp_install(&[]);
|
||||
assert_eq!(refused["isError"], true, "without the flag: {refused}");
|
||||
assert!(refused["content"][0]["text"].as_str().unwrap().contains("--allow-plugin-grants"), "{refused}");
|
||||
let accepted = mcp_install(&["--allow-plugin-grants"]);
|
||||
assert_eq!(accepted["isError"], false, "with the flag: {accepted}");
|
||||
}
|
||||
|
||||
/// `run` and `mcp --headless` refuse `plugin.install`'s `grant` and `allowHeavy` unless the process was
|
||||
/// started with `--allow-plugin-grants`, which `mcp` won't take with `--connect` or the automation roots.
|
||||
#[test]
|
||||
fn plugin_grants_need_the_start_up_flag() {
|
||||
approval_param_needs_the_start_up_flag("grant", json!(["doc.read"]));
|
||||
approval_param_needs_the_start_up_flag("allowHeavy", json!(true));
|
||||
|
||||
let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap();
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants applies to the headless server"));
|
||||
let root = std::env::temp_dir();
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap();
|
||||
assert!(!out.status.success(), "{flag}");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants can't be used with"), "{flag}");
|
||||
}
|
||||
let usage = Command::new(BIN).arg("help").output().unwrap();
|
||||
assert!(String::from_utf8_lossy(&usage.stdout).contains("--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_prints_catalogue() {
|
||||
let out = Command::new(BIN).arg("commands").output().unwrap();
|
||||
@@ -526,7 +597,7 @@ fn exercise_mcp_core(
|
||||
assert!(r["result"]["completion"]["values"].as_array().is_some_and(|v| v.contains(&json!("svg"))), "{r}");
|
||||
|
||||
mcp_send(stdin, json!({"jsonrpc":"2.0","id":5,"method":"resources/list","params":{}}));
|
||||
assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 3));
|
||||
assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 4));
|
||||
mcp_send(stdin, json!({"jsonrpc":"2.0","id":6,"method":"resources/templates/list","params":{}}));
|
||||
assert!(mcp_recv(lines, notes, 6)["result"]["resourceTemplates"].as_array().is_some_and(|v| v.len() >= 4));
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ vectorcraft-render = { workspace = true }
|
||||
# with default features off). Pinned exactly: review the diff before bumping.
|
||||
muda = { version = "=0.21.2", default-features = false }
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
|
||||
# Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd.
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] }
|
||||
block2 = "0.6"
|
||||
|
||||
@@ -95,12 +95,18 @@ impl eframe::App for App {
|
||||
// A ready update installs once the process has exited. The macOS exit below skips
|
||||
// dropping the app, so the helper is started here.
|
||||
self.app.start_pending_update();
|
||||
#[cfg(target_os = "macos")]
|
||||
super::mac_cursor::release();
|
||||
end_before_teardown(self.frames);
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if self.winit_window.as_ref().is_some_and(|w| !w.has_focus() || w.is_visible() == Some(false) || w.is_minimized() == Some(true)) {
|
||||
super::mac_cursor::release();
|
||||
}
|
||||
self.frames = ctx.cumulative_frame_nr();
|
||||
if let Some(why) = self.graphics_loss.take() {
|
||||
// eframe can't give a window a new device: the user saves and starts again.
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
//! AppKit delivery of the UI's existing cursor artwork, independent of canvas presentation.
|
||||
#![forbid(unsafe_code)]
|
||||
// Interim #2292: remove when pinned winit correctly handles macOS cursor image and hotspot sizing.
|
||||
|
||||
use egui::{Context, FullOutput, Plugin, ViewportId};
|
||||
use objc2::{AllocAnyThread, MainThreadMarker, rc::Retained};
|
||||
use objc2_app_kit::{NSApplication, NSBitmapImageRep, NSCursor, NSImage, NSWindow};
|
||||
use objc2_foundation::{NSData, NSPoint, NSSize};
|
||||
use std::cell::RefCell;
|
||||
use vectorcraft_ui_egui::cursors::native_request::{self, Bitmap, Key, Request};
|
||||
|
||||
const CAPACITY: usize = 128;
|
||||
|
||||
fn build(bitmap: &Bitmap) -> Option<Retained<NSCursor>> {
|
||||
let one = &bitmap.representations[0];
|
||||
let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1]));
|
||||
let image = NSImage::initWithSize(NSImage::alloc(), size);
|
||||
for bitmap in &bitmap.representations {
|
||||
let pixels = image::RgbaImage::from_raw(u32::from(bitmap.size[0]), u32::from(bitmap.size[1]), bitmap.rgba.to_vec())?;
|
||||
let mut png = std::io::Cursor::new(Vec::new());
|
||||
pixels.write_to(&mut png, image::ImageFormat::Png).ok()?;
|
||||
let rep = NSBitmapImageRep::imageRepWithData(&NSData::with_bytes(png.get_ref()))?;
|
||||
rep.setSize(size);
|
||||
image.addRepresentation(&rep);
|
||||
}
|
||||
Some(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1]))))
|
||||
}
|
||||
|
||||
/// The ownership protocol also runs against a headless backend in tests.
|
||||
trait Backend {
|
||||
type Window: Clone + PartialEq;
|
||||
type Cursor: Clone + PartialEq;
|
||||
fn window(&self) -> Option<Self::Window>;
|
||||
fn enabled(&self, window: &Self::Window) -> bool;
|
||||
fn suspend(&mut self, window: &Self::Window);
|
||||
fn restore(&mut self, window: &Self::Window);
|
||||
fn build(&mut self, request: &Request) -> Option<Self::Cursor>;
|
||||
fn current(&self) -> Option<Self::Cursor>;
|
||||
fn set(&mut self, cursor: &Self::Cursor);
|
||||
}
|
||||
|
||||
struct State<B: Backend> {
|
||||
backend: B,
|
||||
candidate: Option<B::Window>,
|
||||
cache: Vec<(Key, Option<B::Cursor>)>,
|
||||
// Retain the active object independently of cache eviction.
|
||||
active: Option<(Key, B::Window, B::Cursor)>,
|
||||
}
|
||||
|
||||
impl<B: Backend> State<B> {
|
||||
fn new(backend: B) -> Self {
|
||||
Self { backend, candidate: None, cache: Vec::new(), active: None }
|
||||
}
|
||||
|
||||
fn begin(&mut self) {
|
||||
self.candidate = self.backend.window();
|
||||
}
|
||||
|
||||
fn release(&mut self) {
|
||||
self.candidate = None;
|
||||
if let Some((_, window, _)) = self.active.take() {
|
||||
self.backend.restore(&window);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&mut self, request: Option<Request>) {
|
||||
let window = self.candidate.take().filter(|w| self.backend.window().as_ref() == Some(w));
|
||||
let (Some(request), Some(window)) = (request, window) else {
|
||||
self.release();
|
||||
return;
|
||||
};
|
||||
if let Some((key, owned, cursor)) = &self.active
|
||||
&& *key == request.key
|
||||
&& *owned == window
|
||||
{
|
||||
if self.backend.current().as_ref() != Some(cursor) {
|
||||
self.backend.set(cursor);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.release();
|
||||
// Never take another component's suspension (a sheet or native tracking session).
|
||||
if !self.backend.enabled(&window) {
|
||||
return;
|
||||
}
|
||||
let cursor = if let Some((_, cursor)) = self.cache.iter().find(|(key, _)| *key == request.key) {
|
||||
cursor.clone()
|
||||
} else {
|
||||
let cursor = self.backend.build(&request);
|
||||
if self.cache.len() >= CAPACITY {
|
||||
self.cache.clear();
|
||||
}
|
||||
self.cache.push((request.key, cursor.clone()));
|
||||
cursor
|
||||
};
|
||||
if let Some(cursor) = cursor {
|
||||
self.backend.suspend(&window);
|
||||
self.backend.set(&cursor);
|
||||
self.active = Some((request.key, window, cursor));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct AppKit {
|
||||
root: std::sync::Weak<winit::window::Window>,
|
||||
}
|
||||
impl Backend for AppKit {
|
||||
type Window = Retained<NSWindow>;
|
||||
type Cursor = Retained<NSCursor>;
|
||||
fn window(&self) -> Option<Self::Window> {
|
||||
let mtm = MainThreadMarker::new()?;
|
||||
// Bind the candidate to the host's actual root window without converting raw pointers.
|
||||
// A floating native panel may be key while egui still has stale root focus input.
|
||||
let root = self.root.upgrade()?;
|
||||
if !root.has_focus() || root.is_visible() == Some(false) || root.is_minimized() == Some(true) {
|
||||
return None;
|
||||
}
|
||||
NSApplication::sharedApplication(mtm).keyWindow().filter(|w| w.isVisible() && w.isKeyWindow())
|
||||
}
|
||||
fn enabled(&self, window: &Self::Window) -> bool {
|
||||
window.areCursorRectsEnabled()
|
||||
}
|
||||
fn suspend(&mut self, window: &Self::Window) {
|
||||
window.disableCursorRects();
|
||||
}
|
||||
fn restore(&mut self, window: &Self::Window) {
|
||||
window.enableCursorRects();
|
||||
window.resetCursorRects();
|
||||
// egui-winit may skip an unchanged fallback icon. Rebuild its stored rectangle anyway.
|
||||
if let Some(view) = window.contentView() {
|
||||
window.invalidateCursorRectsForView(&view);
|
||||
}
|
||||
}
|
||||
fn build(&mut self, request: &Request) -> Option<Self::Cursor> {
|
||||
build(&request.bitmap)
|
||||
}
|
||||
fn current(&self) -> Option<Self::Cursor> {
|
||||
Some(NSCursor::currentCursor())
|
||||
}
|
||||
fn set(&mut self, cursor: &Self::Cursor) {
|
||||
cursor.set();
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! { static STATE: RefCell<State<AppKit>> = RefCell::new(State::new(AppKit::default())); }
|
||||
|
||||
fn with_state(f: impl FnOnce(&mut State<AppKit>)) {
|
||||
// All production AppKit access, including restoration, stays on the main thread.
|
||||
if MainThreadMarker::new().is_some() {
|
||||
STATE.with(|state| {
|
||||
if let Ok(mut state) = state.try_borrow_mut() {
|
||||
f(&mut state);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Also called synchronously when native menu tracking begins and before process teardown.
|
||||
pub(crate) fn release() {
|
||||
with_state(State::release);
|
||||
}
|
||||
|
||||
struct EndedPass {
|
||||
viewport: ViewportId,
|
||||
discarded: bool,
|
||||
request: Option<Request>,
|
||||
}
|
||||
|
||||
struct Delivery {
|
||||
begin: fn(),
|
||||
finish: fn(Option<Request>),
|
||||
release: fn(),
|
||||
tracking: fn() -> bool,
|
||||
ended: Vec<EndedPass>,
|
||||
}
|
||||
|
||||
impl Plugin for Delivery {
|
||||
fn debug_name(&self) -> &'static str {
|
||||
"macOS canvas cursor"
|
||||
}
|
||||
fn on_begin_pass(&mut self, ui: &mut egui::Ui) {
|
||||
native_request::clear(ui.ctx());
|
||||
// Floating panels must not acquire or release the main canvas's window.
|
||||
if ui.ctx().viewport_id() == ViewportId::ROOT {
|
||||
(self.begin)();
|
||||
}
|
||||
}
|
||||
fn on_end_pass(&mut self, ui: &mut egui::Ui) {
|
||||
// egui restores the parent viewport before output_hook. Capture this pass here so
|
||||
// a floating panel's output cannot consume or release its parent's cursor.
|
||||
self.ended.push(EndedPass { viewport: ui.ctx().viewport_id(), discarded: ui.ctx().will_discard(), request: native_request::take(ui.ctx()) });
|
||||
}
|
||||
fn input_hook(&mut self, _: &Context, input: &mut egui::RawInput) {
|
||||
if input.viewport_id == ViewportId::ROOT
|
||||
&& (!input.focused || input.viewports.get(&ViewportId::ROOT).is_some_and(|v| v.minimized == Some(true)))
|
||||
{
|
||||
(self.release)();
|
||||
}
|
||||
}
|
||||
fn output_hook(&mut self, ctx: &Context, output: &mut FullOutput) {
|
||||
let Some(ended) = self.ended.pop() else { return };
|
||||
if ended.viewport != ViewportId::ROOT {
|
||||
return;
|
||||
}
|
||||
if ended.discarded
|
||||
|| (output.platform_output.requested_discard() && output.platform_output.num_completed_passes < ctx.options(|o| o.max_passes.get()))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let request = ended.request.filter(|r| {
|
||||
r.viewport == ended.viewport
|
||||
&& r.pass.checked_add(1) == Some(ctx.cumulative_pass_nr_for(ended.viewport))
|
||||
&& ctx.input(|i| i.focused && i.pointer.hover_pos().is_some())
|
||||
&& output.platform_output.cursor_icon == r.fallback
|
||||
&& output.platform_output.cursor_image.is_none()
|
||||
&& !(self.tracking)()
|
||||
});
|
||||
// This is BEFORE egui-winit's platform output. In pinned winit, fallback changes update
|
||||
// the view's stored cursor and invalidate rectangles. Our owned suspension is intended
|
||||
// to keep that update from replacing the native cursor; native timing needs hand testing.
|
||||
(self.finish)(request);
|
||||
}
|
||||
fn on_exit(&mut self, _: &Context) {
|
||||
(self.release)();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn install(ctx: &Context, window: Option<&std::sync::Arc<winit::window::Window>>) {
|
||||
with_state(|state| state.backend.root = window.map(std::sync::Arc::downgrade).unwrap_or_default());
|
||||
ctx.add_plugin(Delivery {
|
||||
begin: || with_state(State::begin),
|
||||
finish: |request| with_state(|state| state.finish(request)),
|
||||
release,
|
||||
tracking: super::mac_menu::is_tracking,
|
||||
ended: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,236 @@
|
||||
use super::*;
|
||||
use egui::{CursorIcon, RawInput};
|
||||
use std::cell::Cell;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
window: Option<u8>,
|
||||
suspended: Vec<u8>,
|
||||
current: Option<Key>,
|
||||
sets: usize,
|
||||
builds: usize,
|
||||
restores: Vec<u8>,
|
||||
fail: bool,
|
||||
}
|
||||
impl Backend for Fake {
|
||||
type Window = u8;
|
||||
type Cursor = Key;
|
||||
fn window(&self) -> Option<u8> {
|
||||
self.window
|
||||
}
|
||||
fn enabled(&self, w: &u8) -> bool {
|
||||
!self.suspended.contains(w)
|
||||
}
|
||||
fn suspend(&mut self, w: &u8) {
|
||||
self.suspended.push(*w);
|
||||
}
|
||||
fn restore(&mut self, w: &u8) {
|
||||
self.suspended.retain(|v| v != w);
|
||||
self.restores.push(*w);
|
||||
self.current = None;
|
||||
}
|
||||
fn build(&mut self, r: &Request) -> Option<Key> {
|
||||
self.builds += 1;
|
||||
(!self.fail).then_some(r.key)
|
||||
}
|
||||
fn current(&self) -> Option<Key> {
|
||||
self.current
|
||||
}
|
||||
fn set(&mut self, cursor: &Key) {
|
||||
self.current = Some(*cursor);
|
||||
self.sets += 1;
|
||||
}
|
||||
}
|
||||
fn fake_state() -> State<Fake> {
|
||||
State::new(Fake { window: Some(1), ..Default::default() })
|
||||
}
|
||||
fn raw(id: ViewportId, focused: bool) -> RawInput {
|
||||
let mut input = RawInput { viewport_id: id, focused, events: vec![egui::Event::PointerMoved(egui::pos2(10.0, 10.0))], ..Default::default() };
|
||||
input.viewports.entry(id).or_default();
|
||||
input
|
||||
}
|
||||
fn publish(ctx: &Context, scale: f32) {
|
||||
let mut session = vectorcraft_engine::Session::new();
|
||||
let cursor = session.cursor(Default::default(), Default::default(), Default::default());
|
||||
let fallback = native_request::request(ctx, cursor, CursorIcon::Default, true, scale);
|
||||
ctx.set_cursor_icon(fallback);
|
||||
}
|
||||
fn request(scale: f32) -> Request {
|
||||
let ctx = Context::default();
|
||||
let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| publish(ui.ctx(), scale));
|
||||
native_request::take(&ctx).unwrap()
|
||||
}
|
||||
fn deliver(state: &mut State<Fake>, request: Option<Request>) {
|
||||
state.begin();
|
||||
state.finish(request);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_cursor_ownership_deduplicates_reasserts_and_restores() {
|
||||
let req = request(1.0);
|
||||
let mut state = fake_state();
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.suspended, [1]);
|
||||
assert_eq!((state.backend.builds, state.backend.sets), (1, 1));
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.sets, 1);
|
||||
// Simulate a platform fallback replacing the cursor after finalization. The next pass
|
||||
// reasserts; this proves the protocol, not AppKit timing or absence of transient flicker.
|
||||
state.backend.current = None;
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.sets, 2);
|
||||
deliver(&mut state, None);
|
||||
assert_eq!(state.backend.restores, [1]);
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
state.backend.window = None;
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert!(state.active.is_none());
|
||||
state.backend.window = Some(1);
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
state.begin();
|
||||
state.backend.window = Some(2);
|
||||
state.finish(Some(req));
|
||||
assert!(state.active.is_none(), "never acquire a different key window mid-pass");
|
||||
assert_eq!(state.backend.restores, [1, 1, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_cursor_respects_other_suspensions_failures_and_cache_eviction() {
|
||||
let mut state = fake_state();
|
||||
state.backend.suspended.push(1);
|
||||
deliver(&mut state, Some(request(1.0)));
|
||||
assert_eq!(state.backend.builds, 0);
|
||||
state.release();
|
||||
assert_eq!(state.backend.suspended, [1]);
|
||||
assert!(state.backend.restores.is_empty());
|
||||
state.backend.suspended.clear();
|
||||
state.backend.fail = true;
|
||||
for _ in 0..2 {
|
||||
deliver(&mut state, Some(request(1.0)));
|
||||
}
|
||||
assert_eq!(state.backend.builds, 1, "cache failed constructions");
|
||||
state.backend.fail = false;
|
||||
for i in 1..140 {
|
||||
deliver(&mut state, Some(request(1.0 + i as f32 / 1000.0)));
|
||||
}
|
||||
assert!(state.cache.len() <= CAPACITY);
|
||||
let active = state.active.unwrap();
|
||||
state.cache.clear();
|
||||
assert_eq!(state.active, Some(active));
|
||||
state.release();
|
||||
assert!(state.backend.suspended.is_empty());
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static FAKE: RefCell<State<Fake>> = RefCell::new(fake_state());
|
||||
static TRACKING: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
fn install_fake(ctx: &Context) {
|
||||
ctx.add_plugin(Delivery {
|
||||
begin: || FAKE.with(|s| s.borrow_mut().begin()),
|
||||
finish: |r| FAKE.with(|s| s.borrow_mut().finish(r)),
|
||||
release: || FAKE.with(|s| s.borrow_mut().release()),
|
||||
tracking: || TRACKING.with(Cell::get),
|
||||
ended: Vec::new(),
|
||||
});
|
||||
}
|
||||
#[test]
|
||||
fn mac_cursor_plugin_consumes_passes_and_releases_for_menu_focus_and_overrides() {
|
||||
FAKE.with(|s| *s.borrow_mut() = fake_state());
|
||||
TRACKING.with(|t| t.set(false));
|
||||
let ctx = Context::default();
|
||||
install_fake(&ctx);
|
||||
install_fake(&ctx);
|
||||
let root = ViewportId::ROOT;
|
||||
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
|
||||
FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 1, "one installed plugin consumes the request"));
|
||||
let _ = headless(&ctx, raw(ViewportId::from_hash_of("floating-panel"), true), |_| {});
|
||||
FAKE.with(|s| assert!(s.borrow().active.is_some()));
|
||||
let _ = headless(&ctx, raw(root, true), |_| {});
|
||||
FAKE.with(|s| assert!(s.borrow().active.is_none(), "empty pass hands back even an unchanged Default icon"));
|
||||
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
|
||||
let _ = headless(&ctx, raw(root, true), |ui| {
|
||||
publish(ui.ctx(), 1.0);
|
||||
ui.ctx().set_cursor_icon(CursorIcon::Text);
|
||||
});
|
||||
FAKE.with(|s| assert!(s.borrow().active.is_none(), "changed-icon handback"));
|
||||
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
|
||||
// The notification calls release without waiting for another UI pass.
|
||||
TRACKING.with(|t| t.set(true));
|
||||
FAKE.with(|s| s.borrow_mut().release());
|
||||
FAKE.with(|s| assert!(s.borrow().active.is_none()));
|
||||
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
|
||||
FAKE.with(|s| assert!(s.borrow().active.is_none()));
|
||||
TRACKING.with(|t| t.set(false));
|
||||
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
|
||||
let _ = headless(&ctx, raw(root, false), |_| {});
|
||||
FAKE.with(|s| assert!(s.borrow().active.is_none()));
|
||||
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
|
||||
FAKE.with(|s| assert!(s.borrow().active.is_some()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_cursor_discarded_pass_does_not_commit_and_installation_does_not_repaint() {
|
||||
FAKE.with(|s| *s.borrow_mut() = fake_state());
|
||||
TRACKING.with(|t| t.set(false));
|
||||
let ctx = Context::default();
|
||||
install_fake(&ctx);
|
||||
let mut passes = 0;
|
||||
let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| {
|
||||
passes += 1;
|
||||
if passes == 1 {
|
||||
publish(ui.ctx(), 1.0);
|
||||
ui.ctx().request_discard("cursor regression");
|
||||
}
|
||||
});
|
||||
assert_eq!(passes, 2);
|
||||
FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 0));
|
||||
let idle = || {
|
||||
let mut input = raw(ViewportId::ROOT, true);
|
||||
input.events.clear();
|
||||
input.time = Some(ctx.input(|i| i.time) + 0.1);
|
||||
input
|
||||
};
|
||||
for _ in 0..3 {
|
||||
let _ = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0));
|
||||
}
|
||||
let out = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0));
|
||||
assert!(out.viewport_output[&ViewportId::ROOT].repaint_delay > std::time::Duration::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_cursor_appkit_representations_have_pixel_sizes_and_point_hotspots() {
|
||||
// Only construct and inspect image/cursor objects: no NSApplication, window or cursor.set().
|
||||
for scale in [0.75, 1.0, 1.25, 1.5, 2.0] {
|
||||
let request = request(scale);
|
||||
let cursor = build(&request.bitmap).unwrap();
|
||||
let image = cursor.image();
|
||||
let one = &request.bitmap.representations[0];
|
||||
let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1]));
|
||||
assert_eq!(image.size(), size);
|
||||
assert_eq!(cursor.hotSpot(), NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1])));
|
||||
let reps = image.representations();
|
||||
assert_eq!(reps.len(), 2);
|
||||
let mut dimensions: Vec<_> = reps
|
||||
.iter()
|
||||
.map(|rep| {
|
||||
assert_eq!(rep.size(), size);
|
||||
(rep.pixelsWide(), rep.pixelsHigh())
|
||||
})
|
||||
.collect();
|
||||
dimensions.sort_unstable();
|
||||
assert_eq!(
|
||||
dimensions,
|
||||
[
|
||||
(isize::try_from(one.size[0]).unwrap(), isize::try_from(one.size[1]).unwrap()),
|
||||
(isize::try_from(one.size[0]).unwrap() * 2, isize::try_from(one.size[1]).unwrap() * 2)
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn headless(ctx: &egui::Context, input: egui::RawInput, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput {
|
||||
let mut output = ctx.run_ui(input, draw);
|
||||
output.textures_delta.clear();
|
||||
output
|
||||
}
|
||||
@@ -31,6 +31,10 @@ use vectorcraft_ui_egui::native_menu::{self, Backend, Event, MenuBar, MenuRole,
|
||||
// asynchronous menu presentation). Keep the native tracking state separate from egui popups.
|
||||
static TRACKING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
pub(crate) fn is_tracking() -> bool {
|
||||
TRACKING.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn observe_tracking(ctx: &egui::Context) {
|
||||
static INSTALL: Once = Once::new();
|
||||
INSTALL.call_once(|| {
|
||||
@@ -41,13 +45,17 @@ fn observe_tracking(ctx: &egui::Context) {
|
||||
let repaint = ctx.clone();
|
||||
let block = RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
|
||||
TRACKING.store(tracking, Ordering::Relaxed);
|
||||
if tracking {
|
||||
super::mac_cursor::release();
|
||||
}
|
||||
// Apply any deferred menu updates as soon as the tracking session ends.
|
||||
if !tracking {
|
||||
repaint.request_repaint();
|
||||
}
|
||||
});
|
||||
// SAFETY: these are AppKit's notification names. The notification center retains
|
||||
// the observer and block for the application's lifetime; callbacks update an atomic and request repaint.
|
||||
// the observer and block for the application's lifetime; callbacks update tracking, restore
|
||||
// owned cursor rectangles and request repaint.
|
||||
#[allow(unsafe_code)]
|
||||
unsafe {
|
||||
NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(Some(name), None, None, &block);
|
||||
|
||||
@@ -36,6 +36,8 @@ mod logging;
|
||||
#[cfg(all(target_os = "macos", feature = "wgpu"))]
|
||||
mod mac_color_space;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac_cursor;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac_fonts;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac_menu;
|
||||
@@ -466,6 +468,8 @@ fn main() -> std::process::ExitCode {
|
||||
// The saved PDF presets live in their own folder (also read by vectorcraft-cli),
|
||||
// which takes over from the copy the preferences file used to hold.
|
||||
prefs_dir::attach_pdf_preset_store(&mut app.session);
|
||||
// The custom dictionary's words, kept in their own file next to the preferences.
|
||||
prefs_dir::attach_custom_dictionary(&mut app.session);
|
||||
// Fit the window to its monitor, or put it back where it was (still hidden).
|
||||
let winit_window = cc.winit_window().cloned();
|
||||
if let Some(w) = &winit_window {
|
||||
@@ -549,6 +553,7 @@ fn main() -> std::process::ExitCode {
|
||||
if !in_window_menus {
|
||||
app.services.native_menu = mac_menu::install(&cc.egui_ctx, &app);
|
||||
}
|
||||
mac_cursor::install(&cc.egui_ctx, winit_window.as_ref());
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
|
||||
@@ -57,6 +57,14 @@ pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the custom dictionary (Edit › Spelling › Add, Edit Custom Dictionary) in the
|
||||
/// `Custom Dictionary.txt` file next to the settings, one word per line, and take in its words.
|
||||
pub fn attach_custom_dictionary(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(path) = store_dir("Custom Dictionary.txt") {
|
||||
session.attach_custom_dictionary(path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -220,3 +220,8 @@ real_name = "Sven Lafebre"
|
||||
[people.kylekanouse]
|
||||
real_name = "Kyle Kanouse"
|
||||
sync_github_name = true
|
||||
|
||||
[people.Hassan1305]
|
||||
real_name = "Hassan Nawaz Khan"
|
||||
display_name = "Hassan Nawaz Khan"
|
||||
sync_github_name = false
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "vectorcraft-apischema"
|
||||
description = "Machine-readable parameter schemas for VectorCraft commands, with a validator and a params text writer"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,174 @@
|
||||
//! For tests: a check of JSON Schema 2020-12 documents, and a validator of instances against them,
|
||||
//! written from the keyword rules of the Core and Validation specifications
|
||||
//! (<https://json-schema.org/draft/2020-12>). It reads only the JSON and shares no code with the
|
||||
//! writer it checks. It covers the keywords the writer uses and reports any other keyword that
|
||||
//! isn't an `x-` annotation.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
const TYPES: &[&str] = &["null", "boolean", "object", "array", "number", "string", "integer"];
|
||||
|
||||
fn unique(items: &[Value]) -> bool {
|
||||
items.iter().enumerate().all(|(i, x)| items.iter().take(i).all(|y| y != x))
|
||||
}
|
||||
|
||||
fn schema_list(items: &Value, at: &str, key: &str) -> Result<(), String> {
|
||||
let list = items.as_array().filter(|l| !l.is_empty()).ok_or_else(|| format!("{at}: `{key}` must be a nonempty array"))?;
|
||||
for (i, x) in list.iter().enumerate() {
|
||||
check_schema(x, &format!("{at}/{key}/{i}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `schema` follows the 2020-12 rules for the keywords it uses, with where it doesn't.
|
||||
pub fn check_schema(schema: &Value, at: &str) -> Result<(), String> {
|
||||
let object = match schema {
|
||||
Value::Bool(_) => return Ok(()),
|
||||
Value::Object(o) => o,
|
||||
other => return Err(format!("{at}: a schema must be an object or a boolean, not {other}")),
|
||||
};
|
||||
for (key, value) in object {
|
||||
let number = || if value.is_number() { Ok(()) } else { Err(format!("{at}: `{key}` must be a number")) };
|
||||
match key.as_str() {
|
||||
"$schema" => {
|
||||
let uri = value.as_str().ok_or_else(|| format!("{at}: `$schema` must be a string"))?;
|
||||
if !uri.contains("://") || uri.ends_with('#') {
|
||||
return Err(format!("{at}: `$schema` must be a normalized URI"));
|
||||
}
|
||||
}
|
||||
"type" => {
|
||||
let known = |v: &Value| v.as_str().is_some_and(|s| TYPES.contains(&s));
|
||||
let ok = known(value) || value.as_array().is_some_and(|l| !l.is_empty() && unique(l) && l.iter().all(known));
|
||||
if !ok {
|
||||
return Err(format!("{at}: `type` must name JSON types, not {value}"));
|
||||
}
|
||||
}
|
||||
"enum" => {
|
||||
if !value.as_array().is_some_and(|l| !l.is_empty() && unique(l)) {
|
||||
return Err(format!("{at}: `enum` must be a nonempty array of unique values"));
|
||||
}
|
||||
}
|
||||
"properties" => {
|
||||
let props = value.as_object().ok_or_else(|| format!("{at}: `properties` must be an object"))?;
|
||||
for (name, x) in props {
|
||||
check_schema(x, &format!("{at}/properties/{name}"))?;
|
||||
}
|
||||
}
|
||||
"required" => {
|
||||
if !value.as_array().is_some_and(|l| unique(l) && l.iter().all(Value::is_string)) {
|
||||
return Err(format!("{at}: `required` must be an array of unique strings"));
|
||||
}
|
||||
}
|
||||
"additionalProperties" | "items" => check_schema(value, &format!("{at}/{key}"))?,
|
||||
"prefixItems" | "anyOf" => schema_list(value, at, key)?,
|
||||
"minimum" | "maximum" | "exclusiveMinimum" | "exclusiveMaximum" => number()?,
|
||||
"minItems" => {
|
||||
if value.as_u64().is_none() {
|
||||
return Err(format!("{at}: `minItems` must be a non-negative integer"));
|
||||
}
|
||||
}
|
||||
"description" => {
|
||||
if !value.is_string() {
|
||||
return Err(format!("{at}: `description` must be a string"));
|
||||
}
|
||||
}
|
||||
"deprecated" => {
|
||||
if !value.is_boolean() {
|
||||
return Err(format!("{at}: `deprecated` must be a boolean"));
|
||||
}
|
||||
}
|
||||
"default" => {
|
||||
if !instance_valid(schema, value) {
|
||||
return Err(format!("{at}: `default` {value} does not validate against its schema"));
|
||||
}
|
||||
}
|
||||
k if k.starts_with("x-") => {}
|
||||
other => return Err(format!("{at}: unexpected keyword `{other}`")),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_type(v: &Value, name: &str) -> bool {
|
||||
match name {
|
||||
"null" => v.is_null(),
|
||||
"boolean" => v.is_boolean(),
|
||||
"object" => v.is_object(),
|
||||
"array" => v.is_array(),
|
||||
"string" => v.is_string(),
|
||||
"number" => v.is_number(),
|
||||
"integer" => v.is_i64() || v.is_u64() || v.as_f64().is_some_and(|x| x.fract() == 0.0),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the instance `v` is valid against `schema`.
|
||||
pub fn instance_valid(schema: &Value, v: &Value) -> bool {
|
||||
let s = match schema {
|
||||
Value::Bool(b) => return *b,
|
||||
Value::Object(o) => o,
|
||||
_ => return false,
|
||||
};
|
||||
let type_ok = match s.get("type") {
|
||||
None => true,
|
||||
Some(Value::String(t)) => has_type(v, t),
|
||||
Some(Value::Array(l)) => l.iter().filter_map(Value::as_str).any(|t| has_type(v, t)),
|
||||
Some(_) => false,
|
||||
};
|
||||
if !type_ok {
|
||||
return false;
|
||||
}
|
||||
if let Some(list) = s.get("enum").and_then(Value::as_array)
|
||||
&& !list.contains(v)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(any) = s.get("anyOf").and_then(Value::as_array)
|
||||
&& !any.iter().any(|x| instance_valid(x, v))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(x) = v.as_f64() {
|
||||
let bound = |key: &str| s.get(key).and_then(Value::as_f64);
|
||||
if bound("minimum").is_some_and(|m| x < m)
|
||||
|| bound("maximum").is_some_and(|m| x > m)
|
||||
|| bound("exclusiveMinimum").is_some_and(|m| x <= m)
|
||||
|| bound("exclusiveMaximum").is_some_and(|m| x >= m)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if let Some(items) = v.as_array() {
|
||||
if s.get("minItems").and_then(Value::as_u64).is_some_and(|n| (items.len() as u64) < n) {
|
||||
return false;
|
||||
}
|
||||
let prefix = s.get("prefixItems").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
|
||||
if items.iter().zip(prefix).any(|(x, p)| !instance_valid(p, x)) {
|
||||
return false;
|
||||
}
|
||||
if let Some(rest) = s.get("items")
|
||||
&& items.iter().skip(prefix.len()).any(|x| !instance_valid(rest, x))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if let Some(object) = v.as_object() {
|
||||
let required = s.get("required").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
|
||||
if required.iter().filter_map(Value::as_str).any(|k| !object.contains_key(k)) {
|
||||
return false;
|
||||
}
|
||||
let props = s.get("properties").and_then(Value::as_object);
|
||||
for (key, x) in object {
|
||||
match props.and_then(|p| p.get(key)) {
|
||||
Some(p) if !instance_valid(p, x) => return false,
|
||||
Some(_) => {}
|
||||
None => {
|
||||
if s.get("additionalProperties").is_some_and(|a| !instance_valid(a, x)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -0,0 +1,940 @@
|
||||
//! Machine-readable parameter schemas for VectorCraft commands. A [`ParamSchema`] lists what each
|
||||
//! parameter of a command is ([`Param`], [`Type`]): its type, whether it is required, what an
|
||||
//! omitted value means, whether null counts as omitted, and the API levels it was added and
|
||||
//! deprecated at. From one schema come:
|
||||
//!
|
||||
//! - [`ParamSchema::validate`], which checks a params object and names the parameter of the first
|
||||
//! problem it finds ([`ParamError`]), and fills in the defaults of omitted values;
|
||||
//! - [`ParamSchema::definition_problem`], which checks the schema itself;
|
||||
//! - [`ParamSchema::params_text`], the params text a command lists;
|
||||
//! - [`ParamSchema::to_json`], the schema as a JSON object in the shape of a JSON Schema 2020-12
|
||||
//! object schema (<https://json-schema.org/draft/2020-12>), with VectorCraft's own fields as
|
||||
//! `x-` keywords;
|
||||
//! - [`hash`], a hash of a set of command schemas, which changes whenever any of them changes.
|
||||
//!
|
||||
//! Checking a value walks the schema, so its depth is the schema's, at most [`MAX_DEPTH`]. An error
|
||||
//! shows a bounded part of a refused value and of a refused key, and the value is not written out
|
||||
//! first, so a huge or deeply nested value costs no more to refuse than a small one.
|
||||
//!
|
||||
//! The crate knows no command and depends on no other VectorCraft crate.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// The JSON Schema dialect [`ParamSchema::to_json`] names in `$schema`.
|
||||
pub const DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";
|
||||
|
||||
/// How many objects and lists may nest inside a schema's params object.
|
||||
pub const MAX_DEPTH: usize = 16;
|
||||
|
||||
/// The largest object id [`Type::Id`] takes: 2^53 - 1, the largest integer every JSON reader holds
|
||||
/// exactly.
|
||||
pub const MAX_ID: u64 = (1 << 53) - 1;
|
||||
|
||||
/// How many characters of a refused value an error shows.
|
||||
const SHOWN_CHARS: usize = 40;
|
||||
|
||||
/// How many characters of a key an error shows.
|
||||
const KEY_CHARS: usize = 64;
|
||||
|
||||
/// One end of a number's range.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Bound {
|
||||
/// The value may equal the bound.
|
||||
Inclusive(f64),
|
||||
/// The value must be past the bound.
|
||||
Exclusive(f64),
|
||||
}
|
||||
|
||||
/// The type of a parameter's value.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Type {
|
||||
/// A JSON number in the range the bounds give, measured in `unit` (`"pt"`, `"deg"`) when set.
|
||||
Number { min: Option<Bound>, max: Option<Bound>, unit: Option<&'static str> },
|
||||
/// A JSON number with no fractional part, in the range given. [`ParamSchema::validate`] gives
|
||||
/// the command `2.0` as `2`.
|
||||
Integer { min: Option<i64>, max: Option<i64> },
|
||||
/// `true` or `false`.
|
||||
Boolean,
|
||||
/// Any string.
|
||||
String,
|
||||
/// One of the strings listed.
|
||||
Enum(&'static [&'static str]),
|
||||
/// An object id: an integer from 0 to [`MAX_ID`], read as [`Type::Integer`] reads one.
|
||||
Id,
|
||||
/// A list of object ids.
|
||||
Ids,
|
||||
/// A color: a string (`"#rrggbb"`, a color key), `[r, g, b]` or an object. The command reads
|
||||
/// which color it is.
|
||||
Color,
|
||||
/// A point: `[x, y]`, two numbers.
|
||||
Point,
|
||||
/// An object with the parameters listed and no other key.
|
||||
Object(&'static [Param]),
|
||||
/// A list of values of one type.
|
||||
Array(&'static Type),
|
||||
}
|
||||
|
||||
impl Type {
|
||||
/// A number with no range and no unit.
|
||||
pub const NUMBER: Type = Type::Number { min: None, max: None, unit: None };
|
||||
}
|
||||
|
||||
/// What an omitted value means.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Omitted {
|
||||
/// The parameter is required, or the command describes the omitted case in its summary.
|
||||
Nothing,
|
||||
/// The value, as JSON text, that [`ParamSchema::validate`] fills in.
|
||||
Value(&'static str),
|
||||
/// A default the command works out itself (`"toggle"`, `"the selected text"`).
|
||||
Note(&'static str),
|
||||
}
|
||||
|
||||
/// What a command changes when it runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Writes {
|
||||
/// Nothing: the command only reads.
|
||||
Nothing,
|
||||
/// State of the running app outside the document and the preferences (view state, the Caps
|
||||
/// Lock state).
|
||||
Session,
|
||||
/// The preferences.
|
||||
Preferences,
|
||||
/// The document, with an undo step.
|
||||
Document,
|
||||
}
|
||||
|
||||
impl Writes {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Writes::Nothing => "nothing",
|
||||
Writes::Session => "session",
|
||||
Writes::Preferences => "preferences",
|
||||
Writes::Document => "document",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One parameter of a command.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Param {
|
||||
pub name: &'static str,
|
||||
pub ty: Type,
|
||||
pub required: bool,
|
||||
pub omitted: Omitted,
|
||||
/// A null value is read as if the parameter were omitted. Otherwise null is refused as a value
|
||||
/// of the wrong type.
|
||||
pub null_omitted: bool,
|
||||
/// What the params text says about the value, in parentheses after its type.
|
||||
pub doc: &'static str,
|
||||
/// The API level the parameter was added at.
|
||||
pub since: u32,
|
||||
/// The API level the parameter was deprecated at.
|
||||
pub deprecated: Option<u32>,
|
||||
/// A value of the wrong type or out of range is not refused here: the command reads it as it
|
||||
/// did before it had a schema. [`ParamSchema::to_json`] still writes the documented type, so a
|
||||
/// JSON Schema validator refuses a value this passes.
|
||||
pub lenient: bool,
|
||||
}
|
||||
|
||||
impl Param {
|
||||
/// A required parameter, added at API level 1.
|
||||
pub const fn new(name: &'static str, ty: Type) -> Param {
|
||||
Param { name, ty, required: true, omitted: Omitted::Nothing, null_omitted: false, doc: "", since: 1, deprecated: None, lenient: false }
|
||||
}
|
||||
/// The parameter may be omitted.
|
||||
pub const fn optional(self) -> Param {
|
||||
Param { required: false, ..self }
|
||||
}
|
||||
/// The parameter may be omitted, and then takes the value `json` (JSON text).
|
||||
pub const fn defaults_to(self, json: &'static str) -> Param {
|
||||
Param { required: false, omitted: Omitted::Value(json), ..self }
|
||||
}
|
||||
/// The parameter may be omitted, and the command then works out the value `note` describes.
|
||||
pub const fn default_note(self, note: &'static str) -> Param {
|
||||
Param { required: false, omitted: Omitted::Note(note), ..self }
|
||||
}
|
||||
/// A null value reads as an omitted one.
|
||||
pub const fn null_omitted(self) -> Param {
|
||||
Param { null_omitted: true, ..self }
|
||||
}
|
||||
pub const fn doc(self, doc: &'static str) -> Param {
|
||||
Param { doc, ..self }
|
||||
}
|
||||
pub const fn since(self, level: u32) -> Param {
|
||||
Param { since: level, ..self }
|
||||
}
|
||||
pub const fn deprecated(self, level: u32) -> Param {
|
||||
Param { deprecated: Some(level), ..self }
|
||||
}
|
||||
pub const fn lenient(self) -> Param {
|
||||
Param { lenient: true, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of one command, and what the command does with them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ParamSchema {
|
||||
pub params: &'static [Param],
|
||||
/// What the command does, after the params object in the params text.
|
||||
pub summary: &'static str,
|
||||
/// What the command returns, after `→` in the params text; empty when the text leaves it out.
|
||||
pub returns: &'static str,
|
||||
/// The API level the command was added at.
|
||||
pub since: u32,
|
||||
/// The API level the command was deprecated at.
|
||||
pub deprecated: Option<u32>,
|
||||
/// What one run costs, in units of a light command (1), for callers that limit a script's work.
|
||||
pub cost: u32,
|
||||
pub writes: Writes,
|
||||
}
|
||||
|
||||
impl ParamSchema {
|
||||
/// A command added at API level 1, costing 1, that changes the document.
|
||||
pub const fn new(params: &'static [Param], summary: &'static str) -> ParamSchema {
|
||||
ParamSchema { params, summary, returns: "", since: 1, deprecated: None, cost: 1, writes: Writes::Document }
|
||||
}
|
||||
pub const fn returns(self, returns: &'static str) -> ParamSchema {
|
||||
ParamSchema { returns, ..self }
|
||||
}
|
||||
pub const fn writes(self, writes: Writes) -> ParamSchema {
|
||||
ParamSchema { writes, ..self }
|
||||
}
|
||||
pub const fn cost(self, cost: u32) -> ParamSchema {
|
||||
ParamSchema { cost, ..self }
|
||||
}
|
||||
pub const fn since(self, level: u32) -> ParamSchema {
|
||||
ParamSchema { since: level, ..self }
|
||||
}
|
||||
pub const fn deprecated(self, level: u32) -> ParamSchema {
|
||||
ParamSchema { deprecated: Some(level), ..self }
|
||||
}
|
||||
|
||||
/// The parameter named `name`.
|
||||
pub fn param(&self, name: &str) -> Option<&'static Param> {
|
||||
self.params.iter().find(|p| p.name == name)
|
||||
}
|
||||
|
||||
/// The names of the top-level parameters, in order.
|
||||
pub fn names(&self) -> Vec<&'static str> {
|
||||
self.params.iter().map(|p| p.name).collect()
|
||||
}
|
||||
|
||||
/// `params` checked against the schema: the first problem as an error naming the parameter,
|
||||
/// or, when it has none, `params` with the defaults of its omitted values filled in (`None`
|
||||
/// when no default was filled in, so `params` is used as it is). Null params read as `{}`.
|
||||
pub fn validate(&self, params: &Value) -> Result<Option<Value>, ParamError> {
|
||||
self.validate_as(params, false)
|
||||
}
|
||||
|
||||
/// [`ParamSchema::validate`] for saved steps recorded by this version or an older one: a key
|
||||
/// the schema doesn't name passes, at any depth, and the command does not read it. Values of
|
||||
/// the parameters the schema names are checked as `validate` checks them.
|
||||
pub fn validate_saved(&self, params: &Value) -> Result<Option<Value>, ParamError> {
|
||||
self.validate_as(params, true)
|
||||
}
|
||||
|
||||
fn validate_as(&self, params: &Value, saved: bool) -> Result<Option<Value>, ParamError> {
|
||||
static EMPTY: std::sync::OnceLock<Map<String, Value>> = std::sync::OnceLock::new();
|
||||
let given = match params {
|
||||
Value::Object(o) => o,
|
||||
Value::Null => EMPTY.get_or_init(Map::new),
|
||||
v => return Err(ParamError { path: String::new(), problem: Problem::NotAnObject { got: shown(v) } }),
|
||||
};
|
||||
Ok(check_object(&At::Root, 0, self.params, given, saved)?.map(Value::Object))
|
||||
}
|
||||
|
||||
/// What is wrong with the schema itself, or `None`: a parameter name that is empty, repeated
|
||||
/// or holds `.`, `[` or `]`; a required parameter with a default; a default that isn't JSON or
|
||||
/// doesn't pass its parameter's type; an enum with no names or a repeated name; a range with
|
||||
/// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`].
|
||||
pub fn definition_problem(&self) -> Option<String> {
|
||||
object_problem("", self.params, 0)
|
||||
}
|
||||
|
||||
/// The params text: the params object (`{name?: string, zoom: number > 0}`), then the summary,
|
||||
/// then `→` and what the command returns.
|
||||
pub fn params_text(&self) -> String {
|
||||
let mut s = object_text(self.params, 0);
|
||||
if !self.summary.is_empty() {
|
||||
s.push(' ');
|
||||
s.push_str(self.summary);
|
||||
}
|
||||
if !self.returns.is_empty() {
|
||||
s.push_str(" → ");
|
||||
s.push_str(self.returns);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The schema as a JSON Schema 2020-12 object schema. Defaults written as JSON go in
|
||||
/// `default`, a parameter that accepts null as omitted is an `anyOf` with `{"type": "null"}`,
|
||||
/// and VectorCraft's own fields are `x-since`, `x-deprecatedSince`, `x-lenient`, `x-unit`,
|
||||
/// `x-kind`, `x-cost`, `x-writes` and `x-returns`. The root `type` is `["object", "null"]` when
|
||||
/// no parameter is required, because null params read as `{}`, and `"object"` otherwise. A JSON
|
||||
/// Schema validator accepts the values [`ParamSchema::validate`] accepts, except that an
|
||||
/// `x-lenient` parameter's schema states only the documented type.
|
||||
pub fn to_json(&self) -> Value {
|
||||
let mut o = object_schema(self.params, 0);
|
||||
if !self.params.iter().any(|p| p.required) {
|
||||
o.insert("type".into(), json!(["object", "null"]));
|
||||
}
|
||||
o.insert("$schema".into(), DIALECT.into());
|
||||
if !self.summary.is_empty() {
|
||||
o.insert("description".into(), self.summary.into());
|
||||
}
|
||||
if !self.returns.is_empty() {
|
||||
o.insert("x-returns".into(), self.returns.into());
|
||||
}
|
||||
o.insert("x-since".into(), self.since.into());
|
||||
if let Some(level) = self.deprecated {
|
||||
o.insert("deprecated".into(), true.into());
|
||||
o.insert("x-deprecatedSince".into(), level.into());
|
||||
}
|
||||
o.insert("x-cost".into(), self.cost.into());
|
||||
o.insert("x-writes".into(), self.writes.name().into());
|
||||
Value::Object(o)
|
||||
}
|
||||
}
|
||||
|
||||
/// A problem [`ParamSchema::validate`] found, at `path`: the parameter's name, with the keys and
|
||||
/// indices leading to a value inside one (`edits[1].name`). The path is empty for the params
|
||||
/// object itself.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ParamError {
|
||||
pub path: String,
|
||||
pub problem: Problem,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Problem {
|
||||
/// The params are not an object.
|
||||
NotAnObject { got: String },
|
||||
/// The key at `path` is not a parameter of the object it is in, which takes `keys`.
|
||||
Unknown { keys: Vec<&'static str> },
|
||||
/// A required parameter is missing.
|
||||
Missing,
|
||||
/// The value is not of the parameter's type: `expected` says what it must be.
|
||||
WrongType { expected: String, got: String },
|
||||
/// The schema nests deeper than [`MAX_DEPTH`] here ([`ParamSchema::definition_problem`]).
|
||||
TooDeep,
|
||||
}
|
||||
|
||||
impl fmt::Display for ParamError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let path = &self.path;
|
||||
match &self.problem {
|
||||
Problem::NotAnObject { got } => write!(f, "the params must be an object, not {got}"),
|
||||
Problem::Unknown { keys } if keys.is_empty() => write!(f, "unknown parameter `{path}`; the object takes no keys"),
|
||||
Problem::Unknown { keys } => write!(f, "unknown parameter `{path}`; it takes: {}", keys.join(", ")),
|
||||
Problem::Missing => write!(f, "missing `{path}`"),
|
||||
Problem::WrongType { expected, got } => write!(f, "`{path}` must be {expected}, not {got}"),
|
||||
Problem::TooDeep => write!(f, "`{path}` is nested too deeply"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ParamError {}
|
||||
|
||||
/// FNV-1a over the bytes of `text`, from `h`.
|
||||
fn fnv1a(mut h: u64, text: &str) -> u64 {
|
||||
for b in text.bytes() {
|
||||
h ^= u64::from(b);
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// `v` as JSON text with the keys of each object in sorted order, whichever order the map keeps
|
||||
/// them in.
|
||||
fn canonical(v: &Value, out: &mut String) {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
let mut keys: Vec<&String> = o.keys().collect();
|
||||
keys.sort();
|
||||
out.push('{');
|
||||
for (i, k) in keys.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
out.push_str(&Value::from(k.as_str()).to_string());
|
||||
out.push(':');
|
||||
if let Some(x) = o.get(k) {
|
||||
canonical(x, out);
|
||||
}
|
||||
}
|
||||
out.push('}');
|
||||
}
|
||||
Value::Array(a) => {
|
||||
out.push('[');
|
||||
for (i, x) in a.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
canonical(x, out);
|
||||
}
|
||||
out.push(']');
|
||||
}
|
||||
other => out.push_str(&other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 64-bit FNV-1a hash of the commands' schemas, taken in the order of their ids: each id and
|
||||
/// its [`ParamSchema::to_json`] text, with the keys of each object sorted. Any change to a schema,
|
||||
/// or a schema added or removed, changes it.
|
||||
pub fn hash<'a>(schemas: impl IntoIterator<Item = (&'a str, &'a ParamSchema)>) -> u64 {
|
||||
let mut all: Vec<(&str, &ParamSchema)> = schemas.into_iter().collect();
|
||||
all.sort_by_key(|(id, _)| *id);
|
||||
all.iter().fold(0xcbf2_9ce4_8422_2325, |h, (id, schema)| {
|
||||
let mut text = String::new();
|
||||
canonical(&schema.to_json(), &mut text);
|
||||
let h = fnv1a(h, id);
|
||||
let h = fnv1a(h, "\n");
|
||||
let h = fnv1a(h, &text);
|
||||
fnv1a(h, "\n")
|
||||
})
|
||||
}
|
||||
|
||||
/// `key` as an error message shows it: cut to [`KEY_CHARS`] characters.
|
||||
pub fn shown_key(key: &str) -> String {
|
||||
let mut chars = key.chars();
|
||||
let head: String = chars.by_ref().take(KEY_CHARS).collect();
|
||||
if chars.next().is_some() { format!("{head}…") } else { head }
|
||||
}
|
||||
|
||||
/// The JSON text of a value, stopping when its characters run out.
|
||||
struct Shown {
|
||||
text: String,
|
||||
left: usize,
|
||||
}
|
||||
|
||||
impl Shown {
|
||||
/// Adds `s`; false when it didn't fit.
|
||||
fn push(&mut self, s: &str) -> bool {
|
||||
for c in s.chars() {
|
||||
if self.left == 0 {
|
||||
return false;
|
||||
}
|
||||
self.left -= 1;
|
||||
self.text.push(c);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Adds the JSON text of string `s`, reading no more of it than can be shown.
|
||||
fn push_string(&mut self, s: &str) -> bool {
|
||||
let head: String = s.chars().take(self.left + 1).collect();
|
||||
self.push(&Value::from(head).to_string())
|
||||
}
|
||||
|
||||
/// Adds the JSON text of `v`; false when it didn't fit. Each object or list writes a bracket,
|
||||
/// so the characters left bound the recursion.
|
||||
fn push_value(&mut self, v: &Value) -> bool {
|
||||
match v {
|
||||
Value::String(s) => self.push_string(s),
|
||||
Value::Array(items) => {
|
||||
self.push("[") && items.iter().enumerate().all(|(i, x)| (i == 0 || self.push(",")) && self.push_value(x)) && self.push("]")
|
||||
}
|
||||
Value::Object(o) => {
|
||||
self.push("{")
|
||||
&& o.iter()
|
||||
.enumerate()
|
||||
.all(|(i, (k, x))| (i == 0 || self.push(",")) && self.push_string(k) && self.push(":") && self.push_value(x))
|
||||
&& self.push("}")
|
||||
}
|
||||
other => self.push(&other.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A value as an error message shows it: its JSON, cut to [`SHOWN_CHARS`] characters. Only what is
|
||||
/// shown is read, however large the value is.
|
||||
fn shown(v: &Value) -> String {
|
||||
let mut out = Shown { text: String::new(), left: SHOWN_CHARS };
|
||||
if !out.push_value(v) {
|
||||
out.text.push('…');
|
||||
}
|
||||
out.text
|
||||
}
|
||||
|
||||
fn join(path: &str, key: &str) -> String {
|
||||
if path.is_empty() { key.to_string() } else { format!("{path}.{key}") }
|
||||
}
|
||||
|
||||
/// Where a value is, from the value up to the params object. The path's text is written only for
|
||||
/// an error.
|
||||
#[derive(Clone, Copy)]
|
||||
enum At<'a> {
|
||||
Root,
|
||||
Key(&'a At<'a>, &'a str),
|
||||
Index(&'a At<'a>, usize),
|
||||
}
|
||||
|
||||
impl At<'_> {
|
||||
/// The path, `edits[1].name`, with each key as [`shown_key`] shows it.
|
||||
fn text(&self) -> String {
|
||||
let mut steps = Vec::new();
|
||||
let mut at = self;
|
||||
while let At::Key(up, _) | At::Index(up, _) = at {
|
||||
steps.push(at);
|
||||
at = up;
|
||||
}
|
||||
let mut out = String::new();
|
||||
for step in steps.into_iter().rev() {
|
||||
match step {
|
||||
At::Key(_, key) => {
|
||||
if !out.is_empty() {
|
||||
out.push('.');
|
||||
}
|
||||
out.push_str(&shown_key(key));
|
||||
}
|
||||
At::Index(_, i) => out.push_str(&format!("[{i}]")),
|
||||
At::Root => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `v` nests no deeper than [`MAX_DEPTH`] counted from `depth`. The walk stops at the
|
||||
/// limit, so it recurses at most [`MAX_DEPTH`] levels and allocates nothing.
|
||||
fn nests_within(v: &Value, depth: usize) -> bool {
|
||||
match v {
|
||||
Value::Array(a) => depth < MAX_DEPTH && a.iter().all(|x| nests_within(x, depth + 1)),
|
||||
Value::Object(o) => depth < MAX_DEPTH && o.values().all(|x| nests_within(x, depth + 1)),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The object `given` checked against `params` (unknown keys first, then each parameter in
|
||||
/// order): with the defaults of omitted values filled in when there are any. `saved` keeps a key
|
||||
/// the schema doesn't name, unless its value nests past [`MAX_DEPTH`].
|
||||
fn check_object(
|
||||
at: &At<'_>,
|
||||
depth: usize,
|
||||
params: &'static [Param],
|
||||
given: &Map<String, Value>,
|
||||
saved: bool,
|
||||
) -> Result<Option<Map<String, Value>>, ParamError> {
|
||||
let refused = |key: &String, v: &Value| !params.iter().any(|p| p.name == key.as_str()) && (!saved || !nests_within(v, depth));
|
||||
if let Some((key, _)) = given.iter().find(|(k, v)| refused(k, v)) {
|
||||
return Err(ParamError { path: At::Key(at, key).text(), problem: Problem::Unknown { keys: params.iter().map(|p| p.name).collect() } });
|
||||
}
|
||||
// The changes are applied once every value has passed, so no refused value is ever copied.
|
||||
let mut changes: Vec<(&'static str, Value)> = Vec::new();
|
||||
for p in params {
|
||||
let here = At::Key(at, p.name);
|
||||
match given.get(p.name) {
|
||||
Some(Value::Null) if p.null_omitted => {}
|
||||
Some(v) => {
|
||||
if let Some(changed) = check_value(&here, depth, &p.ty, v, p.lenient, saved)? {
|
||||
changes.push((p.name, changed));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
None if p.required => return Err(ParamError { path: here.text(), problem: Problem::Missing }),
|
||||
None => {}
|
||||
}
|
||||
// Omitted, or null read as omitted.
|
||||
if let Omitted::Value(json) = p.omitted
|
||||
&& let Ok(v) = serde_json::from_str::<Value>(json)
|
||||
{
|
||||
changes.push((p.name, v));
|
||||
}
|
||||
}
|
||||
if changes.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut filled = given.clone();
|
||||
for (name, v) in changes {
|
||||
filled.insert(name.to_string(), v);
|
||||
}
|
||||
Ok(Some(filled))
|
||||
}
|
||||
|
||||
/// What a value of type `ty` must be, as an error message says it.
|
||||
fn expected(ty: &Type) -> String {
|
||||
match ty {
|
||||
Type::Number { min, max, unit } => {
|
||||
format!("a number{}{}", range_text(min.as_ref(), max.as_ref()), unit.map(|u| format!(" ({u})")).unwrap_or_default())
|
||||
}
|
||||
Type::Integer { min, max } => {
|
||||
format!("an integer{}", range_text(min.map(|m| Bound::Inclusive(m as f64)).as_ref(), max.map(|m| Bound::Inclusive(m as f64)).as_ref()))
|
||||
}
|
||||
Type::Boolean => "true or false".into(),
|
||||
Type::String => "a string".into(),
|
||||
Type::Enum(names) => format!("one of {}", names.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", ")),
|
||||
Type::Id => "an object id (a non-negative integer)".into(),
|
||||
Type::Ids => "a list of object ids".into(),
|
||||
Type::Color => "a color (a string, [r, g, b] or an object)".into(),
|
||||
Type::Point => "[x, y] (two numbers)".into(),
|
||||
Type::Object(_) => "an object".into(),
|
||||
Type::Array(_) => "a list".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// ` > 0`, ` 0 to 100`, ` >= 1 and < 10`: the range text after a number's type.
|
||||
fn range_text(min: Option<&Bound>, max: Option<&Bound>) -> String {
|
||||
match (min, max) {
|
||||
(Some(Bound::Inclusive(a)), Some(Bound::Inclusive(b))) => format!(" {a} to {b}"),
|
||||
(Some(a), Some(b)) => format!("{} and{}", low_text(a), high_text(b)),
|
||||
(Some(a), None) => low_text(a),
|
||||
(None, Some(b)) => high_text(b),
|
||||
(None, None) => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn low_text(b: &Bound) -> String {
|
||||
match b {
|
||||
Bound::Inclusive(a) => format!(" >= {a}"),
|
||||
Bound::Exclusive(a) => format!(" > {a}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn high_text(b: &Bound) -> String {
|
||||
match b {
|
||||
Bound::Inclusive(a) => format!(" <= {a}"),
|
||||
Bound::Exclusive(a) => format!(" < {a}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn in_range(x: f64, min: Option<&Bound>, max: Option<&Bound>) -> bool {
|
||||
let low = match min {
|
||||
Some(Bound::Inclusive(a)) => x >= *a,
|
||||
Some(Bound::Exclusive(a)) => x > *a,
|
||||
None => true,
|
||||
};
|
||||
let high = match max {
|
||||
Some(Bound::Inclusive(b)) => x <= *b,
|
||||
Some(Bound::Exclusive(b)) => x < *b,
|
||||
None => true,
|
||||
};
|
||||
low && high
|
||||
}
|
||||
|
||||
/// The integer a JSON number with no fractional part stands for, as an integer value when it fits
|
||||
/// in one (`2.0` is `2`); `None` for anything else.
|
||||
fn whole(v: &Value) -> Option<Value> {
|
||||
if v.is_i64() || v.is_u64() {
|
||||
return Some(v.clone());
|
||||
}
|
||||
const TWO_63: f64 = 9_223_372_036_854_775_808.0;
|
||||
const TWO_64: f64 = 18_446_744_073_709_551_616.0;
|
||||
let x = v.as_f64().filter(|x| x.fract() == 0.0)?;
|
||||
Some(if (-TWO_63..TWO_63).contains(&x) {
|
||||
json!(x as i64)
|
||||
} else if (0.0..TWO_64).contains(&x) {
|
||||
json!(x as u64)
|
||||
} else {
|
||||
v.clone()
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the [`whole`] value `w` is in the range.
|
||||
fn whole_in_range(w: &Value, min: Option<i64>, max: Option<i64>) -> bool {
|
||||
match (w.as_i64(), w.as_u64(), w.as_f64()) {
|
||||
(Some(x), _, _) => min.is_none_or(|m| x >= m) && max.is_none_or(|m| x <= m),
|
||||
// Past i64::MAX: above any i64 bound.
|
||||
(None, Some(_), _) => max.is_none(),
|
||||
// Past what u64 holds: above any i64 bound.
|
||||
(None, None, Some(x)) if x > 0.0 => max.is_none(),
|
||||
// Below what i64 holds: under any i64 bound, so it meets every maximum and no minimum.
|
||||
(None, None, Some(_)) => min.is_none(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_number(v: &Value) -> bool {
|
||||
v.as_f64().is_some_and(f64::is_finite)
|
||||
}
|
||||
|
||||
/// `v` checked against `ty` at `at`: with the defaults of omitted values inside it filled in, and
|
||||
/// whole numbers written with a fraction made integers, when there are any. A lenient value of
|
||||
/// the wrong type passes as it is, unless it nests past [`MAX_DEPTH`].
|
||||
fn check_value(at: &At<'_>, depth: usize, ty: &Type, v: &Value, lenient: bool, saved: bool) -> Result<Option<Value>, ParamError> {
|
||||
let done = |ok: bool| {
|
||||
if ok || (lenient && nests_within(v, depth)) {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(ParamError { path: at.text(), problem: Problem::WrongType { expected: expected(ty), got: shown(v) } })
|
||||
}
|
||||
};
|
||||
let too_deep = || ParamError { path: at.text(), problem: Problem::TooDeep };
|
||||
if matches!(ty, Type::Ids | Type::Color | Type::Point) && v.is_array() && depth >= MAX_DEPTH {
|
||||
return Err(too_deep());
|
||||
}
|
||||
match ty {
|
||||
Type::Number { min, max, .. } => done(v.as_f64().is_some_and(|x| x.is_finite() && in_range(x, min.as_ref(), max.as_ref()))),
|
||||
Type::Integer { min, max } => match whole(v).filter(|w| whole_in_range(w, *min, *max)) {
|
||||
Some(w) => Ok((w != *v).then_some(w)),
|
||||
None => done(false),
|
||||
},
|
||||
Type::Boolean => done(v.is_boolean()),
|
||||
Type::String => done(v.is_string()),
|
||||
Type::Enum(names) => done(v.as_str().is_some_and(|s| names.contains(&s))),
|
||||
Type::Id => match whole(v).filter(|w| w.as_u64().is_some_and(|x| x <= MAX_ID)) {
|
||||
Some(w) => Ok((w != *v).then_some(w)),
|
||||
None => done(false),
|
||||
},
|
||||
Type::Ids => match v.as_array() {
|
||||
Some(items) => check_items(at, depth, &Type::Id, items, lenient, saved),
|
||||
None => done(false),
|
||||
},
|
||||
Type::Color => done(match v {
|
||||
Value::String(_) => true,
|
||||
Value::Object(_) => nests_within(v, depth),
|
||||
Value::Array(a) => a.len() >= 3 && a.iter().all(is_number),
|
||||
_ => false,
|
||||
}),
|
||||
Type::Point => done(v.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(is_number))),
|
||||
Type::Object(params) => match v {
|
||||
Value::Object(_) if depth >= MAX_DEPTH => Err(too_deep()),
|
||||
Value::Object(o) => Ok(check_object(at, depth + 1, params, o, saved)?.map(Value::Object)),
|
||||
_ => done(false),
|
||||
},
|
||||
Type::Array(item) => match v.as_array() {
|
||||
Some(_) if depth >= MAX_DEPTH => Err(too_deep()),
|
||||
Some(items) => check_items(at, depth + 1, item, items, lenient, saved),
|
||||
None => done(false),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Each of `items` checked against `item`: the list with what [`check_value`] changed, when it
|
||||
/// changed anything.
|
||||
fn check_items(at: &At<'_>, depth: usize, item: &Type, items: &[Value], lenient: bool, saved: bool) -> Result<Option<Value>, ParamError> {
|
||||
let mut changes: Vec<(usize, Value)> = Vec::new();
|
||||
for (i, x) in items.iter().enumerate() {
|
||||
if let Some(changed) = check_value(&At::Index(at, i), depth, item, x, lenient, saved)? {
|
||||
changes.push((i, changed));
|
||||
}
|
||||
}
|
||||
if changes.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut filled = items.to_vec();
|
||||
for (i, v) in changes {
|
||||
if let Some(slot) = filled.get_mut(i) {
|
||||
*slot = v;
|
||||
}
|
||||
}
|
||||
Ok(Some(Value::Array(filled)))
|
||||
}
|
||||
|
||||
/// What is wrong with `params`, the object at `path` nested `depth` objects and lists deep.
|
||||
fn object_problem(path: &str, params: &[Param], depth: usize) -> Option<String> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Some(format!("`{path}` nests deeper than {MAX_DEPTH} levels"));
|
||||
}
|
||||
for (i, p) in params.iter().enumerate() {
|
||||
let at = join(path, p.name);
|
||||
if p.name.is_empty() || p.name.contains(['.', '[', ']']) {
|
||||
return Some(format!("the parameter name `{at}` is empty or holds a path character"));
|
||||
}
|
||||
if params.iter().take(i).any(|q| q.name == p.name) {
|
||||
return Some(format!("`{at}` is listed twice"));
|
||||
}
|
||||
if p.required && p.omitted != Omitted::Nothing {
|
||||
return Some(format!("`{at}` is required and has a default"));
|
||||
}
|
||||
if let Some(problem) = type_problem(&at, &p.ty, depth) {
|
||||
return Some(problem);
|
||||
}
|
||||
if let Omitted::Value(text) = p.omitted {
|
||||
let Ok(v) = serde_json::from_str::<Value>(text) else { return Some(format!("the default of `{at}` isn't JSON: {text}")) };
|
||||
if let Err(e) = check_value(&At::Root, 0, &p.ty, &v, false, false) {
|
||||
return Some(format!("the default of `{at}` doesn't pass its type: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn type_problem(at: &str, ty: &Type, depth: usize) -> Option<String> {
|
||||
let bound = |b: &Bound| match *b {
|
||||
Bound::Inclusive(x) => (x, false),
|
||||
Bound::Exclusive(x) => (x, true),
|
||||
};
|
||||
match ty {
|
||||
Type::Number { min, max, .. } => {
|
||||
let (low, high) = (min.as_ref().map(bound), max.as_ref().map(bound));
|
||||
if low.iter().chain(high.iter()).any(|(x, _)| !x.is_finite()) {
|
||||
return Some(format!("the range of `{at}` has an end that isn't finite"));
|
||||
}
|
||||
match (low, high) {
|
||||
(Some((a, open_a)), Some((b, open_b))) if a > b || (a == b && (open_a || open_b)) => {
|
||||
Some(format!("no value can be in the range of `{at}`"))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
Type::Integer { min: Some(a), max: Some(b) } if a > b => Some(format!("no value can be in the range of `{at}`")),
|
||||
Type::Enum([]) => Some(format!("the enum of `{at}` has no names")),
|
||||
Type::Enum(names) if names.iter().enumerate().any(|(i, n)| names.iter().take(i).any(|m| m == n)) => {
|
||||
Some(format!("the enum of `{at}` repeats a name"))
|
||||
}
|
||||
Type::Object(params) => object_problem(at, params, depth + 1),
|
||||
Type::Array(_) if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")),
|
||||
Type::Array(item) => type_problem(&format!("{at}[]"), item, depth + 1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `{a: number, b?: bool}`: the params object of a params text, `depth` objects and lists deep.
|
||||
fn object_text(params: &[Param], depth: usize) -> String {
|
||||
format!("{{{}}}", params.iter().map(|p| param_text(p, depth)).collect::<Vec<_>>().join(", "))
|
||||
}
|
||||
|
||||
fn param_text(p: &Param, depth: usize) -> String {
|
||||
let mut s = format!("{}{}: {}", p.name, if p.required { "" } else { "?" }, type_text(&p.ty, depth));
|
||||
match p.omitted {
|
||||
Omitted::Value(v) | Omitted::Note(v) => s.push_str(&format!(" (default: {v})")),
|
||||
Omitted::Nothing => {}
|
||||
}
|
||||
if !p.doc.is_empty() {
|
||||
s.push_str(&format!(" ({})", p.doc));
|
||||
}
|
||||
if p.deprecated.is_some() {
|
||||
s.push_str(" (deprecated)");
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn type_text(ty: &Type, depth: usize) -> String {
|
||||
match ty {
|
||||
Type::Object(_) | Type::Array(_) if depth >= MAX_DEPTH => "…".into(),
|
||||
Type::Number { min, max, unit } => {
|
||||
format!("number{}{}", range_text(min.as_ref(), max.as_ref()), unit.map(|u| format!(" {u}")).unwrap_or_default())
|
||||
}
|
||||
Type::Integer { min, max } => {
|
||||
format!("integer{}", range_text(min.map(|m| Bound::Inclusive(m as f64)).as_ref(), max.map(|m| Bound::Inclusive(m as f64)).as_ref()))
|
||||
}
|
||||
Type::Boolean => "bool".into(),
|
||||
Type::String => "string".into(),
|
||||
Type::Enum(names) => names.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join("|"),
|
||||
Type::Id => "id".into(),
|
||||
Type::Ids => "[id…]".into(),
|
||||
Type::Color => "color".into(),
|
||||
Type::Point => "[x, y]".into(),
|
||||
Type::Object(params) => object_text(params, depth + 1),
|
||||
Type::Array(item) => format!("[{}…]", type_text(item, depth + 1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `{"type": "object", "properties": …, "required": […], "additionalProperties": false}`.
|
||||
fn object_schema(params: &[Param], depth: usize) -> Map<String, Value> {
|
||||
let mut o = Map::new();
|
||||
o.insert("type".into(), "object".into());
|
||||
o.insert("properties".into(), Value::Object(params.iter().map(|p| (p.name.to_string(), param_schema(p, depth))).collect()));
|
||||
let required: Vec<Value> = params.iter().filter(|p| p.required).map(|p| p.name.into()).collect();
|
||||
if !required.is_empty() {
|
||||
o.insert("required".into(), required.into());
|
||||
}
|
||||
o.insert("additionalProperties".into(), false.into());
|
||||
o
|
||||
}
|
||||
|
||||
fn param_schema(p: &Param, depth: usize) -> Value {
|
||||
let inner = type_schema(&p.ty, depth);
|
||||
let mut o = if p.null_omitted {
|
||||
let mut o = Map::new();
|
||||
o.insert("anyOf".into(), json!([inner, {"type": "null"}]));
|
||||
o
|
||||
} else {
|
||||
match inner {
|
||||
Value::Object(o) => o,
|
||||
_ => Map::new(),
|
||||
}
|
||||
};
|
||||
if !p.doc.is_empty() {
|
||||
o.insert("description".into(), p.doc.into());
|
||||
}
|
||||
match p.omitted {
|
||||
Omitted::Value(json) => {
|
||||
if let Ok(v) = serde_json::from_str::<Value>(json) {
|
||||
o.insert("default".into(), v);
|
||||
}
|
||||
}
|
||||
Omitted::Note(note) => {
|
||||
o.insert("x-default".into(), note.into());
|
||||
}
|
||||
Omitted::Nothing => {}
|
||||
}
|
||||
o.insert("x-since".into(), p.since.into());
|
||||
if let Some(level) = p.deprecated {
|
||||
o.insert("deprecated".into(), true.into());
|
||||
o.insert("x-deprecatedSince".into(), level.into());
|
||||
}
|
||||
if p.lenient {
|
||||
o.insert("x-lenient".into(), true.into());
|
||||
}
|
||||
Value::Object(o)
|
||||
}
|
||||
|
||||
fn bound_keywords(o: &mut Map<String, Value>, min: Option<&Bound>, max: Option<&Bound>) {
|
||||
let low = match min {
|
||||
Some(Bound::Inclusive(a)) => Some(("minimum", a)),
|
||||
Some(Bound::Exclusive(a)) => Some(("exclusiveMinimum", a)),
|
||||
None => None,
|
||||
};
|
||||
let high = match max {
|
||||
Some(Bound::Inclusive(b)) => Some(("maximum", b)),
|
||||
Some(Bound::Exclusive(b)) => Some(("exclusiveMaximum", b)),
|
||||
None => None,
|
||||
};
|
||||
for (key, x) in low.into_iter().chain(high) {
|
||||
o.insert(key.into(), json!(x));
|
||||
}
|
||||
}
|
||||
|
||||
fn type_schema(ty: &Type, depth: usize) -> Value {
|
||||
match ty {
|
||||
Type::Object(_) | Type::Array(_) if depth >= MAX_DEPTH => Value::Bool(true),
|
||||
Type::Number { min, max, unit } => {
|
||||
let mut o = Map::new();
|
||||
o.insert("type".into(), "number".into());
|
||||
bound_keywords(&mut o, min.as_ref(), max.as_ref());
|
||||
if let Some(u) = unit {
|
||||
o.insert("x-unit".into(), (*u).into());
|
||||
}
|
||||
Value::Object(o)
|
||||
}
|
||||
Type::Integer { min, max } => {
|
||||
let mut o = Map::new();
|
||||
o.insert("type".into(), "integer".into());
|
||||
if let Some(m) = min {
|
||||
o.insert("minimum".into(), (*m).into());
|
||||
}
|
||||
if let Some(m) = max {
|
||||
o.insert("maximum".into(), (*m).into());
|
||||
}
|
||||
Value::Object(o)
|
||||
}
|
||||
Type::Boolean => json!({"type": "boolean"}),
|
||||
Type::String => json!({"type": "string"}),
|
||||
Type::Enum(names) => json!({"enum": names}),
|
||||
Type::Id => json!({"type": "integer", "minimum": 0, "maximum": MAX_ID, "x-kind": "id"}),
|
||||
Type::Ids => json!({"type": "array", "items": {"type": "integer", "minimum": 0, "maximum": MAX_ID, "x-kind": "id"}}),
|
||||
Type::Color => json!({
|
||||
"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "number"}, "minItems": 3}, {"type": "object"}],
|
||||
"x-kind": "color",
|
||||
}),
|
||||
Type::Point => json!({
|
||||
"type": "array",
|
||||
"prefixItems": [{"type": "number"}, {"type": "number"}],
|
||||
"items": false,
|
||||
"minItems": 2,
|
||||
"x-kind": "point",
|
||||
}),
|
||||
Type::Object(params) => Value::Object(object_schema(params, depth + 1)),
|
||||
Type::Array(item) => json!({"type": "array", "items": type_schema(item, depth + 1)}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod conformance;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,536 @@
|
||||
//! Tests of the validator, the params text and the JSON form, on schemas written here.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// The schema with the one parameter `x` of type `ty`.
|
||||
fn one(ty: Type) -> ParamSchema {
|
||||
let params: &'static [Param] = Box::leak(Box::new([Param::new("x", ty)]));
|
||||
ParamSchema::new(params, "")
|
||||
}
|
||||
|
||||
/// Whether `{x: v}` passes the schema of `ty`; on a refusal, the error must name `x`.
|
||||
fn passes(ty: Type, v: Value) -> bool {
|
||||
match one(ty).validate(&json!({ "x": v })) {
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
assert!(e.path.starts_with('x'), "{e}");
|
||||
assert!(e.to_string().contains("`x"), "{e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_are_checked_against_their_range() {
|
||||
let any = Type::NUMBER;
|
||||
assert!(passes(any, json!(-3.5)) && passes(any, json!(7)));
|
||||
assert!(!passes(any, json!("7")) && !passes(any, json!(null)) && !passes(any, json!(true)));
|
||||
let positive = Type::Number { min: Some(Bound::Exclusive(0.0)), max: None, unit: None };
|
||||
assert!(passes(positive, json!(0.001)));
|
||||
assert!(!passes(positive, json!(0)) && !passes(positive, json!(-1)));
|
||||
let percent = Type::Number { min: Some(Bound::Inclusive(0.0)), max: Some(Bound::Inclusive(100.0)), unit: Some("%") };
|
||||
assert!(passes(percent, json!(0)) && passes(percent, json!(100)));
|
||||
assert!(!passes(percent, json!(100.5)));
|
||||
let below = Type::Number { min: None, max: Some(Bound::Exclusive(1.0)), unit: None };
|
||||
assert!(passes(below, json!(0.99)) && !passes(below, json!(1)));
|
||||
assert_eq!(one(positive).validate(&json!({"x": 0})).unwrap_err().to_string(), "`x` must be a number > 0, not 0");
|
||||
assert_eq!(one(percent).validate(&json!({"x": 101})).unwrap_err().to_string(), "`x` must be a number 0 to 100 (%), not 101");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integers_take_no_fraction_and_keep_their_range() {
|
||||
let any = Type::Integer { min: None, max: None };
|
||||
assert!(passes(any, json!(-4)) && passes(any, json!(u64::MAX)));
|
||||
assert!(!passes(any, json!(1.5)) && !passes(any, json!("2")));
|
||||
let small = Type::Integer { min: Some(1), max: Some(25) };
|
||||
assert!(passes(small, json!(1)) && passes(small, json!(25)));
|
||||
assert!(!passes(small, json!(0)) && !passes(small, json!(26)) && !passes(small, json!(u64::MAX)));
|
||||
assert!(passes(small, json!(25.0)) && !passes(small, json!(26.0)) && !passes(small, json!(1e300)) && !passes(small, json!(-1e300)));
|
||||
let negative = Type::Integer { min: None, max: Some(-1_000_000_000_000_000_000) };
|
||||
assert!(passes(negative, json!(-1e20)) && !passes(negative, json!(1e20)));
|
||||
let lowest = Type::Integer { min: Some(i64::MIN), max: None };
|
||||
assert!(!passes(lowest, json!(-1e20)) && passes(lowest, json!(1e20)));
|
||||
}
|
||||
|
||||
/// JSON Schema counts a number with no fractional part as an integer: `2.0` passes, and the
|
||||
/// command gets `2`.
|
||||
#[test]
|
||||
fn a_whole_number_written_with_a_fraction_is_an_integer() {
|
||||
let any = Type::Integer { min: None, max: None };
|
||||
assert_eq!(one(any).validate(&json!({"x": 2.0})).unwrap(), Some(json!({"x": 2})));
|
||||
assert_eq!(one(any).validate(&json!({"x": 2})).unwrap(), None);
|
||||
assert!(passes(any, json!(1e300)));
|
||||
assert_eq!(one(Type::Id).validate(&json!({"x": 7.0})).unwrap(), Some(json!({"x": 7})));
|
||||
assert_eq!(one(Type::Ids).validate(&json!({"x": [1, 2.0]})).unwrap(), Some(json!({"x": [1, 2]})));
|
||||
assert!(passes(Type::Id, json!(MAX_ID)) && !passes(Type::Id, json!(MAX_ID + 1)) && !passes(Type::Id, json!(1e300)));
|
||||
assert_eq!(one(Type::Ids).validate(&json!({"x": [1, "2"]})).unwrap_err().path, "x[1]");
|
||||
}
|
||||
|
||||
/// A value with no finite number in it reads as null in JSON, and a number refuses it; the largest
|
||||
/// finite numbers pass a number with no range.
|
||||
#[test]
|
||||
fn numbers_at_the_edges() {
|
||||
assert!(!passes(Type::NUMBER, json!(f64::NAN)) && !passes(Type::NUMBER, json!(f64::INFINITY)));
|
||||
assert!(passes(Type::NUMBER, json!(f64::MAX)) && passes(Type::NUMBER, json!(f64::MIN)));
|
||||
let unit = Type::Number { min: Some(Bound::Inclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: None };
|
||||
assert!(passes(unit, json!(0.0)) && passes(unit, json!(1.0)) && !passes(unit, json!(-1e-300)) && !passes(unit, json!(1.0000001)));
|
||||
}
|
||||
|
||||
/// A list too long to name one path per entry costs one pass, and the error names the entry.
|
||||
#[test]
|
||||
fn a_huge_list_is_checked_once_and_names_the_entry() {
|
||||
let mut ids: Vec<Value> = (0..200_000u64).map(Value::from).collect();
|
||||
assert_eq!(one(Type::Ids).validate(&json!({ "x": ids })).unwrap(), None);
|
||||
ids.push(json!("no"));
|
||||
let e = one(Type::Ids).validate(&json!({ "x": ids })).unwrap_err();
|
||||
assert_eq!(e.path, "x[200000]");
|
||||
assert!(e.to_string().chars().count() < 120, "{e}");
|
||||
}
|
||||
|
||||
/// A list nested far past anything the schema can take: dropping or writing it out recurses per
|
||||
/// level, which is why the test leaks it rather than dropping it.
|
||||
fn nested_lists(levels: usize) -> Value {
|
||||
(0..levels).fold(json!(1), |inner, _| Value::Array(vec![inner]))
|
||||
}
|
||||
|
||||
/// A refused value is shown from its start only, however deep or long it is, so an error costs
|
||||
/// the same for a hostile value as for a small one.
|
||||
#[test]
|
||||
fn a_refused_value_is_read_only_as_far_as_it_is_shown() {
|
||||
let deep = nested_lists(500_000);
|
||||
let params = json!({});
|
||||
let mut map = params.as_object().unwrap().clone();
|
||||
map.insert("x".into(), deep);
|
||||
let params = Value::Object(map);
|
||||
let e = one(Type::String).validate(¶ms).unwrap_err();
|
||||
assert!(e.to_string().starts_with("`x` must be a string, not [[[[") && e.to_string().ends_with('…'), "{e}");
|
||||
assert!(e.to_string().chars().count() <= 100, "{e}");
|
||||
std::mem::forget(params);
|
||||
|
||||
let huge = "x".repeat(5_000_000);
|
||||
let e = one(Type::Boolean).validate(&json!({ "x": huge })).unwrap_err();
|
||||
assert!(e.to_string().chars().count() <= 100, "{}", e.to_string().len());
|
||||
assert!(e.to_string().ends_with('…'));
|
||||
|
||||
let e = one(Type::Boolean).validate(&json!({"x": {"a": 1, "b": [1, 2]}})).unwrap_err();
|
||||
assert_eq!(e.to_string(), "`x` must be true or false, not {\"a\":1,\"b\":[1,2]}");
|
||||
let e = ParamSchema::new(&[], "").validate(&nested_lists(3)).unwrap_err();
|
||||
assert_eq!(e.to_string(), "the params must be an object, not [[[1]]]");
|
||||
}
|
||||
|
||||
/// A list entry made an integer, and a default filled in, don't copy a value that is still to be
|
||||
/// checked: copying recurses per level.
|
||||
#[test]
|
||||
fn a_list_with_a_change_is_not_copied_before_all_of_it_is_checked() {
|
||||
let params = Value::Object([("x".to_string(), Value::Array(vec![json!(2.0), nested_lists(500_000)]))].into_iter().collect());
|
||||
assert_eq!(one(Type::Ids).validate(¶ms).unwrap_err().path, "x[1]");
|
||||
std::mem::forget(params);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_with_a_default_is_not_copied_before_all_of_it_is_checked() {
|
||||
const FILLED_FIRST: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::String)];
|
||||
let params = Value::Object([("b".to_string(), nested_lists(500_000))].into_iter().collect());
|
||||
assert_eq!(ParamSchema::new(FILLED_FIRST, "").validate(¶ms).unwrap_err().path, "b");
|
||||
std::mem::forget(params);
|
||||
}
|
||||
|
||||
/// A value the schema doesn't look inside is measured before a default copies the object it is in.
|
||||
const WITH_DEFAULT: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::Color).optional()];
|
||||
const LENIENT_AFTER_DEFAULT: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::Boolean).optional().lenient()];
|
||||
|
||||
fn holding(key: &str, v: Value) -> Value {
|
||||
Value::Object([(key.to_string(), v)].into_iter().collect())
|
||||
}
|
||||
|
||||
/// The lists of fixed shape count toward the nesting limit as the other lists do.
|
||||
#[test]
|
||||
fn id_lists_points_and_color_lists_count_toward_the_nesting_limit() {
|
||||
let check = |depth, ty: &Type, v: &Value| check_value(&At::Root, depth, ty, v, false, false);
|
||||
for (ty, v) in [(Type::Ids, json!([1])), (Type::Point, json!([1, 2])), (Type::Color, json!([1, 0, 0]))] {
|
||||
assert!(check(MAX_DEPTH - 1, &ty, &v).is_ok(), "{ty:?}");
|
||||
assert_eq!(check(MAX_DEPTH, &ty, &v).unwrap_err().problem, Problem::TooDeep, "{ty:?}");
|
||||
}
|
||||
assert!(check(MAX_DEPTH, &Type::Color, &json!("#ff0000")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_retired_key_past_the_nesting_limit_is_refused() {
|
||||
let params = holding("older", nested_lists(500_000));
|
||||
let e = ParamSchema::new(WITH_DEFAULT, "").validate_saved(¶ms).unwrap_err();
|
||||
assert_eq!(e.path, "older");
|
||||
assert!(matches!(e.problem, Problem::Unknown { .. }));
|
||||
std::mem::forget(params);
|
||||
let kept = ParamSchema::new(WITH_DEFAULT, "").validate_saved(&holding("older", nested_lists(MAX_DEPTH))).unwrap().unwrap();
|
||||
assert_eq!(kept["a"], json!(0));
|
||||
assert_eq!(kept["older"], nested_lists(MAX_DEPTH));
|
||||
assert!(ParamSchema::new(WITH_DEFAULT, "").validate_saved(&holding("older", nested_lists(MAX_DEPTH + 1))).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_object_past_the_nesting_limit_is_refused() {
|
||||
let params = holding("b", holding("k", nested_lists(500_000)));
|
||||
let e = ParamSchema::new(WITH_DEFAULT, "").validate(¶ms).unwrap_err();
|
||||
assert_eq!(e.path, "b");
|
||||
assert!(matches!(e.problem, Problem::WrongType { .. }));
|
||||
std::mem::forget(params);
|
||||
assert!(ParamSchema::new(WITH_DEFAULT, "").validate(&json!({"b": {"r": 1, "g": 0, "b": 0}})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lenient_value_past_the_nesting_limit_is_refused() {
|
||||
let params = holding("b", nested_lists(500_000));
|
||||
let e = ParamSchema::new(LENIENT_AFTER_DEFAULT, "").validate(¶ms).unwrap_err();
|
||||
assert_eq!(e.path, "b");
|
||||
assert!(matches!(e.problem, Problem::WrongType { .. }));
|
||||
std::mem::forget(params);
|
||||
assert_eq!(ParamSchema::new(LENIENT_AFTER_DEFAULT, "").validate(&json!({"b": [1]})).unwrap().unwrap()["b"], json!([1]));
|
||||
}
|
||||
|
||||
/// A key is cut in the error, and an unknown key is refused whatever it holds.
|
||||
#[test]
|
||||
fn a_hostile_key_is_cut_and_refused() {
|
||||
let key = "k".repeat(1_000_000);
|
||||
let e = one(Type::Boolean).validate(&json!({ key: true, "x": true })).unwrap_err();
|
||||
assert_eq!(e.path.chars().count(), KEY_CHARS + 1);
|
||||
assert!(e.path.ends_with('…') && e.to_string().chars().count() < 200, "{}", e.path.len());
|
||||
for key in ["", "a.b", "a[0]", "`", "\u{0}", "名前"] {
|
||||
let e = one(Type::Boolean).validate(&json!({ key: true, "x": true })).unwrap_err();
|
||||
assert_eq!(e.path, key);
|
||||
assert!(matches!(e.problem, Problem::Unknown { .. }));
|
||||
}
|
||||
assert_eq!(shown_key("short"), "short");
|
||||
}
|
||||
|
||||
/// A schema that refers to itself, which only a mistake can write: checking values stops at the
|
||||
/// nesting limit, and the writers finish.
|
||||
static ENDLESS: Type = Type::Array(&ENDLESS);
|
||||
|
||||
#[test]
|
||||
fn a_schema_that_refers_to_itself_stops_at_the_nesting_limit() {
|
||||
let s = one(ENDLESS);
|
||||
let e = s.validate(&json!({ "x": nested_lists(MAX_DEPTH + 2) })).unwrap_err();
|
||||
assert_eq!(e.problem, Problem::TooDeep);
|
||||
assert!(e.path.starts_with("x[0][0]"));
|
||||
assert!(s.definition_problem().is_some_and(|p| p.contains("nests deeper")));
|
||||
assert!(s.params_text().contains('…'));
|
||||
assert!(s.to_json()["properties"]["x"].is_object());
|
||||
assert_ne!(hash([("a", &s)]), 0);
|
||||
}
|
||||
|
||||
const BAD_DEFAULT: &[Param] = &[Param::new("x", Type::NUMBER).defaults_to("\"zero\"")];
|
||||
const NOT_JSON: &[Param] = &[Param::new("x", Type::NUMBER).defaults_to("{")];
|
||||
const TWICE: &[Param] = &[Param::new("x", Type::NUMBER), Param::new("x", Type::String)];
|
||||
const EMPTY_NAME: &[Param] = &[Param::new("", Type::NUMBER)];
|
||||
const PATH_NAME: &[Param] = &[Param::new("a.b", Type::NUMBER)];
|
||||
const NO_NAMES: &[Param] = &[Param::new("x", Type::Enum(&[]))];
|
||||
const SAME_NAMES: &[Param] = &[Param::new("x", Type::Enum(&["a", "a"]))];
|
||||
const EMPTY_RANGE: &[Param] = &[Param::new("x", Type::Number { min: Some(Bound::Exclusive(1.0)), max: Some(Bound::Inclusive(1.0)), unit: None })];
|
||||
const BACKWARD: &[Param] = &[Param::new("x", Type::Integer { min: Some(2), max: Some(1) })];
|
||||
const NOT_FINITE: &[Param] = &[Param::new("x", Type::Number { min: None, max: Some(Bound::Inclusive(f64::INFINITY)), unit: None })];
|
||||
const REQUIRED_DEFAULT: &[Param] = &[Param { required: true, omitted: Omitted::Value("1"), ..Param::new("x", Type::NUMBER) }];
|
||||
const DEEP_FAULT: &[Param] = &[Param::new("edits", Type::Array(&Type::Object(TWICE)))];
|
||||
|
||||
#[test]
|
||||
fn a_schema_that_is_wrong_in_itself_is_reported() {
|
||||
for (params, why) in [
|
||||
(BAD_DEFAULT, "doesn't pass its type"),
|
||||
(NOT_JSON, "isn't JSON"),
|
||||
(TWICE, "listed twice"),
|
||||
(EMPTY_NAME, "empty or holds"),
|
||||
(PATH_NAME, "empty or holds"),
|
||||
(NO_NAMES, "no names"),
|
||||
(SAME_NAMES, "repeats"),
|
||||
(EMPTY_RANGE, "no value can be"),
|
||||
(BACKWARD, "no value can be"),
|
||||
(NOT_FINITE, "isn't finite"),
|
||||
(REQUIRED_DEFAULT, "required"),
|
||||
(DEEP_FAULT, "`edits[].x` is listed twice"),
|
||||
] {
|
||||
let problem = ParamSchema::new(params, "").definition_problem();
|
||||
assert!(problem.as_deref().is_some_and(|p| p.contains(why)), "{params:?}: {problem:?}");
|
||||
}
|
||||
assert_eq!(ParamSchema::new(VIEW, "").definition_problem(), None);
|
||||
assert_eq!(ParamSchema::new(&[], "").definition_problem(), None);
|
||||
}
|
||||
|
||||
/// Saved steps keep keys the schema doesn't name, at any depth; the values it names are checked.
|
||||
#[test]
|
||||
fn saved_steps_pass_retired_keys_and_check_their_values() {
|
||||
let edits = one(Type::Array(&Type::Object(EDIT)));
|
||||
let retired = json!({"x": [{"name": "A", "old": 1}], "older": true});
|
||||
assert!(edits.validate(&retired).is_err());
|
||||
let filled = edits.validate_saved(&retired).unwrap().unwrap();
|
||||
assert_eq!(filled["x"][0]["delete"], json!(false), "defaults are filled in");
|
||||
assert_eq!(filled["older"], json!(true), "the keys stay");
|
||||
assert_eq!(edits.validate_saved(&json!({"x": [{"name": 5}], "older": true})).unwrap_err().path, "x[0].name");
|
||||
assert_eq!(edits.validate_saved(&json!({"older": true})).unwrap_err().problem, Problem::Missing);
|
||||
}
|
||||
|
||||
/// Every type's JSON form follows the 2020-12 rules, and an independent validator of those rules
|
||||
/// agrees with [`ParamSchema::validate`] on each value.
|
||||
#[test]
|
||||
fn the_json_form_and_the_validator_agree_with_the_2020_12_rules() {
|
||||
const NULLABLE: &[Param] = &[Param::new("a", Type::String).optional().null_omitted(), Param::new("b", Type::Boolean).defaults_to("true")];
|
||||
let types = [
|
||||
Type::NUMBER,
|
||||
Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: Some("pt") },
|
||||
Type::Number { min: Some(Bound::Inclusive(-1.0)), max: Some(Bound::Exclusive(1.0)), unit: None },
|
||||
Type::Integer { min: None, max: None },
|
||||
Type::Integer { min: Some(1), max: Some(25) },
|
||||
Type::Boolean,
|
||||
Type::String,
|
||||
Type::Enum(&["a", "b"]),
|
||||
Type::Id,
|
||||
Type::Ids,
|
||||
Type::Color,
|
||||
Type::Point,
|
||||
Type::Object(EDIT),
|
||||
Type::Object(NULLABLE),
|
||||
Type::Object(&[]),
|
||||
Type::Array(&Type::NUMBER),
|
||||
Type::Array(&Type::Object(EDIT)),
|
||||
];
|
||||
let values = [
|
||||
json!(null),
|
||||
json!(true),
|
||||
json!(0),
|
||||
json!(1),
|
||||
json!(2.0),
|
||||
json!(25.5),
|
||||
json!(-1),
|
||||
json!(-1.0),
|
||||
json!(1e300),
|
||||
json!(MAX_ID),
|
||||
json!(MAX_ID + 1),
|
||||
json!(u64::MAX),
|
||||
json!(""),
|
||||
json!("a"),
|
||||
json!("c"),
|
||||
json!([]),
|
||||
json!([1, 2]),
|
||||
json!([1, 2, 3]),
|
||||
json!([1, "2"]),
|
||||
json!([[1]]),
|
||||
json!({}),
|
||||
json!({"name": "A"}),
|
||||
json!({"name": "A", "delete": false}),
|
||||
json!({"name": "A", "delete": null}),
|
||||
json!({"name": "A", "other": 1}),
|
||||
json!({"a": null, "b": false}),
|
||||
json!({"a": 5}),
|
||||
json!([{"name": "A"}]),
|
||||
json!([{"name": 1}]),
|
||||
];
|
||||
for ty in types {
|
||||
let schema = one(ty);
|
||||
let written = schema.to_json();
|
||||
conformance::check_schema(&written, "#").unwrap_or_else(|e| panic!("{ty:?}: {e}\n{written:#}"));
|
||||
assert_eq!(written["$schema"], "https://json-schema.org/draft/2020-12/schema");
|
||||
for v in &values {
|
||||
let params = json!({ "x": v });
|
||||
let local = schema.validate(¶ms).is_ok();
|
||||
assert_eq!(local, conformance::instance_valid(&written, ¶ms), "{ty:?} on {v}: {written}");
|
||||
}
|
||||
}
|
||||
for params in [VIEW, EDIT, NULLABLE] {
|
||||
let schema = ParamSchema::new(params, "").deprecated(1);
|
||||
conformance::check_schema(&schema.to_json(), "#").unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// The independent checker refuses what the 2020-12 rules refuse, so its passes above mean
|
||||
/// something.
|
||||
#[test]
|
||||
fn the_2020_12_checker_refuses_invalid_schemas() {
|
||||
for bad in [
|
||||
json!(5),
|
||||
json!({"type": "float"}),
|
||||
json!({"enum": []}),
|
||||
json!({"enum": [1, 1]}),
|
||||
json!({"required": ["a", "a"]}),
|
||||
json!({"required": [1]}),
|
||||
json!({"properties": []}),
|
||||
json!({"properties": {"a": 5}}),
|
||||
json!({"items": 1}),
|
||||
json!({"prefixItems": []}),
|
||||
json!({"anyOf": []}),
|
||||
json!({"minimum": "0"}),
|
||||
json!({"minItems": -1}),
|
||||
json!({"description": 5}),
|
||||
json!({"deprecated": "yes"}),
|
||||
json!({"type": "number", "default": "zero"}),
|
||||
json!({"$schema": "not a uri"}),
|
||||
json!({"minimun": 0}),
|
||||
] {
|
||||
assert!(conformance::check_schema(&bad, "#").is_err(), "{bad}");
|
||||
}
|
||||
assert!(conformance::instance_valid(&json!({"type": "integer"}), &json!(2.0)));
|
||||
assert!(!conformance::instance_valid(&json!({"type": "integer"}), &json!(2.5)));
|
||||
assert!(!conformance::instance_valid(&json!({"prefixItems": [{"type": "number"}], "items": false}), &json!([1, 2])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn booleans_and_strings_take_only_their_own_type() {
|
||||
assert!(passes(Type::Boolean, json!(true)) && passes(Type::Boolean, json!(false)));
|
||||
assert!(!passes(Type::Boolean, json!("true")) && !passes(Type::Boolean, json!(1)) && !passes(Type::Boolean, json!(null)));
|
||||
assert!(passes(Type::String, json!("")) && passes(Type::String, json!("View 1")));
|
||||
assert!(!passes(Type::String, json!(5)) && !passes(Type::String, json!(["a"])));
|
||||
assert_eq!(one(Type::Boolean).validate(&json!({"x": "yes"})).unwrap_err().to_string(), "`x` must be true or false, not \"yes\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_enum_takes_one_of_its_names() {
|
||||
let modes = Type::Enum(&["rgb", "cmyk"]);
|
||||
assert!(passes(modes, json!("rgb")) && passes(modes, json!("cmyk")));
|
||||
assert!(!passes(modes, json!("RGB")) && !passes(modes, json!("lab")) && !passes(modes, json!(0)));
|
||||
assert_eq!(one(modes).validate(&json!({"x": "lab"})).unwrap_err().to_string(), "`x` must be one of \"rgb\", \"cmyk\", not \"lab\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_are_non_negative_integers() {
|
||||
assert!(passes(Type::Id, json!(0)) && passes(Type::Id, json!(42)));
|
||||
assert!(!passes(Type::Id, json!(-1)) && !passes(Type::Id, json!(1.5)) && !passes(Type::Id, json!("42")));
|
||||
assert!(passes(Type::Ids, json!([])) && passes(Type::Ids, json!([3, 4])));
|
||||
assert!(!passes(Type::Ids, json!(3)) && !passes(Type::Ids, json!([3, "4"])) && !passes(Type::Ids, json!([-3])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_and_points_have_their_shapes() {
|
||||
assert!(passes(Type::Color, json!("#ff0000")) && passes(Type::Color, json!([1, 0, 0])) && passes(Type::Color, json!({"gray": 50})));
|
||||
assert!(!passes(Type::Color, json!(5)) && !passes(Type::Color, json!([1, 0])) && !passes(Type::Color, json!([1, 0, "x"])));
|
||||
assert!(passes(Type::Point, json!([0, -2.5])));
|
||||
assert!(!passes(Type::Point, json!([1])) && !passes(Type::Point, json!([1, 2, 3])) && !passes(Type::Point, json!([1, "2"])));
|
||||
assert!(!passes(Type::Point, json!({"x": 1, "y": 2})));
|
||||
}
|
||||
|
||||
const EDIT: &[Param] = &[Param::new("name", Type::String), Param::new("delete", Type::Boolean).defaults_to("false")];
|
||||
|
||||
#[test]
|
||||
fn objects_and_arrays_name_the_path_of_the_value_inside() {
|
||||
let edits = Type::Array(&Type::Object(EDIT));
|
||||
assert!(passes(edits, json!([])) && passes(edits, json!([{"name": "A"}, {"name": "B", "delete": true}])));
|
||||
let err = |v: Value| one(edits).validate(&json!({ "x": v })).unwrap_err();
|
||||
assert_eq!(err(json!([{"name": "A"}, {"name": "B", "delete": "no"}])).path, "x[1].delete");
|
||||
assert_eq!(err(json!([{"name": "A"}, {"delete": true}])).to_string(), "missing `x[1].name`");
|
||||
let unknown = err(json!([{"name": "A", "nmae": "B"}]));
|
||||
assert_eq!((unknown.path.as_str(), unknown.problem), ("x[0].nmae", Problem::Unknown { keys: vec!["name", "delete"] }));
|
||||
assert_eq!(err(json!({"name": "A"})).to_string(), "`x` must be a list, not {\"name\":\"A\"}");
|
||||
assert_eq!(err(json!(["A"])).to_string(), "`x[0]` must be an object, not \"A\"");
|
||||
// Defaults inside are filled in too.
|
||||
let filled = one(edits).validate(&json!({"x": [{"name": "A"}]})).unwrap();
|
||||
assert_eq!(filled, Some(json!({"x": [{"name": "A", "delete": false}]})));
|
||||
}
|
||||
|
||||
const VIEW: &[Param] = &[
|
||||
Param::new("name", Type::String).default_note("\"View N\"").null_omitted(),
|
||||
Param::new("center", Type::Point),
|
||||
Param::new("rotation", Type::Number { min: None, max: None, unit: Some("deg") }).defaults_to("0"),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn keys_requirements_nulls_and_defaults() {
|
||||
let s = ParamSchema::new(VIEW, "save a view").returns("{name}");
|
||||
// Unknown keys are refused first, naming the key and the keys the command takes.
|
||||
let e = s.validate(&json!({"centre": [0, 0]})).unwrap_err();
|
||||
assert_eq!((e.path.as_str(), e.problem), ("centre", Problem::Unknown { keys: vec!["name", "center", "rotation"] }));
|
||||
assert_eq!(s.validate(&json!({})).unwrap_err(), ParamError { path: "center".into(), problem: Problem::Missing });
|
||||
// Null counts as omitted only where the schema says so.
|
||||
assert_eq!(s.validate(&json!({"center": [1, 2], "name": null, "rotation": 15})).unwrap(), None);
|
||||
assert_eq!(s.validate(&json!({"center": [1, 2], "rotation": null})).unwrap_err().path, "rotation");
|
||||
// An omitted value with a default gets it; one with a note is left to the command.
|
||||
assert_eq!(s.validate(&json!({"center": [1, 2]})).unwrap(), Some(json!({"center": [1, 2], "rotation": 0})));
|
||||
// Params that aren't an object are refused; null params are `{}`.
|
||||
assert_eq!(s.validate(&json!(5)).unwrap_err().to_string(), "the params must be an object, not 5");
|
||||
assert_eq!(s.validate(&Value::Null).unwrap_err().path, "center");
|
||||
let none = ParamSchema::new(&[], "");
|
||||
assert_eq!(none.validate(&Value::Null).unwrap(), None);
|
||||
assert_eq!(none.validate(&json!({"a": 1})).unwrap_err().to_string(), "unknown parameter `a`; the object takes no keys");
|
||||
}
|
||||
|
||||
const LENIENT: &[Param] = &[Param::new("on", Type::Boolean).optional().lenient(), Param::new("size", Type::NUMBER).optional().lenient()];
|
||||
|
||||
#[test]
|
||||
fn lenient_parameters_pass_values_of_another_type_to_the_command() {
|
||||
let s = ParamSchema::new(LENIENT, "");
|
||||
assert_eq!(s.validate(&json!({"on": "yes", "size": "12"})).unwrap(), None);
|
||||
// Unknown keys are still refused.
|
||||
assert!(s.validate(&json!({"of": true})).is_err());
|
||||
// The JSON form states the documented type, so a validator of that form refuses what passes here.
|
||||
let written = s.to_json();
|
||||
assert_eq!(written["properties"]["on"]["x-lenient"], true);
|
||||
assert!(!conformance::instance_valid(&written, &json!({"on": "yes"})));
|
||||
assert!(conformance::instance_valid(&written, &json!({"on": true})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_params_text_lists_each_parameter_with_its_type() {
|
||||
let s = ParamSchema::new(VIEW, "save a view").returns("{name}");
|
||||
assert_eq!(s.params_text(), "{name?: string (default: \"View N\"), center: [x, y], rotation?: number deg (default: 0)} save a view → {name}");
|
||||
const ALL: &[Param] = &[
|
||||
Param::new("a", Type::Integer { min: Some(1), max: Some(25) }),
|
||||
Param::new("b", Type::Enum(&["x", "y"])).optional(),
|
||||
Param::new("c", Type::Ids).optional().doc("instead of the selection"),
|
||||
Param::new("d", Type::Color).optional().deprecated(2),
|
||||
Param::new("e", Type::Array(&Type::Object(EDIT))).optional(),
|
||||
Param::new("f", Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(10.0)), unit: Some("pt") }).optional(),
|
||||
];
|
||||
assert_eq!(
|
||||
ParamSchema::new(ALL, "").params_text(),
|
||||
"{a: integer 1 to 25, b?: \"x\"|\"y\", c?: [id…] (instead of the selection), d?: color (deprecated), \
|
||||
e?: [{name: string, delete?: bool (default: false)}…], f?: number > 0 and <= 10 pt}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_json_form_is_an_object_schema() {
|
||||
let s = ParamSchema::new(VIEW, "save a view").returns("{name}").writes(Writes::Document).cost(2);
|
||||
let j = s.to_json();
|
||||
assert_eq!(j["$schema"], DIALECT);
|
||||
assert_eq!(j["type"], "object");
|
||||
assert_eq!(j["additionalProperties"], false);
|
||||
assert_eq!(j["required"], json!(["center"]));
|
||||
assert_eq!(j["properties"]["name"]["anyOf"], json!([{"type": "string"}, {"type": "null"}]));
|
||||
assert_eq!(j["properties"]["name"]["x-default"], "\"View N\"");
|
||||
assert_eq!(j["properties"]["rotation"], json!({"type": "number", "x-unit": "deg", "default": 0, "x-since": 1}));
|
||||
assert_eq!(j["properties"]["center"]["prefixItems"], json!([{"type": "number"}, {"type": "number"}]));
|
||||
assert_eq!((j["x-cost"].clone(), j["x-writes"].clone(), j["x-returns"].clone()), (json!(2), json!("document"), json!("{name}")));
|
||||
let range = one(Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: None }).to_json();
|
||||
assert_eq!(range["properties"]["x"], json!({"type": "number", "exclusiveMinimum": 0.0, "maximum": 1.0, "x-since": 1}));
|
||||
}
|
||||
|
||||
/// Null params read as `{}`, so the root of the JSON form allows null exactly when `{}` passes.
|
||||
/// A nested object does not read null as `{}`.
|
||||
#[test]
|
||||
fn the_json_form_allows_null_params_when_no_parameter_is_required() {
|
||||
const OPTIONAL: &[Param] = &[Param::new("inner", Type::Object(&[Param::new("y", Type::Boolean).optional()])).optional()];
|
||||
let optional = ParamSchema::new(OPTIONAL, "");
|
||||
let written = optional.to_json();
|
||||
conformance::check_schema(&written, "#").unwrap();
|
||||
assert_eq!(written["type"], json!(["object", "null"]));
|
||||
assert_eq!(written["properties"]["inner"]["type"], "object");
|
||||
let required = one(Type::Boolean);
|
||||
assert_eq!(required.to_json()["type"], "object");
|
||||
for schema in [optional, required] {
|
||||
let written = schema.to_json();
|
||||
for params in [json!(null), json!({}), json!(5), json!([]), json!("x"), json!({"inner": null}), json!({"inner": {}})] {
|
||||
assert_eq!(schema.validate(¶ms).is_ok(), conformance::instance_valid(&written, ¶ms), "{params} against {written}");
|
||||
}
|
||||
}
|
||||
assert!(optional.validate(&json!(null)).is_ok());
|
||||
assert!(required.validate(&json!(null)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hash_follows_every_schema_but_not_their_order() {
|
||||
let a = ParamSchema::new(VIEW, "save a view");
|
||||
let b = ParamSchema::new(LENIENT, "");
|
||||
let h = hash([("view.a", &a), ("view.b", &b)]);
|
||||
assert_eq!(h, hash([("view.b", &b), ("view.a", &a)]));
|
||||
assert_ne!(h, hash([("view.a", &a)]));
|
||||
assert_ne!(h, hash([("view.a", &a), ("view.c", &b)]));
|
||||
let changed = ParamSchema::new(VIEW, "save a view").since(2);
|
||||
assert_ne!(h, hash([("view.a", &changed), ("view.b", &b)]));
|
||||
}
|
||||
@@ -456,6 +456,41 @@ impl Gradient {
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
/// A gradient whose stops are all CMYK as a ramp of C, M, Y, K and opacity: the stops' own
|
||||
/// inks, an off-center midpoint halfway between its two stops' inks, and a Perceptual
|
||||
/// gradient's curve as [`Self::ink_mixes`] mixes the inks. `None` when a stop is in another
|
||||
/// model, there are no stops, or [`Self::ink_mixes`] gives none for the curve.
|
||||
fn ink_ramp(&self) -> Option<Ramp<5>> {
|
||||
let inks: Vec<[f32; 4]> = self
|
||||
.stops
|
||||
.iter()
|
||||
.map(|s| match s.color {
|
||||
Color::Cmyk { c, m, y, k } => Some([c, m, y, k]),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
if inks.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let entry = |i: usize, w: f32, o: f32| {
|
||||
let (a, b) = (inks[i], inks.get(i + 1).copied().unwrap_or(inks[i]));
|
||||
let [c, m, y, k]: [f32; 4] = std::array::from_fn(|n| a[n] + (b[n] - a[n]) * w);
|
||||
[c, m, y, k, o]
|
||||
};
|
||||
if !self.method.is_classic() {
|
||||
return Some(Ramp { stops: self.ink_mixes()?.into_iter().map(|(t, i, w, o)| (t, entry(i, w, o))).collect() });
|
||||
}
|
||||
let mut stops = Vec::with_capacity(inks.len());
|
||||
for (i, s) in self.stops.iter().enumerate() {
|
||||
stops.push((s.offset, entry(i, 0.0, s.opacity)));
|
||||
if let Some(n) = self.stops.get(i + 1)
|
||||
&& (s.midpoint - 0.5).abs() > 1e-3
|
||||
{
|
||||
stops.push((s.offset + (n.offset - s.offset) * s.midpoint, entry(i, 0.5, (s.opacity + n.opacity) / 2.0)));
|
||||
}
|
||||
}
|
||||
Some(Ramp { stops })
|
||||
}
|
||||
/// The same ramp the other way round: the stops in reverse order at mirrored offsets, each
|
||||
/// segment's midpoint mirrored with it.
|
||||
pub fn reverse(&mut self) {
|
||||
@@ -895,19 +930,45 @@ impl GradientPaint {
|
||||
fill: bool,
|
||||
rgb: &dyn Fn(&Color) -> [f32; 3],
|
||||
) -> impl Iterator<Item = [u8; 4]> + use<> {
|
||||
self.grid(Ramp::new(&self.gradient, rgb), bounds, area, cols, rows, cells, fill, false)
|
||||
}
|
||||
/// [`Self::pixels`] of a linear or radial gradient whose stops are all CMYK, as C, M, Y, K
|
||||
/// and opacity levels mixed from the stops' inks; `None` when a stop is in another model,
|
||||
/// there are no stops, or a Perceptual curve has too many stops for [`Gradient::ink_mixes`].
|
||||
/// Dither's noise adds no ink where the ramp has none.
|
||||
pub fn ink_pixels(&self, bounds: Rect, area: Rect, cols: u16, rows: u16, fill: bool) -> Option<impl Iterator<Item = [u8; 5]> + use<>> {
|
||||
let ramp = self.gradient.ink_ramp()?;
|
||||
Some(self.grid(ramp, bounds, area, cols, rows, [0..cols, 0..rows], fill, true))
|
||||
}
|
||||
/// `ramp` sampled at each cell's center in columns `cells[0]` and rows `cells[1]` of the grid,
|
||||
/// its last channel (opacity) rounded and each other channel with dither's noise, except
|
||||
/// (`inks`) where that channel is empty.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn grid<const N: usize>(
|
||||
&self,
|
||||
ramp: Ramp<N>,
|
||||
bounds: Rect,
|
||||
area: Rect,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
cells: [std::ops::Range<u16>; 2],
|
||||
fill: bool,
|
||||
inks: bool,
|
||||
) -> impl Iterator<Item = [u8; N]> + use<N> {
|
||||
let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither);
|
||||
let ramp = Ramp::new(&self.gradient, rgb);
|
||||
let (cw, ch) = (area.width() / f64::from(cols.max(1)), area.height() / f64::from(rows.max(1)));
|
||||
let (x0, y0) = (area.x0, area.y0);
|
||||
let [across, down] = cells.map(|r| u32::from(r.start)..u32::from(r.end));
|
||||
down.flat_map(move |j| across.clone().map(move |i| (i, j))).map(move |(i, j)| {
|
||||
let p = Point::new(x0 + (f64::from(i) + 0.5) * cw, y0 + (f64::from(j) + 0.5) * ch);
|
||||
let c = ramp.at(geom.param_at(kind, p) as f32);
|
||||
let level = |k: usize| {
|
||||
let noise = if dither { dither_noise(i, j, k as u32) } else { 0.0 };
|
||||
std::array::from_fn(|k| {
|
||||
if k + 1 == N {
|
||||
return (c[k].clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
}
|
||||
let noise = if dither && !(inks && c[k] <= 0.0) { dither_noise(i, j, k as u32) } else { 0.0 };
|
||||
(c[k].clamp(0.0, 1.0) * 255.0 + noise).round().clamp(0.0, 255.0) as u8
|
||||
};
|
||||
[level(0), level(1), level(2), (c[3].clamp(0.0, 1.0) * 255.0).round() as u8]
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -916,9 +977,9 @@ impl GradientPaint {
|
||||
/// (display RGB, or an ink's coverage): its stops, midpoints and a Perceptual gradient's
|
||||
/// in-between colours as stops (as [`Gradient::expanded_stops`]), each turned into that space
|
||||
/// once, with colour and opacity mixed linearly between them, each on its own (as the renderer's
|
||||
/// vector gradients mix them).
|
||||
pub struct Ramp {
|
||||
stops: Vec<(f32, [f32; 4])>,
|
||||
/// vector gradients mix them). `N` counts the channels, with opacity last.
|
||||
pub struct Ramp<const N: usize = 4> {
|
||||
stops: Vec<(f32, [f32; N])>,
|
||||
}
|
||||
|
||||
impl Ramp {
|
||||
@@ -932,10 +993,13 @@ impl Ramp {
|
||||
.collect();
|
||||
Self { stops }
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Ramp<N> {
|
||||
/// Unpremultiplied colour and opacity at `t`, padded past the ends (transparent black
|
||||
/// without stops).
|
||||
pub fn at(&self, t: f32) -> [f32; 4] {
|
||||
let Some(&(t0, first)) = self.stops.first() else { return [0.0; 4] };
|
||||
pub fn at(&self, t: f32) -> [f32; N] {
|
||||
let Some(&(t0, first)) = self.stops.first() else { return [0.0; N] };
|
||||
// Not after the first stop (or not a number): its colour.
|
||||
if t.partial_cmp(&t0) != Some(std::cmp::Ordering::Greater) {
|
||||
return first;
|
||||
@@ -947,7 +1011,7 @@ impl Ramp {
|
||||
return std::array::from_fn(|k| ca[k] + (cb[k] - ca[k]) * u);
|
||||
}
|
||||
}
|
||||
self.stops.last().map_or([0.0; 4], |s| s.1)
|
||||
self.stops.last().map_or([0.0; N], |s| s.1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -604,3 +604,96 @@ fn ink_mixes_use_the_mix_position_when_the_lightness_turns_back() {
|
||||
}
|
||||
assert!(mixes.windows(2).filter(|p| p[1].1 == 0).all(|p| p[0].2 <= p[1].2), "the weights rise: {mixes:?}");
|
||||
}
|
||||
|
||||
fn cmyk_stop(offset: f32, c: f32, m: f32, y: f32, k: f32) -> GradientStop {
|
||||
GradientStop::new(offset, Color::cmyk(c, m, y, k))
|
||||
}
|
||||
|
||||
/// The `n` × 1 grid of `g` as a left-to-right linear gradient's ink pixels.
|
||||
fn ink_row(g: Gradient, n: u16, fill: bool) -> Vec<[u8; 5]> {
|
||||
let b = Rect::new(0.0, 0.0, f64::from(n), 1.0);
|
||||
GradientPaint::new(g).ink_pixels(b, b, n, 1, fill).expect("CMYK stops").collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ink_pixels_mix_the_stops_inks_in_cmyk() {
|
||||
let mut g = Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 1.0, 0.0, 0.0, 0.0), cmyk_stop(1.0, 0.0, 0.0, 0.0, 1.0)]);
|
||||
g.stops[1].opacity = 0.5;
|
||||
let px = ink_row(g.clone(), 10, true);
|
||||
let at = |x: f32| (x * 255.0).round() as u8;
|
||||
for (i, p) in px.iter().enumerate() {
|
||||
let t = (i as f32 + 0.5) / 10.0;
|
||||
assert_eq!(*p, [at(1.0 - t), 0, 0, at(t), at(1.0 - t * 0.5)], "pixel {i}");
|
||||
}
|
||||
// An off-center midpoint is halfway between the two stops' inks, not a display RGB mix.
|
||||
g.stops[0].midpoint = 0.25;
|
||||
let px = ink_row(g.clone(), 4, false);
|
||||
assert_eq!(&px[0][..4], &[at(0.75), 0, 0, at(0.25)], "halfway to the midpoint");
|
||||
assert_eq!(&px[1][..4], &[at(0.5 * 5.0 / 6.0), 0, 0, at(0.5 + 0.5 / 6.0)], "a sixth of the way past it");
|
||||
// A hard stop keeps both sides.
|
||||
let hard = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
cmyk_stop(0.0, 1.0, 0.0, 0.0, 0.0),
|
||||
cmyk_stop(0.5, 1.0, 0.0, 0.0, 0.0),
|
||||
cmyk_stop(0.5, 0.0, 1.0, 0.0, 0.0),
|
||||
cmyk_stop(1.0, 0.0, 1.0, 0.0, 0.0),
|
||||
],
|
||||
);
|
||||
let px = ink_row(hard, 4, false);
|
||||
assert_eq!((&px[1][..4], &px[2][..4]), (&[255, 0, 0, 0][..], &[0, 255, 0, 0][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ink_pixels_dither_only_the_inks_the_ramp_has() {
|
||||
let mut g = Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 0.2, 0.0, 0.0, 0.4), cmyk_stop(1.0, 0.8, 0.0, 0.0, 0.4)]);
|
||||
g.dither = true;
|
||||
let noisy = ink_row(g.clone(), 64, true);
|
||||
let plain = ink_row(g.clone(), 64, false);
|
||||
assert_ne!(noisy, plain, "a fill has noise, a stroke none");
|
||||
for (n, p) in noisy.iter().zip(&plain) {
|
||||
assert_eq!((n[1], n[2]), (0, 0), "no ink on the empty plates: {n:?}");
|
||||
assert!(n[0].abs_diff(p[0]) <= 1 && n[3].abs_diff(p[3]) <= 1, "{n:?} {p:?}");
|
||||
assert_eq!(n[4], 255, "opacity has no noise");
|
||||
}
|
||||
assert!(noisy.iter().zip(&plain).any(|(n, p)| n[3] != p[3]), "K gets its own noise");
|
||||
assert!(noisy.iter().zip(&plain).any(|(n, p)| (n[0] != p[0]) != (n[3] != p[3])), "the noise differs from channel to channel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ink_pixels_follow_the_perceptual_curve_as_ink_mixes() {
|
||||
let mut g = Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 0.0, 0.0, 0.0, 0.0), cmyk_stop(1.0, 1.0, 0.0, 0.0, 0.0)]);
|
||||
g.method = GradientMethod::Perceptual;
|
||||
let mixes = g.ink_mixes().unwrap();
|
||||
let ramp = g.ink_ramp().unwrap();
|
||||
assert_eq!(ramp.stops.len(), mixes.len());
|
||||
for ((t, ink), (o, i, w, _)) in ramp.stops.iter().zip(&mixes) {
|
||||
assert_eq!((*t, ink[0]), (*o, if *i == 0 { *w } else { 1.0 }), "cyan at {t}");
|
||||
}
|
||||
let px = ink_row(g, 2, false);
|
||||
assert!(px[0][0] > 0 && px[0][0] < px[1][0], "{px:?}");
|
||||
assert!(px.iter().all(|p| p[1] == 0 && p[2] == 0 && p[3] == 0), "{px:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ink_pixels_need_every_stop_in_cmyk() {
|
||||
let b = Rect::new(0.0, 0.0, 2.0, 1.0);
|
||||
let with = |stop: GradientStop| GradientPaint::new(Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 1.0, 0.0, 0.0, 0.0), stop]));
|
||||
assert!(with(cmyk_stop(1.0, 0.0, 0.0, 0.0, 1.0)).ink_pixels(b, b, 2, 1, true).is_some());
|
||||
for other in [Color::rgb(1.0, 0.0, 0.0), Color::gray(0.5), Color::lab(50.0, 10.0, 10.0)] {
|
||||
assert!(with(GradientStop::new(1.0, other)).ink_pixels(b, b, 2, 1, true).is_none(), "{other:?}");
|
||||
}
|
||||
assert!(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![])).ink_pixels(b, b, 2, 1, true).is_none(), "no stops");
|
||||
}
|
||||
|
||||
/// A Perceptual curve over the limit of [`Gradient::ink_mixes`] has no inks; a Classic gradient of as many stops does.
|
||||
#[test]
|
||||
fn ink_pixels_stop_at_the_ink_mixes_limit() {
|
||||
let stops: Vec<_> = (0..=MAX_INK_TINTS).map(|i| cmyk_stop(i as f32 / MAX_INK_TINTS as f32, (i % 2) as f32, 0.0, 0.0, 0.0)).collect();
|
||||
let classic = Gradient::new(GradientKind::Linear, stops);
|
||||
let perceptual = Gradient { method: GradientMethod::Perceptual, ..classic.clone() };
|
||||
assert!(!perceptual.fits_ink_tints());
|
||||
let b = Rect::new(0.0, 0.0, 2.0, 1.0);
|
||||
assert!(GradientPaint::new(perceptual).ink_pixels(b, b, 2, 1, false).is_none());
|
||||
assert!(GradientPaint::new(classic).ink_pixels(b, b, 2, 1, false).is_some());
|
||||
}
|
||||
@@ -750,6 +750,7 @@ fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64
|
||||
if resized {
|
||||
o.cached_bounds = None;
|
||||
o.cached_baselines.clear();
|
||||
o.cached_ink = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -904,12 +905,16 @@ pub struct Spine {
|
||||
cum: Vec<f64>,
|
||||
anchors: Vec<f64>,
|
||||
closed: bool,
|
||||
path: PathData,
|
||||
/// The subpath the spine was flattened from, kept so [`Spine::at_length`] can read the
|
||||
/// original curves' tangents. Only the first subpath is stored: the others never affect a
|
||||
/// spine.
|
||||
subpath: SubPath,
|
||||
}
|
||||
|
||||
impl Spine {
|
||||
/// Build a spine from the first subpath of `path`: flatten it to a polyline, record cumulative
|
||||
/// arc lengths, and the arc length at each anchor.
|
||||
/// arc lengths, and the arc length at each anchor. `None` when `path` has no subpath, or when
|
||||
/// the first one flattens to fewer than two points (so it has no length to walk).
|
||||
pub fn new(path: &PathData) -> Option<Self> {
|
||||
let sp = path.subpaths.first()?;
|
||||
let mut pts: Vec<Point> = Vec::new();
|
||||
@@ -946,7 +951,7 @@ impl Spine {
|
||||
if pts.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
Some(Self { pts, cum, anchors, closed: sp.closed, path: path.clone() })
|
||||
Some(Self { pts, cum, anchors, closed: sp.closed, subpath: sp.clone() })
|
||||
}
|
||||
/// The spine's flattened length in arc length.
|
||||
pub fn length(&self) -> f64 {
|
||||
@@ -1012,7 +1017,7 @@ impl Spine {
|
||||
/// `Align to Path` jump between chords instead of following the curve smoothly.
|
||||
pub fn at_length(&self, s: f64) -> (Point, f64) {
|
||||
let s = if s.is_finite() { s.clamp(0.0, self.length()) } else { 0.0 };
|
||||
let Some(sp) = self.path.subpaths.first() else { return (self.pts.first().copied().unwrap_or_default(), 0.0) };
|
||||
let sp = &self.subpath;
|
||||
let n = sp.segment_count();
|
||||
let mut start = 0.0;
|
||||
for i in 0..n {
|
||||
|
||||
@@ -347,6 +347,7 @@ impl Document {
|
||||
t.first_para_continues = false;
|
||||
t.cached_bounds = None;
|
||||
t.cached_baselines.clear();
|
||||
t.cached_ink = None;
|
||||
}
|
||||
let on_path = n.extras().objects_on_path.is_some();
|
||||
let mut renamed = std::collections::HashMap::new();
|
||||
|
||||
@@ -71,6 +71,7 @@ impl Document {
|
||||
}
|
||||
if changed {
|
||||
t.cached_bounds = None;
|
||||
t.cached_ink = None;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@ impl TypeInks {
|
||||
text.xf = Affine::new([a, b, c, d, 0.0, 0.0]);
|
||||
text.cached_bounds = None;
|
||||
text.cached_baselines.clear();
|
||||
text.cached_ink = None;
|
||||
let content = content_hash(&text).map(|hash| (hash, by_node.1, inputs));
|
||||
match content.and_then(|key| self.content.get(&key)) {
|
||||
Some(ink) => {
|
||||
|
||||
@@ -60,6 +60,38 @@ impl ImageBlob {
|
||||
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
Some(Self::png(png))
|
||||
}
|
||||
|
||||
/// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and
|
||||
/// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct
|
||||
/// color. `None` when the image can't be decoded, or when its file stores grayscale already
|
||||
/// and no visible pixel changed.
|
||||
pub fn map_gray(&self, mut f: impl FnMut([u8; 3]) -> u8) -> Option<ImageBlob> {
|
||||
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
|
||||
let (width, height) = img.dimensions();
|
||||
let mut memo: HashMap<[u8; 3], u8> = HashMap::new();
|
||||
let mut changed = self.gray_source().is_none();
|
||||
let mut opaque = true;
|
||||
let mut gray_alpha = Vec::with_capacity(img.len() / 2);
|
||||
for px in img.pixels() {
|
||||
let rgb = [px.0[0], px.0[1], px.0[2]];
|
||||
let level = *memo.entry(rgb).or_insert_with(|| f(rgb));
|
||||
changed |= px.0[3] > 0 && [level; 3] != rgb;
|
||||
opaque &= px.0[3] == 255;
|
||||
gray_alpha.extend_from_slice(&[level, px.0[3]]);
|
||||
}
|
||||
if !changed {
|
||||
return None;
|
||||
}
|
||||
let mut png = Vec::new();
|
||||
let mut out = Cursor::new(&mut png);
|
||||
if opaque {
|
||||
let levels = gray_alpha.iter().step_by(2).copied().collect();
|
||||
image::GrayImage::from_raw(width, height, levels)?.write_to(&mut out, image::ImageFormat::Png).ok()?;
|
||||
} else {
|
||||
image::GrayAlphaImage::from_raw(width, height, gray_alpha)?.write_to(&mut out, image::ImageFormat::Png).ok()?;
|
||||
}
|
||||
Some(Self::png(png))
|
||||
}
|
||||
}
|
||||
|
||||
/// How a grayscale image's file stores its pixels ([`ImageBlob::gray_source`]).
|
||||
|
||||
+388
-39
@@ -1,10 +1,10 @@
|
||||
//! Where a path's strokes paint, from the path's geometry without building their outlines: the
|
||||
//! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes
|
||||
//! up to the miter limit, projecting caps and arrowheads.
|
||||
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points.
|
||||
|
||||
use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit};
|
||||
use vectorcraft_geom::hit::fill_contains;
|
||||
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest};
|
||||
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest};
|
||||
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2};
|
||||
|
||||
use crate::appearance::HEAD_REACH;
|
||||
@@ -101,6 +101,82 @@ fn profile_at(profile: &WidthProfile, segs: &[PathSeg], closed: bool, i: usize,
|
||||
w
|
||||
}
|
||||
|
||||
/// Does the curvature of `seg` stay below one over `side` all along it? A curve's first derivative
|
||||
/// is a mix of its three control differences, and its second a mix of their two differences, which
|
||||
/// bound the curvature from above. Then the edges of a stroke reaching `side` from it do not fold
|
||||
/// back, and those edges reach farthest at the ends of `seg` or where its tangent is square to an
|
||||
/// axis.
|
||||
fn gentle(seg: &PathSeg, side: f64) -> bool {
|
||||
let c = seg.to_cubic();
|
||||
let d = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2].map(|v| v * 3.0);
|
||||
let along = unit(d[0] + d[1] + d[2]);
|
||||
let slowest = d.iter().map(|v| v.dot(along)).fold(f64::INFINITY, f64::min);
|
||||
let bend = 2.0 * (d[1] - d[0]).hypot().max((d[2] - d[1]).hypot());
|
||||
slowest > 0.0 && side * bend < slowest * slowest
|
||||
}
|
||||
|
||||
/// The box a stroke reaching `side` from `seg` paints across it, from the directions its tangent
|
||||
/// can take: the tangent is a mix of the nonzero control differences, so when their directions all
|
||||
/// lie within a quarter turn of the directions' sum, every point across the stroke is in `seg`'s
|
||||
/// box moved `side` along a normal of one of those directions. `None` when they do not. A handle on
|
||||
/// its end point adds no direction, so a straight curve with one measures as a line.
|
||||
fn turning_box(seg: &PathSeg, side: f64) -> Option<Rect> {
|
||||
let c = seg.to_cubic();
|
||||
let d = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2];
|
||||
let moving = || d.iter().map(|v| (*v, v.hypot())).filter(|(_, h)| *h > 0.0).map(|(v, h)| v / h);
|
||||
let along = unit(moving().fold(Vec2::ZERO, |s, v| s + v));
|
||||
if moving().any(|v| v.dot(along) <= 0.0) {
|
||||
return None;
|
||||
}
|
||||
let angle = |v: &Vec2| along.cross(*v).atan2(along.dot(*v));
|
||||
let lo = moving().min_by(|a, b| angle(a).total_cmp(&angle(b)))?;
|
||||
let hi = moving().max_by(|a, b| angle(a).total_cmp(&angle(b)))?;
|
||||
let n = |t: Vec2| (Vec2::new(t.y, -t.x) * side).to_point();
|
||||
let one_side = round_join_box(Point::ZERO, lo, hi, side).unwrap_or_else(|| Rect::from_points(n(lo), n(hi)));
|
||||
let reach = one_side.union(Rect::new(-one_side.x1, -one_side.y1, -one_side.x0, -one_side.y0));
|
||||
let b = ParamCurveExtrema::bounding_box(seg);
|
||||
Some(Rect::new(b.x0 + reach.x0, b.y0 + reach.y0, b.x1 + reach.x1, b.y1 + reach.y1))
|
||||
}
|
||||
|
||||
/// The box a stroke reaching `side` from `seg` paints when it stops square at both ends of `seg`:
|
||||
/// the corners at the ends and the points across the stroke where the tangent is square to an axis.
|
||||
/// A curve that bends tighter than `side` is halved up to `depth` times, and a piece still bending
|
||||
/// that much is measured by [`turning_box`], or grown by `side` on every side when its tangent
|
||||
/// turns too far.
|
||||
fn swept_box(seg: &PathSeg, side: f64, depth: u32) -> Rect {
|
||||
if !matches!(seg, PathSeg::Line(_)) && !gentle(seg, side) {
|
||||
if depth == 0 {
|
||||
return turning_box(seg, side).unwrap_or_else(|| ParamCurveExtrema::bounding_box(seg).inflate(side, side));
|
||||
}
|
||||
return swept_box(&seg.subsegment(0.0..0.5), side, depth - 1).union(swept_box(&seg.subsegment(0.5..1.0), side, depth - 1));
|
||||
}
|
||||
let across = |t: f64| {
|
||||
let (p, tn) = (seg.eval(t), tangent(seg, t));
|
||||
let n = Vec2::new(-tn.y, tn.x) * side;
|
||||
[p + n, p - n]
|
||||
};
|
||||
let [a, b] = across(0.0);
|
||||
seg.extrema().into_iter().chain([1.0]).flat_map(across).fold(Rect::from_points(a, b), |r, p| r.union_pt(p))
|
||||
}
|
||||
|
||||
/// The box of the arc a round join paints `side` from `at`, where the path turns from tangent
|
||||
/// `t_in` to `t_out`: the arc runs on the outer side of the turn, and its box comes from its ends
|
||||
/// and the points on it square to an axis. A joint where the path turns back on itself is given
|
||||
/// the whole disc's box, and one where it does not turn paints no arc (`None`).
|
||||
fn round_join_box(at: Point, t_in: Vec2, t_out: Vec2, side: f64) -> Option<Rect> {
|
||||
let (t_in, t_out) = (unit(t_in), unit(t_out));
|
||||
let turn = t_in.cross(t_out);
|
||||
if turn.abs() < 1e-12 {
|
||||
return (t_in.dot(t_out) < 0.0).then(|| Rect::from_center_size(at, (2.0 * side, 2.0 * side)));
|
||||
}
|
||||
let s = turn.signum();
|
||||
let outer = |t: Vec2| Vec2::new(t.y, -t.x) * s;
|
||||
let (a, b) = (outer(t_in), outer(t_out));
|
||||
let axes = [Vec2::new(1.0, 0.0), Vec2::new(-1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.0, -1.0)];
|
||||
let arc = Rect::from_points(at + a * side, at + b * side);
|
||||
Some(axes.into_iter().filter(|d| a.cross(*d) * s >= 0.0 && d.cross(b) * s >= 0.0).fold(arc, |r, d| r.union_pt(at + d * side)))
|
||||
}
|
||||
|
||||
/// Is `p` inside the convex polygon `pts` (either winding), or within `tol` of it?
|
||||
fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
|
||||
let n = pts.len();
|
||||
@@ -115,39 +191,81 @@ fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
|
||||
|
||||
impl StrokeLayer {
|
||||
/// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads,
|
||||
/// or an alignment that depends on whether the path is closed? Else it reaches evenly round it.
|
||||
/// an alignment that depends on whether the path is closed, or butt caps, which stop at the
|
||||
/// ends of an open path? Else it reaches evenly round it.
|
||||
fn needs_shape(&self) -> bool {
|
||||
self.join == LineJoin::Miter
|
||||
|| self.cap == LineCap::Square
|
||||
|| self.cap != LineCap::Round
|
||||
|| self.start_arrow.is_some()
|
||||
|| self.end_arrow.is_some()
|
||||
|| self.align != StrokeAlign::Center
|
||||
}
|
||||
|
||||
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
|
||||
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
|
||||
/// The box this stroke paints along `segs`, the segments with length of an open subpath, when
|
||||
/// its caps are butt caps: each segment's [`swept_box`] and, with round joins, the arc each
|
||||
/// joint between segments paints ([`round_join_box`]), a shallow one included.
|
||||
/// `None` when `segs` is empty. Butt dashes stop inside the same box. The heads and miter tips
|
||||
/// are measured apart. A segment in the middle is measured only when its own box grown by
|
||||
/// `side`, which holds everything it paints, is not inside the box so far.
|
||||
fn butt_body(&self, segs: &[PathSeg], side: f64) -> Option<Rect> {
|
||||
let (first, last) = (segs.first()?, segs.last()?);
|
||||
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3));
|
||||
let body = segs.iter().skip(1).take(segs.len().saturating_sub(2)).fold(ends, |b, s| {
|
||||
if b.contains_rect(ParamCurveExtrema::bounding_box(s).inflate(side, side)) { b } else { b.union(swept_box(s, side, 3)) }
|
||||
});
|
||||
if self.join != LineJoin::Round {
|
||||
return Some(body);
|
||||
}
|
||||
Some(joints(segs, false).fold(body, |b, (at, t_in, t_out)| round_join_box(at, t_in, t_out, side).map_or(b, |j| b.union(j))))
|
||||
}
|
||||
|
||||
/// The box this stroke paints along `bp` (geometric bounds `bounds`): an open subpath with butt
|
||||
/// caps by [`Self::butt_body`], every other subpath by the box of its segments grown by its
|
||||
/// reach, with `tips` and, when `measure_tips`, the miter spikes the limit keeps, the corners of
|
||||
/// projecting caps and the reach of the arrowheads round their end points.
|
||||
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
|
||||
fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>, measure_tips: bool) -> Rect {
|
||||
let els = bp.elements();
|
||||
let mut out = bounds;
|
||||
let subs = subpaths(bp);
|
||||
let mut out = tips.map_or(bounds, |t| bounds.union(t));
|
||||
let mut side_max: f64 = 0.0;
|
||||
// Every subpath reaches evenly unless one is open and butt-capped; only then is each
|
||||
// subpath's own box needed.
|
||||
let even_only = self.cap != LineCap::Butt || subs.iter().all(|s| s.1);
|
||||
let mut even = even_only.then_some(bounds);
|
||||
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
|
||||
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
|
||||
for (r, closed) in subpaths(bp) {
|
||||
for (r, closed) in subs {
|
||||
let side = self.side_reach(closed);
|
||||
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
|
||||
let butt = self.cap == LineCap::Butt && !closed;
|
||||
if !butt {
|
||||
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
|
||||
}
|
||||
if side <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let square = self.cap == LineCap::Square && !closed;
|
||||
let miters = measure_tips && self.join == LineJoin::Miter;
|
||||
if !(butt || square || miters || !even_only) {
|
||||
continue;
|
||||
}
|
||||
let segs = drawn(&els[r]);
|
||||
if self.join == LineJoin::Miter {
|
||||
if miters {
|
||||
for (at, t_in, t_out) in joints(&segs, closed) {
|
||||
if let Some([_, tip, _]) = miter(at, t_in, t_out, side, self.miter_limit) {
|
||||
out = out.union_pt(tip);
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.cap == LineCap::Square && !closed {
|
||||
if butt {
|
||||
if let Some(body) = self.butt_body(&segs, side) {
|
||||
out = out.union(body);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !even_only {
|
||||
even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)));
|
||||
}
|
||||
if square {
|
||||
for (at, dir) in ends(&segs).into_iter().flatten() {
|
||||
let n = Vec2::new(-dir.y, dir.x) * side;
|
||||
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
|
||||
@@ -158,7 +276,15 @@ impl StrokeLayer {
|
||||
let r = self.head_reach(end);
|
||||
out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r)));
|
||||
}
|
||||
out.union(bounds.inflate(side_max, side_max))
|
||||
even.map_or(out, |e| out.union(e.inflate(side_max, side_max)))
|
||||
}
|
||||
|
||||
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
|
||||
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
|
||||
/// projecting caps and the reach of the arrowheads round their end points. An open subpath
|
||||
/// with butt caps does not reach past its ends ([`Self::butt_body`]).
|
||||
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
|
||||
self.reach_along(bp, bounds, None, true)
|
||||
}
|
||||
|
||||
/// The tip of the miter spike this stroke paints where segment `b` follows segment `a` in a
|
||||
@@ -176,30 +302,7 @@ impl StrokeLayer {
|
||||
/// every joint of `bp` ([`Self::miter_tip`]) or `None` when there are none, instead of measured
|
||||
/// along `bp`. It measures the projecting caps and arrowheads as [`Self::bounds_on`] does.
|
||||
pub fn bounds_with_tips(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>) -> Rect {
|
||||
let els = bp.elements();
|
||||
let mut out = tips.map_or(bounds, |t| bounds.union(t));
|
||||
let mut side_max: f64 = 0.0;
|
||||
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
|
||||
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
|
||||
for (r, closed) in subpaths(bp) {
|
||||
let side = self.side_reach(closed);
|
||||
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
|
||||
if side <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
if self.cap == LineCap::Square && !closed {
|
||||
let segs = drawn(&els[r]);
|
||||
for (at, dir) in ends(&segs).into_iter().flatten() {
|
||||
let n = Vec2::new(-dir.y, dir.x) * side;
|
||||
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (at, _, end) in head_ends(self, bp) {
|
||||
let r = self.head_reach(end);
|
||||
out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r)));
|
||||
}
|
||||
out.union(bounds.inflate(side_max, side_max))
|
||||
self.reach_along(bp, bounds, tips, false)
|
||||
}
|
||||
|
||||
/// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and
|
||||
@@ -314,7 +417,7 @@ impl Appearance {
|
||||
}
|
||||
|
||||
/// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape
|
||||
/// (miter spikes, projecting caps, arrowheads or an alignment) given by `shaped`.
|
||||
/// (miter spikes, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
|
||||
pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect {
|
||||
self.painted_strokes().fold(bounds, |acc, s| {
|
||||
if !s.needs_shape() {
|
||||
@@ -325,6 +428,30 @@ impl Appearance {
|
||||
})
|
||||
}
|
||||
|
||||
/// Does this appearance have a visible butt-capped stroke?
|
||||
pub fn has_butt_stroke(&self) -> bool {
|
||||
self.painted_strokes().any(|s| s.cap == LineCap::Butt)
|
||||
}
|
||||
|
||||
/// Does a visible butt-capped stroke of this appearance run along an open subpath of `bp` with
|
||||
/// a segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
|
||||
/// visual box's margin at the stroke's corners there depends on their direction, which a scale
|
||||
/// out of proportion changes.
|
||||
pub fn has_slanted_butt_stroke(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
|
||||
if !self.has_butt_stroke() {
|
||||
return false;
|
||||
}
|
||||
let slanted = |v: Vec2| {
|
||||
let d = unit(a * v.to_point() - a * Point::ZERO);
|
||||
(d.x * d.y).abs() > 1e-9
|
||||
};
|
||||
let els = bp.elements();
|
||||
subpaths(bp)
|
||||
.into_iter()
|
||||
.filter(|(_, closed)| !closed)
|
||||
.any(|(r, _)| drawn(&els[r]).iter().any(|s| slanted(tangent(s, 0.0)) || slanted(tangent(s, 1.0))))
|
||||
}
|
||||
|
||||
/// Does a visible stroke of this appearance along `bp` (filled with `rule`) paint within
|
||||
/// `tol` of `p` ([`StrokeLayer::hits`])?
|
||||
pub fn stroke_hit(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool {
|
||||
@@ -332,6 +459,31 @@ impl Appearance {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many symbol instances [`crate::Node::has_slanted_butt_stroke`] looks into for one object
|
||||
/// before it answers yes without looking further.
|
||||
pub const SLANT_INSTANCES: usize = 4096;
|
||||
|
||||
impl crate::Node {
|
||||
/// Does a visible butt-capped stroke of this object, of an object in it or of an object in a
|
||||
/// symbol instance's art from `symbols`, placed by `a`, run along an open path with a segment
|
||||
/// at a slant ([`Appearance::has_slanted_butt_stroke`])? Past [`SLANT_INSTANCES`] instances it
|
||||
/// answers yes.
|
||||
pub fn has_slanted_butt_stroke(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
|
||||
self.slanted_butt(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
|
||||
}
|
||||
|
||||
/// [`Self::has_slanted_butt_stroke`] with `left` instances still to look into.
|
||||
fn slanted_butt(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> 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_butt(symbols, a * *xf, left)).unwrap_or(false);
|
||||
}
|
||||
(self.appearance.has_butt_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_butt_stroke(&bp, a)))
|
||||
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_butt(symbols, a, left)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
@@ -378,7 +530,7 @@ mod tests {
|
||||
let (small, big) = (at(100.0).bounds_on(&l, b), at(300.0).bounds_on(&l, b));
|
||||
assert!(big.x1 > small.x1 + 15.0 && big.y1 > small.y1 + 7.0, "{small:?} → {big:?}");
|
||||
// A 300% head on a 2 pt stroke is 24 pt long and wide: its tip, past the end, is inside.
|
||||
assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == -1.0, "{big:?}");
|
||||
assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == 0.0, "{big:?}");
|
||||
// The start has no head.
|
||||
assert_eq!(at(300.0).head_reach(false), 0.0);
|
||||
}
|
||||
@@ -405,6 +557,203 @@ mod tests {
|
||||
assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Outside).bounds_on(&sq, b), b.inflate(4.0, 4.0));
|
||||
}
|
||||
|
||||
/// An open path through `points`.
|
||||
fn polyline(points: &[(f64, f64)]) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
for (i, p) in points.iter().enumerate() {
|
||||
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn butt_caps_stop_at_the_ends_of_an_open_path() {
|
||||
let butt = |f: fn(&mut StrokeLayer)| {
|
||||
stroke(2.0, |s| {
|
||||
s.cap = LineCap::Butt;
|
||||
f(s);
|
||||
})
|
||||
};
|
||||
// A vertical line reaches sideways only.
|
||||
let v = polyline(&[(50.0, 10.0), (50.0, 60.0)]);
|
||||
assert_eq!(butt(|_| {}).bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
|
||||
// A 3-4-5 diagonal: its corners reach 0.8 pt across x and 0.6 pt across y.
|
||||
let d = polyline(&[(0.0, 0.0), (30.0, 40.0)]);
|
||||
let b = butt(|_| {}).bounds_on(&d, d.bounding_box());
|
||||
for (got, want) in [(b.x0, -0.8), (b.y0, -0.6), (b.x1, 30.8), (b.y1, 40.6)] {
|
||||
assert!((got - want).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
// The dashes of a butt stroke stop inside the line as well, and an open path ignores the
|
||||
// alignment.
|
||||
let dashed = butt(|s| s.dash = Some(Dash { pattern: vec![4.0, 2.0], offset: 0.0, align_corners: false }));
|
||||
assert_eq!(dashed.bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
|
||||
assert_eq!(butt(|s| s.align = StrokeAlign::Inside).bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
|
||||
// A round cap reaches half the weight past each end, a square one the corners.
|
||||
let round = butt(|s| s.cap = LineCap::Round).bounds_on(&v, v.bounding_box());
|
||||
assert_eq!(round, Rect::new(49.0, 9.0, 51.0, 61.0));
|
||||
let square = butt(|s| s.cap = LineCap::Square).bounds_on(&v, v.bounding_box());
|
||||
assert_eq!(square, Rect::new(49.0, 9.0, 51.0, 61.0));
|
||||
// Two strokes union.
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
|
||||
ap.stroke_mut().unwrap().cap = LineCap::Butt;
|
||||
let wide = stroke(10.0, |s| s.cap = LineCap::Round);
|
||||
ap.items.push(crate::AppearanceItem::Stroke(wide));
|
||||
let vb = v.bounding_box();
|
||||
assert_eq!(ap.stroked_bounds(vb, || v.clone()), Rect::new(45.0, 5.0, 55.0, 65.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_butt_paths_joins_and_curves_stay_inside_the_box() {
|
||||
// A corner in the middle: the round join reaches a full half weight straight down, outside
|
||||
// the turn, the ends do not, and a miter reaches its tip.
|
||||
let zig = polyline(&[(0.0, 0.0), (20.0, 20.0), (40.0, 0.0)]);
|
||||
let round = stroke(4.0, |s| {
|
||||
s.cap = LineCap::Butt;
|
||||
s.join = LineJoin::Round;
|
||||
})
|
||||
.bounds_on(&zig, zig.bounding_box());
|
||||
assert!((round.y1 - 22.0).abs() < 1e-9, "the round join's reach: {round:?}");
|
||||
assert!((round.x0 + 2.0_f64.sqrt()).abs() < 1e-9 && (round.x1 - 40.0 - 2.0_f64.sqrt()).abs() < 1e-9, "the ends' corners: {round:?}");
|
||||
// A round join paints its arc on the outer side of a turn too shallow to count as a
|
||||
// corner, and nothing where the path goes straight on.
|
||||
let round_butt = stroke(4.0, |s| {
|
||||
s.cap = LineCap::Butt;
|
||||
s.join = LineJoin::Round;
|
||||
});
|
||||
let shallow = polyline(&[(0.0, 0.25), (50.0, 0.0), (100.0, 0.25)]);
|
||||
let b = round_butt.bounds_on(&shallow, shallow.bounding_box());
|
||||
assert!((b.y0 + 2.0).abs() < 1e-12, "{b:?}");
|
||||
let straight = polyline(&[(0.0, 0.0), (0.1, 0.0), (100.0, 0.0)]);
|
||||
assert_eq!(round_butt.bounds_on(&straight, straight.bounding_box()), Rect::new(0.0, -2.0, 100.0, 2.0));
|
||||
let miter = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&zig, zig.bounding_box());
|
||||
assert!((miter.y1 - (20.0 + 2.0 * 2.0_f64.sqrt())).abs() < 1e-9, "the miter tip: {miter:?}");
|
||||
// An arc over the top whose ends leave the page straight down: the top reaches half the
|
||||
// weight past the path, and the bottom stops at the ends.
|
||||
let mut arc = BezPath::new();
|
||||
arc.move_to((0.0, 50.0));
|
||||
arc.curve_to((0.0, 22.4), (22.4, 0.0), (50.0, 0.0));
|
||||
arc.curve_to((77.6, 0.0), (100.0, 22.4), (100.0, 50.0));
|
||||
let b = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&arc, arc.bounding_box());
|
||||
assert!((b.y0 + 2.0).abs() < 1e-9 && (b.x0 + 2.0).abs() < 1e-9 && (b.x1 - 102.0).abs() < 1e-9, "{b:?}");
|
||||
assert!((b.y1 - 50.0).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_butt_curve_with_a_handle_on_its_end_point_stops_near_that_end() {
|
||||
let butt = stroke(2.0, |s| s.cap = LineCap::Butt);
|
||||
// A straight curve whose first or last handle sits on its end point measures like a line.
|
||||
let mut first = BezPath::new();
|
||||
first.move_to((50.0, 10.0));
|
||||
first.curve_to((50.0, 10.0), (50.0, 40.0), (50.0, 60.0));
|
||||
let mut last = BezPath::new();
|
||||
last.move_to((50.0, 10.0));
|
||||
last.curve_to((50.0, 20.0), (50.0, 60.0), (50.0, 60.0));
|
||||
for bp in [first, last] {
|
||||
assert_eq!(butt.bounds_on(&bp, bp.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
|
||||
}
|
||||
// A bend that leaves its start straight up from a handle on the start point: the stroke
|
||||
// reaches only a little below the start, not half the weight.
|
||||
let mut bend = BezPath::new();
|
||||
bend.move_to((0.0, 50.0));
|
||||
bend.curve_to((0.0, 50.0), (0.0, 0.0), (50.0, 0.0));
|
||||
let b = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&bend, bend.bounding_box());
|
||||
assert!(b.y1 >= 50.0 && b.y1 < 50.2, "{b:?}");
|
||||
assert!((b.x0 + 2.0).abs() < 1e-9 && (b.y0 + 2.0).abs() < 1e-9 && (b.x1 - 50.0).abs() < 1e-9, "{b:?}");
|
||||
// Nearly a cusp: the curve turns back at its lowest point, where its tangent is level and
|
||||
// the stroke reaches the full half weight below it.
|
||||
let (a0, a1, a2) = (1e5 * 81.0 / 256.0, -1e5 * 9.0 / 8.0, 1e5);
|
||||
let x = |i: f64| 2e-9 * i / 3.0;
|
||||
let mut cusp = BezPath::new();
|
||||
cusp.move_to((x(0.0), a0));
|
||||
cusp.curve_to((x(1.0), a0 + a1 / 3.0), (x(2.0), a0 + 2.0 * a1 / 3.0 + a2 / 3.0), (x(3.0), a0 + a1 + a2));
|
||||
let b = butt.bounds_on(&cusp, cusp.bounding_box());
|
||||
assert!(b.y0 <= -1.0 + 1e-6, "{b:?}");
|
||||
// A curve far shorter than the weight still reaches half the weight above where its
|
||||
// tangent is level.
|
||||
let mut tiny = BezPath::new();
|
||||
tiny.move_to((0.0, 0.9e-12));
|
||||
tiny.curve_to((0.3e-12, -0.5e-12), (1.7e-12, -0.2e-12), (2e-12, 1e-12));
|
||||
let b = butt.bounds_on(&tiny, tiny.bounding_box());
|
||||
assert!(b.y0 <= -1.0 + 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_butt_stroke_is_slanted_where_a_segment_starts_or_ends_at_a_slant() {
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
|
||||
ap.stroke_mut().unwrap().cap = LineCap::Butt;
|
||||
let id = vectorcraft_geom::Affine::IDENTITY;
|
||||
assert!(!ap.has_slanted_butt_stroke(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
|
||||
// Square ends, slanted segments in the middle.
|
||||
let apex = polyline(&[(0.0, 50.0), (0.0, 40.0), (10.0, 0.0), (20.0, 40.0), (20.0, 50.0)]);
|
||||
assert!(ap.has_slanted_butt_stroke(&apex, id));
|
||||
// A rotation slants a vertical line; a round cap is never slanted.
|
||||
let v = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
|
||||
assert!(ap.has_slanted_butt_stroke(&v, vectorcraft_geom::Affine::rotate(0.3)));
|
||||
ap.stroke_mut().unwrap().cap = LineCap::Round;
|
||||
assert!(!ap.has_slanted_butt_stroke(&apex, id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_slant_check_looks_into_at_most_4096_symbol_instances() {
|
||||
// S0 is a vertical butt line. Each of S1 to S12 holds two instances of the symbol before
|
||||
// it, so an instance of S12 holds 8,191 instances and none of them is slanted. Past 4,096
|
||||
// the check answers yes.
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
|
||||
ap.stroke_mut().unwrap().cap = LineCap::Butt;
|
||||
let line = Node::path(d.alloc_id(), PathData::from_bezpath(&polyline(&[(0.0, 0.0), (0.0, 10.0)])), ap);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "S0".into(), art: std::sync::Arc::new(line) });
|
||||
for k in 1..=12 {
|
||||
let mut instance = |dx: f64| {
|
||||
let xf = vectorcraft_geom::Affine::translate((dx, 0.0));
|
||||
std::sync::Arc::new(Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: format!("S{}", k - 1), xf }))
|
||||
};
|
||||
let pair = vec![instance(0.0), instance(20.0)];
|
||||
let art = Node::group(d.alloc_id(), pair);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: format!("S{k}"), art: std::sync::Arc::new(art) });
|
||||
}
|
||||
let top = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S12".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let symbols = d.symbol_boxes();
|
||||
assert!(top.has_slanted_butt_stroke(&symbols, vectorcraft_geom::Affine::IDENTITY));
|
||||
assert!(symbols.art_measured() <= SLANT_INSTANCES, "{}", symbols.art_measured());
|
||||
// One instance of S1 holds three instances, all looked into.
|
||||
let one = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S1".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
assert!(!one.has_slanted_butt_stroke(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_path_measures_each_of_its_subpaths_by_its_own_ends() {
|
||||
// A closed square at the top and an open line below it: only the square reaches past its
|
||||
// own edges.
|
||||
let mut bp = BezPath::new();
|
||||
bp.extend(square().elements().iter().copied());
|
||||
bp.move_to((50.0, 150.0));
|
||||
bp.line_to((50.0, 200.0));
|
||||
let st = stroke(4.0, |s| s.cap = LineCap::Butt);
|
||||
assert_eq!(st.bounds_on(&bp, bp.bounding_box()), Rect::new(-2.0, -2.0, 102.0, 200.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_middle_segment_can_set_the_box_of_a_butt_path() {
|
||||
// The flat middle segment reaches a full half weight above the path, and the ends' corners
|
||||
// reach 10/51 of it below.
|
||||
let hat = polyline(&[(0.0, 50.0), (10.0, 0.0), (20.0, 0.0), (30.0, 50.0)]);
|
||||
let b = stroke(2.0, |s| {
|
||||
s.cap = LineCap::Butt;
|
||||
s.join = LineJoin::Bevel;
|
||||
})
|
||||
.bounds_on(&hat, hat.bounding_box());
|
||||
let corner = 10.0 / (10.0_f64 * 10.0 + 50.0 * 50.0).sqrt();
|
||||
assert!((b.y0 + 1.0).abs() < 1e-9 && (b.y1 - 50.0 - corner).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_with_tips_measures_a_butt_line_as_bounds_on_does() {
|
||||
let v = polyline(&[(50.0, 10.0), (50.0, 60.0)]);
|
||||
let st = stroke(2.0, |s| s.cap = LineCap::Butt);
|
||||
assert_eq!(st.bounds_with_tips(&v, v.bounding_box(), None), Rect::new(49.0, 10.0, 51.0, 60.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_hit_outside_strokes_on_their_side_only() {
|
||||
let sq = square();
|
||||
|
||||
@@ -121,6 +121,12 @@ pub struct TextObject {
|
||||
/// vertical column's centre line), filled in with `cached_bounds` (not serialized).
|
||||
#[serde(skip)]
|
||||
pub cached_baselines: Vec<(Point, Point)>,
|
||||
/// Cached ink of the glyphs in text space, underline and strikethrough bars included
|
||||
/// (`vectorcraft_effects::preview::laid_out_ink`, `None` when nothing draws),
|
||||
/// with the `cached_bounds` it was measured with: filled in with `cached_bounds` by the engine's
|
||||
/// text edits, and stale once `cached_bounds` differs ([`Self::ink`]). Not serialized.
|
||||
#[serde(skip)]
|
||||
pub cached_ink: Option<(Rect, Option<Rect>)>,
|
||||
}
|
||||
|
||||
/// Conversion from stored character attributes to document-space type controls.
|
||||
|
||||
@@ -71,6 +71,7 @@ impl TextObject {
|
||||
self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
|
||||
self.cached_bounds = None;
|
||||
self.cached_baselines.clear();
|
||||
self.cached_ink = None;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -97,6 +98,7 @@ impl TextObject {
|
||||
list_level_counts: Vec::new(),
|
||||
cached_bounds: None,
|
||||
cached_baselines: Vec::new(),
|
||||
cached_ink: None,
|
||||
}
|
||||
}
|
||||
/// The list counts the story's earlier frames carry into this frame at each level
|
||||
@@ -288,6 +290,12 @@ impl TextObject {
|
||||
TextKind::Point => Some(self.xf.transform_rect_bbox(self.cached_bounds.unwrap_or_else(|| self.estimate_bounds()))),
|
||||
}
|
||||
}
|
||||
/// The cached ink of the glyphs in text space ([`Self::cached_ink`]): `Some(None)` when nothing
|
||||
/// draws, and `None` when it was not measured with the current `cached_bounds`.
|
||||
pub fn ink(&self) -> Option<Option<Rect>> {
|
||||
let (bounds, ink) = self.cached_ink?;
|
||||
(self.cached_bounds == Some(bounds)).then_some(ink)
|
||||
}
|
||||
/// How far the characters' strokes paint past their glyphs, in document space: they scale
|
||||
/// with the type.
|
||||
pub fn char_stroke_outset(&self) -> f64 {
|
||||
|
||||
@@ -603,7 +603,7 @@ fn a_baked_transform_copy_keeps_its_scaled_stroke() {
|
||||
let m = bake_appearance(None, &n).unwrap();
|
||||
let w = widths(&m);
|
||||
assert_eq!(w.len(), 2, "{w:?}");
|
||||
assert!((w[0] - 102.0).abs() < 0.5 && (w[1] - 204.0).abs() < 0.5, "{w:?}");
|
||||
assert!((w[1] - 102.0).abs() < 0.5 && (w[0] - 204.0).abs() < 0.5, "the original on top: {w:?}");
|
||||
assert!(baked_paths(&m).iter().all(|p| p.appearance.stroke().is_none()), "the strokes are outlined");
|
||||
}
|
||||
|
||||
@@ -619,7 +619,7 @@ fn a_baked_transform_copy_keeps_its_moved_pattern() {
|
||||
p => panic!("not a pattern: {p:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(xs, vec![0.0, 30.0]);
|
||||
assert_eq!(xs, vec![30.0, 0.0], "the original on top");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -247,7 +247,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"distort.transform",
|
||||
"Transform…",
|
||||
DT,
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}",
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}",
|
||||
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
|
||||
),
|
||||
g(
|
||||
|
||||
@@ -594,7 +594,7 @@ fn a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills() {
|
||||
};
|
||||
for kind in [image as fn() -> NodeKind, instance] {
|
||||
assert_eq!(starts(kind(), serde_json::json!({"moveH": 30})), [30.0], "{:?}", kind());
|
||||
assert_eq!(starts(kind(), serde_json::json!({"moveH": 30, "copies": 2})), [0.0, 30.0, 60.0], "{:?}", kind());
|
||||
assert_eq!(starts(kind(), serde_json::json!({"moveH": 30, "copies": 2})), [60.0, 30.0, 0.0], "{:?}", kind());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -677,7 +677,8 @@ fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() {
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let copies = art.children().unwrap()[0].children().expect("the object and its copies are objects of their own");
|
||||
assert_eq!(copies.len(), 3);
|
||||
for (i, c) in copies.iter().enumerate() {
|
||||
// The original is on top, after the copies below it.
|
||||
for (i, c) in copies.iter().rev().enumerate() {
|
||||
// Each copy's own box: an unplaced gradient fits it, a placed one moved with it.
|
||||
assert!((c.geometric_bounds().unwrap().x0 - 30.0 * i as f64).abs() < 1e-6);
|
||||
match c.appearance.fill_paint() {
|
||||
|
||||
@@ -87,7 +87,7 @@ pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_r
|
||||
pub use solids::{
|
||||
CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options,
|
||||
classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, three_d_meshes, three_d_meshes_of, three_d_params_as,
|
||||
validate_solid, validate_three_d, validate_three_d_params, view_options,
|
||||
validate_solid, validate_three_d, validate_three_d_at, validate_three_d_params, view_options,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
//! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows,
|
||||
//! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured
|
||||
//! with its geometry effects, and the other instances in it are measured without them.
|
||||
//! [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure as these do and,
|
||||
//! with [`Measure::glyphs`], take point type by the ink of its glyphs (Measure Type by Glyph Bounds).
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
@@ -74,6 +76,121 @@ pub fn anchor_bounds(selection: &Selection, doc: &Document, preview: bool) -> Op
|
||||
union_opt(bounds_of(doc, &selection.whole(), preview), selection.anchors_box(doc))
|
||||
}
|
||||
|
||||
/// How [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure objects:
|
||||
/// `preview` as in [`bounds_of`], and with `glyphs` (Preferences › Type › Measure Type by Glyph
|
||||
/// Bounds), point type, horizontal or vertical, by the ink of its glyphs instead of its em box
|
||||
/// ([`text_ink_in`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Measure {
|
||||
pub preview: bool,
|
||||
pub glyphs: bool,
|
||||
}
|
||||
|
||||
impl Measure {
|
||||
/// See [`by_glyphs`].
|
||||
fn by_glyphs(self, drawn: &Drawn, n: &Node) -> bool {
|
||||
self.glyphs
|
||||
&& matches!(&n.kind, NodeKind::Text(t) if matches!(t.kind, vectorcraft_doc::TextKind::Point))
|
||||
&& n.projection().is_none()
|
||||
&& !(self.preview && drawn.draws_geometry(n))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `m` measures `n` by the ink of its glyphs: point type, not in perspective, and with
|
||||
/// `preview` only when no geometry effect changes what it draws.
|
||||
pub fn by_glyphs(symbols: &SymbolBoxes, n: &Node, m: Measure) -> bool {
|
||||
m.by_glyphs(&Drawn::new(symbols), n)
|
||||
}
|
||||
|
||||
/// [`bounds_of`] measured by `m`.
|
||||
pub fn bounds_of_with(doc: &Document, ids: &[NodeId], m: Measure) -> Option<Rect> {
|
||||
if !m.glyphs {
|
||||
return bounds_of(doc, ids, m.preview);
|
||||
}
|
||||
let symbols = doc.symbol_boxes();
|
||||
let drawn = Drawn::new(&symbols);
|
||||
if !ids.iter().filter_map(|id| doc.node(*id)).any(|n| m.by_glyphs(&drawn, n)) {
|
||||
return bounds_of(doc, ids, m.preview);
|
||||
}
|
||||
ids.iter().filter_map(|id| doc.node(*id)).fold(None, |acc, n| union_opt(acc, measured_in(&drawn, n, Affine::IDENTITY, m)))
|
||||
}
|
||||
|
||||
/// [`oriented_bounds`] measured by `m`.
|
||||
pub fn oriented_bounds_with(doc: &Document, ids: &[NodeId], m: Measure) -> Option<OrientedBox> {
|
||||
if !m.glyphs {
|
||||
return oriented_bounds(doc, ids, m.preview);
|
||||
}
|
||||
let symbols = doc.symbol_boxes();
|
||||
let drawn = Drawn::new(&symbols);
|
||||
if !ids.iter().filter_map(|id| doc.node(*id)).any(|n| m.by_glyphs(&drawn, n)) {
|
||||
return oriented_bounds(doc, ids, m.preview);
|
||||
}
|
||||
let angle = doc.bbox_angle(ids);
|
||||
let to_local = if angle == 0.0 { Affine::IDENTITY } else { OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse() };
|
||||
let rect = ids.iter().filter_map(|id| doc.node(*id)).fold(None, |acc, n| union_opt(acc, measured_in(&drawn, n, to_local, m)))?;
|
||||
Some(OrientedBox { angle, rect })
|
||||
}
|
||||
|
||||
/// [`anchor_bounds`] with the objects selected whole measured by `m`.
|
||||
pub fn anchor_bounds_with(selection: &Selection, doc: &Document, m: Measure) -> Option<Rect> {
|
||||
if selection.anchors.is_empty() {
|
||||
return None;
|
||||
}
|
||||
union_opt(bounds_of_with(doc, &selection.whole(), m), selection.anchors_box(doc))
|
||||
}
|
||||
|
||||
/// The box of `n` as `a` would place it, without changing it, measured by `m`: [`bounds_in`] with
|
||||
/// `preview`, else [`Node::bounds_in`] of its geometric bounds, and point type by its glyphs as
|
||||
/// [`Measure`] says.
|
||||
pub fn bounds_in_with(symbols: &SymbolBoxes, n: &Node, a: Affine, m: Measure) -> Option<Rect> {
|
||||
measured_in(&Drawn::new(symbols), n, a, m)
|
||||
}
|
||||
|
||||
/// See [`bounds_in_with`].
|
||||
fn measured_in(drawn: &Drawn, n: &Node, a: Affine, m: Measure) -> Option<Rect> {
|
||||
if m.by_glyphs(drawn, n)
|
||||
&& let NodeKind::Text(t) = &n.kind
|
||||
&& let Some(r) = text_ink_in(t, a)
|
||||
{
|
||||
// The fills' and characters' strokes paint around the glyphs, as in `Node::visual_bounds`.
|
||||
let o = if m.preview { n.appearance.outset().max(t.char_stroke_outset()) } else { 0.0 };
|
||||
return Some(r.inflate(o, o));
|
||||
}
|
||||
match (m.preview, a == Affine::IDENTITY) {
|
||||
(true, _) => drawn.next().bounds_in(n, a),
|
||||
(false, true) => n.geometric_bounds_with(drawn.symbols),
|
||||
(false, false) => n.bounds_in(drawn.symbols, a, false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The box of the ink of type `t`'s glyphs with its text space mapped by `a * t.xf`: the cached
|
||||
/// ink ([`vectorcraft_doc::TextObject::ink`]) when that map keeps a rectangle square, else the
|
||||
/// glyph outlines and the underline and strikethrough bars mapped point by point
|
||||
/// ([`vectorcraft_text::envelope_ink`]). `None` when nothing draws (no text, only spaces without
|
||||
/// underline or strikethrough, or glyphs without outlines).
|
||||
pub fn text_ink_in(t: &vectorcraft_doc::TextObject, a: Affine) -> Option<Rect> {
|
||||
let m = a * t.xf;
|
||||
let [p, q, r, s, _, _] = m.as_coeffs();
|
||||
let square = (q.abs() <= 1e-12 && r.abs() <= 1e-12) || (p.abs() <= 1e-12 && s.abs() <= 1e-12);
|
||||
if square {
|
||||
let ink = match t.ink() {
|
||||
Some(ink) => ink,
|
||||
None => vectorcraft_text::envelope_ink(t, Affine::IDENTITY, None),
|
||||
};
|
||||
return ink.map(|i| m.transform_rect_bbox(i));
|
||||
}
|
||||
vectorcraft_text::envelope_ink(t, m, None)
|
||||
}
|
||||
|
||||
/// The ink of type `t` laid out as `layout`, in text space: its glyphs
|
||||
/// ([`vectorcraft_text::TextLayout::ink_bounds`]) and its underline and strikethrough bars
|
||||
/// ([`vectorcraft_text::decorations`]), what [`text_ink_in`] measures. `None` when nothing draws.
|
||||
pub fn laid_out_ink(layout: &vectorcraft_text::TextLayout, t: &vectorcraft_doc::TextObject) -> Option<Rect> {
|
||||
vectorcraft_text::decorations(layout, vectorcraft_text::FontDb::global(), t)
|
||||
.into_iter()
|
||||
.fold(layout.ink_bounds(), |acc, (_, bar)| union_opt(acc, Some(bar.bounding_box())))
|
||||
}
|
||||
|
||||
/// The visual bounds of `n` as drawn: those of its [`drawn_art`], else
|
||||
/// [`Node::visual_bounds_with`].
|
||||
pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
|
||||
+183
-29
@@ -46,8 +46,8 @@ pub fn has_gradient_copies(n: &Node) -> bool {
|
||||
/// Is `n` a path or compound path with a visible Transform effect that makes copies and fills and
|
||||
/// strokes that paint the copies differently as one path than as separate objects
|
||||
/// ([`paints_copies_apart`])? Such an object is drawn through its art ([`outline_art`]), each copy
|
||||
/// an object of its own above the one before ([`copy_leaf`]), as Expand Appearance makes it
|
||||
/// (#5920).
|
||||
/// an object of its own below the one before ([`copy_leaf`]), as Expand Appearance makes it
|
||||
/// (#5920, #6316).
|
||||
pub(crate) fn has_layered_copies(n: &Node) -> bool {
|
||||
leaf_geometry(n).is_some_and(|(_, rule)| paints_copies_apart(&n.appearance, rule)) && has_transform_copies(n)
|
||||
}
|
||||
@@ -698,6 +698,8 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
|
||||
let seed = art.id.0;
|
||||
let mut used = art_cost(art);
|
||||
let max = budget.at_least(used);
|
||||
// Read before the effects run: a path's own copies don't make it art of several objects.
|
||||
let copy_whole = copies_whole(art);
|
||||
for e in fx {
|
||||
let Some(bounds) = art.geometric_bounds() else { break };
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
@@ -738,6 +740,14 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
(m, copies, options, crate::distort::transform_affine(bounds, ¶ms, seed))
|
||||
});
|
||||
// Art of several objects is copied whole, so the copies don't interleave member by member.
|
||||
if let Some((m, copies, options, _)) = transform
|
||||
&& copies > 0
|
||||
&& copy_whole
|
||||
{
|
||||
used = copy_art(art, m, copies, copy_scaling(options), max);
|
||||
continue;
|
||||
}
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
let Some((path, rule)) = leaf_geometry(leaf) else { return };
|
||||
// What the other paths leave of the budget.
|
||||
@@ -747,7 +757,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
|
||||
// Transform Patterns and Scale Strokes & Effects change each copy's fills and
|
||||
// strokes; a gradient paints each copy by itself, not the one piece the copies
|
||||
// make together; and Expand Appearance (`apart`) makes each copy an object.
|
||||
// Fills and strokes that stack paint each copy above the one before (#5920).
|
||||
// Fills and strokes that stack paint each copy below the one before (#5920, #6316).
|
||||
let separate = copies > 0
|
||||
&& (apart
|
||||
|| leaf.appearance.has_unplaced_gradient()
|
||||
@@ -813,6 +823,19 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
|
||||
/// doesn't grow with them (a horizontal line stretched vertically).
|
||||
const MAX_STROKE_SCALE: f64 = 1.0e6;
|
||||
|
||||
/// How a Transform effect with `options` scales what it maps: strokes, effects and patterns as
|
||||
/// its options say.
|
||||
fn copy_scaling(options: crate::distort::TransformOptions) -> vectorcraft_doc::Scaling {
|
||||
vectorcraft_doc::Scaling {
|
||||
strokes: options.strokes,
|
||||
effects: options.strokes.then_some(crate::scale_effect as fn(&mut Effect, f64)),
|
||||
patterns: options.patterns,
|
||||
// A map that flattens the path leaves its fitted gradients fitted, as `fixes_fit` does.
|
||||
keep_fit_when_flat: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect whose Transform Patterns or Scale Strokes & Effects is on (`options`), with
|
||||
/// map `m` and `copies`, applied to `leaf` (a path or compound path with geometry `path`) as Object
|
||||
/// › Transform with those options transforms an object (#885): the strokes' weights and dashes
|
||||
@@ -829,14 +852,7 @@ fn transform_leaf(
|
||||
options: crate::distort::TransformOptions,
|
||||
budget: Budget,
|
||||
) -> (Budget, bool) {
|
||||
let scaling = vectorcraft_doc::Scaling {
|
||||
strokes: options.strokes,
|
||||
effects: options.strokes.then_some(crate::scale_effect as fn(&mut Effect, f64)),
|
||||
patterns: options.patterns,
|
||||
// A map that flattens the path leaves its fitted gradients fitted, as `fixes_fit` does.
|
||||
keep_fit_when_flat: true,
|
||||
..Default::default()
|
||||
};
|
||||
let scaling = copy_scaling(options);
|
||||
if !options.objects {
|
||||
if options.strokes
|
||||
&& let Some(k) = vectorcraft_doc::Scaling::factor(m).filter(|k| k.is_finite() && *k > 0.0)
|
||||
@@ -861,36 +877,172 @@ fn transform_leaf(
|
||||
(copy_leaf(leaf, path, m, copies, scaling, budget), true)
|
||||
}
|
||||
|
||||
/// Replace `leaf` (a path or compound path with geometry `path`) by a group of it and `copies`
|
||||
/// more, each mapped once more by `m` than the last (with `scaling`), as a Transform effect copies
|
||||
/// an object. Each copy is an object of its own, so its gradients fit it (a placed gradient moves
|
||||
/// with it) rather than spanning every copy, and its strokes and patterns can differ from the
|
||||
/// others'. The copies stop where [`crate::distort::transform_within`]'s would, before they pass
|
||||
/// `budget`, and before one's strokes would scale past [`MAX_STROKE_SCALE`]. Returns what the
|
||||
/// copies cost, the original included.
|
||||
fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget {
|
||||
let mut made = Budget::of(path);
|
||||
let mut placements: Vec<Arc<Node>> = vec![Arc::new(leaf.clone())];
|
||||
/// Does a Transform effect's copies of `art` copy it whole ([`copy_art`])? They do when `art` is a
|
||||
/// group or layer of several objects, at least one of which paints, with no type left in it and no
|
||||
/// fill or stroke of its own that paints. Type that stays type is copied in its place by the baking
|
||||
/// that keeps it, a clipping group's first member is its clip, and the art's own fills and strokes
|
||||
/// paint the shape of everything under it, copies included. A member that [`makes_art`] is copied
|
||||
/// in its place as well: each copy would make that art again, past what [`copy_art`] counts.
|
||||
fn copies_whole(art: &Node) -> bool {
|
||||
fn parts(n: &Node, count: &mut usize, painted: &mut bool, text: &mut bool) {
|
||||
match &n.kind {
|
||||
NodeKind::Text(_) => *text = true,
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => {
|
||||
*count += 1;
|
||||
*painted |= n.appearance.items.iter().any(crate::paints);
|
||||
}
|
||||
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => {
|
||||
*count += 1;
|
||||
*painted = true;
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
*painted |= n.appearance.items.iter().any(crate::paints);
|
||||
children.iter().for_each(|c| parts(c, count, painted, text));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if art.clips() || !matches!(art.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || art.appearance.items.iter().any(crate::paints) {
|
||||
return false;
|
||||
}
|
||||
let (mut count, mut painted, mut text) = (0, false, false);
|
||||
parts(art, &mut count, &mut painted, &mut text);
|
||||
count > 1 && painted && !text && !art.children().into_iter().flatten().any(|c| makes_art(c))
|
||||
}
|
||||
|
||||
/// Does `n` or anything visible under it, the art of its opacity masks included, carry a visible
|
||||
/// effect that makes art when it is drawn (its own or that of a fill or stroke that paints), or is
|
||||
/// any of them a compound shape? Raster effects, color adjustments and unknown effects make none.
|
||||
fn makes_art(n: &Node) -> bool {
|
||||
let makes = |e: &Effect| {
|
||||
e.visible
|
||||
&& (is_geometry(&e.id)
|
||||
|| crate::is_pathfinder(&e.id)
|
||||
|| crate::is_three_d(&e.id)
|
||||
|| e.id == crate::CROP_MARKS
|
||||
|| e.id == crate::addons::halftone::HALFTONE)
|
||||
};
|
||||
n.visible
|
||||
&& (n.is_compound_shape()
|
||||
|| n.appearance.effects.iter().any(makes)
|
||||
|| n.appearance.items.iter().any(|i| crate::paints(i) && i.effects().iter().any(makes))
|
||||
|| n.extras().mask.as_deref().is_some_and(|m| makes_art(&m.art))
|
||||
|| n.children().into_iter().flatten().any(|c| makes_art(c)))
|
||||
}
|
||||
|
||||
/// What the paths under `n` cost together, those of its opacity masks included.
|
||||
fn copy_cost(n: &Node) -> Budget {
|
||||
let mut cost = Budget { anchors: 0, lines: 0 };
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| {
|
||||
if let NodeKind::Path { guide: false, path, .. } = &c.kind {
|
||||
cost = cost.plus(Budget::of(path));
|
||||
}
|
||||
});
|
||||
cost
|
||||
}
|
||||
|
||||
/// What the geometry effects of `leaf` (with geometry `path`) and of its fills and strokes add to
|
||||
/// what `path` costs when it is drawn.
|
||||
fn effects_cost(leaf: &Node, path: &PathData) -> Budget {
|
||||
let none = Budget { anchors: 0, lines: 0 };
|
||||
let items: Vec<&AppearanceItem> = leaf.appearance.items.iter().filter(|i| crate::paints(i) && crate::has_geometry(i.effects())).collect();
|
||||
if items.is_empty() && !crate::has_geometry(&leaf.appearance.effects) {
|
||||
return none;
|
||||
}
|
||||
let Some(bounds) = path.bounds() else { return none };
|
||||
let ctx = GeomContext { seed: leaf.id.0, ..GeomContext::of(leaf) };
|
||||
let own = crate::apply_geometry_with(&leaf.appearance.effects, path, bounds, &ctx);
|
||||
let item_cost = |i: &&AppearanceItem| {
|
||||
let b = own.bounds()?;
|
||||
Some(Budget::of(&crate::apply_geometry_with(i.effects(), &own, b, &ctx.item(i))))
|
||||
};
|
||||
// The object's geometry is drawn as it is only by what has no geometry effect of its own.
|
||||
let plain = items.is_empty() || leaf.appearance.items.iter().any(|i| crate::paints(i) && !crate::has_geometry(i.effects()));
|
||||
let base = if plain { Budget::of(&own) } else { none };
|
||||
base.plus(items.iter().filter_map(item_cost).fold(none, Budget::plus)).minus(Budget::of(path))
|
||||
}
|
||||
|
||||
/// Remove the guides anywhere under `n`.
|
||||
fn without_guides(n: &mut Node) {
|
||||
let Some(children) = n.children_mut() else { return };
|
||||
children.retain(|c| !matches!(c.kind, NodeKind::Path { guide: true, .. }));
|
||||
children.iter_mut().for_each(|c| without_guides(Arc::make_mut(c)));
|
||||
}
|
||||
|
||||
/// Replace the members of `art` by groups of them: the original on top and `copies` more below it,
|
||||
/// each mapped once more by `m` than the last (with `scaling`), as a Transform effect copies a
|
||||
/// group, without its guides. The copies stop where [`copy_leaf`]'s would, before they pass `budget` or
|
||||
/// [`crate::distort::MAX_COPY_OBJECTS`] nodes in all, the art of opacity masks counted. Returns what
|
||||
/// the art costs after.
|
||||
fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget {
|
||||
let Some(members) = art.children().cloned() else { return art_cost(art) };
|
||||
let original = Node::group(art.id, members);
|
||||
let mut made = copy_cost(&original);
|
||||
let mut drawn = original.clone();
|
||||
without_guides(&mut drawn);
|
||||
let mut nodes = original.count_with_masks();
|
||||
let one = drawn.count_with_masks();
|
||||
let mut placements: Vec<Arc<Node>> = vec![];
|
||||
let mut xf = Affine::IDENTITY;
|
||||
for _ in 0..copies {
|
||||
xf *= m;
|
||||
// A copy scaled up is drawn with more lines.
|
||||
let cost = Budget::of(&path.transformed(xf));
|
||||
if !budget.fits(made.plus(cost)) {
|
||||
break;
|
||||
}
|
||||
if scaling.strokes && vectorcraft_doc::Scaling::factor(xf).is_some_and(|k| !(k.is_finite() && k <= MAX_STROKE_SCALE)) {
|
||||
break;
|
||||
}
|
||||
let mut copy = leaf.clone();
|
||||
nodes = nodes.saturating_add(one);
|
||||
if nodes > crate::distort::MAX_COPY_OBJECTS {
|
||||
break;
|
||||
}
|
||||
let mut copy = drawn.clone();
|
||||
copy.transform(xf, scaling);
|
||||
if !copy.geometric_bounds().is_some_and(crate::distort::within_reach) {
|
||||
let cost = copy_cost(©);
|
||||
if !budget.fits(made.plus(cost)) || !copy.geometric_bounds().is_some_and(crate::distort::within_reach) {
|
||||
break;
|
||||
}
|
||||
placements.push(Arc::new(copy));
|
||||
made = made.plus(cost);
|
||||
}
|
||||
// The copies become nodes of their own under a group with the object's id and name.
|
||||
// The last copy is the lowest.
|
||||
placements.reverse();
|
||||
placements.push(Arc::new(original));
|
||||
if let Some(children) = art.children_mut() {
|
||||
*children = placements;
|
||||
}
|
||||
made
|
||||
}
|
||||
|
||||
/// Replace `leaf` (a path or compound path with geometry `path`) by a group of it and `copies`
|
||||
/// more below it, each mapped once more by `m` than the last (with `scaling`), as a Transform effect
|
||||
/// copies an object. Each copy is an object of its own, so its gradients fit it (a placed gradient
|
||||
/// moves with it) rather than spanning every copy, and its strokes and patterns can differ from the
|
||||
/// others'. The copies stop where [`crate::distort::transform_within`]'s would, before they pass
|
||||
/// `budget` with what each copy's own geometry effects make ([`effects_cost`]), and before one's
|
||||
/// strokes would scale past [`MAX_STROKE_SCALE`]. Returns what the copies cost, the original
|
||||
/// included.
|
||||
fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget {
|
||||
let mut made = Budget::of(path).plus(effects_cost(leaf, path));
|
||||
let mut placements: Vec<Arc<Node>> = vec![Arc::new(leaf.clone())];
|
||||
let mut xf = Affine::IDENTITY;
|
||||
for _ in 0..copies {
|
||||
xf *= m;
|
||||
// A copy scaled up is drawn with more lines.
|
||||
let moved = path.transformed(xf);
|
||||
if scaling.strokes && vectorcraft_doc::Scaling::factor(xf).is_some_and(|k| !(k.is_finite() && k <= MAX_STROKE_SCALE)) {
|
||||
break;
|
||||
}
|
||||
let mut copy = leaf.clone();
|
||||
copy.transform(xf, scaling);
|
||||
// Each copy's own geometry effects make a different amount, as the copy and its effects scale.
|
||||
let cost = Budget::of(&moved).plus(effects_cost(©, &moved));
|
||||
if !budget.fits(made.plus(cost)) || !copy.geometric_bounds().is_some_and(crate::distort::within_reach) {
|
||||
break;
|
||||
}
|
||||
placements.push(Arc::new(copy));
|
||||
made = made.plus(cost);
|
||||
}
|
||||
// The copies become nodes of their own under a group with the object's id and name, the object
|
||||
// on top.
|
||||
placements.reverse();
|
||||
let mut g = Node::group(leaf.id, placements);
|
||||
g.name = leaf.name.clone();
|
||||
*leaf = g;
|
||||
@@ -1463,6 +1615,8 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) {
|
||||
placements.push(Arc::new(copy));
|
||||
}
|
||||
*room -= placements.len() - 1;
|
||||
// The object stays on top of its copies, as a path does.
|
||||
placements.reverse();
|
||||
let mut g = Node::group(src.id, placements);
|
||||
g.name = src.name.clone();
|
||||
*c = Arc::new(g);
|
||||
|
||||
+744
-47
@@ -3,10 +3,11 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, LineJoin, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{PathData, Rect};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, LineJoin, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_three_d::{Edge, Revolve};
|
||||
|
||||
use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, solid_paints, union_bounds};
|
||||
use crate::util::{flag, num, text};
|
||||
use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
|
||||
|
||||
@@ -17,6 +18,13 @@ pub const REVOLVE: &str = "threeD.revolve";
|
||||
/// thousands of faces took gigabytes; past this the source path is drawn.
|
||||
const MAX_PAINT_COPIES: usize = 256 << 20;
|
||||
|
||||
/// The most face and box tests a group's transparent members' faces take together to rejoin their
|
||||
/// members' last runs; past them each starts a run of its own.
|
||||
const MAX_OVERLAP_TESTS: usize = 1 << 22;
|
||||
|
||||
/// The width of the stroke around each face that covers the seams between faces.
|
||||
const SEAM_WIDTH: f64 = 0.75;
|
||||
|
||||
/// About the bytes one copy of `paint` takes.
|
||||
fn paint_bytes(paint: &Paint) -> usize {
|
||||
use std::mem::size_of;
|
||||
@@ -60,6 +68,7 @@ pub fn revolve_options(p: &Value) -> Revolve {
|
||||
shade: flag(p, "shade", true),
|
||||
smooth_shading: true,
|
||||
cap_ends: flag(p, "cap", true),
|
||||
curve_samples: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,12 +76,94 @@ pub fn revolve_options(p: &Value) -> Revolve {
|
||||
/// by the evaluator; unsupported source kinds remain unchanged when rendered.
|
||||
pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> {
|
||||
validate_revolve_params(p)?;
|
||||
let path = profile(n).ok_or("Revolve currently requires a path or compound path. Select a profile drawn with the Pen tool.")?;
|
||||
let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?;
|
||||
if !path.subpaths.iter().any(|sp| sp.anchors.len() >= 2) {
|
||||
return Err("Revolve requires at least two anchors".into());
|
||||
let effects = &n.appearance.effects;
|
||||
// The profile is measured before the object's one Revolve, hidden or shown.
|
||||
let before = effects.iter().position(|e| e.id == REVOLVE).and_then(|i| effects.get(..i)).unwrap_or(effects);
|
||||
if is_container(n) {
|
||||
const EMPTY: &str = "Revolve requires a group holding a shape with at least two anchors";
|
||||
let mut shapes = members(n, "Revolve")?;
|
||||
if !shapes.iter().any(|s| has_two_anchors(&s.path)) {
|
||||
return Err(EMPTY.into());
|
||||
}
|
||||
reshape_members(n, before, &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or(EMPTY)?;
|
||||
let options = shared_options(&shapes, revolve_options(p))?;
|
||||
let mut copies = 0;
|
||||
return shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies));
|
||||
}
|
||||
vectorcraft_three_d::revolve(&path, b, revolve_options(p)).map(|_| ())
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
if !has_two_anchors(&path) {
|
||||
return Err("Revolve requires a shape with at least two anchors".into());
|
||||
}
|
||||
let path = geometry(&path, before, &GeomContext::of(n));
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let paints = solid_paints(n);
|
||||
check_surface(&path, b, revolve_options(p), surface_item(&paints), &mut 0)
|
||||
}
|
||||
|
||||
/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of
|
||||
/// appearance item `target` of `n`. The surfaces of every fill and stroke that carries a Revolve,
|
||||
/// `target`'s included, share one budget of paint copies, as in [`art`]. A visible object-level
|
||||
/// Revolve draws in place of those surfaces.
|
||||
pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> {
|
||||
if is_container(n) || visible(&n.appearance.effects) || target >= n.appearance.items.len() {
|
||||
return validate_revolve(n, p);
|
||||
}
|
||||
validate_revolve_params(p)?;
|
||||
const EMPTY: &str = "Revolve requires a shape with at least two anchors";
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
if !has_two_anchors(&path) {
|
||||
return Err(EMPTY.into());
|
||||
}
|
||||
let ctx = GeomContext::of(n);
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut copies = 0;
|
||||
for (i, item) in n.appearance.items.iter().enumerate() {
|
||||
let effects = item.effects();
|
||||
let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && e.id == REVOLVE) };
|
||||
let options = match at.and_then(|at| effects.get(at)) {
|
||||
_ if i == target => revolve_options(p),
|
||||
Some(fx) if crate::paints(item) => revolve_options(&merged_params(REVOLVE, &fx.params)),
|
||||
_ => continue,
|
||||
};
|
||||
let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item));
|
||||
let b = path.bounds().ok_or(EMPTY)?;
|
||||
check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_two_anchors(path: &PathData) -> bool {
|
||||
path.subpaths.iter().any(|sp| sp.anchors.len() >= 2)
|
||||
}
|
||||
|
||||
/// The bytes the copies of `paint` take on `faces` faces: a face's fill, its shadow and their seam
|
||||
/// strokes make up to four copies.
|
||||
fn paint_copies(faces: usize, paint: &Paint) -> usize {
|
||||
faces.saturating_mul(4).saturating_mul(paint_bytes(paint))
|
||||
}
|
||||
|
||||
/// An error when `path` does not revolve or when its surface in `item`'s paint takes `copies`, the
|
||||
/// bytes of an object's paint copies so far, past [`MAX_PAINT_COPIES`].
|
||||
fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&AppearanceItem>, copies: &mut usize) -> Result<(), String> {
|
||||
let faces = vectorcraft_three_d::revolve(path, b, options)?;
|
||||
*copies = copies.saturating_add(item.map_or(0, |i| paint_copies(faces.len(), &paint_of(i).0)));
|
||||
if *copies > MAX_PAINT_COPIES {
|
||||
return Err("Revolve paint is too complex for this surface; reduce Segments or simplify the gradient".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `options` with one number of samples for every curve of `shapes`, the members of one group: the
|
||||
/// members share Revolve's limits.
|
||||
fn shared_options(shapes: &[Profile], options: Revolve) -> Result<Revolve, String> {
|
||||
let samples = vectorcraft_three_d::revolve_curve_samples(shapes.iter().map(|s| &s.path), options)?;
|
||||
Ok(Revolve { curve_samples: Some(samples), ..options })
|
||||
}
|
||||
|
||||
/// The item whose paint an object's surface takes: its top fill, else its top stroke.
|
||||
fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> {
|
||||
items.iter().rev().find(|i| matches!(i, AppearanceItem::Fill(_))).or_else(|| items.last())
|
||||
}
|
||||
|
||||
/// Check Revolve's parameter values `p` alone: its lights, `edge` and `cap`.
|
||||
@@ -87,38 +178,31 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn profile(n: &Node) -> Option<PathData> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } => Some(path.clone()),
|
||||
NodeKind::Compound { children, .. } => {
|
||||
Some(PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
|
||||
apply_geometry_with(fx, path, path.bounds().unwrap_or(Rect::ZERO), ctx)
|
||||
}
|
||||
|
||||
/// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts
|
||||
/// the bytes of the paint copies of every surface of the object.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn surface(
|
||||
n: &Node,
|
||||
path: &PathData,
|
||||
b: Rect,
|
||||
options: Revolve,
|
||||
fx: &Effect,
|
||||
paint: Paint,
|
||||
opacity: f32,
|
||||
blend: vectorcraft_doc::color::BlendMode,
|
||||
expand: bool,
|
||||
) -> Option<Node> {
|
||||
let b = path.bounds()?;
|
||||
copies: &mut usize,
|
||||
) -> Option<(Vec<f64>, Node)> {
|
||||
// A loaded file or a profile edited past the limits keeps drawing its source path instead
|
||||
// of crashing the frame. Commands validate the same evaluator and report its errors.
|
||||
let options = revolve_options(&merged_params(REVOLVE, &fx.params));
|
||||
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
|
||||
let faces = vectorcraft_three_d::revolve(path, b, options).ok()?;
|
||||
// A face's fill, its shadow and their seam strokes: up to four copies of the paint.
|
||||
if faces.len().saturating_mul(4).saturating_mul(paint_bytes(&paint)) > MAX_PAINT_COPIES {
|
||||
*copies = copies.saturating_add(paint_copies(faces.len(), &paint));
|
||||
if *copies > MAX_PAINT_COPIES {
|
||||
return None;
|
||||
}
|
||||
// Visibility is an expansion option, never a change to live geometry or export baking.
|
||||
@@ -146,6 +230,7 @@ fn surface(
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let depths: Vec<f64> = faces.iter().map(|f: &vectorcraft_three_d::VisibleFace| f.depth).collect();
|
||||
let children = faces
|
||||
.into_iter()
|
||||
.map(|face| {
|
||||
@@ -188,7 +273,7 @@ fn surface(
|
||||
.into_iter()
|
||||
.flat_map(|item| {
|
||||
let AppearanceItem::Fill(fill) = &item else { return vec![item] };
|
||||
let mut edge = StrokeLayer::new(fill.paint.clone(), 0.75);
|
||||
let mut edge = StrokeLayer::new(fill.paint.clone(), SEAM_WIDTH);
|
||||
// Acute face corners must stay within the overlap width. Miter joins
|
||||
// amplify this seam stroke into visible spikes along the silhouette.
|
||||
edge.join = LineJoin::Round;
|
||||
@@ -202,7 +287,16 @@ fn surface(
|
||||
let mut group = Node::group(n.id, children);
|
||||
group.opacity = opacity;
|
||||
group.blend = blend;
|
||||
Some(group)
|
||||
Some((depths, group))
|
||||
}
|
||||
|
||||
/// A surface of one object about the bounds of `path`, built with options derived from `fx`.
|
||||
/// `copies` is the count [`surface`] adds to.
|
||||
fn object_surface(n: &Node, path: &PathData, fx: &Effect, item: &AppearanceItem, expand: bool, copies: &mut usize) -> Option<Node> {
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
let options = revolve_options(&merged_params(REVOLVE, &fx.params));
|
||||
surface(n, path, b, options, fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
|
||||
}
|
||||
|
||||
fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> Color, opacity: impl Fn(f64) -> f32) -> Paint {
|
||||
@@ -237,26 +331,23 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
|
||||
/// each of them. Each mesh adds its triangles to `total` as it is built, and the first that takes
|
||||
/// `total` past `limit` stops with an error before the next is built.
|
||||
pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
let path = profile(n).ok_or("Revolve currently requires a path or compound path")?;
|
||||
if is_container(n) {
|
||||
return group_meshes(n, total, limit);
|
||||
}
|
||||
let (path, rule) = object_profile(n, "Revolve")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<crate::SolidMesh, String> {
|
||||
let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?;
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(path, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?;
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?;
|
||||
Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) })
|
||||
};
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) {
|
||||
let before = n.appearance.effects.get(..index).unwrap_or_default();
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
|
||||
let path = geometry(&path, before, &ctx);
|
||||
let item = n
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|i| matches!(i, AppearanceItem::Fill(_)) && crate::paints(i))
|
||||
.or_else(|| n.appearance.items.iter().rev().find(|i| crate::paints(i)))
|
||||
.ok_or("the revolved object has no fill or stroke")?;
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
|
||||
let mut out = vec![];
|
||||
crate::solids::keep_mesh(&mut out, total, mesh(&path, fx, item)?, limit)?;
|
||||
return Ok(out);
|
||||
@@ -274,28 +365,49 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis.
|
||||
fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
let index = n
|
||||
.appearance
|
||||
.effects
|
||||
.iter()
|
||||
.position(|e| e.visible && e.id == REVOLVE)
|
||||
.ok_or("a 3D effect on a group's fill or stroke draws nothing to export")?;
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
|
||||
let mut shapes = members(n, "Revolve")?;
|
||||
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
|
||||
let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params)))?;
|
||||
let mut out = vec![];
|
||||
for s in &shapes {
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?;
|
||||
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity * s.opacity) }, limit)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn art(n: &Node, expand: bool) -> Option<Node> {
|
||||
if !has_revolve(n) {
|
||||
return None;
|
||||
}
|
||||
let path = profile(n)?;
|
||||
if is_container(n) {
|
||||
return group_art(n, expand);
|
||||
}
|
||||
let (path, _) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let mut children = vec![];
|
||||
let mut copies = 0;
|
||||
let mut remaining = n.appearance.effects.clone();
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) {
|
||||
let fx = n.appearance.effects.get(index)?;
|
||||
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
|
||||
// An object's surface uses its top visible fill, falling back to its stroke.
|
||||
let item = n
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|i| matches!(i, AppearanceItem::Fill(_)) && crate::paints(i))
|
||||
.or_else(|| n.appearance.items.iter().rev().find(|i| crate::paints(i)))?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints)?;
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
children.push(Arc::new(surface(n, &path, fx, paint, opacity, blend, expand)?));
|
||||
children.push(Arc::new(object_surface(n, &path, fx, item, expand, &mut copies)?));
|
||||
// Later geometry acts on the projected art as a whole through container evaluation.
|
||||
remaining = n
|
||||
.appearance
|
||||
@@ -312,9 +424,8 @@ fn art(n: &Node, expand: bool) -> Option<Node> {
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE) {
|
||||
let fx = item.effects().get(index)?;
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut art = surface(n, &p, fx, paint, opacity, blend, expand)?;
|
||||
let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?;
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| e.id != REVOLVE).cloned().collect();
|
||||
children.push(Arc::new(art));
|
||||
} else {
|
||||
@@ -328,6 +439,244 @@ fn art(n: &Node, expand: bool) -> Option<Node> {
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// The members' `surfaces`, or runs of their faces, in order, from the [`Scope`] at `level` of each
|
||||
/// one's `Profile::scopes` inward: consecutive surfaces that share a scope go in one group with its
|
||||
/// opacity and blending mode, so each applies once, to the faces it holds together.
|
||||
fn scoped(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>, level: usize) -> Vec<Arc<Node>> {
|
||||
fn close(id: NodeId, run: &mut Vec<(&[Scope], Arc<Node>)>, scope: Option<Scope>, level: usize, out: &mut Vec<Arc<Node>>) {
|
||||
if let Some(scope) = scope {
|
||||
let mut group = Node::group(id, scoped(id, std::mem::take(run), level + 1));
|
||||
group.opacity = scope.opacity;
|
||||
group.blend = scope.blend;
|
||||
out.push(Arc::new(group));
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
let mut run = vec![];
|
||||
let mut scope = None;
|
||||
for (scopes, s) in surfaces {
|
||||
let at = scopes.get(level).copied();
|
||||
if at.map(|a| a.key) != scope.map(|s: Scope| s.key) {
|
||||
close(id, &mut run, scope, level, &mut out);
|
||||
scope = at;
|
||||
}
|
||||
if scope.is_some() {
|
||||
run.push((scopes, s));
|
||||
} else {
|
||||
out.push(s);
|
||||
}
|
||||
}
|
||||
close(id, &mut run, scope, level, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// What a face can paint, to tell whether two faces overlap: the convex hull of the points and
|
||||
/// control points of its outline, which holds the outline, and the hull's box grown by half the
|
||||
/// seam stroke.
|
||||
struct Coverage {
|
||||
bounds: Rect,
|
||||
hull: Vec<Point>,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
/// `None` for a face with no outline and no box.
|
||||
fn of(face: &Node) -> Option<Coverage> {
|
||||
let points: Vec<Point> = match face.path_data() {
|
||||
Some(path) => path
|
||||
.to_bezpath()
|
||||
.elements()
|
||||
.iter()
|
||||
.flat_map(|e| match *e {
|
||||
PathEl::MoveTo(p) | PathEl::LineTo(p) => vec![p],
|
||||
PathEl::QuadTo(a, b) => vec![a, b],
|
||||
PathEl::CurveTo(a, b, c) => vec![a, b, c],
|
||||
PathEl::ClosePath => vec![],
|
||||
})
|
||||
.collect(),
|
||||
None => {
|
||||
let b = face.visual_bounds()?;
|
||||
vec![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 hull = convex_hull(points);
|
||||
let first = *hull.first()?;
|
||||
let reach = SEAM_WIDTH / 2.0;
|
||||
let bounds = hull.iter().fold(Rect::from_points(first, first), |b, p| b.union_pt(*p)).inflate(reach, reach);
|
||||
Some(Coverage { bounds, hull })
|
||||
}
|
||||
|
||||
/// Do the two faces' hulls, each grown by half the seam stroke, overlap? A test of the
|
||||
/// separating axes of their edges and of the page's axes: `true` whenever they overlap, and
|
||||
/// sometimes near a corner when they don't.
|
||||
fn meets(&self, other: &Coverage) -> bool {
|
||||
fn normals(hull: &[Point]) -> impl Iterator<Item = Vec2> + '_ {
|
||||
(0..hull.len()).filter_map(|i| {
|
||||
let (a, b) = (hull.get(i)?, hull.get((i + 1) % hull.len())?);
|
||||
Some(Vec2::new(a.y - b.y, b.x - a.x))
|
||||
})
|
||||
}
|
||||
let axes = [Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)].into_iter().chain(normals(&self.hull)).chain(normals(&other.hull));
|
||||
let span = |hull: &[Point], axis: Vec2| {
|
||||
hull.iter().map(|p| p.to_vec2().dot(axis)).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v)))
|
||||
};
|
||||
axes.filter(|axis| axis.hypot() > 0.0).all(|axis| {
|
||||
let ((a0, a1), (b0, b1)) = (span(&self.hull, axis), span(&other.hull, axis));
|
||||
let gap = SEAM_WIDTH * axis.hypot();
|
||||
b0 - a1 < gap && a0 - b1 < gap
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The convex hull of `points`, counterclockwise in a y-up frame, without repeated points.
|
||||
fn convex_hull(mut points: Vec<Point>) -> Vec<Point> {
|
||||
points.retain(|p| p.is_finite());
|
||||
points.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
|
||||
points.dedup();
|
||||
if points.len() < 3 {
|
||||
return points;
|
||||
}
|
||||
// One side of the hull from the first point to the last, without the last.
|
||||
fn side<'a>(points: impl Iterator<Item = &'a Point>) -> Vec<Point> {
|
||||
let mut chain: Vec<Point> = vec![];
|
||||
for &p in points {
|
||||
while let [.., o, a] = chain[..]
|
||||
&& (a - o).cross(p - o) <= 0.0
|
||||
{
|
||||
chain.pop();
|
||||
}
|
||||
chain.push(p);
|
||||
}
|
||||
chain.pop();
|
||||
chain
|
||||
}
|
||||
let mut hull = side(points.iter());
|
||||
hull.extend(side(points.iter().rev()));
|
||||
hull
|
||||
}
|
||||
|
||||
/// Do boxes `a` and `b` overlap with some area?
|
||||
fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1
|
||||
}
|
||||
|
||||
/// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them,
|
||||
/// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when
|
||||
/// the effect is only on the group's own fills or strokes or when its members can't be revolved.
|
||||
fn group_art(n: &Node, expand: bool) -> Option<Node> {
|
||||
let index = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE)?;
|
||||
let fx = n.appearance.effects.get(index)?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
let b = union_bounds(&shapes)?;
|
||||
let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params))).ok()?;
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut copies = 0;
|
||||
let mut surfaces = vec![];
|
||||
let mut opaque = true;
|
||||
for s in &shapes {
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
// The opacity and blending of the member and the groups it is in apply through its scopes.
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
|
||||
// A member with transparency of its own keeps every face, as a transparent object does.
|
||||
let expand = expand && s.scopes.is_empty();
|
||||
let (depths, art) = surface(n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?;
|
||||
surfaces.push((depths, art, s.scopes.as_slice()));
|
||||
}
|
||||
if surfaces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
|
||||
let children = if !plain {
|
||||
scoped(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect(), 0)
|
||||
} else {
|
||||
let count = surfaces.len();
|
||||
let mut faces = vec![];
|
||||
for (member, (depths, s, scopes)) in surfaces.into_iter().enumerate() {
|
||||
let (opacity, blend) = (s.opacity, s.blend);
|
||||
if let NodeKind::Group { children, .. } = s.kind {
|
||||
faces.extend(depths.into_iter().zip(children).map(|(depth, face)| (depth, member, opacity, blend, scopes, face)));
|
||||
}
|
||||
}
|
||||
// A stable sort: faces at the same depth keep the members' order.
|
||||
faces.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if opaque {
|
||||
vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(.., face)| face).collect()))]
|
||||
} else {
|
||||
// An opaque member's face goes in the order on its own. The faces of a member with
|
||||
// transparency share a run, one group with the opacity and blending mode of its fill or
|
||||
// stroke, and its scopes group runs further. Such a face joins its member's last run
|
||||
// unless a face drawn after that run overlaps it: only then does the member split,
|
||||
// where one group can't be both behind and in front of another face.
|
||||
struct Run<'a> {
|
||||
member: Option<usize>,
|
||||
scopes: &'a [Scope],
|
||||
bounds: Rect,
|
||||
faces: Vec<Arc<Node>>,
|
||||
cover: Vec<Coverage>,
|
||||
opacity: f32,
|
||||
blend: vectorcraft_doc::color::BlendMode,
|
||||
}
|
||||
let mut runs: Vec<Run> = vec![];
|
||||
let mut last_run = vec![None; count];
|
||||
// Past this many tests a face starts a run of its own, which never draws out of order.
|
||||
let mut budget = MAX_OVERLAP_TESTS;
|
||||
for (_, member, opacity, blend, scopes, face) in faces {
|
||||
let paints = opacity > 0.0 && scopes.iter().all(|s| s.opacity > 0.0);
|
||||
let Some(cover) = Coverage::of(&face).filter(|_| paints) else {
|
||||
// A face that paints nothing goes in the order on its own and overlaps nothing.
|
||||
runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend });
|
||||
continue;
|
||||
};
|
||||
if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() {
|
||||
runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
|
||||
continue;
|
||||
}
|
||||
let mut clear = |r: &Run| {
|
||||
budget = budget.saturating_sub(1);
|
||||
if !overlaps(r.bounds, cover.bounds) {
|
||||
return budget > 0;
|
||||
}
|
||||
budget = budget.saturating_sub(r.cover.len());
|
||||
budget > 0 && r.cover.iter().all(|c| !overlaps(c.bounds, cover.bounds) || !c.meets(&cover))
|
||||
};
|
||||
let joins =
|
||||
last_run.get(member).copied().flatten().filter(|&i: &usize| runs.get(i + 1..).is_some_and(|later| later.iter().all(&mut clear)));
|
||||
match joins.and_then(|i| runs.get_mut(i)) {
|
||||
Some(run) => {
|
||||
run.bounds = run.bounds.union(cover.bounds);
|
||||
run.faces.push(face);
|
||||
run.cover.push(cover);
|
||||
}
|
||||
None => {
|
||||
if let Some(last) = last_run.get_mut(member) {
|
||||
*last = Some(runs.len());
|
||||
}
|
||||
runs.push(Run { member: Some(member), scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
|
||||
}
|
||||
}
|
||||
}
|
||||
let runs = runs.into_iter().filter_map(|mut r| {
|
||||
// A face on its own needs a group only for the opacity or blending mode of its fill or stroke.
|
||||
if r.member.is_none() && r.opacity >= 1.0 && r.blend == Default::default() {
|
||||
return r.faces.pop().map(|face| (r.scopes, face));
|
||||
}
|
||||
let mut group = Node::group(n.id, r.faces);
|
||||
group.opacity = r.opacity;
|
||||
group.blend = r.blend;
|
||||
Some((r.scopes, Arc::new(group)))
|
||||
});
|
||||
scoped(n.id, runs.collect(), 0)
|
||||
}
|
||||
};
|
||||
let remaining =
|
||||
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children, clip: false };
|
||||
art.appearance = Appearance { effects: remaining, ..Default::default() }.into();
|
||||
Some(art)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -495,6 +844,354 @@ mod tests {
|
||||
assert_eq!(expand_revolve_art(&n).unwrap().children().unwrap()[0], expanded.children().unwrap()[0]);
|
||||
}
|
||||
|
||||
/// A closed rectangle `x` to `x + 10` across, filled solid.
|
||||
fn member(id: u64, x: f64) -> Arc<Node> {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((x, 0.0));
|
||||
b.line_to((x + 10.0, 0.0));
|
||||
b.line_to((x + 10.0, 40.0));
|
||||
b.line_to((x, 40.0));
|
||||
b.close_path();
|
||||
Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.8, 0.2, 0.1)), Paint::None, 0.0)))
|
||||
}
|
||||
|
||||
fn group_with(params: Value, children: Vec<Arc<Node>>) -> Node {
|
||||
let mut g = Node::group(NodeId(9), children);
|
||||
g.appearance.effects.push(crate::new_effect(REVOLVE, ¶ms).unwrap());
|
||||
g
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_members_share_the_axis_on_the_edge_of_them_all() {
|
||||
let mut hidden = (*member(3, -500.0)).clone();
|
||||
hidden.visible = false;
|
||||
let nested = Arc::new(Node::group(NodeId(5), vec![member(4, 90.0)]));
|
||||
let children = vec![member(1, 0.0), nested, Arc::new(hidden)];
|
||||
// Left edge, 5 pt out: the axis at -5, the far wall (100) 105 from it.
|
||||
let g = group_with(json!({"segments":32,"offset":5,"rotationX":0}), children.clone());
|
||||
let b = revolve_art(&g).unwrap().visual_bounds().unwrap();
|
||||
assert!((b.x0 + 110.0).abs() < 1.5 && (b.x1 - 100.0).abs() < 1.5, "{b:?}");
|
||||
// Right edge, 5 pt out: the axis at 105, the far wall (0) 105 from it.
|
||||
let g = group_with(json!({"segments":32,"offset":5,"edge":"right","rotationX":0}), children);
|
||||
let b = revolve_art(&g).unwrap().visual_bounds().unwrap();
|
||||
assert!((b.x1 - 210.0).abs() < 1.5 && (b.x0 - 0.0).abs() < 1.5, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opaque_members_share_one_back_to_front_order() {
|
||||
let g = group_with(json!({"segments":16}), vec![member(1, 0.0), member(2, 50.0)]);
|
||||
let art = revolve_art(&g).unwrap();
|
||||
assert_eq!(art.children().unwrap().len(), 1, "one order for every face");
|
||||
assert!(art.children().unwrap()[0].children().unwrap().len() > 16);
|
||||
}
|
||||
|
||||
/// The opacities and blending modes of the groups a face is drawn in, outermost first, leaving
|
||||
/// out groups with neither.
|
||||
type Chain = Vec<(f32, vectorcraft_doc::color::BlendMode)>;
|
||||
|
||||
/// The faces of `art` in drawing order, each with its [`Chain`].
|
||||
fn faces_in_order(art: &Node) -> Vec<(Node, Chain)> {
|
||||
fn visit(n: &Node, mut scopes: Chain, out: &mut Vec<(Node, Chain)>) {
|
||||
match n.children() {
|
||||
Some(children) => {
|
||||
if n.opacity != 1.0 || n.blend != Default::default() {
|
||||
scopes.push((n.opacity, n.blend));
|
||||
}
|
||||
for c in children {
|
||||
visit(c, scopes.clone(), out);
|
||||
}
|
||||
}
|
||||
None => out.push((n.clone(), scopes)),
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
visit(art, vec![], &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transparent_member_leaves_every_face_in_one_back_to_front_order() {
|
||||
let faces_of = |members| faces_in_order(&revolve_art(&group_with(json!({"segments":16}), members)).unwrap());
|
||||
let alone = faces_of(vec![member(1, 0.0), member(2, 50.0)]);
|
||||
let mut faded = (*member(3, 20.0)).clone();
|
||||
faded.opacity = 0.5;
|
||||
let faces = faces_of(vec![member(1, 0.0), member(2, 50.0), Arc::new(faded)]);
|
||||
let opaque: Vec<_> = faces.iter().filter(|(_, s)| s.is_empty()).map(|(f, _)| f).collect();
|
||||
assert_eq!(opaque, alone.iter().map(|(f, _)| f).collect::<Vec<_>>(), "the opaque members' faces keep their shared order");
|
||||
assert!(faces.iter().all(|(_, s)| s.is_empty() || s == &[(0.5, Default::default())]), "the member's opacity applies once to each face");
|
||||
let first = faces.iter().position(|(_, s)| !s.is_empty()).unwrap();
|
||||
let last = faces.iter().rposition(|(_, s)| !s.is_empty()).unwrap();
|
||||
assert!(first > 0 && last + 1 < faces.len(), "the ring between the others draws in front of the back ones and behind the front ones");
|
||||
let groups = |art: &Node| {
|
||||
let mut count = 0;
|
||||
art.walk(&mut |n| count += usize::from(n.children().is_some() && n.opacity == 0.5));
|
||||
count
|
||||
};
|
||||
// Rings one above the other: their faces alternate in the order but none overlaps the
|
||||
// other ring, so each ring's opacity applies once, to all its faces.
|
||||
let faded = |id, y: f64| {
|
||||
let mut n = (*member(id, 40.0)).clone();
|
||||
n.opacity = 0.5;
|
||||
if let NodeKind::Path { path, .. } = &mut n.kind {
|
||||
*path = PathData::from_bezpath(&(Affine::translate((0.0, y)) * path.to_bezpath()));
|
||||
}
|
||||
Arc::new(n)
|
||||
};
|
||||
let art = revolve_art(&group_with(json!({"segments":16}), vec![faded(1, 0.0), faded(2, 200.0)])).unwrap();
|
||||
assert!(faces_in_order(&art).iter().all(|(_, s)| s == &[(0.5, Default::default())]));
|
||||
assert_eq!(groups(&art), 2, "one group for each ring");
|
||||
// A tall cylinder inside both that paints nothing splits neither.
|
||||
let mut hidden = (*member(3, 0.0)).clone();
|
||||
hidden.opacity = 0.0;
|
||||
if let NodeKind::Path { path, .. } = &mut hidden.kind {
|
||||
*path = PathData::from_bezpath(&(Affine::translate((0.0, -20.0)) * Affine::scale_non_uniform(1.0, 7.0) * path.to_bezpath()));
|
||||
}
|
||||
let art = revolve_art(&group_with(json!({"segments":16}), vec![faded(1, 0.0), faded(2, 200.0), Arc::new(hidden)])).unwrap();
|
||||
assert_eq!(groups(&art), 2, "one group for each faded ring");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_whose_fill_or_stroke_paints_nothing_stays_invisible() {
|
||||
let clear_fill = {
|
||||
let mut n = (*member(3, 20.0)).clone();
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) {
|
||||
f.opacity = 0.0;
|
||||
}
|
||||
n
|
||||
};
|
||||
let clear_stroke = {
|
||||
let mut n = (*member(4, 20.0)).clone();
|
||||
n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
|
||||
for item in n.appearance.items.iter_mut() {
|
||||
if let AppearanceItem::Stroke(s) = item {
|
||||
s.opacity = 0.0;
|
||||
}
|
||||
}
|
||||
n
|
||||
};
|
||||
for clear in [clear_fill, clear_stroke] {
|
||||
let art = revolve_art(&group_with(json!({"segments":16}), vec![member(1, 0.0), member(2, 50.0), Arc::new(clear)])).unwrap();
|
||||
let faces = faces_in_order(&art);
|
||||
let alone = faces_in_order(&revolve_art(&group_with(json!({"segments":16}), vec![member(1, 0.0), member(2, 50.0)])).unwrap());
|
||||
let opaque: Vec<_> = faces.iter().filter(|(_, s)| s.is_empty()).map(|(f, _)| f).collect();
|
||||
assert_eq!(opaque, alone.iter().map(|(f, _)| f).collect::<Vec<_>>(), "only the opaque members' faces draw without transparency");
|
||||
assert!(faces.len() > alone.len(), "the clear member's faces stay in the art");
|
||||
assert!(faces.iter().all(|(_, s)| s.is_empty() || s.iter().any(|(o, _)| *o == 0.0)), "each clear face is drawn at 0% opacity");
|
||||
}
|
||||
}
|
||||
|
||||
fn star(id: u64) -> Arc<Node> {
|
||||
let anchors = (0..1200)
|
||||
.map(|i| {
|
||||
let (s, c) = (i as f64 * std::f64::consts::PI / 600.0).sin_cos();
|
||||
let r = if i % 2 == 0 { 100.0 } else { 60.0 };
|
||||
vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(200.0 + r * c, 200.0 + r * s))
|
||||
})
|
||||
.collect();
|
||||
Arc::new(Node::path(
|
||||
NodeId(id),
|
||||
PathData::new(vec![vectorcraft_geom::SubPath::new(anchors, true)]),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faces_overlap_by_their_painted_shapes_and_seams_not_only_their_boxes() {
|
||||
let face = |points: &[(f64, f64)]| {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to(points[0]);
|
||||
for &p in &points[1..] {
|
||||
b.line_to(p);
|
||||
}
|
||||
b.close_path();
|
||||
Coverage::of(&Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::default())).unwrap()
|
||||
};
|
||||
let a = face(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)]);
|
||||
assert_eq!(a.hull.len(), 3);
|
||||
assert_eq!(
|
||||
face(&[(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (10.0, 10.0), (5.0, 5.0), (0.0, 10.0)]).hull.len(),
|
||||
4,
|
||||
"a point on an edge or inside is left out"
|
||||
);
|
||||
// Across the diagonal 2 / sqrt(2) apart: their boxes overlap, their shapes and seams don't.
|
||||
let b = face(&[(10.0, 10.0), (10.0, 2.0), (2.0, 10.0)]);
|
||||
assert!(overlaps(a.bounds, b.bounds) && !a.meets(&b) && !b.meets(&a));
|
||||
// 1 / sqrt(2) apart, within the two half seam strokes.
|
||||
let c = face(&[(10.0, 10.0), (10.0, 1.0), (1.0, 10.0)]);
|
||||
assert!(a.meets(&c) && c.meets(&a));
|
||||
assert!(a.meets(&a), "a face meets itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_members_share_revolves_limits() {
|
||||
let alone = group_with(json!({}), vec![star(1)]);
|
||||
assert!(validate_revolve(&alone, &json!({})).is_ok());
|
||||
let both = group_with(json!({}), vec![star(1), star(2)]);
|
||||
let refused = validate_revolve(&both, &json!({})).unwrap_err();
|
||||
assert!(refused.contains("reduce Segments"), "{refused}");
|
||||
assert_eq!(revolve_art(&both), None, "past the limits the source draws");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blending_modes_apply_once_to_the_member_or_group_that_has_them() {
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
let blend = |n: Arc<Node>, mode: BlendMode| {
|
||||
let mut n = (*n).clone();
|
||||
n.blend = mode;
|
||||
Arc::new(n)
|
||||
};
|
||||
let inner = blend(member(4, 60.0), BlendMode::Multiply);
|
||||
let screened = blend(Arc::new(Node::group(NodeId(5), vec![member(3, 40.0), inner])), BlendMode::Screen);
|
||||
let group = group_with(json!({}), vec![blend(member(1, 0.0), BlendMode::Multiply), member(2, 20.0), screened]);
|
||||
let art = revolve_art(&group).expect("revolved");
|
||||
let faces = faces_in_order(&art);
|
||||
let modes = |s: &[(f32, BlendMode)]| s.iter().map(|(_, b)| *b).collect::<Vec<_>>();
|
||||
let chains = [vec![BlendMode::Multiply], vec![], vec![BlendMode::Screen], vec![BlendMode::Screen, BlendMode::Multiply]];
|
||||
for chain in &chains {
|
||||
assert!(faces.iter().any(|(_, s)| &modes(s) == chain), "faces drawn in {chain:?}");
|
||||
}
|
||||
assert!(faces.iter().all(|(_, s)| chains.contains(&modes(s))), "each mode applies once, to the member or group that has it");
|
||||
// Faces of the screened group's members that come together in the drawing order share one Screen group.
|
||||
let runs = |faces: &[(Node, Chain)], inside: &dyn Fn(&Chain) -> bool| {
|
||||
faces.windows(2).filter(|w| inside(&w[1].1) && !inside(&w[0].1)).count() + usize::from(faces.first().is_some_and(|f| inside(&f.1)))
|
||||
};
|
||||
let groups = |art: &Node, pick: &dyn Fn(&Node) -> bool| {
|
||||
let mut count = 0;
|
||||
art.walk(&mut |n| count += usize::from(n.children().is_some() && pick(n)));
|
||||
count
|
||||
};
|
||||
let screened = |s: &Chain| s.first().is_some_and(|(_, b)| *b == BlendMode::Screen);
|
||||
assert_eq!(groups(&art, &|n| n.blend == BlendMode::Screen), runs(&faces, &screened));
|
||||
let plain = group_with(json!({}), vec![member(1, 0.0)]);
|
||||
assert_ne!(expand_revolve_art(&plain), revolve_art(&plain), "an opaque member's hidden faces are removed");
|
||||
let multiplied = group_with(json!({}), vec![blend(member(1, 0.0), BlendMode::Multiply)]);
|
||||
assert_eq!(expand_revolve_art(&multiplied), revolve_art(&multiplied), "a blended member keeps every face");
|
||||
// A nested group's opacity applies once, to its members' faces that come together.
|
||||
let mut faded = Node::group(NodeId(6), vec![member(3, 40.0), member(4, 45.0)]);
|
||||
faded.opacity = 0.5;
|
||||
let art = revolve_art(&group_with(json!({}), vec![member(1, 0.0), Arc::new(faded)])).expect("revolved");
|
||||
let faces = faces_in_order(&art);
|
||||
assert!(faces.iter().all(|(_, s)| s.is_empty() || s == &[(0.5, BlendMode::Normal)]), "the faded group's opacity applies once");
|
||||
let half = |s: &Chain| !s.is_empty();
|
||||
assert!(faces.iter().any(|(_, s)| half(s)) && faces.iter().any(|(_, s)| !half(s)));
|
||||
assert_eq!(groups(&art, &|n| n.opacity == 0.5), runs(&faces, &half), "the faded group's members, together");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_3d_effect_on_a_groups_fill_is_refused() {
|
||||
let mut group = Node::group(NodeId(9), vec![member(1, 0.0)]);
|
||||
group.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into();
|
||||
for id in [REVOLVE, crate::EXTRUDE] {
|
||||
assert!(crate::validate_three_d(&group, id, &json!({})).is_ok(), "{id} on the group itself");
|
||||
let refused = crate::validate_three_d_at(&group, id, &json!({}), Some((0, 0))).unwrap_err();
|
||||
assert!(refused.contains("on the group itself"), "{id}: {refused}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_measures_the_profile_after_the_geometry_effects_before_revolve() {
|
||||
let roughen = crate::new_effect("distort.roughen", &json!({"size": 1, "detail": 100})).unwrap();
|
||||
let mut group = group_with(json!({}), vec![star(1)]);
|
||||
assert!(validate_revolve(&group, &json!({})).is_ok());
|
||||
group.appearance.effects.insert(0, roughen.clone());
|
||||
assert!(validate_revolve(&group, &json!({})).is_err(), "the group's reshaped member");
|
||||
assert_eq!(revolve_art(&group), None);
|
||||
let mut object = (*star(1)).clone();
|
||||
assert!(validate_revolve(&object, &json!({})).is_ok());
|
||||
object.appearance.effects.insert(0, roughen);
|
||||
assert!(validate_revolve(&object, &json!({})).is_err(), "a reshaped object not yet revolved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_of_a_hidden_revolve_leaves_out_the_geometry_effects_after_it() {
|
||||
let roughen = crate::new_effect("distort.roughen", &json!({"size": 1, "detail": 100})).unwrap();
|
||||
let mut hidden = crate::new_effect(REVOLVE, &json!({})).unwrap();
|
||||
hidden.visible = false;
|
||||
let mut object = (*star(1)).clone();
|
||||
object.appearance.effects = vec![hidden.clone(), roughen.clone()];
|
||||
assert_eq!(validate_revolve(&object, &json!({})), Ok(()), "an object whose Revolve is shown again");
|
||||
let mut group = group_with(json!({}), vec![star(1)]);
|
||||
group.appearance.effects = vec![hidden, roughen];
|
||||
assert_eq!(validate_revolve(&group, &json!({})), Ok(()), "a group whose Revolve is shown again");
|
||||
for n in [&mut object, &mut group] {
|
||||
n.appearance.effects[0].visible = true;
|
||||
assert!(revolve_art(n).is_some(), "shown, the Revolve draws");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_copies_past_the_budget_are_refused_for_the_whole_group() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let painted = |id: u64, x: f64, stops: usize| {
|
||||
let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect();
|
||||
let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut node = (*member(id, x)).clone();
|
||||
node.appearance = Appearance::basic(paint, Paint::None, 0.0).into();
|
||||
Arc::new(node)
|
||||
};
|
||||
let plain = member(1, 0.0);
|
||||
let NodeKind::Path { path: profile, .. } = &plain.kind else { panic!("a path") };
|
||||
let faces = vectorcraft_three_d::revolve(profile, profile.bounds().unwrap(), revolve_options(&json!({}))).unwrap().len();
|
||||
let stops = MAX_PAINT_COPIES * 6 / 10 / (faces * 4) / std::mem::size_of::<GradientStop>();
|
||||
let one = group_with(json!({}), vec![painted(1, 0.0, stops)]);
|
||||
assert_eq!(validate_revolve(&one, &json!({})), Ok(()));
|
||||
let two = group_with(json!({}), vec![painted(1, 0.0, stops), painted(2, 20.0, stops)]);
|
||||
let refused = validate_revolve(&two, &json!({})).unwrap_err();
|
||||
assert!(refused.contains("simplify the gradient"), "{refused}");
|
||||
assert_eq!(revolve_art(&two), None, "past the budget the source draws");
|
||||
let object = painted(3, 0.0, stops * 2);
|
||||
assert!(validate_revolve(&object, &json!({})).is_err(), "one object past the budget");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fills_of_one_object_share_the_budget_of_paint_copies() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let source = profile_node();
|
||||
let NodeKind::Path { path: profile, .. } = &source.kind else { panic!("a path") };
|
||||
let faces = vectorcraft_three_d::revolve(profile, profile.bounds().unwrap(), revolve_options(&json!({}))).unwrap().len();
|
||||
let stops = MAX_PAINT_COPIES * 6 / 10 / (faces * 4) / std::mem::size_of::<GradientStop>();
|
||||
let fill = |stops: usize, revolved: bool| {
|
||||
let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect();
|
||||
let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut item = AppearanceItem::Fill(FillLayer::new(paint));
|
||||
if revolved {
|
||||
item.effects_mut().push(fx());
|
||||
}
|
||||
item
|
||||
};
|
||||
let with = |items: Vec<AppearanceItem>| {
|
||||
let mut n = source.clone();
|
||||
n.appearance = Appearance { items, ..Default::default() }.into();
|
||||
n
|
||||
};
|
||||
let one = with(vec![fill(stops, true)]);
|
||||
assert!(revolve_art(&one).is_some());
|
||||
assert_eq!(validate_item_revolve(&one, &json!({}), 0, 0), Ok(()));
|
||||
let two = with(vec![fill(stops, true), fill(stops, true)]);
|
||||
assert_eq!(revolve_art(&two), None, "past the budget the source draws");
|
||||
let refused = validate_item_revolve(&two, &json!({}), 1, 0).unwrap_err();
|
||||
assert!(refused.contains("simplify the gradient"), "{refused}");
|
||||
let second = with(vec![fill(stops, true), fill(stops, false)]);
|
||||
assert!(validate_item_revolve(&second, &json!({}), 1, 0).is_err(), "the item the effect goes on counts");
|
||||
assert_eq!(validate_item_revolve(&second, &json!({}), 0, 0), Ok(()), "an item without a Revolve does not");
|
||||
let below = with(vec![fill(stops * 2, false), fill(1, false)]);
|
||||
assert!(validate_item_revolve(&below, &json!({}), 0, 0).is_err(), "the item's own paint, not the top fill");
|
||||
assert_eq!(validate_item_revolve(&below, &json!({}), 1, 0), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_items_revolve_is_validated_after_only_the_geometry_effects_before_it() {
|
||||
let roughen = crate::new_effect("distort.roughen", &json!({"size": 1, "detail": 100})).unwrap();
|
||||
let mut object = (*star(1)).clone();
|
||||
let mut hidden = fx();
|
||||
hidden.visible = false;
|
||||
let item = object.appearance.items.first_mut().unwrap();
|
||||
item.effects_mut().push(hidden);
|
||||
item.effects_mut().push(roughen);
|
||||
assert_eq!(validate_item_revolve(&object, &json!({}), 0, 0), Ok(()), "the roughen after it is not swept");
|
||||
assert!(validate_item_revolve(&object, &json!({}), 0, 2).is_err(), "a Revolve added after the roughen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_unknown_paints_and_later_distortion_keep_complete_surfaces() {
|
||||
let mut n = profile_node();
|
||||
|
||||
@@ -138,7 +138,7 @@ pub fn inflate_options(p: &Value) -> Inflate {
|
||||
}
|
||||
|
||||
/// The shape a solid is made from: a path's or a compound path's outline.
|
||||
fn profile(n: &Node) -> Option<(PathData, FillRule)> {
|
||||
pub(crate) fn profile(n: &Node) -> Option<(PathData, FillRule)> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, guide: false, clipping: false, .. } => Some((path.clone(), *rule)),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
@@ -156,7 +156,7 @@ fn profile(n: &Node) -> Option<(PathData, FillRule)> {
|
||||
|
||||
/// What a 3D effect paints `n` with: its own fills and strokes, else, for type that has none, the
|
||||
/// fill and stroke of its first painted run (its characters' colours).
|
||||
fn solid_paints(n: &Node) -> Vec<AppearanceItem> {
|
||||
pub(crate) fn solid_paints(n: &Node) -> Vec<AppearanceItem> {
|
||||
let own: Vec<AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).cloned().collect();
|
||||
if !own.is_empty() || !matches!(n.kind, NodeKind::Text(_)) {
|
||||
return own;
|
||||
@@ -207,29 +207,52 @@ pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
|
||||
return shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()));
|
||||
}
|
||||
let (path, rule) = profile(n).ok_or_else(|| {
|
||||
format!("{label} currently requires a path, compound path, type or group. Convert images and other objects to paths first.")
|
||||
})?;
|
||||
let (path, rule) = object_profile(n, label)?;
|
||||
let b = path.bounds().ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
|
||||
facets(id, &path, rule, b, p).map(|_| ())
|
||||
}
|
||||
|
||||
/// [`profile`], or the error a command reports for object `n`: type with no outlines to build from
|
||||
/// (empty, or only spaces) is a shape without anchors, and any other object is the wrong kind.
|
||||
pub(crate) fn object_profile(n: &Node, label: &str) -> Result<(PathData, FillRule), String> {
|
||||
profile(n).ok_or_else(|| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
format!("{label} requires a shape with at least two anchors")
|
||||
} else {
|
||||
format!("{label} currently requires a path, compound path, type or group. Convert images and other objects to paths first.")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A group in a 3D effect's group, or a member of it, whose opacity is below 100% or whose blending
|
||||
/// mode is not Normal. The members of one group share its `key`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Scope {
|
||||
pub(crate) key: usize,
|
||||
pub(crate) opacity: f32,
|
||||
pub(crate) blend: BlendMode,
|
||||
}
|
||||
|
||||
/// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint
|
||||
/// it, and the opacity of the objects it is in (1 for the object with the effect itself).
|
||||
struct Profile {
|
||||
path: PathData,
|
||||
rule: FillRule,
|
||||
items: Vec<AppearanceItem>,
|
||||
opacity: f32,
|
||||
/// it, and the opacity of the objects it is in multiplied together (1 for the object with the
|
||||
/// effect itself). `scopes` lists those objects with transparency of their own ([`Scope`]), from
|
||||
/// the outermost group down to the member itself (none for the object itself). Group Revolve
|
||||
/// applies each once, to the surfaces of the members it holds together.
|
||||
pub(crate) struct Profile {
|
||||
pub(crate) path: PathData,
|
||||
pub(crate) rule: FillRule,
|
||||
pub(crate) items: Vec<AppearanceItem>,
|
||||
pub(crate) opacity: f32,
|
||||
pub(crate) scopes: Vec<Scope>,
|
||||
}
|
||||
|
||||
/// Is `n` a group or layer (a 3D effect on it turns its members about one shared axis)?
|
||||
fn is_container(n: &Node) -> bool {
|
||||
pub(crate) fn is_container(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. })
|
||||
}
|
||||
|
||||
/// The bounds of every shape together: the centre a group's members turn about.
|
||||
fn union_bounds(shapes: &[Profile]) -> Option<Rect> {
|
||||
pub(crate) fn union_bounds(shapes: &[Profile]) -> Option<Rect> {
|
||||
shapes.iter().filter_map(|s| s.path.bounds()).reduce(|a, c| a.union(c))
|
||||
}
|
||||
|
||||
@@ -245,15 +268,26 @@ const MAX_MESH_TRIANGLES: usize = 2_000_000;
|
||||
/// effects and painted with its own fills and strokes. Like the effect on a group in the
|
||||
/// reference app, they turn about one shared axis (the centre of their bounds together) rather
|
||||
/// than each about its own. An error names what the group holds that can't become a solid.
|
||||
fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
|
||||
fn walk(n: &Node, opacity: f32, label: &str, out: &mut Vec<Profile>) -> Result<(), String> {
|
||||
pub(crate) fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
|
||||
struct Walk<'a> {
|
||||
label: &'a str,
|
||||
out: Vec<Profile>,
|
||||
keys: usize,
|
||||
}
|
||||
fn walk(n: &Node, opacity: f32, scopes: &[Scope], w: &mut Walk) -> Result<(), String> {
|
||||
let label = w.label;
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
continue;
|
||||
}
|
||||
let opacity = opacity * c.opacity;
|
||||
let mut scopes = scopes.to_vec();
|
||||
if c.blend != BlendMode::Normal || c.opacity < 1.0 {
|
||||
w.keys += 1;
|
||||
scopes.push(Scope { key: w.keys, opacity: c.opacity, blend: c.blend });
|
||||
}
|
||||
if is_container(c) {
|
||||
walk(c, opacity, label, out)?;
|
||||
walk(c, opacity, &scopes, w)?;
|
||||
continue;
|
||||
}
|
||||
let Some((path, rule)) = profile(c) else {
|
||||
@@ -266,19 +300,19 @@ fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
|
||||
};
|
||||
return Err(format!("{label} on a group needs paths, compound paths and type: release or expand its {what} first."));
|
||||
};
|
||||
if out.len() >= MAX_MEMBERS {
|
||||
if w.out.len() >= MAX_MEMBERS {
|
||||
return Err(format!("{label} on a group takes at most {MAX_MEMBERS} objects"));
|
||||
}
|
||||
let path = geometry(&path, &c.appearance.effects, &GeomContext::of(c));
|
||||
if path.bounds().is_some() {
|
||||
out.push(Profile { path, rule, items: solid_paints(c), opacity });
|
||||
w.out.push(Profile { path, rule, items: solid_paints(c), opacity, scopes });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(n, 1.0, label, &mut out)?;
|
||||
Ok(out)
|
||||
let mut w = Walk { label, out: vec![], keys: 0 };
|
||||
walk(n, 1.0, &[], &mut w)?;
|
||||
Ok(w.out)
|
||||
}
|
||||
|
||||
/// Can 3D effect `id` (Revolve included, [`is_three_d`]) with parameters `p` draw `n`? Checked
|
||||
@@ -288,6 +322,19 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
if id == crate::REVOLVE { crate::validate_revolve(n, p) } else { validate_solid(n, id, p) }
|
||||
}
|
||||
|
||||
/// [`validate_three_d`] for an effect at `(item, index)`, index `index` of the effects of
|
||||
/// appearance item `item` of `n` (the effects' length for a new effect), or on the object itself
|
||||
/// when `at` is `None`. A Revolve on a fill or stroke is checked in that item's paint, after the
|
||||
/// item's geometry effects before it, together with the object's other items that carry a Revolve.
|
||||
/// A group's or layer's fills and strokes take no 3D effect: only the group's own effect draws.
|
||||
pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> {
|
||||
match at {
|
||||
Some(_) if is_container(n) => Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()),
|
||||
Some((item, index)) if id == crate::REVOLVE => crate::revolve::validate_item_revolve(n, p, item, index),
|
||||
_ => validate_three_d(n, id, p),
|
||||
}
|
||||
}
|
||||
|
||||
/// Are 3D effect `id`'s parameter values `p` valid? The checks of [`validate_three_d`] that do not
|
||||
/// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does
|
||||
/// not need to fit.
|
||||
@@ -385,7 +432,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<(&AppearanceItem, f32
|
||||
|
||||
/// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before`
|
||||
/// its 3D effect, about the bounds of all of them.
|
||||
fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) {
|
||||
pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) {
|
||||
if before.iter().any(|e| e.visible && is_geometry(&e.id))
|
||||
&& let Some(b) = union_bounds(shapes)
|
||||
{
|
||||
@@ -501,7 +548,7 @@ pub fn solid_art(n: &Node) -> Option<Node> {
|
||||
let remaining: Vec<Effect>;
|
||||
if let Some((index, fx)) = solid(&n.appearance.effects) {
|
||||
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
|
||||
children.extend(art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0 }])?);
|
||||
children.extend(art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?);
|
||||
// Later geometry effects act on the projected art as a whole.
|
||||
remaining = n
|
||||
.appearance
|
||||
@@ -517,7 +564,7 @@ pub fn solid_art(n: &Node) -> Option<Node> {
|
||||
for item in &paints {
|
||||
if let Some((index, fx)) = solid(item.effects()) {
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
|
||||
for mut art in art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0 }])? {
|
||||
for mut art in art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])? {
|
||||
Arc::make_mut(&mut art).appearance.effects =
|
||||
item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
|
||||
children.push(art);
|
||||
@@ -680,14 +727,14 @@ fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<SolidM
|
||||
let paints = solid_paints(n);
|
||||
if let Some((index, fx)) = solid(&n.appearance.effects) {
|
||||
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
|
||||
meshes_for(fx, &[Profile { path, rule, items: paints, opacity: 1.0 }], total, limit)?
|
||||
meshes_for(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], total, limit)?
|
||||
} else {
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut out = vec![];
|
||||
for item in &paints {
|
||||
if let Some((index, fx)) = solid(item.effects()) {
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
out.extend(meshes_for(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0 }], total, limit)?);
|
||||
out.extend(meshes_for(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], total, limit)?);
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -51,7 +51,7 @@ fn the_meshes_of_one_object_share_one_triangle_budget() {
|
||||
assert!(keep_mesh(&mut out, &mut total, meshes[1].clone(), first).is_err());
|
||||
assert_eq!(out.len(), 1);
|
||||
// Building past the budget stops with an error instead of holding every mesh.
|
||||
let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0 }];
|
||||
let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }];
|
||||
let Some(effect) = n.appearance.effects.first() else { panic!("no effect") };
|
||||
let mut total = 0;
|
||||
assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_ok());
|
||||
|
||||
@@ -56,6 +56,28 @@ fn check(bp: &BezPath, st: &StrokeLayer, what: &str) {
|
||||
assert!(checked > 0, "{what}: no samples");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_butt_capped_open_path_is_measured_where_it_paints() {
|
||||
let mut vertical = BezPath::new();
|
||||
vertical.move_to((50.0, 10.0));
|
||||
vertical.line_to((50.0, 90.0));
|
||||
let mut diagonal = BezPath::new();
|
||||
diagonal.move_to((10.0, 10.0));
|
||||
diagonal.line_to((40.0, 50.0));
|
||||
let mut arc = BezPath::new();
|
||||
arc.move_to((10.0, 50.0));
|
||||
arc.curve_to((10.0, 22.4), (32.4, 0.0), (60.0, 0.0));
|
||||
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0);
|
||||
stroke.cap = LineCap::Butt;
|
||||
for (name, bp) in [("vertical", vertical), ("diagonal", diagonal), ("arc", arc)] {
|
||||
let painted = outline_region(&PathData::from_bezpath(&bp), FillRule::NonZero, &stroke).to_bezpath().bounding_box();
|
||||
let bounds = stroke.bounds_on(&bp, bp.bounding_box());
|
||||
for (got, want) in [(bounds.x0, painted.x0), (bounds.y0, painted.y0), (bounds.x1, painted.x1), (bounds.y1, painted.y1)] {
|
||||
assert!((got - want).abs() < 0.05, "{name}: measured {bounds:?}, paints {painted:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_and_clicks_cover_what_every_stroke_paints() {
|
||||
let profiles = [None, Some(WidthProfile::lens()), Some(WidthProfile { points: vec![(0.0, 2.0, 0.5), (0.6, 0.8, 1.6), (1.0, 1.2, 0.3)] })];
|
||||
|
||||
@@ -105,7 +105,7 @@ fn each_copy_scales_its_stroke_once_more() {
|
||||
let n = stroked(json!({"scaleH": 200, "scaleV": 200, "copies": 2, "strokes": true}));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let widths: Vec<f64> = leaves(&art).iter().map(|p| stroke_of(p).0).collect();
|
||||
assert_eq!(widths, vec![2.0, 4.0, 8.0]);
|
||||
assert_eq!(widths, vec![8.0, 4.0, 2.0], "the original on top");
|
||||
// Without the option the copies keep the original's weight.
|
||||
let plain = stroked(json!({"scaleH": 200, "scaleV": 200, "copies": 2}));
|
||||
assert!(!has_transform_art(&plain));
|
||||
@@ -127,7 +127,7 @@ fn transform_patterns_moves_each_copys_pattern() {
|
||||
assert!(has_transform_options(&n));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let xs: Vec<f64> = leaves(&art).iter().map(|p| pattern_xf(p).as_coeffs()[4]).collect();
|
||||
assert_eq!(xs, vec![0.0, 30.0, 60.0]);
|
||||
assert_eq!(xs, vec![60.0, 30.0, 0.0], "the original on top");
|
||||
// Without it, every copy's pattern stays put (the tiles don't follow the copies).
|
||||
let n = patterned(json!({"moveH": 30, "patterns": false, "strokes": false, "objects": true}));
|
||||
assert!(!has_transform_art(&n));
|
||||
@@ -218,7 +218,7 @@ fn each_copy_of_a_strokes_own_transform_scales_its_weight_once_more() {
|
||||
let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "copies": 2, "strokes": true}));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let widths: Vec<f64> = stroked_leaves(&art).iter().map(|p| stroke_of(p).0).collect();
|
||||
assert_eq!(widths, vec![2.0, 4.0, 8.0]);
|
||||
assert_eq!(widths, vec![8.0, 4.0, 2.0], "the original on top");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -268,7 +268,7 @@ fn a_fills_own_transform_moves_each_copys_pattern_with_transform_patterns() {
|
||||
assert!(has_transform_options(&n));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let xs: Vec<f64> = pattern_leaves(&art).iter().map(|p| pattern_xf(p).as_coeffs()[4]).collect();
|
||||
assert_eq!(xs, vec![0.0, 30.0, 60.0]);
|
||||
assert_eq!(xs, vec![60.0, 30.0, 0.0], "the original on top");
|
||||
// Off, the pattern stays put.
|
||||
assert!(!has_transform_art(&fill_with_effect(json!({"moveH": 30, "copies": 2}))));
|
||||
}
|
||||
@@ -294,7 +294,7 @@ fn a_strokes_own_transform_draws_bakes_expands_and_measures_alike() {
|
||||
let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "copies": 1, "strokes": true}));
|
||||
let drawn = reshape(None, &n, None).unwrap();
|
||||
let widths = |art: &Node| stroked_leaves(art).iter().map(|p| stroke_of(p).0).collect::<Vec<f64>>();
|
||||
assert_eq!(widths(&drawn), vec![2.0, 4.0]);
|
||||
assert_eq!(widths(&drawn), vec![4.0, 2.0], "the original on top");
|
||||
// Expand Appearance.
|
||||
assert_eq!(widths(&expand_outlined(None, &n, None).unwrap()), widths(&drawn));
|
||||
// Export.
|
||||
@@ -394,9 +394,9 @@ fn filled_and_stroked(fill: Paint, params: Value) -> Node {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() {
|
||||
// Black fill, white stroke, each copy scaled and turned (#5920): each copy is an object of its
|
||||
// own above the one before, so its fill covers the strokes of the copies below.
|
||||
fn copies_with_a_fill_and_a_stroke_are_drawn_one_below_another() {
|
||||
// Black fill, white stroke, each copy scaled and turned (#5920, #6316): each copy is an object
|
||||
// of its own below the one before, so the fills above cover the strokes of the copies below.
|
||||
let params = json!({"scaleH": 97, "scaleV": 97, "rotate": 10, "copies": 25});
|
||||
let n = filled_and_stroked(Paint::solid(Color::BLACK), params.clone());
|
||||
assert!(has_transform_art(&n));
|
||||
@@ -407,10 +407,10 @@ fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() {
|
||||
assert!(matches!(p.kind, NodeKind::Path { .. }), "one shape each, not one path of every copy");
|
||||
assert!(!p.appearance.fill_paint().is_none() && p.appearance.stroke().is_some());
|
||||
}
|
||||
// The original is at the bottom, the smallest copy on top.
|
||||
assert_eq!(paths[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let top = paths[25].geometric_bounds().unwrap();
|
||||
assert!(top.width() < 100.0 && top.height() < 100.0, "{top:?}");
|
||||
// The smallest copy is at the bottom, the original on top.
|
||||
assert_eq!(paths[25].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let bottom = paths[0].geometric_bounds().unwrap();
|
||||
assert!(bottom.width() < 100.0 && bottom.height() < 100.0, "{bottom:?}");
|
||||
// Drawn as Expand Appearance makes it.
|
||||
assert_eq!(leaves(&expand_outlined(None, &n, None).unwrap()).len(), 26);
|
||||
|
||||
@@ -427,3 +427,252 @@ fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() {
|
||||
// No copies: nothing to stack.
|
||||
assert!(!has_transform_art(&filled_and_stroked(Paint::solid(Color::BLACK), json!({"rotate": 10}))));
|
||||
}
|
||||
|
||||
/// A group of two squares side by side, each with a black fill and a white stroke, with the
|
||||
/// Transform effect `params`.
|
||||
fn two_squares(params: Value) -> Node {
|
||||
let square = |id, x| {
|
||||
let a = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::WHITE), 4.0);
|
||||
std::sync::Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)), a))
|
||||
};
|
||||
let mut g = Node::group(NodeId(20), vec![square(21, 0.0), square(22, 120.0)]);
|
||||
g.appearance.effects.push(transform(params));
|
||||
g
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_copies_are_whole_groups_below_the_original() {
|
||||
let art = crate::evaluate_container(None, &two_squares(json!({"scaleH": 95, "scaleV": 95, "copies": 10}))).unwrap();
|
||||
let copies = art.children().unwrap();
|
||||
assert_eq!(copies.len(), 11, "the original and 10 copies");
|
||||
for c in copies {
|
||||
assert_eq!(c.children().map(Vec::len), Some(2), "each copy holds both squares");
|
||||
}
|
||||
// The smallest copy is at the bottom, the original on top with its members in their order.
|
||||
let width = |i: usize| copies[i].geometric_bounds().unwrap().width();
|
||||
assert!((0..10).all(|i| width(i) < width(i + 1)), "{:?}", (0..11).map(width).collect::<Vec<_>>());
|
||||
assert_eq!(copies[10].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 220.0, 100.0));
|
||||
let members = copies[10].children().unwrap();
|
||||
assert_eq!(members[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
assert_eq!(members[1].geometric_bounds().unwrap(), Rect::new(120.0, 0.0, 220.0, 100.0));
|
||||
|
||||
// Without copies the members stay members of the art.
|
||||
let art = crate::evaluate_container(None, &two_squares(json!({"scaleH": 50, "scaleV": 50}))).unwrap();
|
||||
assert_eq!(art.children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>(), [NodeId(21), NodeId(22)]);
|
||||
|
||||
// A group's own fill paints the shape of all its copies, so each member keeps its place.
|
||||
let mut own_fill = two_squares(json!({}));
|
||||
own_fill.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into();
|
||||
let copies = transform(json!({"moveH": 300, "copies": 2}));
|
||||
crate::reshape::reshape_leaves_within(&mut own_fill, &[&copies], crate::geometry::Budget::EFFECTS, None);
|
||||
assert_eq!(own_fill.children().map(Vec::len), Some(2), "a stack of copies per member");
|
||||
|
||||
// A guide in the group stays one guide.
|
||||
let mut guided = two_squares(json!({}));
|
||||
let mut guide = Node::path(NodeId(23), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default());
|
||||
if let NodeKind::Path { guide: on, .. } = &mut guide.kind {
|
||||
*on = true;
|
||||
}
|
||||
if let Some(members) = guided.children_mut() {
|
||||
members.push(std::sync::Arc::new(guide));
|
||||
}
|
||||
guided.appearance.effects.clear();
|
||||
crate::reshape::reshape_leaves_within(&mut guided, &[&copies], crate::geometry::Budget::EFFECTS, None);
|
||||
assert_eq!(guided.children().map(Vec::len), Some(3), "the original and 2 copies");
|
||||
let mut guides = 0;
|
||||
guided.walk(&mut |n| guides += usize::from(matches!(n.kind, NodeKind::Path { guide: true, .. })));
|
||||
assert_eq!(guides, 1);
|
||||
|
||||
// A clipping group's first member stays its clip.
|
||||
let mut clipping = two_squares(json!({}));
|
||||
if let NodeKind::Group { clip, .. } = &mut clipping.kind {
|
||||
*clip = true;
|
||||
}
|
||||
clipping.appearance.effects.clear();
|
||||
crate::reshape::reshape_leaves_within(&mut clipping, &[&copies], crate::geometry::Budget::EFFECTS, None);
|
||||
assert_eq!(clipping.children().map(Vec::len), Some(2), "the clip and the clipped member");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_copies_stop_at_the_node_limit() {
|
||||
// Empty groups cost no anchors, so only the count of nodes stops their copies.
|
||||
let empties = (0..5_000).map(|i| std::sync::Arc::new(Node::group(NodeId(100 + i), vec![])));
|
||||
let mut g = two_squares(json!({}));
|
||||
if let Some(members) = g.children_mut() {
|
||||
members.extend(empties);
|
||||
}
|
||||
g.appearance.effects.clear();
|
||||
let copies = transform(json!({"moveH": 1, "copies": 1000}));
|
||||
crate::reshape::reshape_leaves_within(&mut g, &[&copies], crate::geometry::Budget::EFFECTS, None);
|
||||
let mut nodes = 0usize;
|
||||
g.walk(&mut |_| nodes += 1);
|
||||
assert!(nodes <= crate::distort::MAX_COPY_OBJECTS + 1, "{nodes}");
|
||||
assert!(g.children().unwrap().len() < 1001, "the limit stopped the copies");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_copies_count_the_art_of_opacity_masks() {
|
||||
let empties = (0..5_000).map(|i| std::sync::Arc::new(Node::group(NodeId(100 + i), vec![]))).collect();
|
||||
let mut g = two_squares(json!({}));
|
||||
if let Some(members) = g.children_mut() {
|
||||
let mask = vectorcraft_doc::OpacityMask::new(Node::group(NodeId(99), empties), true);
|
||||
std::sync::Arc::make_mut(&mut members[0]).extras_mut().mask = Some(Box::new(mask));
|
||||
}
|
||||
g.appearance.effects.clear();
|
||||
let copies = transform(json!({"moveH": 1, "copies": 1000}));
|
||||
crate::reshape::reshape_leaves_within(&mut g, &[&copies], crate::geometry::Budget::EFFECTS, None);
|
||||
let nodes = g.count_with_masks();
|
||||
assert!(nodes <= crate::distort::MAX_COPY_OBJECTS + 1, "{nodes}");
|
||||
}
|
||||
|
||||
/// The anchors `n` draws with every effect inside it evaluated, group by group and member by
|
||||
/// member as drawing and baking evaluate them. The count stops once it passes `limit`.
|
||||
fn drawn_anchors(n: &Node, limit: usize) -> usize {
|
||||
fn count(n: &Node, limit: usize, total: &mut usize) {
|
||||
if *total > limit {
|
||||
return;
|
||||
}
|
||||
if n.children().is_some() && !matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
let art = crate::evaluate_container(None, n).unwrap_or_else(|| n.clone());
|
||||
art.children().into_iter().flatten().for_each(|c| count(c, limit, total));
|
||||
return;
|
||||
}
|
||||
if let Some(art) = reshape(None, n, None) {
|
||||
count(&art, limit, total);
|
||||
return;
|
||||
}
|
||||
let Some((path, _)) = crate::reshape::leaf_geometry(n) else { return };
|
||||
let Some(bounds) = path.bounds() else { return };
|
||||
let own = crate::apply_geometry(&n.appearance.effects, &path, bounds);
|
||||
let items: Vec<usize> = n
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.filter(|i| crate::has_geometry(i.effects()))
|
||||
.filter_map(|i| Some(crate::apply_geometry(i.effects(), &own, own.bounds()?).anchor_count()))
|
||||
.collect();
|
||||
*total += if items.is_empty() { own.anchor_count() } else { items.iter().sum() };
|
||||
}
|
||||
let mut total = 0;
|
||||
count(n, limit, &mut total);
|
||||
total
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_copies_keep_what_the_effects_inside_them_make_to_the_budget() {
|
||||
let most = crate::geometry::MAX_EFFECT_ANCHORS;
|
||||
let copies = |key: &str| transform(json!({key: 1, "copies": 1000}));
|
||||
|
||||
// Copies of a group whose member group makes copies of its own.
|
||||
let inner = two_squares(json!({"moveH": 1, "copies": 1000}));
|
||||
let mut outer = Node::group(NodeId(30), vec![std::sync::Arc::new(inner)]);
|
||||
outer.appearance.effects.push(copies("moveV"));
|
||||
let drawn = drawn_anchors(&outer, 2 * most);
|
||||
assert!(drawn <= most, "a group inside: {drawn}");
|
||||
|
||||
// Copies of a group whose member path makes copies of its own.
|
||||
let mut own = two_squares(json!({"moveH": 1, "copies": 1000}));
|
||||
if let Some(members) = own.children_mut() {
|
||||
std::sync::Arc::make_mut(&mut members[0]).appearance.effects.push(copies("moveV"));
|
||||
}
|
||||
let drawn = drawn_anchors(&own, 2 * most);
|
||||
assert!(drawn <= most, "a path's own effect: {drawn}");
|
||||
|
||||
// Copies of a group whose member's fill makes copies of its own.
|
||||
let mut item = two_squares(json!({"moveH": 1, "copies": 1000}));
|
||||
if let Some(members) = item.children_mut() {
|
||||
std::sync::Arc::make_mut(&mut members[0]).appearance.items[0].effects_mut().push(copies("moveV"));
|
||||
}
|
||||
let drawn = drawn_anchors(&item, 2 * most);
|
||||
assert!(drawn <= most, "a fill's own effect: {drawn}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_with_scaled_effects_keep_what_each_one_makes_to_the_budget() {
|
||||
// Each copy's Roughen is twice as large as the last's, and the rough edges take more lines.
|
||||
let roughen = Effect { id: "distort.roughen".into(), params: json!({"size": 40, "relative": false, "detail": 20}), visible: true };
|
||||
let lines = |budget: crate::geometry::Budget| {
|
||||
let mut g = two_squares(json!({}));
|
||||
if let Some(members) = g.children_mut() {
|
||||
let m = std::sync::Arc::make_mut(&mut members[0]);
|
||||
m.appearance.items.retain(AppearanceItem::is_fill);
|
||||
m.appearance.effects.push(roughen.clone());
|
||||
members.truncate(1);
|
||||
}
|
||||
g.appearance.effects.clear();
|
||||
let copies = transform(json!({"scaleH": 200, "scaleV": 200, "copies": 5, "strokes": true}));
|
||||
crate::reshape::reshape_leaves_within(&mut g, &[&copies], budget, None);
|
||||
let (mut count, mut lines) = (0, 0);
|
||||
for leaf in leaves(&g) {
|
||||
count += 1;
|
||||
let Some((path, _)) = crate::reshape::leaf_geometry(leaf) else { continue };
|
||||
let drawn = crate::apply_geometry(&leaf.appearance.effects, &path, path.bounds().unwrap());
|
||||
lines += crate::geometry::Budget::of(&drawn).lines;
|
||||
}
|
||||
(count, lines)
|
||||
};
|
||||
let (all, most) = lines(crate::geometry::Budget::EFFECTS);
|
||||
assert_eq!(all, 6, "the original and 5 copies");
|
||||
let cap = most / 2;
|
||||
let budget = crate::geometry::Budget { anchors: crate::geometry::MAX_EFFECT_ANCHORS, lines: cap };
|
||||
let (count, drawn) = lines(budget);
|
||||
assert!(count < all, "the budget stopped the copies");
|
||||
assert!(drawn <= cap, "{drawn} > {cap}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_copies_are_whole_only_when_nothing_inside_makes_more_art() {
|
||||
let copies = transform(json!({"moveH": 300, "copies": 2}));
|
||||
let effect = |id: &str| Effect { id: id.into(), params: json!({}), visible: true };
|
||||
let roughen = effect("distort.roughen");
|
||||
// Two squares under a group with `change` made to the first member.
|
||||
let whole = |change: &dyn Fn(&mut Node)| {
|
||||
let mut g = two_squares(json!({}));
|
||||
if let Some(members) = g.children_mut() {
|
||||
change(std::sync::Arc::make_mut(&mut members[0]));
|
||||
}
|
||||
g.appearance.effects.clear();
|
||||
crate::reshape::reshape_leaves_within(&mut g, &[&copies], crate::geometry::Budget::EFFECTS, None);
|
||||
g.children().unwrap().len() == 3
|
||||
};
|
||||
// A group of one square with effect `e`, in place of the member.
|
||||
let in_group = |m: &mut Node, e: &Effect| {
|
||||
let square = Node::path(NodeId(40), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default());
|
||||
let mut g = Node::group(NodeId(41), vec![std::sync::Arc::new(square), std::sync::Arc::new(m.clone())]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
*m = g;
|
||||
};
|
||||
assert!(whole(&|_| {}));
|
||||
// Effects that only change pixels, and effects turned off, are copied with the art.
|
||||
assert!(whole(&|m| m.appearance.effects.push(effect("stylize.dropShadow"))));
|
||||
assert!(whole(&|m| m.appearance.effects.push(Effect { visible: false, ..roughen.clone() })));
|
||||
// Effects that draw nothing are copied with the art as well.
|
||||
assert!(
|
||||
whole(&|m| {
|
||||
m.visible = false;
|
||||
m.appearance.effects.push(roughen.clone());
|
||||
}),
|
||||
"a hidden member's effect"
|
||||
);
|
||||
assert!(
|
||||
whole(&|m| {
|
||||
*m.appearance.items[0].paint_mut() = Paint::None;
|
||||
m.appearance.items[0].effects_mut().push(roughen.clone());
|
||||
}),
|
||||
"the effect of a fill that paints nothing"
|
||||
);
|
||||
assert!(whole(&|m| m.appearance.effects.push(effect("no.such.effect"))), "an unknown effect");
|
||||
// Effects that make more art than a copy holds keep each member's copies in its place.
|
||||
assert!(!whole(&|m| m.appearance.effects.push(roughen.clone())), "a member's own effect");
|
||||
assert!(!whole(&|m| m.appearance.items[0].effects_mut().push(roughen.clone())), "a fill's own effect");
|
||||
assert!(!whole(&|m| in_group(m, &roughen)), "a group's own effect");
|
||||
assert!(!whole(&|m| in_group(m, &effect("pathfinder.add"))), "a Pathfinder effect");
|
||||
assert!(
|
||||
!whole(&|m| {
|
||||
let mut art = Node::group(NodeId(43), vec![]);
|
||||
in_group(&mut art, &roughen);
|
||||
m.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
|
||||
}),
|
||||
"an effect in an opacity mask"
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ heif = ["dep:heic-rs", "dep:rayon"]
|
||||
[dependencies]
|
||||
# Which paths stored in documents may be opened.
|
||||
craft-docpath = { workspace = true }
|
||||
craft-proof = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
@@ -39,6 +40,8 @@ vectorcraft-metafile = { workspace = true }
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
vectorcraft-affinity = { workspace = true }
|
||||
vectorcraft-scriptcheck = { workspace = true }
|
||||
# The commands' parameter schemas (schemas.rs).
|
||||
vectorcraft-apischema = { workspace = true }
|
||||
image = { workspace = true }
|
||||
jxl-oxide = { workspace = true }
|
||||
jxl-color = { workspace = true }
|
||||
@@ -85,3 +88,5 @@ zune-jpegxl = { workspace = true }
|
||||
zune-core = { workspace = true }
|
||||
# The JavaScript parser's lexer, compared with the script checker's on the same scripts.
|
||||
vectorcraft-js = { workspace = true }
|
||||
# A bundled font's own glyph boxes, for the glyph bounds tests.
|
||||
skrifa = { workspace = true }
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
pub mod actionset;
|
||||
mod addons;
|
||||
mod apiref;
|
||||
pub(crate) mod appearance;
|
||||
mod assets;
|
||||
mod attributes;
|
||||
@@ -82,6 +83,7 @@ mod select;
|
||||
pub(crate) mod shaper;
|
||||
pub mod shortcutset;
|
||||
pub(crate) mod slices;
|
||||
pub mod spelling;
|
||||
mod stroke;
|
||||
mod style;
|
||||
pub mod stylelib;
|
||||
@@ -129,6 +131,9 @@ pub struct CommandSpec {
|
||||
pub run: Run,
|
||||
/// Record in the journal (false for queries and selection-only helpers).
|
||||
pub journal: bool,
|
||||
/// The parameters' schema: [`Session::execute`] checks the params against it before the
|
||||
/// command runs, and `params` is the text it writes ([`crate::schemas`]).
|
||||
pub schema: Option<&'static vectorcraft_apischema::ParamSchema>,
|
||||
}
|
||||
|
||||
/// Serializable command metadata.
|
||||
@@ -142,11 +147,29 @@ pub struct CommandInfo {
|
||||
pub enabled: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub disabled_reason: Option<String>,
|
||||
/// The parameters' schema as a JSON Schema 2020-12 object schema, for a command that has one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub schema: Option<Value>,
|
||||
/// The same schema in the form an MCP tool's `inputSchema` takes ([`input_schema`]).
|
||||
#[serde(rename = "inputSchema", skip_serializing_if = "Option::is_none")]
|
||||
pub input_schema: Option<Value>,
|
||||
}
|
||||
|
||||
/// `schema` as an MCP tool input schema: the root `type` is `"object"`, since the arguments are
|
||||
/// always an object, and every other keyword is kept. The root of [`CommandInfo::schema`] also
|
||||
/// takes null when no parameter is required.
|
||||
pub(crate) fn input_schema(schema: &Value) -> Value {
|
||||
let mut o = schema.clone();
|
||||
if let Some(map) = o.as_object_mut() {
|
||||
map.insert("type".into(), "object".into());
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
impl CommandSpec {
|
||||
pub fn info(&self, s: &Session) -> CommandInfo {
|
||||
let e = (self.enabled)(s);
|
||||
let schema = self.schema.map(vectorcraft_apischema::ParamSchema::to_json);
|
||||
CommandInfo {
|
||||
id: self.id,
|
||||
label: self.label,
|
||||
@@ -155,6 +178,8 @@ impl CommandSpec {
|
||||
params: self.params,
|
||||
enabled: e.is_ok(),
|
||||
disabled_reason: e.err(),
|
||||
input_schema: schema.as_ref().map(input_schema),
|
||||
schema,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,10 +262,17 @@ pub fn has_clipboard(s: &Session) -> std::result::Result<(), String> {
|
||||
|
||||
macro_rules! cmd {
|
||||
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true }
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, schema: None }
|
||||
};
|
||||
(query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false }
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, schema: None }
|
||||
};
|
||||
// With a parameter schema: `schema: &SCHEMA` after the run function.
|
||||
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr, schema: $schema:expr) => {
|
||||
$crate::cmd::CommandSpec { schema: Some($schema), ..$crate::cmd::cmd!($id, $label, [$($m),*], $sc, $params, $en, $run) }
|
||||
};
|
||||
(query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr, schema: $schema:expr) => {
|
||||
$crate::cmd::CommandSpec { schema: Some($schema), ..$crate::cmd::cmd!(query $id, $label, [$($m),*], $sc, $params, $en, $run) }
|
||||
};
|
||||
}
|
||||
pub(crate) use cmd;
|
||||
@@ -321,6 +353,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(expand::specs());
|
||||
v.extend(attributes::specs());
|
||||
v.extend(interactivity::specs());
|
||||
v.extend(spelling::specs());
|
||||
v.extend(svgfilter::specs());
|
||||
v.extend(newart::specs());
|
||||
v.extend(colortheme::specs());
|
||||
@@ -352,6 +385,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(actionset::specs());
|
||||
v.extend(importmatches::specs());
|
||||
v.extend(addons::specs());
|
||||
// Last, so the reference it writes ends with its own section.
|
||||
v.extend(apiref::specs());
|
||||
v
|
||||
})
|
||||
}
|
||||
@@ -368,6 +403,14 @@ pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result
|
||||
if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) }
|
||||
}
|
||||
|
||||
/// [`run_spec`] for a command run outside [`Session::execute`]: with params checked against the
|
||||
/// command's schema, and the defaults of omitted values filled in, as `execute` does
|
||||
/// ([`crate::schemas::check`]).
|
||||
pub(crate) fn run_checked(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result<Value> {
|
||||
let checked = crate::schemas::check(spec, p, s.replaying())?;
|
||||
run_spec(s, spec, checked.as_ref().unwrap_or(p))
|
||||
}
|
||||
|
||||
// ---------- param helpers ----------
|
||||
|
||||
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
|
||||
|
||||
@@ -275,6 +275,7 @@ fn same_art(a: &NodeKind, b: &NodeKind) -> bool {
|
||||
moved.xf = a.xf;
|
||||
moved.cached_bounds = a.cached_bounds;
|
||||
moved.cached_baselines.clone_from(&a.cached_baselines);
|
||||
moved.cached_ink = a.cached_ink;
|
||||
**a == moved
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
//! `engine.apiReference`: the command API reference in Markdown, written when it is asked for from
|
||||
//! the parameter schemas of the built-in commands ([`crate::schemas`]). Each command that has a
|
||||
//! schema gets a section, in registry order, with its parameters in the schema's order; a command
|
||||
//! without a schema, a plug-in's included, is left out. The text depends only on the registry, so
|
||||
//! every call in one build returns the same bytes.
|
||||
//!
|
||||
//! Text from a schema is escaped before it goes into a heading, a list item or a table cell: the
|
||||
//! Markdown punctuation characters get a backslash (CommonMark 0.31.2, backslash escapes,
|
||||
//! <https://spec.commonmark.org/0.31.2/#backslash-escapes>), so a description shows as plain text and
|
||||
//! cannot end a table cell or make a link, an image or HTML; line breaks, tabs and other control
|
||||
//! characters become spaces.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_apischema::{Bound, MAX_DEPTH, MAX_ID, Omitted, Param, ParamSchema, Type, Writes};
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, cmd, command_specs};
|
||||
use crate::EngineError;
|
||||
|
||||
const ID: &str = "engine.apiReference";
|
||||
|
||||
/// The largest reference the command returns, in bytes of UTF-8.
|
||||
pub const MAX_BYTES: usize = 1 << 20;
|
||||
|
||||
static REFERENCE: ParamSchema = ParamSchema::new(
|
||||
&[],
|
||||
"the command API reference in Markdown, written from the built-in commands' parameter schemas: a section for each command that has one, in registry order",
|
||||
)
|
||||
.returns("{markdown: string}")
|
||||
.writes(Writes::Nothing)
|
||||
.since(2);
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "engine.apiReference",
|
||||
"Command API Reference",
|
||||
[],
|
||||
None,
|
||||
"{} the command API reference in Markdown, written from the built-in commands' parameter schemas: a section for each command that has one, in registry order → {markdown: string}",
|
||||
always,
|
||||
api_reference,
|
||||
schema: &REFERENCE
|
||||
)]
|
||||
}
|
||||
|
||||
fn api_reference(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "markdown": reference(command_specs())? }))
|
||||
}
|
||||
|
||||
const HEADER: &str = "# VectorCraft command API reference\n\nThis reference lists only the commands that have a parameter schema, in registry order. `engine.commands` lists every command, with its params text and whether it can run now.\n";
|
||||
|
||||
/// The reference for the commands of `specs` that have a schema, or an error when it would be
|
||||
/// larger than [`MAX_BYTES`]; a reference that is too large is never cut short.
|
||||
pub(crate) fn reference(specs: &[CommandSpec]) -> Result<String> {
|
||||
let mut out = String::from(HEADER);
|
||||
let mut sections = 0;
|
||||
for spec in specs {
|
||||
let Some(schema) = spec.schema else { continue };
|
||||
let text = section(spec, schema);
|
||||
if out.len() + text.len() > MAX_BYTES {
|
||||
return Err(EngineError::Other(format!("`{ID}`: the reference would be larger than {MAX_BYTES} bytes")));
|
||||
}
|
||||
out.push_str(&text);
|
||||
sections += 1;
|
||||
}
|
||||
if sections == 0 {
|
||||
out.push_str("\nNo commands have parameter schemas.\n");
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One command's section: its heading, a list of what it is, and its parameters.
|
||||
fn section(spec: &CommandSpec, schema: &ParamSchema) -> String {
|
||||
let menu = if spec.menu.is_empty() { "None".to_string() } else { spec.menu.iter().map(|m| escape(m)).collect::<Vec<_>>().join(" › ") };
|
||||
let mut s = format!("\n## {}\n\n", escape(spec.id));
|
||||
s.push_str(&format!("- Label: {}\n", escape(spec.label)));
|
||||
s.push_str(&format!("- Menu: {menu}\n"));
|
||||
s.push_str(&format!("- API level: {}\n", schema.since));
|
||||
s.push_str(&format!("- Deprecated: {}\n", level_text(schema.deprecated)));
|
||||
s.push_str(&format!("- Writes: {}\n", writes_text(schema.writes)));
|
||||
s.push_str(&format!("- Cost: {}\n", schema.cost));
|
||||
s.push_str(&format!("- Summary: {}\n", text_or_none(schema.summary)));
|
||||
s.push_str(&format!("- Returns: {}\n\n", text_or_none(schema.returns)));
|
||||
if schema.params.is_empty() {
|
||||
s.push_str("No parameters.\n");
|
||||
return s;
|
||||
}
|
||||
s.push_str("| Parameter | Type | Range | Unit | Default | Required | Since | Deprecated | Description |\n");
|
||||
s.push_str("|---|---|---|---|---|---|---|---|---|\n");
|
||||
rows("", schema.params, 0, &mut s);
|
||||
s
|
||||
}
|
||||
|
||||
/// A table row for each of `params`, and after each one the rows of the members of an object it
|
||||
/// holds: `edits[].name` for an object in a list, `options.size` for an object.
|
||||
fn rows(prefix: &str, params: &[Param], depth: usize, out: &mut String) {
|
||||
for p in params {
|
||||
let name = if prefix.is_empty() { p.name.to_string() } else { format!("{prefix}.{}", p.name) };
|
||||
let (range, unit) = range_and_unit(&p.ty);
|
||||
out.push_str(&format!(
|
||||
"| {} | {} | {range} | {unit} | {} | {} | {} | {} | {} |\n",
|
||||
escape(&name),
|
||||
type_text(&p.ty, depth),
|
||||
default_text(p.omitted),
|
||||
if p.required { "Yes" } else { "No" },
|
||||
p.since,
|
||||
level_text(p.deprecated),
|
||||
description(p),
|
||||
));
|
||||
if depth < MAX_DEPTH
|
||||
&& let Some((members, path)) = members(&p.ty, name, depth)
|
||||
{
|
||||
rows(&path, members, depth + 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of the object `ty` holds, directly or as the items of lists, with the path of
|
||||
/// its members' prefix (`name`, `name[]`, `name[][]`).
|
||||
fn members(ty: &Type, mut path: String, depth: usize) -> Option<(&'static [Param], String)> {
|
||||
let mut ty = ty;
|
||||
for _ in depth..MAX_DEPTH {
|
||||
match ty {
|
||||
Type::Object(params) => return Some((params, path)),
|
||||
Type::Array(item) => {
|
||||
path.push_str("[]");
|
||||
ty = item;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn type_text(ty: &Type, depth: usize) -> String {
|
||||
match ty {
|
||||
Type::Number { .. } => "number".into(),
|
||||
Type::Integer { .. } => "integer".into(),
|
||||
Type::Boolean => "boolean".into(),
|
||||
Type::String => "string".into(),
|
||||
Type::Enum(names) => format!("one of {}", names.iter().map(|n| format!("\"{}\"", escape(n))).collect::<Vec<_>>().join(", ")),
|
||||
Type::Id => "object id (integer)".into(),
|
||||
Type::Ids => "list of object ids".into(),
|
||||
Type::Color => escape("color (a string, [r, g, b] or an object)"),
|
||||
Type::Point => escape("point ([x, y], two numbers)"),
|
||||
Type::Object(_) => "object".into(),
|
||||
Type::Array(_) if depth >= MAX_DEPTH => "list".into(),
|
||||
Type::Array(item) => format!("list of {}", type_text(item, depth + 1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The range and unit cells of a value of type `ty`.
|
||||
fn range_and_unit(ty: &Type) -> (String, String) {
|
||||
let ends = |low: Option<String>, high: Option<String>| {
|
||||
let both: Vec<String> = low.into_iter().chain(high).collect();
|
||||
if both.is_empty() { "None".to_string() } else { both.join(", ") }
|
||||
};
|
||||
match ty {
|
||||
Type::Number { min, max, unit } => {
|
||||
let low = min.map(|b| match b {
|
||||
Bound::Inclusive(a) => format!("at least {a}"),
|
||||
Bound::Exclusive(a) => format!("more than {a}"),
|
||||
});
|
||||
let high = max.map(|b| match b {
|
||||
Bound::Inclusive(a) => format!("at most {a}"),
|
||||
Bound::Exclusive(a) => format!("less than {a}"),
|
||||
});
|
||||
(ends(low, high), unit.map_or("None".to_string(), escape))
|
||||
}
|
||||
Type::Integer { min, max } => (ends(min.map(|a| format!("at least {a}")), max.map(|a| format!("at most {a}"))), "None".into()),
|
||||
Type::Id => (format!("at least 0, at most {MAX_ID}"), "None".into()),
|
||||
_ => ("None".into(), "None".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn default_text(omitted: Omitted) -> String {
|
||||
match omitted {
|
||||
Omitted::Nothing => "None".into(),
|
||||
Omitted::Value(json) => format!("{} (JSON)", escape(json)),
|
||||
Omitted::Note(note) => format!("{} (worked out by the command)", escape(note)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameter's doc text, and what the schema says about how its value is checked.
|
||||
fn description(p: &Param) -> String {
|
||||
let mut parts = Vec::new();
|
||||
if !p.doc.is_empty() {
|
||||
parts.push(escape(p.doc));
|
||||
}
|
||||
if p.null_omitted {
|
||||
parts.push("null reads as omitted".to_string());
|
||||
}
|
||||
if p.lenient {
|
||||
parts.push("lenient (a value of another type or out of range is passed to the command, not refused)".to_string());
|
||||
}
|
||||
if parts.is_empty() { "None".to_string() } else { parts.join("; ") }
|
||||
}
|
||||
|
||||
fn level_text(level: Option<u32>) -> String {
|
||||
level.map_or("None".to_string(), |l| format!("API level {l}"))
|
||||
}
|
||||
|
||||
fn writes_text(writes: Writes) -> &'static str {
|
||||
match writes {
|
||||
Writes::Nothing => "nothing",
|
||||
Writes::Session => "session",
|
||||
Writes::Preferences => "preferences",
|
||||
Writes::Document => "document",
|
||||
}
|
||||
}
|
||||
|
||||
fn text_or_none(text: &str) -> String {
|
||||
if text.is_empty() { "None".to_string() } else { escape(text) }
|
||||
}
|
||||
|
||||
/// The characters [`escape`] puts a backslash before.
|
||||
const ESCAPED: &[char] = &['\\', '|', '[', ']', '<', '>', '`', '*', '_', '!', '&', '#', '~', ':', '@'];
|
||||
|
||||
/// `text` as plain Markdown text on one line: each of [`ESCAPED`] with a backslash before it, the
|
||||
/// `.` after `www` too (so no autolink starts), and each control character as a space.
|
||||
pub(crate) fn escape(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for c in text.chars() {
|
||||
if c.is_control() {
|
||||
out.push(' ');
|
||||
continue;
|
||||
}
|
||||
let after_www = out.len().checked_sub(3).and_then(|at| out.as_bytes().get(at..)).is_some_and(|b| b.eq_ignore_ascii_case(b"www"));
|
||||
if ESCAPED.contains(&c) || (c == '.' && after_www) {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn run(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn spec(id: &'static str, menu: &'static [&'static str], schema: Option<&'static ParamSchema>) -> CommandSpec {
|
||||
CommandSpec { id, label: "Label", menu, shortcut: None, params: "", enabled: always, run, journal: false, schema }
|
||||
}
|
||||
|
||||
/// The cells of a table row as a GFM table reads them: split at each `|` that has no backslash
|
||||
/// before it, with the outer pipes and the spaces around each cell taken off.
|
||||
fn cells(row: &str) -> Vec<String> {
|
||||
let inner = row.strip_prefix('|').and_then(|r| r.strip_suffix('|')).unwrap_or_else(|| panic!("not a table row: {row}"));
|
||||
let (mut out, mut cell, mut chars) = (Vec::new(), String::new(), inner.chars());
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'\\' => {
|
||||
cell.push(c);
|
||||
cell.extend(chars.next());
|
||||
}
|
||||
'|' => out.push(std::mem::take(&mut cell).trim().to_string()),
|
||||
_ => cell.push(c),
|
||||
}
|
||||
}
|
||||
out.push(cell.trim().to_string());
|
||||
out
|
||||
}
|
||||
|
||||
/// What `text` shows as: each escaped character as itself. Panics on a Markdown punctuation
|
||||
/// character without its backslash, or a backslash before a character that needs none.
|
||||
fn literal(text: &str) -> String {
|
||||
let (mut out, mut chars) = (String::new(), text.chars());
|
||||
while let Some(c) = chars.next() {
|
||||
assert!(!ESCAPED.contains(&c) || c == '\\', "`{c}` is not escaped in {text}");
|
||||
if c == '\\' {
|
||||
let next = chars.next().unwrap_or_else(|| panic!("a backslash ends {text}"));
|
||||
assert!(ESCAPED.contains(&next) || next == '.', "`\\{next}` in {text}");
|
||||
out.push(next);
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The shown cells of the row of parameter `name`.
|
||||
fn row(markdown: &str, name: &str) -> Vec<String> {
|
||||
let found = markdown.lines().filter(|l| l.starts_with('|')).find(|l| cells(l).first().map(|c| literal(c)).as_deref() == Some(name));
|
||||
let row = found.unwrap_or_else(|| panic!("no row for {name} in\n{markdown}"));
|
||||
let cells = cells(row);
|
||||
assert_eq!(cells.len(), 9, "{row}");
|
||||
cells.iter().map(|c| literal(c)).collect()
|
||||
}
|
||||
|
||||
/// The text after `- {label}: ` in the section's list.
|
||||
fn item(markdown: &str, label: &str) -> String {
|
||||
let prefix = format!("- {label}: ");
|
||||
let line = markdown.lines().find_map(|l| l.strip_prefix(prefix.as_str()));
|
||||
literal(line.unwrap_or_else(|| panic!("no {label} in\n{markdown}")))
|
||||
}
|
||||
|
||||
/// Two calls give the same bytes, with no document open, and the reference has one section
|
||||
/// for each built-in command that has a schema, in registry order, ending with this command's.
|
||||
#[test]
|
||||
fn the_reference_lists_each_schema_once_in_registry_order_and_is_the_same_each_time() {
|
||||
let mut s = Session::new();
|
||||
let first = s.execute(ID, &json!({})).unwrap();
|
||||
let second = s.execute(ID, &Value::Null).unwrap();
|
||||
assert_eq!(first, second);
|
||||
let markdown = first["markdown"].as_str().unwrap();
|
||||
assert_eq!(markdown, reference(command_specs()).unwrap());
|
||||
assert!(markdown.len() < MAX_BYTES / 10, "{} bytes", markdown.len());
|
||||
let headings: Vec<String> = markdown.lines().filter_map(|l| l.strip_prefix("## ")).map(literal).collect();
|
||||
let expected: Vec<&str> = command_specs().iter().filter(|c| c.schema.is_some()).map(|c| c.id).collect();
|
||||
assert_eq!(headings, expected);
|
||||
assert_eq!(headings.last().map(String::as_str), Some(ID));
|
||||
assert!(expected.contains(&"view.saved.new") && !headings.iter().any(|h| h == "file.new"));
|
||||
let new_view = &markdown[markdown.find("## view.saved.new").unwrap()..];
|
||||
let names: Vec<String> = new_view
|
||||
.lines()
|
||||
.skip_while(|l| !l.starts_with("|---"))
|
||||
.skip(1)
|
||||
.take_while(|l| l.starts_with('|'))
|
||||
.map(|l| literal(&cells(l)[0]))
|
||||
.collect();
|
||||
assert_eq!(names, ["name", "center", "zoom", "rotation"]);
|
||||
let edit = &markdown[markdown.find("## view.saved.edit").unwrap()..];
|
||||
assert_eq!(row(edit, "edits[].newName")[8], "null reads as omitted");
|
||||
assert_eq!(row(edit, "newName")[8], "rename; null reads as omitted");
|
||||
}
|
||||
|
||||
const INNER: &[Param] =
|
||||
&[Param::new("size", Type::Integer { min: Some(1), max: Some(10) }), Param::new("mode", Type::Enum(&["a", "b"])).defaults_to("\"a\"")];
|
||||
|
||||
static FULL: ParamSchema = ParamSchema::new(
|
||||
&[
|
||||
Param::new("zoom", Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(64.0)), unit: Some("pt") })
|
||||
.doc("1 = 100%"),
|
||||
Param::new("name", Type::String).default_note("the first free name").null_omitted(),
|
||||
Param::new("old", Type::Boolean).defaults_to("true").since(2).deprecated(3).lenient(),
|
||||
Param::new("edits", Type::Array(&Type::Object(INNER))).optional(),
|
||||
Param::new("ids", Type::Ids).optional(),
|
||||
Param::new("at", Type::Point).optional(),
|
||||
Param::new("color", Type::Color).optional(),
|
||||
Param::new("id", Type::Id).optional(),
|
||||
Param::new("ratio", Type::Number { min: Some(Bound::Inclusive(-1.5)), max: Some(Bound::Exclusive(2.0)), unit: None }).optional(),
|
||||
],
|
||||
"do the thing",
|
||||
)
|
||||
.returns("{done}")
|
||||
.writes(Writes::Preferences)
|
||||
.since(2)
|
||||
.deprecated(4)
|
||||
.cost(5);
|
||||
|
||||
/// Each field of a schema shows, nested members in their order under dotted names.
|
||||
#[test]
|
||||
fn every_field_of_a_schema_is_shown() {
|
||||
let markdown = reference(&[spec("test.full", &["View", "Saved"], Some(&FULL))]).unwrap();
|
||||
for (label, shown) in [
|
||||
("Label", "Label"),
|
||||
("Menu", "View › Saved"),
|
||||
("API level", "2"),
|
||||
("Deprecated", "API level 4"),
|
||||
("Writes", "preferences"),
|
||||
("Cost", "5"),
|
||||
("Summary", "do the thing"),
|
||||
("Returns", "{done}"),
|
||||
] {
|
||||
assert_eq!(item(&markdown, label), shown, "{label}");
|
||||
}
|
||||
let lenient = "lenient (a value of another type or out of range is passed to the command, not refused)";
|
||||
let expected: [[&str; 9]; 11] = [
|
||||
["zoom", "number", "more than 0, at most 64", "pt", "None", "Yes", "1", "None", "1 = 100%"],
|
||||
["name", "string", "None", "None", "the first free name (worked out by the command)", "No", "1", "None", "null reads as omitted"],
|
||||
["old", "boolean", "None", "None", "true (JSON)", "No", "2", "API level 3", lenient],
|
||||
["edits", "list of object", "None", "None", "None", "No", "1", "None", "None"],
|
||||
["edits[].size", "integer", "at least 1, at most 10", "None", "None", "Yes", "1", "None", "None"],
|
||||
["edits[].mode", "one of \"a\", \"b\"", "None", "None", "\"a\" (JSON)", "No", "1", "None", "None"],
|
||||
["ids", "list of object ids", "None", "None", "None", "No", "1", "None", "None"],
|
||||
["at", "point ([x, y], two numbers)", "None", "None", "None", "No", "1", "None", "None"],
|
||||
["color", "color (a string, [r, g, b] or an object)", "None", "None", "None", "No", "1", "None", "None"],
|
||||
["id", "object id (integer)", "at least 0, at most 9007199254740991", "None", "None", "No", "1", "None", "None"],
|
||||
["ratio", "number", "at least -1.5, less than 2", "None", "None", "No", "1", "None", "None"],
|
||||
];
|
||||
let names: Vec<String> =
|
||||
markdown.lines().filter(|l| l.starts_with("| ") && !l.starts_with("| Parameter")).map(|l| literal(&cells(l)[0])).collect();
|
||||
assert_eq!(names, expected.map(|r| r[0]));
|
||||
for want in expected {
|
||||
assert_eq!(row(&markdown, want[0]), want, "{}", want[0]);
|
||||
}
|
||||
}
|
||||
|
||||
const HOSTILE: &str = "a | b [link](https://evil.example) <script>x</script> `code` \\ *em* _u_  & ~~s~~ # h www.example.com me@example.com\r\nnext\tline";
|
||||
|
||||
static ESCAPES: ParamSchema =
|
||||
ParamSchema::new(&[Param::new("a|b", Type::String).doc(HOSTILE).defaults_to("\"<b>|</b>\"")], HOSTILE).returns(HOSTILE);
|
||||
|
||||
/// Markdown in a schema's text shows as plain text: a description stays in its own cell of a
|
||||
/// nine-cell row, every punctuation character is escaped, and line breaks and tabs are spaces.
|
||||
#[test]
|
||||
fn markdown_in_schema_text_stays_literal_in_its_cell() {
|
||||
let markdown = reference(&[spec("test.escapes", &["A|B", "[x](y)"], Some(&ESCAPES))]).unwrap();
|
||||
let shown = HOSTILE.replace(['\r', '\n', '\t'], " ");
|
||||
let cells = row(&markdown, "a|b");
|
||||
assert_eq!(cells[4], "\"<b>|</b>\" (JSON)");
|
||||
assert_eq!(cells[8], shown);
|
||||
assert_eq!(item(&markdown, "Summary"), shown);
|
||||
assert_eq!(item(&markdown, "Returns"), shown);
|
||||
assert_eq!(item(&markdown, "Menu"), "A|B › [x](y)");
|
||||
assert!(markdown.contains("www\\.example"), "{markdown}");
|
||||
let table: Vec<&str> = markdown.lines().filter(|l| l.starts_with('|')).collect();
|
||||
assert_eq!(table.len(), 3, "the header, the delimiter row and one row: {table:?}");
|
||||
assert!(!markdown.contains('\r') && !markdown.contains('\t'));
|
||||
}
|
||||
|
||||
/// A registry with no schema gives the header and a line that says so; a command without a
|
||||
/// schema adds nothing.
|
||||
#[test]
|
||||
fn a_registry_without_schemas_gives_a_document_that_says_so() {
|
||||
let empty = format!("{HEADER}\nNo commands have parameter schemas.\n");
|
||||
assert_eq!(reference(&[]).unwrap(), empty);
|
||||
assert_eq!(reference(&[spec("test.none", &["View"], None)]).unwrap(), empty);
|
||||
let one = reference(&[spec("test.none", &[], None), spec("test.full", &[], Some(&FULL)), spec("test.other", &[], None)]).unwrap();
|
||||
assert_eq!(one, reference(&[spec("test.full", &[], Some(&FULL))]).unwrap());
|
||||
}
|
||||
|
||||
/// A reference of exactly [`MAX_BYTES`] is returned; one byte more is an error naming the
|
||||
/// command, with no part of the reference.
|
||||
#[test]
|
||||
fn a_reference_past_the_limit_is_an_error() {
|
||||
let with = |summary: String| -> Result<String> {
|
||||
let schema: &'static ParamSchema = Box::leak(Box::new(ParamSchema::new(&[], Box::leak(summary.into_boxed_str()))));
|
||||
reference(&[spec("test.big", &[], Some(schema))])
|
||||
};
|
||||
let base = with("x".into()).unwrap().len();
|
||||
let fits = with("x".repeat(MAX_BYTES - base + 1)).unwrap();
|
||||
assert_eq!(fits.len(), MAX_BYTES);
|
||||
let e = with("x".repeat(MAX_BYTES - base + 2)).unwrap_err().to_string();
|
||||
assert!(e.contains(ID) && e.contains("larger than 1048576 bytes"), "{e}");
|
||||
assert!(e.len() < 200, "{e}");
|
||||
}
|
||||
|
||||
/// An unknown key is refused with a parameter error naming it, and the command needs no
|
||||
/// document.
|
||||
#[test]
|
||||
fn an_unknown_parameter_is_refused_naming_it() {
|
||||
let mut s = Session::new();
|
||||
let e = s.execute(ID, &json!({"prefix": "view."})).unwrap_err().to_string();
|
||||
assert!(e.contains(ID) && e.contains("`prefix`"), "{e}");
|
||||
assert!(s.execute(ID, &json!([])).is_err());
|
||||
assert!(s.active().is_none());
|
||||
assert!(s.execute(ID, &json!({})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_marks_each_punctuation_character_and_flattens_control_characters() {
|
||||
assert_eq!(escape("a|b"), "a\\|b");
|
||||
assert_eq!(escape("WWW.x and w.x"), "WWW\\.x and w.x");
|
||||
assert_eq!(escape("é\u{7}\u{85}z"), "é z");
|
||||
assert_eq!(escape("1.5 > 1"), "1.5 \\> 1");
|
||||
}
|
||||
}
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eyedropper",
|
||||
[],
|
||||
None,
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's solid fill and stroke for this instance only, as the Eyedropper Options allow, and a sampled gradient or pattern, a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}",
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -1204,11 +1204,10 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let attrs = s.prefs.eyedropper.attrs(p).map_err(|e| bad(C, e))?;
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection takes the clicked
|
||||
// object's solid fill and stroke, as the Eyedropper Options allow, for this instance only. A
|
||||
// gradient or pattern sampled for it, a source that is not a path, compound path or type (a
|
||||
// symbol instance's own appearance is empty), and options that pick up neither color are
|
||||
// refused, and the paint defaults stay as they are. A path of a compound path stands for the
|
||||
// compound path, which holds the paint.
|
||||
// object's fill and stroke, as the Eyedropper Options allow, for this instance only. A source
|
||||
// that is not a path, compound path or type (a symbol instance's own appearance is empty) and
|
||||
// options that pick up neither color are refused, and the paint defaults stay as they are. A
|
||||
// path of a compound path stands for the compound path, which holds the paint.
|
||||
if !reverse
|
||||
&& !append
|
||||
&& !defaults_only
|
||||
@@ -1219,11 +1218,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let src = Arc::new(d.node(super::path::compound_or_self(d, clicked)).ok_or(EngineError::NoNode(clicked))?.clone());
|
||||
let (fill, stroke) = (super::paint::proxy_paint(&src, false, None), super::paint::proxy_paint(&src, true, None));
|
||||
let a = attrs.appearance;
|
||||
if !vectorcraft_doc::symbol_overrides::takes_part_paint(&src)
|
||||
|| !(a.fill.color || a.stroke.color)
|
||||
|| (a.fill.color && !super::paint::part_takes(&fill))
|
||||
|| (a.stroke.color && !super::paint::part_takes(&stroke))
|
||||
{
|
||||
if !vectorcraft_doc::symbol_overrides::takes_part_paint(&src) || !(a.fill.color || a.stroke.color) {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
super::brushsym::edit_part(s, id, &path, "Eyedropper", |o| {
|
||||
|
||||
@@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Assets",
|
||||
[],
|
||||
None,
|
||||
"{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included), format3D: usda|usdz|gltf|obj | null (a 3D asset's mesh format; null for art exported as pictures)}]} the Asset Export panel's assets, in order",
|
||||
"{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included, with the clips of the groups and layers that hold it), format3D: usda|usdz|gltf|obj | null (a 3D asset's mesh format; null for art exported as pictures)}]} the Asset Export panel's assets, in order",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
|
||||
@@ -272,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Symbol Instance Part",
|
||||
[],
|
||||
None,
|
||||
"{id, path: [i…] (as symbol.instance.setAppearance)} select one path, compound path or type object of a dynamic symbol instance's art, as a Direct Selection click on it does: the instance is selected alone, and until the selection changes paint.setFill and paint.setStroke with a solid color or none, paint.invert and paint.complement on a solid color (without ids, id or item; type whose characters differ in color is refused) and appearance.copyFrom with a solid fill and stroke (the Eyedropper, without ids, reverse or append; options that pick up neither color are refused) change that object's fill or stroke for this instance only; gradients and patterns are refused, and so are the commands that change the selected objects without ids (transparency.set, the gradient commands, object.group, edit.cut and edit.clear among them); edit.copy copies the instance whole, and selection exports, artboard.fitToSelection, object.liquify, object.isolate, library.add and select.save use the instance (docs/mcp.md); selectPart itself is refused for a static symbol, a path naming no object, a group, image or other kind of object, a hidden, locked or template object or one inside such a group, and a hidden or locked instance → {id, path}",
|
||||
"{id, path: [i…] (as symbol.instance.setAppearance)} select one path, compound path or type object of a dynamic symbol instance's art, as a Direct Selection click on it does: the instance is selected alone, and until the selection changes paint.setFill and paint.setStroke (solid, none, gradient or pattern), transparency.set with opacity and/or blend, paint.invert and paint.complement on a solid color (without ids, id or item; type whose characters differ in color is refused) and appearance.copyFrom (the Eyedropper, without ids, reverse or append; options that pick up neither color are refused; a gradient or pattern fill or stroke is taken) change that object for this instance only; the gradient annotator commands, isolate/knockout on transparency.set, object.group, edit.cut and edit.clear among the commands that change the selected objects without ids are refused; edit.copy copies the instance whole, and selection exports, artboard.fitToSelection, object.liquify, object.isolate, library.add and select.save use the instance (docs/mcp.md); selectPart itself is refused for a static symbol, a path naming no object, a group, image or other kind of object, a hidden, locked or template object or one inside such a group, and a hidden or locked instance → {id, path}",
|
||||
has_doc,
|
||||
symbol_instance_select_part
|
||||
),
|
||||
|
||||
@@ -510,7 +510,7 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some()));
|
||||
let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?;
|
||||
let r = (spec.run)(s, p)?;
|
||||
let r = crate::cmd::run_checked(s, spec, p)?;
|
||||
let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) };
|
||||
s.edit("Paintbrush", |d, _| {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
|
||||
@@ -90,10 +90,11 @@ pub(crate) fn edit_part(s: &mut Session, id: NodeId, path: &[u32], label: &str,
|
||||
})
|
||||
}
|
||||
|
||||
/// The refusal of anything but a solid color fill or stroke change while an object of a symbol
|
||||
/// instance's art is selected ([`selected_part`]), and of selecting any other object of the art.
|
||||
/// The refusal of a change that is not the fill, stroke, opacity or blend of a path, compound path
|
||||
/// or type while an object of a symbol instance's art is selected ([`selected_part`]), and of
|
||||
/// selecting any other object of the art.
|
||||
pub(crate) fn part_only() -> EngineError {
|
||||
EngineError::Other("Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change".into())
|
||||
EngineError::Other("Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change".into())
|
||||
}
|
||||
|
||||
pub(super) fn symbol_instance_select_part(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -115,7 +115,8 @@ pub(crate) fn subpath_selected_segments(
|
||||
let n = sp.anchors.len();
|
||||
let mut selected_segs = BTreeSet::new();
|
||||
|
||||
let has_explicit_segs = seg_refs.is_some_and(|segments| segments.iter().any(|&(s, _)| s == si));
|
||||
// Segments picked anywhere on the path leave anchors out of it, as Clear does.
|
||||
let has_explicit_segs = seg_refs.is_some_and(|segments| !segments.is_empty());
|
||||
if has_explicit_segs {
|
||||
if let Some(segments) = seg_refs {
|
||||
for &(s, seg) in segments {
|
||||
|
||||
@@ -48,9 +48,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert to Grayscale",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed, notChanged, warning?}",
|
||||
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert; an embedded image is stored with one gray channel) → {changed, notChanged, warning?}",
|
||||
has_selection,
|
||||
|s, p| recolor(s, p, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray)
|
||||
|s, p| recolor_gray(s, p, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray)
|
||||
),
|
||||
cmd!(
|
||||
"edit.colors.toRGB",
|
||||
@@ -187,6 +187,8 @@ pub(crate) struct Recolor<'a> {
|
||||
/// Maps solid colours and gradient stops with their link and tint in place of `f`.
|
||||
links: Option<&'a LinkMap<'a>>,
|
||||
scope: Scope,
|
||||
/// Recolored images are stored with one gray channel ([`ImageBlob::map_gray`]).
|
||||
gray_images: bool,
|
||||
/// Image key → the key of its recoloured copy (`None`: unchanged).
|
||||
images: HashMap<String, Option<String>>,
|
||||
/// Pattern name → the name of its recoloured copy (`None`: unchanged, or being recoloured).
|
||||
@@ -198,7 +200,17 @@ pub(crate) struct Recolor<'a> {
|
||||
|
||||
impl<'a> Recolor<'a> {
|
||||
pub(crate) fn new(scope: Scope, f: &'a dyn Fn(Color) -> Color) -> Self {
|
||||
Self { f, links: None, scope, images: HashMap::new(), patterns: HashMap::new(), new_images: vec![], new_patterns: vec![], changed: 0 }
|
||||
Self {
|
||||
f,
|
||||
links: None,
|
||||
scope,
|
||||
gray_images: false,
|
||||
images: HashMap::new(),
|
||||
patterns: HashMap::new(),
|
||||
new_images: vec![],
|
||||
new_patterns: vec![],
|
||||
changed: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A pass that maps only solid colours and gradient stops, with their swatch link and tint
|
||||
@@ -215,7 +227,7 @@ impl<'a> Recolor<'a> {
|
||||
|
||||
/// A pass that maps colors as this one does, with nothing recolored yet.
|
||||
fn again(&self) -> Self {
|
||||
Self { links: self.links, ..Self::new(self.scope, self.f) }
|
||||
Self { links: self.links, gray_images: self.gray_images, ..Self::new(self.scope, self.f) }
|
||||
}
|
||||
|
||||
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
|
||||
@@ -313,10 +325,15 @@ impl<'a> Recolor<'a> {
|
||||
return done.clone();
|
||||
}
|
||||
let f = self.f;
|
||||
let new = d.images.get(key)?.map_rgb(|[r, g, b]| {
|
||||
let [r, g, b, _] = f(Color::rgb8(r, g, b)).to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
});
|
||||
let blob = d.images.get(key)?;
|
||||
let new = if self.gray_images {
|
||||
blob.map_gray(|[r, g, b]| f(Color::rgb8(r, g, b)).to_rgba8(1.0)[0])
|
||||
} else {
|
||||
blob.map_rgb(|[r, g, b]| {
|
||||
let [r, g, b, _] = f(Color::rgb8(r, g, b)).to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
})
|
||||
};
|
||||
let new = new.map(|blob| {
|
||||
let k = blob.content_key();
|
||||
self.new_images.push((k.clone(), blob));
|
||||
@@ -400,6 +417,11 @@ pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dy
|
||||
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p), f))
|
||||
}
|
||||
|
||||
/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel.
|
||||
fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p), f) })
|
||||
}
|
||||
|
||||
/// [`recolor`] with solid colours and gradient stops mapped through `links`, with their swatch
|
||||
/// link and tint.
|
||||
pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result<Value> {
|
||||
@@ -575,10 +597,11 @@ fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
other => return Err(bad(C, format!("unknown mode `{other}` (rgb|cmyk|gray|global)"))),
|
||||
};
|
||||
let convert = bool_or(p, "convert", false);
|
||||
recolor(s, p, C, "Adjust Colors", &move |c| {
|
||||
let f = move |c| {
|
||||
let out = adjust(c);
|
||||
if convert { out } else { keep_model(c, out) }
|
||||
})
|
||||
};
|
||||
if convert && mode == "gray" { recolor_gray(s, p, C, "Adjust Colors", &f) } else { recolor(s, p, C, "Adjust Colors", &f) }
|
||||
}
|
||||
|
||||
enum BlendOrder {
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export CSS",
|
||||
[],
|
||||
None,
|
||||
"{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of the object's visual bounds, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once",
|
||||
"{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of what the object draws, with the clips, masks and effects of the groups and layers that hold it, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
|
||||
@@ -183,7 +183,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Lock Guides",
|
||||
["View", "Guides"],
|
||||
Some("Cmd+Alt+;"),
|
||||
"{locked?: bool} toggle (or set) the session's guide lock; locking deselects the ruler guides and guide paths in every open document → {locked}",
|
||||
"{locked?: bool} toggle (or set) the session's guide lock, leaving the lockGuidesByDefault preference as it is; locking deselects the ruler guides and guide paths in every open document; guide.add and a guide dragged out of a ruler still make new guides while locked → {locked}",
|
||||
has_doc,
|
||||
lock_guides
|
||||
),
|
||||
@@ -277,6 +277,27 @@ impl Session {
|
||||
pub fn guides_locked(&self) -> bool {
|
||||
self.menu.guides_locked
|
||||
}
|
||||
|
||||
/// Set View → Guides → Lock Guides. Locked guides can't stay selected, ruler guides or guide
|
||||
/// paths, in any open document ([`Session::select`] lets those go in the active one).
|
||||
pub(crate) fn set_guides_locked(&mut self, locked: bool) {
|
||||
self.menu.guides_locked = locked;
|
||||
if !locked {
|
||||
return;
|
||||
}
|
||||
let guides_selected =
|
||||
self.doc().is_ok_and(|st| !st.selection.guides.is_empty() || st.selection.objects.iter().any(|id| crate::is_guide_path(&st.doc, *id)));
|
||||
// It fails only without a document, and then no guide is selected.
|
||||
if guides_selected {
|
||||
let _ = self.select(|_, sel| sel.guides.clear());
|
||||
}
|
||||
let active = self.active;
|
||||
for (i, st) in self.docs.iter_mut().enumerate() {
|
||||
if Some(i) != active && crate::deselect_hidden(&self.menu, &st.doc, &mut st.selection) {
|
||||
st.revision += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Select ----------
|
||||
@@ -717,21 +738,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn lock_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let v = switch_or(p, "locked", !s.menu.guides_locked, "view.guides.lock")?;
|
||||
s.menu.guides_locked = v;
|
||||
// Locked guides can't stay selected, ruler guides or guide paths, in any open document
|
||||
// ([`Session::select`] lets those go in the active one).
|
||||
let st = s.doc()?;
|
||||
if v && (!st.selection.guides.is_empty() || st.selection.objects.iter().any(|id| crate::is_guide_path(&st.doc, *id))) {
|
||||
s.select(|_, sel| sel.guides.clear())?;
|
||||
}
|
||||
if v {
|
||||
let active = s.active;
|
||||
for (i, st) in s.docs.iter_mut().enumerate() {
|
||||
if Some(i) != active && crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection) {
|
||||
st.revision += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
s.set_guides_locked(v);
|
||||
Ok(json!({ "locked": v }))
|
||||
}
|
||||
|
||||
|
||||
@@ -1063,8 +1063,12 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
let cuts = super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs);
|
||||
if cuts.is_empty() {
|
||||
subpaths.push(sp);
|
||||
} else {
|
||||
} else if seg_refs.is_some_and(|segments| !segments.is_empty()) {
|
||||
subpaths.extend(super::path::without_segments(sp, &cuts));
|
||||
} else {
|
||||
// Picked anchors leave the path with their connections, as Clear removes them.
|
||||
let gone: BTreeSet<usize> = anchor_refs.into_iter().flatten().filter_map(|&(s, a)| (s == si).then_some(a)).collect();
|
||||
subpaths.extend(super::path::without_anchors(sp, &gone));
|
||||
}
|
||||
}
|
||||
subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
|
||||
@@ -280,9 +280,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let item = item_target(s, p, C)?;
|
||||
if effects::is_three_d(id) {
|
||||
for target in appearance_targets(s, p)? {
|
||||
let targets = appearance_targets(s, p)?;
|
||||
for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) {
|
||||
let n = s.doc()?.doc.node(target).ok_or(EngineError::NoNode(target))?;
|
||||
effects::validate_three_d(n, id, &effect.params).map_err(|e| bad(C, e))?;
|
||||
// A new effect goes after the item's others.
|
||||
let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten();
|
||||
let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len())));
|
||||
effects::validate_three_d_at(n, id, &effect.params, on).map_err(|e| bad(C, e))?;
|
||||
if id == effects::REVOLVE && effects::has_revolve(n) {
|
||||
return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead."));
|
||||
}
|
||||
@@ -589,7 +593,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
cur.extend(new);
|
||||
}
|
||||
if visible != Some(false) {
|
||||
effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?;
|
||||
effects::validate_three_d_at(n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?;
|
||||
} else {
|
||||
// Hidden, the effect draws nothing, so its object need not fit. The values given are
|
||||
// checked, and after a change of 3D type so is every value it keeps.
|
||||
@@ -865,8 +869,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
// keeps it as its only member).
|
||||
Some((image, false)) => Some(rasterfx::replace_with_image(v, image)),
|
||||
image => {
|
||||
let m = if container && effects::has_solid(&v) {
|
||||
// A group's or layer's 3D effect: the shaded faces of its members' solids.
|
||||
let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) {
|
||||
// A 3D effect on a group or layer, or on type: the shaded faces of its solids.
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
|
||||
@@ -193,6 +193,169 @@ fn type_extrudes_as_its_glyphs_and_stays_editable() {
|
||||
assert_ne!(effects::solid_art(&node(&s, id)).unwrap(), art, "the solid follows the edited text");
|
||||
}
|
||||
|
||||
/// #3617: Revolve takes live type and stays type, updating when the text changes, and saves,
|
||||
/// exports, expands and undoes as one step.
|
||||
#[test]
|
||||
fn type_revolves_as_its_glyphs_and_stays_editable() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": "O", "size": 72})).unwrap();
|
||||
let id = NodeId(t["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#cc2200"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null, "params": {"segments": 16}})).unwrap();
|
||||
let n = node(&s, id);
|
||||
assert!(matches!(n.kind, NodeKind::Text(_)), "still type");
|
||||
let art = effects::revolve_art(&n).expect("a surface of the glyphs");
|
||||
let mut tinted = false;
|
||||
art.walk(&mut |c| {
|
||||
if let Some([r, g, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) {
|
||||
tinted |= r > g && r > b;
|
||||
}
|
||||
});
|
||||
assert!(tinted, "shaded from the characters' red");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert_eq!(effects::revolve_art(restored.node(id).unwrap()).unwrap(), art, "the same art after a save");
|
||||
let meshes = effects::three_d_meshes(&n).unwrap();
|
||||
assert_eq!(meshes.len(), 1, "one mesh of every contour of the type");
|
||||
s.execute("text.setText", &json!({"ids": [id.0], "text": "OO"})).unwrap();
|
||||
assert_ne!(effects::revolve_art(&node(&s, id)).unwrap(), art, "the surface follows the edited text");
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(!effects::has_revolve(&node(&s, id)), "expanded");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::Text(_)));
|
||||
assert!(effects::has_revolve(&node(&s, id)));
|
||||
// Extrude & Bevel on type expands the same way.
|
||||
s.execute("effect.remove", &json!({"index": 0, "ids": [id.0], "item": null})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(!effects::has_solid(&node(&s, id)), "expanded");
|
||||
}
|
||||
|
||||
/// Revolve refuses type with no outlines, and a group with no visible shape, without adding an
|
||||
/// effect. Extrude & Bevel gives the same reason for empty type.
|
||||
#[test]
|
||||
fn revolve_refuses_type_and_groups_without_a_shape() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
for text in ["", " "] {
|
||||
let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": text, "size": 72})).unwrap();
|
||||
let id = NodeId(t["id"].as_u64().unwrap());
|
||||
for effect in ["threeD.revolve", "threeD.extrude"] {
|
||||
let err = s.execute("effect.apply", &json!({"effect": effect, "ids": [id.0], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("at least two anchors"), "{effect}, {text:?}: {err}");
|
||||
assert!(node(&s, id).appearance.effects.is_empty());
|
||||
}
|
||||
}
|
||||
let (mut s, a) = session_with_rect();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
for member in [a.0, b] {
|
||||
s.execute("select.set", &json!({"ids": [member]})).unwrap();
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
}
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("group holding a shape"), "{err}");
|
||||
assert!(node(&s, g).appearance.effects.is_empty());
|
||||
}
|
||||
|
||||
/// A Revolve on one fill is checked in that fill's paint, and `effect.setParams` on it as well.
|
||||
#[test]
|
||||
fn revolve_on_a_fill_is_checked_in_that_fills_paint() {
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer};
|
||||
let (mut s, id) = session_with_rect();
|
||||
// The paint copies of 100 faces reach the 256 MiB budget: 8 segments stay under, 64 pass it.
|
||||
let count = (256 << 20) / (4 * 100 * std::mem::size_of::<GradientStop>());
|
||||
let stops = (0..count).map(|i| GradientStop::new(i as f32 / count as f32, Color::rgb(1.0, 0.0, 0.0))).collect();
|
||||
let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
s.edit("fills", |d, _| {
|
||||
let n = d.node_mut(id).unwrap();
|
||||
n.appearance.items =
|
||||
vec![AppearanceItem::Fill(FillLayer::new(ramp)), AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0))))];
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": 0})).unwrap_err().to_string();
|
||||
assert!(err.contains("simplify the gradient"), "{err}");
|
||||
assert!(node(&s, id).appearance.items[0].effects().is_empty());
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": 0, "params": {"segments": 8}})).unwrap();
|
||||
let err = s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": 0, "params": {"segments": 128}})).unwrap_err().to_string();
|
||||
assert!(err.contains("simplify the gradient"), "{err}");
|
||||
}
|
||||
|
||||
/// A hidden Revolve still counts as the object's one Revolve: a second one is refused, and the
|
||||
/// hidden one can be shown again over the geometry effects after it.
|
||||
#[test]
|
||||
fn a_second_revolve_is_refused_over_a_hidden_one() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null})).unwrap();
|
||||
s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": null, "visible": false})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [id.0], "item": null})).unwrap();
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("one Revolve effect"), "{err}");
|
||||
let ids: Vec<_> = node(&s, id).appearance.effects.iter().map(|e| e.id.clone()).collect();
|
||||
assert_eq!(ids, ["threeD.revolve", "distort.roughen"]);
|
||||
s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": null, "visible": true})).unwrap();
|
||||
assert!(node(&s, id).appearance.effects[0].visible);
|
||||
}
|
||||
|
||||
/// Revolve on a group sweeps every member about one axis on the left edge of their bounds, keeps
|
||||
/// each member's paint, follows an edited member, expands and undoes as one step.
|
||||
#[test]
|
||||
fn revolve_on_a_group_shares_one_axis_and_members_stay_editable() {
|
||||
let (mut s, a) = session_with_rect();
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#cc2200"})).unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 250, "y": 100, "width": 50, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [b], "color": "#0022cc"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null, "params": {"segments": 16, "rotationX": 90}})).unwrap();
|
||||
assert_eq!(node(&s, g).children().unwrap().len(), 2, "the members stay as they were");
|
||||
let art = effects::revolve_art(&node(&s, g)).expect("a surface of the members");
|
||||
// The axis is the left edge of both members together (x = 100), so the right member's far
|
||||
// wall sweeps out to 200 pt from it on either side: x = 300 and x = -100.
|
||||
let bounds = art.visual_bounds().unwrap();
|
||||
assert!((bounds.x1 - 300.0).abs() < 2.0 && (bounds.x0 + 100.0).abs() < 2.0, "{bounds:?}");
|
||||
let (mut red, mut blue) = (false, false);
|
||||
art.walk(&mut |c| {
|
||||
if let Some([r, _, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) {
|
||||
red |= r > b;
|
||||
blue |= b > r;
|
||||
}
|
||||
});
|
||||
assert!(red && blue, "each member keeps its own paint");
|
||||
assert_eq!(effects::three_d_meshes(&node(&s, g)).unwrap().len(), 2, "a mesh for each member");
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
|
||||
assert!(vectorcraft_testkit::svg_shapes(&svg) >= 4, "both members exported as vector faces");
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": -40, "dy": 0})).unwrap();
|
||||
assert_ne!(effects::revolve_art(&node(&s, g)).unwrap(), art, "a moved member reshapes the surface");
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
|
||||
assert!(!effects::has_revolve(&node(&s, g)), "expanded");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(effects::has_revolve(&node(&s, g)));
|
||||
}
|
||||
|
||||
/// A group holding what can't be swept is refused as a whole, and a clipping group is named.
|
||||
#[test]
|
||||
fn revolve_refuses_a_group_with_a_member_it_can_not_sweep() {
|
||||
let (mut s, a) = session_with_rect();
|
||||
let b = s.execute("shape.ellipse", &json!({"x": 120, "y": 120, "width": 60, "height": 60})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
|
||||
let clip = s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].clone();
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [clip.as_u64().unwrap()], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("path, compound path, type or group"), "{err}");
|
||||
let c = s.execute("shape.rectangle", &json!({"x": 250, "y": 250, "width": 50, "height": 50})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [clip, c]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("Revolve on a group") && err.contains("clipping groups"), "{err}");
|
||||
assert!(node(&s, g).appearance.effects.is_empty());
|
||||
}
|
||||
|
||||
/// Scripts from before the Perspective angle give `perspective` as a 0–100 % strength: it is
|
||||
/// stored as the angle that shows the same view, and a later angle replaces an earlier strength.
|
||||
#[test]
|
||||
@@ -581,7 +744,7 @@ fn expand_appearance_makes_each_copy_of_a_transform_an_object() {
|
||||
let copies = n.children().unwrap();
|
||||
assert_eq!(copies.len(), 3, "the path and its two copies");
|
||||
let xs: Vec<f64> = copies.iter().map(|c| c.geometric_bounds().unwrap().x0).collect();
|
||||
assert_eq!(xs, vec![100.0, 250.0, 400.0]);
|
||||
assert_eq!(xs, vec![400.0, 250.0, 100.0], "the original on top");
|
||||
for c in copies {
|
||||
assert!(matches!(c.kind, NodeKind::Path { .. }), "{}", c.kind_label());
|
||||
assert_eq!(fill(c), Some(Color::rgb(1.0, 0.0, 0.0)));
|
||||
@@ -600,10 +763,10 @@ fn expand_appearance_makes_each_copy_of_a_transform_an_object() {
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
let columns = node(&s, id).children().unwrap().to_vec();
|
||||
assert_eq!(columns.len(), 3);
|
||||
for (col, x) in columns.iter().zip([100.0, 250.0, 400.0]) {
|
||||
for (col, x) in columns.iter().zip([400.0, 250.0, 100.0]) {
|
||||
let cells = col.children().unwrap_or_else(|| panic!("a column is a group: {}", col.kind_label()));
|
||||
let ys: Vec<(f64, f64)> = cells.iter().map(|c| (c.geometric_bounds().unwrap().x0, c.geometric_bounds().unwrap().y0)).collect();
|
||||
assert_eq!(ys, vec![(x, 100.0), (x, 250.0)]);
|
||||
assert_eq!(ys, vec![(x, 250.0), (x, 100.0)]);
|
||||
assert!(cells.iter().all(|c| matches!(c.appearance.fill_paint(), Paint::Solid { .. })));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,6 +184,8 @@ mod tests_batch;
|
||||
#[cfg(test)]
|
||||
mod tests_screens;
|
||||
#[cfg(test)]
|
||||
mod tests_selexport;
|
||||
#[cfg(test)]
|
||||
mod tests_text;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in their layers)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path",
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path",
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
|
||||
@@ -94,27 +94,63 @@ pub fn export_source<'a>(st: &'a DocState, p: &Value) -> Result<Cow<'a, Document
|
||||
return Err(bad("document.export", "select something to export (or turn off selectedOnly)"));
|
||||
}
|
||||
let mut d = Document::clone(&st.doc);
|
||||
d.layers = st.doc.layers.iter().filter_map(|l| selected_part(l, &keep)).map(Arc::new).collect();
|
||||
d.layers = enclosed(&st.doc, &keep, false);
|
||||
Ok(Cow::Owned(d))
|
||||
}
|
||||
|
||||
/// `n` with only the parts in `keep` (whole, with everything inside them), `None` when none is.
|
||||
fn selected_part(n: &Node, keep: &HashSet<NodeId>) -> Option<Node> {
|
||||
/// The layers of `doc` with only the objects in `keep` (whole, with everything inside them), each
|
||||
/// in the layers, groups and compound paths that hold it. Those keep what they apply to the object
|
||||
/// on the canvas: their clipping paths, opacity masks, effects, opacity and blend modes. An object
|
||||
/// of a blend, envelope, repeat or intertwine goes in on its own, without the art made from it. With
|
||||
/// `shown`, the layers and groups that hold the objects are visible, and those layers print and are
|
||||
/// not template layers.
|
||||
fn enclosed(doc: &Document, keep: &HashSet<NodeId>, shown: bool) -> Vec<Arc<Node>> {
|
||||
let holders: HashSet<NodeId> = keep.iter().filter_map(|id| doc.ancestry(*id)).flatten().filter(|id| !keep.contains(id)).collect();
|
||||
let mut out = vec![];
|
||||
for l in &doc.layers {
|
||||
selected_part(l, keep, &holders, shown, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The parts of `n` in `keep` (whole, with everything inside them), added to `out`: `n` itself, or
|
||||
/// `n` with only those parts when it is one of their `holders`, made visible, printable and not a
|
||||
/// template with `shown`.
|
||||
fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId>, shown: bool, out: &mut Vec<Arc<Node>>) {
|
||||
if keep.contains(&n.id) {
|
||||
return Some(n.clone());
|
||||
out.push(n.clone());
|
||||
return;
|
||||
}
|
||||
let Some(children) = n.children().filter(|_| holders.contains(&n.id)) else { return };
|
||||
let mut kept = vec![];
|
||||
for c in children {
|
||||
selected_part(c, keep, holders, shown, &mut kept);
|
||||
}
|
||||
if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }) {
|
||||
out.extend(kept);
|
||||
return;
|
||||
}
|
||||
let children = n.children()?;
|
||||
let mut kept: Vec<Arc<Node>> = children.iter().filter_map(|c| selected_part(c, keep).map(Arc::new)).collect();
|
||||
if kept.is_empty() {
|
||||
return None;
|
||||
return;
|
||||
}
|
||||
let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
|
||||
if let Some(first) = children.first().filter(|f| clip && kept.first().is_none_or(|k| k.id != f.id)) {
|
||||
// A clipping group or layer keeps its clipping path; a Shaper group its source art, which
|
||||
// draws nothing.
|
||||
let first_stays = n.clips() || n.extras().shaper.is_some();
|
||||
if let Some(first) = children.first().filter(|f| first_stays && kept.first().is_none_or(|k| k.id != f.id)) {
|
||||
kept.insert(0, first.clone());
|
||||
}
|
||||
let mut out = n.clone();
|
||||
*out.children_mut()? = kept;
|
||||
Some(out)
|
||||
let mut part = Node::clone(n);
|
||||
if let Some(ch) = part.children_mut() {
|
||||
*ch = kept;
|
||||
}
|
||||
if shown {
|
||||
part.visible = true;
|
||||
if let NodeKind::Layer { template, printable, .. } = &mut part.kind {
|
||||
*template = false;
|
||||
*printable = true;
|
||||
}
|
||||
}
|
||||
out.push(Arc::new(part));
|
||||
}
|
||||
|
||||
/// `doc` with only the art over `rect` (an artboard): objects whose visual bounds miss it are left
|
||||
@@ -126,13 +162,20 @@ fn selected_part(n: &Node, keep: &HashSet<NodeId>) -> Option<Node> {
|
||||
/// holds a symbol instance also stays when what the canvas paints for it reaches `rect`
|
||||
/// ([`vectorcraft_render::painted_bounds`]: the effects in the symbols' art and its own effects). A
|
||||
/// clipping layer keeps every object, its clipping path among them. An artboard's file then holds
|
||||
/// its own art, not a whole document of artboards.
|
||||
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document {
|
||||
fn kept(n: &Arc<Node>, doc: &Document, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect) -> Option<Arc<Node>> {
|
||||
/// its own art, not a whole document of artboards. `renderer` measures the 3D art, and keeps it for
|
||||
/// the next artboard of the same document.
|
||||
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Document {
|
||||
fn kept(
|
||||
n: &Arc<Node>,
|
||||
doc: &Document,
|
||||
symbols: &SymbolBoxes,
|
||||
rect: vectorcraft_geom::Rect,
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
) -> Option<Arc<Node>> {
|
||||
if matches!(n.kind, NodeKind::Layer { clip: false, .. }) {
|
||||
let mut layer = Node::clone(n);
|
||||
let children = layer.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
|
||||
return Some(Arc::new(layer));
|
||||
}
|
||||
// A group that doesn't clip keeps only its members over the artboard, so art gathered in one
|
||||
@@ -141,19 +184,18 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document
|
||||
if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() {
|
||||
let mut group = Node::clone(n);
|
||||
let children = group.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
|
||||
return (!children.is_empty()).then(|| Arc::new(group));
|
||||
}
|
||||
let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1;
|
||||
let mut holds_instance = false;
|
||||
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
|
||||
let drawn = || vectorcraft_render::effect_bounds(symbols, n).is_some_and(over);
|
||||
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
|
||||
(n.visual_bounds_with(symbols).is_none_or(over) || drawn() || painted()).then(|| n.clone())
|
||||
(n.visual_bounds_with(symbols).is_none_or(over) || renderer.effect_bounds(symbols, n).is_some_and(over) || painted()).then(|| n.clone())
|
||||
}
|
||||
let symbols = doc.symbol_boxes().with_brush_art();
|
||||
let mut d = doc.clone();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect)).collect();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect();
|
||||
d
|
||||
}
|
||||
|
||||
@@ -196,7 +238,7 @@ fn expand_presets<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Va
|
||||
/// with `selectionOnly` the selected objects alone.
|
||||
fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(Cow<'a, Document>, bool)> {
|
||||
if f.id == "txt" && bool_or(p, "selectionOnly", false) {
|
||||
let doc = selection(s, cmd)?.0;
|
||||
let doc = selection(s, cmd, true)?.0;
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
return Ok((Cow::Owned(doc), display_doc_title));
|
||||
}
|
||||
@@ -206,11 +248,21 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C
|
||||
Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title))
|
||||
}
|
||||
|
||||
/// The selected objects (not on template layers) alone on one layer, with one artboard: their
|
||||
/// visual bounds.
|
||||
fn selection(s: &mut Session, cmd: &str) -> Result<(Document, vectorcraft_geom::Rect)> {
|
||||
/// The selected objects (not on template layers) in the layers and groups that hold them
|
||||
/// ([`isolated`]), with one artboard: their crop. With `text`, the objects alone on one layer, so a
|
||||
/// text export holds the type of the selected objects and not that of a clipping path around them.
|
||||
fn selection(s: &mut Session, cmd: &str, text: bool) -> Result<(Document, vectorcraft_geom::Rect)> {
|
||||
let ids = selected_artwork(s)?;
|
||||
isolated(&s.doc()?.doc, &ids, "Selection").ok_or_else(|| bad(cmd, "select something to export"))
|
||||
let doc = &s.doc()?.doc;
|
||||
let (mut d, bounds) = isolated(doc, &ids, "Selection").ok_or_else(|| bad(cmd, "select something to export"))?;
|
||||
if text {
|
||||
let mut layer = Node::layer(d.alloc_id(), "Selection", vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
*ch = ids.iter().filter_map(|id| doc.node(*id).cloned().map(Arc::new)).collect();
|
||||
}
|
||||
d.layers = vec![Arc::new(layer)];
|
||||
}
|
||||
Ok((d, bounds))
|
||||
}
|
||||
|
||||
/// The selected objects (their top-most selected ancestors) that are artwork: those on template
|
||||
@@ -225,25 +277,30 @@ pub(crate) fn selected_artwork(s: &Session) -> Result<Vec<NodeId>> {
|
||||
Ok(ids.into_iter().filter(|id| !on_template(*id)).collect())
|
||||
}
|
||||
|
||||
/// The crop of an export of objects `ids` of `doc` alone: the bounds the renderer measures for what
|
||||
/// it draws for them, their effects included ([`vectorcraft_render::effect_bounds`]; symbol
|
||||
/// instances are measured by their art), `None` when they have none.
|
||||
/// The crop of an export of objects `ids` of `doc` alone ([`isolated`]): the bounds the renderer
|
||||
/// measures for what it draws for them, their effects included ([`vectorcraft_render::effect_bounds`];
|
||||
/// symbol instances are measured by their art), with what the layers and groups that hold them
|
||||
/// apply (a clipping group or layer is measured by its clip), `None` when they have none.
|
||||
pub(crate) fn export_crop(doc: &Document, ids: &[NodeId]) -> Option<vectorcraft_geom::Rect> {
|
||||
let symbols = doc.symbol_boxes();
|
||||
ids.iter().filter_map(|id| vectorcraft_render::effect_bounds(&symbols, doc.node(*id)?)).reduce(|a, b| a.union(b))
|
||||
isolated_art(doc, ids).1
|
||||
}
|
||||
|
||||
/// Objects `ids` of `doc` alone on one layer (in that order, back to front), with one artboard
|
||||
/// named `name`: their [`export_crop`] (`None` when they have none).
|
||||
/// The layers of [`isolated`] and their crop.
|
||||
fn isolated_art(doc: &Document, ids: &[NodeId]) -> (Vec<Arc<Node>>, Option<vectorcraft_geom::Rect>) {
|
||||
let keep: HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let layers = enclosed(doc, &keep, true);
|
||||
let symbols = doc.symbol_boxes();
|
||||
let bounds = layers.iter().filter_map(|l| vectorcraft_render::effect_bounds(&symbols, l)).reduce(|a, b| a.union(b));
|
||||
(layers, bounds)
|
||||
}
|
||||
|
||||
/// Objects `ids` of `doc` alone, each in the layers and groups that hold it ([`enclosed`], made
|
||||
/// visible), with one artboard named `name`: their [`export_crop`] (`None` when they have none).
|
||||
pub(crate) fn isolated(doc: &Document, ids: &[NodeId], name: &str) -> Option<(Document, vectorcraft_geom::Rect)> {
|
||||
let bounds = export_crop(doc, ids)?;
|
||||
let nodes: Vec<Arc<Node>> = ids.iter().filter_map(|id| doc.node(*id).cloned().map(Arc::new)).collect();
|
||||
let (layers, bounds) = isolated_art(doc, ids);
|
||||
let bounds = bounds?;
|
||||
let mut d = single_artboard(doc, bounds, name);
|
||||
let mut layer = Node::layer(d.alloc_id(), name, vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
*ch = nodes;
|
||||
}
|
||||
d.layers = vec![Arc::new(layer)];
|
||||
d.layers = layers;
|
||||
Some((d, bounds))
|
||||
}
|
||||
|
||||
@@ -259,7 +316,7 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable(C, str_param(p, "format"), path)?;
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (d, bounds) = selection(s, C)?;
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
// The encoder's warnings (options accepted but not applied, features approximated or left
|
||||
// out), as document.export reports them.
|
||||
let (bytes, warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
|
||||
|
||||
@@ -125,7 +125,7 @@ const BACKGROUND: FormatOption = FormatOption {
|
||||
name: "background",
|
||||
ty: "string",
|
||||
default: "\"transparent\"",
|
||||
description: "transparent, white, black or a colour such as \"#ff8800\" (JPEG: white when transparent)",
|
||||
description: "transparent, white, black or a colour such as \"#ff8800\" (JPEG: white when transparent); drawn under the finished art, so blend modes do not read it",
|
||||
};
|
||||
|
||||
const ANTI_ALIAS: FormatOption = FormatOption {
|
||||
|
||||
@@ -180,9 +180,11 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
|
||||
let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(doc, opts.profile != vectorcraft_svg::Profile::Tiny12);
|
||||
let doc = flat.as_ref().unwrap_or(doc);
|
||||
let mut enc = Encoded { warnings, ..Encoded::default() };
|
||||
// One renderer measures the art over every artboard: each 3D solid is built once.
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
for artboard in boards {
|
||||
// A chosen artboard's file holds the art over it (#550) and is named after it (#3544).
|
||||
let over = artboard.filter(|_| chosen).and_then(|b| doc.artboards.get(b)).map(|a| super::export::art_over(doc, a.rect));
|
||||
let over = artboard.filter(|_| chosen).and_then(|b| doc.artboards.get(b)).map(|a| super::export::art_over(doc, a.rect, &mut renderer));
|
||||
let file = ExportOptions { artboard, artboard_title: chosen, ..opts.clone() };
|
||||
let mut out = vectorcraft_svg::export_full(over.as_ref().unwrap_or(doc), &file, native.as_deref());
|
||||
let bytes = out.take_bytes();
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
//! Exports of objects alone (Export Selection, Export for Screens by selection or by layer, Asset
|
||||
//! Export, a CSS rule's picture and `selectedOnly`) draw the objects as the canvas draws them: with
|
||||
//! the clipping paths, opacity masks, effects, opacity and blend modes of the layers and groups that
|
||||
//! hold them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
fn id(v: &Value) -> u64 {
|
||||
v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}"))
|
||||
}
|
||||
|
||||
/// A red 300 pt square at (100, 100) clipped by a 200 pt circle at (150, 150): (square, clip group).
|
||||
fn clipped(s: &mut Session) -> (u64, u64) {
|
||||
let square = id(&run(s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300})));
|
||||
run(s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let circle = id(&run(s, "shape.ellipse", json!({"x": 150, "y": 150, "width": 200, "height": 200})));
|
||||
let group = id(&run(s, "object.clippingMask.make", json!({"ids": [circle, square]})));
|
||||
(square, group)
|
||||
}
|
||||
|
||||
fn b64(v: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap_or_else(|| panic!("no dataBase64 in {v}"))).unwrap()
|
||||
}
|
||||
|
||||
fn rect_of(v: &Value) -> Rect {
|
||||
let n = |i: usize| v[i].as_f64().unwrap_or_else(|| panic!("bad bounds {v}"));
|
||||
Rect::new(n(0), n(1), n(0) + n(2), n(1) + n(3))
|
||||
}
|
||||
|
||||
/// What the canvas draws of the whole document over `r`, at 1 px per point.
|
||||
fn canvas(s: &Session, r: Rect) -> image::RgbaImage {
|
||||
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, r, 1.0, false);
|
||||
image::load_from_memory(&img.to_png().unwrap()).unwrap().to_rgba8()
|
||||
}
|
||||
|
||||
/// The pixels of `png` that differ from `want` by more than 64 in a channel (anti-aliased edges
|
||||
/// differ by less), and every pixel when the sizes differ.
|
||||
fn differing(png: &[u8], want: &image::RgbaImage) -> usize {
|
||||
let got = image::load_from_memory(png).unwrap().to_rgba8();
|
||||
if got.dimensions() != want.dimensions() {
|
||||
return (want.width() * want.height()) as usize;
|
||||
}
|
||||
got.pixels().zip(want.pixels()).filter(|(a, b)| a.0.iter().zip(b.0.iter()).any(|(x, y)| x.abs_diff(*y) > 64)).count()
|
||||
}
|
||||
|
||||
/// Export Selection of what is selected, as a PNG, matches the canvas over its crop: fewer than 200
|
||||
/// pixels differ (anti-aliased edges), or 200 times `edges` with [`selection_png_matches_canvas_with`].
|
||||
fn selection_png_matches_canvas(s: &mut Session, want: Rect, what: &str) {
|
||||
selection_png_matches_canvas_with(s, want, what, 1);
|
||||
}
|
||||
|
||||
fn selection_png_matches_canvas_with(s: &mut Session, want: Rect, what: &str, edges: usize) {
|
||||
let r = run(s, "document.exportSelection", json!({"format": "png", "scale": 1}));
|
||||
let got = rect_of(&r["bounds"]);
|
||||
assert!((got.x0 - want.x0).abs() < 1.5 && (got.y0 - want.y0).abs() < 1.5, "{what}: crop {got:?}, want {want:?}");
|
||||
assert!((got.width() - want.width()).abs() < 3.0 && (got.height() - want.height()).abs() < 3.0, "{what}: crop {got:?}, want {want:?}");
|
||||
let off = differing(&b64(&r), &canvas(s, got));
|
||||
assert!(off < 200 * edges, "{what}: {off} pixels differ from the canvas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_selection_of_a_clipped_object_keeps_its_clip() {
|
||||
let mut s = session();
|
||||
let (square, _) = clipped(&mut s);
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "the square alone");
|
||||
let svg = b64(&run(&mut s, "document.exportSelection", json!({"format": "svg"})));
|
||||
let text = String::from_utf8_lossy(&svg);
|
||||
assert!(text.contains("<clipPath") && text.contains("clip-path"), "the SVG clips the square: {text}");
|
||||
// Opened again, the SVG draws what the canvas draws.
|
||||
let mut t = Session::new();
|
||||
run(&mut t, "document.open", json!({"name": "sel.svg", "dataBase64": vectorcraft_format::base64_encode(&svg)}));
|
||||
let board = t.doc().unwrap().doc.artboards[0].rect;
|
||||
let reopened = canvas(&t, board);
|
||||
let mut png = vec![];
|
||||
reopened.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let off = differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0)));
|
||||
assert!(off < 200, "the reopened SVG: {off} pixels differ from the canvas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_selection_of_a_clipping_layer_keeps_the_layer_clip() {
|
||||
let mut s = session();
|
||||
let layer = id(&run(&mut s, "layer.new", json!({"name": "L"})));
|
||||
run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "shape.ellipse", json!({"x": 150, "y": 150, "width": 200, "height": 200}));
|
||||
run(&mut s, "layer.clippingMask.toggle", json!({"id": layer}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "a clipping layer's objects");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_selection_keeps_the_opacity_effects_and_mask_of_the_groups_around_it() {
|
||||
let mut s = session();
|
||||
let (square, group) = clipped(&mut s);
|
||||
let other = id(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})));
|
||||
let outer = id(&run(&mut s, "object.group", json!({"ids": [group, other]})));
|
||||
run(&mut s, "transparency.set", json!({"ids": [outer], "opacity": 50}));
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "inside a group at 50%");
|
||||
// A drop shadow on the clip group reaches past its clip.
|
||||
run(&mut s, "effect.apply", json!({"ids": [group], "effect": "stylize.dropShadow"}));
|
||||
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
|
||||
let got = rect_of(&r["bounds"]);
|
||||
assert!(got.x1 > 352.0 && got.y1 > 352.0, "the crop takes in the clip group's shadow: {got:?}");
|
||||
assert!(differing(&b64(&r), &canvas(&s, got)) < 200, "with the shadow");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
// An opacity mask on the clip group.
|
||||
let mask = id(&run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300})));
|
||||
run(
|
||||
&mut s,
|
||||
"paint.setFill",
|
||||
json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]}}),
|
||||
);
|
||||
run(&mut s, "transparency.makeOpacityMask", json!({"ids": [mask, group]}));
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
|
||||
let got = rect_of(&r["bounds"]);
|
||||
assert!(differing(&b64(&r), &canvas(&s, got)) < 200, "with an opacity mask on the clip group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_selection_across_clip_groups_and_of_whole_ones() {
|
||||
let mut s = session();
|
||||
let (a, ga) = clipped(&mut s);
|
||||
let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 90, "height": 90})));
|
||||
let c = id(&run(&mut s, "shape.rectangle", json!({"x": 420, "y": 420, "width": 50, "height": 50})));
|
||||
let gb = id(&run(&mut s, "object.clippingMask.make", json!({"ids": [c, b]})));
|
||||
// A member of each clip group: each keeps its own clip.
|
||||
run(&mut s, "select.set", json!({"ids": [a, b]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 470.0, 470.0), "a member of each of two clip groups");
|
||||
// The clip groups themselves.
|
||||
run(&mut s, "select.set", json!({"ids": [ga, gb]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 470.0, 470.0), "two clip groups");
|
||||
// Nested clip groups: the inner group's member is clipped by both, cropped to the outer clip.
|
||||
let strip = id(&run(&mut s, "shape.rectangle", json!({"x": 0, "y": 200, "width": 500, "height": 100})));
|
||||
run(&mut s, "object.clippingMask.make", json!({"ids": [strip, ga]}));
|
||||
run(&mut s, "select.set", json!({"ids": [a]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(0.0, 200.0, 500.0, 300.0), "a member of nested clip groups");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_clipping_path_and_a_blend_object_export_on_their_own() {
|
||||
let mut s = session();
|
||||
let (square, group) = clipped(&mut s);
|
||||
let circle = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap()[0].id.0;
|
||||
assert_ne!(circle, square);
|
||||
// The clipping path alone: the clip group's other art stays out.
|
||||
run(&mut s, "select.set", json!({"ids": [circle]}));
|
||||
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
|
||||
let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8();
|
||||
assert_eq!(img.dimensions(), (200, 200), "cropped to the clipping path");
|
||||
assert!(!img.pixels().any(|p| p[0] > 200 && p[1] < 80 && p[3] > 0), "the clipped square is left out");
|
||||
// An object of a blend goes in on its own, without the blend's steps.
|
||||
let mut s = session();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let a = id(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 60})));
|
||||
let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 60, "height": 60})));
|
||||
run(&mut s, "select.set", json!({"ids": [a, b]}));
|
||||
run(&mut s, "object.blend.make", json!({}));
|
||||
run(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
|
||||
let got = rect_of(&r["bounds"]);
|
||||
assert!(got.x1 < 90.0 && got.y1 < 90.0, "the blend object's own bounds: {got:?}");
|
||||
let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8();
|
||||
let centre = img.get_pixel(img.width() / 2, img.height() / 2);
|
||||
assert!(centre[0] > 200 && centre[3] > 200, "the object is drawn: {centre:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_css_picture_of_a_clipped_object_is_clipped() {
|
||||
let mut s = session();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let star = id(&run(&mut s, "shape.star", json!({"cx": 250, "cy": 250, "radius1": 150, "radius2": 70, "points": 5})));
|
||||
let circle = id(&run(&mut s, "shape.ellipse", json!({"x": 200, "y": 200, "width": 100, "height": 100})));
|
||||
run(&mut s, "object.clippingMask.make", json!({"ids": [circle, star]}));
|
||||
let r = run(&mut s, "css.export", json!({"ids": [star], "rasterize": true, "unnamed": true}));
|
||||
let image = r["images"].as_array().and_then(|i| i.first()).unwrap_or_else(|| panic!("no picture: {r}"));
|
||||
let png = b64(image);
|
||||
let size = image::load_from_memory(&png).unwrap().to_rgba8().dimensions();
|
||||
assert_eq!(size, (100, 100), "the picture is cropped to the clip");
|
||||
assert!(differing(&png, &canvas(&s, Rect::new(200.0, 200.0, 300.0, 300.0))) < 100, "the picture matches the canvas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_asset_on_a_hidden_layer_is_drawn_clipped() {
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id.0;
|
||||
let (square, _) = clipped(&mut s);
|
||||
let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap();
|
||||
run(&mut s, "layer.setProps", json!({"id": layer, "visible": false}));
|
||||
let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]}));
|
||||
let img = image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8();
|
||||
assert_eq!(img.dimensions(), (200, 200), "cropped to the clip");
|
||||
let (centre, corner) = (img.get_pixel(100, 100), img.get_pixel(3, 3));
|
||||
assert!(centre[0] > 200 && centre[3] > 200, "the square is drawn: {centre:?}");
|
||||
assert_eq!(corner[3], 0, "outside the circle stays clear: {corner:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_for_screens_and_assets_by_selection_keep_the_clip() {
|
||||
let mut s = session();
|
||||
let (square, _) = clipped(&mut s);
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
let r = run(&mut s, "document.exportForScreens", json!({"selection": "one", "formats": [{"format": "png", "scale": 1}, {"format": "svg"}]}));
|
||||
let want = canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0));
|
||||
let png = r["files"].as_array().unwrap().iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(".png"))).unwrap();
|
||||
assert!(differing(&b64(png), &want) < 200, "Export for Screens by selection: {}", png["name"]);
|
||||
let svg = r["files"].as_array().unwrap().iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(".svg"))).unwrap();
|
||||
let text = String::from_utf8(b64(svg)).unwrap();
|
||||
assert!(text.contains("<clipPath"), "the SVG clips the square: {text}");
|
||||
let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap();
|
||||
let list = run(&mut s, "assets.list", json!({}));
|
||||
let bounds = rect_of(&list["assets"][0]["bounds"]);
|
||||
assert!((bounds.width() - 200.0).abs() < 3.0, "the asset's crop is its clip: {bounds:?}");
|
||||
let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]}));
|
||||
assert!(differing(&b64(&r["files"][0]), &want) < 200, "Asset Export: {}", r["files"][0]["name"]);
|
||||
}
|
||||
|
||||
/// The red pixels of `png`.
|
||||
fn red(png: &[u8]) -> usize {
|
||||
image::load_from_memory(png).unwrap().to_rgba8().pixels().filter(|p| p[0] > 200 && p[1] < 80 && p[3] > 200).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_on_a_non_printing_layer_exports_to_pdf() {
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id.0;
|
||||
let (square, _) = clipped(&mut s);
|
||||
run(&mut s, "layer.setProps", json!({"id": layer, "printable": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
let pdf = b64(&run(&mut s, "document.exportSelection", json!({"format": "pdf", "createLayers": false, "preserveEditing": false})));
|
||||
let mut t = Session::new();
|
||||
run(&mut t, "document.open", json!({"name": "sel.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)}));
|
||||
let page = t.doc().unwrap().doc.artboards[0].rect;
|
||||
let mut png = vec![];
|
||||
canvas(&t, page).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
assert!(red(&png) > 20_000, "the PDF draws the square: {} red pixels", red(&png));
|
||||
assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 300, "the PDF draws what the canvas draws");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_for_screens_of_layers_draws_them_as_the_canvas_does() {
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id.0;
|
||||
clipped(&mut s);
|
||||
// A layer at 50% opacity: its art is drawn at 50%.
|
||||
run(&mut s, "transparency.set", json!({"ids": [layer], "opacity": 50}));
|
||||
let r = run(&mut s, "document.exportForScreens", json!({"layers": [layer], "formats": [{"format": "png", "scale": 1}]}));
|
||||
let png = b64(&r["files"][0]);
|
||||
assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 200, "the layer's opacity applies");
|
||||
// A template layer's art is still drawn.
|
||||
run(&mut s, "transparency.set", json!({"ids": [layer], "opacity": 100}));
|
||||
run(&mut s, "layer.setProps", json!({"id": layer, "template": true}));
|
||||
let r = run(&mut s, "document.exportForScreens", json!({"layers": [layer], "formats": [{"format": "png", "scale": 1}, {"format": "svg"}]}));
|
||||
let files = r["files"].as_array().unwrap();
|
||||
let file = |ext: &str| b64(files.iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(ext))).unwrap());
|
||||
assert!(red(&file(".png")) > 20_000, "the template layer's art is drawn: {} red pixels", red(&file(".png")));
|
||||
assert!(String::from_utf8(file(".svg")).unwrap().contains("<clipPath"), "the SVG holds the clipped art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_export_of_the_selection_leaves_out_a_type_clipping_path() {
|
||||
let mut s = session();
|
||||
// The front object, the type "Clip", becomes the clipping path.
|
||||
let inner = id(&run(&mut s, "text.create", json!({"x": 100, "y": 110, "text": "Inner"})));
|
||||
let clip = id(&run(&mut s, "text.create", json!({"x": 100, "y": 100, "text": "Clip"})));
|
||||
run(&mut s, "object.clippingMask.make", json!({"ids": [clip, inner]}));
|
||||
let mut first = None;
|
||||
s.doc().unwrap().doc.layers[0].walk(&mut |n| {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. }) {
|
||||
first = n.children().and_then(|c| c.first()).map(|c| c.id.0);
|
||||
}
|
||||
});
|
||||
assert_eq!(first, Some(clip), "the type is the clipping path");
|
||||
run(&mut s, "select.set", json!({"ids": [inner]}));
|
||||
let txt = b64(&run(&mut s, "document.export", json!({"format": "txt", "selectionOnly": true})));
|
||||
assert_eq!(String::from_utf8(txt).unwrap(), "Inner\n");
|
||||
let txt = b64(&run(&mut s, "document.exportSelection", json!({"format": "txt"})));
|
||||
assert_eq!(String::from_utf8(txt).unwrap(), "Inner\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_clip_groups_symbols_and_large_selections_keep_their_clips() {
|
||||
// Five clip groups inside each other, each clip a little smaller.
|
||||
let mut s = session();
|
||||
let (square, mut group) = clipped(&mut s);
|
||||
for i in 1..5 {
|
||||
let inset = 10.0 * f64::from(i);
|
||||
let clip = id(&run(&mut s, "shape.rectangle", json!({"x": 150.0 + inset, "y": 150.0 + inset, "width": 200.0 - 2.0 * inset, "height": 400})));
|
||||
group = id(&run(&mut s, "object.clippingMask.make", json!({"ids": [clip, group]})));
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(190.0, 190.0, 310.0, 590.0), "a member of five nested clip groups");
|
||||
|
||||
// A symbol instance in a clip group.
|
||||
let mut s = session();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let art = id(&run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300})));
|
||||
run(&mut s, "select.set", json!({"ids": [art]}));
|
||||
let instance = id(&run(&mut s, "symbol.new", json!({"name": "Red"})));
|
||||
let circle = id(&run(&mut s, "shape.ellipse", json!({"x": 150, "y": 150, "width": 200, "height": 200})));
|
||||
run(&mut s, "object.clippingMask.make", json!({"ids": [circle, instance]}));
|
||||
run(&mut s, "select.set", json!({"ids": [instance]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "a symbol instance in a clip group");
|
||||
|
||||
// 200 clip groups, a member of each selected.
|
||||
let mut s = session();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let mut members = vec![];
|
||||
for i in 0..200 {
|
||||
let (x, y) = (f64::from(i % 20) * 25.0, f64::from(i / 20) * 25.0);
|
||||
let m = id(&run(&mut s, "shape.rectangle", json!({"x": x, "y": y, "width": 20, "height": 20})));
|
||||
let c = id(&run(&mut s, "shape.ellipse", json!({"x": x, "y": y, "width": 20, "height": 20})));
|
||||
run(&mut s, "object.clippingMask.make", json!({"ids": [c, m]}));
|
||||
members.push(m);
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": members}));
|
||||
// The circles' anti-aliased edges differ by up to about 30 pixels each; without their clips the
|
||||
// squares' corners differ by 86 pixels each.
|
||||
selection_png_matches_canvas_with(&mut s, Rect::new(0.0, 0.0, 495.0, 245.0), "members of 200 clip groups", 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_asset_in_a_hidden_or_locked_clip_group_is_drawn_clipped() {
|
||||
for change in ["object.hide", "object.lock"] {
|
||||
let mut s = session();
|
||||
let (square, group) = clipped(&mut s);
|
||||
let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap();
|
||||
let want = canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0));
|
||||
run(&mut s, "select.set", json!({"ids": [group]}));
|
||||
run(&mut s, change, json!({}));
|
||||
let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]}));
|
||||
assert!(differing(&b64(&r["files"][0]), &want) < 200, "{change}: the asset draws as the canvas did");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_only_keeps_holders_and_takes_a_blend_object_alone() {
|
||||
let mut s = session();
|
||||
let (square, _) = clipped(&mut s);
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
let r = run(&mut s, "document.export", json!({"format": "png", "scale": 1, "selectedOnly": true}));
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
assert!(differing(&b64(&r), &canvas(&s, board)) < 200, "selectedOnly keeps the clip");
|
||||
// An object of a blend is written on its own.
|
||||
let mut s = session();
|
||||
let a = id(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 60})));
|
||||
let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 60, "height": 60})));
|
||||
run(&mut s, "select.set", json!({"ids": [a, b]}));
|
||||
run(&mut s, "object.blend.make", json!({}));
|
||||
run(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let svg = run(&mut s, "document.serialize", json!({"format": "svg", "selectedOnly": true}))["text"].as_str().unwrap().to_string();
|
||||
let mut t = Session::new();
|
||||
run(&mut t, "document.open", json!({"name": "a.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())}));
|
||||
let mut paths = 0;
|
||||
for l in &t.doc().unwrap().doc.layers {
|
||||
l.walk(&mut |n| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })));
|
||||
}
|
||||
assert_eq!(paths, 1, "the blend object alone, without the steps: {svg}");
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
//! cut into atomic regions: the faces of the planar arrangement of every fill, outlined stroke and
|
||||
//! clipping path in them ([`po::regions`]). The same paints cover each whole region, so its colour
|
||||
//! is exact: those paints composited as the renderer composites them ([`Composer`], blend modes by
|
||||
//! [`composite`]), over white (or over nothing with Preserve Alpha); in CMYK documents their inks
|
||||
//! [`composite`]), with white under the finished art (or nothing with Preserve Alpha); in CMYK documents their inks
|
||||
//! composite, plane by plane ([`cmyk_planes`]), and the colour is CMYK. Each region becomes a path
|
||||
//! filled with that flat colour. Where gradients, patterns, images, opacity masks or raster
|
||||
//! effects reach there is no single colour: those regions are rendered into one image per group,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::analysis::{Scratch, outlined_text, overlapping, reach};
|
||||
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, WHITE};
|
||||
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
|
||||
use super::options::FlattenOptions;
|
||||
use super::{
|
||||
Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, effects, isolated_doc, outline_strokes_under, planes_cmyk, po, separate,
|
||||
shape_node, shapes, unique_key,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, outline_strokes_under, planes_cmyk, po,
|
||||
separate, shape_node, shapes, unique_key,
|
||||
};
|
||||
|
||||
// ---------- plan ----------
|
||||
@@ -235,18 +235,14 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool
|
||||
if alone[3] < 0.5 / 255.0 {
|
||||
return None;
|
||||
}
|
||||
let start = if o.preserve_alpha { CLEAR } else { WHITE };
|
||||
let px = if o.preserve_alpha {
|
||||
alone
|
||||
} else {
|
||||
c.top = None;
|
||||
c.eval(elems, start)
|
||||
};
|
||||
// The white goes under the finished art, as under the renderer's: blend modes read only the art.
|
||||
let on_page = |p: Px| if o.preserve_alpha { p } else { composite(BlendMode::Normal, WHITE, p) };
|
||||
let px = on_page(alone);
|
||||
let rgb = [px[0], px[1], px[2]];
|
||||
// The K plane composites the same way.
|
||||
let k = cmyk.then(|| {
|
||||
c.plane = 1;
|
||||
c.eval(elems, start)[0]
|
||||
on_page(c.eval(elems, CLEAR))[0]
|
||||
});
|
||||
// A paint showing as it is keeps its colour (spot, process, swatch) and overprint.
|
||||
let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3);
|
||||
@@ -266,7 +262,7 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool
|
||||
}
|
||||
|
||||
/// `art` rendered over `rect` at `ppi`: over white with the white the art doesn't cover taken out
|
||||
/// again (so blend modes see the white page), or over nothing with Preserve Alpha. The image and
|
||||
/// again, or over nothing with Preserve Alpha. The image and
|
||||
/// its `clip` reach a pixel further. An opaque image in a CMYK document holds the art's ink
|
||||
/// amounts (a CMYK TIFF), so its CMYK colours keep their numbers (#2160); other images are PNGs.
|
||||
/// Fails when the image can't be encoded.
|
||||
|
||||
@@ -43,6 +43,7 @@ fn cell(c: &str) -> Cell {
|
||||
}
|
||||
|
||||
pub(super) fn parse_csv(csv: &str) -> (Vec<String>, Vec<String>, Vec<Vec<Option<f64>>>) {
|
||||
let csv = csv.strip_prefix('\u{feff}').unwrap_or(csv);
|
||||
// Records end at line breaks outside quotes; a record is tab-separated if it has a tab outside quotes.
|
||||
let rows: Vec<Vec<Cell>> = split_unquoted(csv, '\n')
|
||||
.into_iter()
|
||||
@@ -169,7 +170,9 @@ pub(super) fn fmt_value(v: f64) -> String {
|
||||
// `{:.0}` prints its exact digits.
|
||||
if v.abs() < 9e18 { format!("{}", v.round() as i64) } else { format!("{v:.0}") }
|
||||
} else {
|
||||
format!("{:.2}", v).trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
let s = format!("{:.2}", v).trim_end_matches('0').trim_end_matches('.').to_string();
|
||||
// A tiny negative rounds to "-0.00"; show it as plain zero like -0.0.
|
||||
if s == "-0" { "0".to_string() } else { s }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,13 @@ fn fmt_value_does_not_saturate_beyond_i64() {
|
||||
assert_eq!(super::fmt_value(2.5), "2.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fmt_value_tiny_negative_is_zero() {
|
||||
assert_eq!(super::fmt_value(-0.004), "0");
|
||||
assert_eq!(super::fmt_value(-0.0049), "0");
|
||||
assert_eq!(super::fmt_value(-0.006), "-0.01");
|
||||
}
|
||||
|
||||
fn graph(s: &mut Session, ty: &str) -> NodeId {
|
||||
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
|
||||
NodeId(
|
||||
@@ -4198,3 +4205,8 @@ fn character_formats_are_kept_and_bigger_labels_space_out() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_leading_byte_order_mark_is_ignored() {
|
||||
assert_eq!(super::parse_csv("\u{feff}1,2\n3,4"), super::parse_csv("1,2\n3,4"));
|
||||
}
|
||||
@@ -1167,9 +1167,11 @@ fn artboard_fit_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::panelcmds::refuse_locked(d, &indices)?;
|
||||
}
|
||||
let mut fits = vec![];
|
||||
// One renderer measures every artboard: each 3D solid is built once.
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
for i in unlocked {
|
||||
let was = d.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
|
||||
if let Some(b) = vectorcraft_render::encode::art_bounds_on(d, was) {
|
||||
if let Some(b) = renderer.art_bounds_on(d, was) {
|
||||
// At least 1 pt a side, as `rect_from` makes Artboard Options' sizes.
|
||||
fits.push((i, was, Rect::new(b.x0, b.y0, b.x0 + b.width().max(1.0), b.y0 + b.height().max(1.0))));
|
||||
}
|
||||
|
||||
@@ -203,10 +203,11 @@ pub(crate) fn whole_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a command's implementation without the enablement check or journaling.
|
||||
/// Run a command's implementation without the enablement check or journaling. A command with a
|
||||
/// parameter schema runs with its params checked ([`super::run_checked`]).
|
||||
pub(crate) fn run_raw(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
|
||||
let c = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
super::run_spec(s, c, p)
|
||||
super::run_checked(s, c, p)
|
||||
}
|
||||
|
||||
/// Merge the undo entries pushed since the history had `from` entries into one labelled step.
|
||||
|
||||
@@ -217,13 +217,15 @@ impl Session {
|
||||
/// After a command changed the selection, with New Art Has Basic Appearance on: the fill and
|
||||
/// stroke proxies and the weight take what the selection shows in them, so new art looks like
|
||||
/// it. A paint the selected objects don't share (a "?" proxy) stays as it was, and art without
|
||||
/// paint (a placed image, whose None would make new art invisible) changes nothing. The
|
||||
/// template is left alone, and without a stroke to show the weight stays too.
|
||||
/// paint (a placed image that isn't colorized, whose None would make new art invisible) changes
|
||||
/// nothing. The template is left alone, and without a stroke to show the weight stays too.
|
||||
pub(crate) fn load_selection_paints(&mut self) {
|
||||
if !self.prefs.new_art_basic {
|
||||
return;
|
||||
}
|
||||
let has_paint = self.proxy_source(false).is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty());
|
||||
let has_paint = self
|
||||
.proxy_source(false)
|
||||
.is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some());
|
||||
if !has_paint {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -6,16 +6,23 @@ use super::{
|
||||
use vectorcraft_doc::{NodeKind, TextKind};
|
||||
|
||||
impl Session {
|
||||
/// The bounds of `ids` the Transform panel, the bounding box, Align and Distribute measure:
|
||||
/// with Use Preview Bounds on, visual bounds as drawn (strokes and geometry effects included,
|
||||
/// see [`effects::preview`]), else geometric bounds.
|
||||
/// The bounds of `ids` the Transform panel and the bounding box measure: with Use Preview
|
||||
/// Bounds on, visual bounds as drawn (strokes and geometry effects included, see
|
||||
/// [`effects::preview`]), else geometric bounds; with Measure Type by Glyph Bounds on, point
|
||||
/// type by the ink of its glyphs ([`Session::bounds_measure`]).
|
||||
pub fn transform_bounds(&self, ids: &[NodeId]) -> Option<Rect> {
|
||||
effects::preview::bounds_of(&self.doc().ok()?.doc, ids, self.prefs.use_preview_bounds)
|
||||
effects::preview::bounds_of_with(&self.doc().ok()?.doc, ids, self.bounds_measure())
|
||||
}
|
||||
/// [`Session::transform_bounds`] square to the objects' own angle (their rotated bounding
|
||||
/// box, see [`Document::oriented_bounds`]).
|
||||
pub fn transform_box(&self, ids: &[NodeId]) -> Option<OrientedBox> {
|
||||
effects::preview::oriented_bounds(&self.doc().ok()?.doc, ids, self.prefs.use_preview_bounds)
|
||||
effects::preview::oriented_bounds_with(&self.doc().ok()?.doc, ids, self.bounds_measure())
|
||||
}
|
||||
/// How the bounding box, the Transform panel and `object.setBounds` measure objects: Use
|
||||
/// Preview Bounds, and point type by its glyphs with Measure Type by Glyph Bounds
|
||||
/// (`typeGlyphBounds`).
|
||||
pub fn bounds_measure(&self) -> effects::preview::Measure {
|
||||
effects::preview::Measure { preview: self.prefs.use_preview_bounds, glyphs: self.prefs.type_glyph_bounds }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,24 +59,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
let st = s.doc()?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
|
||||
check_switches(p, &["proportional"], "object.setBounds")?;
|
||||
let how = s.bounds_measure();
|
||||
if anchors
|
||||
&& transforms_objects(p)
|
||||
&& !bool_or(p, "copy", false)
|
||||
&& let Some(b) = effects::preview::anchor_bounds(&st.selection, &st.doc, s.prefs.use_preview_bounds)
|
||||
&& let Some(b) = effects::preview::anchor_bounds_with(&st.selection, &st.doc, how)
|
||||
{
|
||||
return Ok(Bounds::Anchors(ids, b));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
// Sizes are measured square to the bounding box, which a rotation turns with the objects:
|
||||
// the math below runs in its frame.
|
||||
let frame = d.oriented_bounds(&ids, false).ok_or_else(|| EngineError::Other("no bounds".into()))?;
|
||||
// the math below runs in its frame. With Measure Type by Glyph Bounds, point type is measured
|
||||
// by its glyphs' ink, which a transform of the type moves and scales with it.
|
||||
let geometric = effects::preview::Measure { preview: false, ..how };
|
||||
let frame = effects::preview::oriented_bounds_with(d, &ids, geometric).ok_or_else(|| EngineError::Other("no bounds".into()))?;
|
||||
let g = frame.rect;
|
||||
let symbols = d.symbol_boxes();
|
||||
let by_glyphs = how.glyphs && ids.iter().filter_map(|id| d.node(*id)).any(|n| effects::preview::by_glyphs(&symbols, n, how));
|
||||
// With Use Preview Bounds the values measure the visual box as drawn, whose margins around the
|
||||
// geometric box (left, top, right, bottom) scale with the strokes or stay. The margins of
|
||||
// `vs`, the visual box without the strokes in symbols' art, scale; those strokes keep their
|
||||
// weight when an instance scales, so the rest of the margins stay.
|
||||
// weight when an instance scales, so the rest of the margins stay. Type measured by its glyphs
|
||||
// is measured as drawn after each scale tried instead (below).
|
||||
let (v, vs) = if s.prefs.use_preview_bounds {
|
||||
(effects::preview::oriented_bounds(d, &ids, true).map_or(g, |b| b.rect), scaling_box(d, &ids, &frame).unwrap_or(g))
|
||||
let v = effects::preview::oriented_bounds_with(d, &ids, how).map_or(g, |b| b.rect);
|
||||
(v, if by_glyphs { v } else { scaling_box(d, &ids, &frame).unwrap_or(g) })
|
||||
} else {
|
||||
(g, g)
|
||||
};
|
||||
@@ -125,22 +132,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
// The scales and the point above can miss the size or the reference point when the margins of
|
||||
// the objects differ, the members of groups and the objects in symbols' art included, and with
|
||||
// strokes that scale, when the sizes are out of proportion. The objects are then measured one
|
||||
// by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects are
|
||||
// measured as drawn after each scale tried instead ([`refit_drawn`]).
|
||||
let symbols = d.symbol_boxes();
|
||||
let drawn = || ids.iter().filter_map(|id| d.node(*id)).any(|n| effects::preview::draws_geometry(&symbols, n));
|
||||
// by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects,
|
||||
// objects with a butt-capped stroke along a segment at a slant, whose margins change with the
|
||||
// segment's direction, and type measured by its glyphs, are measured as drawn after each scale
|
||||
// tried instead ([`refit_drawn`]).
|
||||
let to_local = frame.to_doc().inverse();
|
||||
let drawn = || {
|
||||
by_glyphs
|
||||
|| ids
|
||||
.iter()
|
||||
.filter_map(|id| d.node(*id))
|
||||
.any(|n| effects::preview::draws_geometry(&symbols, n) || n.has_slanted_butt_stroke(&symbols, to_local))
|
||||
};
|
||||
// Without Use Preview Bounds the box has no margins (`v`, `vs` and `g` are one box, glyph ink
|
||||
// included), so the scales above are exact and nothing is refitted.
|
||||
let solved = if !(s.prefs.use_preview_bounds && w >= 0.0 && h >= 0.0) {
|
||||
None
|
||||
} else if transforms_objects(p) && !bool_or(p, "typeAreas", false) && drawn() {
|
||||
let options = scaling_options(s, p);
|
||||
let to_local = frame.to_doc().inverse();
|
||||
let measure = |sx: f64, sy: f64| {
|
||||
let xf = frame.conjugate(about(rp, Affine::scale_non_uniform(sx, sy)));
|
||||
let sc = if Scaling::factor(xf).is_some() { options } else { Scaling::default() };
|
||||
ids.iter().filter_map(|id| d.node(*id)).fold(None, |acc, n| {
|
||||
let mut n = n.clone();
|
||||
n.transform(xf, sc);
|
||||
vectorcraft_geom::union_opt(acc, effects::preview::bounds_in(&symbols, &n, to_local))
|
||||
vectorcraft_geom::union_opt(acc, effects::preview::bounds_in_with(&symbols, &n, to_local, how))
|
||||
})
|
||||
};
|
||||
// The scales above keep the effects' reach as a margin that stays, and give 0 for a size
|
||||
|
||||
@@ -287,7 +287,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Bounds",
|
||||
[],
|
||||
None,
|
||||
"{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
"{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
has_selection,
|
||||
set_bounds
|
||||
),
|
||||
|
||||
@@ -12,7 +12,7 @@ fn origin_of(s: &Session, p: &Value, ids: &[NodeId]) -> Result<Point> {
|
||||
// Direct-selected anchors transform alone (see [`apply_transform`]), about their own centre.
|
||||
let st = s.doc()?;
|
||||
if !bool_or(p, "copy", false)
|
||||
&& let Some(b) = effects::preview::anchor_bounds(&st.selection, &st.doc, s.prefs.use_preview_bounds)
|
||||
&& let Some(b) = effects::preview::anchor_bounds_with(&st.selection, &st.doc, s.bounds_measure())
|
||||
{
|
||||
return Ok(b.center());
|
||||
}
|
||||
|
||||
@@ -21,7 +21,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|freeform, method?: classic|perceptual (as paint.editGradient; default classic), 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, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; 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), dither?: bool (linear and radial 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), ids?|id?, 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 or radial `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 colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters 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); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, a solid color or `none` changes that object for this instance only, and a gradient or pattern is refused → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{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|freeform, method?: classic|perceptual (as paint.editGradient; default classic), 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, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; 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), dither?: bool (linear and radial 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), ids?|id?, 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 or radial `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 colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters 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); 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) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke",
|
||||
[],
|
||||
None,
|
||||
"{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, a solid color or `none` changes that object for this instance only, and a gradient or pattern is refused",
|
||||
"{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern)",
|
||||
has_doc,
|
||||
|s, p| { set_paint(s, p, false) }
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transparency",
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
transparency
|
||||
),
|
||||
@@ -487,12 +487,9 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
s.remember_paint(&paint);
|
||||
return Ok(json!({"objects": ids.len()}));
|
||||
}
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection: a solid color or
|
||||
// none changes that object for this instance only, and anything else is refused.
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection: that object's
|
||||
// fill or stroke changes for this instance only (solid, none, gradient or pattern).
|
||||
if let Some((id, path)) = selected_part_target(s, p, cmd)? {
|
||||
if !part_takes(&paint) {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
super::brushsym::edit_part(s, id, &path, if fill { "Fill Color" } else { "Stroke Color" }, |o| {
|
||||
if fill {
|
||||
o.fill = Some(paint.clone());
|
||||
@@ -620,8 +617,9 @@ fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result<Option<(Nod
|
||||
Ok(part)
|
||||
}
|
||||
|
||||
/// Can an object of a dynamic symbol instance's art selected with Direct Selection take `paint`? A
|
||||
/// solid color or none can; a gradient or pattern cannot.
|
||||
/// Can Invert / Complement recolour `paint` on an object of a dynamic symbol instance's art selected
|
||||
/// with Direct Selection? A solid color or none can; a gradient or pattern cannot (one override
|
||||
/// holds one paint, and those commands recolour solid colours only).
|
||||
pub(crate) fn part_takes(paint: &Paint) -> bool {
|
||||
matches!(paint, Paint::Solid { .. } | Paint::None)
|
||||
}
|
||||
@@ -962,6 +960,46 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
|
||||
fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "transparency.set";
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection: opacity and
|
||||
// blend change that object for this instance only. Isolate, knockout and Appearance `item` /
|
||||
// `target` stay refused here (they act on the instance or a stack row).
|
||||
if p.get("ids").is_none()
|
||||
&& p.get("id").is_none()
|
||||
&& p.get("item").is_none()
|
||||
&& let Some((id, path)) = super::brushsym::selected_part(s)?
|
||||
{
|
||||
for key in ["isolate", "knockout", "knockoutShape", "aligned", "target"] {
|
||||
if p.get(key).is_some() {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
}
|
||||
if p.get("opacity").is_none() && p.get("blend").is_none() {
|
||||
return Err(bad(C, "give opacity or blend"));
|
||||
}
|
||||
check_numbers(p, &["opacity"], C)?;
|
||||
let opacity = match p.get("opacity") {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
Some(v) => Some(Some(v.as_f64().map(super::opacitymask::percent).ok_or_else(|| bad(C, "opacity must be a number"))?)),
|
||||
};
|
||||
let blend = match p.get("blend") {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
Some(b) => {
|
||||
let name = b.as_str().ok_or_else(|| bad(C, "blend must be a mode name"))?;
|
||||
Some(Some(BlendMode::parse(name).ok_or_else(|| bad(C, format!("unknown blend mode {b}")))?))
|
||||
}
|
||||
};
|
||||
super::brushsym::edit_part(s, id, &path, "Transparency", |o| {
|
||||
if let Some(op) = opacity {
|
||||
o.opacity = op;
|
||||
}
|
||||
if let Some(b) = blend {
|
||||
o.blend = b;
|
||||
}
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
super::opacitymask::refuse_symbol_part_unnamed(s, p)?;
|
||||
let ids = super::opacitymask::transparency_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
|
||||
@@ -18,13 +18,24 @@
|
||||
//! `effect.setParams` answer a key the effect doesn't take, or a value of another type than its
|
||||
//! default, with a parameter error ([`check_effect_params`]).
|
||||
//!
|
||||
//! A command with a parameter schema (`CommandSpec::schema`) is also checked against the schema
|
||||
//! before it runs ([`crate::schemas::check`]): the schema refuses a value of the wrong type or out
|
||||
//! of range, a missing required parameter and an unknown key at any depth, and fills in declared
|
||||
//! defaults, so the command runs with the filled-in params. The check here still runs first for
|
||||
//! such a command, so a misspelled top-level key gets the same error from either, and a
|
||||
//! `command.batch` or an `action.batch` checks each step's schema before the first step runs. The
|
||||
//! keys of commands without a schema, and the options of exports and effects, are checked only as
|
||||
//! this module describes.
|
||||
//!
|
||||
//! Saved steps play through [`Session::replay`] instead: a journal or an action recorded by an older
|
||||
//! version, with a key a command no longer reads or an effect parameter it no longer takes, still
|
||||
//! plays. Even there, an effect's `color` that the effect can't read and a Levels or Curves
|
||||
//! plays. A key a schema doesn't name passes there too, and the values of the parameters it names
|
||||
//! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves
|
||||
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
|
||||
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_apischema::shown_key;
|
||||
|
||||
use super::{bad, command_specs, find_command};
|
||||
use crate::Result;
|
||||
@@ -239,9 +250,11 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
|
||||
/// The parameter error of command `id` for `key`, which isn't one of `keys`: with the nearest of
|
||||
/// them, or all of them.
|
||||
pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError {
|
||||
let near = nearest(key, keys);
|
||||
let key = shown_key(key);
|
||||
bad(
|
||||
id,
|
||||
match nearest(key, keys) {
|
||||
match near {
|
||||
Some(near) => format!("unknown parameter `{key}`; did you mean `{near}`?"),
|
||||
None if keys.is_empty() => format!("unknown parameter `{key}`; the command takes no parameters"),
|
||||
None => format!("unknown parameter `{key}`; the command takes: {}", keys.join(", ")),
|
||||
@@ -522,6 +535,7 @@ fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Val
|
||||
Some(near) => format!("did you mean `{within}{near}`?"),
|
||||
None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")),
|
||||
};
|
||||
let key = shown_key(key);
|
||||
return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}")));
|
||||
}
|
||||
(Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?,
|
||||
@@ -538,9 +552,11 @@ fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Val
|
||||
fn check_option_keys(id: &str, within: &str, given: &serde_json::Map<String, Value>, keys: &[&str], why_not: &str, trees: &Value) -> Result<()> {
|
||||
for (key, value) in given {
|
||||
if !keys.contains(&key.as_str()) {
|
||||
let near = nearest(key, keys);
|
||||
let key = shown_key(key);
|
||||
return Err(bad(
|
||||
id,
|
||||
match nearest(key, keys) {
|
||||
match near {
|
||||
Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"),
|
||||
None => format!("unknown parameter `{within}{key}`; {why_not}"),
|
||||
},
|
||||
@@ -647,6 +663,7 @@ fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map<String, Value>)
|
||||
Some(near) => format!("did you mean `{within}settings.{near}`?"),
|
||||
None => format!("`{within}settings` takes: {}", formats.join(", ")),
|
||||
};
|
||||
let format = shown_key(format);
|
||||
return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}")));
|
||||
}
|
||||
if let Value::Object(options) = options {
|
||||
@@ -758,10 +775,13 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
check_keys(id, spec.params, params)?;
|
||||
if in_batch {
|
||||
crate::schemas::check(spec, params, false)?;
|
||||
}
|
||||
if matches!(id, "command.batch" | "action.batch") && !in_batch {
|
||||
for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() {
|
||||
if let (Some(step_id), Some(step_params)) = (step.get("command").and_then(Value::as_str), step.get("params")) {
|
||||
check_params_in(step_id, step_params, true)?;
|
||||
if let Some(step_id) = step.get("command").and_then(Value::as_str) {
|
||||
check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -778,8 +798,8 @@ pub(crate) fn nearest_command(id: &str) -> Option<&'static str> {
|
||||
/// The error for `id`, which names no command: with the nearest command id, when one is near.
|
||||
pub(crate) fn unknown_command(id: &str) -> crate::EngineError {
|
||||
match nearest_command(id) {
|
||||
Some(near) => crate::EngineError::UnknownCommandNear(id.to_string(), near.to_string()),
|
||||
None => crate::EngineError::UnknownCommand(id.to_string()),
|
||||
Some(near) => crate::EngineError::UnknownCommandNear(shown_key(id), near.to_string()),
|
||||
None => crate::EngineError::UnknownCommand(shown_key(id)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1329,7 +1329,7 @@ pub(super) fn replace_deleted_pieces(d: &mut Document, beside: &mut Beside, orig
|
||||
|
||||
/// Remove anchors and their incident segments, keeping each surviving stretch as an open path.
|
||||
/// Only a closed path can have a surviving stretch that wraps past the last anchor.
|
||||
fn without_anchors(sp: SubPath, removed: &BTreeSet<usize>) -> Vec<SubPath> {
|
||||
pub(super) fn without_anchors(sp: SubPath, removed: &BTreeSet<usize>) -> Vec<SubPath> {
|
||||
let n = sp.anchors.len();
|
||||
let gone: BTreeSet<usize> = removed.iter().copied().filter(|&i| i < n).collect();
|
||||
if gone.is_empty() {
|
||||
|
||||
+116
-35
@@ -11,15 +11,18 @@
|
||||
//! `document.open` reads (`fileio::plugin_formats`).
|
||||
//!
|
||||
//! A filter may ask for a heavy budget (`Budget::Heavy`: minutes rather than a minute, for routing,
|
||||
//! packing or simulation). It installs only once the user agrees (`plugin.install {allowHeavy}`),
|
||||
//! which loading a folder doesn't ask, so folders skip it; the app runs it in the background with
|
||||
//! Cancel ([`FilterRun`]).
|
||||
//! packing or simulation). It installs only once a person agrees, which loading a folder doesn't
|
||||
//! ask, so folders skip it; the app runs it in the background with Cancel ([`FilterRun`]).
|
||||
//!
|
||||
//! A plug-in whose manifest lists permissions installs once the user grants them
|
||||
//! (`plugin.install {grant}`, recorded with the module's hash and kept in the plug-in store), and
|
||||
//! a filter does only what they allow: without `doc.read` it is given no objects, without
|
||||
//! `doc.write` an output that changes the document is refused, and without `state` it neither
|
||||
//! reads nor writes the data it keeps with the document.
|
||||
//! A plug-in whose manifest lists permissions installs once a person grants them (recorded with
|
||||
//! the module's hash and kept in the plug-in store), and a filter does only what they allow:
|
||||
//! without `doc.read` it is given no objects, without `doc.write` an output that changes the
|
||||
//! document is refused, and without `state` it neither reads nor writes the data it keeps with
|
||||
//! the document.
|
||||
//!
|
||||
//! `plugin.install {grant, allowHeavy}` takes effect only with an [`InstallApproval`], which no
|
||||
//! command can set, or in a session started to accept them from requests
|
||||
//! ([`Session::allow_plugin_grants_from_requests`]).
|
||||
//!
|
||||
//! A filter or a live effect may add menu commands of its own (its manifest's `commands`). Each
|
||||
//! is the command `plugin.<plug-in id>.<command id>` while the plug-in is installed
|
||||
@@ -41,7 +44,6 @@
|
||||
//! images or symbol instances of those kinds, to read only: its output must return each of them
|
||||
//! unchanged ([`objects::decode_output_with`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -134,9 +136,9 @@ pub struct FilterRun {
|
||||
params: Vec<u8>,
|
||||
/// The objects the plug-in is given, and the container new objects go in.
|
||||
inputs: Vec<NodeId>,
|
||||
/// The type, images and symbol instances among them (a filter that asks for them), as given:
|
||||
/// its output must return each one unchanged.
|
||||
read_only: HashMap<NodeId, Value>,
|
||||
/// The type, images and symbol instances among them (a filter that asks for them): its output
|
||||
/// must return each one as `input` gives it. These are their places in `input`.
|
||||
read_only: objects::ReadOnlySpans,
|
||||
parent: Option<NodeId>,
|
||||
/// The document it was made from, and that document's revision then.
|
||||
document: (u64, u64),
|
||||
@@ -270,7 +272,7 @@ impl FilterRun {
|
||||
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
|
||||
let m = self.plugin.manifest();
|
||||
let may = m.permissions();
|
||||
let out = objects::decode_output_with(output, &self.read_only).map_err(err)?;
|
||||
let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?;
|
||||
if out.document_data.is_some() && !may.contains(&Permission::State) {
|
||||
return Err(not_granted(&m.name, Permission::State));
|
||||
}
|
||||
@@ -431,6 +433,7 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
|
||||
enabled: has_doc,
|
||||
run: unrouted,
|
||||
journal: true,
|
||||
schema: None,
|
||||
}));
|
||||
made.push(spec);
|
||||
spec
|
||||
@@ -556,6 +559,45 @@ fn grant_param(c: &str, p: &Value) -> Result<Option<Vec<Permission>>> {
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// What a person approved for one install: the module they were shown (its id, SHA-256 and the
|
||||
/// permissions it lists) and whether they agreed to its heavy budget. Only the code that asked the
|
||||
/// person sets it ([`Session::approve_plugin_install`]); no command can.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct InstallApproval {
|
||||
pub id: String,
|
||||
pub hash: String,
|
||||
pub permissions: Vec<String>,
|
||||
pub heavy: bool,
|
||||
}
|
||||
|
||||
impl InstallApproval {
|
||||
/// Is `plugin` the module this approval was given for?
|
||||
fn covers(&self, plugin: &Plugin) -> bool {
|
||||
let m = plugin.manifest();
|
||||
self.id == m.id && self.hash == plugin.hash() && self.permissions.iter().map(String::as_str).eq(permissions::names(&m.permissions()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Lets the next `plugin.install` take its `grant` and `allowHeavy`, for the module `approval`
|
||||
/// describes. Call it only with what a person approved, just before that install.
|
||||
pub fn approve_plugin_install(&mut self, approval: InstallApproval) {
|
||||
self.plugin_install_approval = Some(approval);
|
||||
}
|
||||
|
||||
/// Drops an approval that no install has spent.
|
||||
pub fn clear_plugin_install_approval(&mut self) {
|
||||
self.plugin_install_approval = None;
|
||||
}
|
||||
|
||||
/// Makes `plugin.install` accept `grant` and `allowHeavy` from any request in this session.
|
||||
/// For the person starting the process (`vectorcraft-cli --allow-plugin-grants`), never for
|
||||
/// a request.
|
||||
pub fn allow_plugin_grants_from_requests(&mut self) {
|
||||
self.plugin_grants_from_requests = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Would installing `plugin` take another module's place: one installed with its id and other
|
||||
/// bytes, or, with none installed, the settings and cache the plug-in store keeps for its id?
|
||||
fn takes_over(s: &Session, plugin: &Plugin) -> bool {
|
||||
@@ -565,13 +607,17 @@ fn takes_over(s: &Session, plugin: &Plugin) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// `plugin.install`: loads and checks the module, refuses one that asks for a heavy budget unless
|
||||
/// `allowHeavy` says the user agreed, one that lists permissions the user hasn't granted this very
|
||||
/// module unless `grant` lists them all, one that would take another module's place ([`takes_over`])
|
||||
/// unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records the grant with
|
||||
/// the module's hash, keeps it for the next start and installs it → its `plugin.list` entry.
|
||||
/// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an
|
||||
/// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget
|
||||
/// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this
|
||||
/// very module unless `grant` lists them all, one that would take another module's place
|
||||
/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records
|
||||
/// the grant with the module's hash, keeps it for the next start and installs it → its
|
||||
/// `plugin.list` entry. A module that lists no permissions ends any grant held for its id.
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.install";
|
||||
// One use: spent whatever this install does.
|
||||
let approval = s.plugin_install_approval.take();
|
||||
let replace = match p.get("replace") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(switch_or(p, "replace", false, C)?),
|
||||
@@ -600,25 +646,38 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
),
|
||||
));
|
||||
}
|
||||
// A heavy plug-in is installed once the user agrees: whoever installs it asks them first.
|
||||
// `grant` and `allowHeavy` say that a person agreed, and a request alone can't say that.
|
||||
let approval = approval.filter(|a| a.covers(&plugin));
|
||||
if !s.plugin_grants_from_requests && ((grant.is_some() && approval.is_none()) || (allow_heavy && !approval.is_some_and(|a| a.heavy))) {
|
||||
return Err(bad(
|
||||
C,
|
||||
"`grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app",
|
||||
));
|
||||
}
|
||||
// A heavy plug-in is installed once a person agrees.
|
||||
if plugin.manifest().budget == Budget::Heavy && !allow_heavy {
|
||||
let (minutes, times) = vectorcraft_plugins::heavy_terms();
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees",
|
||||
"“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants",
|
||||
plugin.manifest().name
|
||||
),
|
||||
));
|
||||
}
|
||||
// A plug-in that lists permissions installs once the user grants them: whoever installs it
|
||||
// asks them first, unless they already granted this very module all of them.
|
||||
// A plug-in that lists permissions installs once they are granted, unless a grant recorded for
|
||||
// this very module already covers all of them.
|
||||
let m = plugin.manifest();
|
||||
let wanted = m.permissions();
|
||||
if !s.plugin_approved(&plugin) && !grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))) {
|
||||
let name = permissions::display_text(&m.name, permissions::MAX_SHOWN_NAME);
|
||||
let asked = permissions::names(&wanted).join(", ");
|
||||
return Err(bad(C, format!("“{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees")));
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"“{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants"
|
||||
),
|
||||
));
|
||||
}
|
||||
// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
|
||||
// grant only once it is there; when the grant can't be written, the store gets the module it
|
||||
@@ -634,6 +693,22 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref());
|
||||
stored = false;
|
||||
}
|
||||
} else {
|
||||
// This module takes the id over, so nothing the user approved for the id applies any more.
|
||||
registry::revoke(&m.id);
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant at
|
||||
// the next launch. A grant that can't be removed still approves the old bytes, so the store
|
||||
// gets the module it held back. When that module can't be read or written back, or there
|
||||
// was none, no module goes with the grant, and the grant stops counting for this session. A
|
||||
// grants file that is too large or doesn't hold a list approves nothing, and the new module
|
||||
// stays; one that can't be opened or read may approve the old bytes once it reads again.
|
||||
if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref()));
|
||||
stored = !back;
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(&m.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
// It gets the settings and cache kept for its id.
|
||||
s.attach_plugin_storage(plugin.id());
|
||||
@@ -844,19 +919,25 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
// Its settings and cache go first: when they can't be moved aside, the plug-in stays installed,
|
||||
// as it was, and a second `plugin.remove` tries again.
|
||||
if (installed || stored)
|
||||
&& let Err(e) = s.remove_plugin_storage(id)
|
||||
{
|
||||
// Installed again, it asks again. A grant that can't be removed still approves the module, and
|
||||
// so may a grants file that can't be opened or read. One that is too large or doesn't hold a
|
||||
// list approves nothing and doesn't stop the removal.
|
||||
let forget = || s.store_grant(id, None) || !s.holds_plugin_grant(id);
|
||||
// Its settings and cache are moved aside and its grant removed before anything is deleted: when
|
||||
// either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove`
|
||||
// tries again.
|
||||
let failed = if installed || stored {
|
||||
s.remove_plugin_storage(id, forget).err().map(|e| e.to_string())
|
||||
} else {
|
||||
(!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string())
|
||||
};
|
||||
if let Some(e) = failed {
|
||||
if installed {
|
||||
s.attach_plugin_storage(id);
|
||||
}
|
||||
return Err(EngineError::Other(e.to_string()));
|
||||
return Err(EngineError::Other(e));
|
||||
}
|
||||
// Installed again, it asks again.
|
||||
registry::revoke(id);
|
||||
s.store_grant(id, None);
|
||||
s.unstore_plugin(id);
|
||||
if !stored && (!installed || !registry::remove(id)) {
|
||||
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
|
||||
@@ -908,7 +989,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, with at most 16 MiB of pixels and 16 MiB of type runs per run (later ones come with pixelsOmitted or truncated); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
|
||||
has_doc,
|
||||
run
|
||||
),
|
||||
@@ -917,7 +998,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Install Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (true once the user agreed to a heavy budget: a filter whose manifest asks for one, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (the permissions the user granted: a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; with a plug-in store attached, only the grants kept there count), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry",
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry",
|
||||
always,
|
||||
install
|
||||
),
|
||||
@@ -926,7 +1007,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Inspect Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions the user hasn't granted this very module, its bytes included: plugin.install then needs grant) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)",
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)",
|
||||
always,
|
||||
inspect
|
||||
),
|
||||
@@ -935,7 +1016,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, the command fails and the plug-in stays installed); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}",
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
|
||||
@@ -227,6 +227,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
// Guides & Grid
|
||||
p!("guideColor", "Guides & Grid", "Guides", "Color", color),
|
||||
p!("guideStyle", "Guides & Grid", "Guides", "Style", choice(LINE_STYLE)),
|
||||
p!("lockGuidesByDefault", "Guides & Grid", "Guides", "Lock Guides by Default", bool),
|
||||
p!("gridColor", "Guides & Grid", "Grid", "Color", color),
|
||||
p!("gridStyle", "Guides & Grid", "Grid", "Style", choice(LINE_STYLE)),
|
||||
p!("gridlineEvery", "Guides & Grid", "Grid", "Gridline every", len(1.0, 16383.0, General)),
|
||||
@@ -437,6 +438,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
// The Align panel menu's Align to Glyph Bounds: Align and Distribute measure type by its glyphs' ink.
|
||||
p!("alignGlyphBoundsPoint", "Type", "Align to Glyph Bounds", "Point Text", bool),
|
||||
p!("alignGlyphBoundsArea", "Type", "Align to Glyph Bounds", "Area Text", bool),
|
||||
// The bounding box and the Transform panel measure point type by its glyphs' ink (also in the Transform panel menu).
|
||||
p!("typeGlyphBounds", "Type", "Glyph Bounds", "Measure Type by Glyph Bounds", bool),
|
||||
// Artboard Options › Global: the canvas darkens the area outside the artboards while the Artboard tool is active.
|
||||
p!("fadeRegionOutsideArtboard", "General", "Artboard Options", "Fade Region Outside Artboard", bool),
|
||||
p!("artboardUpdateWhileDragging", "General", "Artboard Options", "Update While Dragging", bool),
|
||||
@@ -693,10 +696,16 @@ impl Session {
|
||||
let fonts_folder_changed = p.fonts_folder != self.prefs.fonts_folder;
|
||||
let hyphen_exceptions_changed = p.hyphenation_exceptions != self.prefs.hyphenation_exceptions;
|
||||
let corner_radius_changed = p.corner_radius != self.prefs.corner_radius;
|
||||
let lock_guides_changed = p.lock_guides_by_default != self.prefs.lock_guides_by_default;
|
||||
if p.trace_presets != self.prefs.trace_presets {
|
||||
self.trace_preset_changes.replaced();
|
||||
}
|
||||
self.prefs = p;
|
||||
// Guides & Grid › Lock Guides by Default sets the lock when it changes, the saved value at
|
||||
// start included. Otherwise the lock stays as View › Guides › Lock Guides left it.
|
||||
if lock_guides_changed {
|
||||
self.set_guides_locked(self.prefs.lock_guides_by_default);
|
||||
}
|
||||
if corner_radius_changed {
|
||||
// General › Corner Radius is the Rounded Rectangle tool's radius (#394): a tool already
|
||||
// made (active, or lent a selection tool for a drag) takes the new value.
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
//! Edit → Spelling: the words of the document's type that its dictionaries don't know
|
||||
//! (`text.spelling.check`) and the words they suggest instead (`text.spelling.suggest`), checked
|
||||
//! by craft-proof in each run's language
|
||||
//! ([Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html)).
|
||||
//! A word is changed with `text.editRange` over the bytes the check gives. Add and Edit Custom
|
||||
//! Dictionary keep words in the custom dictionary (`text.spelling.dictionary`, `addWord`,
|
||||
//! `removeWord`, `changeWord`), which every document's check takes as right; Ignore All
|
||||
//! (`text.spelling.ignoreAll`) skips a word in the active document only.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::ops::Range;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_proof::{IssueKind, Options, ProofLang};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject};
|
||||
|
||||
use super::menucmds::whole_or;
|
||||
use super::typemenu::{all_texts, text_ids};
|
||||
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param};
|
||||
|
||||
/// Most unknown words one check lists; past it the result says `more`.
|
||||
pub const MAX_WORDS: usize = 10_000;
|
||||
|
||||
/// Most suggestions one word gets.
|
||||
pub const MAX_SUGGESTIONS: u64 = 20;
|
||||
|
||||
/// Longest word suggestions are looked for, in bytes: the search costs more with the length.
|
||||
const MAX_WORD_LEN: usize = 128;
|
||||
|
||||
/// The Edit › Spelling commands.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "text.spelling.check",
|
||||
"Check Spelling",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than 10000 words, the rest left out)}. text.editRange {id, start, end, insert} changes one",
|
||||
has_doc,
|
||||
check
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.suggest",
|
||||
"Spelling Suggestions",
|
||||
[],
|
||||
None,
|
||||
"{word, max?: 1..20 (default 5), lang?: language tag (default English)} the words the dictionary of lang suggests instead of word, best first → {suggestions: [word…]}",
|
||||
has_doc,
|
||||
suggest
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.dictionary",
|
||||
"Edit Custom Dictionary",
|
||||
[],
|
||||
None,
|
||||
"{} the words of the custom dictionary, sorted (lower case, as they are kept) → {words: [word…]}",
|
||||
always,
|
||||
dictionary
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.addWord",
|
||||
"Add to Custom Dictionary",
|
||||
[],
|
||||
None,
|
||||
"{word} adds word (one word, at most 64 characters; kept in lower case) to the custom dictionary, which every language's check takes as right, and saves it → {word, added: bool (false: it was there already)}",
|
||||
always,
|
||||
add_word
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.removeWord",
|
||||
"Delete from Custom Dictionary",
|
||||
[],
|
||||
None,
|
||||
"{word} deletes word from the custom dictionary and saves it (an error when it isn't there) → {word}",
|
||||
always,
|
||||
remove_word
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.changeWord",
|
||||
"Change in Custom Dictionary",
|
||||
[],
|
||||
None,
|
||||
"{word, to} replaces word in the custom dictionary with to and saves it (an error when word isn't there) → {word: to}",
|
||||
always,
|
||||
change_word
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.ignoreAll",
|
||||
"Ignore All",
|
||||
[],
|
||||
None,
|
||||
"{word} the active document's spelling checks skip word from now on, until it closes (not saved, not undoable) → {word}",
|
||||
has_doc,
|
||||
ignore_all
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// `text.spelling.check`: the unknown words of the given type objects (or every visible, unlocked
|
||||
/// one), in paint order, each paragraph checked on its own, at most [`MAX_WORDS`] of them.
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.check";
|
||||
// Given `ids` are checked like Find and Replace's, so a malformed one is an error rather than
|
||||
// a check of the whole document.
|
||||
let ids = match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(_) => in_paint_order(&s.doc()?.doc, text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?)),
|
||||
None => all_texts(&s.doc()?.doc),
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let mut words = vec![];
|
||||
let mut more = false;
|
||||
for id in ids {
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue };
|
||||
let text = t.plain_text();
|
||||
let (found, cut) = misspellings(t, &st.spelling_ignored, MAX_WORDS - words.len());
|
||||
for m in found {
|
||||
let Some(word) = text.get(m.range.clone()) else { continue };
|
||||
words.push(json!({ "id": id.0, "start": m.range.start, "end": m.range.end, "word": word, "lang": m.lang.tag() }));
|
||||
}
|
||||
if cut {
|
||||
more = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(json!({ "words": words, "more": more }))
|
||||
}
|
||||
|
||||
/// One word of a type object its dictionaries don't know ([`misspellings`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Misspelling {
|
||||
/// The word's bytes in the object's [`TextObject::plain_text`].
|
||||
pub range: Range<usize>,
|
||||
/// The language it was checked in.
|
||||
pub lang: ProofLang,
|
||||
}
|
||||
|
||||
/// The words of `t` its dictionaries don't know, in text order: each run checked in its
|
||||
/// language, each paragraph on its own, leaving out the words in `ignored` (a document's Ignore
|
||||
/// All words). At most `max` of them; the flag says the list was cut short there. What
|
||||
/// `text.spelling.check` lists for one object, and what Auto Spell Check underlines.
|
||||
pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (Vec<Misspelling>, bool) {
|
||||
let text = t.plain_text();
|
||||
// Each run in its own language, at its bytes of the plain text.
|
||||
let mut spans: Vec<(Range<usize>, ProofLang)> = Vec::with_capacity(t.runs.len());
|
||||
let mut at = 0;
|
||||
for r in &t.runs {
|
||||
let end = at + r.text.len();
|
||||
spans.push((at..end, ProofLang::from_tag(r.style.language.as_deref())));
|
||||
at = end;
|
||||
}
|
||||
let opts = Options::default();
|
||||
let mut found = vec![];
|
||||
// craft-proof checks one paragraph at a time (its language detection reads the paragraph),
|
||||
// and the check stops at the paragraph where the list fills up rather than proofing the rest
|
||||
// of the text.
|
||||
let mut para_start = 0;
|
||||
for para in text.split('\n') {
|
||||
let para_end = para_start + para.len();
|
||||
let para_spans: Vec<(Range<usize>, ProofLang)> = spans
|
||||
.iter()
|
||||
.filter_map(|(r, lang)| {
|
||||
let (a, b) = (r.start.max(para_start), r.end.min(para_end));
|
||||
(a < b).then(|| (a - para_start..b - para_start, *lang))
|
||||
})
|
||||
.collect();
|
||||
for issue in craft_proof::check_text_with(para, ¶_spans, &opts, false, false) {
|
||||
if issue.kind != IssueKind::Spelling {
|
||||
continue;
|
||||
}
|
||||
let (start, end) = (para_start + issue.start, para_start + issue.end);
|
||||
let Some(word) = text.get(start..end) else { continue };
|
||||
if craft_proof::custom_word(word).is_some_and(|w| ignored.contains(&w)) {
|
||||
continue;
|
||||
}
|
||||
if found.len() == max {
|
||||
return (found, true);
|
||||
}
|
||||
found.push(Misspelling { range: start..end, lang: issue.lang });
|
||||
}
|
||||
// Past the paragraph and its `\n`.
|
||||
para_start = para_end + 1;
|
||||
}
|
||||
(found, false)
|
||||
}
|
||||
|
||||
/// Goes up each time the custom dictionary may have changed: an add, delete or change (saved or
|
||||
/// not, since a save takes in the words another window saved), and a dictionary file attached.
|
||||
static DICTIONARY_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The custom dictionary's generation: what [`misspellings`] found before it last changed may be
|
||||
/// out of date (Auto Spell Check checks the type again).
|
||||
pub fn dictionary_generation() -> u64 {
|
||||
DICTIONARY_GENERATION.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn dictionary_changed() {
|
||||
DICTIONARY_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// `ids` sorted back to front, as the document paints them: by their index paths, which are in
|
||||
/// paint order.
|
||||
fn in_paint_order(d: &Document, mut ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let paths = d.index_paths(ids.iter().copied());
|
||||
ids.sort_by(|a, b| paths.get(a).cmp(&paths.get(b)));
|
||||
ids
|
||||
}
|
||||
|
||||
/// `text.spelling.suggest`: up to `max` of the words the dictionary of `lang` suggests for `word`.
|
||||
fn suggest(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.suggest";
|
||||
let word = str_param(p, "word").map(str::trim).filter(|w| !w.is_empty()).ok_or_else(|| bad(C, "missing `word`"))?;
|
||||
let max = whole_or(p, "max", 5, C)?;
|
||||
if !(1..=MAX_SUGGESTIONS).contains(&max) {
|
||||
return Err(bad(C, format!("`max` must be 1 to {MAX_SUGGESTIONS}")));
|
||||
}
|
||||
if word.len() > MAX_WORD_LEN {
|
||||
return Ok(json!({ "suggestions": [] }));
|
||||
}
|
||||
let lang = ProofLang::from_tag(str_param(p, "lang"));
|
||||
// `max` is at most MAX_SUGGESTIONS, so it fits.
|
||||
let suggestions = craft_proof::suggest_in(word, usize::try_from(max).unwrap_or(5), lang);
|
||||
Ok(json!({ "suggestions": suggestions }))
|
||||
}
|
||||
|
||||
/// `p`'s `key` as a custom-dictionary word (trimmed, lower case), or an error naming what it must be.
|
||||
fn word_param(p: &Value, key: &str, command: &str) -> Result<String> {
|
||||
let w = str_param(p, key).ok_or_else(|| bad(command, format!("missing `{key}`")))?;
|
||||
craft_proof::custom_word(w)
|
||||
.ok_or_else(|| bad(command, format!("`{key}` must be one word of at most {} characters", craft_proof::MAX_CUSTOM_WORD_CHARS)))
|
||||
}
|
||||
|
||||
/// Largest custom dictionary file taken in, in bytes: craft-proof reads no more of one (its
|
||||
/// `MAX_CUSTOM_FILE_BYTES`), so a larger file would lose its other words when written back.
|
||||
pub const MAX_DICTIONARY_FILE_BYTES: u64 = 1_000_000;
|
||||
|
||||
/// Whether the custom dictionary file at `path` can be written over without losing words: it is
|
||||
/// missing (a first save creates it), or a file that can be read whole. Otherwise why not.
|
||||
fn dictionary_file_readable(path: &std::path::Path) -> std::result::Result<(), String> {
|
||||
match std::fs::metadata(path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
Ok(m) if !m.is_file() => Err("it isn't a file".into()),
|
||||
Ok(m) if m.len() > MAX_DICTIONARY_FILE_BYTES => Err(format!("it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes")),
|
||||
Ok(_) => {
|
||||
// Read it whole, as craft-proof will: a file that opens but then can't be read would
|
||||
// read as no words there.
|
||||
use std::io::Read;
|
||||
let mut bytes = Vec::new();
|
||||
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
|
||||
file.take(MAX_DICTIONARY_FILE_BYTES + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > MAX_DICTIONARY_FILE_BYTES {
|
||||
return Err(format!("it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After a failed save took a command's change back: take in the words the file holds again, so
|
||||
/// a word another window saved meanwhile, which the change had added too, stays.
|
||||
fn retake_file_words(s: &Session) {
|
||||
if let Some(path) = s.dictionary_file.as_deref().filter(|p| dictionary_file_readable(p).is_ok()) {
|
||||
craft_proof::load_user_dictionary(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the custom dictionary to its file when the session has one, leaving out `removed`. A file
|
||||
/// that is there but can't be read whole is left alone rather than written over with only the
|
||||
/// words read. On an error the caller takes its own change back, so memory and file agree.
|
||||
fn save_dictionary(s: &Session, removed: &[String], command: &str) -> Result<()> {
|
||||
let Some(path) = &s.dictionary_file else { return Ok(()) };
|
||||
if let Err(why) = dictionary_file_readable(path) {
|
||||
return Err(bad(command, format!("the custom dictionary {} can't be read ({why}), so it is left as it is", path.display())));
|
||||
}
|
||||
craft_proof::save_user_dictionary(path, removed)
|
||||
.map_err(|e| bad(command, format!("the custom dictionary couldn't be saved to {}: {e}", path.display())))
|
||||
}
|
||||
|
||||
/// `text.spelling.dictionary`: the custom dictionary's words.
|
||||
fn dictionary(_s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "words": craft_proof::user_dictionary() }))
|
||||
}
|
||||
|
||||
/// `text.spelling.addWord`: Add, and Edit Custom Dictionary's Add.
|
||||
fn add_word(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.addWord";
|
||||
let word = word_param(p, "word", C)?;
|
||||
let added = !craft_proof::user_dictionary().contains(&word);
|
||||
craft_proof::add_word(&word);
|
||||
let saved = save_dictionary(s, &[], C);
|
||||
dictionary_changed();
|
||||
saved.inspect_err(|_| {
|
||||
// Only this command's word: words the save took in from the file stay.
|
||||
if added {
|
||||
craft_proof::remove_word(&word);
|
||||
retake_file_words(s);
|
||||
}
|
||||
})?;
|
||||
Ok(json!({ "word": word, "added": added }))
|
||||
}
|
||||
|
||||
/// `text.spelling.removeWord`: Edit Custom Dictionary's Delete.
|
||||
fn remove_word(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.removeWord";
|
||||
let word = word_param(p, "word", C)?;
|
||||
if !craft_proof::remove_word(&word) {
|
||||
return Err(bad(C, format!("`{word}` isn't in the custom dictionary")));
|
||||
}
|
||||
let saved = save_dictionary(s, std::slice::from_ref(&word), C);
|
||||
dictionary_changed();
|
||||
saved.inspect_err(|_| craft_proof::add_word(&word))?;
|
||||
Ok(json!({ "word": word }))
|
||||
}
|
||||
|
||||
/// `text.spelling.changeWord`: Edit Custom Dictionary's Change.
|
||||
fn change_word(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.changeWord";
|
||||
let word = word_param(p, "word", C)?;
|
||||
let to = word_param(p, "to", C)?;
|
||||
if !craft_proof::user_dictionary().contains(&word) {
|
||||
return Err(bad(C, format!("`{word}` isn't in the custom dictionary")));
|
||||
}
|
||||
if word == to {
|
||||
let saved = save_dictionary(s, &[], C);
|
||||
dictionary_changed();
|
||||
saved?;
|
||||
return Ok(json!({ "word": to }));
|
||||
}
|
||||
let to_is_new = !craft_proof::user_dictionary().contains(&to);
|
||||
craft_proof::remove_word(&word);
|
||||
craft_proof::add_word(&to);
|
||||
let saved = save_dictionary(s, std::slice::from_ref(&word), C);
|
||||
dictionary_changed();
|
||||
saved.inspect_err(|_| {
|
||||
if to_is_new {
|
||||
craft_proof::remove_word(&to);
|
||||
retake_file_words(s);
|
||||
}
|
||||
craft_proof::add_word(&word);
|
||||
})?;
|
||||
Ok(json!({ "word": to }))
|
||||
}
|
||||
|
||||
/// `text.spelling.ignoreAll`: Ignore All, for the active document.
|
||||
fn ignore_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.ignoreAll";
|
||||
let word = word_param(p, "word", C)?;
|
||||
// Not a change to the document, so its revision stays: a tool edit computed meanwhile still
|
||||
// applies (`command_sweep`'s check of commands that don't wait for one).
|
||||
s.doc_mut()?.spelling_ignored.insert(word.clone());
|
||||
Ok(json!({ "word": word }))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Keep the custom dictionary in the file at `path` (the desktop app's, beside its
|
||||
/// preferences), and take in the words already there. A missing file reads as no words and is
|
||||
/// created by the first save. A file that is there but can't be read whole is logged and left
|
||||
/// as it is: changes to the dictionary are refused rather than written over it.
|
||||
pub fn attach_custom_dictionary(&mut self, path: std::path::PathBuf) {
|
||||
match dictionary_file_readable(&path) {
|
||||
Ok(()) => {
|
||||
craft_proof::load_user_dictionary(&path);
|
||||
}
|
||||
Err(why) => log::warn!("not reading the custom dictionary {}: {why}; it is left as it is", path.display()),
|
||||
}
|
||||
self.dictionary_file = Some(path);
|
||||
dictionary_changed();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! of symbols the library panel shows. A library is a document holding the symbols with the
|
||||
//! resources they use (nested symbols, patterns, swatches, brushes, graphic styles, images) and
|
||||
//! their Symbol Options; saved, it is a native `.vectorcraft` file, which File › Open also opens.
|
||||
//! The built-in library is generated here ([`BUILTIN`]); User Defined ones are the `.vectorcraft`
|
||||
//! The built-in libraries are generated here ([`BUILTIN`]); User Defined ones are the `.vectorcraft`
|
||||
//! files in the user library folder ([`Libraries`]), and Other Library… loads the symbols of any
|
||||
//! document VectorCraft opens. `symbol.addFromLibrary` copies symbols into the document;
|
||||
//! `symbol.saveLibrary` writes the document's.
|
||||
@@ -12,7 +12,7 @@ use std::sync::{Arc, LazyLock};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol, SymbolNineSlice};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
|
||||
use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_natural_size};
|
||||
@@ -154,7 +154,10 @@ pub struct BuiltinSymbolLibrary {
|
||||
}
|
||||
|
||||
/// The built-in symbol libraries, in menu order: original art generated in code.
|
||||
pub const BUILTIN: &[BuiltinSymbolLibrary] = &[BuiltinSymbolLibrary { id: "basic-shapes", name: "Basic Shapes", make: basic_shapes }];
|
||||
pub const BUILTIN: &[BuiltinSymbolLibrary] = &[
|
||||
BuiltinSymbolLibrary { id: "basic-shapes", name: "Basic Shapes", make: basic_shapes },
|
||||
BuiltinSymbolLibrary { id: "ui-frames", name: "UI Frames", make: ui_frames },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
fn builtin_library(id: &str) -> Option<Arc<SymbolLibrary>> {
|
||||
@@ -194,6 +197,30 @@ fn basic_shapes() -> SymbolLibrary {
|
||||
SymbolLibrary { name: "Basic Shapes".into(), doc }
|
||||
}
|
||||
|
||||
/// UI Frames: panel, button and bar HUD chrome with default 9-slice guides (original art).
|
||||
fn ui_frames() -> SymbolLibrary {
|
||||
// Heights keep default 9-slice (0.25) past each corner radius so a vertical resize
|
||||
// stretches only the flat middle, not the curves.
|
||||
let frames = [
|
||||
("Panel", Rect::new(-48.0, -36.0, 48.0, 36.0), 10.0, "#2b3340", "#8aa0b8"),
|
||||
("Button", Rect::new(-36.0, -18.0, 36.0, 18.0), 8.0, "#3a6ea5", "#d7e6f5"),
|
||||
("Bar", Rect::new(-56.0, -24.0, 56.0, 24.0), 10.0, "#1f6b4a", "#b7e0c9"),
|
||||
];
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
for (name, rect, radius, fill_hex, edge_hex) in frames {
|
||||
let fill = Color::from_hex(fill_hex).unwrap_or(Color::BLACK);
|
||||
let edge = Color::from_hex(edge_hex).unwrap_or(Color::BLACK);
|
||||
let id = doc.alloc_id();
|
||||
let art = Node::path(id, shapes::rounded_rectangle(rect, radius), Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.5));
|
||||
let Ok((art, size, _)) = normalize(art) else { continue };
|
||||
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
|
||||
set_natural_size(&mut doc, name, Some(size));
|
||||
doc.set_symbol_nine_slice(name, Some(SymbolNineSlice::default()));
|
||||
}
|
||||
doc.title = "UI Frames".into();
|
||||
SymbolLibrary { name: "UI Frames".into(), doc }
|
||||
}
|
||||
|
||||
/// An instance of symbol `name` (what the resource gathering follows).
|
||||
fn instance(name: &str) -> Node {
|
||||
Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })
|
||||
|
||||
@@ -1611,6 +1611,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
list_level_counts: Vec::new(),
|
||||
cached_bounds: None,
|
||||
cached_baselines: Vec::new(),
|
||||
cached_ink: None,
|
||||
};
|
||||
super::create::new_type_alignment(s, p, C, &mut t)?;
|
||||
if !on_path {
|
||||
@@ -1901,6 +1902,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
|
||||
list_level_counts: Vec::new(),
|
||||
cached_bounds: None,
|
||||
cached_baselines: Vec::new(),
|
||||
cached_ink: None,
|
||||
};
|
||||
for r in &mut h.runs {
|
||||
r.style.tracking = tr;
|
||||
|
||||
@@ -48,7 +48,7 @@ impl Kind {
|
||||
|
||||
/// One command spec (the `cmd!` macro wants literals; these ids are built with `concat!`).
|
||||
const fn spec(id: &'static str, label: &'static str, menu: &'static [&'static str], params: &'static str, run: Run, journal: bool) -> CommandSpec {
|
||||
CommandSpec { id, label, menu, shortcut: None, params, enabled: has_doc, run, journal }
|
||||
CommandSpec { id, label, menu, shortcut: None, params, enabled: has_doc, run, journal, schema: None }
|
||||
}
|
||||
|
||||
macro_rules! style_cmds {
|
||||
|
||||
@@ -304,6 +304,7 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
t.cached_bounds = Some(lay.bounds);
|
||||
t.cached_baselines = lay.baselines();
|
||||
t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t)));
|
||||
}
|
||||
|
||||
/// [`refresh_bounds`] for a document that is opening: the first frame takes the layout
|
||||
@@ -315,6 +316,7 @@ pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
t.cached_bounds = Some(lay.bounds);
|
||||
t.cached_baselines = lay.baselines();
|
||||
t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t)));
|
||||
vectorcraft_text::keep_layout(t, stamp, lay);
|
||||
}
|
||||
|
||||
|
||||
@@ -718,7 +718,9 @@ fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool,
|
||||
|
||||
/// The text objects Find and Replace and Find Next reach: on visible, unlocked layers, and not
|
||||
/// inside a hidden or locked group, which hides or locks what it holds as a layer does (#5900).
|
||||
fn all_texts(d: &Document) -> Vec<NodeId> {
|
||||
/// The visible, unlocked type objects of visible, unlocked layers, off locked artboards, in paint
|
||||
/// order: the text Find and Replace and Check Spelling go through.
|
||||
pub(crate) fn all_texts(d: &Document) -> Vec<NodeId> {
|
||||
fn visit(n: &Node, locks: &LockedArtboards<'_>, v: &mut Vec<NodeId>) {
|
||||
if !n.visible || n.locked {
|
||||
return;
|
||||
|
||||
@@ -2,33 +2,106 @@
|
||||
//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_apischema::{Bound, Param, ParamSchema, Type, Writes};
|
||||
use vectorcraft_doc::SavedView;
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_req, finite_numbers, has_doc, str_param, switch_or};
|
||||
|
||||
// The parameter schemas. Each command's params text is the text its schema writes
|
||||
// (`ParamSchema::params_text`), which a test in `crate::schemas` checks.
|
||||
|
||||
static CAPS_LOCK: ParamSchema = ParamSchema::new(
|
||||
&[Param::new("on", Type::Boolean).optional()],
|
||||
"set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value",
|
||||
)
|
||||
.returns("{on}")
|
||||
.writes(Writes::Session);
|
||||
|
||||
static NEW_VIEW: ParamSchema = ParamSchema::new(
|
||||
&[
|
||||
Param::new("name", Type::String).default_note("the first free \"View N\"").null_omitted(),
|
||||
Param::new("center", Type::Point),
|
||||
Param::new("zoom", Type::Number { min: Some(Bound::Exclusive(0.0)), max: None, unit: None }).doc("1 = 100%"),
|
||||
Param::new("rotation", Type::Number { min: None, max: None, unit: Some("deg") }).defaults_to("0"),
|
||||
],
|
||||
"save a view in the document (the app fills in the current one; at most 25, names up to 255 characters, each name once)",
|
||||
)
|
||||
.returns("{name, index}");
|
||||
|
||||
/// One rename or delete of Edit Views….
|
||||
const VIEW_EDIT: &[Param] = &[
|
||||
Param::new("name", Type::String),
|
||||
Param::new("newName", Type::String).optional().null_omitted(),
|
||||
Param::new("delete", Type::Boolean).optional().null_omitted(),
|
||||
];
|
||||
|
||||
static EDIT_VIEWS: ParamSchema = ParamSchema::new(
|
||||
&[
|
||||
Param::new("name", Type::String).optional().null_omitted(),
|
||||
Param::new("newName", Type::String).optional().null_omitted().doc("rename"),
|
||||
Param::new("delete", Type::Boolean).optional().null_omitted(),
|
||||
Param::new("edits", Type::Array(&Type::Object(VIEW_EDIT))).optional().null_omitted().doc("instead of name"),
|
||||
],
|
||||
"rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}",
|
||||
);
|
||||
|
||||
static LIST_VIEWS: ParamSchema = ParamSchema::new(&[], "").returns("{views: [{name, center, zoom, rotation}]}").writes(Writes::Nothing);
|
||||
|
||||
static TRANSPARENCY_GRID: ParamSchema = ParamSchema::new(
|
||||
&[Param::new("on", Type::Boolean).default_note("toggle").null_omitted()],
|
||||
"show the transparency grid behind the active document's artboards (each document has its own setting)",
|
||||
)
|
||||
.returns("{on}")
|
||||
.writes(Writes::Session);
|
||||
|
||||
static GLYPH_SNAP: ParamSchema = ParamSchema::new(
|
||||
&[
|
||||
Param::new("baseline", Type::Boolean).optional(),
|
||||
Param::new("xHeight", Type::Boolean).optional(),
|
||||
Param::new("bounds", Type::Boolean).optional(),
|
||||
Param::new("proximity", Type::Boolean).optional(),
|
||||
Param::new("angular", Type::Boolean).optional(),
|
||||
Param::new("anchors", Type::Boolean).optional(),
|
||||
],
|
||||
"the Character panel's Snap to Glyph options, kept in the preferences (the glyphSnap group, all on by default): which guides View › Snap to Glyph gives: the baseline and x-height of a single line of type, Glyph Bounds (each glyph's edges), Proximity Guides (both edges of each character's width), Angular Guides (a glyph's slanted strokes, and every guide of rotated type) and the glyphs' anchor points; {} reads them",
|
||||
)
|
||||
.returns("the options")
|
||||
.writes(Writes::Preferences);
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(query "view.capsLock", "Caps Lock Cursor State", [], None, "{on?: bool} set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value → {on}", always, caps_lock),
|
||||
cmd!(
|
||||
query "view.capsLock",
|
||||
"Caps Lock Cursor State",
|
||||
[],
|
||||
None,
|
||||
"{on?: bool} set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value → {on}",
|
||||
always,
|
||||
caps_lock,
|
||||
schema: &CAPS_LOCK
|
||||
),
|
||||
cmd!(
|
||||
"view.saved.new",
|
||||
"New View…",
|
||||
["View"],
|
||||
None,
|
||||
"{name?, center: [x, y], zoom: (1 = 100%), rotation?: deg} save a view in the document (the app fills in the current one; default \"View N\"; at most 25, names up to 255 characters, each name once) → {name, index}",
|
||||
"{name?: string (default: the first free \"View N\"), center: [x, y], zoom: number > 0 (1 = 100%), rotation?: number deg (default: 0)} save a view in the document (the app fills in the current one; at most 25, names up to 255 characters, each name once) → {name, index}",
|
||||
has_doc,
|
||||
new_view
|
||||
new_view,
|
||||
schema: &NEW_VIEW
|
||||
),
|
||||
cmd!(
|
||||
"view.saved.edit",
|
||||
"Edit Views…",
|
||||
["View"],
|
||||
None,
|
||||
"{name, newName?: rename, delete?: bool} | {edits: [{name, newName?, delete?}…]} rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}",
|
||||
"{name?: string, newName?: string (rename), delete?: bool, edits?: [{name: string, newName?: string, delete?: bool}…] (instead of name)} rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}",
|
||||
has_views,
|
||||
edit_views
|
||||
edit_views,
|
||||
schema: &EDIT_VIEWS
|
||||
),
|
||||
cmd!(query "view.saved.list", "Saved Views", [], None, "{} → {views: [{name, center, zoom, rotation}]}", has_doc, list_views),
|
||||
cmd!(query "view.saved.list", "Saved Views", [], None, "{} → {views: [{name, center, zoom, rotation}]}", has_doc, list_views, schema: &LIST_VIEWS),
|
||||
cmd!(
|
||||
query "view.transparencyGrid",
|
||||
"Show Transparency Grid",
|
||||
@@ -36,16 +109,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Some("Cmd+Shift+D"),
|
||||
"{on?: bool (default: toggle)} show the transparency grid behind the active document's artboards (each document has its own setting) → {on}",
|
||||
has_doc,
|
||||
transparency_grid
|
||||
transparency_grid,
|
||||
schema: &TRANSPARENCY_GRID
|
||||
),
|
||||
cmd!(
|
||||
query "view.snapToGlyph.options",
|
||||
"Snap to Glyph Options",
|
||||
[],
|
||||
None,
|
||||
"{baseline?: bool, xHeight?: bool, bounds?: bool, proximity?: bool, angular?: bool, anchors?: bool} the Character panel's Snap to Glyph options, kept in the preferences (the glyphSnap group, all on by default): which guides View › Snap to Glyph gives — the baseline and x-height of a single line of type, Glyph Bounds (each glyph's edges), Proximity Guides (both edges of each character's width), Angular Guides (a glyph's slanted strokes, and every guide of rotated type) and the glyphs' anchor points; {} reads them → the options",
|
||||
"{baseline?: bool, xHeight?: bool, bounds?: bool, proximity?: bool, angular?: bool, anchors?: bool} the Character panel's Snap to Glyph options, kept in the preferences (the glyphSnap group, all on by default): which guides View › Snap to Glyph gives: the baseline and x-height of a single line of type, Glyph Bounds (each glyph's edges), Proximity Guides (both edges of each character's width), Angular Guides (a glyph's slanted strokes, and every guide of rotated type) and the glyphs' anchor points; {} reads them → the options",
|
||||
always,
|
||||
glyph_snap_options
|
||||
glyph_snap_options,
|
||||
schema: &GLYPH_SNAP
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -280,6 +355,92 @@ mod tests {
|
||||
assert_eq!(s.execute("view.saved.new", &json!({"name": long, "center": [0, 0], "zoom": 1})).unwrap()["name"], "x".repeat(255));
|
||||
}
|
||||
|
||||
/// Each command refuses a value its schema doesn't take with an error naming the parameter, and
|
||||
/// leaves the document, its views, its undo history and the settings as they were.
|
||||
#[test]
|
||||
fn each_view_command_refuses_a_bad_value_naming_the_parameter() {
|
||||
let mut s = session_with_views(&["A"]);
|
||||
for (id, params, named) in [
|
||||
("view.capsLock", json!({"on": "yes"}), "`on`"),
|
||||
("view.capsLock", json!({"of": true}), "`of`"),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 0}), "`zoom`"),
|
||||
("view.saved.new", json!({"center": [0, "0"], "zoom": 1}), "`center`"),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 1, "rotation": "15"}), "`rotation`"),
|
||||
("view.saved.new", json!({"name": 5, "center": [0, 0], "zoom": 1}), "`name`"),
|
||||
("view.saved.new", json!({"zoom": 1}), "`center`"),
|
||||
("view.saved.edit", json!({"name": "A", "delete": "yes"}), "`delete`"),
|
||||
("view.saved.edit", json!({"name": "A", "newName": 7}), "`newName`"),
|
||||
("view.saved.edit", json!({"edits": [{"name": "A", "delete": 1}]}), "`edits[0].delete`"),
|
||||
("view.saved.edit", json!({"edits": [{"newName": "B"}]}), "`edits[0].name`"),
|
||||
("view.saved.edit", json!({"edits": "A"}), "`edits`"),
|
||||
("view.saved.list", json!({"all": true}), "`all`"),
|
||||
("view.transparencyGrid", json!({"on": 1}), "`on`"),
|
||||
("view.snapToGlyph.options", json!({"bounds": "off"}), "`bounds`"),
|
||||
] {
|
||||
let st = s.doc().unwrap();
|
||||
let doc = (st.doc.views.clone(), st.history.undo.len(), st.is_dirty());
|
||||
let (grid, caps, snap) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap);
|
||||
let e = s.execute(id, ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains(id) && e.contains(named), "{id} {params}: {e}");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!((&st.doc.views, st.history.undo.len(), st.is_dirty()), (&doc.0, doc.1, doc.2), "{id} {params}");
|
||||
assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap), (grid, caps, snap), "{id} {params}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command run by another command's implementation has its params checked against its schema
|
||||
/// too, with nothing changed when they are refused.
|
||||
#[test]
|
||||
fn a_raw_run_is_checked_against_the_schema() {
|
||||
let mut s = session_with_views(&[]);
|
||||
let e = super::super::menucmds::run_raw(&mut s, "view.saved.new", &json!({"center": [0, 0], "zoom": -1})).unwrap_err().to_string();
|
||||
assert!(e.contains("view.saved.new") && e.contains("`zoom` must be a number > 0, not -1"), "{e}");
|
||||
assert!(s.doc().unwrap().doc.views.is_empty());
|
||||
assert!(s.doc().unwrap().history.undo.is_empty());
|
||||
super::super::menucmds::run_raw(&mut s, "view.saved.new", &json!({"center": [0, 0], "zoom": 1})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.views.len(), 1);
|
||||
}
|
||||
|
||||
/// An edit list with nothing in it and an edit that leaves a view as it is add no undo step;
|
||||
/// names with path characters are only names; a key with one is refused and named.
|
||||
#[test]
|
||||
fn edit_views_edges() {
|
||||
let mut s = session_with_views(&["a.b[0]", "plain"]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("view.saved.edit", &json!({"edits": []})).unwrap()["views"].as_array().map(Vec::len), Some(2));
|
||||
s.execute("view.saved.edit", &json!({"name": "plain", "newName": "plain"})).unwrap();
|
||||
s.execute("view.saved.edit", &json!({"edits": [{"name": "plain", "newName": "plain"}]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
s.execute("view.saved.edit", &json!({"name": "a.b[0]", "newName": "c[1].d"})).unwrap();
|
||||
assert_eq!(names(&mut s), ["c[1].d", "plain"]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
let e = s.execute("view.saved.edit", &json!({"a.b": 1})).unwrap_err().to_string();
|
||||
assert!(e.contains("`a.b`"), "{e}");
|
||||
let e = s.execute("view.saved.edit", &json!({"edits": [{"name": "plain", "a.b": 1}]})).unwrap_err().to_string();
|
||||
assert!(e.contains("`edits[0].a.b`; it takes: name, newName, delete"), "{e}");
|
||||
// Repeated and unknown names keep the command's own errors.
|
||||
let e = s.execute("view.saved.edit", &json!({"edits": [{"name": "plain", "newName": "c[1].d"}]})).unwrap_err().to_string();
|
||||
assert!(e.contains("exists"), "{e}");
|
||||
let e = s.execute("view.saved.edit", &json!({"name": "", "delete": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("no view named"), "{e}");
|
||||
}
|
||||
|
||||
/// A refused call during a drag leaves the drag running and adds no undo step; canceling the
|
||||
/// drag then leaves the history as it was.
|
||||
#[test]
|
||||
fn a_refused_call_leaves_an_interaction_alone() {
|
||||
let mut s = session_with_views(&["A"]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.begin_interaction("Move").unwrap();
|
||||
assert!(s.execute("view.saved.new", &json!({"name": 5, "center": [0, 0], "zoom": 1})).is_err());
|
||||
assert!(s.doc().unwrap().interaction.is_some());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
s.cancel_interaction().unwrap();
|
||||
assert!(s.doc().unwrap().interaction.is_none());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
assert_eq!(names(&mut s), ["A"]);
|
||||
}
|
||||
|
||||
/// Edit Views… is off until the document has a view.
|
||||
#[test]
|
||||
fn edit_views_needs_a_saved_view() {
|
||||
|
||||
@@ -368,7 +368,7 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
q["ids"] = ids.clone();
|
||||
}
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
let result = (spec.run)(s, &q)?;
|
||||
let result = super::run_checked(s, spec, &q)?;
|
||||
if clear_stroke {
|
||||
s.paint.stroke = Paint::None;
|
||||
}
|
||||
|
||||
@@ -58,6 +58,9 @@ pub struct DocState {
|
||||
/// View Opacity Mask (Alt-click the mask thumbnail): the masked object whose mask the canvas
|
||||
/// shows alone, in greyscale, while that mask is edited (see [`DocState::shown_mask`]).
|
||||
pub mask_view: Option<NodeId>,
|
||||
/// Check Spelling's Ignore All: the words (as craft-proof keys them, lower case) a spelling
|
||||
/// check of this document skips. Kept while the document is open: not saved, not undoable.
|
||||
pub spelling_ignored: std::collections::BTreeSet<String>,
|
||||
/// View → Show Transparency Grid, per document (saved view state, not undoable).
|
||||
pub transparency_grid: bool,
|
||||
/// The format Save writes ([`cmd::fileio::SAVE_FORMATS`]): the one the document was opened
|
||||
@@ -109,6 +112,8 @@ pub struct DocState {
|
||||
pub opened_by: Option<Arc<file_access::AutomationRoots>>,
|
||||
/// What [`DocState::any_empty_artboards`] last measured. Not saved.
|
||||
empty_artboards: std::cell::RefCell<EmptyArtboards>,
|
||||
/// What [`DocState::any_art_to_fit`] last measured. Not saved.
|
||||
art_to_fit: std::cell::RefCell<Option<ArtToFit>>,
|
||||
}
|
||||
|
||||
/// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that
|
||||
@@ -121,10 +126,25 @@ struct EmptyArtboards {
|
||||
any: bool,
|
||||
}
|
||||
|
||||
/// Whether an unlocked artboard of those asked about has art that Fit to Artwork Bounds fits it
|
||||
/// to, with what was measured: the document (held as [`EmptyArtboards::doc`] holds it), the
|
||||
/// artboards, and the generations of what the measure reads outside the document. One is kept for
|
||||
/// each open document, and its weak reference keeps the measured document's allocation (not its
|
||||
/// contents) until the next measure or until the document closes.
|
||||
#[derive(Clone, Debug)]
|
||||
struct ArtToFit {
|
||||
doc: std::sync::Weak<Document>,
|
||||
indices: Vec<usize>,
|
||||
outside: (u64, u64),
|
||||
any: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many times [`DocState::any_empty_artboards`] measured a document on this thread.
|
||||
pub(crate) static EMPTY_ARTBOARD_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`DocState::any_art_to_fit`] measured a document on this thread.
|
||||
pub(crate) static ART_TO_FIT_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
@@ -288,6 +308,7 @@ impl DocState {
|
||||
uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
opened_as_tab: true,
|
||||
mask_view: None,
|
||||
spelling_ignored: Default::default(),
|
||||
transparency_grid,
|
||||
format: "vectorcraft",
|
||||
save_options: Default::default(),
|
||||
@@ -305,6 +326,7 @@ impl DocState {
|
||||
last_perspective: None,
|
||||
opened_by: file_access::current(),
|
||||
empty_artboards: Default::default(),
|
||||
art_to_fit: Default::default(),
|
||||
}
|
||||
}
|
||||
/// `measure`'s answer for the document now. `measure` runs once for each version of the document,
|
||||
@@ -319,6 +341,38 @@ impl DocState {
|
||||
}
|
||||
last.any
|
||||
}
|
||||
/// Whether an unlocked artboard of `indices` has art that Fit to Artwork Bounds fits it to. A
|
||||
/// menu asks on every frame it is open, and measuring builds the solids of 3D effects, so the
|
||||
/// answer is kept for this version of the document and those artboards, and a change of the
|
||||
/// selection or the view keeps it. It is measured again when what the measure reads outside the
|
||||
/// document changes: the installed plug-ins, whose effects draw art, and the installed fonts,
|
||||
/// which set the bounds of all type.
|
||||
pub fn any_art_to_fit(&self, indices: &[usize]) -> bool {
|
||||
self.any_art_to_fit_with(indices, (vectorcraft_plugins::registry::revision(), vectorcraft_text::FontDb::global().generation()))
|
||||
}
|
||||
/// [`Self::any_art_to_fit`], with `outside` the generations of the plug-ins and the fonts.
|
||||
pub(crate) fn any_art_to_fit_with(&self, indices: &[usize], outside: (u64, u64)) -> bool {
|
||||
// Measuring runs renderer and plug-in code; should it ever ask again while measuring, it
|
||||
// is measured without being kept rather than borrowed twice.
|
||||
let Ok(mut last) = self.art_to_fit.try_borrow_mut() else {
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
return indices.iter().filter_map(|i| self.doc.artboards.get(*i)).any(|a| !a.locked && r.art_bounds_on(&self.doc, a.rect).is_some());
|
||||
};
|
||||
if let Some(k) = last.as_ref()
|
||||
&& std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&self.doc))
|
||||
&& k.indices == indices
|
||||
&& k.outside == outside
|
||||
{
|
||||
return k.any;
|
||||
}
|
||||
#[cfg(test)]
|
||||
ART_TO_FIT_MEASURES.with(|c| c.set(c.get() + 1));
|
||||
// One renderer measures every artboard: each object once.
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
let any = indices.iter().filter_map(|i| self.doc.artboards.get(*i)).any(|a| !a.locked && r.art_bounds_on(&self.doc, a.rect).is_some());
|
||||
*last = Some(ArtToFit { doc: Arc::downgrade(&self.doc), indices: indices.to_vec(), outside, any });
|
||||
any
|
||||
}
|
||||
/// Unsaved changes: the document differs from the saved one (selection changes and changes that
|
||||
/// are not edits to save don't count, [`DocState::same_content`]).
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
|
||||
@@ -12,6 +12,7 @@ pub mod guard;
|
||||
pub mod inspect;
|
||||
pub mod journal;
|
||||
pub mod link_watch;
|
||||
pub mod schemas;
|
||||
pub mod steps;
|
||||
pub mod store;
|
||||
mod tooling;
|
||||
@@ -148,15 +149,28 @@ pub struct Session {
|
||||
/// Where the saved PDF presets are kept, one file each; `None`: only for the session
|
||||
/// ([`Session::attach_pdf_preset_store`]).
|
||||
pdf_preset_dir: Option<std::path::PathBuf>,
|
||||
/// The custom dictionary file Edit › Spelling › Add and Edit Custom Dictionary save to; `None`:
|
||||
/// the words are kept only for the process ([`Session::attach_custom_dictionary`]).
|
||||
dictionary_file: Option<std::path::PathBuf>,
|
||||
/// Where the ICC profiles `color.loadProfile` loads are kept; `None`: only for the process
|
||||
/// ([`Session::attach_profile_store`]).
|
||||
profile_dir: Option<std::path::PathBuf>,
|
||||
/// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process
|
||||
/// ([`Session::attach_plugin_store`]).
|
||||
plugin_dir: Option<std::path::PathBuf>,
|
||||
/// The plug-in ids whose grant in the plug-in store should be gone but could not be removed:
|
||||
/// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful
|
||||
/// [`Session::store_grant`] for the id takes it out.
|
||||
ignored_plugin_grants: std::sync::Mutex<std::collections::BTreeSet<String>>,
|
||||
/// A filter's output that a run made in the background handed in for `plugin.run` to apply
|
||||
/// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it.
|
||||
plugin_output: Option<cmd::plugin::HandedIn>,
|
||||
/// What a person approved for the next `plugin.install` ([`Session::approve_plugin_install`]);
|
||||
/// that install spends it, whatever it does.
|
||||
plugin_install_approval: Option<cmd::plugin::InstallApproval>,
|
||||
/// `plugin.install` takes `grant` and `allowHeavy` from any request
|
||||
/// ([`Session::allow_plugin_grants_from_requests`]).
|
||||
plugin_grants_from_requests: bool,
|
||||
/// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first; not saved.
|
||||
pub recent_urls: Vec<String>,
|
||||
/// The saved tracing presets' revision and latest changes ([`Session::trace_presets_revision`]).
|
||||
|
||||
@@ -41,6 +41,12 @@ pub struct Prefs {
|
||||
/// Align panel menu › Align to Glyph Bounds › Area Text: the same for area type, instead of
|
||||
/// its frame.
|
||||
pub align_glyph_bounds_area: bool,
|
||||
/// Preferences › Type › Glyph Bounds › Measure Type by Glyph Bounds (also in the Transform
|
||||
/// panel menu): the bounding box, the Transform panel's, Control bar's and Properties panel's X,
|
||||
/// Y, W and H, and `object.setBounds` measure each point type object selected as an object (not
|
||||
/// inside a selected group) by the ink of its glyphs instead of its em box
|
||||
/// ([`crate::Session::bounds_measure`]).
|
||||
pub type_glyph_bounds: bool,
|
||||
/// Artboard Options › Fade Region Outside Artboard: while the Artboard tool is active, the
|
||||
/// canvas draws everything outside the artboards darker, the pasteboard and the art on it.
|
||||
pub fade_region_outside_artboard: bool,
|
||||
@@ -114,6 +120,8 @@ pub struct Prefs {
|
||||
// Guides & Grid
|
||||
pub guide_color: String,
|
||||
pub guide_style: String,
|
||||
/// Lock Guides by Default: the app starts with View › Guides › Lock Guides on.
|
||||
pub lock_guides_by_default: bool,
|
||||
pub grid_color: String,
|
||||
pub grid_style: String,
|
||||
pub gridline_every: f64,
|
||||
@@ -370,6 +378,7 @@ impl Default for Prefs {
|
||||
use_preview_bounds: false,
|
||||
align_glyph_bounds_point: false,
|
||||
align_glyph_bounds_area: false,
|
||||
type_glyph_bounds: false,
|
||||
fade_region_outside_artboard: true,
|
||||
artboard_update_while_dragging: true,
|
||||
display_print_size: false,
|
||||
@@ -421,6 +430,7 @@ impl Default for Prefs {
|
||||
identify_objects_by: s("objectName"),
|
||||
guide_color: s("#4affff"),
|
||||
guide_style: s("lines"),
|
||||
lock_guides_by_default: false,
|
||||
grid_color: s("#c8c8c8"),
|
||||
grid_style: s("lines"),
|
||||
gridline_every: 72.0,
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
//! The commands' parameter schemas ([`vectorcraft_apischema::ParamSchema`]) and the API level they
|
||||
//! belong to.
|
||||
//!
|
||||
//! A command with a schema (`CommandSpec::schema`) has its params checked against it by
|
||||
//! [`crate::Session::execute`] before it runs ([`check`]), and by the steps that run a command's
|
||||
//! implementation directly ([`crate::cmd::run_checked`]): a value of the wrong type, out of range
|
||||
//! or not in its list, a missing required parameter or an unknown key is refused with a parameter
|
||||
//! error naming the parameter, and the command does not run, so the document and its undo history
|
||||
//! stay as they were. An omitted value with a default takes it. The steps of a `command.batch` or
|
||||
//! an `action.batch` are checked before the first one runs. Saved steps
|
||||
//! ([`crate::Session::replay`]) keep their keys a schema doesn't name, and their values are checked.
|
||||
//! The command's `params` text is the text its schema writes, and `engine.commands` lists the schema
|
||||
//! of each command that has one.
|
||||
//!
|
||||
//! [`API_VERSION`] goes up by one whenever a schema of a built-in command changes, and
|
||||
//! [`SCHEMA_HASHES`] gains a row with the new level and [`schema_hash`]: a test fails while the
|
||||
//! newest row does not match the schemas. Commands that plug-ins add have no schema.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_apischema::{ParamError, Problem};
|
||||
|
||||
use crate::cmd::params::unknown;
|
||||
use crate::cmd::{CommandSpec, bad, command_specs};
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// The API level of the commands' parameters.
|
||||
pub const API_VERSION: u32 = 2;
|
||||
|
||||
/// [`schema_hash`] at each API level, oldest first; the last row is [`API_VERSION`]'s.
|
||||
pub const SCHEMA_HASHES: &[(u32, u64)] = &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653)];
|
||||
|
||||
/// The hash of every built-in command's schema ([`vectorcraft_apischema::hash`]).
|
||||
pub fn schema_hash() -> u64 {
|
||||
vectorcraft_apischema::hash(command_specs().iter().filter_map(|c| Some((c.id, c.schema?))))
|
||||
}
|
||||
|
||||
/// Each built-in schema that is wrong in itself, with why ([`vectorcraft_apischema::ParamSchema::definition_problem`]).
|
||||
/// Worked out once, the first time a command with a schema runs.
|
||||
fn definition_problems() -> &'static [(&'static str, String)] {
|
||||
static PROBLEMS: OnceLock<Vec<(&'static str, String)>> = OnceLock::new();
|
||||
PROBLEMS.get_or_init(|| command_specs().iter().filter_map(|c| Some((c.id, c.schema?.definition_problem()?))).collect())
|
||||
}
|
||||
|
||||
/// `params` checked against the schema of `spec`: a parameter error under the command's id for the
|
||||
/// first problem, or the params with the defaults of omitted values filled in (`None` when the
|
||||
/// command has no schema or nothing was filled in, so `params` is used as it is). A command with no
|
||||
/// schema costs one branch. `saved`: the params of a saved step, whose keys the schema doesn't name
|
||||
/// pass. A schema that is wrong in itself is an internal error, and its command does not run.
|
||||
pub(crate) fn check(spec: &CommandSpec, params: &Value, saved: bool) -> Result<Option<Value>> {
|
||||
let Some(schema) = spec.schema else { return Ok(None) };
|
||||
if let Some((_, why)) = definition_problems().iter().find(|(id, _)| *id == spec.id) {
|
||||
return Err(EngineError::Internal { cmd: spec.id.into(), msg: why.clone() });
|
||||
}
|
||||
let checked = if saved { schema.validate_saved(params) } else { schema.validate(params) };
|
||||
checked.map_err(|e| param_error(spec.id, &e))
|
||||
}
|
||||
|
||||
/// The parameter error of command `id` for `e`, in the words the message catalogs translate. An
|
||||
/// unknown top-level key is reported as the commands without a schema report it, with the nearest
|
||||
/// key.
|
||||
fn param_error(id: &str, e: &ParamError) -> EngineError {
|
||||
let path = &e.path;
|
||||
match &e.problem {
|
||||
Problem::NotAnObject { got } => bad(id, format!("the params must be an object, not {got}")),
|
||||
Problem::Unknown { keys } if !path.contains(['.', '[']) => unknown(id, path, keys),
|
||||
Problem::Unknown { keys } if keys.is_empty() => bad(id, format!("unknown parameter `{path}`; the object takes no keys")),
|
||||
Problem::Unknown { keys } => bad(id, format!("unknown parameter `{path}`; it takes: {keys}", keys = keys.join(", "))),
|
||||
Problem::Missing => bad(id, format!("missing `{path}`")),
|
||||
Problem::WrongType { expected, got } => bad(id, format!("`{path}` must be {expected}, not {got}")),
|
||||
Problem::TooDeep => EngineError::Internal { cmd: id.into(), msg: e.to_string() },
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../../apischema/src/conformance.rs"]
|
||||
mod conformance;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use proptest::prelude::*;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_apischema::{Bound, Omitted, Param, ParamSchema, Type};
|
||||
|
||||
use super::conformance::{check_schema, instance_valid};
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
|
||||
fn schemas() -> Vec<(&'static str, &'static ParamSchema)> {
|
||||
command_specs().iter().filter_map(|c| Some((c.id, c.schema?))).collect()
|
||||
}
|
||||
|
||||
/// The params text of a command with a schema is the text the schema writes.
|
||||
#[test]
|
||||
fn params_text_is_the_text_the_schema_writes() {
|
||||
assert!(!schemas().is_empty());
|
||||
for c in command_specs() {
|
||||
if let Some(schema) = c.schema {
|
||||
assert_eq!(c.params, schema.params_text(), "{}", c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A schema changed without a new API level (and a new row of hashes) fails here: add the row
|
||||
/// `(API_VERSION + 1, <the hash below>)` and raise [`API_VERSION`].
|
||||
#[test]
|
||||
fn schema_hash_matches_the_api_version() {
|
||||
let last = SCHEMA_HASHES.last().copied();
|
||||
assert_eq!(last.map(|(level, _)| level), Some(API_VERSION), "the last row of SCHEMA_HASHES is not API_VERSION's");
|
||||
assert_eq!(last.map(|(_, hash)| hash), Some(schema_hash()), "the schemas changed: {:#x}", schema_hash());
|
||||
assert!(SCHEMA_HASHES.windows(2).all(|w| w[0].0 < w[1].0), "the API levels go up");
|
||||
}
|
||||
|
||||
/// Every schema is sound in itself ([`ParamSchema::definition_problem`]), so no command is
|
||||
/// refused for its schema, and no parameter or command is newer than the API level.
|
||||
#[test]
|
||||
fn schemas_are_sound_and_levels_are_known() {
|
||||
fn walk(id: &str, params: &[Param]) {
|
||||
for p in params {
|
||||
assert!(p.since >= 1 && p.since <= API_VERSION, "{id}.{}", p.name);
|
||||
if let Type::Object(inner) | Type::Array(&Type::Object(inner)) = p.ty {
|
||||
walk(id, inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(definition_problems(), &[]);
|
||||
for (id, schema) in schemas() {
|
||||
assert!(schema.since >= 1 && schema.since <= API_VERSION, "{id}");
|
||||
walk(id, schema.params);
|
||||
}
|
||||
}
|
||||
|
||||
/// Each command's defaults are of its parameter's type (an omitted value takes them), with
|
||||
/// which ones are filled in.
|
||||
#[test]
|
||||
fn declared_defaults_are_filled_in() {
|
||||
let new_view = command_specs().iter().find(|c| c.id == "view.saved.new").and_then(|c| c.schema).unwrap();
|
||||
let filled = new_view.validate(&json!({"center": [1, 2], "zoom": 1})).unwrap().unwrap();
|
||||
assert_eq!(filled["rotation"], json!(0));
|
||||
assert!(filled.get("name").is_none(), "the command works out the name");
|
||||
assert!(new_view.param("rotation").is_some_and(|p| matches!(p.omitted, Omitted::Value("0"))));
|
||||
}
|
||||
|
||||
/// A refusal from the schema names the parameter, and the command does not run.
|
||||
#[test]
|
||||
fn a_refused_value_names_the_parameter_under_the_command() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": -1})).unwrap_err().to_string();
|
||||
assert!(e.contains("view.saved.new") && e.contains("`zoom` must be a number > 0, not -1"), "{e}");
|
||||
let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": 1, "rotaton": 5})).unwrap_err().to_string();
|
||||
assert!(e.contains("unknown parameter `rotaton`; did you mean `rotation`?"), "{e}");
|
||||
let e = s.execute("view.saved.new", &Value::Null).unwrap_err().to_string();
|
||||
assert!(e.contains("view.saved.new") && e.contains("missing `center`"), "{e}");
|
||||
assert!(s.doc().unwrap().doc.views.is_empty());
|
||||
assert!(s.doc().unwrap().history.undo.is_empty());
|
||||
}
|
||||
|
||||
/// The key check runs before the schema, so a misspelled key is the error even when a value is
|
||||
/// bad too, and the schema reports the value when the keys are right.
|
||||
#[test]
|
||||
fn a_misspelled_key_is_reported_before_a_bad_value() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": -1, "rotaton": 5})).unwrap_err().to_string();
|
||||
assert!(e.contains("did you mean `rotation`?"), "{e}");
|
||||
let e = s.execute("view.saved.new", &json!({"center": "here", "zoom": -1})).unwrap_err().to_string();
|
||||
assert!(e.contains("`center` must be [x, y] (two numbers), not \"here\""), "{e}");
|
||||
}
|
||||
|
||||
/// Saved steps keep a retired key, at the top level and inside `edits`, and a bad value is
|
||||
/// still refused, with no undo step; the journal keeps the params as given.
|
||||
#[test]
|
||||
fn saved_steps_keep_retired_keys_and_check_values() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let retired = json!({"name": "A", "center": [1, 2], "zoom": 2, "fitArt": true});
|
||||
assert!(s.execute("view.saved.new", &retired).is_err());
|
||||
s.replay("view.saved.new", &retired).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.views[0].name, "A");
|
||||
let last = s.journal.last().unwrap();
|
||||
assert_eq!(last.1, retired, "the journal has the params as given, with no default filled in");
|
||||
s.replay("view.saved.edit", &json!({"edits": [{"name": "A", "newName": "B", "was": 1}]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.views[0].name, "B");
|
||||
assert!(s.execute("view.saved.edit", &json!({"edits": [{"name": "B", "newName": "C", "was": 1}]})).is_err());
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let e = s.replay("view.saved.new", &json!({"center": [1, 2], "zoom": 0, "fitArt": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("`zoom`"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
// A frontend that replays through its own path sets the flag, and gets the same rule.
|
||||
let outer = s.set_replaying(true);
|
||||
s.execute("view.saved.new", &json!({"name": "C", "center": [1, 2], "zoom": 2, "fitArt": true})).unwrap();
|
||||
s.set_replaying(outer);
|
||||
}
|
||||
|
||||
/// A batch step a schema refuses stops the batch before its first step runs.
|
||||
#[test]
|
||||
fn a_batch_is_checked_against_the_schemas_before_its_first_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let step = |p: Value| json!({"command": "view.saved.new", "params": p});
|
||||
for (last, named) in [
|
||||
(step(json!({"center": [0, 0], "zoom": 0})), "`zoom`"),
|
||||
(step(json!({"center": [0, 0]})), "`zoom`"),
|
||||
(json!({"command": "view.saved.new"}), "`center`"),
|
||||
] {
|
||||
let batch = json!({"commands": [step(json!({"name": "First", "center": [0, 0], "zoom": 1})), last]});
|
||||
let e = s.execute("command.batch", &batch).unwrap_err().to_string();
|
||||
assert!(e.contains("view.saved.new") && e.contains(named), "{e}");
|
||||
assert!(s.doc().unwrap().doc.views.is_empty(), "the first step did not run: {e}");
|
||||
assert!(s.doc().unwrap().history.undo.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Values and keys far larger than any a command takes are refused with a short error and no
|
||||
/// panic. Nested values are leaked because dropping one recurses per level.
|
||||
#[test]
|
||||
fn hostile_values_are_refused_with_a_short_error() {
|
||||
fn deep(levels: usize) -> Value {
|
||||
(0..levels).fold(json!(1), |inner, _| Value::Array(vec![inner]))
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let huge = "z".repeat(2_000_000);
|
||||
for params in [
|
||||
json!({ huge.as_str(): 1, "center": [0, 0], "zoom": 1 }),
|
||||
json!({"center": [0, 0], "zoom": huge}),
|
||||
json!({"center": huge, "zoom": 1}),
|
||||
json!({"center": [0, 0], "zoom": 1, "name": [huge]}),
|
||||
json!({"center": [0, 0], "zoom": f64::MAX, "rotation": f64::INFINITY}),
|
||||
] {
|
||||
let e = s.execute("view.saved.new", ¶ms).unwrap_err().to_string();
|
||||
assert!(e.chars().count() < 400, "{} chars", e.chars().count());
|
||||
}
|
||||
let e = s.execute("view.saved.edit", &json!({"edits": [{"name": "A", huge.as_str(): 1}]})).unwrap_err().to_string();
|
||||
assert!(e.chars().count() < 400, "{} chars", e.chars().count());
|
||||
let nested = json!({"center": [0, 0]});
|
||||
let Value::Object(mut map) = nested else { panic!() };
|
||||
map.insert("zoom".into(), deep(500_000));
|
||||
let params = Value::Object(map);
|
||||
let e = s.execute("view.saved.new", ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains("`zoom`") && e.chars().count() < 400, "{e}");
|
||||
std::mem::forget(params);
|
||||
assert!(s.doc().unwrap().doc.views.is_empty());
|
||||
assert!(s.doc().unwrap().history.undo.is_empty());
|
||||
}
|
||||
|
||||
/// Each command's JSON schema follows the 2020-12 rules, and a validator of those rules, which
|
||||
/// shares no code with the writer, gives the same answer as the schema check. None of these
|
||||
/// schemas has a lenient parameter.
|
||||
#[test]
|
||||
fn the_listed_schemas_follow_2020_12_and_agree_with_the_check() {
|
||||
let cases: &[(&str, Value)] = &[
|
||||
("view.capsLock", json!({})),
|
||||
("view.capsLock", json!({"on": true})),
|
||||
("view.capsLock", json!({"on": "yes"})),
|
||||
("view.capsLock", json!({"on": null})),
|
||||
("view.capsLock", json!({"of": true})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 1})),
|
||||
("view.saved.new", json!({"center": [0.5, -2], "zoom": 0.001, "rotation": -30, "name": "A"})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 1, "name": null})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 1, "rotation": null})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 0})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": -1})),
|
||||
("view.saved.new", json!({"center": [0], "zoom": 1})),
|
||||
("view.saved.new", json!({"center": [0, 0, 0], "zoom": 1})),
|
||||
("view.saved.new", json!({"center": [0, "0"], "zoom": 1})),
|
||||
("view.saved.new", json!({"zoom": 1})),
|
||||
("view.saved.new", json!({"center": [0, 0]})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 1, "name": 5})),
|
||||
("view.saved.edit", json!({})),
|
||||
("view.saved.edit", json!({"name": "A", "newName": "B"})),
|
||||
("view.saved.edit", json!({"name": null, "delete": null})),
|
||||
("view.saved.edit", json!({"edits": []})),
|
||||
("view.saved.edit", json!({"edits": null})),
|
||||
("view.saved.edit", json!({"edits": [{"name": "A", "delete": true}, {"name": "B", "newName": null}]})),
|
||||
("view.saved.edit", json!({"edits": [{"newName": "B"}]})),
|
||||
("view.saved.edit", json!({"edits": [{"name": "A", "delete": 1}]})),
|
||||
("view.saved.edit", json!({"edits": [{"name": "A", "x": 1}]})),
|
||||
("view.saved.edit", json!({"edits": {"name": "A"}})),
|
||||
("view.saved.list", json!({})),
|
||||
("view.saved.list", json!({"all": true})),
|
||||
("view.transparencyGrid", json!({})),
|
||||
("view.transparencyGrid", json!({"on": null})),
|
||||
("view.transparencyGrid", json!({"on": false})),
|
||||
("view.transparencyGrid", json!({"on": 1})),
|
||||
("view.snapToGlyph.options", json!({"bounds": false, "angular": true})),
|
||||
("view.snapToGlyph.options", json!({"bounds": null})),
|
||||
("view.capsLock", json!(null)),
|
||||
("view.saved.new", json!(null)),
|
||||
("view.saved.edit", json!(null)),
|
||||
("view.saved.list", json!(null)),
|
||||
("view.transparencyGrid", json!(null)),
|
||||
("view.snapToGlyph.options", json!(null)),
|
||||
("view.capsLock", json!([])),
|
||||
("view.saved.new", json!(5)),
|
||||
("view.transparencyGrid", json!("on")),
|
||||
("engine.apiReference", json!({})),
|
||||
("engine.apiReference", json!(null)),
|
||||
("engine.apiReference", json!({"prefix": "view."})),
|
||||
("engine.apiReference", json!([])),
|
||||
];
|
||||
assert_eq!(schemas().len(), 7);
|
||||
for (id, schema) in schemas() {
|
||||
let written = schema.to_json();
|
||||
check_schema(&written, id).unwrap_or_else(|e| panic!("{e}\n{written:#}"));
|
||||
assert!(cases.iter().any(|(c, _)| *c == id), "{id} has no cases");
|
||||
}
|
||||
for (id, params) in cases {
|
||||
let schema = schemas().into_iter().find(|(c, _)| c == id).unwrap().1;
|
||||
assert_eq!(schema.validate(params).is_ok(), instance_valid(&schema.to_json(), params), "{id} {params}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine's own listing carries the schema of each command that has one.
|
||||
#[test]
|
||||
fn engine_commands_list_the_schemas() {
|
||||
let s = Session::new();
|
||||
let all = s.commands();
|
||||
let grid = all.iter().find(|c| c.id == "view.transparencyGrid").and_then(|c| c.schema.clone()).unwrap();
|
||||
assert_eq!(grid["$schema"], vectorcraft_apischema::DIALECT);
|
||||
assert_eq!(grid["properties"]["on"]["x-default"], "toggle");
|
||||
let listed = serde_json::to_value(all.iter().find(|c| c.id == "view.saved.new").unwrap()).unwrap();
|
||||
assert_eq!(listed["schema"]["required"], json!(["center", "zoom"]));
|
||||
let without = serde_json::to_value(all.iter().find(|c| c.id == "file.new").unwrap()).unwrap();
|
||||
assert!(without.get("schema").is_none());
|
||||
}
|
||||
|
||||
/// The listing gives each command with a schema an `inputSchema`, the form an MCP tool's input
|
||||
/// schema takes: the same schema with the root `type` `"object"`, and every other keyword kept,
|
||||
/// nested parameters, required names, defaults and VectorCraft's own fields included. A command
|
||||
/// with no schema lists neither.
|
||||
#[test]
|
||||
fn engine_commands_list_an_input_schema_with_an_object_root() {
|
||||
let s = Session::new();
|
||||
let listed: Vec<Value> = s.commands().iter().map(|c| serde_json::to_value(c).unwrap()).collect();
|
||||
let mut with_schema = 0;
|
||||
for c in &listed {
|
||||
let id = c["id"].as_str().unwrap();
|
||||
let Some(schema) = c.get("schema") else {
|
||||
assert!(c.get("inputSchema").is_none(), "{id}");
|
||||
continue;
|
||||
};
|
||||
with_schema += 1;
|
||||
let input = c.get("inputSchema").unwrap_or_else(|| panic!("{id} has no inputSchema"));
|
||||
assert_eq!(input["type"], "object", "{id}");
|
||||
assert_eq!(input["$schema"], vectorcraft_apischema::DIALECT, "{id}");
|
||||
check_schema(input, id).unwrap_or_else(|e| panic!("{e}\n{input:#}"));
|
||||
assert!(!instance_valid(input, &Value::Null), "{id}: the arguments are an object");
|
||||
let without_type = |v: &Value| {
|
||||
let mut v = v.clone();
|
||||
v.as_object_mut().map(|o| o.remove("type"));
|
||||
v
|
||||
};
|
||||
assert_eq!(without_type(schema), without_type(input), "{id}");
|
||||
}
|
||||
assert_eq!(with_schema, schemas().len());
|
||||
let get = |id: &str| listed.iter().find(|c| c["id"] == id).unwrap();
|
||||
// No required parameter: the schema also takes null, the input schema does not.
|
||||
let list = get("view.saved.list");
|
||||
assert_eq!(list["schema"]["type"], json!(["object", "null"]));
|
||||
assert_eq!(list["inputSchema"]["type"], "object");
|
||||
// Required parameters and their constraints are kept.
|
||||
let new_view = get("view.saved.new");
|
||||
assert_eq!(new_view["inputSchema"]["required"], json!(["center", "zoom"]));
|
||||
assert_eq!(new_view["inputSchema"]["properties"], new_view["schema"]["properties"]);
|
||||
// Nested objects in an array keep their keys.
|
||||
let edit = &get("view.saved.edit")["inputSchema"]["properties"]["edits"];
|
||||
assert!(edit.to_string().contains("newName"), "{edit}");
|
||||
assert!(get("file.new").get("inputSchema").is_none());
|
||||
}
|
||||
|
||||
/// A deprecated command and a deprecated parameter keep their deprecation in the input schema.
|
||||
#[test]
|
||||
fn an_input_schema_keeps_deprecation() {
|
||||
static PARAMS: [Param; 2] = [Param::new("old", Type::Boolean).optional().deprecated(1), Param::new("on", Type::Boolean).optional()];
|
||||
let schema = ParamSchema::new(&PARAMS, "Old command.").deprecated(1).to_json();
|
||||
let input = crate::cmd::input_schema(&schema);
|
||||
check_schema(&input, "synthetic").unwrap_or_else(|e| panic!("{e}\n{input:#}"));
|
||||
assert_eq!(schema["type"], json!(["object", "null"]));
|
||||
assert_eq!(input["type"], "object");
|
||||
assert_eq!(input["deprecated"], true);
|
||||
assert_eq!(input["x-deprecatedSince"], 1);
|
||||
assert_eq!(input["properties"]["old"], schema["properties"]["old"]);
|
||||
assert_eq!(input["properties"]["old"]["deprecated"], true);
|
||||
assert_eq!(input["description"], "Old command.");
|
||||
}
|
||||
|
||||
/// The listing says what each View command changes when it runs. Only the commands that make an
|
||||
/// undo step list `document`.
|
||||
#[test]
|
||||
fn each_view_command_lists_what_it_writes() {
|
||||
let listed: Vec<(&str, Value)> = schemas().into_iter().map(|(id, schema)| (id, schema.to_json()["x-writes"].clone())).collect();
|
||||
let expected = [
|
||||
("view.capsLock", "session"),
|
||||
("view.saved.new", "document"),
|
||||
("view.saved.edit", "document"),
|
||||
("view.saved.list", "nothing"),
|
||||
("view.transparencyGrid", "session"),
|
||||
("view.snapToGlyph.options", "preferences"),
|
||||
];
|
||||
for (id, writes) in expected {
|
||||
let got = listed.iter().find(|(c, _)| *c == id).map(|(_, w)| w.clone());
|
||||
assert_eq!(got, Some(json!(writes)), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Values of type `ty` that pass it.
|
||||
fn valid(ty: Type) -> BoxedStrategy<Value> {
|
||||
fn number(min: Option<Bound>, max: Option<Bound>) -> BoxedStrategy<Value> {
|
||||
let low = match min {
|
||||
Some(Bound::Inclusive(a)) => a,
|
||||
Some(Bound::Exclusive(a)) => a + 1e-6_f64.max(a.abs() * 1e-9),
|
||||
None => -1e6,
|
||||
};
|
||||
let high = match max {
|
||||
Some(Bound::Inclusive(b)) => b,
|
||||
Some(Bound::Exclusive(b)) => b - 1e-6_f64.max(b.abs() * 1e-9),
|
||||
None => low.max(0.0) + 1e6,
|
||||
};
|
||||
(low..=high).prop_map(|x| json!(x)).boxed()
|
||||
}
|
||||
match ty {
|
||||
Type::Number { min, max, .. } => number(min, max),
|
||||
Type::Integer { min, max } => (min.unwrap_or(-1_000_000)..=max.unwrap_or(1_000_000)).prop_map(|x| json!(x)).boxed(),
|
||||
Type::Boolean => any::<bool>().prop_map(Value::from).boxed(),
|
||||
Type::String => "[ -~]{0,12}".prop_map(Value::from).boxed(),
|
||||
Type::Enum(names) => prop::sample::select(names.to_vec()).prop_map(Value::from).boxed(),
|
||||
Type::Id => (0u64..10_000).prop_map(Value::from).boxed(),
|
||||
Type::Ids => prop::collection::vec(0u64..10_000, 0..4).prop_map(Value::from).boxed(),
|
||||
Type::Color => Just(json!("#336699")).boxed(),
|
||||
Type::Point => (-1e6..1e6f64, -1e6..1e6f64).prop_map(|(x, y)| json!([x, y])).boxed(),
|
||||
Type::Object(params) => valid_object(params),
|
||||
Type::Array(item) => prop::collection::vec(valid(*item), 0..3).prop_map(Value::from).boxed(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Objects that pass `params`: each required parameter, and each optional one or not.
|
||||
fn valid_object(params: &'static [Param]) -> BoxedStrategy<Value> {
|
||||
let parts: Vec<BoxedStrategy<Option<(String, Value)>>> = params
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let entry = valid(p.ty).prop_map(move |v| Some((p.name.to_string(), v)));
|
||||
if p.required { entry.boxed() } else { prop_oneof![Just(None), entry].boxed() }
|
||||
})
|
||||
.collect();
|
||||
parts.prop_map(|entries| Value::Object(entries.into_iter().flatten().collect::<Map<String, Value>>())).boxed()
|
||||
}
|
||||
|
||||
/// Commands with a schema and params for them that pass it.
|
||||
fn valid_calls() -> BoxedStrategy<(&'static str, Value)> {
|
||||
let calls: Vec<BoxedStrategy<(&'static str, Value)>> =
|
||||
schemas().into_iter().map(|(id, schema)| valid_object(schema.params).prop_map(move |p| (id, p)).boxed()).collect();
|
||||
prop::strategy::Union::new(calls).boxed()
|
||||
}
|
||||
|
||||
proptest! {
|
||||
/// Params that pass a command's schema never get a parameter error about a value's type or
|
||||
/// range from the command itself: the schema refuses whatever the command's own checks would.
|
||||
#[test]
|
||||
fn schema_valid_params_get_no_type_error_from_the_command((id, params) in valid_calls(), views in 0usize..3) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
for i in 0..views {
|
||||
s.execute("view.saved.new", &json!({"name": format!("V{i}"), "center": [0, 0], "zoom": 1})).unwrap();
|
||||
}
|
||||
match s.execute(id, ¶ms) {
|
||||
Err(EngineError::BadParams { msg, .. }) => {
|
||||
prop_assert!(!msg.contains(" must be ") && !msg.contains("missing") && !msg.contains("unknown parameter"), "{id} {params}: {msg}");
|
||||
}
|
||||
Err(EngineError::Internal { msg, .. }) => prop_assert!(false, "{id} {params} panicked: {msg}"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,9 +80,13 @@ impl Session {
|
||||
brush_libraries: Default::default(),
|
||||
libraries: Default::default(),
|
||||
pdf_preset_dir: None,
|
||||
dictionary_file: None,
|
||||
profile_dir: None,
|
||||
plugin_dir: None,
|
||||
ignored_plugin_grants: Default::default(),
|
||||
plugin_output: None,
|
||||
plugin_install_approval: None,
|
||||
plugin_grants_from_requests: false,
|
||||
recent_urls: vec![],
|
||||
trace_preset_changes: Default::default(),
|
||||
ui_language: None,
|
||||
|
||||
@@ -60,6 +60,11 @@ impl Session {
|
||||
if !self.replaying {
|
||||
self.check_params(id, params)?;
|
||||
}
|
||||
// A command with a parameter schema runs only with params that pass it, and with the
|
||||
// defaults of omitted values filled in; the journal keeps the params as given. Saved steps
|
||||
// keep their keys the schema doesn't name, as above.
|
||||
let checked = crate::schemas::check(spec, params, self.replaying)?;
|
||||
let run_params = checked.as_ref().unwrap_or(params);
|
||||
// Objects given as `id` (where it stands for `ids` of one) or as `ids` beside it are checked
|
||||
// before anything else: a malformed one, or one naming no object, is an error under this
|
||||
// command's id, never the selection in its place. `effect.apply {id: "stylize.dropShadow"}`
|
||||
@@ -126,7 +131,7 @@ impl Session {
|
||||
if let Some(ids) = &select_first {
|
||||
s.execute("select.set", &serde_json::json!({ "ids": ids }))?;
|
||||
}
|
||||
let r = cmd::run_spec(s, spec, params);
|
||||
let r = cmd::run_spec(s, spec, run_params);
|
||||
if r.is_err()
|
||||
&& let Some((uid, selection, layer)) = selected_before
|
||||
&& let Some(st) = s.docs.iter_mut().find(|d| d.uid == uid)
|
||||
|
||||
+145
-37
@@ -28,7 +28,7 @@
|
||||
//! The files are untrusted input like any other: sizes and counts are capped, a file that does not
|
||||
//! parse is skipped with a log record, and every write is atomic.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -62,6 +62,8 @@ pub const DISABLED_FILE: &str = "disabled.json";
|
||||
pub const DISABLED_LOCK: &str = "disabled.lock";
|
||||
/// The file in the plug-in store that holds the permissions the user granted.
|
||||
const GRANTS_FILE: &str = "grants.json";
|
||||
/// The error of a `plugin.remove` that can't remove the plug-in's grant from [`GRANTS_FILE`].
|
||||
pub(crate) const GRANT_NOT_REMOVED: &str = "the plug-in's grant can't be removed from the plug-in store";
|
||||
/// The largest grants file read.
|
||||
const MAX_GRANTS_FILE: u64 = 1 << 20;
|
||||
/// The folder in the plug-in store that holds each plug-in's settings and cache.
|
||||
@@ -110,15 +112,21 @@ fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
|
||||
|
||||
/// The content of `path` when it is at most `max` bytes; the file is never read past `max`.
|
||||
pub(crate) fn read_capped(path: &Path, max: u64) -> Result<Vec<u8>, String> {
|
||||
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
|
||||
let mut bytes = vec![];
|
||||
file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?;
|
||||
let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > max {
|
||||
return Err(too_large(max));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// The first `max + 1` bytes of `path` at most, so that a result longer than `max` shows the file is
|
||||
/// over its cap.
|
||||
fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
|
||||
let mut bytes = vec![];
|
||||
std::fs::File::open(path)?.take(max + 1).read_to_end(&mut bytes)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// What a file over its cap is told (a detail after the file's name, in the log or an error).
|
||||
fn too_large(max: u64) -> String {
|
||||
format!("larger than {max} bytes")
|
||||
@@ -168,13 +176,21 @@ fn lock_disabled(_: &Path) -> Option<std::fs::File> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Remove `dir/file`; a file that isn't there is what was wanted.
|
||||
fn take(dir: &Path, file: &str) {
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: [`Session::put_back_plugin`] fails on this thread, as on a full volume.
|
||||
pub(crate) static PUT_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted.
|
||||
fn take(dir: &Path, file: &str) -> bool {
|
||||
let path = dir.join(file);
|
||||
if let Err(e) = std::fs::remove_file(&path)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
log::warn!("can't remove {}: {e}", path.display());
|
||||
match std::fs::remove_file(&path) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
|
||||
log::warn!("can't remove {}: {e}", path.display());
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,6 +299,9 @@ impl Session {
|
||||
let disabled =
|
||||
read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(disabled);
|
||||
if self.plugin_dir.as_ref() != Some(&dir) {
|
||||
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
}
|
||||
self.plugin_dir = Some(dir);
|
||||
self.load_stored_plugins();
|
||||
}
|
||||
@@ -291,15 +310,18 @@ impl Session {
|
||||
/// disabled (matched by file name, which is made from the id). The launch marker names each
|
||||
/// file while it loads. A module that doesn't load, and one that lists permissions the grants
|
||||
/// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and
|
||||
/// stays in the folder with its grant.
|
||||
/// stays in the folder with its grant. A grant for an id whose stored module lists no
|
||||
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
|
||||
/// the rest of the session ([`Session::plugin_approver`]).
|
||||
pub fn load_stored_plugins(&mut self) {
|
||||
let Some(dir) = self.plugin_dir.clone() else { return };
|
||||
if safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
let grants = stored_grants(&dir);
|
||||
let grants = self.counted_grants(&dir);
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut left = MAX_PLUGIN_STORE;
|
||||
let mut asks_nothing = BTreeSet::new();
|
||||
for path in list_files(&dir, PLUGIN_EXT) {
|
||||
if left == 0 {
|
||||
log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together");
|
||||
@@ -325,6 +347,7 @@ impl Session {
|
||||
let m = plugin.manifest();
|
||||
match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) {
|
||||
Some(g) => {
|
||||
asks_nothing.remove(&m.id);
|
||||
vectorcraft_plugins::registry::grant(g.clone());
|
||||
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id));
|
||||
vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string()));
|
||||
@@ -335,12 +358,24 @@ impl Session {
|
||||
}
|
||||
}
|
||||
Ok(plugin) => {
|
||||
asks_nothing.insert(plugin.id().to_string());
|
||||
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id()));
|
||||
vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string()));
|
||||
}
|
||||
Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let kept = read_grants(&dir);
|
||||
for id in &asks_nothing {
|
||||
vectorcraft_plugins::registry::revoke(id);
|
||||
let named = match &kept {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
};
|
||||
if named && !self.store_grant(id, None) && self.holds_plugin_grant(id) {
|
||||
self.ignore_stored_grant(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the disabled plug-ins saved for the next launch to the plug-in folder → whether they
|
||||
@@ -379,7 +414,8 @@ impl Session {
|
||||
|
||||
/// Whether `plugin` installs without asking the user: it lists no permissions, or this very
|
||||
/// module (its id and SHA-256) was granted every one it lists, in the grants of the attached
|
||||
/// plug-in store when there is one ([`grant_covers`]), else in this process's
|
||||
/// plug-in store when there is one ([`grant_covers`]), not counting a grant that should be gone
|
||||
/// and could not be removed ([`Session::ignore_stored_grant`]), else in this process's
|
||||
/// ([`vectorcraft_plugins::registry::approved`]).
|
||||
pub(crate) fn plugin_approved(&self, plugin: &vectorcraft_plugins::Plugin) -> bool {
|
||||
self.plugin_approver()(plugin)
|
||||
@@ -388,7 +424,7 @@ impl Session {
|
||||
/// [`Session::plugin_approved`] for many plug-ins: reads the store's grants once, when it is
|
||||
/// made, and checks each plug-in against them.
|
||||
pub(crate) fn plugin_approver(&self) -> impl Fn(&vectorcraft_plugins::Plugin) -> bool + use<> {
|
||||
let grants = self.plugin_dir.as_deref().map(stored_grants);
|
||||
let grants = self.plugin_dir.as_deref().map(|dir| self.counted_grants(dir));
|
||||
move |plugin| {
|
||||
let m = plugin.manifest();
|
||||
match &grants {
|
||||
@@ -398,6 +434,15 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those this session
|
||||
/// doesn't count ([`Session::ignore_stored_grant`]).
|
||||
fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
let ignored = self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut grants = stored_grants(dir);
|
||||
grants.retain(|id, _| !ignored.contains(id));
|
||||
grants
|
||||
}
|
||||
|
||||
/// Write the module `bytes` of the plug-in `id` to the store → whether they went there (`false`
|
||||
/// without a folder).
|
||||
pub(crate) fn store_plugin(&self, id: &str, bytes: &[u8]) -> bool {
|
||||
@@ -417,12 +462,15 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Return the store's module for the plug-in `id` to `previous`, the bytes it held before a
|
||||
/// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed.
|
||||
pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) {
|
||||
/// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed. → whether the
|
||||
/// store now holds `previous`.
|
||||
pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) -> bool {
|
||||
#[cfg(test)]
|
||||
if PUT_BACK_FAILS.get() {
|
||||
return false;
|
||||
}
|
||||
match previous {
|
||||
Some(bytes) => {
|
||||
self.store_plugin(id, bytes);
|
||||
}
|
||||
Some(bytes) => self.store_plugin(id, bytes),
|
||||
None => self.unstore_plugin(id),
|
||||
}
|
||||
}
|
||||
@@ -438,13 +486,29 @@ impl Session {
|
||||
/// are written back as they were, except one for `id`. A grants file that is too large, can't
|
||||
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now
|
||||
/// holds what was asked (`false` without a folder).
|
||||
/// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts
|
||||
/// again ([`Session::ignore_stored_grant`]).
|
||||
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
let done = self.write_grant(id, grant);
|
||||
if done {
|
||||
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
/// Stop counting the store's grant for the plug-in `id` until [`Session::store_grant`] next
|
||||
/// succeeds for it or another store is attached: for a grant that should be gone and could not
|
||||
/// be removed, which would otherwise approve the bytes it covers.
|
||||
pub(crate) fn ignore_stored_grant(&self, id: &str) {
|
||||
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string());
|
||||
}
|
||||
|
||||
fn write_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
let Some(dir) = &self.plugin_dir else { return false };
|
||||
let mut file = match read_grants(dir) {
|
||||
Ok(file) => file,
|
||||
Err(e) => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -460,8 +524,7 @@ impl Session {
|
||||
let mut entries: Vec<serde_json::Value> = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect();
|
||||
entries.extend(file.other);
|
||||
if entries.is_empty() {
|
||||
take(dir, GRANTS_FILE);
|
||||
return true;
|
||||
return take(dir, GRANTS_FILE);
|
||||
}
|
||||
// The file is read back only up to its cap: written compactly when pretty-printed is larger,
|
||||
// and not at all when that is too.
|
||||
@@ -475,11 +538,20 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the plug-in `id` from the store.
|
||||
pub(crate) fn unstore_plugin(&self, id: &str) {
|
||||
if let Some(dir) = &self.plugin_dir {
|
||||
take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)));
|
||||
}
|
||||
/// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this
|
||||
/// version can't use ([`GrantsFile::names`]). `true` when the grants file can't be opened or
|
||||
/// read, because it may name `id` once it reads again; `false` without a folder, and when the
|
||||
/// file is too large or doesn't hold a list.
|
||||
pub(crate) fn holds_plugin_grant(&self, id: &str) -> bool {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| match read_grants(dir) {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
})
|
||||
}
|
||||
|
||||
/// Remove the plug-in `id` from the store → whether its file is gone (`false` without a folder).
|
||||
pub(crate) fn unstore_plugin(&self, id: &str) -> bool {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id))))
|
||||
}
|
||||
|
||||
/// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without
|
||||
@@ -500,10 +572,15 @@ impl Session {
|
||||
/// Delete the settings and cache of plug-in `id` from the store, and stop keeping any for it.
|
||||
/// The folder is first renamed out of the way (`<folder>.removed`), and that fails, leaving it
|
||||
/// as it was, when the rename does; what the deletion then leaves stays under that name, with a
|
||||
/// log record. A later call for the id tries to delete it again.
|
||||
pub(crate) fn remove_plugin_storage(&self, id: &str) -> Result<(), StorageError> {
|
||||
/// log record. A later call for the id tries to delete it again. `forget` runs once the folder is
|
||||
/// out of the way, before anything is deleted: when it returns `false`, the folder is renamed
|
||||
/// back and this fails.
|
||||
pub(crate) fn remove_plugin_storage(&self, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> {
|
||||
let not_forgotten = || StorageError::Io(GRANT_NOT_REMOVED.to_string());
|
||||
vectorcraft_plugins::registry::set_storage(id, None);
|
||||
let Some(dir) = &self.plugin_dir else { return Ok(()) };
|
||||
let Some(dir) = &self.plugin_dir else {
|
||||
return if forget() { Ok(()) } else { Err(not_forgotten()) };
|
||||
};
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let path = plugin_data_dir(dir, id);
|
||||
// Every storage handed out for the folder, including those runs still hold, is closed once
|
||||
@@ -518,6 +595,9 @@ impl Session {
|
||||
let data = dir.join(PLUGIN_DATA_DIR);
|
||||
if is_link(&data) {
|
||||
log::warn!("{} is a link: the plug-in settings and cache it leads to are left", data.display());
|
||||
if !forget() {
|
||||
return Err(not_forgotten());
|
||||
}
|
||||
close();
|
||||
return Ok(());
|
||||
}
|
||||
@@ -530,6 +610,14 @@ impl Session {
|
||||
Err(e) => return Err(StorageError::Io(format!("{}: {e}", path.display()))),
|
||||
Ok(()) => {}
|
||||
}
|
||||
if !forget() {
|
||||
if std::fs::symlink_metadata(&aside).is_ok()
|
||||
&& let Err(e) = std::fs::rename(&aside, &path)
|
||||
{
|
||||
log::warn!("can't move {} back: {e}", aside.display());
|
||||
}
|
||||
return Err(not_forgotten());
|
||||
}
|
||||
close();
|
||||
if std::fs::symlink_metadata(&aside).is_ok()
|
||||
&& let Err(e) = std::fs::remove_dir_all(&aside)
|
||||
@@ -960,16 +1048,36 @@ struct GrantsFile {
|
||||
other: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl GrantsFile {
|
||||
/// Whether the file has an entry for the plug-in `id`, usable by this version or not.
|
||||
fn names(&self, id: &str) -> bool {
|
||||
self.grants.contains_key(id) || self.other.iter().any(|e| e.get("id").and_then(serde_json::Value::as_str) == Some(id))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the grants file of a plug-in store gave no grants.
|
||||
struct GrantsError {
|
||||
/// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is
|
||||
/// too large or doesn't hold a list, and approves nothing.
|
||||
unread: bool,
|
||||
/// The detail for a log record.
|
||||
why: String,
|
||||
}
|
||||
|
||||
/// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too
|
||||
/// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an
|
||||
/// invalid id, is kept in [`GrantsFile::other`] with a log record.
|
||||
fn read_grants(dir: &Path) -> Result<GrantsFile, String> {
|
||||
fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
|
||||
let path = dir.join(GRANTS_FILE);
|
||||
if !path.exists() {
|
||||
return Ok(GrantsFile::default());
|
||||
let bytes = match read_past_cap(&path, MAX_GRANTS_FILE) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(GrantsFile::default()),
|
||||
Err(e) => return Err(GrantsError { unread: true, why: e.to_string() }),
|
||||
};
|
||||
if bytes.len() as u64 > MAX_GRANTS_FILE {
|
||||
return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) });
|
||||
}
|
||||
let entries =
|
||||
read_capped(&path, MAX_GRANTS_FILE).and_then(|bytes| serde_json::from_slice::<Vec<serde_json::Value>>(&bytes).map_err(|e| e.to_string()))?;
|
||||
let entries = serde_json::from_slice::<Vec<serde_json::Value>>(&bytes).map_err(|e| GrantsError { unread: false, why: e.to_string() })?;
|
||||
let mut file = GrantsFile::default();
|
||||
let mut first_error = None;
|
||||
for entry in entries {
|
||||
@@ -997,7 +1105,7 @@ fn stored_grants(dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permission
|
||||
match read_grants(dir) {
|
||||
Ok(file) => file.grants,
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
BTreeMap::new()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,6 +158,7 @@ mod simplify_part;
|
||||
mod slices;
|
||||
mod smartguides;
|
||||
mod smooth_path;
|
||||
mod spelling;
|
||||
mod store;
|
||||
mod strokegeom;
|
||||
mod strokegradient;
|
||||
@@ -185,6 +186,7 @@ mod transformfx;
|
||||
mod transparencygrid;
|
||||
mod trap;
|
||||
mod typearea;
|
||||
mod typeglyphbounds;
|
||||
mod typescale;
|
||||
mod typeundo;
|
||||
mod units;
|
||||
|
||||
@@ -823,6 +823,13 @@ fn shape_builder_applies_a_merge_before_what_comes_next() {
|
||||
// No files: the command fails after the merge.
|
||||
assert!(s.execute("text.addFontFiles", &json!({"files": []})).is_err());
|
||||
}),
|
||||
("a call its schema refuses", |s, _, _| {
|
||||
// The refused call adds no undo step of its own: the merge's is the last one.
|
||||
let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": 0})).unwrap_err().to_string();
|
||||
assert!(e.contains("`zoom`"), "{e}");
|
||||
assert!(s.doc().unwrap().doc.views.is_empty());
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Shape Builder"));
|
||||
}),
|
||||
];
|
||||
let _proof = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let dir = vectorcraft_testkit::temp_dir("shape-builder-merge-first");
|
||||
|
||||
@@ -173,6 +173,22 @@ fn blend_recolors_a_colorized_gray_image_without_alpha() {
|
||||
assert_eq!(colorize(&s, middle), Some(Paint::solid(Color::rgb(0.5, 0.5, 0.5))));
|
||||
}
|
||||
|
||||
/// A colorized image shows a fill and no stroke, so selecting it loads them for new art as any
|
||||
/// object without a stroke does (the weight stays).
|
||||
#[test]
|
||||
fn selecting_a_colorized_image_gives_new_art_its_fill_and_no_stroke() {
|
||||
let mut s = session();
|
||||
let id = image(&mut s, "gray", gray(false));
|
||||
s.execute("paint.setFill", &json!({"color": "#336699"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 5.0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!(s.paint.fill.color().map(|c| c.to_hex()), Some("#336699".into()));
|
||||
assert_eq!((s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_proxy_invert_recolors_a_colorized_gray_image_and_undo_restores_it() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -2698,19 +2698,15 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() {
|
||||
assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1), (0, 2)].into());
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
assert_eq!(pasted(&mut s), [2]);
|
||||
// Cut takes the segment between them. The two surviving runs of an ordinary path
|
||||
// become independent objects, and this path keeps the first run (#3380).
|
||||
// Cut takes the two anchors out of the path, as Clear does (#6361): each side keeps one
|
||||
// anchor, which makes no path, so nothing is left.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let original = path(&s, id);
|
||||
let picked = s.doc().unwrap().selection.clone();
|
||||
s.execute("edit.cut", &json!({})).unwrap();
|
||||
let left = paths(&s);
|
||||
assert_eq!(left.len(), 2);
|
||||
assert_eq!(left[0].0, id);
|
||||
assert!(left.iter().all(|(_, p)| p.subpaths.len() == 1 && !p.subpaths[0].closed));
|
||||
assert_eq!(left[0].1.subpaths[0].anchors, original.subpaths[0].anchors[..2]);
|
||||
assert_eq!(left[1].1.subpaths[0].anchors, original.subpaths[0].anchors[2..]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, left.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
assert!(left.is_empty());
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty());
|
||||
assert_eq!(s.clipboard.nodes.len(), 1);
|
||||
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors[1..3]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Dynamic symbols (#4938): an instance changes the appearance of objects in its symbol's art and
|
||||
//! stays linked; editing the symbol keeps those changes, Reset and Break Link handle them. Direct
|
||||
//! Selection picks one path, compound path or type object of an instance's art, and a solid color
|
||||
//! Fill or Stroke changes it.
|
||||
//! Selection picks one path, compound path or type object of an instance's art, and Fill, Stroke,
|
||||
//! opacity and blend change it for that instance.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
@@ -51,8 +51,9 @@ fn pixel(s: &Session, x: u32, y: u32) -> [u8; 4] {
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
const BLUE: [u8; 4] = [0, 0, 255, 255];
|
||||
|
||||
/// The refusal of anything but a solid fill or stroke on a picked object says so.
|
||||
const REFUSED: &str = "solid color fill and stroke";
|
||||
/// The refusal of a change that is not fill, stroke, opacity or blend on a picked path, compound
|
||||
/// path or type (or of selecting any other kind of object) says so.
|
||||
const REFUSED: &str = "fill, stroke, opacity and blend";
|
||||
|
||||
#[test]
|
||||
fn a_dynamic_instance_paints_one_object_its_own_way_and_stays_linked() {
|
||||
@@ -655,8 +656,7 @@ fn commands_on_the_selection_leave_a_picked_objects_instance_alone() {
|
||||
("object.repeat.release", json!({})),
|
||||
("object.intertwine.release", json!({})),
|
||||
("object.objectsOnPath.expand", json!({})),
|
||||
("transparency.set", json!({"opacity": 50})),
|
||||
("transparency.set", json!({"blend": "multiply"})),
|
||||
("transparency.set", json!({"opacity": 50, "isolate": true})),
|
||||
("transparency.releaseOpacityMask", json!({})),
|
||||
("transparency.setOpacityMask", json!({"invert": true, "clip": false})),
|
||||
("transparency.disableOpacityMask", json!({})),
|
||||
@@ -858,38 +858,30 @@ fn a_press_on_an_image_of_the_art_is_refused_and_moves_nothing() {
|
||||
assert_eq!(overrides(&s, inst), 0);
|
||||
}
|
||||
|
||||
/// A gradient or pattern for a picked object is refused and changes nothing, new art's paint
|
||||
/// included. An object that shows a gradient takes a solid color.
|
||||
/// A gradient or pattern for a picked object is stored on the instance; Invert, Complement and the
|
||||
/// gradient annotator stay refused. An object that shows a gradient takes a solid color.
|
||||
#[test]
|
||||
fn gradients_and_patterns_on_a_picked_object_are_refused() {
|
||||
fn gradients_and_patterns_on_a_picked_object_are_taken() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
let g = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": g})).unwrap();
|
||||
let tile = square(&mut s, 150.0);
|
||||
s.execute("object.pattern.make", &json!({"ids": [tile.0], "name": "Dots", "edit": false})).unwrap();
|
||||
// An object to sample a gradient from.
|
||||
let far = square(&mut s, 150.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [far.0], "gradient": g})).unwrap();
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
let undo = undo_steps(&s);
|
||||
let (fill, stroke) = (s.paint.fill.clone(), s.paint.stroke.clone());
|
||||
for (cmd, p) in [
|
||||
("paint.setFill", json!({"gradient": g})),
|
||||
("paint.setStroke", json!({"gradient": g})),
|
||||
("paint.setFill", json!({"gradient": g, "span": "selection"})),
|
||||
("paint.setFill", json!({"swatch": "Ramp"})),
|
||||
("paint.setFill", json!({"swatch": "Dots"})),
|
||||
("appearance.copyFrom", json!({"source": far.0})),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(REFUSED), "{cmd} {p}: {e}");
|
||||
}
|
||||
assert_eq!((overrides(&s, inst), undo_steps(&s)), (0, undo), "nothing changes");
|
||||
assert_eq!((&s.paint.fill, &s.paint.stroke), (&fill, &stroke), "new art keeps its paint");
|
||||
// An object whose art has a gradient takes a solid color; Invert, Complement and selecting one
|
||||
// of its stops are refused.
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": {"gradient": g}})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": g})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_))));
|
||||
s.execute("paint.setStroke", &json!({"gradient": g})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].stroke, Some(Paint::Gradient(_))));
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ramp"})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_))));
|
||||
s.execute("paint.setFill", &json!({"swatch": "Dots"})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Pattern { .. })));
|
||||
s.execute("appearance.copyFrom", &json!({"source": far.0})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_))));
|
||||
// Invert, Complement and selecting a stop are refused on a gradient.
|
||||
for cmd in ["paint.invert", "paint.complement"] {
|
||||
let e = s.execute(cmd, &json!({"stroke": false})).unwrap_err().to_string();
|
||||
assert!(e.contains(REFUSED), "{cmd}: {e}");
|
||||
@@ -902,10 +894,8 @@ fn gradients_and_patterns_on_a_picked_object_are_refused() {
|
||||
assert_eq!(s.selected_stop(), None);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
assert_eq!(pixel(&s, 80, 30), RED);
|
||||
// The Eyedropper's options can leave the gradient out: the fill stays.
|
||||
s.execute("appearance.copyFrom", &json!({"source": far.0, "pickUp": {"appearance": {"fill": {"color": false}}}})).unwrap();
|
||||
assert_eq!(pixel(&s, 80, 30), RED);
|
||||
// Options that pick up neither color leave nothing to change, so the click is refused.
|
||||
let (undo, fill) = (undo_steps(&s), s.paint.fill.clone());
|
||||
let neither = json!({"source": far.0, "pickUp": {"appearance": {"fill": {"color": false}, "stroke": {"color": false}}}});
|
||||
let e = s.execute("appearance.copyFrom", &neither).unwrap_err().to_string();
|
||||
@@ -913,6 +903,26 @@ fn gradients_and_patterns_on_a_picked_object_are_refused() {
|
||||
assert_eq!((undo_steps(&s), &s.paint.fill), (undo, &fill), "nothing changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_and_blend_on_a_picked_object_go_through_transparency_set() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
assert_eq!(node(&s, inst).extras().symbol_overrides[0].opacity, Some(0.5));
|
||||
s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap();
|
||||
let o = node(&s, inst).extras().symbol_overrides[0].clone();
|
||||
assert_eq!(o.opacity, Some(0.5));
|
||||
assert_eq!(o.blend, Some(vectorcraft_color::BlendMode::Multiply));
|
||||
// A static symbol's instance refuses selectPart, so transparency.set acts on the instance whole.
|
||||
let mut t = session();
|
||||
let static_inst = pair(&mut t, "static");
|
||||
t.execute("select.set", &json!({"ids": [static_inst.0]})).unwrap();
|
||||
t.execute("transparency.set", &json!({"opacity": 40})).unwrap();
|
||||
assert!(node(&t, static_inst).extras().symbol_overrides.is_empty());
|
||||
assert!((node(&t, static_inst).opacity - 0.4).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_part_refuses_hidden_and_locked_objects_of_the_art() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -342,7 +342,12 @@ fn pixels(s: &Session, id: NodeId) -> Vec<[u8; 4]> {
|
||||
|
||||
/// A selected embedded 2×2 image.
|
||||
fn image_node(s: &mut Session) -> NodeId {
|
||||
let bytes = png([[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 128]]);
|
||||
image_of(s, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 128]])
|
||||
}
|
||||
|
||||
/// A selected embedded 2×2 image of the pixels `px`.
|
||||
fn image_of(s: &mut Session, px: [[u8; 4]; 4]) -> NodeId {
|
||||
let bytes = png(px);
|
||||
s.edit("Place", |d, sel| {
|
||||
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(bytes));
|
||||
let id = d.alloc_id();
|
||||
@@ -383,6 +388,85 @@ fn invert_recolours_an_embedded_image() {
|
||||
assert_eq!(pixels(&s, id)[..2], [[0, 0, 0, 255], [0, 255, 0, 255]]);
|
||||
}
|
||||
|
||||
/// The key of image object `id`'s blob.
|
||||
fn image_key(s: &Session, id: NodeId) -> String {
|
||||
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not an image") };
|
||||
im.key.clone()
|
||||
}
|
||||
|
||||
/// Convert to Grayscale stores an image with one color channel, alpha kept (#5632).
|
||||
#[test]
|
||||
fn convert_to_grayscale_stores_an_image_as_grayscale() {
|
||||
let mut s = session();
|
||||
let id = image_node(&mut s);
|
||||
let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(r["changed"], 1);
|
||||
let key = image_key(&s, id);
|
||||
let source = s.doc().unwrap().doc.images[&key].gray_source();
|
||||
assert!(source.is_some_and(|g| g.alpha && !g.one_bit), "a grayscale file with alpha: {source:?}");
|
||||
let gray = |hex: &str| Color::from_hex(hex).unwrap().in_model(vectorcraft_color::cms::Model::Gray).to_rgba8(1.0)[0];
|
||||
let (r_, g_, b_, w) = (gray("#ff0000"), gray("#00ff00"), gray("#0000ff"), gray("#ffffff"));
|
||||
assert_eq!(pixels(&s, id), [[r_, r_, r_, 255], [g_, g_, g_, 255], [b_, b_, b_, 255], [w, w, w, 128]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(pixels(&s, id)[0], [255, 0, 0, 255], "one undo step restores the color image");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
// An image that is already grayscale has nothing to convert.
|
||||
let again = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(again["changed"], 0);
|
||||
assert_eq!(image_key(&s, id), key);
|
||||
}
|
||||
|
||||
/// An RGB image whose pixels are all neutral still becomes a one-channel image (#5632).
|
||||
#[test]
|
||||
fn convert_to_grayscale_stores_a_neutral_rgb_image_as_grayscale() {
|
||||
let mut s = session();
|
||||
let id = image_of(&mut s, [[255, 255, 255, 255], [0, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]]);
|
||||
let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(r["changed"], 1);
|
||||
let source = s.doc().unwrap().doc.images[&image_key(&s, id)].gray_source();
|
||||
assert!(source.is_some_and(|g| !g.alpha), "an opaque image has no alpha channel: {source:?}");
|
||||
}
|
||||
|
||||
/// Select All leaves a hidden neutral RGB image out of Convert to Grayscale, which would change it.
|
||||
#[test]
|
||||
fn a_hidden_neutral_rgb_image_counts_as_not_converted() {
|
||||
let mut s = session();
|
||||
let hidden = image_of(&mut s, [[255, 255, 255, 255], [0, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]]);
|
||||
s.execute("layer.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap();
|
||||
rect(&mut s, json!("#ff0000"));
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(r["notChanged"], json!({"locked": 0, "hidden": 1}), "{r}");
|
||||
}
|
||||
|
||||
/// Adjust Colors converting to gray stores an image with one channel; without Convert it keeps
|
||||
/// the image's RGB (#5632).
|
||||
#[test]
|
||||
fn adjust_colors_converting_to_gray_stores_an_image_as_grayscale() {
|
||||
let source = |convert: bool| {
|
||||
let mut s = session();
|
||||
let id = image_node(&mut s);
|
||||
s.execute("edit.colors.adjustBalance", &json!({"mode": "gray", "gray": 10, "convert": convert})).unwrap();
|
||||
s.doc().unwrap().doc.images[&image_key(&s, id)].gray_source()
|
||||
};
|
||||
assert!(source(true).is_some(), "converted to gray");
|
||||
assert!(source(false).is_none(), "the colors keep their model");
|
||||
}
|
||||
|
||||
/// A PDF of a CMYK document writes an image Convert to Grayscale made with one channel (#5632).
|
||||
#[test]
|
||||
fn a_converted_image_is_written_to_pdf_as_gray_in_a_cmyk_document() {
|
||||
let mut s = session();
|
||||
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
image_of(&mut s, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [10, 200, 30, 255]]);
|
||||
s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
let opts = vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() };
|
||||
let pdf = String::from_utf8_lossy(&vectorcraft_pdf::export(&s.doc().unwrap().doc, &opts).unwrap()).into_owned();
|
||||
let image = pdf.split("/Subtype/Image").nth(1).or_else(|| pdf.split("/Subtype /Image").nth(1)).expect("an image in the PDF");
|
||||
let image = &image[..image.find("stream").unwrap_or(image.len())];
|
||||
assert!(image.contains("/DeviceGray") && !image.contains("/DeviceRGB"), "one color channel: {image}");
|
||||
}
|
||||
|
||||
/// "Dots": a red square tile; a selected rectangle filled with it.
|
||||
fn pattern_fill(s: &mut Session) -> NodeId {
|
||||
rect(s, json!("#ff0000"));
|
||||
|
||||
@@ -447,6 +447,27 @@ fn export_selection_keeps_the_effects_in_the_crop() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An Outer Glow at its default Screen mode on the bare page is in a PNG on white and in a JPEG,
|
||||
/// and in a transparent PNG (#6125).
|
||||
#[test]
|
||||
fn a_screen_outer_glow_is_in_raster_exports() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.outerGlow"})).unwrap();
|
||||
let mut pixel = |p: serde_json::Value| {
|
||||
let v = s.execute("document.export", &p).unwrap();
|
||||
let img = image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8();
|
||||
// 2 pt past the square's stroke, on the right.
|
||||
*img.get_pixel(122, 110)
|
||||
};
|
||||
for p in [json!({"format": "png", "background": "white"}), json!({"format": "jpg"})] {
|
||||
let px = pixel(p.clone());
|
||||
assert!(px[0] > 235 && px[1] > 235 && px[2] < 235, "{p}: yellow on white: {px:?}");
|
||||
}
|
||||
let px = pixel(json!({"format": "png", "background": "transparent"}));
|
||||
assert!(px[3] > 0 && px[0] > 235 && px[1] > 235 && px[2] < 40, "the glow is yellow in the transparent image: {px:?}");
|
||||
}
|
||||
|
||||
/// A group's own drop shadow is inside the crop of the group's selection export too.
|
||||
#[test]
|
||||
fn export_selection_keeps_a_groups_shadow_in_the_crop() {
|
||||
|
||||
@@ -3687,6 +3687,40 @@ fn ruler_guides_and_lock() {
|
||||
assert!(s.execute("guide.remove", &json!({"index": 0})).is_err());
|
||||
}
|
||||
|
||||
/// While guides are locked, a guide dragged out of a ruler and `guide.add` still make new guides,
|
||||
/// each in one undo step and not selected. The ruler guides and guide paths in the document, the
|
||||
/// new guides included, can't be selected, moved or deleted.
|
||||
#[test]
|
||||
fn new_guides_can_be_made_while_guides_are_locked() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let path = guide_path(&mut s, 300.0);
|
||||
s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
let n = undo_len(&s);
|
||||
s.ruler_guide(true, &PointerEvent::new(PointerKind::Drag, 153.0, 30.0), true, v).unwrap();
|
||||
s.ruler_guide(true, &PointerEvent::new(PointerKind::Up, 153.0, 30.0), true, v).unwrap();
|
||||
assert_eq!(guides(&s), [(false, 50.0), (true, 153.0)]);
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "New Guide");
|
||||
assert_eq!(s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap()["index"], 2);
|
||||
assert_eq!(guides(&s).len(), 3);
|
||||
assert_eq!(selected_guides(&s), Vec::<usize>::new());
|
||||
for (id, params) in [
|
||||
("guide.select", json!({"indexes": [1]})),
|
||||
("guide.move", json!({"index": 1, "pos": 170})),
|
||||
("guide.remove", json!({"index": 1})),
|
||||
("guide.setLayer", json!({"index": 1, "layer": s.doc().unwrap().current_layer().unwrap().0})),
|
||||
] {
|
||||
assert!(matches!(s.execute(id, ¶ms), Err(EngineError::Disabled(..))), "{id}");
|
||||
}
|
||||
assert_eq!(guides(&s).len(), 3);
|
||||
sel(&mut s, &[path]);
|
||||
assert!(selected(&s).is_empty(), "a guide path can't be selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_guide_lock_parameters_keep_guides_selected() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1786,6 +1786,54 @@ fn delete_empty_artboards_check_measures_a_document_once() {
|
||||
assert_eq!(delete_empty_enabled_counted(&s), (true, 0), "after another change of the selection");
|
||||
}
|
||||
|
||||
/// Whether Fit to Artwork Bounds has art to fit on `indices`, as a menu asks for it, with the
|
||||
/// plug-ins' and fonts' generations `outside`, and how many times asking measured a document on
|
||||
/// this thread.
|
||||
fn art_to_fit_counted(s: &Session, indices: &[usize], outside: (u64, u64)) -> (bool, usize) {
|
||||
let measures = || crate::doc_state::ART_TO_FIT_MEASURES.with(std::cell::Cell::get);
|
||||
let before = measures();
|
||||
let any = s.doc().unwrap().any_art_to_fit_with(indices, outside);
|
||||
(any, measures() - before)
|
||||
}
|
||||
|
||||
/// A menu asks whether Fit to Artwork Bounds has art on every frame while it is open: the answer is
|
||||
/// measured once for a version of the document and the artboards asked about, kept through a change
|
||||
/// of the selection or the view, and measured again after an edit, for other artboards, and when
|
||||
/// the plug-ins or the fonts change.
|
||||
#[test]
|
||||
fn art_to_fit_is_measured_once_for_a_version_of_the_document() {
|
||||
let mut s = row_of_artboards(2);
|
||||
let both = [0, 1];
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (false, 1), "the first frame");
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (false, 0), "a later frame");
|
||||
let art = box_at(&mut s, 10.0, 20.0);
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 1), "an edit puts art on artboard 1");
|
||||
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 0), "after a change of the selection");
|
||||
s.execute("view.transparencyGrid", &json!({})).unwrap();
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 0), "after a change of the view");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (0, 0)), (false, 1), "other artboards");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (1, 0)), (false, 1), "a plug-in installed or removed");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (1, 1)), (false, 1), "fonts installed");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (1, 1)), (false, 0));
|
||||
}
|
||||
|
||||
/// A change made to the document in place (`Arc::make_mut`, with no other holder and no change
|
||||
/// of revision) is measured again: the kept answer holds the document it measured weakly, so a
|
||||
/// changed document is a new allocation, not the old address.
|
||||
#[test]
|
||||
fn art_to_fit_follows_a_change_in_place() {
|
||||
let mut s = row_of_artboards(2);
|
||||
box_at(&mut s, 10.0, 20.0);
|
||||
assert_eq!(art_to_fit_counted(&s, &[0], (0, 0)), (true, 1), "art on artboard 1");
|
||||
let st = s.doc_mut().unwrap();
|
||||
assert_eq!(Arc::strong_count(&st.doc), 1, "the undo history holds the document before the edit");
|
||||
let (revision, empty_spot) = (st.revision, st.doc.artboards[1].rect);
|
||||
Arc::make_mut(&mut st.doc).artboards[0].rect = empty_spot;
|
||||
assert_eq!(st.revision, revision);
|
||||
assert_eq!(art_to_fit_counted(&s, &[0], (0, 0)), (false, 1), "artboard 1 moved off the art");
|
||||
}
|
||||
|
||||
/// The enabled state follows an edit, an undo, a redo, an added and a removed artboard, a locked
|
||||
/// artboard, and each change measures the document once.
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 320 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user