Merge main into type-3d-redraw

# Conflicts:
#	crates/ui-egui/src/canvas/tests.rs
#	docs/target-app-parity.md
This commit is contained in:
Drew Dibble committed 2026-11-09 09:49:25 -07:00
commit bd779077e5
279 files changed
+20001 -1647

No files matched your search

Generated
+16 -14
View File
@@ -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"
@@ -1059,7 +1070,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"chrono",
"dunce",
@@ -6463,6 +6474,7 @@ dependencies = [
"cfb",
"chrono",
"craft-docpath",
"craft-proof",
"crc32fast",
"flate2",
"hayro-jpeg2000",
@@ -6511,6 +6523,7 @@ name = "vectorcraft-eps"
version = "0.21.0"
dependencies = [
"craft-pdf",
"encoding_rs",
"fax",
"flate2",
"hayro-ccitt",
@@ -6651,6 +6664,8 @@ dependencies = [
name = "vectorcraft-plugins"
version = "0.21.0"
dependencies = [
"craft-vectorcraft-format",
"image",
"log",
"serde",
"serde_json",
@@ -8221,7 +8236,6 @@ dependencies = [
"nix",
"typed-path",
"windows-sys 0.61.2",
"zopfli",
]
[[package]]
@@ -8236,18 +8250,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.4.12"
+5 -1
View File
@@ -16,13 +16,14 @@ 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"] }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -99,6 +100,9 @@ ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
hayro-ccitt = "0.3"
# Substring search for the EPS reader's PostScript `search`.
memchr = "2"
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
encoding_rs = "0.8.42"
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] }
# CMYK image samples (vectorcraft-doc's cmyk module): the image crate's own TIFF and JPEG
+2 -2
View File
@@ -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-09 · **Change:** minor (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
@@ -87,7 +87,7 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so
| 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 |
+74 -15
View File
@@ -5,7 +5,7 @@
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300]
//! vectorcraft-cli commands
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli info FILE
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
//! vectorcraft-cli perf [--paths 50000] [--deep]
@@ -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,11 +107,13 @@ 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.
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
Open IN (any readable format) and export OUT in the format its extension picks (see Writable
formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects
resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
@@ -114,7 +126,10 @@ USAGE:
IN left things out (hidden text, art or layers it could not read; the notes say which) unless
--replace-lossy is given. --editing-data opens a .ai or an EPS with editing data from its editing copy
even where that draws differently from its PDF part or page (which can be older), as long as
it can be read. A PDF OUT omits the embedded native document unless --preserve-editing is
it can be read. --legacy-name-encoding reads the names in a .ai's or an EPS's editing data
that aren't UTF-8 (layers, objects, artboards, colors, gradients, patterns, graphic styles,
swatches, brushes, symbols, variables and data sets, and data sets' text values) in
windows-1252 (the default), macintosh, windows-949, shift_jis, gbk or big5. A PDF OUT omits the embedded native document unless --preserve-editing is
given (the app's Save As PDF still defaults to keeping it). With --preserve-editing, when the
attachment is written the result's warnings say so (it is left out, with its own warning, for
--artboard or a --range without every artboard).
@@ -221,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
}
@@ -238,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() {
@@ -249,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) }
@@ -259,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());
}
@@ -273,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}"))?)
@@ -302,8 +335,20 @@ fn commands() -> Result<(), String> {
}
fn convert(args: &[String]) -> Result<(), String> {
let valued =
["--scale", "-s", "--ppi", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"];
let valued = [
"--scale",
"-s",
"--ppi",
"--artboard",
"-a",
"--range",
"-r",
"--decimals",
"--ai-version",
"--hidden-objects",
"--transparent-images",
"--legacy-name-encoding",
];
if help_requested(args, &valued) {
return help();
}
@@ -312,6 +357,9 @@ fn convert(args: &[String]) -> Result<(), String> {
(None::<f64>, None::<u64>, None::<String>, false, false, false, false);
let mut ppi = None::<f64>;
let mut decimals = None::<u64>;
// The encoding of a legacy `.ai`'s names that aren't UTF-8, passed on as `document.open`'s
// `legacyNameEncoding`; the engine checks it.
let mut legacy_names = None::<String>;
// Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`,
// `transparentImages`); the engine checks their values.
let mut legacy: Vec<(&str, String)> = vec![];
@@ -334,6 +382,9 @@ fn convert(args: &[String]) -> Result<(), String> {
"--replace-lossy" => replace_lossy = true,
"--editing-data" => editing_data = true,
"--preserve-editing" => preserve_editing = true,
"--legacy-name-encoding" => {
legacy_names = Some(it.next().cloned().ok_or("--legacy-name-encoding needs an encoding such as windows-949")?);
}
"--ai-version" => legacy.push(("aiVersion", it.next().cloned().ok_or("--ai-version needs 7 or pdf")?)),
"--hidden-objects" => legacy.push(("hiddenObjects", it.next().cloned().ok_or("--hidden-objects needs layer, omit or visible")?)),
"--transparent-images" => legacy.push(("transparentImages", it.next().cloned().ok_or("--transparent-images needs flatten or omit")?)),
@@ -346,8 +397,14 @@ fn convert(args: &[String]) -> Result<(), String> {
return Err("a .ait template holds every artboard: --artboard and --range don't apply".into());
}
let mut h = Headless::new();
let opened = if editing_data {
let params = json!({"path": input, "editingData": "always"});
let opened = if editing_data || legacy_names.is_some() {
let mut params = json!({"path": input});
if editing_data {
params["editingData"] = json!("always");
}
if let Some(e) = &legacy_names {
params["legacyNameEncoding"] = json!(e);
}
h.call("engine.execute", json!({"command": "document.open", "params": params})).map_err(|e| format!("open {input}: {e}"))?
} else {
h.call("app.open", json!({"path": input})).map_err(|e| format!("open {input}: {e}"))?
@@ -534,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}"));
@@ -568,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"))?);
@@ -585,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.
+71
View File
@@ -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();
+1 -1
View File
@@ -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"
+9
View File
@@ -92,12 +92,21 @@ impl eframe::App for App {
}
fn on_exit(&mut self) {
file_access::unconfined(|| save_prefs(&self.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.
+241
View File
@@ -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;
+236
View File
@@ -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
}
+9 -1
View File
@@ -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);
+6 -1
View File
@@ -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;
@@ -97,7 +99,7 @@ use titlebar::opted_into_system_title_bar;
#[cfg(windows)]
use titlebar::set_taskbar_icon;
#[cfg(all(test, feature = "wgpu"))]
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame};
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
struct App {
@@ -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"))]
{
+8
View File
@@ -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::*;
+75 -1
View File
@@ -193,7 +193,8 @@ fn the_system_title_bar_preference_keeps_the_window_decorations() {
/// Preferences › User Interface › VectorCraft Title Bar on Every Desktop gives the app frame where
/// the probe chose the desktop's (KDE, X11, a window opened through XWayland); without it the probe
/// decides, and `VECTORCRAFT_TITLEBAR` takes precedence over both.
/// decides, and `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` takes precedence over
/// both.
#[test]
fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
assert!(!super::opted_into_app_title_bar(None), "no preferences: the default");
@@ -245,6 +246,79 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
}
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
/// on. The saved preference still decides while the variable is unset.
#[test]
fn the_titlebar_variable_takes_precedence_over_system_title_bar() {
use craft_window::Frame;
assert!(super::system_title_bar_applies(true, false));
assert!(!super::system_title_bar_applies(true, true));
assert!(!super::system_title_bar_applies(false, false));
assert!(!super::system_title_bar_applies(false, true));
// VECTORCRAFT_TITLEBAR=app with System Title Bar on: VectorCraft draws its own title bar.
let frame = super::start_frame(Frame::Desktop, Some(true), false, false);
assert_eq!(super::custom_titlebar_from(&frame, super::system_title_bar_applies(true, true)), !cfg!(target_os = "macos"));
// VECTORCRAFT_TITLEBAR=desktop with System Title Bar off keeps the desktop's frame.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let frame = super::start_frame(Frame::App(craft_window::Layout::default()), Some(false), false, false);
assert!(!super::custom_titlebar_from(&frame, super::system_title_bar_applies(false, true)));
}
}
/// `VECTORCRAFT_TITLEBAR` read from the environment at startup, with System Title Bar off and on.
/// The variable is process-wide and read once, so each value runs in a separate test process.
#[test]
fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
const CHILD: &str = "VECTORCRAFT_TEST_TITLEBAR_CHILD";
if std::env::var_os(CHILD).is_none() {
for value in ["app", "system", "desktop", "unknown"] {
// Linux and the BSDs: hold `spawning` while the child starts, so it does not keep a
// copy of a GPU start test's locked start file (see `CHILD_SPAWN`).
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
let spawning = super::spawning();
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::the_titlebar_variable_decides_the_frame_before_the_window_opens", "--nocapture"])
.env(CHILD, "1")
.env("VECTORCRAFT_TITLEBAR", value)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
drop(spawning);
let output = child.unwrap().wait_with_output().unwrap();
assert!(
output.status.success(),
"VECTORCRAFT_TITLEBAR={value}\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
return;
}
let value = std::env::var("VECTORCRAFT_TITLEBAR").unwrap();
let not_read = cfg!(any(target_os = "macos", target_os = "windows"));
assert_eq!(super::titlebar_from_env(), !not_read && value != "unknown", "VECTORCRAFT_TITLEBAR={value}");
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
let custom = super::custom_titlebar(saved);
let expected = match value.as_str() {
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
"app" => true,
"system" | "desktop" => false,
// Not a value the variable takes: System Title Bar decides when it is on. Otherwise the
// `craft-window` probe decides, the same with System Title Bar off as with no saved
// preferences.
_ if opted_into_system => false,
_ => super::custom_titlebar(None),
};
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
}
}
/// The file extensions the macOS bundle declares: its document types and its own exported type.
fn plist_extensions(plist: &str) -> Vec<&str> {
["<key>CFBundleTypeExtensions</key>", "<key>public.filename-extension</key>"]
+21 -10
View File
@@ -41,7 +41,8 @@ pub(crate) const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
/// Whether the user asked for the system title bar in Preferences › User Interface › System Title
/// Bar. Read from the saved preferences before the window opens; a missing or unreadable value is
/// `false` (the default). This preference forces the desktop/native frame back on.
/// `false` (the default). This preference forces the desktop/native frame back on unless
/// `VECTORCRAFT_TITLEBAR` is set to `app`, `system` or `desktop` ([`system_title_bar_applies`]).
pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
}
@@ -55,8 +56,8 @@ pub(crate) fn opted_into_app_title_bar(saved: Option<&vectorcraft_ui_egui::UiSta
/// Whether the app draws the frame on this start, before the System Title Bar preference is
/// applied ([`custom_titlebar_from`]). `probed_app` is the `craft-window` probe's answer and
/// `overridden` its `VECTORCRAFT_TITLEBAR` override. In order: the override decides when it is
/// set; VectorCraft Title Bar on Every Desktop (`opted_into_app`) gives the app frame; a window
/// `overridden` its `VECTORCRAFT_TITLEBAR` override. In order: the override decides when the
/// variable is set to `app`, `system` or `desktop`;VectorCraft Title Bar on Every Desktop (`opted_into_app`) gives the app frame; a window
/// that opens through XWayland (`forced_to_x11`) gets the desktop frame; otherwise the probe
/// decides.
pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> bool {
@@ -87,12 +88,19 @@ fn probed_choice() -> &'static craft_window::Choice {
}
/// Whether `VECTORCRAFT_TITLEBAR` chose this window's frame (Linux and the BSDs), so Preferences ›
/// User Interface › VectorCraft Title Bar on Every Desktop does not apply while it is set. Always
/// `false` on macOS and Windows.
/// User Interface › System Title Bar and VectorCraft Title Bar on Every Desktop do not apply while
/// it is set to `app`, `system` or `desktop`. Always `false` on macOS and Windows.
pub(crate) fn titlebar_from_env() -> bool {
cfg!(not(any(target_os = "macos", target_os = "windows"))) && probed_choice().overridden().is_some()
}
/// Whether System Title Bar decides this start: `opted_into_system` unless `VECTORCRAFT_TITLEBAR`
/// is set to `app`, `system` or `desktop` (`from_env`), which chooses the frame for the run it is
/// set in.
pub(crate) fn system_title_bar_applies(opted_into_system: bool, from_env: bool) -> bool {
opted_into_system && !from_env
}
/// Whether this start draws its own title bar, given the frame the shared `craft-window` crate
/// decided and the user's System Title Bar preference.
///
@@ -100,9 +108,10 @@ pub(crate) fn titlebar_from_env() -> bool {
/// ([`craft_window::Frame::Desktop`]) on macOS, Windows, X11 and any Wayland compositor with
/// server-side decorations (KDE, Sway, Hyprland, COSMIC); the app draws it
/// ([`craft_window::Frame::App`]) only where the compositor leaves it to the app (GNOME's Mutter),
/// or when `VECTORCRAFT_TITLEBAR` overrides the probe. VectorCraft draws its own title bar exactly
/// or when `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` overrides the probe. VectorCraft draws its own title bar exactly
/// when `craft-window` says the app owns the frame **and** the user has not opted into the system
/// title bar; the preference always forces the native frame back on.
/// title bar; the preference forces the native frame back on unless `VECTORCRAFT_TITLEBAR` is set
/// to one of those values ([`system_title_bar_applies`]).
///
/// macOS and Windows keep today's behavior and are decided by [`CUSTOM_TITLEBAR`] rather than the
/// probe: `craft-window` returns `Frame::Desktop` for both (the OS always draws a frame), but
@@ -124,16 +133,18 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
/// Title Bar preference. Call once at startup, before [`native_options`].
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
/// `desktop`. Call once at startup,
/// before [`native_options`].
///
/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through
/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins,
/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins,
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
let choice = probed_choice();
let opted_into_system = opted_into_system_title_bar(saved);
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
// ignores the frame there).
let opted_into_app = cfg!(not(any(target_os = "macos", target_os = "windows"))) && opted_into_app_title_bar(saved);
+5
View File
@@ -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
+75 -11
View File
@@ -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)
}
}
+93
View File
@@ -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());
}
+42 -30
View File
@@ -143,38 +143,11 @@ impl Color {
}
/// HSB with hue in degrees 0..360, saturation and brightness 0..1.
pub fn to_hsb(&self) -> [f32; 3] {
let [r, g, b] = self.to_rgb();
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let d = max - min;
let h = if d <= 0.0 {
0.0
} else if max == r {
60.0 * (((g - b) / d).rem_euclid(6.0))
} else if max == g {
60.0 * ((b - r) / d + 2.0)
} else {
60.0 * ((r - g) / d + 4.0)
};
// f32 rounding in rem_euclid can yield exactly 360; wrap back to 0.
let h = if h >= 360.0 { 0.0 } else { h };
let s = if max <= 0.0 { 0.0 } else { d / max };
[h, s, max]
rgb_to_hsb(self.to_rgb())
}
pub fn from_hsb(h: f32, s: f32, v: f32) -> Self {
let h = h.rem_euclid(360.0) / 60.0;
let c = v * s;
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
let (r, g, b) = match h as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = v - c;
Color::Rgb { r: r + m, g: g + m, b: b + m }
let [r, g, b] = hsb_to_rgb([h, s, v]);
Color::Rgb { r, g, b }
}
/// `#rrggbb` (display RGB).
pub fn to_hex(&self) -> String {
@@ -327,6 +300,45 @@ impl Color {
}
}
/// HSB (hue in degrees 0..360, saturation and brightness 0..1) of RGB numbers 0..1, with no color
/// conversion ([`Color::to_hsb`] reads the display color first).
pub fn rgb_to_hsb([r, g, b]: [f32; 3]) -> [f32; 3] {
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let d = max - min;
let h = if d <= 0.0 {
0.0
} else if max == r {
60.0 * (((g - b) / d).rem_euclid(6.0))
} else if max == g {
60.0 * ((b - r) / d + 2.0)
} else {
60.0 * ((r - g) / d + 4.0)
};
// f32 rounding in rem_euclid can yield exactly 360; wrap back to 0.
let h = if h >= 360.0 { 0.0 } else { h };
let s = if max <= 0.0 { 0.0 } else { d / max };
[h, s, max]
}
/// RGB numbers 0..1 of HSB `[h, s, v]` (hue in degrees, saturation and brightness 0..1): the inverse
/// of [`rgb_to_hsb`].
pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
let h = h.rem_euclid(360.0) / 60.0;
let c = v * s;
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
let (r, g, b) = match h as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = v - c;
[r + m, g + m, b + m]
}
/// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations
/// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from.
pub fn keep_model(orig: Color, new: Color) -> Color {
+8 -4
View File
@@ -904,12 +904,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 +950,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 +1016,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 {
+18 -4
View File
@@ -128,11 +128,14 @@ fn live_inputs() -> u64 {
}
/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by
/// name and art) and patterns and the [`LiveInputs`] as they were, the art and its [`art_size`].
/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art
/// and its [`art_size`].
struct EvaluatedLive {
node: Node,
symbols: Vec<(String, Arc<Node>)>,
patterns: Vec<crate::PatternDef>,
swatches: crate::Shared<Vec<vectorcraft_color::Swatch>>,
swatch_groups: crate::Shared<Vec<vectorcraft_color::SwatchGroup>>,
inputs: u64,
art: Rc<Vec<Node>>,
size: usize,
@@ -146,6 +149,8 @@ impl EvaluatedLive {
&& self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| *name == s.name && Arc::ptr_eq(art, &s.art))
&& self.node == *n
&& self.patterns == doc.patterns
&& self.swatches == doc.swatches
&& self.swatch_groups == doc.swatch_groups
}
}
@@ -184,8 +189,8 @@ thread_local! {
/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while
/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of
/// `doc` or the [`LiveInputs`] have changed since, and on every click while it or the document's
/// symbols or patterns hold a placed document ([`holds_placed`]).
/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every
/// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]).
fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
let inputs = live_inputs();
let kept = EVALUATED.with_borrow_mut(|kept| {
@@ -206,7 +211,16 @@ fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
return art;
}
let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect();
let e = EvaluatedLive { node: n.clone(), symbols, patterns: doc.patterns.clone(), inputs, art: art.clone(), size };
let e = EvaluatedLive {
node: n.clone(),
symbols,
patterns: doc.patterns.clone(),
swatches: doc.swatches.clone(),
swatch_groups: doc.swatch_groups.clone(),
inputs,
art: art.clone(),
size,
};
EVALUATED.with_borrow_mut(|kept| {
kept.insert(0, e);
kept.truncate(LIVE_KEPT);
+31 -1
View File
@@ -605,11 +605,41 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
fn a_kept_evaluation_is_stale_after_the_live_inputs_change() {
let d = Document::new(100.0, 100.0);
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let e = EvaluatedLive { node: n.clone(), symbols: vec![], patterns: vec![], inputs: 7, art: std::rc::Rc::new(vec![]), size: 0 };
let e = kept_evaluation(&d, &n);
assert!(e.is_of(&d, &n, 7));
assert!(!e.is_of(&d, &n, 8));
}
/// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art.
fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive {
EvaluatedLive {
node: n.clone(),
symbols: vec![],
patterns: vec![],
swatches: d.swatches.clone(),
swatch_groups: d.swatch_groups.clone(),
inputs: 7,
art: std::rc::Rc::new(vec![]),
size: 0,
}
}
/// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's
/// pieces name swatches.
#[test]
fn a_kept_evaluation_is_stale_after_a_swatch_changes() {
let mut d = Document::new(100.0, 100.0);
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let e = kept_evaluation(&d, &n);
assert!(e.is_of(&d, &n, 7));
d.swatches.first_mut().unwrap().name = "Renamed".into();
assert!(!e.is_of(&d, &n, 7));
let mut d = Document::new(100.0, 100.0);
let e = kept_evaluation(&d, &n);
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Added".into(), swatches: vec![] });
assert!(!e.is_of(&d, &n, 7));
}
/// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a
/// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the
/// clipping path and the art.
+1
View File
@@ -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 }
+2
View File
@@ -82,6 +82,7 @@ mod select;
pub(crate) mod shaper;
pub mod shortcutset;
pub(crate) mod slices;
pub mod spelling;
mod stroke;
mod style;
pub mod stylelib;
@@ -321,6 +322,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());
+6 -11
View File
@@ -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| {
+1 -1
View File
@@ -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
),
+4 -3
View File
@@ -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> {
@@ -1,5 +1,5 @@
use super::{
Beside, BuilderMap, EngineError, FillRule, Node, NodeId, PathData, Point, Rect, Result, Session, SubPath, Touched, Value, b, bad, check_numbers,
Arc, Beside, BuilderMap, EngineError, FillRule, Node, NodeId, PathData, Point, Rect, Result, Session, Touched, Value, b, bad, check_numbers,
f64_or, fill_param, finite, gap_param, ids_json, json, marquee_param, po, points_param, remnant, replace_leaves, replace_with_pieces, root_ids,
shape_node, switch_or,
};
@@ -41,6 +41,7 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
let gap = gap_param(p);
// The map the Shape Builder tool already has, which a click or drag of it is made over.
let shared = s.tool.shape_builder_map().filter(|(_, g)| *g == gap);
let prepared = s.tool.shape_builder_merge();
let label = if erase { "Shape Builder Delete" } else { "Shape Builder" };
let (ids, merged, touched, split) = s.edit(label, |d, sel| {
let (shapes, leaves) = b::shape_builder_shapes(d, &roots, open_filled_as_closed);
@@ -89,16 +90,28 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
touched.add(map.hit(q, Some(tol)));
return Ok((ids, None, touched, Some(split)));
}
let mut touched = Touched { regions: marquee.map(|(a, b)| map.regions_in_marquee(a, b)).unwrap_or_default(), ..Default::default() };
touched.extend(&map.builder_hits_along(&pts, piece_tol));
touched.edges = map.erased_edges(&touched);
let touched = map.merge_touched(&pts, marquee, piece_tol);
if touched.is_empty() {
return Err(EngineError::Other("Shape Builder: no region under the pointer".into()));
}
let cuts: Vec<&SubPath> = touched.edges.iter().filter_map(|&k| map.edges.get(k)?.0.path.subpaths.first()).collect();
let inputs = b::merge_inputs(&leaves.iter().collect::<Vec<_>>(), open_filled_as_closed);
// The tool computed this merge on another thread when it would come out the same.
let ready = prepared.as_ref().filter(|m| {
shared.as_ref().is_some_and(|(s, _)| Arc::ptr_eq(s, &m.map) && std::ptr::eq(s.as_ref(), map))
&& m.gap == gap
&& m.touched == touched
&& m.inputs == inputs
});
let computed;
let geometry = match ready {
Some(m) => &m.geometry,
None => {
computed = b::merge_geometry(map, &touched, gap, &inputs);
&computed
}
};
let picked: Vec<&po::Region> = touched.regions.iter().filter_map(|&i| map.regions.get(i).map(|r| &r.0)).collect();
let faces = po::FaceMerger::with_gap(&map.shapes, gap_param(p));
let union = if picked.is_empty() { PathData::default() } else { faces.merge(&picked) };
let union = &geometry.union;
// Pick Color From Artwork: the merged shape takes the look of the front-most object under the
// drag's first point, else under its last point, else of the front-most object. Color
// Swatches: the current fill, with the rest of the look of the front-most object over the
@@ -115,7 +128,7 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
// What goes in place of each object the map was made from (none: it stays as it is).
let mut outs: Vec<Option<Vec<Node>>> = vec![];
let mut merged_id = None;
for (i, (sh, leaf)) in map.shapes.iter().zip(&leaves).enumerate() {
for (i, leaf) in leaves.iter().take(map.shapes.len()).enumerate() {
let mut out = None;
let pieces: Vec<usize> = map.lines.iter().enumerate().filter(|(_, (l, _))| l.key == i as u64).map(|(k, _)| k).collect();
if !pieces.is_empty() {
@@ -131,41 +144,15 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
}
out = Some(kept);
}
} else {
} else if let Some(Some(rest)) = geometry.rests.get(i) {
// A shape loses the regions deleted or merged, then the edges deleted (each one on
// its outline, shared edges from every shape along them).
let in_union = picked.iter().any(|r| r.sources.contains(&i));
let mut rest = if in_union {
// What is left of it: its faces not merged or deleted, united. They share their
// edges with the merged faces exactly, where subtracting the merged shape left
// slivers of the outline along them (#569). A sliver goes in only where the
// shape covers it and the merged shape does not take it in.
let kept: Vec<&po::Region> = map
.regions
.iter()
.enumerate()
.filter(|(k, (r, ..))| r.sources.contains(&i) && !touched.regions.contains(k))
.map(|(_, (r, ..))| r)
.collect();
if kept.is_empty() { PathData::default() } else { faces.merge_rest(i, &kept, &picked) }
// its outline, shared edges from every shape along them). What is left of its own
// outline keeps its fill rule; united faces fill with non-zero.
out = Some(if rest.path.is_empty() {
vec![]
} else {
b::node_outline(leaf).map_or_else(|| sh.path.clone(), |o| o.0)
};
let fill_closes = open_filled_as_closed && !leaf.appearance.fill_paint().is_none();
// Edges come back from the planar map within a few hundredths of the outlines they
// follow, whatever else is selected.
let cut_tol = b::outline_snap(&sh.path);
let mut cut = false;
for piece in &cuts {
if let Some(r) = po::cut_out(&rest, piece, fill_closes, cut_tol) {
rest = r;
cut = true;
}
}
if in_union || cut {
// What is left of its own outline keeps its fill rule; united faces fill with non-zero.
out = Some(if rest.is_empty() { vec![] } else { vec![remnant(d, leaf, rest, in_union.then_some(FillRule::NonZero))] });
}
vec![remnant(d, leaf, rest.path.clone(), rest.united.then_some(FillRule::NonZero))]
});
}
// The merged shape goes in place of the object it takes its look from, so it stays in
// that object's group (a clip group too).
+17 -9
View File
@@ -1027,6 +1027,12 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
if !direct { clear(s, &json!({ "ids": roots, "guides": true })) } else { cut_direct_selection(s, &roots) }
}
/// Remove the geometry copied by a direct-selection Cut, including selected guides in one edit.
/// Select every surviving piece while retaining intentional compound-path structure.
/// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths
/// lose only the copied geometry. An exhausted partial path is removed, along with its compound
/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection
/// references with surviving object IDs.
fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let st = s.doc()?;
let sel = st.selection.clone();
@@ -1035,6 +1041,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let gone = selection.guides.clone();
d.retain_guides(selection, |i, _| !gone.contains(&i));
let mut survivors = vec![];
let mut pieces = super::pathops::Beside::replacing(d, roots);
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
@@ -1042,20 +1049,22 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
d.remove(*id)?;
continue;
}
let Some(path) = node.path_data() else {
if node.path_data().is_none() {
d.remove(*id)?;
continue;
};
}
let original = super::path::deletion_source(d, *id)?;
let seg_refs = sel.segments.get(id);
let anchor_refs = sel.anchors.get(id);
let mut subpaths = Vec::new();
for (si, sp) in path.subpaths.iter().enumerate() {
let cuts = super::clipboard::subpath_selected_segments(sp, si, seg_refs, anchor_refs);
let owned = std::mem::take(&mut super::path::path_mut(d, *id)?.subpaths);
for (si, sp) in owned.into_iter().enumerate() {
let cuts = super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs);
if cuts.is_empty() {
subpaths.push(sp.clone());
subpaths.push(sp);
} else {
subpaths.extend(super::path::without_segments(sp.clone(), &cuts));
subpaths.extend(super::path::without_segments(sp, &cuts));
}
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
@@ -1068,11 +1077,10 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
d.remove(p)?;
}
} else {
let path_node = super::path::path_mut(d, *id)?;
path_node.subpaths = subpaths;
survivors.push(*id);
survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
}
}
pieces.finish(d)?;
selection.set(survivors);
selection.anchors.clear();
selection.segments.clear();
+5 -4
View File
@@ -93,16 +93,17 @@ pub use save::{
remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder,
templates_folder,
};
pub(crate) use screens::{
PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS,
check_settings as check_screen_settings, export as export_screens, safe_file_name, store_settings as store_screen_settings,
with_export_preset as with_screen_export_preset,
};
pub use screens::{
PRESET_FILE_EXTS as SCREEN_EXPORT_PRESET_EXTS, PRESET_FILE_FORMAT as SCREEN_EXPORT_PRESET_FORMAT, PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS,
PRESETS as SCREEN_PRESETS, SHARED_KEYS as SCREEN_SETTINGS_KEYS, ScreenExport, ScreenExportPreset, ScreenSize,
builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list,
preset_rows as screen_preset_rows,
};
pub(crate) use screens::{
check_settings as check_screen_settings, export as export_screens, safe_file_name, store_settings as store_screen_settings,
with_export_preset as with_screen_export_preset,
};
pub use svg::options_map as svg_options;
/// Atomic file writes (a temporary file renamed over the target: a failed write never damages the
/// file it replaces), for the apps' own writers too.
+3 -3
View File
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferen Line truncated
always,
load::open
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused",
has_doc,
screens::export_for_screens
),
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save Export Preset",
[],
None,
"{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, includeArtboardFill, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}",
"{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, includeArtboardFill, antiAlias, folder, fullDocument} (as document.exportForScreens; its other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused, and so are the keys document.exportForScreens refuses, in settings and in its format rows and settings → {name, created, settings}",
always,
screens::presets_save
),
+13 -10
View File
@@ -184,7 +184,8 @@ fn through_editing_data(
) -> (Document, Vec<String>, bool) {
let Some(layers) = layers else { return (doc, warnings, false) };
let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines;
let (doc, mut warnings, read) = vectorcraft_eps::layered_ai_from(layers, doc, warnings, outlined, opts.trust_editing_data, unit);
let (doc, mut warnings, read) =
vectorcraft_eps::layered_ai_from(layers, doc, warnings, outlined, opts.trust_editing_data, unit, opts.legacy_names);
// The layers weren't read (or couldn't be): the notes of reading the PDF part still hold.
if !read {
return (doc, warnings, false);
@@ -209,12 +210,12 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions)
return None;
}
let private = opened.illustrator_data()?;
Some(editing_copy_alone(&private))
Some(editing_copy_alone(&private, opts))
}
/// [`from_editing_data_alone`] of `private`, the editor's copy already read.
fn editing_copy_alone(private: &[u8]) -> Result<(Document, Vec<String>)> {
vectorcraft_eps::ai_alone(private)
fn editing_copy_alone(private: &[u8], opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
vectorcraft_eps::ai_alone_with(private, opts.legacy_names)
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
}
@@ -247,7 +248,7 @@ fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: &EngineError) -> Option
return None;
}
let private = vectorcraft_pdf::illustrator_data_without_pdf_part(bytes, opts.password.as_deref())?;
let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit).ok()?;
let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit, opts.legacy_names).ok()?;
let notes = std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
Some(outlined_if_asked(doc, notes, opts))
}
@@ -323,7 +324,7 @@ pub(crate) fn page_or_editing_data(
match read {
Ok((doc, notes)) => Ok((doc, notes, false)),
Err(e) if is_placeholder(&e) => {
let l = load_with(name, bytes, &LoadOptions { password: opts.password.clone(), ..Default::default() })?;
let l = load_with(name, bytes, &LoadOptions { password: opts.password.clone(), legacy_names: opts.legacy_names, ..Default::default() })?;
Ok((l.doc, l.warnings, true))
}
Err(e) if page_index == 0 => match load_with(name, bytes, &LoadOptions { pages: None, ..opts.clone() }) {
@@ -352,7 +353,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
_ if matches!(format.id, "eps" | "ps") || vectorcraft_pdf::is_postscript(bytes) => {
let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes)));
restore_or_import(editing, || {
let r = vectorcraft_eps::import_trusting(bytes, opts.editing_data, opts.trust_editing_data)
let r = vectorcraft_eps::import_names(bytes, opts.editing_data, opts.trust_editing_data, opts.legacy_names)
.map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?;
Ok((r.document, r.warnings))
})?
@@ -391,7 +392,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
{
let pages = o.trim_pages();
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit) {
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names) {
Ok((mut doc, warnings)) => {
doc.setup.bleed = pages.bleed;
editing_data = true;
@@ -413,8 +414,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// decoded draws nothing either): its notes are at most the page's own.
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
let copy_alone = || match &private {
Some(private) => Some(editing_copy_alone(private)),
None if layers.is_some() => opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p)),
Some(private) => Some(editing_copy_alone(private, opts)),
None if layers.is_some() => {
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts))
}
None => None,
};
let alone = (r.only_text || empty)
+15 -3
View File
@@ -39,6 +39,9 @@ pub struct LoadOptions {
/// A `.ai` opens from its editing copy even where that draws differently from its PDF part
/// (which can be older than it), with a warning, instead of from the PDF part.
pub trust_editing_data: bool,
/// The encoding names in a `.ai` or EPS's editing data are read in when they aren't UTF-8
/// (`legacyNameEncoding`).
pub legacy_names: vectorcraft_eps::NameEncoding,
/// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries;
/// off, it opens as another app would open it, from the editing copy of its art or its pages.
pub native: bool,
@@ -57,6 +60,7 @@ impl Default for LoadOptions {
dxf: Default::default(),
editing_data: true,
trust_editing_data: false,
legacy_names: vectorcraft_eps::NameEncoding::default(),
native: true,
}
}
@@ -65,8 +69,9 @@ impl Default for LoadOptions {
impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false | `always`) and `dxf`
/// (the DXF import options).
/// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false | `always`),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF
/// import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
let pages = match p.get("pages").filter(|v| !v.is_null()).or_else(|| p.get("page").filter(|v| !v.is_null())) {
None => None,
@@ -95,8 +100,15 @@ impl LoadOptions {
Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true),
Some(v) => (v.as_bool().ok_or_else(|| bad(cmd, "editingData must be true, false or \"always\""))?, false),
};
let legacy_names = match p.get("legacyNameEncoding").filter(|v| !v.is_null()) {
None => vectorcraft_eps::NameEncoding::default(),
Some(v) => v
.as_str()
.and_then(vectorcraft_eps::NameEncoding::from_label)
.ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?,
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, native: true })
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, legacy_names, native: true })
}
/// Does the document read only part of the file, or read it differently (a page range, another
+3 -1
View File
@@ -752,6 +752,8 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
/// file becomes the document's own; the live document gets them in [`SaveJob::finish`]). Bad
/// options fail here, before anything is encoded.
pub fn save_job(s: &mut Session, plan: SavePlan) -> Result<SaveJob> {
// A Shape Builder merge still being computed for a click is saved with the document.
s.finish_tool_edit_later()?;
// The web build, without a clock, leaves the dates unless given one.
let at = if plan.path.is_some() && plan.retargets() { clock_date(s, "modified", plan.modified) } else { None };
job_for_stamped(s, s.doc()?, plan, at)
@@ -1102,7 +1104,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
+35 -2
View File
@@ -193,7 +193,10 @@ pub(super) fn name_without_device(name: &str) -> String {
}
/// Keys of a format row that aren't encoder options.
const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
/// The writable formats a format row can't name.
pub(crate) const UNWRITTEN_FORMATS: [&str; 5] = ["template", "txt", "dxf", "emf", "wmf"];
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
struct Row {
@@ -214,7 +217,7 @@ impl Row {
return Err(bad(C, "each format is an object {format, scale?, suffix?}"));
}
let format = writable(C, Some(str_param(row, "format").unwrap_or("png")), None)?;
if matches!(format.id, "template" | "txt" | "dxf" | "emf" | "wmf") {
if UNWRITTEN_FORMATS.contains(&format.id) {
return Err(bad(C, "Export for Screens writes png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai or vectorcraft"));
}
// Vector formats have no pixel size: it doesn't apply and adds no @2x suffix (not even one
@@ -285,6 +288,36 @@ impl Row {
/// or where to.
pub const SHARED_KEYS: [&str; 6] = ["formats", "preset", "settings", "prefix", "subfolders", "antiAlias"];
/// The keys `document.exportForScreens` reads: those of [`ScreenParams`], the formats and their
/// settings, `antiAlias`, `exportPreset` and `openLocation`, which the app reads.
pub(crate) const PARAM_KEYS: [&str; 25] = [
"artboard",
"artboards",
"range",
"folder",
"zip",
"fullDocument",
"includeBleed",
"includeArtboardFill",
"subfolders",
"preset",
"prefix",
"assets",
"layers",
"selection",
"name",
"counterStart",
"counterPer",
"date",
"folders",
"pdfs",
"formats",
"settings",
"antiAlias",
"exportPreset",
"openLocation",
];
/// What `document.exportForScreens` reads besides the formats.
#[derive(Default, Deserialize)]
#[serde(default, rename_all = "camelCase")]
@@ -1022,6 +1022,21 @@ fn an_ai_file_saved_without_its_pdf_part_pastes_from_its_editing_data() {
assert!(e.contains("placeholder"), "{e}");
}
/// `file.place` reads a `.ai` saved without its PDF part in the `legacyNameEncoding` it is given.
#[test]
fn an_ai_file_saved_without_its_pdf_part_places_in_the_encoding_picked() {
let mut data = ai::sample_data();
let at = data.windows(4).position(|w| w == b"Pair").unwrap();
// 빨강 in code page 949.
data.splice(at..at + 4, br"\273\241\260\255".iter().copied());
let file = vectorcraft_format::base64_encode(&ai::ai(&compressed(&data), PLACEHOLDER));
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = s.execute("file.place", &json!({"name": "art.ai", "dataBase64": file, "link": false, "legacyNameEncoding": "windows-949"})).unwrap();
let placed = s.doc().unwrap().doc.layers[0].children().unwrap()[0].clone();
assert_eq!(names(&placed.children().unwrap()[1..]), ["빨강", "Ring", "Window"], "{r}");
}
#[test]
fn an_ai_file_saved_without_its_pdf_part_places_from_its_editing_data() {
let [sample, damaged, plain] = placeholder_files();
@@ -184,6 +184,41 @@ showpage
assert!(e.contains("junk.eps"), "{e}");
}
/// `legacyNameEncoding` picks the code page of a legacy `.ai`'s layer names that aren't UTF-8; by
/// default they come in as Windows-1252, with a warning naming them. An encoding it doesn't know is
/// refused.
#[test]
fn legacy_ai_layer_names_open_in_the_encoding_picked() {
let mut s = Session::new();
// A layer named 레이어 1 in Windows code page 949.
let ai = b"%!PS-Adobe-3.0\n%%BoundingBox: 0 0 100 100\n%%DocumentNeededResources: procset Adobe_IllustratorA_AI3 1.0 0\n%AI3_TemplateBox: 50 50 50 50\n%%EndComments\n\
%%BeginProlog\n%%IncludeResource: procset Adobe_IllustratorA_AI3 1.0 0\n%%EndProlog\n%%BeginSetup\nAdobe_IllustratorA_AI3 /initialize get exec\n%%EndSetup\n\
%AI5_BeginLayer\n1 1 1 1 0 0 2 0 0 0 Lb\n(\\267\\271\\300\\314\\276\\356 1) Ln\n0 0 0 1 K\n0 i 1 w\n10 10 m\n90 90 L\nS\nLB\n%AI5_EndLayer--\n%%PageTrailer\n%%Trailer\n%%EOF\n";
let open_as = |s: &mut Session, encoding: Option<&str>| {
let mut p = json!({"name": "korean.ai", "dataBase64": vectorcraft_format::base64_encode(ai)});
if let Some(e) = encoding {
p["legacyNameEncoding"] = json!(e);
}
s.execute("document.open", &p)
};
let r = open_as(&mut s, None).unwrap();
assert_eq!(s.doc().unwrap().doc.layers[0].name.as_deref(), Some("·¹À̾î 1"));
assert_eq!(
r["warnings"],
json!(["the name `·¹À̾î 1` isn't UTF-8 and was read as windows-1252: if it looks wrong, open the file with another legacyNameEncoding"])
);
for encoding in ["windows-949", "EUC-KR"] {
let r = open_as(&mut s, Some(encoding)).unwrap();
assert_eq!(s.doc().unwrap().doc.layers[0].name.as_deref(), Some("레이어 1"), "{encoding}");
assert!(r["warnings"][0].as_str().is_some_and(|w| w.contains("`레이어 1`") && w.contains("windows-949")), "{r}");
}
let e = open_as(&mut s, Some("utf-16")).unwrap_err();
assert!(
matches!(&e, EngineError::BadParams { msg, .. } if msg == "legacyNameEncoding must be one of windows-1252, macintosh, windows-949, shift_jis, gbk, big5"),
"{e}"
);
}
#[test]
fn eps_files_place_as_one_group_clipped_to_their_bounding_box() {
let mut s = rich();
+4 -1
View File
@@ -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 }
}
}
+12
View File
@@ -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"));
}
+5 -3
View File
@@ -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;
}
+48 -10
View File
@@ -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() {
+178 -34
View File
@@ -6,9 +6,9 @@
//! by `|`; a `?` marks an optional one, and a `:`, `=` or `(` starts what the entry says about it. An entry that starts
//! with `…` stands for keys listed elsewhere: those of each command it names after `as` or `of`
//! (`…settings as file.new`), or, naming none, any key (the options of the format an export picks). Objects inside a value aren't
//! described key by key, so only the top level is checked, except in an export's options: those
//! are checked against the options of the formats the command can write, in `marks`, `bleed` and
//! the other objects too ([`check_export_options`]).
//! described key by key, so only the top level is checked, except in the options of an export, a
//! save or Export for Screens: those are checked against the options of the formats the command
//! can write, in `marks`, `bleed` and the other objects too ([`check_export_options`]).
//!
//! [`Session::execute`] answers a key the description doesn't name with a parameter error
//! ([`check_params`]), for every caller (the app, the control channel, MCP, the CLI) and for the
@@ -531,25 +531,183 @@ fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Val
Ok(())
}
/// The options of an export command `id`. `document.export`, `document.exportSelection` and
/// `document.serialize` take a key that some format reads (one object can carry several formats'
/// options; `document.formats` lists them). `document.exportPdf`, `document.pdfSettings` and
/// `pdf.preset.save` take a key that PDF reads, `document.exportEps` one that EPS reads and
/// `document.exportDxf` one that DXF reads. Where a command takes `marks`, `bleed`, `flattener` or
/// another object option of PDF or EPS, only the object's own keys pass. An SVG export's `svg`
/// object is checked when it is read. Saved presets are not checked: one with a key that is no
/// longer read keeps loading.
/// `given`, the options object at `within` (`""` for the params themselves, `options.`,
/// `formats[0].`), has only `keys`, and only their own keys in the PDF and EPS object options
/// (`trees`). `why_not` says why a key that is not near any of `keys` is refused, and where the
/// keys are listed.
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()) {
return Err(bad(
id,
match nearest(key, keys) {
Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"),
None => format!("unknown parameter `{within}{key}`; {why_not}"),
},
));
}
if let (Some(Value::Object(schema)), Value::Object(value)) = (trees.get(key), value) {
check_option_tree(id, &format!("{within}{key}."), value, schema)?;
}
}
Ok(())
}
/// Why an export option that no format reads is refused.
const NO_FORMAT: &str = "no format takes it (see document.formats)";
/// Why a save option that no save format reads is refused.
const NO_SAVE_FORMAT: &str = "no save format takes it (see file.formatOptions)";
/// The format ids Export for Screens writes: the writable formats, those exporter plug-ins add
/// included, but those it doesn't write.
pub fn screen_formats() -> Vec<&'static str> {
use super::fileio::{FORMATS, SCREEN_UNWRITTEN_FORMATS, plugin_formats};
let added = plugin_formats();
FORMATS.iter().chain(added.iter().copied()).filter(|f| f.write && !SCREEN_UNWRITTEN_FORMATS.contains(&f.id)).map(|f| f.id).collect()
}
/// The keys a format row of Export for Screens, and the settings of a format, take: the row's own
/// (`format`, `scale`…), `includeArtboardFill` and `richBlack`, which the encoders read from a
/// row's options (`with_artboard_fills`, the render options), `params`, an exporter plug-in's own,
/// and a key some format reads, as `document.export` takes them.
fn screen_option_keys() -> Vec<&'static str> {
use super::fileio::{FORMATS, SCREEN_ROW_KEYS};
let mut keys: Vec<&str> = SCREEN_ROW_KEYS.to_vec();
keys.extend(["includeArtboardFill", "richBlack", "params"]);
keys.extend(FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).map(|o| o.name));
keys
}
/// A format row of Export for Screens, or the settings of a format, without the keys the export
/// refuses in it ([`check_screen_rows`]), inside `marks`, `svg` and the other object options too:
/// a saved row or preset that holds a key that is no longer read loads without it.
pub fn drop_unread_row_options(row: &mut serde_json::Map<String, Value>) {
fn retain_tree(o: &mut serde_json::Map<String, Value>, schema: &serde_json::Map<String, Value>) {
o.retain(|k, _| schema.contains_key(k));
for (k, v) in o.iter_mut() {
if let (Some(Value::Object(inner)), Value::Object(v)) = (schema.get(k), v) {
retain_tree(v, inner);
}
}
}
let keys = screen_option_keys();
row.retain(|k, _| keys.contains(&k.as_str()));
let trees = screen_option_trees();
for (k, v) in row.iter_mut() {
if let (Some(Value::Object(schema)), Value::Object(v)) = (trees.get(k), v) {
retain_tree(v, schema);
}
}
}
/// [`option_trees`] of Export for Screens: its remembered settings mark PDF security whose
/// passwords were left out with `security.passwordRequired`, which the export reads.
fn screen_option_trees() -> Value {
let mut trees = option_trees();
if let Some(security) = trees.get_mut("security").and_then(Value::as_object_mut) {
security.insert("passwordRequired".into(), Value::Null);
}
trees
}
/// The object options an export or save checks key by key: PDF's `marks`, `bleed` and the others,
/// the flattener's, and SVG's `svg` with the artboard keys it may carry.
fn option_trees() -> Value {
let mut trees = pdf_option_tree();
if let Some(tree) = trees.as_object_mut() {
tree.insert("flattener".into(), serde_json::to_value(super::flatten::FlattenOptions::default()).unwrap_or_default());
let mut svg = serde_json::to_value(vectorcraft_svg::ExportOptions::default()).unwrap_or_default();
if let Some(svg) = svg.as_object_mut() {
svg.extend(super::fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]).map(|k| (k.to_string(), Value::Null)));
}
tree.insert("svg".into(), svg);
}
trees
}
/// The format rows (`formats`) and the per-format `settings` of Export for Screens params `p`, at
/// `within` (`settings.` in `document.exportPresets.save`). A row, and the settings of a format,
/// take [`screen_option_keys`]; `settings` takes the formats Export for Screens writes.
fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map<String, Value>) -> Result<()> {
let keys = screen_option_keys();
let trees = &screen_option_trees();
if let Some(Value::Array(rows)) = p.get("formats") {
for (i, row) in rows.iter().enumerate() {
if let Value::Object(row) = row {
check_option_keys(id, &format!("{within}formats[{i}]."), row, &keys, NO_FORMAT, trees)?;
}
}
}
if let Some(Value::Object(settings)) = p.get("settings") {
let formats = screen_formats();
for (format, options) in settings {
if !formats.contains(&format.as_str()) {
let why = match nearest(format, &formats) {
Some(near) => format!("did you mean `{within}settings.{near}`?"),
None => format!("`{within}settings` takes: {}", formats.join(", ")),
};
return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}")));
}
if let Value::Object(options) = options {
check_option_keys(id, &format!("{within}settings.{format}."), options, &keys, NO_FORMAT, trees)?;
}
}
}
Ok(())
}
/// The options of an export or save command `id`. `document.export`, `document.exportSelection`
/// and `document.serialize` take a key that some format reads (one object can carry several
/// formats' options; `document.formats` lists them). `document.exportPdf`, `document.pdfSettings`
/// and `pdf.preset.save` take a key that PDF reads, `document.exportEps` one that EPS reads and
/// `document.exportDxf` one that DXF reads. `document.save`, `file.saveAs`, `file.saveCopy` and
/// `file.saveAsTemplate` take, beside the path and in `options`, a key that some save format
/// reads. `document.exportForScreens` takes the keys it reads, and checks its format rows and
/// settings ([`check_screen_rows`]), as `document.exportPresets.save` does in its `settings` and
/// `assets.export` and `assets.settings.set` do in theirs.
/// Where a command takes `marks`, `bleed`, `flattener`, `svg` or another object option of PDF,
/// EPS or SVG, only the object's own keys pass ([`option_trees`]). Saved presets are not checked:
/// one with a key that is no longer read keeps loading.
fn check_export_options(id: &str, params: &Value) -> Result<()> {
use super::fileio::{FORMATS, dxf, eps, pdf};
use super::fileio::{FORMATS, SAVE_FORMATS, SCREEN_PARAM_KEYS, TEMPLATE_FORMATS, dxf, eps, pdf};
let Value::Object(given) = params else { return Ok(()) };
match (id, given.get("settings")) {
("document.exportForScreens", _) => {
if let Some(key) = given.keys().find(|k| !SCREEN_PARAM_KEYS.contains(&k.as_str())) {
return Err(unknown(id, key, &SCREEN_PARAM_KEYS));
}
return check_screen_rows(id, "", given);
}
("document.exportPresets.save", Some(Value::Object(settings))) => {
let why = format!("`settings` takes: {}", SCREEN_PARAM_KEYS.join(", "));
check_option_keys(id, "settings.", settings, &SCREEN_PARAM_KEYS, &why, &Value::Null)?;
return check_screen_rows(id, "settings.", settings);
}
// Export Assets exports with, and stores, Export for Screens' format rows and settings.
("assets.export" | "assets.settings.set", _) => return check_screen_rows(id, "", given),
_ => {}
}
let mut keys: Vec<&str> = vec!["path", "format", "acknowledgeLoss"];
// A save's `options` and the keys they take.
let mut inner: Option<(&serde_json::Map<String, Value>, Vec<&str>)> = None;
let why_not = match id {
"document.save" | "file.saveAs" | "file.saveCopy" | "file.saveAsTemplate" => {
let saved = FORMATS.iter().filter(|f| SAVE_FORMATS.contains(&f.id) || TEMPLATE_FORMATS.contains(&f.id));
let options: Vec<&str> = saved.flat_map(|f| f.options).map(|o| o.name).collect();
if let Some(Value::Object(o)) = given.get("options") {
inner = Some((o, options.clone()));
}
keys.extend(["options", "modified"]);
keys.extend(options);
NO_SAVE_FORMAT
}
"document.export" | "document.exportSelection" | "document.serialize" => {
// `richBlack` is Appearance of Black's setting for a raster export, and `params` an
// exporter plug-in's own.
keys.extend(["includeArtboardFill", "selectedOnly", "richBlack", "params"]);
keys.extend(FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).map(|o| o.name));
"no format takes it"
NO_FORMAT
}
"document.exportPdf" | "document.pdfSettings" | "pdf.preset.save" => {
keys.push("includeArtboardFill");
@@ -559,38 +717,24 @@ fn check_export_options(id: &str, params: &Value) -> Result<()> {
"pdf.preset.save" => keys.extend(["name", "newName", "description"]),
_ => {}
}
"PDF doesn't take it"
"PDF doesn't take it (see document.formats)"
}
"document.exportEps" => {
keys.push("includeArtboardFill");
keys.extend(eps::OPTIONS.iter().map(|o| o.name));
"EPS doesn't take it"
"EPS doesn't take it (see document.formats)"
}
"document.exportDxf" => {
keys.extend(dxf::OPTIONS.iter().map(|o| o.name));
"DXF doesn't take it"
"DXF doesn't take it (see document.formats)"
}
_ => return Ok(()),
};
let mut trees = pdf_option_tree();
if let Some(tree) = trees.as_object_mut() {
tree.insert("flattener".into(), serde_json::to_value(super::flatten::FlattenOptions::default()).unwrap_or_default());
let trees = option_trees();
if let Some((o, options)) = inner {
check_option_keys(id, "options.", o, &options, NO_SAVE_FORMAT, &trees)?;
}
for (key, value) in given {
if !keys.contains(&key.as_str()) {
return Err(bad(
id,
match nearest(key, &keys) {
Some(near) => format!("unknown parameter `{key}`; did you mean `{near}`?"),
None => format!("unknown parameter `{key}`; {why_not} (see document.formats)"),
},
));
}
if let (Some(Value::Object(schema)), Value::Object(value)) = (trees.get(key), value) {
check_option_tree(id, &format!("{key}."), value, schema)?;
}
}
Ok(())
check_option_keys(id, "", given, &keys, why_not, &trees)
}
/// [`check_keys`] for an engine command, the steps of a `command.batch` or an `action.batch` included,
+57 -10
View File
@@ -1,6 +1,7 @@
//! Path editing commands (used by the Pen and Direct Selection tools and Object → Path).
use std::collections::BTreeSet;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling};
@@ -1206,6 +1207,11 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Delete direct-selected anchors or segments and whole selected objects in one edit.
/// Leave surviving pieces selected, splitting ordinary contours into independent sibling objects.
/// `p.guides: true` also removes the selected ruler guides in that edit; otherwise guides remain.
/// Layers are retained, and an object removed with a selected ancestor is not removed twice.
/// Returns JSON `null` on success; selection is replaced by the surviving object IDs.
pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
// `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step.
let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?;
@@ -1237,11 +1243,13 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
if d.node(*id).is_none() {
continue;
}
let remove_node = {
let original = deletion_source(d, *id)?;
let subpaths: Vec<SubPath> = {
let path = path_mut(d, *id)?;
let subpaths = std::mem::take(&mut path.subpaths);
if let Some(refs) = segments.get(id) {
// A segment pick cuts its connection, keeping every neighboring cubic.
path.subpaths = std::mem::take(&mut path.subpaths)
subpaths
.into_iter()
.enumerate()
.flat_map(|(si, sp)| {
@@ -1249,11 +1257,11 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
without_segments(sp, &cuts)
})
.filter(|s| s.anchors.len() >= 2)
.collect();
.collect()
} else {
// Remove every selected anchor against the original indexes, keeping surviving
// stretches separate rather than joining across deleted anchors.
path.subpaths = std::mem::take(&mut path.subpaths)
subpaths
.into_iter()
.enumerate()
.flat_map(|(si, sp)| {
@@ -1261,16 +1269,14 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
without_anchors(sp, &gone)
})
.filter(|s| s.anchors.len() >= 2)
.collect();
.collect()
}
path.subpaths.retain(|s| s.anchors.len() >= 2);
path.subpaths.is_empty()
};
if remove_node {
if subpaths.is_empty() {
emptied.put(d, *id, vec![])?;
} else {
// The remainder is selected whole, so the next Delete removes it.
survivors.push(*id);
// Every remaining piece is selected whole, so the next Delete removes them.
survivors.extend(replace_deleted_pieces(d, &mut emptied, original, subpaths)?);
}
}
emptied.finish(d)?;
@@ -1280,6 +1286,47 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Retain path `id` from `d` without copying its geometry before deletion takes its subpaths.
/// The shared snapshot supplies the original path classification and, only if needed, gradient
/// bounds after the working node's geometry has moved. Returns `NoNode` for a missing/non-path ID.
pub(super) fn deletion_source(d: &Document, id: NodeId) -> Result<Arc<Node>> {
let (parent, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
// Verify the cached position still names this path before retaining the shared node.
d.children(parent)
.and_then(|children| children.get(index))
.filter(|n| n.id == id && n.path_data().is_some())
.cloned()
.ok_or(EngineError::NoNode(id))
}
/// Replace the deleted path in `d` with the nonempty surviving runs in `subpaths`.
/// `original` must be retained by [`deletion_source`] before taking the working node's geometry.
/// An ordinary single-contour source becomes siblings; multi-subpath paths and compound members
/// retain their node. Only actual splits pin unplaced gradients to `original`'s bounds; already
/// placed gradients and connected remainders retain their placement behavior.
///
/// Returns the surviving IDs in `subpaths` order (the first keeps the source ID). The original
/// node's geometry is updated immediately. Replacements are handed to `beside`, which may defer
/// insertion; the caller must finish that [`Beside`] before using new IDs in `d`.
/// Missing/invalid paths return an error.
pub(super) fn replace_deleted_pieces(d: &mut Document, beside: &mut Beside, original: Arc<Node>, subpaths: Vec<SubPath>) -> Result<Vec<NodeId>> {
let id = original.id;
let single = original.path_data().is_some_and(|p| p.subpaths.len() == 1);
if single && compound_or_self(d, id) == id {
// Pin only actual splits: each new object's smaller bounds would otherwise refit its gradients.
if subpaths.len() > 1
&& original.appearance.has_unplaced_gradient()
&& let Some(bounds) = original.geometric_bounds()
{
d.node_mut(id).ok_or(EngineError::NoNode(id))?.appearance.pin_gradients(bounds);
}
super::draw2::replace_with_pieces(d, beside, id, subpaths.into_iter().map(PathData::single).collect())
} else {
path_mut(d, id)?.subpaths = subpaths;
Ok(vec![id])
}
}
/// 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> {
+134 -38
View File
@@ -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
@@ -36,6 +39,10 @@
//! (`vc_settings_*`, `vc_cache_*`), in the plug-in store under its id ([`crate::store`]):
//! `plugin.clearCache` empties the cache, `plugin.list` and `plugin.info` give its size
//! (`cacheBytes`), replacing the plug-in keeps both and `plugin.remove` deletes them.
//!
//! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type,
//! images or symbol instances of those kinds, to read only: its output must return each of them
//! unchanged ([`objects::decode_output_with`]).
use std::sync::{Arc, Mutex, RwLock};
@@ -75,6 +82,9 @@ pub fn describe(p: &Plugin) -> Value {
if m.budget == Budget::Heavy {
v["budget"] = json!("heavy");
}
if !m.inputs.is_empty() {
v["inputs"] = json!(m.inputs);
}
if m.paint_output {
v["paintOutput"] = json!(true);
}
@@ -126,6 +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): 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),
@@ -192,8 +205,10 @@ impl FilterRun {
st.selection.objects.clone()
}
};
// Without `doc.read` a filter is given no objects: it can only add new ones.
let inputs = if may.contains(&Permission::DocRead) { objects::filter_targets(&st.doc, &selected) } else { Vec::new() };
// Without `doc.read` a filter is given no objects: it can only add new ones. Type, images
// and symbol instances only when its manifest asks for them (`inputs`).
let kinds = m.input_kinds();
let inputs = if may.contains(&Permission::DocRead) { objects::filter_targets_with(&st.doc, &selected, &kinds) } else { Vec::new() };
let parent = st.insertion_parent();
let bounds = st.doc.bounds_of(&inputs, false);
let board = bounds.and_then(|b| st.doc.artboard_at(b.center())).and_then(|i| st.doc.artboards.get(i)).or(st.doc.artboards.first());
@@ -206,10 +221,12 @@ impl FilterRun {
params["_context"]["mode"] = json!("command");
params["_context"]["command"] = json!(cmd.id);
}
let input = objects::encode_input(&st.doc, &inputs);
let params = serde_json::to_vec(&params).map_err(|e| bad(c, e.to_string()))?;
// The input and the parameters may use half the plug-in's memory together.
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
let document = (st.uid, st.revision);
Ok(FilterRun { plugin, command, input, params, inputs, parent, document })
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document })
}
/// The plug-in, for its name and budget.
@@ -249,12 +266,13 @@ impl FilterRun {
}
/// Applies the plug-in's `output` to the active document as one undo step: its objects, and what
/// it keeps with the document from now on. An output its permissions don't allow is refused,
/// and the document stays as it was.
/// it keeps with the document from now on. An output its permissions don't allow, and one that
/// changes or leaves out a read-only object it was given, is refused, and the document stays as
/// it was.
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
let m = self.plugin.manifest();
let may = m.permissions();
let out = objects::decode_output(output).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));
}
@@ -540,6 +558,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 {
@@ -549,13 +606,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)?),
@@ -584,25 +645,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
@@ -618,6 +692,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());
@@ -828,19 +918,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())));
@@ -874,7 +970,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -892,7 +988,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 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. 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
),
@@ -901,7 +997,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
),
@@ -910,7 +1006,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
),
@@ -919,7 +1015,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
),
+6
View File
@@ -678,6 +678,12 @@ impl Session {
for e in self.prefs.keep_folders(&mut p) {
log::warn!("{e}");
}
// The edit the active tool computes on another thread is applied first (the Preferences
// dialog applies its settings here, outside a command). A failure to apply it was the
// edit's own, and the preferences apply all the same.
if self.depth == 0 {
let _ = self.finish_tool_edit_later();
}
let grid_changed = p.gridline_every != self.prefs.gridline_every || p.grid_subdivisions != self.prefs.grid_subdivisions;
let history_changed = p.history_states != self.prefs.history_states;
let tile_edge_changed = p.pattern_tile_edge_color != self.prefs.pattern_tile_edge_color;
+4 -3
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Setup",
[],
None,
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
has_doc,
setup
),
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Preview",
[],
None,
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
has_doc,
preview
),
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print",
[],
Some("Cmd+P"),
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
has_doc,
print
),
@@ -228,6 +228,7 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
view: sh.view,
window: sh.window,
place: sh.place,
copies: &sh.copies,
area: sh.area,
marks: sh.marks.as_ref(),
negative: sh.negative,
+319
View File
@@ -0,0 +1,319 @@
//! 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::ops::Range;
use craft_proof::{IssueKind, Options, ProofLang};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind};
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 ignored = &st.spelling_ignored;
let opts = Options::default();
let mut words = vec![];
let mut more = false;
'texts: for id in ids {
let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue };
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;
}
// 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, &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 words.len() == MAX_WORDS {
more = true;
break 'texts;
}
words.push(json!({ "id": id.0, "start": start, "end": end, "word": word, "lang": issue.lang.tag() }));
}
// Past the paragraph and its `\n`.
para_start = para_end + 1;
}
}
Ok(json!({ "words": words, "more": more }))
}
/// `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);
save_dictionary(s, &[], C).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")));
}
save_dictionary(s, std::slice::from_ref(&word), C).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 {
save_dictionary(s, &[], C)?;
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);
save_dictionary(s, std::slice::from_ref(&word), C).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);
}
}
+3 -1
View File
@@ -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;
+29 -1
View File
@@ -1,4 +1,4 @@
use super::{NodeId, Value, cmd};
use super::{NodeId, Value, cmd, find_command};
/// The commands that act on the active artboard (#693), which the app passes as their `artboard`:
/// Paste in Place, in Front and in Back paste onto it, Align to Artboard aligns to it, Distribute
@@ -78,6 +78,34 @@ pub(crate) fn strip_replay_only(id: &str, p: &mut Value) {
}
}
/// Queries that apply the edit the active tool is computing before they run, as edits do
/// ([`Session::finish_tool_edit`]): a batch runs edits, Find Objects with `select`, Select All
/// Instances and Lock Guides change the selection, and the proof views, the preferences and added
/// fonts give the documents new revisions (they draw again, and type lays out again).
const WAIT_FOR_TOOL_EDIT: &[&str] = &[
"command.batch",
"document.find",
"symbol.selectInstances",
"view.guides.lock",
"view.proofSetup",
"view.proofColors",
"view.overprintPreview",
"view.separationsPreview",
"prefs.set",
"prefs.reset",
"text.addFontFiles",
];
/// Does command `id`, run on its own, first apply the edit the active tool is computing on
/// another thread and the input held for it ([`Session::finish_tool_edit`])? Every command that
/// can edit, select, save or give a document a new revision does; queries that only read do not
/// (`commands_that_do_not_wait_for_a_tool_edit_change_no_document` in the command sweep checks
/// them). A frontend that adds params from
/// its own state (the active artboard) applies them first itself.
pub fn waits_for_tool_edit(id: &str) -> bool {
find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id))
}
/// Journaled commands that write a file and change nothing in the document: with an object of a
/// dynamic symbol instance's art selected, they read the instance as queries do
/// ([`crate::Session::execute`]).
+4
View File
@@ -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
@@ -288,6 +291,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(),
+27 -1
View File
@@ -62,6 +62,19 @@ pub struct Session {
/// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes
/// back as it was at the release ([`Session::pointer`]).
pub(crate) lender: Option<Box<dyn Tool>>,
/// Pointer and key input that came while the tool computed an edit on another thread, each with
/// its number and view, made in order once the edit is applied.
held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>,
/// The number the next pointer or key event handed to the session gets.
input_count: u64,
/// The number of the event whose handling started the edit the tool is computing.
edit_started_by: Option<u64>,
/// Set while the tool's edit and the input held for it are applied: the commands that run then
/// do not start applying them again.
settling_tool_edit: bool,
/// Requests for the UI from making held input where nothing could take them (a command, a tool
/// switch), which the next [`Session::tool_poll`] returns.
held_ui: Vec<UiRequest>,
/// The active document (its uid) and its [`History::step`] when the tool last handled a pointer
/// event or drew its overlays: when they differ at the next one, the tool is told first
/// ([`vectorcraft_tools::Tool::history_moved`]). None until the first.
@@ -135,15 +148,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`]).
@@ -308,7 +334,7 @@ mod session;
pub(crate) use command_sets::SELECTS_GIVEN_IDS;
#[cfg(test)]
use command_sets::given_ids;
pub use command_sets::{FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD};
pub use command_sets::{FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
pub use doc_state::{DocState, OpenRows, RecalledSelection};
pub use error::{EngineError, Result};
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
+1 -1
View File
@@ -176,7 +176,7 @@ pub struct Prefs {
pub system_title_bar: bool,
/// Linux and the BSDs: draw the app bar as the title bar in sessions where the desktop draws
/// the frame (X11, Wayland compositors with server-side decorations, XWayland), as on GNOME.
/// Read when the app starts; System Title Bar and `VECTORCRAFT_TITLEBAR` take precedence over it.
/// Read when the app starts; System Title Bar and `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` take precedence over it.
pub app_title_bar: bool,
// Performance
pub gpu_performance: bool,
+1 -1
View File
@@ -1,4 +1,4 @@
use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, given_ids, strip_replay_only};
use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, given_ids, strip_replay_only, waits_for_tool_edit};
use super::doc_state::DocState;
use super::error::{EngineError, Result};
use super::history::NamedStep;
+12
View File
@@ -46,6 +46,11 @@ impl Session {
journal: Journal::default(),
tool: vectorcraft_tools::create("selection"),
lender: None,
held_input: Default::default(),
input_count: 0,
edit_started_by: None,
settling_tool_edit: false,
held_ui: vec![],
tool_step: None,
selection_at_lend: None,
lent_selection: None,
@@ -75,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,
@@ -160,6 +169,9 @@ impl Session {
}
self.press_type_selection = None;
let view = self.last_view;
// The edit the tool computes on another thread and the input held for it belong to the
// document being left. The switch goes on whatever they did, as for the deactivation.
let _ = self.finish_tool_edit_later();
// The switch goes on whatever the lent tool's last actions did, as for the deactivation.
let _ = self.give_back_tool(view);
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
+5
View File
@@ -230,6 +230,11 @@ impl Session {
if label != "Typing" && cmd::typing_in_progress(self) {
cmd::settle_interaction(self)?;
}
// An edit the tool computes on another thread (a Shape Builder merge) is applied first too,
// so the snapshot the interaction previews from and goes back to holds it.
if !self.in_interaction() {
self.finish_tool_edit_later()?;
}
self.clear_deferred_overlay_cache();
let paint = self.paint.clone();
let st = self.doc_mut()?;
+7 -1
View File
@@ -1,6 +1,6 @@
use super::{
CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, Value, cmd, find_command, given_ids, guard,
strip_replay_only,
strip_replay_only, waits_for_tool_edit,
};
impl Session {
@@ -39,6 +39,12 @@ impl Session {
/// Execute a command by id. This is THE entry point for every frontend.
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?;
// An edit the active tool is computing on another thread (a Shape Builder merge) is
// applied before a command that may edit, select, save or give a document a new revision,
// as the click came first. Queries that only read do not wait for it.
if self.depth == 0 && waits_for_tool_edit(id) {
self.finish_tool_edit_later()?;
}
let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id));
let r = self.execute_spec(spec, id, params);
self.reading = outer;
+4
View File
@@ -207,6 +207,10 @@ impl Session {
/// [`Session::end_undo_scope`]: open an undo group there or, when one is open already, join it,
/// so that the edits are part of its step. `None` without a document.
pub fn begin_undo_scope(&mut self) -> Option<UndoScope> {
// An edit the tool computes on another thread is a step before the scope, so the scope's
// snapshot holds it. A failure to apply it was the edit's own, and the scope begins all the
// same.
let _ = self.finish_tool_edit_later();
let journal = self.journal.len();
let st = self.active()?;
let uid = st.uid;
+272 -69
View File
@@ -28,11 +28,12 @@
//! 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};
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::SystemTime;
use vectorcraft_pdf::{PdfPreset, builtin_preset};
use vectorcraft_plugins::safe_mode;
@@ -61,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.
@@ -79,9 +82,9 @@ pub(crate) const MAX_CACHE_SCAN: usize = storage::MAX_CACHE_ENTRIES * 2;
/// Held while a plug-in's settings or cache change, so two runs can't pass a cap together or lose
/// each other's settings.
static PLUGIN_DATA_LOCK: Mutex<()> = Mutex::new(());
/// The closed flag of each plug-in folder's storage, shared by every storage made for the folder
/// until the plug-in is removed, which sets it and drops it.
static PLUGIN_DATA_OPEN: Mutex<BTreeMap<PathBuf, Arc<AtomicBool>>> = Mutex::new(BTreeMap::new());
/// The state of each plug-in folder's storage, shared by every storage made for the folder until
/// the plug-in is removed, which closes it and drops it.
static PLUGIN_DATA_OPEN: Mutex<BTreeMap<PathBuf, Arc<PluginData>>> = Mutex::new(BTreeMap::new());
/// The file name (without extension) a stored item called `name` gets: its name made safe for any
/// file system, then a hash of the name, so that names that differ only in characters a file name
@@ -109,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")
@@ -167,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,
}
}
@@ -282,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();
}
@@ -290,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");
@@ -324,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()));
@@ -334,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
@@ -378,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)
@@ -387,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 {
@@ -397,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 {
@@ -416,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),
}
}
@@ -437,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;
}
};
@@ -459,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.
@@ -474,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
@@ -499,17 +572,22 @@ 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, and is deleted at the plug-in's next removal.
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
// the folder is out of the way; until then they keep working.
let close = || {
if let Some(closed) = PLUGIN_DATA_OPEN.lock().unwrap_or_else(|e| e.into_inner()).remove(&path) {
closed.store(true, Ordering::Release);
if let Some(data) = PLUGIN_DATA_OPEN.lock().unwrap_or_else(|e| e.into_inner()).remove(&path) {
data.closed.store(true, Ordering::Release);
}
};
// A `storage` folder that is a link leads out of the store: nothing there is deleted. A link
@@ -517,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(());
}
@@ -529,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)
@@ -568,22 +657,67 @@ pub(crate) fn plugin_data_dir(dir: &Path, id: &str) -> PathBuf {
fn plugin_storage(dir: Option<&Path>, id: &str) -> Option<Arc<dyn Storage>> {
let dir = dir?;
let data = plugin_data_dir(dir, id);
let closed = PLUGIN_DATA_OPEN.lock().unwrap_or_else(|e| e.into_inner()).entry(data.clone()).or_default().clone();
Some(Arc::new(PluginStorage { root: dir.to_path_buf(), dir: data, closed }))
let state = PLUGIN_DATA_OPEN.lock().unwrap_or_else(|e| e.into_inner()).entry(data.clone()).or_default().clone();
Some(Arc::new(PluginStorage { root: dir.to_path_buf(), dir: data, state }))
}
/// A file's size and modified time (`None`: there is no file).
type FileStamp = Option<(u64, SystemTime)>;
/// The stamp of the file at `path`.
fn file_stamp(path: &Path) -> Result<FileStamp, StorageError> {
match std::fs::metadata(path) {
Ok(m) => Ok(Some((m.len(), m.modified().map_err(|e| io(&e))?))),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(io(&e)),
}
}
/// The modified time of the folder at `dir` (`None`: it can't be read, or there is no folder).
fn folder_stamp(dir: &Path) -> Option<SystemTime> {
std::fs::symlink_metadata(dir).ok()?.modified().ok()
}
/// What every storage made for one plug-in folder shares ([`PLUGIN_DATA_OPEN`]).
#[derive(Default)]
struct PluginData {
/// Set, under [`PLUGIN_DATA_LOCK`], once the plug-in is removed.
closed: AtomicBool,
kept: Mutex<Kept>,
}
/// What the folder's files last held in this process.
#[derive(Default)]
struct Kept {
settings: Option<KeptSettings>,
cache: Option<KeptCache>,
}
/// The settings by key, and the settings file's stamp when they were read or written.
struct KeptSettings {
stamp: FileStamp,
values: BTreeMap<String, Vec<u8>>,
}
/// The bytes of the cache entries, and the cache folder's stamp when they were added up.
#[derive(Clone, Copy)]
struct KeptCache {
stamp: Option<SystemTime>,
bytes: u64,
}
/// The settings and cache of one plug-in, in its folder of the plug-in store (see the module docs).
/// Keys and entry names are [`storage::valid_name`]s; an entry's file name is its name as
/// [`case_safe`] writes it, so that names differing only in case get different files. A link
/// anywhere in the folder's path below the store is refused, and so is a cache file that is not a
/// plain file.
/// plain file. The settings stay in memory ([`Kept`]) while the settings file keeps its size and
/// modified time, and every change is written to the file before the call returns. The total
/// `cache_bytes` reports stays in memory while the cache folder keeps its modified time.
pub(crate) struct PluginStorage {
/// The plug-in store, and the plug-in's folder in it.
root: PathBuf,
dir: PathBuf,
/// Set, under [`PLUGIN_DATA_LOCK`], once the plug-in is removed; shared by every storage of the
/// folder ([`PLUGIN_DATA_OPEN`]).
closed: Arc<AtomicBool>,
state: Arc<PluginData>,
}
/// The sizes of `files` added up, at most `u64::MAX`: the sizes come from the file system.
@@ -657,17 +791,29 @@ impl PluginStorage {
Ok(())
}
/// The settings, by key. A file that is too large or doesn't parse is moved aside
/// ([`BAD_SETTINGS_FILE`]) with a log record, and the settings are empty. `meter` is charged the
/// file's size before it is read.
fn read_settings(&self, meter: &mut Meter) -> Result<BTreeMap<String, Vec<u8>>, StorageError> {
fn kept(&self) -> MutexGuard<'_, Kept> {
self.state.kept.lock().unwrap_or_else(|e| e.into_inner())
}
/// The settings: those in `kept` when the settings file still has their stamp, else the file's,
/// which then replace them.
fn read_settings<'a>(&self, kept: &'a mut Option<KeptSettings>, meter: &mut Meter) -> Result<&'a mut KeptSettings, StorageError> {
let path = self.settings_path();
self.no_links(&path)?;
let size = match std::fs::metadata(&path) {
Ok(m) => m.len(),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(e) => return Err(io(&e)),
let stamp = file_stamp(&path)?;
let held = match kept.take() {
Some(held) if held.stamp == stamp => held,
_ => self.load_settings(stamp, meter)?,
};
Ok(kept.insert(held))
}
/// Reads the settings file, whose stamp is `stamp`. A file that is too large or doesn't parse is
/// moved aside ([`BAD_SETTINGS_FILE`]) with a log record, and the settings are empty. `meter` is
/// charged the file's size before it is read.
fn load_settings(&self, stamp: FileStamp, meter: &mut Meter) -> Result<KeptSettings, StorageError> {
let path = self.settings_path();
let Some((size, _)) = stamp else { return Ok(KeptSettings { stamp, values: BTreeMap::new() }) };
let readable = size <= storage::MAX_SETTINGS_BYTES as u64;
if readable {
meter.take(size)?;
@@ -683,12 +829,30 @@ impl PluginStorage {
settings.filter(|s| s.len() <= storage::MAX_SETTINGS && s.values().all(|v| v.len() <= storage::MAX_SETTING_BYTES))
});
match parsed {
Some(settings) => Ok(settings),
Some(values) => Ok(KeptSettings { stamp, values }),
None => {
let aside = self.dir.join(BAD_SETTINGS_FILE);
log::warn!("the plug-in settings {} don't read: moved to {} and started empty", path.display(), aside.display());
std::fs::rename(&path, &aside).map_err(|e| io(&e))?;
Ok(BTreeMap::new())
Ok(KeptSettings { stamp: None, values: BTreeMap::new() })
}
}
}
/// Writes the settings in `kept` to the file and records the file's new stamp. When that fails,
/// or settings were written and the file is gone, `kept` is emptied, so the next call reads the
/// file again.
fn save_settings(&self, kept: &mut Option<KeptSettings>, meter: &mut Meter) -> Result<(), StorageError> {
let Some(held) = kept.as_mut() else { return Ok(()) };
let written = self.write_settings(&held.values, meter);
match (written, file_stamp(&self.settings_path())) {
(Ok(()), Ok(stamp)) if stamp.is_some() || held.values.is_empty() => {
held.stamp = stamp;
Ok(())
}
(written, _) => {
*kept = None;
written
}
}
}
@@ -716,7 +880,7 @@ impl PluginStorage {
/// Fails with [`StorageError::Unavailable`] once the storage is closed.
fn open(&self) -> Result<(), StorageError> {
if self.closed.load(Ordering::Acquire) { Err(StorageError::Unavailable) } else { Ok(()) }
if self.state.closed.load(Ordering::Acquire) { Err(StorageError::Unavailable) } else { Ok(()) }
}
/// The entries of the cache folder (plain files named as [`Self::entry_path`] names them, which
@@ -753,28 +917,33 @@ impl Storage for PluginStorage {
fn setting(&self, key: &str, meter: &mut Meter) -> Result<Option<Vec<u8>>, StorageError> {
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
self.open()?;
Ok(self.read_settings(meter)?.remove(key))
let mut kept = self.kept();
Ok(self.read_settings(&mut kept.settings, meter)?.values.get(key).cloned())
}
fn set_setting(&self, key: &str, value: &[u8], meter: &mut Meter) -> Result<(), StorageError> {
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
self.open()?;
let mut settings = self.read_settings(meter)?;
let mut kept = self.kept();
let settings = &mut self.read_settings(&mut kept.settings, meter)?.values;
if value.len() > storage::MAX_SETTING_BYTES || (!settings.contains_key(key) && settings.len() >= storage::MAX_SETTINGS) {
return Err(StorageError::Full);
}
if settings.get(key).is_some_and(|old| old == value) {
return Ok(());
}
settings.insert(key.to_string(), value.to_vec());
self.write_settings(&settings, meter)
self.save_settings(&mut kept.settings, meter)
}
fn delete_setting(&self, key: &str, meter: &mut Meter) -> Result<bool, StorageError> {
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
self.open()?;
let mut settings = self.read_settings(meter)?;
if settings.remove(key).is_none() {
let mut kept = self.kept();
if self.read_settings(&mut kept.settings, meter)?.values.remove(key).is_none() {
return Ok(false);
}
self.write_settings(&settings, meter).map(|()| true)
self.save_settings(&mut kept.settings, meter).map(|()| true)
}
fn cache_entry(&self, name: &str, meter: &mut Meter) -> Result<Option<Vec<u8>>, StorageError> {
@@ -808,7 +977,10 @@ impl Storage for PluginStorage {
meter.take(value.len() as u64)?;
std::fs::create_dir_all(self.cache_dir()).map_err(|e| io(&e))?;
self.no_links(&path)?;
write_atomic(&path, value).map_err(|e| io(&e))
write_atomic(&path, value).map_err(|e| io(&e))?;
let stamp = folder_stamp(&self.cache_dir());
self.kept().cache = stamp.map(|_| KeptCache { stamp, bytes: total });
Ok(())
}
fn remove_cache_entry(&self, name: &str) -> Result<bool, StorageError> {
@@ -817,7 +989,10 @@ impl Storage for PluginStorage {
let path = self.entry_path(name);
self.no_links(&path)?;
match std::fs::remove_file(&path) {
Ok(()) => Ok(true),
Ok(()) => {
self.kept().cache = None;
Ok(true)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(io(&e)),
}
@@ -845,6 +1020,7 @@ impl Storage for PluginStorage {
freed = freed.saturating_add(m.len());
}
}
self.kept().cache = Some(KeptCache { stamp: folder_stamp(&dir), bytes: 0 });
Ok(freed)
}
@@ -852,7 +1028,14 @@ impl Storage for PluginStorage {
if self.open().is_err() {
return 0;
}
self.cache_files().map(|(files, _)| sum_sizes(&files)).unwrap_or(0)
let stamp = folder_stamp(&self.cache_dir());
if let Some(kept) = self.kept().cache.filter(|k| k.stamp == stamp) {
return kept.bytes;
}
let Ok((files, _)) = self.cache_files() else { return 0 };
let bytes = sum_sizes(&files);
self.kept().cache = Some(KeptCache { stamp, bytes });
bytes
}
}
@@ -865,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 {
@@ -902,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()
}
}
+1
View File
@@ -158,6 +158,7 @@ mod simplify_part;
mod slices;
mod smartguides;
mod smooth_path;
mod spelling;
mod store;
mod strokegeom;
mod strokegradient;
+480
View File
@@ -607,6 +607,486 @@ fn shape_builder_merge_uses_the_map_the_tool_has() {
assert_eq!(maps_built(), built + 1, "another gap");
}
/// 40 squares 20 pt wide in a row, each 10 pt right of the one before (160 segments, which the
/// Shape Builder merges on another thread), all selected.
fn square_row(s: &mut Session) -> Vec<NodeId> {
let ids: Vec<NodeId> = (0..40).map(|k| rect(s, f64::from(k) * 10.0, 0.0, 20.0, 20.0)).collect();
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
ids
}
/// The active document of `s` without its dates, so documents made in two sessions at different
/// times compare equal when their art is.
fn undated(s: &Session) -> vectorcraft_doc::Document {
let mut d = (*s.doc().unwrap().doc).clone();
(d.metadata.created, d.metadata.modified) = (None, None);
d
}
/// The Shape Builder over [`square_row`], its map built, after a click at (15, 10): the merge is
/// being computed on another thread, and the document is as it was.
fn click_row(s: &mut Session, v: ViewInfo) {
s.select_tool("shapeBuilder", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Move, 15.0, 10.0), v).unwrap();
s.tool_poll(v, true).unwrap();
let revision = s.doc().unwrap().revision;
s.pointer(&PointerEvent::new(PointerKind::Down, 15.0, 10.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 15.0, 10.0), v).unwrap();
assert!(s.tool_editing() && s.tool_waiting());
assert_eq!(s.doc().unwrap().revision, revision, "the release returns before the merge is applied");
}
/// A click of the Shape Builder on a large selection merges on another thread, and the merge the
/// next poll applies is the command's own, as one undo step.
#[test]
fn shape_builder_merges_a_large_selection_on_another_thread() {
use vectorcraft_tools::builder::merges_computed;
let v = ViewInfo::default();
let mut s = session();
square_row(&mut s);
click_row(&mut s, v);
let computed = merges_computed();
s.tool_poll(v, true).unwrap();
assert!(!s.tool_editing());
assert_eq!(merges_computed(), computed, "the command takes the merge computed on another thread");
assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge");
assert_eq!(layer_children(&s), 41, "the overlap and what is left of the two squares over it");
let mut direct = session();
square_row(&mut direct);
direct.execute("shapeBuilder.merge", &json!({"points": [[15, 10]]})).unwrap();
assert!(undated(&s) == undated(&direct), "the same document as the command gives");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer_children(&s), 40, "one undo step");
}
/// What comes after a click whose merge is being computed on another thread waits for the merge
/// and runs on the merged art, as when the merge ran on the calling thread: a command (an edit,
/// an undo, a selection, a save, a batch, Lock Guides, the proof views, a preference, Add Font
/// Files), an option change, another tool, a save made outside a command, preferences applied
/// outside a command, a dialog's preview, a scrubbed field's undo scope, a Cmd-click or Cmd-drag
/// with the selection tool. The merge is the one computed on the other thread.
#[test]
fn shape_builder_applies_a_merge_before_what_comes_next() {
use vectorcraft_tools::builder::merges_computed;
type Next = (&'static str, fn(&mut Session, &[NodeId], &std::path::Path));
let v = ViewInfo::default();
let next: Vec<Next> = vec![
("Select All Instances", |s, _, _| {
s.execute("symbol.selectInstances", &json!({"name": "S"})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects.len(), 1);
}),
("an edit", |s, _, _| {
s.execute("object.move", &json!({"dx": 0, "dy": 100})).unwrap();
}),
("an undo", |s, _, _| {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer_children(s), 40, "the undo takes the merge back");
s.execute("edit.redo", &json!({})).unwrap();
}),
("another selection", |s, _, _| {
s.execute("select.inverse", &json!({})).unwrap();
}),
("Select All", |s, _, _| {
s.execute("select.all", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects.len(), 41);
}),
("a save", |s, _, dir| {
s.execute("file.saveAs", &json!({"path": dir.join("a.vectorcraft").to_string_lossy()})).unwrap();
assert!(!s.doc().unwrap().is_dirty(), "the file holds the merge");
}),
("a save outside a command", |s, _, dir| {
let p = json!({"path": dir.join("b.vectorcraft").to_string_lossy()});
let plan = cmd::fileio::save_plan(s, cmd::fileio::SaveMode::SaveAs, &p).unwrap();
assert_eq!(layer_children(s), 40, "planning a save leaves the document");
let job = cmd::fileio::save_job(s, plan).unwrap();
assert_eq!(layer_children(s), 41, "the snapshot is taken after the merge");
drop(job);
}),
("a batch", |s, _, _| {
s.execute("command.batch", &json!({"commands": [{"command": "object.move", "params": {"dx": 0, "dy": 50}}]})).unwrap();
}),
("an option change", |s, _, _| {
s.set_tool_option_cmd(&json!({"key": "gapDetection", "value": true})).unwrap();
}),
("another tool", |s, _, _| {
s.select_tool("selection", ViewInfo::default()).unwrap();
}),
("a closed document", |s, _, _| {
s.execute("file.close", &json!({})).unwrap();
}),
("Lock Guides", |s, _, _| {
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
}),
("an option set from a panel", |s, _, _| {
s.set_tool_option("gapDetection", &json!(true));
}),
("a dialog's preview, canceled", |s, _, _| {
s.begin_interaction("Move").unwrap();
s.preview("object.move", &json!({"dx": 7, "dy": 0})).unwrap();
s.preview("object.move", &json!({"dx": 9, "dy": 0})).unwrap();
s.cancel_interaction().unwrap();
assert_eq!(layer_children(s), 41, "canceling the preview keeps the merge");
}),
("a dialog's preview, kept", |s, _, _| {
s.begin_interaction("Move").unwrap();
s.preview("object.move", &json!({"dx": 7, "dy": 0})).unwrap();
s.commit_interaction().unwrap();
let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect();
assert_eq!(labels, ["Move", "Shape Builder"]);
}),
("a scrubbed field, canceled", |s, _, _| {
let scope = s.begin_undo_scope().unwrap();
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
s.end_undo_scope(scope, true);
assert_eq!(
s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()),
Some("Shape Builder"),
"the scrub's step is undone, not the merge"
);
}),
("a held click, then another tool", |s, _, _| {
let v = ViewInfo::default();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 55.0, 10.0), v).unwrap();
}
assert!(s.tool_editing(), "the click is held");
s.select_tool("selection", v).unwrap();
let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect();
assert_eq!(labels, ["Shape Builder", "Shape Builder"], "the held click merges with the Shape Builder first");
}),
("a held click, then another document", |s, _, _| {
let v = ViewInfo::default();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 55.0, 10.0), v).unwrap();
}
let first = s.active_index().unwrap();
s.add_document(vectorcraft_doc::Document::new(100.0, 100.0), None);
assert!(!s.tool_editing());
let labels: Vec<&str> = s.documents()[first].history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect();
assert_eq!(labels, ["Shape Builder", "Shape Builder"], "the held click merges in its own document first");
s.set_active(first);
}),
("a Cmd-click", |s, _, _| {
let v = ViewInfo::default();
let cmd = Mods { cmd: true, ..Default::default() };
assert_eq!(s.cursor(Point::new(500.0, 300.0), cmd, v), vectorcraft_tools::Cursor::Busy, "Cmd shows the merge is computed");
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 500.0, 300.0).with_mods(cmd), v).unwrap();
}
assert!(s.tool_editing(), "the click is held");
while s.tool_waiting() {
s.tool_poll(v, true).unwrap();
}
assert!(s.doc().unwrap().selection.is_empty(), "the lent selection tool deselects after the merge");
assert_eq!(s.tool_id(), "shapeBuilder");
}),
("a Cmd-drag", |s, _, _| {
let v = ViewInfo::default();
let cmd = Mods { cmd: true, ..Default::default() };
for (kind, y) in [(PointerKind::Down, 10.0), (PointerKind::Drag, 60.0), (PointerKind::Drag, 110.0), (PointerKind::Up, 110.0)] {
s.pointer(&PointerEvent::new(kind, 305.0, y).with_mods(cmd), v).unwrap();
}
assert!(s.tool_editing(), "the drag is held");
while s.tool_waiting() {
s.tool_poll(v, true).unwrap();
}
let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect();
assert_eq!(labels, ["Move", "Shape Builder"]);
}),
// The proof views redraw every document (a new revision); they are left off, as the
// other tests of the process-wide proof view expect.
("Separations Preview", |s, _, _| {
s.execute("view.separationsPreview", &json!({"on": false})).unwrap();
}),
("Overprint Preview", |s, _, _| {
s.execute("view.overprintPreview", &json!({"on": false})).unwrap();
}),
("Proof Colors", |s, _, _| {
s.execute("view.proofColors", &json!({"on": false})).unwrap();
}),
("Proof Setup", |s, _, _| {
s.execute("view.proofSetup", &json!({})).unwrap();
}),
("a preference", |s, _, _| {
let every = s.prefs.gridline_every;
s.execute("prefs.set", &json!({"key": "gridlineEvery", "value": every + 10.0})).unwrap();
}),
("Reset Preferences", |s, _, _| {
s.execute("prefs.reset", &json!({})).unwrap();
}),
("preferences applied outside a command", |s, _, _| {
let mut p = s.prefs.clone();
p.gridline_every += 10.0;
s.apply_prefs(p);
}),
("Add Font Files", |s, _, _| {
// No files: the command fails after the merge.
assert!(s.execute("text.addFontFiles", &json!({"files": []})).is_err());
}),
];
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");
for (what, then) in next {
let mut s = session();
if what == "Select All Instances" {
let far = rect(&mut s, 500.0, 500.0, 20.0, 20.0);
s.execute("symbol.new", &json!({"name": "S", "ids": [far.0]})).unwrap();
}
let ids = square_row(&mut s);
click_row(&mut s, v);
let computed = merges_computed();
let journal = s.journal.len();
then(&mut s, &ids, &dir);
assert!(!s.tool_editing(), "{what}");
assert_eq!(merges_computed(), computed, "{what}: the merge computed on another thread");
assert_eq!(s.journal.since(journal).first().map(|j| j.0.as_str()), Some("shapeBuilder.merge"), "{what}: the merge comes first");
if what != "a closed document" {
assert!(layer_children(&s) >= 41, "{what}: the merge stays");
}
}
}
/// Gestures and arrow keys that come while a merge is computed on another thread are held and
/// made after it, in order: the document is the one they make one after the other, and the
/// events count as made once they are and the merge they start is applied.
#[test]
fn shape_builder_holds_gestures_made_during_a_merge() {
type Gesture = fn(&mut Session, ViewInfo);
let cases: [(&str, bool, Gesture); 6] = [
("a second click", false, |s, v| {
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 55.0, 10.0), v).unwrap();
}
}),
("a drag", false, |s, v| {
for (kind, x) in [(PointerKind::Down, 75.0), (PointerKind::Drag, 85.0), (PointerKind::Drag, 95.0), (PointerKind::Up, 95.0)] {
s.pointer(&PointerEvent::new(kind, x, 10.0), v).unwrap();
}
}),
("two clicks", false, |s, v| {
for x in [55.0, 135.0] {
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, x, 10.0), v).unwrap();
}
}
}),
("a Cmd-click", false, |s, v| {
let cmd = Mods { cmd: true, ..Default::default() };
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 500.0, 300.0).with_mods(cmd), v).unwrap();
}
}),
("a Cmd-drag and a click", false, |s, v| {
let cmd = Mods { cmd: true, ..Default::default() };
for (kind, y) in [(PointerKind::Down, 10.0), (PointerKind::Drag, 110.0), (PointerKind::Up, 110.0)] {
s.pointer(&PointerEvent::new(kind, 305.0, y).with_mods(cmd), v).unwrap();
}
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 55.0, 10.0), v).unwrap();
}
}),
("an arrow key", true, |s, v| {
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
}),
];
let v = ViewInfo::default();
let start = |swatches: bool| {
let mut s = session();
if swatches {
s.select_tool("shapeBuilder", v).unwrap();
s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "swatches"})).unwrap();
}
square_row(&mut s);
click_row(&mut s, v);
s
};
for (what, swatches, send) in cases {
// One after the other: the merge applied before the gesture, and each merge after its own.
let mut one = start(swatches);
while one.tool_waiting() {
one.tool_poll(v, true).unwrap();
}
send(&mut one, v);
while one.tool_waiting() {
one.tool_poll(v, true).unwrap();
}
// While the merge is computed.
let mut s = start(swatches);
let revision = s.doc().unwrap().revision;
let from = s.input_count();
send(&mut s, v);
let to = s.input_count();
assert!(s.tool_editing() && !s.input_applied(from, to), "{what}: held");
assert_eq!(s.doc().unwrap().revision, revision, "{what}: nothing made before the merge");
while s.tool_waiting() {
s.tool_poll(v, true).unwrap();
}
assert!(!s.tool_editing() && s.input_applied(from, to), "{what}");
assert!(undated(&s) == undated(&one), "{what}: the document the gestures make one after the other");
assert_eq!(s.doc().unwrap().selection, one.doc().unwrap().selection, "{what}");
assert_eq!(s.paint.fill, one.paint.fill, "{what}");
let labels = |s: &Session| s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect::<Vec<_>>();
assert_eq!(labels(&s), labels(&one), "{what}");
// The click's merge alone.
let mut merged = start(swatches);
while merged.tool_waiting() {
merged.tool_poll(v, true).unwrap();
}
let changed = labels(&s).len() > labels(&merged).len()
|| s.paint.fill != merged.paint.fill
|| s.doc().unwrap().selection != merged.doc().unwrap().selection;
assert!(changed, "{what}: the gesture did something");
}
}
/// A press held while a merge is computed on another thread, then dropped (a long touch, a
/// canceled touch, a second finger), is never made: once the merge is applied, the tool is at
/// rest and the document is the one the same input makes, dropped the same way, after the merge.
/// A held click before the press is still made, and so is a perspective plane key held after it.
#[test]
fn shape_builder_drops_a_press_held_during_a_merge() {
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
type Gesture = fn(&mut Session, ViewInfo);
fn press(s: &mut Session, v: ViewInfo, x: f64, mods: Mods) {
s.pointer(&PointerEvent::new(PointerKind::Down, x, 10.0).with_mods(mods), v).unwrap();
}
fn click(s: &mut Session, v: ViewInfo) {
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 55.0, 10.0), v).unwrap();
}
}
// What a case sends, and whether the perspective grid is shown.
let cases: [(&str, bool, Gesture); 7] = [
("a press", false, |s, v| press(s, v, 75.0, Mods::default())),
("a drag", false, |s, v| {
press(s, v, 75.0, Mods::default());
s.pointer(&PointerEvent::new(PointerKind::Drag, 95.0, 10.0), v).unwrap();
}),
("a Cmd-press", false, |s, v| press(s, v, 305.0, Mods { cmd: true, ..Default::default() })),
("a press and a key", false, |s, v| {
press(s, v, 75.0, Mods::default());
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
}),
("a press and an arrow key", false, |s, v| {
press(s, v, 75.0, Mods::default());
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
}),
("a press and a plane key", true, |s, v| {
press(s, v, 75.0, Mods::default());
s.tool_key(ToolKey::Digit(3), Mods::default(), v).unwrap();
}),
("a click, then a press", false, |s, v| {
click(s, v);
press(s, v, 135.0, Mods::default());
}),
];
let v = ViewInfo::default();
let start = |grid: bool| {
let mut s = session();
s.select_tool("shapeBuilder", v).unwrap();
s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "swatches"})).unwrap();
if grid {
s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
}
square_row(&mut s);
click_row(&mut s, v);
s
};
// A tool left in the middle of a gesture keeps waiting: the polls stop after a few.
let settle = |s: &mut Session| {
for _ in 0..8 {
if !s.tool_waiting() {
return;
}
s.tool_poll(v, true).unwrap();
}
};
let labels = |s: &Session| s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect::<Vec<_>>();
let plane = |s: &Session| PerspectiveGrid::from_doc(&s.doc().unwrap().doc).unwrap().plane;
for (what, grid, send) in cases {
// The same input after the merge, dropped the same way.
let mut one = start(grid);
settle(&mut one);
send(&mut one, v);
one.drop_tool_press(v).unwrap();
settle(&mut one);
let mut s = start(grid);
if grid {
assert_ne!(plane(&s), Plane::Right, "{what}: the plane before the key");
}
let from = s.input_count();
send(&mut s, v);
let to = s.input_count();
assert!(s.tool_editing() && !s.input_applied(from, to), "{what}: held");
s.drop_tool_press(v).unwrap();
settle(&mut s);
assert!(!s.tool_waiting() && !s.tool_editing() && s.input_applied(from, to), "{what}");
assert!(!s.tool_busy(), "{what}: the tool is at rest");
assert_eq!(s.tool_id(), "shapeBuilder", "{what}: no tool is lent");
assert!(undated(&s) == undated(&one), "{what}: the document the input makes after the merge");
assert_eq!(labels(&s), labels(&one), "{what}");
assert_eq!(s.doc().unwrap().selection, one.doc().unwrap().selection, "{what}");
assert_eq!(s.paint.fill, one.paint.fill, "{what}");
if grid {
assert_eq!(plane(&one), Plane::Right, "{what}: the plane key is made after the merge");
assert_eq!(plane(&s), Plane::Right, "{what}: the plane key is made");
}
}
}
/// A new revision of the document made outside a command while a merge is computed on another
/// thread keeps the merge when the selected art is as it was (the next poll applies it, as the
/// command computes it), and drops it when the art changed.
#[test]
fn shape_builder_keeps_a_merge_over_a_new_revision_of_the_same_art() {
use vectorcraft_tools::builder::merges_computed;
let v = ViewInfo::default();
let mut s = session();
square_row(&mut s);
click_row(&mut s, v);
let computed = merges_computed();
s.active_mut().unwrap().revision += 1;
s.tool_poll(v, true).unwrap();
assert!(!s.tool_editing());
assert_eq!(merges_computed(), computed, "the merge computed on another thread");
assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge");
let mut direct = session();
square_row(&mut direct);
direct.execute("shapeBuilder.merge", &json!({"points": [[15, 10]]})).unwrap();
assert!(undated(&s) == undated(&direct), "the same document as the command gives");
// The art changed: the merge is dropped.
let mut s = session();
let ids = square_row(&mut s);
click_row(&mut s, v);
let journal = s.journal.len();
let st = s.active_mut().unwrap();
Arc::make_mut(&mut st.doc).node_mut(ids[1]).unwrap().transform(Affine::translate((0.0, 50.0)), false);
st.revision += 1;
s.tool_poll(v, true).unwrap();
assert!(!s.tool_editing());
assert_eq!(s.journal.len(), journal, "nothing merged");
assert_eq!(layer_children(&s), 40);
}
/// A merge computed for the tool Cmd lent the selection tool's drag away from is applied before
/// a command too.
#[test]
fn shape_builder_merge_of_the_lending_tool_comes_first() {
let v = ViewInfo::default();
let mut s = session();
square_row(&mut s);
click_row(&mut s, v);
let lent = s.make_tool("selection");
s.lender = Some(std::mem::replace(&mut s.tool, lent));
assert!(s.tool_editing());
let journal = s.journal.len();
s.execute("object.move", &json!({"dx": 0, "dy": 100})).unwrap();
assert!(!s.tool_editing());
assert_eq!(s.journal.since(journal).first().map(|j| j.0.as_str()), Some("shapeBuilder.merge"));
assert_eq!(s.tool_id(), "selection", "the lent tool stays active until the release");
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("shapeBuilder"));
}
#[test]
fn shape_builder_tool_merges_the_narrow_shape_it_highlights_in_a_wide_selection() {
let mut s = session();
+16
View File
@@ -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();
+36 -12
View File
@@ -2698,11 +2698,26 @@ 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 out of the path, as with Direct Selection chosen.
// 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).
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 = path(&s, id).subpaths.iter().map(|sp| sp.anchors.len()).collect::<Vec<_>>();
assert_eq!((s.clipboard.nodes.len(), left), (1, vec![2, 2]));
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_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();
assert_eq!(paths(&s), vec![(id, original.clone())]);
assert_eq!(s.doc().unwrap().selection, picked);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(paths(&s), left);
// Drawing on: the last anchor the Pen leaves selected doesn't make Copy take that anchor.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
@@ -3412,6 +3427,7 @@ fn a_filled_pencil_path_keeps_no_stroke() {
assert!(!s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_paint().is_none());
}
/// Interior and endpoint deletions preserve each surviving run without adding connecting segments.
#[test]
fn open_anchor_delete_splits_runs_without_new_connections() {
let cases = [
@@ -3439,16 +3455,19 @@ fn open_anchor_delete_splits_runs_without_new_connections() {
assert!(s.doc().unwrap().doc.node(id).is_none(), "only isolated points remain: {removed:?}");
assert!(s.doc().unwrap().selection.objects.is_empty());
} else {
let result = path(&s, id);
assert_eq!(result.subpaths.len(), expected.len(), "deleted anchors: {removed:?}");
for (sp, indices) in result.subpaths.iter().zip(&expected) {
let pieces = &s.doc().unwrap().selection.objects;
assert_eq!(pieces.len(), expected.len(), "deleted anchors: {removed:?}");
assert_eq!(pieces[0], id);
for (piece, indices) in pieces.iter().zip(&expected) {
let result = path(&s, *piece);
assert_eq!(result.subpaths.len(), 1);
let sp = &result.subpaths[0];
assert!(!sp.closed);
assert_eq!(sp.anchors.iter().map(|a| a.p).collect::<Vec<_>>(), indices.iter().map(|&i| original.anchors[i].p).collect::<Vec<_>>());
for (segment, pair) in indices.windows(2).enumerate() {
assert_eq!(sp.segment(segment), original.segment(pair[0]));
}
}
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
}
assert_eq!(undo_steps(&s), undo + 1);
assert!(s.doc().unwrap().selection.anchors.is_empty() && s.doc().unwrap().selection.segments.is_empty());
@@ -3547,6 +3566,7 @@ fn open_anchor_delete_does_not_change_explicit_remove_anchors() {
}
}
/// Baked transforms and mixed whole/partial selection survive splitting and atomic Undo/Redo.
#[test]
fn open_anchor_delete_after_transform_keeps_mixed_selection_atomic() {
use vectorcraft_geom::Affine;
@@ -3584,13 +3604,17 @@ fn open_anchor_delete_after_transform_keeps_mixed_selection_atomic() {
let st = s.doc().unwrap();
assert!(st.doc.node(whole).is_none());
assert_eq!(st.doc.node(untouched), before.node(untouched));
let result = path(&s, id);
assert_eq!(result.subpaths.len(), 2);
for (sp, segment) in result.subpaths.iter().zip([0, 3]) {
let pieces = st.selection.objects.clone();
assert_eq!(pieces.len(), 2);
assert_eq!(pieces[0], id);
for (piece, segment) in pieces.iter().zip([0, 3]) {
let result = path(&s, *piece);
assert_eq!(result.subpaths.len(), 1);
let sp = &result.subpaths[0];
assert_eq!(sp.segment_count(), 1);
assert_eq!(sp.segment(0), original.subpaths[0].segment(segment));
}
assert_eq!(st.selection.objects, vec![id]);
assert_eq!(st.selection.objects, pieces);
assert!(st.selection.anchors.is_empty() && st.selection.segments.is_empty());
assert_eq!(undo_steps(&s), undo + 1);
let after = st.doc.clone();
@@ -3599,7 +3623,7 @@ fn open_anchor_delete_after_transform_keeps_mixed_selection_atomic() {
assert_eq!(s.doc().unwrap().selection, selection);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, after);
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
assert_eq!(s.doc().unwrap().selection.objects, pieces);
}
}
+40 -30
View File
@@ -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();
+202
View File
@@ -177,6 +177,208 @@ fn export_options_pass_every_listed_key() {
}
}
const SAVES: [&str; 4] = ["document.save", "file.saveAs", "file.saveCopy", "file.saveAsTemplate"];
/// A save refuses a key no save format reads, beside the path, in `options` and in the PDF and
/// SVG objects of either, under each save command.
#[test]
fn save_options_refuse_a_key_no_save_format_reads() {
let why = "no save format takes it (see file.formatOptions)";
for id in SAVES {
assert_eq!(refusal(id, json!({"path": "a.pdf", "noSuchOption": true})), format!("unknown parameter `noSuchOption`; {why}"));
assert_eq!(
refusal(id, json!({"path": "a.pdf", "options": {"noSuchOption": true}})),
format!("unknown parameter `options.noSuchOption`; {why}")
);
assert_eq!(refusal(id, json!({"compres": true})), "unknown parameter `compres`; did you mean `compress`?");
assert_eq!(refusal(id, json!({"options": {"compres": true}})), "unknown parameter `options.compres`; did you mean `options.compress`?");
// An export's own key is not a save's.
assert_eq!(refusal(id, json!({"path": "a.png", "quality": 80})), format!("unknown parameter `quality`; {why}"));
for (given, message) in [
(json!({"path": "a.pdf", "marks": {"useDocumentBleed": true}}), "unknown parameter `marks.useDocumentBleed`; `marks` takes:"),
(json!({"path": "a.pdf", "options": {"marks": {"x": 1}}}), "unknown parameter `options.marks.x`; `options.marks` takes:"),
(json!({"path": "a.ai", "bleed": {"useDocumen": true}}), "unknown parameter `bleed.useDocumen`; did you mean `bleed.useDocument`?"),
// The `svg` object is checked when the save writes no SVG too.
(json!({"path": "a.pdf", "svg": {"noSuchOption": true}}), "unknown parameter `svg.noSuchOption`; `svg` takes:"),
(
json!({"path": "a.pdf", "options": {"svg": {"minfy": true}}}),
"unknown parameter `options.svg.minfy`; did you mean `options.svg.minify`?",
),
] {
let got = refusal(id, given.clone());
assert!(got.starts_with(message), "{id} {given}: {got}");
}
// A key that another format a save writes reads still passes: the save leaves it out.
for given in [
json!({"path": "a.svg", "compress": true}),
json!({"path": "a.pdf", "options": {"preview": true, "styling": "style"}}),
json!({"path": "a.vectorcraft", "standard": "pdfX4", "marks": {"trim": true}}),
json!({"path": "a.ai", "acknowledgeLoss": true, "modified": null, "svg": {"minify": true}}),
json!({"path": "a.svg", "svg": {"styling": "css", "artboard": 0, "useArtboards": true}}),
] {
check_params(id, &given).unwrap_or_else(|e| panic!("{id} {given}: {e}"));
}
}
}
/// A save passes each option of each format it writes, beside the path and in `options`, and
/// each key its description names.
#[test]
fn save_options_pass_every_listed_key() {
use crate::cmd::fileio::{FORMATS, SAVE_FORMATS, TEMPLATE_FORMATS};
for f in FORMATS.iter().filter(|f| SAVE_FORMATS.contains(&f.id) || TEMPLATE_FORMATS.contains(&f.id)) {
for o in f.options {
for params in [json!({"format": f.id, o.name: null}), json!({"format": f.id, "options": {o.name: null}})] {
for id in SAVES {
check_params(id, &params).unwrap_or_else(|e| panic!("{id} {params}: {e}"));
}
}
}
}
for id in SAVES {
let keys = doc_keys(find_command(id).unwrap().params).unwrap().keys;
let refused: Vec<&str> = keys.into_iter().filter(|key| check_params(id, &json!({*key: null})).is_err()).collect();
assert_eq!(refused, Vec::<&str>::new(), "{id} names and refuses these");
}
}
/// Export for Screens refuses a key it doesn't take, and in its rows and settings a key no format
/// reads, by the row's path; `document.exportPresets.save` checks the rows of its settings.
#[test]
fn export_for_screens_refuses_a_key_no_format_reads() {
let id = "document.exportForScreens";
assert!(
refusal(id, json!({"folder": "out", "noSuchOption": true})).starts_with("unknown parameter `noSuchOption`; the command takes: artboard, ")
);
assert_eq!(refusal(id, json!({"subfolder": true})), "unknown parameter `subfolder`; did you mean `subfolders`?");
let no_format = "no format takes it (see document.formats)";
for (given, message) in [
(json!({"formats": [{"format": "png", "noSuchOption": 1}]}), format!("unknown parameter `formats[0].noSuchOption`; {no_format}")),
(
json!({"formats": [{"format": "png"}, {"format": "pdf", "marks": {"useDocumentBleed": true}}]}),
"unknown parameter `formats[1].marks.useDocumentBleed`; `formats[1].marks` takes:".into(),
),
(
json!({"formats": [{"format": "pdf", "security": {"openPasswrd": "x"}}]}),
"unknown parameter `formats[0].security.openPasswrd`; did you mean `formats[0].security.openPassword`?".into(),
),
(
json!({"formats": [{"format": "eps", "flattener": {"balanse": 50}}]}),
"unknown parameter `formats[0].flattener.balanse`; did you mean `formats[0].flattener.balance`?".into(),
),
(json!({"formats": [{"format": "jpg", "sufix": "@2x"}]}), "unknown parameter `formats[0].sufix`; did you mean `formats[0].suffix`?".into()),
(json!({"settings": {"pnj": {}}}), "unknown parameter `settings.pnj`; did you mean `settings.png`?".into()),
(json!({"settings": {"dxf": {}}}), "unknown parameter `settings.dxf`; `settings` takes: ".into()),
(
json!({"settings": {"png": {"bckground": "white"}}}),
"unknown parameter `settings.png.bckground`; did you mean `settings.png.background`?".into(),
),
(json!({"settings": {"pdf": {"bleed": {"top": 9, "inner": 1}}}}), "unknown parameter `settings.pdf.bleed.inner`;".into()),
] {
let got = refusal(id, given.clone());
assert!(got.starts_with(&message), "{given}: {got}");
}
let save = "document.exportPresets.save";
assert_eq!(
refusal(save, json!({"name": "a", "settings": {"formats": [{"format": "png", "noSuchOption": 1}]}})),
format!("unknown parameter `settings.formats[0].noSuchOption`; {no_format}")
);
assert!(
refusal(save, json!({"name": "a", "settings": {"settings": {"pdf": {"marks": {"x": 1}}}}}))
.starts_with("unknown parameter `settings.settings.pdf.marks.x`;")
);
assert_eq!(
refusal(save, json!({"name": "a", "settings": {"formtas": [{"format": "png"}]}})),
"unknown parameter `settings.formtas`; did you mean `settings.formats`?"
);
assert!(
refusal(save, json!({"name": "a", "settings": {"noSuchOption": true}}))
.starts_with("unknown parameter `settings.noSuchOption`; `settings` takes: artboard, ")
);
// Export Assets takes the same rows and settings, and stores them.
for asset in ["assets.export", "assets.settings.set"] {
assert_eq!(
refusal(asset, json!({"formats": [{"format": "png", "noSuchOption": 1}]})),
format!("unknown parameter `formats[0].noSuchOption`; {no_format}")
);
assert!(refusal(asset, json!({"settings": {"pdf": {"marks": {"x": 1}}}})).starts_with("unknown parameter `settings.pdf.marks.x`;"));
check_params(asset, &json!({"formats": [{"format": "jpg", "scale": "2x", "quality": 80}]})).unwrap();
}
// An exporter plug-in's `params` in a row (its format is a plug-in's: tests/plugin_export.rs).
check_params(id, &json!({"formats": [{"format": "png", "params": {}}]})).unwrap();
// Keys the preset leaves out are still Export for Screens params.
check_params(save, &json!({"name": "a", "settings": {"zip": true, "formats": [{"format": "jpg", "quality": 80}]}})).unwrap();
// The encoders read Include Artboard Fill and Appearance of Black from a row or a format's
// settings.
for given in [
json!({"formats": [{"format": "png", "includeArtboardFill": false, "richBlack": true}]}),
json!({"settings": {"png": {"includeArtboardFill": false, "richBlack": true}}}),
] {
check_params(id, &given).unwrap_or_else(|e| panic!("{given}: {e}"));
}
}
/// Export for Screens passes each key its description names, each option of a format in a row or
/// in settings, and the built-in presets; `settings` takes the formats a row can write.
#[test]
fn export_for_screens_passes_every_listed_key() {
use crate::cmd::fileio::{FORMATS, check_screen_settings, screen_export_builtin_presets};
let id = "document.exportForScreens";
let keys = doc_keys(find_command(id).unwrap().params).unwrap().keys;
assert!(keys.len() > 20, "{keys:?}");
// The keys the check takes are the ones the description names.
let (mut named, mut taken) = (keys.clone(), crate::cmd::fileio::SCREEN_PARAM_KEYS.to_vec());
named.sort_unstable();
taken.sort_unstable();
assert_eq!(named, taken);
let refused: Vec<&str> = keys.into_iter().filter(|key| check_params(id, &json!({*key: null})).is_err()).collect();
assert_eq!(refused, Vec::<&str>::new(), "{id} names and refuses these");
check_params(id, &json!({"artboard": 0, "openLocation": true})).unwrap();
let s = Session::new();
for f in FORMATS.iter().filter(|f| f.write) {
for o in f.options {
let row = json!({"formats": [{"format": "png", "scale": 2, "suffix": "", "folder": "x", o.name: null}]});
check_params(id, &row).unwrap_or_else(|e| panic!("{row}: {e}"));
}
let written = check_screen_settings(&s, &json!({"formats": [{"format": f.id}]})).is_ok();
let settings = json!({"settings": {f.id: {}}});
assert_eq!(check_params(id, &settings).is_ok(), written, "{settings}");
}
for preset in screen_export_builtin_presets() {
let settings = serde_json::Value::Object(preset.settings);
check_params(id, &settings).unwrap_or_else(|e| panic!("{}: {e}", preset.name));
check_params("document.exportPresets.save", &json!({"name": "a", "settings": settings})).unwrap();
}
}
/// A saved row loses the keys Export for Screens refuses in it, inside its object options too, and
/// keeps the others.
#[test]
fn a_saved_row_drops_the_keys_no_format_reads() {
use crate::cmd::params::drop_unread_row_options;
let serde_json::Value::Object(mut row) = json!({
"format": "pdf", "scale": "1x", "noSuchOption": 1, "params": {"x": 1},
"marks": {"useDocumentBleed": true, "trim": true}, "preset": "High Quality Print",
"security": {"passwordRequired": true, "noSuchLock": 1}
}) else {
panic!("an object")
};
drop_unread_row_options(&mut row);
assert_eq!(
serde_json::Value::Object(row.clone()),
json!({
"format": "pdf", "scale": "1x", "params": {"x": 1}, "marks": {"trim": true}, "preset": "High Quality Print",
"security": {"passwordRequired": true}
})
);
check_params("document.exportForScreens", &json!({"formats": [row]})).unwrap();
// Remembered security whose passwords were left out, with one given again.
let security = json!({"passwordRequired": true, "openPassword": "x"});
for id in ["document.exportForScreens", "assets.export", "assets.settings.set"] {
check_params(id, &json!({"formats": [{"format": "pdf", "security": security}], "settings": {"pdf": {"security": security}}})).unwrap();
}
}
/// `stroke.set` names every key it reads (its own, `item`, and `ids`/`id`/`target`), so a
/// misnamed one is refused instead of answering `objects: 1` with nothing changed.
#[test]
File diff suppressed because it is too large. Load diff
+63
View File
@@ -144,6 +144,68 @@ fn preview_lists_pages_tiles_inks_and_warnings() {
assert_eq!(v["sheets"][3]["tile"], 4);
}
#[test]
fn copies_per_sheet_print_a_grid_of_the_artboard() {
// A 2 × 3.5 in card filled by a rectangle.
let mut s = Session::new();
s.execute("file.new", &json!({"width": 144, "height": 252})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 144, "height": 252})).unwrap();
let v = s.execute("print.setup", &json!({})).unwrap();
assert_eq!((v["settings"]["copiesPerSheet"].clone(), v["settings"]["gutter"].clone()), (json!(false), json!(0.0)));
// With an 18 pt gutter, Letter holds 3 × 3 copies; the first, at the top left, spans x 72 to 216.
let set = json!({"settings": {"copiesPerSheet": true, "gutter": 18}});
let v = s.execute("print.preview", &set).unwrap();
let copies = v["sheets"][0]["copies"].as_array().unwrap();
assert_eq!((v["pages"].clone(), copies.len(), copies[0].clone()), (json!(1), 9, json!([72.0, 0.0, 216.0, 252.0])));
// The PDF draws the card's paths nine times.
let cards = |bytes: &[u8]| {
let mut n = 0;
vectorcraft_pdf::import(bytes).unwrap().walk(|node| {
n += usize::from(node.path_data().and_then(|p| p.bounds()).is_some_and(|b| (b.width().round(), b.height().round()) == (144.0, 252.0)))
});
n
};
let (bytes, v) = print(&mut s, set);
assert_eq!(v["pages"], 1);
let one = cards(&print(&mut s, json!({})).0);
assert!(one > 0 && cards(&bytes) == 9 * one, "{one}");
// PostScript places the art once per copy.
let mut ps = |p: Value| {
let v = s.execute("file.print", &p).unwrap();
String::from_utf8(vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap()
};
let one = ps(json!({"format": "postscript"})).matches(" cm\n").count();
let grid = ps(json!({"format": "postscript", "settings": {"copiesPerSheet": true, "gutter": 18}})).matches(" cm\n").count();
assert_eq!(grid, one + 8);
}
#[test]
fn print_presets_keep_copies_per_sheet_and_older_presets_leave_it_off() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 144, "height": 252})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 144, "height": 252})).unwrap();
// [Default] prints one copy per sheet.
let v = s.execute("print.presets.list", &json!({})).unwrap();
assert_eq!((v["presets"][0]["settings"]["copiesPerSheet"].clone(), v["presets"][0]["settings"]["gutter"].clone()), (json!(false), json!(0.0)));
// A saved preset keeps the option and the gutter, lists them as changed, and prints with them.
s.execute("print.presets.save", &json!({"name": "Cards", "settings": {"copiesPerSheet": true, "gutter": 18}})).unwrap();
let v = s.execute("print.presets.list", &json!({})).unwrap();
let changed: Vec<&str> = v["presets"][1]["changed"].as_array().unwrap().iter().filter_map(|c| c["option"].as_str()).collect();
assert_eq!(changed, ["copiesPerSheet", "gutter"]);
let v = s.execute("print.preview", &json!({"preset": "Cards"})).unwrap();
assert_eq!(v["sheets"][0]["copies"].as_array().map(Vec::len), Some(9));
// The option survives export and import.
let text = s.execute("print.presets.export", &json!({"names": ["Cards"]})).unwrap()["data"].as_str().unwrap().to_string();
let mut t = Session::new();
t.execute("print.presets.import", &json!({"data": text})).unwrap();
assert_eq!((t.prefs.print_presets[0].settings.copies_per_sheet, t.prefs.print_presets[0].settings.gutter), (true, 18.0));
// A presets file written without the option imports with it off and no gutter.
let old = r#"{"format": "vcprintpresets", "presets": [{"name": "Old", "settings": {"copies": 2}}]}"#;
t.execute("print.presets.import", &json!({"data": old})).unwrap();
let q = &t.prefs.print_presets[1].settings;
assert_eq!((q.copies, q.copies_per_sheet, q.gutter), (2, false, 0.0));
}
#[test]
fn bad_settings_are_bad_params() {
let (mut s, _) = session();
@@ -154,6 +216,7 @@ fn bad_settings_are_bad_params() {
json!({"settings": {"media": "quarto"}}),
json!({"settings": {"artboards": "range", "range": "2"}}),
json!({"settings": {"scaling": "tileFull", "overlap": 500}}),
json!({"settings": {"gutter": 800}}),
] {
for c in ["file.print", "print.preview"] {
assert!(matches!(s.execute(c, &p), Err(EngineError::BadParams { .. })), "{c} {p}");
+1 -1
View File
@@ -72,7 +72,7 @@ fn save_as_takes_on_path_format_and_options() {
let d = dir("saveas");
let mut s = session();
let pdf = path(&d, "doc.pdf");
s.execute("file.saveAs", &json!({"path": pdf, "options": {"range": "1", "bogus": 1}})).unwrap();
s.execute("file.saveAs", &json!({"path": pdf, "options": {"range": "1", "preview": true}})).unwrap();
let st = s.doc().unwrap();
assert_eq!((st.format, st.title()), ("pdf", "doc.pdf".to_string()));
assert_eq!(Value::Object(st.save_options.clone()), json!({"range": "1"}), "only the format's own options are kept");
+272
View File
@@ -0,0 +1,272 @@
//! Edit → Spelling (`text.spelling.check`, `text.spelling.suggest`): the unknown words of the
//! document's type, at the bytes `text.editRange` changes, each in its run's language.
use serde_json::{Value, json};
use crate::cmd::spelling::MAX_DICTIONARY_FILE_BYTES;
use crate::*;
/// A session with a new 400 × 400 document.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s
}
/// Runs a command that must succeed and gives its result.
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap()
}
/// New point type at (10, `y`) holding `t`.
fn text(s: &mut Session, y: f64, t: &str) -> NodeId {
NodeId(run(s, "text.create", json!({"x": 10, "y": y, "text": t}))["id"].as_u64().unwrap())
}
/// The unknown words a check lists: (id, start, end, word).
fn unknown(s: &mut Session, p: Value) -> Vec<(u64, u64, u64, String)> {
let r = run(s, "text.spelling.check", p);
assert_eq!(r["more"], false);
r["words"]
.as_array()
.unwrap()
.iter()
.map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["end"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string()))
.collect()
}
#[test]
fn check_lists_unknown_words_at_the_bytes_edit_range_changes() {
let mut s = session();
// "—" is three bytes, so the unknown word starts at byte 12, not character 10. Punctuation,
// not a word, so the result doesn't depend on which dictionary is built in.
let t = text(&mut s, 50.0, "drawing — qzxvw tools");
assert_eq!(unknown(&mut s, json!({})), [(t.0, 12, 17, "qzxvw".to_string())]);
let w = &run(&mut s, "text.spelling.check", json!({}))["words"][0];
assert_eq!(w["lang"], "en", "text with no language is checked in English");
// Change: the bytes the check gave, as one undo step.
run(&mut s, "text.editRange", json!({"id": t.0, "start": 12, "end": 17, "insert": "vector"}));
assert_eq!(unknown(&mut s, json!({})), []);
run(&mut s, "edit.undo", json!({}));
assert_eq!(unknown(&mut s, json!({})).len(), 1, "undo brings the word back");
}
#[test]
fn check_goes_through_visible_unlocked_type_in_paint_order_or_the_ids_given() {
let mut s = session();
let a = text(&mut s, 50.0, "first qzxvw");
let b = text(&mut s, 100.0, "second wvxzq");
let hidden = text(&mut s, 150.0, "hidden qqzzx");
let locked = text(&mut s, 200.0, "locked zzqqx");
run(&mut s, "object.hide", json!({"ids": [hidden.0]}));
run(&mut s, "object.lock", json!({"ids": [locked.0]}));
let ids: Vec<u64> = unknown(&mut s, json!({})).iter().map(|w| w.0).collect();
assert_eq!(ids, [a.0, b.0], "hidden and locked type are left out");
assert_eq!(unknown(&mut s, json!({"ids": [b.0]})), [(b.0, 7, 12, "wvxzq".to_string())]);
assert_eq!(unknown(&mut s, json!({"ids": null})).len(), 2, "null ids is the default");
let both = [(a.0, 6, 11, "qzxvw".to_string()), (b.0, 7, 12, "wvxzq".to_string())];
assert_eq!(unknown(&mut s, json!({"ids": [b.0, a.0]})), both, "given ids are listed in paint order too");
for ids in [json!(b.0), json!("all"), json!({"id": b.0}), json!([-1]), json!(["x"]), json!([999_999])] {
assert!(s.execute("text.spelling.check", &json!({"ids": ids})).is_err(), "malformed ids {ids} is refused");
}
}
#[test]
fn a_language_without_a_dictionary_marks_nothing() {
let mut s = session();
let t = text(&mut s, 50.0, "qzxvw");
run(&mut s, "text.setFormat", json!({"ids": [t.0], "language": "German"}));
assert_eq!(unknown(&mut s, json!({})), [], "German has no spelling dictionary in craft-proof");
}
#[test]
fn suggest_offers_dictionary_words() {
let mut s = session();
let r = run(&mut s, "text.spelling.suggest", json!({"word": "drawng"}));
let got: Vec<&str> = r["suggestions"].as_array().unwrap().iter().map(|w| w.as_str().unwrap()).collect();
assert!(got.len() <= 5, "five at most by default: {got:?}");
assert!(got.contains(&"drawing"), "{got:?}");
assert_eq!(run(&mut s, "text.spelling.suggest", json!({"word": "drawng", "max": 1}))["suggestions"].as_array().unwrap().len(), 1);
assert!(s.execute("text.spelling.suggest", &json!({})).is_err(), "a word is required");
assert!(s.execute("text.spelling.suggest", &json!({"word": " "})).is_err(), "a blank word is refused");
for max in [json!(0), json!(21), json!(-1), json!("3")] {
assert!(s.execute("text.spelling.suggest", &json!({"word": "drawng", "max": max})).is_err(), "max {max}");
}
}
#[test]
fn each_paragraph_is_checked_on_its_own_at_the_bytes_of_the_whole_text() {
let mut s = session();
// Read as one block, the Vietnamese first paragraph would make the whole text Vietnamese,
// which has no dictionary, and the English typo below it would go unmarked.
let vi = "Cảm ơn những người bạn";
let t = text(&mut s, 50.0, &format!("{vi}\ndrawing qzxvw tools"));
let at = vi.len() + 1 + "drawing ".len();
assert_eq!(unknown(&mut s, json!({})), [(t.0, at as u64, at as u64 + 5, "qzxvw".to_string())]);
}
// The custom dictionary is craft-proof's, shared by the whole process, so each test below uses
// made-up words of its own: tests running at the same time never see each other's.
/// The words a check of the whole active document lists.
fn marked(s: &mut Session) -> Vec<String> {
unknown(s, json!({})).into_iter().map(|w| w.3).collect()
}
#[test]
fn added_words_are_right_in_every_check_until_deleted() {
let mut s = session();
text(&mut s, 50.0, "drawing Zqvwkx tools");
assert_eq!(marked(&mut s), ["Zqvwkx"]);
// Kept in lower case, so the capitalized word is right too.
let r = run(&mut s, "text.spelling.addWord", json!({"word": " Zqvwkx "}));
assert_eq!((r["word"].as_str(), r["added"].as_bool()), (Some("zqvwkx"), Some(true)));
assert_eq!(marked(&mut s), Vec::<String>::new());
assert_eq!(run(&mut s, "text.spelling.addWord", json!({"word": "zqvwkx"}))["added"], false, "already there");
let words = run(&mut s, "text.spelling.dictionary", json!({}))["words"].clone();
assert!(words.as_array().unwrap().contains(&json!("zqvwkx")), "{words}");
// Another document's check takes it as right too.
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
text(&mut s, 50.0, "zqvwkx");
assert_eq!(marked(&mut s), Vec::<String>::new());
run(&mut s, "text.spelling.removeWord", json!({"word": "ZQVWKX"}));
assert_eq!(marked(&mut s), ["zqvwkx"]);
let e = s.execute("text.spelling.removeWord", &json!({"word": "zqvwkx"})).unwrap_err().to_string();
assert!(e.contains("isn't in the custom dictionary"), "{e}");
}
#[test]
fn a_changed_word_replaces_the_old_one() {
let mut s = session();
text(&mut s, 50.0, "xkvzqa xkvzqb");
run(&mut s, "text.spelling.addWord", json!({"word": "xkvzqa"}));
assert_eq!(marked(&mut s), ["xkvzqb"]);
assert_eq!(run(&mut s, "text.spelling.changeWord", json!({"word": "xkvzqa", "to": "Xkvzqb"}))["word"], "xkvzqb");
assert_eq!(marked(&mut s), ["xkvzqa"]);
let e = s.execute("text.spelling.changeWord", &json!({"word": "xkvzqa", "to": "x"})).unwrap_err().to_string();
assert!(e.contains("isn't in the custom dictionary"), "{e}");
run(&mut s, "text.spelling.removeWord", json!({"word": "xkvzqb"}));
}
#[test]
fn the_custom_dictionary_file_is_read_and_kept_up_to_date() {
let dir = vectorcraft_testkit::temp_dir("spelling-dictionary");
let file = dir.join("Custom Dictionary.txt");
std::fs::write(&file, "kqzvwx\nnot one word\n\n").unwrap();
let mut s = session();
s.attach_custom_dictionary(file.clone());
text(&mut s, 50.0, "kqzvwx vkqzwx");
assert_eq!(marked(&mut s), ["vkqzwx"], "the file's word is right; its line of three words is skipped");
run(&mut s, "text.spelling.addWord", json!({"word": "vkqzwx"}));
let saved = std::fs::read_to_string(&file).unwrap();
assert!(saved.lines().any(|l| l == "kqzvwx") && saved.lines().any(|l| l == "vkqzwx"), "{saved}");
run(&mut s, "text.spelling.changeWord", json!({"word": "kqzvwx", "to": "kqzvwy"}));
run(&mut s, "text.spelling.removeWord", json!({"word": "vkqzwx"}));
let saved = std::fs::read_to_string(&file).unwrap();
assert!(saved.lines().any(|l| l == "kqzvwy"), "{saved}");
assert!(!saved.lines().any(|l| l == "kqzvwx" || l == "vkqzwx"), "changed and deleted words are gone from the file: {saved}");
run(&mut s, "text.spelling.removeWord", json!({"word": "kqzvwy"}));
}
#[test]
fn ignore_all_skips_a_word_in_the_active_document_only() {
let mut s = session();
text(&mut s, 50.0, "Wqzxkv drawing wqzxkv vqzxkw");
run(&mut s, "text.spelling.ignoreAll", json!({"word": "WQZXKV"}));
assert_eq!(marked(&mut s), ["vqzxkw"], "every occurrence, whatever its case");
let words = run(&mut s, "text.spelling.dictionary", json!({}))["words"].clone();
assert!(!words.as_array().unwrap().contains(&json!("wqzxkv")), "not added to the custom dictionary");
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
text(&mut s, 50.0, "wqzxkv");
assert_eq!(marked(&mut s), ["wqzxkv"], "another document still marks it");
}
#[test]
fn custom_dictionary_commands_refuse_what_isnt_one_word() {
let mut s = session();
let long = "q".repeat(65);
for (id, p) in [
("text.spelling.addWord", json!({})),
("text.spelling.addWord", json!({"word": " "})),
("text.spelling.addWord", json!({"word": "two words"})),
("text.spelling.addWord", json!({"word": long})),
("text.spelling.addWord", json!({"word": 5})),
("text.spelling.removeWord", json!({})),
("text.spelling.changeWord", json!({"word": "qzx"})),
("text.spelling.changeWord", json!({"word": "qzx", "to": "a b"})),
("text.spelling.ignoreAll", json!({"word": "a\tb"})),
] {
assert!(s.execute(id, &p).is_err(), "{id} {p} is refused");
}
let mut empty = Session::new();
assert!(empty.execute("text.spelling.ignoreAll", &json!({"word": "qzx"})).is_err(), "Ignore All needs a document");
assert!(empty.execute("text.spelling.dictionary", &json!({})).is_ok(), "the dictionary is the app's");
}
/// Whether the custom dictionary holds `word`.
fn in_dictionary(s: &mut Session, word: &str) -> bool {
run(s, "text.spelling.dictionary", json!({}))["words"].as_array().unwrap().contains(&json!(word))
}
#[test]
fn a_dictionary_file_that_cant_be_read_whole_is_never_written_over() {
let dir = vectorcraft_testkit::temp_dir("spelling-unreadable");
// A folder where the file should be can't be read as one; a file past what craft-proof reads
// would lose its other words if written back.
let folder = dir.join("Custom Dictionary.txt");
std::fs::create_dir_all(&folder).unwrap();
let big = dir.join("big.txt");
let words = "qkzvxw\n".repeat((MAX_DICTIONARY_FILE_BYTES / 7 + 2) as usize);
std::fs::write(&big, &words).unwrap();
for path in [folder.clone(), big.clone()] {
let mut s = session();
s.attach_custom_dictionary(path.clone());
let e = s.execute("text.spelling.addWord", &json!({"word": "zkqvxw"})).unwrap_err().to_string();
assert!(e.contains("can't be read"), "{}: {e}", path.display());
assert!(!in_dictionary(&mut s, "zkqvxw"), "the refused word isn't kept either");
}
assert!(folder.is_dir());
assert_eq!(std::fs::read_to_string(&big).unwrap(), words, "the large file is as it was");
}
#[test]
fn a_change_that_cant_be_saved_is_taken_back() {
let mut s = session();
run(&mut s, "text.spelling.addWord", json!({"word": "wkqzvx"}));
let dir = vectorcraft_testkit::temp_dir("spelling-rollback");
let folder = dir.join("Custom Dictionary.txt");
std::fs::create_dir_all(&folder).unwrap();
let mut failing = session();
failing.attach_custom_dictionary(folder);
assert!(failing.execute("text.spelling.removeWord", &json!({"word": "wkqzvx"})).is_err());
assert!(in_dictionary(&mut s, "wkqzvx"), "a delete that wasn't saved leaves the word");
assert!(failing.execute("text.spelling.changeWord", &json!({"word": "wkqzvx", "to": "wkqzvy"})).is_err());
assert!(in_dictionary(&mut s, "wkqzvx") && !in_dictionary(&mut s, "wkqzvy"), "a change that wasn't saved leaves the old word");
run(&mut s, "text.spelling.removeWord", json!({"word": "wkqzvx"}));
}
#[cfg(unix)]
#[test]
fn a_word_another_window_saved_stays_when_this_save_fails() {
use std::os::unix::fs::PermissionsExt;
let dir = vectorcraft_testkit::temp_dir("spelling-readonly");
let file = dir.join("Custom Dictionary.txt");
std::fs::write(&file, "").unwrap();
let mut s = session();
s.attach_custom_dictionary(file.clone());
// Another window saves a word this session hasn't taken in, then the folder can't be written:
// the save reads the file, takes the word in, and fails writing.
std::fs::write(&file, "zvkqxw\n").unwrap();
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o500)).unwrap();
let probe = dir.join("probe");
let writable = std::fs::write(&probe, "").is_ok();
let r = (!writable).then(|| s.execute("text.spelling.addWord", &json!({"word": "zvkqxw"})));
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap();
let Some(r) = r else {
// Run as root, the folder stays writable: there is no failing save to check.
return;
};
assert!(r.is_err(), "{r:?}");
assert!(in_dictionary(&mut s, "zvkqxw"), "the word in the file stays, though this Add was taken back");
run(&mut s, "text.spelling.removeWord", json!({"word": "zvkqxw"}));
}
+22
View File
@@ -268,6 +268,28 @@ fn escape_on_a_shape_drag_saves_the_option_it_put_back() {
assert_eq!(s.prefs.corner_radius, radius);
}
/// Setting another tool's option during a polygon drag leaves the drag's options alone: Escape
/// still puts back the side count the arrow changed.
#[test]
fn escape_puts_back_the_sides_after_another_tool_s_option_is_set() {
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
let mut s = session();
let v = ViewInfo { smart_guides: false, ..Default::default() };
select(&mut s, "polygon");
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
// Saves every option, the one the arrow changed included.
s.set_tool_option("length", &json!(50));
let values = json!({"points": 9});
s.set_tool_options(Some("star"), values.as_object().unwrap());
assert_eq!(s.tool_options()["sides"], json!(7), "the drag keeps its side count");
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
assert_eq!(s.tool_options()["sides"], json!(6));
assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(6));
assert_eq!(s.prefs.tool_settings["star"]["points"], json!(9));
}
/// The Fidelity an Alt smoothing drag uses on a selected path.
fn alt_smooth_fidelity(s: &mut Session) -> Option<f64> {
use vectorcraft_tools::{Action, Mods, PointerEvent, PointerKind};
+286 -10
View File
@@ -83,6 +83,23 @@ pub enum UiRequest {
/// Place a file with these `file.place` params: a click or drag of the place cursor, when
/// [`Session::place_cursor_requests`] is set.
Place(Value),
/// A press held while the tool computed an edit on another thread was made now, at `pos` in the
/// document with [`crate::DocState::uid`] `doc`, with tool `tool` active (the selection tool Cmd
/// lent): the frontend does what it does after a press it hands over itself.
HeldPress {
doc: Option<u64>,
pos: Point,
tool: &'static str,
},
}
/// Pointer or key input that came while the active tool computed an edit on another thread
/// ([`Tool::editing`]), made in order once the edit is applied ([`Session::tool_poll`],
/// [`Session::finish_tool_edit`]).
#[derive(Clone, Copy, Debug)]
pub(crate) enum HeldInput {
Pointer(PointerEvent),
Key(ToolKey, Mods),
}
impl Session {
@@ -106,6 +123,7 @@ impl Session {
/// Choose a tool (the toolbar, its shortcut, MCP), finishing any pending tool work first.
pub fn select_tool(&mut self, id: &str, view: ViewInfo) -> Result<()> {
self.finish_tool_edit_later()?;
// Choosing a perspective tool shows the document's perspective grid; Hide Grid hides it
// again, the tool staying chosen.
if matches!(id, "perspectiveGrid" | "perspectiveSelection")
@@ -129,6 +147,8 @@ impl Session {
/// Switch to tool `id` without choosing it afresh (back from a temporary tool: a hidden
/// perspective grid stays hidden), finishing any pending tool work first.
pub fn switch_tool(&mut self, id: &str, view: ViewInfo) -> Result<()> {
// The edit the tool computes on another thread and the input held for it come first.
self.finish_tool_edit_later()?;
self.give_back_tool(view)?;
if self.tool.id() == id {
return Ok(());
@@ -257,7 +277,15 @@ impl Session {
/// Give `t` the persistent options stored for it in `prefs`.
fn restore_tool_settings(prefs: &Prefs, t: &mut dyn Tool) {
Self::restore_stores(prefs, t, |_| true);
}
/// Give `t` the persistent options stored for it in `prefs`, from the stores `wanted` accepts.
fn restore_stores(prefs: &Prefs, t: &mut dyn Tool, wanted: impl Fn(&str) -> bool) {
for (store, keys) in settings::stores(t.id()) {
if !wanted(store) {
continue;
}
let Some(saved) = prefs.tool_settings.get(store) else { continue };
for k in keys {
if let Some(v) = saved.get(*k) {
@@ -267,6 +295,7 @@ impl Session {
}
// Alt switches the Pencil, Paintbrush or Blob Brush to Smooth, using Smooth Tool Options' Fidelity.
if matches!(t.id(), "pencil" | "paintbrush" | "blobBrush")
&& wanted("smooth")
&& let Some(v) = prefs.tool_settings.get("smooth").and_then(|s| s.get("fidelity"))
{
t.set_option("smoothFidelity", v);
@@ -421,8 +450,85 @@ impl Session {
self.tool_step = now;
}
/// Feed a pointer event to the active tool. Returns requests for the UI.
/// Feed a pointer event to the active tool. Returns requests for the UI. While the tool computes
/// an edit on another thread, a press and what follows it are held and made once the edit is
/// applied, in order ([`Session::tool_poll`]); moves of the pointer with no button held go to
/// the tool at once.
pub fn pointer(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result<Vec<UiRequest>> {
let n = self.next_input();
if ev.kind != PointerKind::Move && (!self.held_input.is_empty() || self.tool_edit_pending()) {
self.held_input.push_back((n, HeldInput::Pointer(*ev), view));
return Ok(vec![]);
}
let r = self.pointer_now(ev, view);
self.note_edit_start(n);
r
}
/// The number of the next pointer or key event handed to the session.
fn next_input(&mut self) -> u64 {
let n = self.input_count;
self.input_count = n.wrapping_add(1);
n
}
/// How many pointer and key events have been handed to the session ([`Session::pointer`],
/// [`Session::tool_key`]); with [`Session::input_applied`], a frontend tells when the events it
/// handed over have been made.
pub fn input_count(&self) -> u64 {
self.input_count
}
/// Have the events numbered `from..to` ([`Session::input_count`] before and after handing them
/// over) been made, and the edit they started on another thread applied?
pub fn input_applied(&self, from: u64, to: u64) -> bool {
let ours = |n: &u64| (from..to).contains(n);
!self.held_input.iter().any(|(n, ..)| ours(n)) && !(self.tool_edit_pending() && self.edit_started_by.as_ref().is_some_and(ours))
}
/// After event `n` was made: the event that started the edit being computed, if one is.
fn note_edit_start(&mut self, n: u64) {
if !self.tool_edit_pending() {
self.edit_started_by = None;
} else if self.edit_started_by.is_none() {
self.edit_started_by = Some(n);
}
}
/// Is the active tool, or the tool Cmd lent the selection tool's drag away from, computing an
/// edit on another thread?
fn tool_edit_pending(&self) -> bool {
self.tool.editing() || self.lender.as_ref().is_some_and(|t| t.editing())
}
/// Makes the input held while the tool computed an edit, in order, until a held gesture starts
/// another such edit.
fn replay_held_input(&mut self) -> Result<Vec<UiRequest>> {
let mut ui = vec![];
let mut failed = None;
while !self.tool_edit_pending()
&& let Some((n, input, view)) = self.held_input.pop_front()
{
let r = match input {
HeldInput::Pointer(ev) => self.pointer_now(&ev, view).map(|mut r| {
if ev.kind == PointerKind::Down {
r.push(UiRequest::HeldPress { doc: self.active().map(|d| d.uid), pos: ev.pos, tool: self.tool.id() });
}
r
}),
HeldInput::Key(key, mods) => self.tool_key_now(key, mods, view),
};
self.note_edit_start(n);
match r {
Ok(r) => ui.extend(r),
// The input after it is still made, as it was when each event came on its own.
Err(e) => failed = failed.or(Some(e)),
}
}
failed.map_or(Ok(ui), Err)
}
fn pointer_now(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result<Vec<UiRequest>> {
self.pointer_event(ev, view, true)
}
@@ -433,8 +539,25 @@ impl Session {
/// nothing and a click opens no size dialog. The tool gets back the persistent options it had
/// when the press began, and none of the press's changes to them are stored. A dropped Type
/// press restores the prior selection. The freeform gradient point selected once the tool
/// took the press is selected again.
/// took the press is selected again. A press held while the tool computes an edit on another
/// thread has not reached the tool: it is removed from the held input with the pointer events
/// and tool keys held after it, and the tool is left as it is. A perspective plane key held
/// after it stays held, since the plane it picks outlasts a dropped press. Pointer events held
/// after the last held release belong to the press the tool has, and are removed with it.
pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> {
let (from, held) = self.held_press();
let keep: Vec<bool> = (self.held_input.iter().enumerate())
.map(|(j, (_, input, _))| match input {
_ if j < from => true,
HeldInput::Pointer(_) => false,
HeldInput::Key(key, _) => !held || self.plane_key(*key).is_some(),
})
.collect();
let mut keep = keep.into_iter();
self.held_input.retain(|_| keep.next().unwrap_or(true));
if held {
return Ok(());
}
// Nothing to roll back without a document; the tool still drops the press and gets the release.
let _ = self.cancel_interaction();
let before = self.press_options.take();
@@ -476,6 +599,19 @@ impl Session {
r.map(drop)
}
/// Where the input of the press in progress starts in the held input, and whether the press
/// itself is held: the last held press when no release is held after it; otherwise the input
/// after the last held release (all of it when none is held), which follows a press the tool
/// already has.
fn held_press(&self) -> (usize, bool) {
let ends = |kind: PointerKind| matches!(kind, PointerKind::Down | PointerKind::Up);
match self.held_input.iter().rposition(|(_, input, _)| matches!(input, HeldInput::Pointer(ev) if ends(ev.kind))) {
Some(i) if matches!(self.held_input.get(i), Some((_, HeldInput::Pointer(ev), _)) if ev.kind == PointerKind::Down) => (i, true),
Some(i) => (i + 1, false),
None => (0, false),
}
}
/// The options of `t` that [`Self::store_tool_settings`] stores.
fn persistent_options(t: &dyn Tool) -> Map<String, Value> {
let opts = t.options();
@@ -610,19 +746,148 @@ impl Session {
self.tool.wants_samples()
}
/// Is the active tool waiting for work it runs on another thread ([`Tool::waiting`])?
/// Is the active tool waiting for work it runs on another thread ([`Tool::waiting`]), is input
/// held until an edit it computes is applied, or are requests for the UI left from making it?
pub fn tool_waiting(&self) -> bool {
self.tool.waiting()
self.tool.waiting() || !self.held_input.is_empty() || !self.held_ui.is_empty()
}
/// Lets the active tool check on the work [`Session::tool_waiting`] reports, and with `wait`
/// wait for it to finish ([`Tool::poll`]).
pub fn tool_poll(&mut self, view: ViewInfo, wait: bool) -> Result<()> {
self.with_tool_cx(view, |t, cx| t.poll(cx, wait));
self.take_tool_panic()
/// wait for it to finish ([`Tool::poll`]); an edit the work made is applied, and then the input
/// held for it is made. Returns requests for the UI, those left from making held input where
/// nothing could take them first ([`Session::finish_tool_edit_later`]).
pub fn tool_poll(&mut self, view: ViewInfo, wait: bool) -> Result<Vec<UiRequest>> {
if self.settling_tool_edit {
return Ok(vec![]);
}
self.settling_tool_edit = true;
let r = self.tool_poll_now(view, wait);
self.settling_tool_edit = false;
// On an error the requests left wait for the next poll.
let r = r?;
let mut ui = std::mem::take(&mut self.held_ui);
ui.extend(r);
Ok(ui)
}
fn tool_poll_now(&mut self, view: ViewInfo, wait: bool) -> Result<Vec<UiRequest>> {
let acts = self.with_tool_cx(view, |t, cx| t.poll(cx, wait));
self.take_tool_panic()?;
let applied = !acts.is_empty();
let mut ui = self.apply_actions(acts)?;
if !self.tool_edit_pending() {
self.edit_started_by = None;
// The input held for an edit applied now is made at the next poll, so what waits for the
// edit alone (a `ui.pointer` reply) sees the document as the edit left it.
if !applied {
ui.extend(self.replay_held_input()?);
}
}
Ok(ui)
}
/// Is the active tool computing an edit on another thread ([`Tool::editing`]), or is input held
/// until it is applied?
pub fn tool_editing(&self) -> bool {
self.tool_edit_pending() || !self.held_input.is_empty()
}
/// Waits for the edit the active tool computes on another thread and applies it
/// ([`Tool::finish_edit`]), then makes the input held for it, waiting in turn for an edit that
/// starts, so what runs next sees the document as the gestures left it. Commands, saves, option
/// changes, interactions, undo scopes and tool or document switches call it first. Returns
/// requests for the UI, with those left from earlier ([`Session::finish_tool_edit_later`]); on
/// an error, the next [`Session::tool_poll`] returns them.
pub fn finish_tool_edit(&mut self) -> Result<Vec<UiRequest>> {
if self.settling_tool_edit {
return Ok(vec![]);
}
let mut ui = std::mem::take(&mut self.held_ui);
if self.tool_editing() {
self.settling_tool_edit = true;
let r = self.finish_tool_edit_now();
self.settling_tool_edit = false;
match r {
Ok(r) => ui.extend(r),
Err(e) => {
ui.append(&mut self.held_ui);
self.held_ui = ui;
return Err(e);
}
}
}
Ok(ui)
}
/// [`Session::finish_tool_edit`] for a caller that cannot hand requests to the UI (a command, a
/// tool switch): the next [`Session::tool_poll`] returns them, and [`Session::tool_waiting`]
/// holds until then.
pub(crate) fn finish_tool_edit_later(&mut self) -> Result<()> {
let ui = self.finish_tool_edit()?;
self.held_ui.extend(ui);
Ok(())
}
fn finish_tool_edit_now(&mut self) -> Result<Vec<UiRequest>> {
let mut ui = vec![];
let mut failed = None;
loop {
match self.finish_pending_edit() {
Ok(r) => ui.extend(r),
Err(e) => failed = failed.or(Some(e)),
}
// A tool that cannot finish its edit keeps the input held.
if self.tool_edit_pending() {
break;
}
self.edit_started_by = None;
if self.held_input.is_empty() {
break;
}
match self.replay_held_input() {
Ok(r) => ui.extend(r),
Err(e) => failed = failed.or(Some(e)),
}
}
match failed {
None => Ok(ui),
Some(e) => {
self.held_ui.extend(ui);
Err(e)
}
}
}
/// Waits for the edit being computed and applies it: the active tool's, or that of the tool
/// Cmd lent the selection tool's drag away from, which is active meanwhile.
fn finish_pending_edit(&mut self) -> Result<Vec<UiRequest>> {
if self.tool.editing() {
let acts = self.with_tool_cx(self.last_view, |t, cx| t.finish_edit(cx));
self.take_tool_panic()?;
return self.apply_actions(acts);
}
let Some(lender) = self.lender.take_if(|t| t.editing()) else { return Ok(vec![]) };
let lent = std::mem::replace(&mut self.tool, lender);
let acts = self.with_tool_cx(self.last_view, |t, cx| t.finish_edit(cx));
let r = self.take_tool_panic().and_then(|()| self.apply_actions(acts));
self.lender = Some(std::mem::replace(&mut self.tool, lent));
r
}
/// A key for the active tool. While the tool computes an edit on another thread, the key is held
/// and made once the edit is applied, after the input held before it.
pub fn tool_key(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> Result<Vec<UiRequest>> {
let n = self.next_input();
if self.tool_editing() {
self.held_input.push_back((n, HeldInput::Key(key, mods), view));
return Ok(vec![]);
}
let r = self.tool_key_now(key, mods, view);
self.note_edit_start(n);
r
}
fn tool_key_now(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> Result<Vec<UiRequest>> {
// 1–4 pick the active perspective plane while the grid is shown.
if let Some(plane) = self.plane_key(key) {
self.execute("perspective.plane.set", &serde_json::json!({ "plane": plane.id() }))?;
@@ -828,7 +1093,8 @@ impl Session {
/// it is on, makes the drawing tools' a crosshair, [`Cursor::precise`]). With Cmd held, the pointer of the selection tool a
/// press would borrow ([`Self::lend_selection_tool`]).
pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor {
let lent = if mods.cmd && self.lender.is_none() { self.lent_tool(self.tool.id(), &mods) } else { None };
// While an edit is computed, a Cmd press is held for the active tool, which shows it is busy.
let lent = if mods.cmd && self.lender.is_none() && !self.tool_editing() { self.lent_tool(self.tool.id(), &mods) } else { None };
let c = match lent {
Some(id) => {
let lent = self.make_tool(id);
@@ -851,6 +1117,9 @@ impl Session {
self.tool.options()
}
pub fn set_tool_option(&mut self, key: &str, v: &Value) {
// The active tool's edit being computed is applied with the options it was started with. A
// failure to apply it was the edit's own, and the option is set all the same.
let _ = self.finish_tool_edit_later();
if key == "queue" && self.tool.id() == "place" {
self.note_place_queue_roots();
}
@@ -907,7 +1176,10 @@ impl Session {
}
Self::restore_tool_settings(&self.prefs, lender);
}
Self::restore_tool_settings(&self.prefs, self.tool.as_mut());
// Only the stores it shares with the tool set: the active tool's own options stay as they
// are, also in the middle of a drag that Escape can cancel.
let set = other.id();
Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store));
}
out
}
@@ -922,6 +1194,10 @@ impl Session {
{
return Err(format!("unknown tool `{t}`"));
}
// The active tool's merge being computed is applied with the options it was started with.
if tool.is_none_or(|t| t == self.tool.id()) {
self.finish_tool_edit_later().map_err(|e| e.to_string())?;
}
let mut values = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default();
if let Some(k) = p.get("key").and_then(Value::as_str) {
values.insert(k.to_string(), p.get("value").cloned().unwrap_or(Value::Null));
+50
View File
@@ -219,6 +219,56 @@ fn every_command_with_junk_params() {
);
}
/// Each document's uid, revision and selected ids, the active document and the current paint.
type ToolEditState = (Vec<(u64, u64, Vec<u64>)>, Option<usize>, vectorcraft_tools::PaintDefaults);
/// What a command that runs while the active tool computes an edit on another thread must leave
/// as it was: every document's revision and selection, which document is active, and the current
/// paint.
fn tool_edit_state(s: &Session) -> ToolEditState {
let docs = s.documents().iter().map(|d| (d.uid, d.revision, d.selection.objects.iter().map(|i| i.0).collect())).collect();
(docs, s.active_index(), s.paint.clone())
}
/// Every command that runs at once while the active tool computes an edit on another thread (a
/// Shape Builder merge), rather than applying the edit first (`waits_for_tool_edit`), leaves the
/// documents' revisions and selections, the active document and the current paint as they were,
/// with `{}`, junk params and params that turn its options on and off: the edit, computed for the
/// document as it was, still applies after it.
#[test]
fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() {
let path = safe_path();
let mut failures = vec![];
for fx in [Fixture::Single, Fixture::Multi] {
for c in command_specs().iter().filter(|c| !vectorcraft_engine::waits_for_tool_edit(c.id)) {
let mut cases = junk_params(c.params, &path);
if heavy(c.id) {
cases.truncate(12);
}
for k in param_keys(c.params) {
for v in [json!(true), json!(false), json!(1), json!("on")] {
cases.push(json!({ k.as_str(): v }));
}
}
// Find Objects selects only with a filter, which one key at a time does not give it.
if c.id == "document.find" {
cases.extend([json!({"kind": "Path", "select": true}), json!({"name": "no such name", "select": true})]);
}
for p in &cases {
let mut s = fx.session();
let before = tool_edit_state(&s);
let _ = catch_quiet(|| no_panic(s.execute(c.id, p)));
if tool_edit_state(&s) != before {
failures.push(format!("{} {p} [{fx:?}]", c.id));
}
}
}
}
failures.sort();
failures.dedup_by(|a, b| a.split(' ').next() == b.split(' ').next());
assert!(failures.is_empty(), "{} commands change a document without waiting for a tool edit:\n{}", failures.len(), failures.join("\n"));
}
/// Junk inside the obvious structured params: ids arrays, anchors, matrices, colours, stops.
#[test]
fn structured_junk() {
+154
View File
@@ -2415,6 +2415,64 @@ proptest! {
let text = type42_composite_eps(&font, gid);
survive("damaged Type 42 glyphs", || vectorcraft_eps::import(text.as_bytes()).ok().map(|r| r.document))?;
}
/// CID-keyed fonts with hostile CMaps (codespace ranges of any length, mappings past them)
/// and Type 0 CIDFonts with damaged binary data (offset table, charstrings, subroutine table,
/// any FDBytes and GDBytes), shown with any bytes: drawn, measured and outlined, or refused.
#[test]
fn eps_cid_fonts_never_panic(
space in prop::collection::vec((prop::collection::vec(any::<u8>(), 0..6), prop::collection::vec(any::<u8>(), 0..6)), 0..4),
cids in prop::collection::vec((prop::collection::vec(any::<u8>(), 1..5), any::<u16>()), 0..6),
data in prop::collection::vec(any::<u8>(), 0..200),
fd_bytes in 0u8..6,
gd_bytes in 0u8..6,
len_iv in -2i8..8,
shown in prop::collection::vec(any::<u8>(), 0..24),
) {
let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::<String>();
let ranges: String = space.iter().map(|(lo, hi)| format!("<{}> <{}>\n", hex(lo), hex(hi))).collect();
let maps: String = cids.iter().map(|(c, cid)| format!("<{}> <{}> {cid}\n", hex(c), hex(c))).collect();
let text = format!(
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n\
/CIDInit /ProcSet findresource begin 20 dict begin /CIDFontName /F def /CIDFontType 0 def\n\
/FDArray [4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 4 dict dup begin /lenIV {len_iv} def\n\
/SubrMapOffset 3 def /SDBytes 2 def /SubrCount 4 def end def currentdict end] def\n\
/CIDMapOffset 0 def /FDBytes {fd_bytes} def /GDBytes {gd_bytes} def /CIDCount 40 def\n\
(Hex) {} StartData\n{}\n\
/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /M def\n\
{} begincodespacerange\n{ranges}endcodespacerange\n{} begincidrange\n{maps}endcidrange\n\
endcmap CMapName currentdict /CMap defineresource pop end end\n\
/C /M [/F] composefont 40 scalefont setfont 10 20 moveto <{}> show <{}> stringwidth pop pop\n\
10 60 moveto <{}> true charpath fill\nshowpage\n%%EOF\n",
data.len(), hex(&data), space.len(), cids.len(), hex(&shown), hex(&shown), hex(&shown)
);
survive("hostile CID-keyed fonts", || vectorcraft_eps::import(text.as_bytes()).ok().map(|r| r.document))?;
}
/// Embedded Type 1 fonts whose encrypted part is damaged or hostile (any bytes, binary or
/// hexadecimal), shown, measured and outlined: drawn, or left out.
#[test]
fn eps_type1_programs_never_panic(
part in prop::collection::vec(any::<u8>(), 0..400),
hex in any::<bool>(),
shown in prop::collection::vec(any::<u8>(), 0..12),
) {
let hexed = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::<String>();
// Bytes that would end the part early are left out, as `cleartomark` ends it.
let part: Vec<u8> = part.into_iter().filter(|b| *b != b'c').collect();
let mut bytes = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n\
12 dict begin /FontName /T1 def /FontType 1 def /FontMatrix [0.001 0 0 0.001 0 0] def /FontBBox [0 0 1000 1000] def\n\
/Encoding StandardEncoding def currentdict end currentfile eexec\n"
.to_vec();
if hex {
bytes.extend(hexed(&part).into_bytes());
} else {
bytes.extend(part);
}
bytes.extend(format!("\n{}\ncleartomark\n/T1 findfont 40 scalefont setfont 10 20 moveto <{}> show <{}> stringwidth pop pop\n\
10 60 moveto <{}> true charpath fill\nshowpage\n%%EOF\n", "0".repeat(512), hexed(&shown), hexed(&shown), hexed(&shown)).into_bytes());
survive("hostile Type 1 programs", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?;
}
}
/// The TrueType font [`type42_composite_eps`] carries.
@@ -3239,6 +3297,50 @@ fn text_editing_of(document: &str, objects: &str) -> String {
/// Area Type Options as an area frame's data may keep them: rows, columns, gutters and the first
/// baseline, and keys besides, each with a value of any kind, in or out of range.
/// A paragraph's attributes as a text document might keep them: an alignment (key 0), auto leading
/// (7), hyphenation options (10 to 15) and tab stops (30) of any value or type, the stops a list of
/// any length whose entries may be anything.
fn arb_paragraph_attributes() -> impl Strategy<Value = String> {
let values = prop::sample::select(vec![
"0",
"1",
"2",
"3",
"6",
"7",
"-1",
"2.5",
"1e400",
"-1e400",
"NaN",
"inf",
"1e9",
"(x)",
"true",
"false",
"/nil",
"[ 1 ]",
"<< /0 1 >>",
]);
let keys = prop::sample::select(vec!["0", "7", "10", "11", "12", "13", "14", "15"]);
let stop = (values.clone(), values.clone(), 0usize..3).prop_map(|(at, align, shape)| match shape {
0 => format!("<< /0 {at} /1 {align} >>"),
1 => format!("<< /1 {align} >>"),
_ => at.to_string(),
});
let tabs = (prop::collection::vec(stop, 0..40), 0usize..4).prop_map(|(stops, shape)| match shape {
0 => format!("/30 << /0 [ {} ] >>", stops.join(" ")),
1 => "/30 << /0 7 >>".to_string(),
2 => "/30 [ 1 2 ]".to_string(),
_ => String::new(),
});
(prop::collection::vec((keys, values), 0..8), tabs).prop_map(|(kv, tabs)| {
let mut attrs: Vec<String> = kv.iter().map(|(k, v)| format!("/{k} {v}")).collect();
attrs.push(tabs);
attrs.join(" ")
})
}
fn arb_area_options() -> impl Strategy<Value = String> {
let keys = prop::sample::select(vec!["3", "4", "5", "7", "8", "10", "13", "14"]);
let values = prop::sample::select(vec![
@@ -3399,6 +3501,23 @@ fn the_shown_stories_fixture_opens_with_its_layers() {
assert!(texts.iter().all(|t| t.contains('\u{2028}') && t.contains('\n')), "{texts:?}");
}
/// The fuzzed editing data with its layer, pattern and global colour named in code page 949 opens
/// with those names, read in that encoding, from its layers.
#[test]
fn the_editing_fixture_reads_names_in_a_legacy_encoding() {
// 레이어 1, then 빨강.
let text = editing_text()
.replace("(One) Ln", r"(\267\271\300\314\276\356 1) Ln")
.replace("(Dots)", r"(\273\241\260\255)")
.replace("(Black global)", r"(\273\241\260\255 global)");
let bytes = editing_eps(&text);
let r = vectorcraft_eps::import_names(&bytes, true, true, vectorcraft_eps::NameEncoding::Korean).unwrap();
let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert_eq!(names, ["레이어 1", "Two"], "{:?}", r.warnings);
assert!(r.document.pattern("빨강").is_some(), "{:?}", r.warnings);
assert!(r.document.swatch("빨강 global").is_some_and(|s| s.global), "{:?}", r.warnings);
}
proptest! {
#![proptest_config(config())]
@@ -3446,6 +3565,18 @@ proptest! {
survive(".ai text frames with hostile area options", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
/// The same text document with hostile paragraph attributes: an alignment, auto leading,
/// hyphenation options and tab stops of any value, type or size.
#[test]
fn text_frames_with_hostile_paragraph_attributes_never_panic(attrs in arb_paragraph_attributes()) {
let text = frames_document_text().replace("/5 << /0 2 /1 4 /2 6 >>", &format!("/5 << /1 4 /2 6 {attrs} >>"));
let editing = text_editing_of(&text, FRAME_OBJECTS);
let bytes = editing_eps(&editing);
survive("EPS text frames with hostile paragraph attributes", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?;
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&editing)].concat();
survive(".ai text frames with hostile paragraph attributes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
/// The type on a path of the same text document with hostile Type on a Path Options, opened as
/// an EPS document and as a `.ai`'s editing data.
#[test]
@@ -3475,6 +3606,26 @@ proptest! {
survive("mutated EPS editing data", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?;
}
/// Names of any bytes (a layer's, a pattern's, a global colour's) read in any legacy name
/// encoding: each byte written as an octal escape, so every code page sees bytes it doesn't
/// define, cut sequences and UTF-8 alike.
#[test]
fn eps_editing_data_names_in_any_encoding_never_panic(
name in prop::collection::vec(any::<u8>(), 0..24),
encoding in prop::sample::select(vectorcraft_eps::NameEncoding::LABELS.to_vec()),
) {
let escaped: String = name.iter().map(|b| format!("\\{b:03o}")).collect();
let text = editing_text()
.replace("(One) Ln", &format!("({escaped}) Ln"))
.replace("(Dots)", &format!("({escaped})"))
.replace("(Black global)", &format!("({escaped} global)"));
let bytes = editing_eps(&text);
let encoding = vectorcraft_eps::NameEncoding::from_label(encoding).unwrap();
survive("EPS editing data names in a legacy encoding", || {
vectorcraft_eps::import_names(&bytes, true, false, encoding).ok().map(|r| r.document)
})?;
}
/// A `.ai` whose envelopes are damaged or hostile: any kind, warp style, options word,
/// Fidelity and grid size, corners out of range or repeated, the contents block cut short.
#[test]
@@ -5082,6 +5233,9 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
"-9 /Real (CornerRadius) ,",
"1 /Bool (Absolute) ,",
"-0.5 /Real ,",
"0.5 /Real ,",
"1 /Real ,",
"1e308 /Real ,",
"1.5 /Real ,",
"-2 /Real ,",
"; (BSLeftWidthsArray) ,",
@@ -751,6 +751,7 @@ fn cut_anchor_of_closed_path_opens_it_with_single_undo_step() {
check_session(&s).unwrap();
}
/// Cutting an interior connection copies that segment and leaves two selected sibling objects.
#[test]
fn cut_middle_segment_of_open_path_splits_into_two_open_paths_with_single_undo_step() {
let mut s = Session::new();
@@ -772,16 +773,20 @@ fn cut_middle_segment_of_open_path_splits_into_two_open_paths_with_single_undo_s
// Source path should now be split into two surviving open runs.
let src_node = s.doc().unwrap().doc.node(id).unwrap();
let src_path = src_node.path_data().unwrap();
assert_eq!(src_path.subpaths.len(), 2, "two open paths/subpaths remain after cutting middle segment");
assert_eq!(src_path.subpaths.len(), 1);
assert!(!src_path.subpaths[0].closed);
assert_eq!(src_path.subpaths[0].anchors.len(), 2);
assert_eq!(src_path.subpaths[0].anchors[0].p.x, 10.0);
assert_eq!(src_path.subpaths[0].anchors[1].p.x, 50.0);
assert!(!src_path.subpaths[1].closed);
assert_eq!(src_path.subpaths[1].anchors.len(), 2);
assert_eq!(src_path.subpaths[1].anchors[0].p.x, 90.0);
assert_eq!(src_path.subpaths[1].anchors[1].p.x, 130.0);
let pieces = s.doc().unwrap().selection.objects.clone();
assert_eq!(pieces.len(), 2, "two independent path objects remain after cutting the middle segment");
assert_eq!(pieces[0], id);
let second = &s.doc().unwrap().doc.node(pieces[1]).unwrap().path_data().unwrap().subpaths[0];
assert!(!second.closed);
assert_eq!(second.anchors.len(), 2);
assert_eq!(second.anchors[0].p.x, 90.0);
assert_eq!(second.anchors[1].p.x, 130.0);
// Clipboard holds the cut middle segment:
assert_eq!(s.clipboard.nodes.len(), 1);
@@ -800,7 +805,9 @@ fn cut_middle_segment_of_open_path_splits_into_two_open_paths_with_single_undo_s
// Redo re-applies the split:
run(&mut s, "edit.redo", json!({}));
let redone_path = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap();
assert_eq!(redone_path.subpaths.len(), 2);
assert_eq!(redone_path.subpaths.len(), 1);
assert_eq!(s.doc().unwrap().selection.objects, pieces);
assert!(s.doc().unwrap().doc.node(pieces[1]).is_some());
check_session(&s).unwrap();
}
@@ -0,0 +1,243 @@
//! Original synthetic geometry for the deletion half of #3380; no external fixtures.
use serde_json::json;
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, Paint};
use vectorcraft_doc::{Appearance, NodeId, NodeKind};
use vectorcraft_engine::Session;
use vectorcraft_geom::{Affine, Anchor, PathData, Rect, SubPath};
use vectorcraft_testkit::{invariants::check_session, raster::render_artboard};
/// Create the same rectangle for the edited path and its stacking-order neighbors.
fn rectangle(s: &mut Session) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": 30, "y": 30, "width": 80, "height": 60})).unwrap()["id"].as_u64().unwrap())
}
/// Start a small document suitable for exact geometry and rendered-history assertions.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s
}
/// Clear, explicit anchor deletion and Cut preserve styled survivors, sibling order and history.
#[test]
fn deleting_opposite_rectangle_segments_makes_independent_styled_objects_and_undoes_once() {
for command in ["edit.clear", "path.deleteAnchors", "edit.cut"] {
let mut s = session();
let below = rectangle(&mut s);
let id = rectangle(&mut s);
let above = rectangle(&mut s);
s.execute("select.set", &json!({"ids": [below.0, id.0, above.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
{
let n = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap();
n.name = Some("Styled rectangle".into());
n.opacity = 0.65;
n.transform(Affine::translate((12.0, 8.0)) * Affine::rotate(0.23) * Affine::scale_non_uniform(1.1, 0.8), true);
n.appearance =
Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.2, 0.4, 0.8)), 4.0)
.into();
}
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 1], [0, 3]]})).unwrap();
let original = s.doc().unwrap().doc.node(id).unwrap().clone();
let before_doc = serde_json::to_value(&s.doc().unwrap().doc).unwrap();
let before_selection = s.doc().unwrap().selection.clone();
let history = s.doc().unwrap().history.undo.len();
s.execute(command, &json!({})).unwrap();
let st = s.doc().unwrap();
let children = st.doc.node(group).unwrap().children().unwrap();
assert_eq!(children.len(), 4, "{command}: two independent pieces between the existing siblings");
assert_eq!([children[0].id, children[1].id, children[3].id], [below, id, above]);
let ids = [id, children[2].id];
assert_eq!(st.selection.objects, ids);
assert!(st.selection.anchors.is_empty() && st.selection.segments.is_empty());
assert_eq!(st.history.undo.len(), history + 1);
// The two surviving sides, in contour order, carry every node property and baked transform.
let anchors = &original.path_data().unwrap().subpaths[0].anchors;
for (piece, indexes) in ids.into_iter().zip([[2, 3], [0, 1]]) {
let mut expected = original.clone();
expected.id = piece;
let mut run = vec![anchors[indexes[0]], anchors[indexes[1]]];
run[0].h_in = run[0].p;
run[1].h_out = run[1].p;
if let NodeKind::Path { path, live, .. } = &mut expected.kind {
*path = PathData::single(SubPath::new(run, false));
*live = None;
}
assert_eq!(st.doc.node(piece).unwrap(), &expected, "{command}");
}
let rendered = render_artboard(&st.doc);
let after_doc = serde_json::to_value(&st.doc).unwrap();
let after_selection = st.selection.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_doc);
assert_eq!(s.doc().unwrap().selection, before_selection);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after_doc);
assert_eq!(s.doc().unwrap().selection, after_selection);
assert_eq!(render_artboard(&s.doc().unwrap().doc), rendered);
check_session(&s).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
assert!(ids.iter().all(|id| s.doc().unwrap().doc.node(*id).is_none()));
assert!(s.doc().unwrap().doc.node(below).is_some() && s.doc().unwrap().doc.node(above).is_some());
}
}
/// Removing separated anchors retains each cubic run and retracts only its unused endpoint handles.
#[test]
fn deleting_separated_anchors_splits_an_open_path_and_keeps_cubic_handles() {
let mut s = session();
let id = rectangle(&mut s);
let anchors: Vec<_> = (0..8)
.map(|i| {
let mut a = Anchor::corner((20.0 + f64::from(i) * 15.0, 50.0).into());
a.h_in = a.p + (-4.0, -8.0);
a.h_out = a.p + (4.0, 8.0);
a
})
.collect();
*std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap() =
PathData::single(SubPath::new(anchors.clone(), false));
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [0, 5]]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let st = s.doc().unwrap();
assert_eq!(st.selection.objects.len(), 3);
for (piece, start) in st.selection.objects.iter().zip([0, 3, 6]) {
let pd = st.doc.node(*piece).unwrap().path_data().unwrap();
assert_eq!(pd.subpaths.len(), 1);
let sp = &pd.subpaths[0];
assert!(!sp.closed);
assert_eq!(sp.anchors.len(), 2);
assert_eq!(sp.anchors[0].p, anchors[start].p);
assert_eq!(sp.anchors[0].h_out, anchors[start].h_out);
assert_eq!(sp.anchors[1].h_in, anchors[start + 1].h_in);
assert_eq!(sp.anchors[0].h_in, sp.anchors[0].p);
assert_eq!(sp.anchors[1].h_out, sp.anchors[1].p);
}
check_session(&s).unwrap();
}
/// Existing multi-subpath paths and explicit compound members retain structure and exact geometry.
#[test]
fn deletion_preserves_intentional_multi_subpaths_and_compound_members() {
for command in ["edit.clear", "edit.cut"] {
for compound in [false, true] {
let mut s = session();
let id = rectangle(&mut s);
let other = rectangle(&mut s);
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(other).unwrap().transform(Affine::translate((110.0, 0.0)), true);
let extra = s.doc().unwrap().doc.node(other).unwrap().path_data().unwrap().subpaths[0].clone();
let original = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
assert_ne!(extra, original, "the untouched contour must be distinguishable from the edited one");
let container = if compound {
s.execute("select.set", &json!({"ids": [id.0, other.0]})).unwrap();
NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap())
} else {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap().subpaths.push(extra.clone());
s.doc().unwrap().doc.parent_of(id).unwrap()
};
let children = s.doc().unwrap().doc.node(container).unwrap().children().unwrap().len();
let sibling = s.doc().unwrap().doc.node(other).unwrap().clone();
let original = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
let mut expected = vec![
SubPath::new(vec![original.anchors[2], original.anchors[3]], false),
SubPath::new(vec![original.anchors[0], original.anchors[1]], false),
];
if !compound {
expected.push(extra);
}
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 1], [0, 3]]})).unwrap();
s.execute(command, &json!({})).unwrap();
let st = s.doc().unwrap();
assert_eq!(st.doc.node(container).unwrap().children().unwrap().len(), children);
assert_eq!(st.doc.node(id).unwrap().path_data().unwrap().subpaths.len(), if compound { 2 } else { 3 });
assert_eq!(st.doc.node(id).unwrap().path_data().unwrap().subpaths, expected, "{command}, compound: {compound}");
assert_eq!(st.doc.node(other).unwrap(), &sibling);
assert_eq!(st.selection.objects, [id]);
check_session(&s).unwrap();
}
}
}
/// Splitting keeps the original gradient fit on every piece and leaves placed vectors unchanged.
#[test]
fn deletion_split_preserves_gradient_placement() {
for command in ["edit.clear", "path.deleteAnchors", "edit.cut"] {
for kind in [GradientKind::Linear, GradientKind::Radial] {
for placed in [false, true] {
let mut s = session();
let id = rectangle(&mut s);
let mut fill = GradientPaint::new(Gradient { kind, ..Default::default() });
fill.angle = 45.0;
let mut stroke = GradientPaint::new(Gradient { kind, ..Default::default() });
stroke.angle = 90.0;
if placed {
fill.geom = Some(GradientGeom::fit(kind, Rect::new(20.0, 10.0, 160.0, 150.0), 35.0));
stroke.geom = Some(GradientGeom::fit(kind, Rect::new(10.0, 20.0, 150.0, 160.0), -25.0));
}
{
let n = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap();
n.transform(Affine::translate((10.0, 5.0)) * Affine::rotate(0.15), false);
n.appearance = Appearance::basic(Paint::Gradient(Box::new(fill.clone())), Paint::Gradient(Box::new(stroke.clone())), 8.0).into();
}
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 1], [0, 3]]})).unwrap();
let st = s.doc().unwrap();
let before = st.doc.clone();
let before_selection = st.selection.clone();
let history = st.history.undo.len();
let original = before.node(id).unwrap();
let bounds = original.geometric_bounds().unwrap();
let fill_geom = fill.resolve(bounds);
let stroke_geom = stroke.resolve(bounds.inflate(4.0, 4.0));
// The old single-node remainder keeps the original full bounds. Its rendering is
// an independent reference for the two new objects, including unplaced gradients.
let mut expected = (*before).clone();
let a = &original.path_data().unwrap().subpaths[0].anchors;
if let NodeKind::Path { path, live, .. } = &mut expected.node_mut(id).unwrap().kind {
*path = PathData::new(vec![SubPath::new(vec![a[2], a[3]], false), SubPath::new(vec![a[0], a[1]], false)]);
*live = None;
}
let expected_image = render_artboard(&expected);
assert!(expected_image.ink() > 0);
s.execute(command, &json!({})).unwrap();
let st = s.doc().unwrap();
assert_eq!(st.selection.objects.len(), 2);
assert_eq!(st.history.undo.len(), history + 1);
assert!(render_artboard(&st.doc) == expected_image, "{command}, {kind:?}, placed: {placed}: gradient colors moved");
for piece in &st.selection.objects {
let n = st.doc.node(*piece).unwrap();
for (paint, expected_geom) in [(n.appearance.fill_paint(), fill_geom), (n.appearance.stroke_paint(), stroke_geom)] {
let Paint::Gradient(g) = paint else { panic!("gradient was replaced") };
assert_eq!(g.geom, Some(expected_geom), "{command}, {kind:?}, placed: {placed}");
}
}
let after = st.doc.clone();
let after_selection = st.selection.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().selection, before_selection);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, after);
assert_eq!(s.doc().unwrap().selection, after_selection);
assert!(render_artboard(&s.doc().unwrap().doc) == expected_image);
check_session(&s).unwrap();
}
}
}
}
/// A connected remainder keeps automatic fitting; pinning is needed only for separate objects.
#[test]
fn deleting_one_segment_keeps_unplaced_gradients() {
let mut s = session();
let id = rectangle(&mut s);
let paint = Paint::Gradient(Box::new(GradientPaint::new(Default::default())));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance = Appearance::basic(paint.clone(), paint, 8.0).into();
let appearance = s.doc().unwrap().doc.node(id).unwrap().appearance.clone();
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 1]]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let st = s.doc().unwrap();
assert_eq!(st.selection.objects, [id]);
assert_eq!(st.doc.node(id).unwrap().appearance, appearance);
assert_eq!(st.doc.node(id).unwrap().path_data().unwrap().subpaths.len(), 1);
}
+1
View File
@@ -14,6 +14,7 @@ mod beyond_canvas;
mod clear_commands;
mod compound_attributes;
mod copy_direct_selection;
mod delete_path_pieces;
mod dimensions;
mod eyedropper_sources;
mod find_replace_paras;
+21
View File
@@ -125,6 +125,27 @@ fn an_export_step_or_preset_with_a_key_no_longer_read_still_runs() {
s.execute("document.export", &json!({"format": "pdf", "preset": "Old"})).unwrap();
}
/// So does a save, or an Export for Screens, with a key that is no longer read, and an Export for
/// Screens preset file that holds one in a row still loads and exports. `Session::execute`
/// refuses the same options.
#[test]
fn a_save_or_screens_step_with_a_key_no_longer_read_still_runs() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let save = json!({"format": "pdf", "noSuchOption": true, "options": {"retired": 1, "marks": {"useDocumentBleed": true}}});
assert!(check_params("file.saveCopy", &save).is_err());
assert!(s.execute("file.saveCopy", &save).is_err());
s.replay("file.saveCopy", &save).unwrap();
let screens = json!({"noSuchOption": true, "formats": [{"format": "png", "retired": 1}], "settings": {"pdf": {"marks": {"retired": true}}}});
assert!(check_params("document.exportForScreens", &screens).is_err());
assert!(s.execute("document.exportForScreens", &screens).is_err());
s.replay("document.exportForScreens", &screens).unwrap();
let file = json!({"format": "vcexportpresets", "presets": [{"name": "Old", "settings": {"formats": [{"format": "png", "noLongerRead": 1}]}}]});
s.execute("document.exportPresets.import", &json!({"data": file.to_string()})).unwrap();
check_params("document.exportForScreens", &json!({"exportPreset": "Old"})).unwrap();
s.execute("document.exportForScreens", &json!({"exportPreset": "Old"})).unwrap();
}
/// So do an effect's own parameters (#1592): a journal or a file with a key the effect doesn't
/// take, or a value of another type, replays and opens; the effect reads what it knows, clamped.
#[test]
@@ -40,6 +40,7 @@ fn clearing_every_cache_empties_each_plugins_cache_and_keeps_its_settings() {
std::fs::create_dir_all(&folder).unwrap();
let ids = ["test.clearcache.a", "test.clearcache.b"];
let mut s = Session::new();
s.allow_plugin_grants_from_requests();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
s.attach_plugin_store(folder.clone());
for id in ids {
+16
View File
@@ -157,6 +157,22 @@ fn the_exporter_is_given_its_parameters_and_the_file_it_writes() {
let _ = std::fs::remove_dir_all(&dir);
}
/// Export for Screens writes an exporter's format from a row, with the row's `params`, and takes
/// settings for that format.
#[test]
fn export_for_screens_takes_an_exporter_s_format_and_params() {
let mut s = session();
let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#;
install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.screens", r#"["tss"]"#, params), Echo::Params));
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "plugin.test.screens", "params": {"density": 7}}]})).unwrap();
let file = &r["files"][0];
assert!(file["name"].as_str().unwrap().ends_with(".tss"), "{r}");
let got: Value = serde_json::from_slice(&vectorcraft_format::base64_decode(file["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(got["density"], json!(7.0));
let settings = json!({"formats": [{"format": "plugin.test.screens"}], "settings": {"plugin.test.screens": {"params": {"density": 2}}}});
s.execute("document.exportForScreens", &settings).unwrap();
}
/// Only the selected objects, with `selectedOnly`, as for the built-in formats.
#[test]
fn selected_only_hands_over_the_selection() {
+61
View File
@@ -695,6 +695,7 @@ proptest! {
prop_assert!(shown.chars().count() <= vectorcraft_plugins::permissions::MAX_SHOWN_NAME);
}
let mut s = rich_session();
s.allow_plugin_grants_from_requests();
let module = wat::parse_str(tpl::returning(&text, r#"{"objects":[]}"#)).unwrap();
let data = vectorcraft_format::base64_encode(&module);
let r = catch_quiet(|| {
@@ -824,6 +825,65 @@ proptest! {
}
}
/// Manifests with hostile `inputs` (unknown, repeated and oddly cased kinds, long lists, junk of
/// every type) with any `api`, kind and permissions parse to an error or to a filter at `api` 2
/// or later asking for each kind once, whose `permissions` list `doc.read` so that installing
/// it asks for approval. One that installs and echoes its input on a document
/// with type, images and symbols leaves the document as it was, and it still renders.
#[test]
fn hostile_manifest_inputs_never_crash(
kind in prop::sample::select(vec!["filter", "effect", "exporter"]),
names in prop::collection::vec(prop::sample::select(vec!["type", "image", "symbolInstance", "Type", "text", "path", ""]), 0..6),
long in prop::option::weighted(0.1, 4usize..300),
inputs in prop::option::weighted(0.8, prop_oneof![Just(Value::Null), arb_junk()]),
api in prop_oneof![2 => Just(json!(2)), 1 => Just(json!(1)), 1 => Just(json!(3)), 1 => arb_junk()],
permissions in prop_oneof![Just(Value::Null), Just(json!([])), Just(json!(["doc.read", "doc.write"])), Just(json!(["doc.write"]))],
) {
let mut m = json!({"id": "fuzz.inputs", "name": "Inputs", "kind": kind, "api": api});
if kind == "exporter" {
m["extensions"] = json!(["fz"]);
}
if !permissions.is_null() {
m["permissions"] = permissions;
}
m["inputs"] = match (inputs, long) {
(_, Some(n)) => json!(vec!["image"; n]),
(Some(Value::Null) | None, None) => json!(names),
(Some(junk), None) => junk,
};
let text = m.to_string();
let parsed = catch_quiet(|| vectorcraft_plugins::Manifest::parse(text.as_bytes()));
let parsed = parsed.map_err(|msg| TestCaseError::fail(format!("panicked on {text}: {msg}")))?;
if let Ok(man) = &parsed {
let kinds = man.input_kinds();
prop_assert_eq!(kinds.len(), man.inputs.len(), "{}", text);
prop_assert!(kinds.iter().enumerate().all(|(i, k)| !kinds[..i].contains(k)), "{}", text);
prop_assert!(kinds.is_empty() || (man.kind == vectorcraft_plugins::Kind::Filter && man.api >= 2), "{}", text);
let reads = man.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == "doc.read"));
prop_assert!(kinds.is_empty() || (man.asks_permissions() && reads), "{}", text);
}
let mut s = rich_session();
s.allow_plugin_grants_from_requests();
let module = wat::parse_str(tpl::module(&text, tpl::ECHO, "", 1)).unwrap();
let data = vectorcraft_format::base64_encode(&module);
let grant = json!(["doc.read", "doc.write", "state", "effect.render", "export.write"]);
let before = s.doc().unwrap().doc.clone();
let r = catch_quiet(|| {
let installed = s.execute("plugin.install", &json!({"dataBase64": data, "grant": grant})).is_ok();
let _ = s.execute("select.all", &json!({}));
let ran = installed && s.execute("plugin.run", &json!({"id": "fuzz.inputs"})).is_ok();
(installed, ran)
});
let (installed, ran) = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?;
prop_assert!(!installed || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text);
if ran {
prop_assert!(s.doc().unwrap().doc.layers == before.layers, "an echo changed the document: {}", text);
}
renders(&s, &text)?;
vectorcraft_plugins::registry::remove("fuzz.inputs");
vectorcraft_plugins::registry::revoke("fuzz.inputs");
}
/// A plug-in that calls the storage imports with hostile keys (`..`, separators, device names,
/// control characters, too long), values, lengths and pointers in and out of its memory runs to
/// an output, never a panic; every call returns a length or a storage code, and the settings and
@@ -857,6 +917,7 @@ proptest! {
let _ = std::fs::remove_dir_all(&store.0);
let folder = store.0.clone();
let mut s = Session::new();
s.allow_plugin_grants_from_requests();
s.attach_plugin_store(folder.clone());
let storing = |id: &str| format!(r#"{{"id":"{id}","name":"F","kind":"filter","api":2,"permissions":["settings","cache"]}}"#);
let grant = json!(["settings", "cache"]);
+32
View File
@@ -204,6 +204,7 @@ fn a_disabled_plug_in_whose_new_grant_cant_be_stored_stays_disabled() {
let _f = fresh();
let dir = tmp_dir("reinstall-no-grant");
let mut s = launch(&dir);
s.allow_plugin_grants_from_requests();
let manifest = r#"{"id":"test.sm.g","name":"Test","version":"1","kind":"filter","permissions":["doc.read"]}"#;
let module = |out: &str| vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(manifest, out)).unwrap());
s.execute("plugin.install", &json!({"dataBase64": module(r#"{"objects":[]}"#), "grant": ["doc.read"]})).unwrap();
@@ -217,6 +218,37 @@ fn a_disabled_plug_in_whose_new_grant_cant_be_stored_stays_disabled() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A stored module that lists no permissions and isn't read, because it is disabled or Safe Mode is
/// on, leaves the grant for its id in the store. The load that reads it forgets the grant.
#[test]
fn a_stored_module_that_is_not_read_keeps_the_grant_for_its_id() {
let _f = fresh();
let dir = tmp_dir("unread-grant");
let id = "test.sm.unread";
let mut s = launch(&dir);
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&filter(id))})).unwrap();
let grants = dir.join("grants.json");
let entry = serde_json::to_vec(&json!([{"id": id, "hash": "0".repeat(64), "permissions": ["doc.read"]}])).unwrap();
std::fs::write(&grants, &entry).unwrap();
s.execute("plugin.setEnabled", &json!({"id": id, "enabled": false})).unwrap();
let mut s = launch(&dir);
assert!(!installed(id), "the disabled module is skipped");
assert_eq!(std::fs::read(&grants).unwrap(), entry, "a disabled module keeps the grant");
s.execute("plugin.setEnabled", &json!({"id": id, "enabled": true})).unwrap();
vectorcraft_engine::cmd::plugin::start_in_safe_mode();
let mut s = launch(&dir);
assert!(!installed(id), "Safe Mode loads nothing");
assert_eq!(std::fs::read(&grants).unwrap(), entry, "Safe Mode keeps the grant");
safe_mode::set_active(None);
vectorcraft_engine::cmd::plugin::load_prefs_folder(&mut s);
assert!(installed(id));
assert!(!grants.exists(), "the load that reads the module forgets the grant");
let _ = std::fs::remove_dir_all(&dir);
}
/// A launch where the stored plug-in `id` stopped while loading: it is installed, then disabled by
/// its stored file alone (as Disable and Continue saves it), and the next launch skips it.
fn stored_plug_in_disabled_by_file(dir: &std::path::Path, id: &str) -> Session {
+2
View File
@@ -37,6 +37,8 @@ hayro-ccitt = { workspace = true }
serde_json = { workspace = true }
# Substring search for PostScript `search`.
memchr = { workspace = true }
# Names in legacy .ai files that aren't UTF-8, read in the encoding the user picks.
encoding_rs = { workspace = true }
[dev-dependencies]
vectorcraft-testkit = { workspace = true }
+1 -1
View File
@@ -462,7 +462,7 @@ fn an_artboard_larger_than_the_canvas_is_written_on_a_large_canvas() {
let bounds = read.layers.iter().filter_map(|l| l.visual_bounds()).reduce(|a, b| a.union(b)).unwrap();
assert!((bounds.x0 - 1000.0).abs() < 1e-6 && (bounds.y1 - 2000.0).abs() < 1e-6 && (bounds.width() - 2000.0).abs() < 1e-6, "{bounds:?}");
// The same without a readable PDF part, on its first page's size.
let (alone, notes) = crate::ai_alone_on_page(&p.data, (20_000.0, 20_000.0), 1.389).unwrap();
let (alone, notes) = crate::ai_alone_on_page(&p.data, (20_000.0, 20_000.0), 1.389, crate::NameEncoding::default()).unwrap();
assert_eq!(alone.artboards.iter().map(|a| a.rect).collect::<Vec<_>>(), [Rect::new(0.0, 0.0, 20_000.0, 20_000.0)], "{notes:?}");
// And from the editing data alone, as a file saved without its PDF part opens.
let alone = read_back(&doc);
+27 -4
View File
@@ -35,6 +35,7 @@
mod ai;
mod ate;
mod cid;
mod data;
mod graphics;
mod interp;
@@ -44,11 +45,14 @@ mod obj;
mod preview;
mod shading;
mod text;
mod type1;
mod type42;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_cid;
#[cfg(test)]
mod tests_composite;
#[cfg(test)]
mod tests_fontnames;
@@ -60,6 +64,10 @@ mod tests_illustrator;
mod tests_images;
#[cfg(test)]
mod tests_native;
#[cfg(test)]
mod tests_type1;
#[cfg(test)]
mod tests_type42;
use std::collections::HashSet;
use std::sync::Arc;
@@ -73,6 +81,7 @@ use graphics::{GState, Out};
use interp::{Fault, Interp};
use obj::PsError;
pub use ai::NameEncoding;
#[cfg(test)]
pub(crate) use ai::objects_read;
pub(crate) use ai::{
@@ -80,7 +89,7 @@ pub(crate) use ai::{
symbol_art_member, warp_number,
};
pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES};
pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from};
pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from};
pub(crate) use native::{MAX_TEXT, scale_document};
pub use text::family_style;
@@ -89,6 +98,10 @@ const LETTER: [f64; 4] = [0.0, 0.0, 612.0, 792.0];
/// Largest page side read (points).
const MAX_SIDE: f64 = 1e5;
/// The start of the warning that type was set in fonts that aren't available, before ": " and
/// their families: PDF import's words, as type in those fonts comes in the same way.
pub(crate) const MISSING_FONTS_NOTE: &str = "fonts that aren't available show in the fallback font until they are";
/// A read file.
#[derive(Debug)]
pub struct Imported {
@@ -251,6 +264,13 @@ pub fn import_with(bytes: &[u8], editing_data: bool) -> Result<Imported, String>
/// [`import_with`]; `trust`: an Illustrator EPS's layers are used even where they draw differently
/// from its page, with a note (`editingData: "always"`, as for a `.ai`).
pub fn import_trusting(bytes: &[u8], editing_data: bool, trust: bool) -> Result<Imported, String> {
import_names(bytes, editing_data, trust, NameEncoding::default())
}
/// [`import_trusting`], with the names in the editing copy that aren't UTF-8 (layers, objects,
/// artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables
/// and data sets) read in `names`.
pub fn import_names(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncoding) -> Result<Imported, String> {
let ps = program(bytes)?;
let dsc = Dsc::read(ps);
// A legacy `.ai` VectorCraft wrote: its prolog prints the art plainly (gradients flat, no
@@ -258,7 +278,7 @@ pub fn import_trusting(bytes: &[u8], editing_data: bool, trust: bool) -> Result<
// printed).
if editing_data
&& dsc.own_legacy
&& let Some(Ok((document, warnings))) = native::program_alone(ps, dsc.illustrator)
&& let Some(Ok((document, warnings))) = native::program_alone(ps, dsc.illustrator, names)
{
return Ok(Imported { document, warnings, preview: false });
}
@@ -278,7 +298,7 @@ pub fn import_trusting(bytes: &[u8], editing_data: bool, trust: bool) -> Result<
}
let drew = !out.drawn.is_empty();
let why = match (&result, drew) {
(Ok(()), true) if editing_data => return Ok(native::layered(ps, finish(out), trust, dsc.illustrator)),
(Ok(()), true) if editing_data => return Ok(native::layered(ps, finish(out), trust, dsc.illustrator, names)),
(Ok(()), true) => return Ok(finish(out)),
(Ok(()), false) => "it draws nothing VectorCraft's PostScript reader can show".to_string(),
(Err(e), _) => reason(e, fault.as_ref()),
@@ -286,7 +306,7 @@ pub fn import_trusting(bytes: &[u8], editing_data: bool, trust: bool) -> Result<
// A file in the legacy Illustrator format whose program can't be run (a `.ai` that names the
// prolog defining its operators without including it): its layers, which the program has, or
// its art on one layer when it has none (Illustrator 3).
let why = match editing_data.then(|| native::program_alone(ps, dsc.illustrator)).flatten() {
let why = match editing_data.then(|| native::program_alone(ps, dsc.illustrator, names)).flatten() {
Some(Ok((document, warnings))) => return Ok(Imported { document, warnings, preview: false }),
Some(Err(e)) => format!("{why}; its layers couldn't be read either ({e})"),
None => why,
@@ -348,6 +368,9 @@ fn finish_with(out: Out, layers: Vec<Arc<Node>>) -> Imported {
}
doc.layers = layers;
let mut warnings = out.warnings;
if !out.missing_fonts.is_empty() {
warnings.push(format!("{MISSING_FONTS_NOTE}: {}", out.missing_fonts.join(", ")));
}
doc.limit_depth_noting(&mut warnings);
Imported { document: doc, warnings, preview: false }
}
+4 -1
View File
@@ -39,14 +39,17 @@ pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN;
pub(crate) use envelope::MAX_CHECKED;
pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType};
pub(crate) use frames::text_frames;
pub use obj::{NameEncoding, Names};
pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS;
#[cfg(test)]
pub(crate) use read::objects_read;
#[cfg(test)]
pub use read::read;
#[cfg(test)]
pub(crate) use read::with_image_limits;
pub use read::{
BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles,
palette, read, read_beside, symbols, variables,
palette, read_beside, read_in, symbols, variables,
};
pub(crate) use read::{
MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_style_list, slot_frame, slot_of, style_moves_with,
+8 -7
View File
@@ -57,7 +57,7 @@ use vectorcraft_color::Paint;
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
use super::lex::{Lexer, Tok};
use super::obj;
use super::obj::Names;
/// The brush manager's order: the plug-in name of its object.
pub(super) const MANAGER: &str = "Adobe Brush Manager Order"; // brand-ok: the plug-in name the files use
@@ -157,16 +157,17 @@ pub(super) enum BrushError {
}
/// The strings of a plug-in object's section (`section`: what follows `%AI8_BeginPluginObject`):
/// its plug-in name, its name and its parameters, joined. The name is `None` with one string, and
/// the whole is `None` with none.
pub(super) fn plugin_strings(section: &[u8]) -> Option<(String, Option<String>, String)> {
/// its plug-in name, the bytes of its name and its parameters, joined, read by `names` without
/// notes. The name is `None` with one string, and the whole is `None` with none. A brush's name has
/// its note when the brush is read, and the names of its art when their art is read.
pub(super) fn plugin_strings(section: &[u8], names: &Names) -> Option<(String, Option<Vec<u8>>, String)> {
let mut lex = Lexer::new(section);
let mut strings = vec![];
let mut params = vec![];
while let Some(t) = lex.next_token() {
if let Tok::Str(s) | Tok::Hex(s) = t.tok {
if strings.len() < 2 {
strings.push(obj::text(&s));
strings.push(s);
} else {
// Joined before they are text: a string may end inside a character.
let room = MAX_PARAMS.saturating_sub(params.len());
@@ -175,8 +176,8 @@ pub(super) fn plugin_strings(section: &[u8]) -> Option<(String, Option<String>,
}
}
let mut strings = strings.into_iter();
let kind = strings.next()?;
Some((kind, strings.next(), obj::text(&params)))
let kind = names.quiet(&strings.next()?);
Some((kind, strings.next(), names.quiet(&params)))
}
/// The brush manager's order (`params`: its parameters): the kind and name of each brush. Pairs
+334
View File
@@ -47,6 +47,237 @@ pub(super) fn text(bytes: &[u8]) -> String {
}
}
/// The encoding names in the editing data that aren't UTF-8 are read in (layers, objects,
/// artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables
/// and data sets, and data sets' text values). Legacy files store them in the code page of the
/// system that wrote them and don't say which.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NameEncoding {
/// Windows-1252, Latin-1 for its gaps.
#[default]
Windows1252,
/// Mac OS Roman.
Macintosh,
/// Korean: Windows code page 949 (EUC-KR and Unified Hangul Code).
Korean,
/// Japanese: Shift_JIS (Windows code page 932).
ShiftJis,
/// Simplified Chinese: GBK (Windows code page 936).
Gbk,
/// Traditional Chinese: Big5 (Windows code page 950).
Big5,
}
impl NameEncoding {
/// The labels [`NameEncoding::from_label`] reads, one for each encoding.
pub const LABELS: [&str; 6] = ["windows-1252", "macintosh", "windows-949", "shift_jis", "gbk", "big5"];
/// The encoding with label `label` (any case): one of [`Self::LABELS`], or `euc-kr` for
/// [`NameEncoding::Korean`].
pub fn from_label(label: &str) -> Option<Self> {
let label = label.trim().to_ascii_lowercase();
Some(match label.as_str() {
"windows-1252" => Self::Windows1252,
"macintosh" => Self::Macintosh,
"windows-949" | "euc-kr" => Self::Korean,
"shift_jis" => Self::ShiftJis,
"gbk" => Self::Gbk,
"big5" => Self::Big5,
_ => return None,
})
}
/// The encoding's label, as [`Self::LABELS`] gives it.
pub fn label(self) -> &'static str {
match self {
Self::Windows1252 => "windows-1252",
Self::Macintosh => "macintosh",
Self::Korean => "windows-949",
Self::ShiftJis => "shift_jis",
Self::Gbk => "gbk",
Self::Big5 => "big5",
}
}
/// `bytes` as text: UTF-8 as it is, else read in this encoding, with each sequence it doesn't
/// define as U+FFFD (Windows-1252 defines every byte).
fn decode(self, bytes: &[u8]) -> Decoded {
if let Ok(s) = std::str::from_utf8(bytes) {
return Decoded { text: s.to_string(), fallback: false, replaced: false };
}
let other = match self {
Self::Windows1252 => return Decoded { text: bytes.iter().map(|b| cp1252(*b)).collect(), fallback: true, replaced: false },
Self::Macintosh => encoding_rs::MACINTOSH,
Self::Korean => encoding_rs::EUC_KR,
Self::ShiftJis => encoding_rs::SHIFT_JIS,
Self::Gbk => encoding_rs::GBK,
Self::Big5 => encoding_rs::BIG5,
};
let (text, replaced) = other.decode_without_bom_handling(bytes);
Decoded { text: text.into_owned(), fallback: true, replaced }
}
/// [`NameEncoding::decode`] as the text, whether the bytes weren't UTF-8, and whether some
/// weren't valid in the encoding either.
pub(super) fn decoded(self, bytes: &[u8]) -> (String, bool, bool) {
let d = self.decode(bytes);
(d.text, d.fallback, d.replaced)
}
}
/// A name's hash, for counting the names past the notes.
fn hash(name: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
name.hash(&mut h);
h.finish()
}
/// Bytes read as text by [`NameEncoding::decode`].
struct Decoded {
text: String,
/// The bytes weren't UTF-8.
fallback: bool,
/// Some weren't valid in the encoding either, and became U+FFFD.
replaced: bool,
}
/// Most names that weren't UTF-8 each named in a note; the rest are counted in one.
const MAX_NAME_NOTES: usize = 3;
/// Most other names counted (the count stops there).
const MAX_NAMES_COUNTED: usize = 10_000;
/// The names read in a [`NameEncoding`], and the notes on those that weren't UTF-8: one for each
/// name (the first [`MAX_NAME_NOTES`]), then one counting the others (up to
/// [`MAX_NAMES_COUNTED`]).
#[derive(Debug, Default)]
pub struct Names {
pub encoding: NameEncoding,
noted: Vec<(String, bool)>,
/// Hashes of the other names.
more: std::collections::HashSet<u64>,
}
impl Names {
pub fn new(encoding: NameEncoding) -> Self {
Self { encoding, ..Self::default() }
}
/// `bytes` read in the encoding, without a note (a list or a parameter string that repeats
/// names noted where they are defined).
pub fn quiet(&self, bytes: &[u8]) -> String {
self.encoding.decode(bytes).text
}
/// A string's or name's text as a name: a string that isn't UTF-8 read in the encoding,
/// with a note.
pub(super) fn text(&mut self, v: &V) -> Option<String> {
match v {
V::Str(s) => Some(self.bytes(s)),
V::Name(n) => Some(n.clone()),
_ => None,
}
}
/// `bytes` read as a name (see [`Names::text`]).
pub fn bytes(&mut self, bytes: &[u8]) -> String {
let d = self.encoding.decode(bytes);
if d.fallback {
self.note(&d.text, d.replaced);
}
d.text
}
/// The first text value of `o`'s entry `key`, as a name.
pub(super) fn entry(&mut self, o: &Obj, key: &str) -> Option<String> {
let v = o.get(key)?.iter().find(|v| matches!(v, V::Str(_)))?;
self.text(v)
}
/// The name the XML id in `id` (an `AI10_ArtUID`) gives its object ([`xml_name`]): a string that
/// isn't UTF-8 is read in the encoding, with a note on the name.
pub(super) fn xml_id_name(&mut self, id: &Obj) -> Option<String> {
match id.content.iter().find(|v| matches!(v, V::Str(_) | V::Name(_)))? {
V::Str(bytes) => {
let d = self.encoding.decode(bytes);
let name = xml_name(&d.text);
if d.fallback {
self.note(&name, d.replaced);
}
Some(name)
}
v => v.text().map(|t| xml_name(&t)),
}
}
/// A note on `name`, which wasn't UTF-8 (`replaced`: parts of it weren't valid in the encoding
/// either).
pub(super) fn note(&mut self, name: &str, replaced: bool) {
if self.noted.iter().any(|(n, _)| n == name) {
return;
}
if self.noted.len() < MAX_NAME_NOTES {
self.noted.push((name.to_string(), replaced));
} else {
self.count(hash(name));
}
}
fn count(&mut self, h: u64) {
if self.more.len() < MAX_NAMES_COUNTED {
self.more.insert(h);
}
}
/// Take the notes of `other`, a reader's for part of the same data.
pub fn absorb(&mut self, other: Names) {
for (name, replaced) in other.noted {
self.note(&name, replaced);
}
for h in other.more {
self.count(h);
}
}
/// Take the notes of `other` on the names in `used` (names read but then not used, such as the
/// layers of data whose layers aren't used, left out).
pub fn absorb_among(&mut self, other: Names, used: &[&str]) {
for (name, replaced) in other.noted {
if used.contains(&name.as_str()) {
self.note(&name, replaced);
}
}
for n in used {
let h = hash(n);
if other.more.contains(&h) {
self.count(h);
}
}
}
/// The notes on the names that weren't UTF-8.
pub fn notes(&self) -> Vec<String> {
let label = self.encoding.label();
let mut out: Vec<String> = self
.noted
.iter()
.map(|(name, replaced)| {
if *replaced {
format!(
"the name `{name}` isn't UTF-8, and parts of it aren't valid {label} either: open the file with another legacyNameEncoding"
)
} else {
format!("the name `{name}` isn't UTF-8 and was read as {label}: if it looks wrong, open the file with another legacyNameEncoding")
}
})
.collect();
if !self.more.is_empty() {
out.push(format!("more names that aren't UTF-8 were read as {label} ({count})", count = self.more.len()));
}
out
}
}
fn cp1252(b: u8) -> char {
const HIGH: [char; 32] = [
'€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž', '\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—',
@@ -172,4 +403,107 @@ mod tests {
assert_eq!(text(b"caf\xe9 \x80"), "café €");
assert_eq!(text("ü".as_bytes()), "ü");
}
/// The default reads every byte as Windows-1252 does, the five bytes it leaves undefined as the
/// C1 controls of Latin-1, as `text` always has.
#[test]
fn names_default_to_windows_1252_with_latin_1_in_its_gaps() {
let all: Vec<u8> = (0x80..=0xff).collect();
let mut names = Names::default();
assert_eq!(names.bytes(&all), text(&all));
let gaps: String = [0x81u8, 0x8d, 0x8f, 0x90, 0x9d].iter().map(|b| names.bytes(&[*b])).collect();
assert_eq!(gaps, "\u{81}\u{8d}\u{8f}\u{90}\u{9d}");
assert_eq!(names.bytes(b"\x80\x9f"), "€Ÿ");
}
/// A name that is UTF-8 is read as it is in every encoding, without a note.
#[test]
fn utf8_names_need_no_encoding() {
for label in NameEncoding::LABELS {
let mut names = Names::new(NameEncoding::from_label(label).unwrap());
assert_eq!(names.bytes("레이어 1".as_bytes()), "레이어 1");
assert_eq!(names.text(&V::Str(b"Layer 1".to_vec())).as_deref(), Some("Layer 1"));
assert!(names.notes().is_empty(), "{label}");
}
}
/// Each encoding reads the bytes of a name written in it.
#[test]
fn names_in_each_encoding() {
for (label, bytes, want) in [
("windows-1252", &b"Caf\xe9"[..], "Café"),
("macintosh", b"Caf\x8e", "Café"),
("windows-949", b"\xb7\xb9\xc0\xcc\xbe\xee 1", "레이어 1"),
("euc-kr", b"\xb7\xb9\xc0\xcc\xbe\xee 1", "레이어 1"),
("shift_jis", b"\x83\x8c\x83\x43\x83\x84\x81\x5b 1", "レイヤー 1"),
("gbk", b"\xcd\xbc\xb2\xe3 1", "图层 1"),
("big5", b"\xb9\xcf\xbch 1", "圖層 1"),
] {
let mut names = Names::new(NameEncoding::from_label(label).unwrap());
assert_eq!(names.bytes(bytes), want, "{label}");
assert_eq!(
names.notes(),
vec![format!(
"the name `{want}` isn't UTF-8 and was read as {}: if it looks wrong, open the file with another legacyNameEncoding",
names.encoding.label()
)]
);
}
assert_eq!(NameEncoding::from_label(" Windows-949 "), Some(NameEncoding::Korean));
assert_eq!(NameEncoding::from_label("utf-8"), None);
for label in NameEncoding::LABELS {
assert_eq!(NameEncoding::from_label(label).map(NameEncoding::label), Some(label));
}
}
/// The Korean bytes read by default come in as Windows-1252, with a note naming what they
/// became.
#[test]
fn korean_bytes_by_default_come_in_as_windows_1252_with_a_note() {
let mut names = Names::default();
let name = names.bytes(b"\xb7\xb9\xc0\xcc\xbe\xee 1");
assert_eq!(name, "·¹À̾î 1");
assert_eq!(
names.notes(),
vec!["the name `·¹À̾î 1` isn't UTF-8 and was read as windows-1252: if it looks wrong, open the file with another legacyNameEncoding"]
);
}
/// Bytes the encoding doesn't define come in as U+FFFD, and the note says so.
#[test]
fn malformed_names_keep_a_replacement_character() {
let mut names = Names::new(NameEncoding::Korean);
let name = names.bytes(b"\xb7\xb9\xc0 1");
assert!(name.contains('\u{fffd}'), "{name:?}");
assert!(name.starts_with('레'), "{name:?}");
let notes = names.notes();
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("isn't UTF-8, and parts of it aren't valid windows-949 either:"), "{notes:?}");
}
/// The notes name the first names once each, and count the others.
#[test]
fn name_notes_are_capped() {
let mut names = Names::new(NameEncoding::Macintosh);
for i in 0..10u8 {
let bytes = [b'a' + i, 0x8e];
names.bytes(&bytes);
names.bytes(&bytes);
}
let notes = names.notes();
assert_eq!(notes.len(), MAX_NAME_NOTES + 1);
assert!(notes[0].contains("`aé`"), "{notes:?}");
assert_eq!(notes.last().map(String::as_str), Some("more names that aren't UTF-8 were read as macintosh (7)"));
let mut all = Names::new(NameEncoding::Macintosh);
all.absorb(names);
assert_eq!(all.notes(), notes);
// The count stops at its limit, whatever the file holds.
let mut many = Names::new(NameEncoding::Macintosh);
for i in 0..MAX_NAME_NOTES + MAX_NAMES_COUNTED + 50 {
let mut bytes = i.to_string().into_bytes();
bytes.push(0x8e);
many.bytes(&bytes);
}
assert_eq!(many.notes().last().map(String::as_str), Some("more names that aren't UTF-8 were read as macintosh (10000)"));
}
}
+77 -36
View File
@@ -32,7 +32,7 @@ use vectorcraft_color::gradient::{Gradient, GradientGeom, GradientKind, Gradient
use vectorcraft_color::{Color, Paint};
use super::lex::{Lexer, Tok};
use super::obj::V;
use super::obj::{NameEncoding, Names, V};
/// Largest number of stops read in one gradient.
pub(crate) const MAX_STOPS: usize = 256;
@@ -49,8 +49,8 @@ pub(super) struct Named {
}
/// The paint of a colour operator's operands (`op`: its name, lower case or not), with the named
/// colour it uses. `None` when the operands don't fit.
pub(super) fn color_op(op: &str, vals: &[V]) -> Option<(Paint, Option<Named>)> {
/// colour it uses, its name read by `names`. `None` when the operands don't fit.
pub(super) fn color_op_in(op: &str, vals: &[V], names: &mut Names) -> Option<(Paint, Option<Named>)> {
let nums: Vec<f32> = vals.iter().filter_map(V::num).map(|v| v as f32).collect();
let unit = |v: f32| v.clamp(0.0, 1.0);
let last = |n: usize| nums.get(nums.len().checked_sub(n)?..);
@@ -64,9 +64,9 @@ pub(super) fn color_op(op: &str, vals: &[V]) -> Option<(Paint, Option<Named>)> {
let [r, g, b] = last(3)? else { return None };
Some((Paint::solid(Color::rgb(unit(*r), unit(*g), unit(*b))), None))
}
"x" => named(vals, Some(false)),
"xx" => named(vals, None),
"xk" => named(vals, None).map(|(p, n)| (p, n.map(|n| Named { spot: false, ..n }))),
"x" => named(vals, Some(false), names),
"xx" => named(vals, None, names),
"xk" => named(vals, None, names).map(|(p, n)| (p, n.map(|n| Named { spot: false, ..n }))),
"xs" | "xz" => registration(op, vals),
_ => None,
}
@@ -78,14 +78,14 @@ fn is_registration(name: &str) -> bool {
/// `c m y k (name) tint x` or `c m y k [r g b | L a b] (name) tint type Xx` (type 1: RGB, 2: Lab);
/// `rgb` forces RGB or CMYK.
fn named(vals: &[V], rgb: Option<bool>) -> Option<(Paint, Option<Named>)> {
fn named(vals: &[V], rgb: Option<bool>, names: &mut Names) -> Option<(Paint, Option<Named>)> {
let at = vals.iter().rposition(|v| matches!(v, V::Str(_) | V::Name(_)))?;
let name = vals.get(at)?.text()?;
let name = vals.get(at)?;
let before: Vec<f32> = vals.get(..at)?.iter().filter_map(V::num).map(|v| v as f32).collect();
let after: Vec<f32> = vals.get(at + 1..)?.iter().filter_map(V::num).map(|v| v as f32).collect();
let unit = |v: f32| v.clamp(0.0, 1.0);
let tint = 1.0 - unit(*after.first()?);
if is_registration(&name) {
if is_registration(&name.text()?) {
let full = Color::cmyk(1.0, 1.0, 1.0, 1.0);
let paint = Paint::Solid { color: full.tinted(tint), swatch: Some(vectorcraft_color::swatch::REGISTRATION.into()), tint };
return Some((paint, None));
@@ -105,6 +105,7 @@ fn named(vals: &[V], rgb: Option<bool>) -> Option<(Paint, Option<Named>)> {
let [c, m, y, k] = before.get(from..from + 4)? else { return None };
Color::cmyk(unit(*c), unit(*m), unit(*y), unit(*k))
};
let name = names.text(name)?;
let paint = Paint::Solid { color: color.tinted(tint), swatch: Some(name.clone()), tint };
Some((paint, Some(Named { name, color, tint, spot: true })))
}
@@ -130,7 +131,7 @@ fn registration(op: &str, vals: &[V]) -> Option<(Paint, Option<Named>)> {
}
/// The colour of a gradient stop's colour values and style.
fn stop_color(style: f64, comps: &[V]) -> Option<(Color, Option<Named>)> {
fn stop_color(style: f64, comps: &[V], names: &mut Names) -> Option<(Color, Option<Named>)> {
let nums: Vec<f32> = comps.iter().filter_map(V::num).map(|v| v as f32).collect();
let unit = |v: f32| v.clamp(0.0, 1.0);
let tail = |n: usize| nums.get(nums.len().checked_sub(n)?..);
@@ -145,7 +146,7 @@ fn stop_color(style: f64, comps: &[V]) -> Option<(Color, Option<Named>)> {
(Color::rgb(unit(*r), unit(*g), unit(*b)), None)
}
_ => {
let (paint, named) = named(comps, Some(style as i64 == 4))?;
let (paint, named) = named(comps, Some(style as i64 == 4), names)?;
(paint.color()?, named)
}
})
@@ -159,16 +160,16 @@ pub(super) struct GradientDef {
}
impl GradientDef {
/// `(name) type stops Bd`.
pub fn begin(vals: &[V]) -> Option<Self> {
let name = vals.iter().find_map(|v| if let V::Str(_) = v { v.text() } else { None })?;
/// `(name) type stops Bd`, the name read by `names`.
pub fn begin(vals: &[V], names: &mut Names) -> Option<Self> {
let name = vals.iter().find(|v| matches!(v, V::Str(_))).and_then(|v| names.text(v))?;
let nums: Vec<f64> = vals.iter().filter_map(V::num).collect();
let kind = if nums.first().copied() == Some(1.0) { GradientKind::Radial } else { GradientKind::Linear };
Some(Self { name, gradient: Gradient::new(kind, vec![]) })
}
/// A stop (`Bs`).
pub fn stop(&mut self, vals: &[V], spots: &mut Vec<Named>) {
/// A stop (`Bs`), the name of its colour read by `names`.
pub fn stop(&mut self, vals: &[V], spots: &mut Vec<Named>, names: &mut Names) {
if self.gradient.stops.len() >= MAX_STOPS {
return;
}
@@ -179,7 +180,7 @@ impl GradientDef {
let newer = n >= 5 && n.checked_sub(3).and_then(num) == Some(6.0);
let (style_at, opacity) = if newer { (n.checked_sub(5), n.checked_sub(4).and_then(num).unwrap_or(1.0)) } else { (n.checked_sub(3), 1.0) };
let (Some(style_at), Some(style)) = (style_at, style_at.and_then(num)) else { return };
let Some((color, named)) = stop_color(style, vals.get(..style_at).unwrap_or_default()) else { return };
let Some((color, named)) = stop_color(style, vals.get(..style_at).unwrap_or_default(), names) else { return };
let mut stop = GradientStop::new((ramp / 100.0).clamp(0.0, 1.0) as f32, color);
stop.opacity = opacity.clamp(0.0, 1.0) as f32;
stop.midpoint = (mid / 100.0).clamp(0.13, 0.87) as f32;
@@ -225,9 +226,16 @@ pub(super) struct ColorNames {
vals: Vec<V>,
def: Option<GradientDef>,
spots: Vec<Named>,
/// Reads the names found (the reader reads them again, and keeps the notes on them).
decoder: Names,
}
impl ColorNames {
/// The names found to be read in `encoding`.
pub fn new(encoding: NameEncoding) -> Self {
Self { decoder: Names::new(encoding), ..Self::default() }
}
pub fn token(&mut self, tok: Tok<'_>) {
self.take(tok, true);
}
@@ -252,7 +260,7 @@ impl ColorNames {
};
let vals = std::mem::take(&mut self.vals);
match w {
b"Bd" => self.def = GradientDef::begin(&vals),
b"Bd" => self.def = GradientDef::begin(&vals, &mut self.decoder),
b"BD" => {
if let Some((name, _)) = self.def.take().and_then(GradientDef::finish) {
self.gradients.push(name);
@@ -260,18 +268,18 @@ impl ColorNames {
}
b"Bs" => {
if let Some(d) = self.def.as_mut() {
d.stop(&vals, &mut self.spots);
d.stop(&vals, &mut self.spots, &mut self.decoder);
}
}
b"x" | b"X" | b"Xx" | b"XX" | b"Xk" | b"XK" => {
if let Some((_, Some(n))) = std::str::from_utf8(w).ok().and_then(|op| color_op(op, &vals)) {
if let Some((_, Some(n))) = std::str::from_utf8(w).ok().and_then(|op| color_op_in(op, &vals, &mut self.decoder)) {
self.spots.push(n);
}
}
b"@" | b"&" if outer => {
for v in &vals {
if let V::Str(s) = v {
let mut inner = ColorNames::default();
let mut inner = ColorNames::new(self.decoder.encoding);
let mut lex = Lexer::new(s);
while let Some(t) = lex.next_token() {
inner.take(t.tok, false);
@@ -396,10 +404,10 @@ impl Instance {
Self { stroke, length: 1.0, ..Self::default() }
}
/// `flag (name) x y angle length a b c d tx ty Bg`.
pub fn bg(&mut self, vals: &[V]) {
/// `flag (name) x y angle length a b c d tx ty Bg`, the name read by `names`.
pub fn bg(&mut self, vals: &[V], names: &mut Names) {
let Some(at) = vals.iter().rposition(|v| matches!(v, V::Str(_))) else { return };
self.name = vals.get(at).and_then(V::text);
self.name = vals.get(at).and_then(|v| names.text(v));
let n: Vec<f64> = vals.get(at + 1..).unwrap_or_default().iter().filter_map(V::num).collect();
if let [x, y, angle, length, m @ ..] = n.as_slice() {
self.origin = Point::new(*x, *y);
@@ -520,6 +528,35 @@ mod tests {
v.iter().map(|n| V::Num(*n)).collect()
}
fn color_op(op: &str, vals: &[V]) -> Option<(Paint, Option<Named>)> {
color_op_in(op, vals, &mut Names::default())
}
/// A named colour, a gradient and its stop's colour, and the gradient an object names, read in
/// the encoding picked, so that names written alike match.
#[test]
fn colour_and_gradient_names_read_in_the_encoding() {
let mut names = Names::new(super::super::obj::NameEncoding::Korean);
let mut v = nums(&[0.0, 0.5, 1.0, 0.0]);
v.extend([V::Str(b"\xbb\xa1\xb0\xad".to_vec()), V::Num(0.0)]);
let (_, named) = color_op_in("x", &v, &mut names).unwrap();
assert_eq!(named.unwrap().name, "빨강");
let mut d = GradientDef::begin(&[V::Str(b"\xb1\xd7\xb6\xf3".to_vec()), V::Num(0.0)], &mut names).unwrap();
let mut stop = nums(&[0.0, 0.5, 1.0, 0.0]);
stop.extend([V::Str(b"\xbb\xa1\xb0\xad".to_vec()), V::Num(0.0), V::Num(3.0), V::Num(50.0), V::Num(0.0)]);
let mut spots = vec![];
d.stop(&stop, &mut spots, &mut names);
assert_eq!(spots.first().map(|s| s.name.as_str()), Some("빨강"));
let (name, g) = d.finish().unwrap();
assert_eq!(name, "그라");
let mut i = Instance::begin(&[]);
let mut bg = vec![V::Num(1.0), V::Str(b"\xb1\xd7\xb6\xf3".to_vec())];
bg.extend(nums(&[0.0, 0.0, 0.0, 10.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
i.bg(&bg, &mut names);
assert!(i.paint(&HashMap::from([(name, g)]), &ShownNames::default(), Affine::IDENTITY).is_some());
assert_eq!(names.notes().len(), 2);
}
#[test]
fn registration_paints_with_the_registration_swatch_at_its_tint() {
let mut v = nums(&[0.75, 0.68, 0.67, 0.9, 0.0, 0.0, 0.0]);
@@ -608,10 +645,11 @@ mod tests {
#[test]
fn gradient_definition_and_instance() {
let mut d = GradientDef::begin(&[V::Str(b"G".to_vec()), V::Num(1.0), V::Num(2.0)]).unwrap();
let names = &mut Names::default();
let mut d = GradientDef::begin(&[V::Str(b"G".to_vec()), V::Num(1.0), V::Num(2.0)], names).unwrap();
let mut spots = vec![];
d.stop(&nums(&[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 2.0, 0.5, 6.0, 30.0, 100.0]), &mut spots);
d.stop(&nums(&[0.81, 0.0, 1.0, 6.0, 50.0, 0.0]), &mut spots);
d.stop(&nums(&[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 2.0, 0.5, 6.0, 30.0, 100.0]), &mut spots, names);
d.stop(&nums(&[0.81, 0.0, 1.0, 6.0, 50.0, 0.0]), &mut spots, names);
let (name, g) = d.finish().unwrap();
assert_eq!(name, "G");
assert_eq!(g.kind, GradientKind::Radial);
@@ -622,7 +660,7 @@ mod tests {
let mut i = Instance::begin(&[]);
let mut bg = vec![V::Num(1.0), V::Str(b"G".to_vec())];
bg.extend(nums(&[100.0, 100.0, 0.0, 50.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
i.bg(&bg);
i.bg(&bg, names);
i.bm(&nums(&[50.0, 0.0, 0.0, -50.0, 100.0, 100.0]));
let shown = ShownNames::default();
let Some(Paint::Gradient(gp)) = i.paint(&defs, &shown, Affine::IDENTITY) else { panic!() };
@@ -634,7 +672,7 @@ mod tests {
assert!(i.paint(&HashMap::new(), &shown, Affine::IDENTITY).is_none());
// Newer files give the matrix with `Xm`; the `Bm`s after it are bands of a cached ramp.
let mut i = Instance::begin(&[]);
i.bg(&bg);
i.bg(&bg, names);
i.xm(&nums(&[40.0, 0.0, 0.0, -40.0, 10.0, 10.0]));
i.bm(&nums(&[5.0, 0.0, 0.0, -40.0, 30.0, 10.0]));
let Some(Paint::Gradient(gp)) = i.paint(&defs, &shown, Affine::IDENTITY) else { panic!() };
@@ -679,11 +717,12 @@ mod tests {
#[test]
fn gradient_stops_beyond_the_cap_are_ignored() {
let mut d = GradientDef::begin(&[V::Str(b"H".to_vec()), V::Num(0.0)]).unwrap();
let names = &mut Names::default();
let mut d = GradientDef::begin(&[V::Str(b"H".to_vec()), V::Num(0.0)], names).unwrap();
let mut spots = vec![];
for i in 0..257 {
let ramp = i as f64 / 256.0 * 100.0;
d.stop(&nums(&[0.2, 0.4, 0.6, 0.0, 1.0, 1.0, 6.0, 50.0, ramp]), &mut spots);
d.stop(&nums(&[0.2, 0.4, 0.6, 0.0, 1.0, 1.0, 6.0, 50.0, ramp]), &mut spots, names);
}
let (_, g) = d.finish().unwrap();
assert_eq!(g.stops.len(), MAX_STOPS);
@@ -694,9 +733,10 @@ mod tests {
#[test]
fn stops_at_one_ramp_point_keep_their_sides() {
for (kind, listed) in [(0.0, [0.75, 0.25]), (1.0, [0.25, 0.75])] {
let mut d = GradientDef::begin(&[V::Str(b"E".to_vec()), V::Num(kind), V::Num(2.0)]).unwrap();
let names = &mut Names::default();
let mut d = GradientDef::begin(&[V::Str(b"E".to_vec()), V::Num(kind), V::Num(2.0)], names).unwrap();
for (gray, mid) in listed.into_iter().zip([40.0, 70.0]) {
d.stop(&nums(&[gray, 0.0, 1.0, 6.0, mid, 30.0]), &mut vec![]);
d.stop(&nums(&[gray, 0.0, 1.0, 6.0, mid, 30.0]), &mut vec![], names);
}
let (_, g) = d.finish().unwrap();
let lightness: Vec<f32> = g.stops.iter().map(|s| (s.color.to_rgb()[0] * 100.0).round() / 100.0).collect();
@@ -711,16 +751,17 @@ mod tests {
/// art space, `Xm` for the whole ramp and a `Bm` for each pair of stops.
#[test]
fn a_linear_gradient_runs_its_whole_ramp_not_its_last_part() {
let mut d = GradientDef::begin(&[V::Str(b"L".to_vec()), V::Num(0.0), V::Num(3.0)]).unwrap();
let names = &mut Names::default();
let mut d = GradientDef::begin(&[V::Str(b"L".to_vec()), V::Num(0.0), V::Num(3.0)], names).unwrap();
for ramp in [100.0, 60.0, 20.0] {
d.stop(&nums(&[0.2, 0.4, 0.6, 0.0, 1.0, 1.0, 6.0, 50.0, ramp]), &mut vec![]);
d.stop(&nums(&[0.2, 0.4, 0.6, 0.0, 1.0, 1.0, 6.0, 50.0, ramp]), &mut vec![], names);
}
let defs = HashMap::from([d.finish().unwrap()]);
let instance = |xm: bool| {
let mut i = Instance::begin(&[]);
let mut bg = vec![V::Num(1.0), V::Str(b"L".to_vec())];
bg.extend(nums(&[0.3, -0.2, -90.0, 0.5, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]));
i.bg(&bg);
i.bg(&bg, &mut Names::default());
if xm {
i.xm(&nums(&[0.0, -200.0, -30.0, 0.0, 10.0, 300.0]));
}
+28 -12
View File
@@ -26,7 +26,7 @@ use vectorcraft_color::Color;
use vectorcraft_doc::swatches::color_name;
use super::lex::{Lexer, Tok};
use super::obj::V;
use super::obj::{Names, V};
use super::paint::{self, Named};
/// Largest number of swatches read from one palette.
@@ -73,8 +73,9 @@ impl Palette {
}
}
/// The palette of `data`: what follows `%AI5_BeginPalette`, up to its end.
pub(super) fn palette(data: &[u8]) -> Palette {
/// The palette of `data`: what follows `%AI5_BeginPalette`, up to its end, its names read by
/// `names`.
pub(super) fn palette(data: &[u8], names: &mut Names) -> Palette {
let mut lex = Lexer::new(data);
let mut out = Palette::default();
let mut vals: Vec<V> = Vec::new();
@@ -125,15 +126,15 @@ pub(super) fn palette(data: &[u8]) -> Palette {
cell = None;
}
"Bg" if in_gradient => {
if let Some(name) = last_text(&vals) {
if let Some(name) = last_text(&vals, names) {
cell = Some(Entry { cell: Cell::Gradient(name.clone()), name });
}
}
"BB" => in_gradient = false,
"p" => cell = first_text(&vals).map(|name| Entry { cell: Cell::Pattern(name.clone()), name }),
"p" => cell = first_text(&vals, names).map(|name| Entry { cell: Cell::Pattern(name.clone()), name }),
"Xs" | "Xz" | "XS" | "XZ" => cell = None,
"g" | "k" | "x" | "Xa" | "Xx" | "Xk" => {
cell = paint::color_op(w, &vals).and_then(|(p, named)| match named {
cell = paint::color_op_in(w, &vals, names).and_then(|(p, named)| match named {
Some(Named { name, color, spot, .. }) => Some(Entry { name, cell: Cell::Color { color, global: true, spot } }),
None => p.color().map(|color| Entry { name: color_name(color), cell: Cell::Color { color, global: false, spot: false } }),
});
@@ -141,7 +142,7 @@ pub(super) fn palette(data: &[u8]) -> Palette {
"Pg" => {
cell = None;
// Capped as swatches are: a file of many `Pg` would make as many empty groups.
if let Some(name) = first_text(&vals)
if let Some(name) = first_text(&vals, names)
&& out.groups.len() < MAX_SWATCHES
{
out.groups.push((name, Vec::new()));
@@ -150,7 +151,7 @@ pub(super) fn palette(data: &[u8]) -> Palette {
"Pc" => {
// The name before `Pc`, or the one the paint gives; `[Registration]` and the other
// built-in swatches every document has are left out.
let name = last_text(&vals);
let name = last_text(&vals, names);
if let Some(mut e) = cell.take()
&& !name.as_ref().is_some_and(|n| n.starts_with('['))
&& count < MAX_SWATCHES
@@ -181,12 +182,12 @@ fn push(vals: &mut Vec<V>, v: V) {
}
}
fn first_text(vals: &[V]) -> Option<String> {
vals.iter().find(|v| matches!(v, V::Str(_))).and_then(V::text)
fn first_text(vals: &[V], names: &mut Names) -> Option<String> {
vals.iter().find(|v| matches!(v, V::Str(_))).and_then(|v| names.text(v))
}
fn last_text(vals: &[V]) -> Option<String> {
vals.iter().rev().find(|v| matches!(v, V::Str(_))).and_then(V::text)
fn last_text(vals: &[V], names: &mut Names) -> Option<String> {
vals.iter().rev().find(|v| matches!(v, V::Str(_))).and_then(|v| names.text(v))
}
#[cfg(test)]
@@ -197,6 +198,21 @@ mod tests {
Entry { name: name.into(), cell: Cell::Color { color, global, spot } }
}
fn palette(data: &[u8]) -> Palette {
super::palette(data, &mut Names::default())
}
/// Swatch, group and spot colour names that aren't UTF-8 are read in the encoding picked.
#[test]
fn palette_names_read_in_the_encoding() {
let mut names = Names::new(super::super::obj::NameEncoding::ShiftJis);
// 赤 (red) and 色 (color) in Shift_JIS.
let p = super::palette(b"0 0 Pb\n0 (\x90\x46) 1 Pg\n0 1 1 0 (\x90\xd4) 0 x\n(\x90\xd4)\nPc\nPB\n", &mut names);
assert_eq!(p.groups.first().map(|(n, s)| (n.as_str(), s.len())), Some(("色", 1)));
assert_eq!(p.groups.first().and_then(|(_, s)| s.first()), Some(&color("赤", Color::cmyk(0.0, 1.0, 1.0, 0.0), true, true)));
assert_eq!(names.notes().len(), 2);
}
#[test]
fn a_palette_gives_its_swatches_in_order() {
let p = palette(
+39 -24
View File
@@ -125,7 +125,7 @@ use vectorcraft_geom::{AnchorKind, FillRule, PathData};
use super::super::ate::CANVAS_CENTRE;
use super::super::graphics::HAIRLINE;
use super::lex::{Lexer, Tok};
use super::obj::{self, Obj, V};
use super::obj::{self, NameEncoding, Obj, V};
use super::paint::{self, Global, GradientDef, Instance, Named, ShownNames};
use crate::ps;
@@ -238,22 +238,30 @@ pub(super) fn remember_xml_id(xml_ids: &mut HashMap<String, Option<NodeId>>, byt
}
}
/// [`read_in`], names that aren't UTF-8 read as Windows-1252.
#[cfg(test)]
pub fn read(data: &[u8], large_canvas: bool) -> Result<Structure, String> {
read_in(data, large_canvas, NameEncoding::default())
}
/// Read the structure of the editing data `data`, applying the file's `%AI24_LargeCanvasScale` only
/// when `large_canvas` is set: an EPS's page is drawn at the full size, but a `.ai`'s PDF part may
/// keep the reduced one, which the PDF import reads as it is (#2031).
pub fn read(data: &[u8], large_canvas: bool) -> Result<Structure, String> {
read_with(data, large_canvas, false)
/// keep the reduced one, which the PDF import reads as it is (#2031). Names that aren't UTF-8
/// (layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes,
/// symbols, variables and data sets) are read in `names`, each with a warning.
pub fn read_in(data: &[u8], large_canvas: bool, names: NameEncoding) -> Result<Structure, String> {
read_with(data, large_canvas, false, names)
}
/// [`read`] for a file whose page art replaces the objects the reader doesn't read (see
/// [`read_in`] for a file whose page art replaces the objects the reader doesn't read (see
/// [`Reader::unread_box`]): an image past the hard limits ([`raster::Limits`]) is then such an
/// object, where [`read`] leaves it out with a note.
pub(crate) fn read_over_page(data: &[u8], large_canvas: bool) -> Result<Structure, String> {
read_with(data, large_canvas, true)
/// object, where [`read_in`] leaves it out with a note.
pub(crate) fn read_over_page(data: &[u8], large_canvas: bool, names: NameEncoding) -> Result<Structure, String> {
read_with(data, large_canvas, true, names)
}
fn read_with(data: &[u8], large_canvas: bool, page_art: bool) -> Result<Structure, String> {
let mut r = Reader::with_names(data);
fn read_with(data: &[u8], large_canvas: bool, page_art: bool, names: NameEncoding) -> Result<Structure, String> {
let mut r = Reader::with_names(data, names);
r.large_canvas = large_canvas.then_some(1.0);
r.page_art = page_art;
r.run()?;
@@ -263,17 +271,18 @@ fn read_with(data: &[u8], large_canvas: bool, page_art: bool) -> Result<Structur
/// How many objects [`read`] counts against [`MAX_NODES`] in the editing data `data`.
#[cfg(test)]
pub(crate) fn objects_read(data: &[u8]) -> Result<usize, String> {
let mut r = Reader::with_names(data);
let mut r = Reader::with_names(data, NameEncoding::default());
r.run()?;
Ok(r.nodes)
}
/// [`read`] for editing data kept apart from the program `ps` it came with (an EPS's private
/// data): the program's header gives the author and the custom colors the editing data's header
/// doesn't. `page_art`: as [`read_over_page`] reads a file.
pub fn read_beside(data: &[u8], large_canvas: bool, ps: &[u8], page_art: bool) -> Result<Structure, String> {
let header = Reader::header_of(ps);
let mut r = Reader::with_names(data);
/// doesn't. `page_art`: as [`read_over_page`] reads a file. `names`: the encoding of names that
/// aren't UTF-8.
pub fn read_beside(data: &[u8], large_canvas: bool, ps: &[u8], page_art: bool, names: NameEncoding) -> Result<Structure, String> {
let header = Reader::header_of(ps, names);
let mut r = Reader::with_names(data, names);
r.large_canvas = large_canvas.then_some(1.0);
r.page_art = page_art;
// The program's custom colors have swatches of their names, which no gradient or pattern takes.
@@ -292,8 +301,8 @@ pub fn read_beside(data: &[u8], large_canvas: bool, ps: &[u8], page_art: bool) -
/// and patterns. Names come only from what the reader reads: not from the alternates of versioned
/// content, the prolog, resources, sections it skips (such as symbols and the text document) or
/// what follows the trailer. The palette the reader keeps is the last one outside those and the
/// sections it reads on their own.
fn swatch_names(data: &[u8]) -> (ShownNames, Option<&[u8]>) {
/// sections it reads on their own. Names that aren't UTF-8 are read in `encoding`.
fn swatch_names(data: &[u8], encoding: NameEncoding) -> (ShownNames, Option<&[u8]>) {
/// The sections the reader reads on their own whose definitions and colors it keeps.
const READ_APART: &[&str] = &["BeginPattern", "BeginBrushPattern", "BeginPluginObject", "BeginArtStyles", "BeginArtStyleList"];
/// Whether the marker `m` ends what began with `begin` and ends with `end`, `depth` of its kind
@@ -311,7 +320,9 @@ fn swatch_names(data: &[u8]) -> (ShownNames, Option<&[u8]>) {
}
let mut names = ShownNames::default();
names.reserve(vectorcraft_color::swatch::REGISTRATION);
let mut colors = paint::ColorNames::default();
// The reader reads these names again, and keeps the notes on them.
let mut decoder = obj::Names::new(encoding);
let mut colors = paint::ColorNames::new(encoding);
let mut lex = Lexer::new(data);
// What the reader skips wherever it is (the marker of one of its kind nested in it, its end
// marker, how many are open inside it, and where reading goes on when it doesn't end), the
@@ -386,7 +397,7 @@ fn swatch_names(data: &[u8]) -> (ShownNames, Option<&[u8]>) {
// A palette's names are those of the palette kept, as the palette reads them.
_ if skip.is_some() || palette_at.is_some() || section.is_some_and(|s| !s.3) => continue,
Tok::Str(s) | Tok::Hex(s) if std::mem::take(&mut head) => {
let text = obj::text(s);
let text = decoder.bytes(s);
if !text.contains('\n') {
names.reserve(&text);
}
@@ -396,7 +407,7 @@ fn swatch_names(data: &[u8]) -> (ShownNames, Option<&[u8]>) {
colors.token(t.tok);
}
colors.gradients.iter().filter(|n| !n.contains('\n')).for_each(|n| names.reserve(n));
let palette = palette.map(super::palette::palette).unwrap_or_default();
let palette = palette.map(|p| super::palette::palette(p, &mut decoder)).unwrap_or_default();
if palette.is_empty() {
for mode in [ColorMode::Rgb, ColorMode::Cmyk] {
let (swatches, groups) = vectorcraft_color::default_swatches(mode.model());
@@ -631,6 +642,8 @@ struct Reader<'a> {
/// The legacy text object being read (`To` … `TO`), and the modal type attributes.
text: Option<legacy_text::LegacyText>,
type_state: legacy_text::TypeState,
/// How names that aren't UTF-8 are read, and the notes on them.
names: obj::Names,
/// The file has brush objects (the brush manager's order or a brush).
brush_objects: bool,
/// The brush manager's order.
@@ -668,13 +681,14 @@ pub(crate) fn is_look_slot(name: Option<&str>) -> bool {
impl<'a> Reader<'a> {
/// A reader of the editing data `data` as a whole, with the names its gradients and patterns
/// get in the document and its art styles found first ([`swatch_names`]): the symbols defined
/// before the art styles section use them too.
fn with_names(data: &'a [u8]) -> Self {
/// before the art styles section use them too. Names that aren't UTF-8 are read in `encoding`.
fn with_names(data: &'a [u8], encoding: NameEncoding) -> Self {
let mut r = Self::new(data);
let (names, styles) = swatch_names(data);
r.names = obj::Names::new(encoding);
let (names, styles) = swatch_names(data, encoding);
r.global_names = names;
if let Some(section) = styles {
r.styles = super::style::art_styles(section);
r.styles = super::style::art_styles_in(section, &mut r.names);
}
r
}
@@ -794,6 +808,7 @@ impl<'a> Reader<'a> {
v7_patterns: HashSet::new(),
text: None,
type_state: legacy_text::TypeState::default(),
names: obj::Names::default(),
brush_objects: false,
brush_order: None,
brush_drafts: Vec::new(),
+1 -1
View File
@@ -640,7 +640,7 @@ impl<'a> Reader<'a> {
/// comes in as the page draws it, within the symbol's box placed by the matrix when the box is
/// known.
fn symbol_instance(&mut self, o: &Obj) -> Result<(), String> {
let name = o.text("SymbolRef");
let name = self.names.entry(o, "SymbolRef");
let affine = |n: &[f64]| match n {
[a, b, c, d, e, f] if [a, b, c, d, e, f].iter().all(|v| v.is_finite()) => Some(super::Affine::new([*a, *b, *c, *d, *e, *f])),
_ => None,
+33 -14
View File
@@ -123,7 +123,7 @@ impl<'a> Reader<'a> {
// GUARDS: a definition's art takes the file's art styles and hands them back, so a
// section inside it would replace the file's own.
if self.subreader_depth == 0 {
self.styles = crate::import::ai::style::art_styles(section);
self.styles = crate::import::ai::style::art_styles_in(section, &mut self.names);
}
return Ok(());
}
@@ -134,7 +134,7 @@ impl<'a> Reader<'a> {
}
if m == "BeginPalette" {
let section = self.section("EndPalette")?;
self.palette = crate::import::ai::palette::palette(section);
self.palette = crate::import::ai::palette::palette(section, &mut self.names);
return Ok(());
}
if m == "BeginEncoding" {
@@ -309,7 +309,7 @@ impl<'a> Reader<'a> {
return;
}
let Some(open) = v.iter().position(|&b| b == b'(') else { return };
let (Some(head), Some(name)) = (v.get(..open), v.get(open..).and_then(ps_string)) else { return };
let (Some(head), Some(name)) = (v.get(..open), v.get(open..).and_then(ps_bytes)) else { return };
// One more than a color has, so that too many are seen.
let parts: Vec<Option<f32>> = head
.split(u8::is_ascii_whitespace)
@@ -322,6 +322,7 @@ impl<'a> Reader<'a> {
[Some(r), Some(g), Some(b)] if !cmyk => vectorcraft_color::Color::rgb(*r, *g, *b),
_ => return,
};
let name = self.names.bytes(&name);
if !name.trim().is_empty() && !self.custom_colors.iter().any(|n| n.name == name) {
// A gradient or pattern defined after it does not take its swatch's name.
self.global_names.reserve(&name);
@@ -378,6 +379,7 @@ impl<'a> Reader<'a> {
Legacy::Yes(def) => return self.define_legacy_pattern(&def),
}
let mut sub = Reader::new(section);
sub.names = super::obj::Names::new(self.names.encoding);
sub.subreader_depth = self.subreader_depth + 1;
sub.pattern = Some(PatternHead::default());
// The gradients and art styles defined so far and the names given, lent (and the gradients
@@ -392,6 +394,7 @@ impl<'a> Reader<'a> {
self.take_back_budgets(&mut sub);
self.nodes = sub.nodes;
self.gradients = std::mem::take(&mut sub.gradients);
self.names.absorb(std::mem::take(&mut sub.names));
self.global_names = std::mem::take(&mut sub.global_names);
self.styles = std::mem::take(&mut sub.styles);
// Unread art in the definition, hidden or not, leaves the tile incomplete.
@@ -409,8 +412,9 @@ impl<'a> Reader<'a> {
/// tile's box (`_ &`). Each layer starts from the state the definition starts with.
fn define_legacy_pattern(&mut self, def: &LegacyPattern) {
let mut sub = Reader::new(b"");
sub.names = super::obj::Names::new(self.names.encoding);
sub.subreader_depth = self.subreader_depth + 1;
sub.pattern = Some(PatternHead { taken: true, name: def.name.clone(), tile: Some(def.tile) });
sub.pattern = Some(PatternHead { taken: true, name: self.names.bytes(&def.name), tile: Some(def.tile) });
sub.gradients = std::mem::take(&mut self.gradients);
sub.global_names = std::mem::take(&mut self.global_names);
sub.styles = std::mem::take(&mut self.styles);
@@ -429,6 +433,7 @@ impl<'a> Reader<'a> {
self.gradients = std::mem::take(&mut sub.gradients);
self.global_names = std::mem::take(&mut sub.global_names);
self.styles = std::mem::take(&mut sub.styles);
self.names.absorb(std::mem::take(&mut sub.names));
let whole = read.is_ok()
&& sub.unsupported.is_empty()
&& sub.unknown.is_empty()
@@ -569,10 +574,11 @@ impl<'a> Reader<'a> {
return;
}
let name = match Lexer::new(section).next_token().map(|t| t.tok) {
Some(Tok::Str(bytes)) => obj::text(&bytes),
Some(Tok::Str(bytes)) => self.names.bytes(&bytes),
_ => return,
};
let mut sub = Reader::new(section);
sub.names = super::obj::Names::new(self.names.encoding);
sub.subreader_depth = self.subreader_depth + 1;
sub.symbol = Some(SymbolHead::default());
sub.template = self.template;
@@ -591,6 +597,7 @@ impl<'a> Reader<'a> {
self.global_names = std::mem::take(&mut sub.global_names);
self.styles = std::mem::take(&mut sub.styles);
self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles);
self.names.absorb(std::mem::take(&mut sub.names));
// Art stopped by a trailer, or with an array, type, image, placed file, gradient mesh or
// gradient still open at the end (as [`Reader::run_string`] checks), isn't whole.
let open = sub.done
@@ -709,7 +716,7 @@ impl<'a> Reader<'a> {
if names.len() >= MAX_LISTED {
break;
}
names.push(obj::text(&bytes));
names.push(self.names.quiet(&bytes));
}
}
self.symbol_list = Some(names);
@@ -719,7 +726,7 @@ impl<'a> Reader<'a> {
/// order or a brush ([`brush`]); other objects are left alone. A brush without a name is counted
/// as not read.
fn plugin_object(&mut self, section: &[u8]) {
let Some((kind, name, params)) = brush::plugin_strings(section) else { return };
let Some((kind, name, params)) = brush::plugin_strings(section, &self.names) else { return };
if kind == brush::MANAGER {
if name.is_some() {
self.brush_objects = true;
@@ -737,8 +744,12 @@ impl<'a> Reader<'a> {
self.brushes_unread += 1;
return;
}
match brush::parse_tool_object(tool, &name, &params) {
Ok(d) => self.brush_drafts.push(d),
match brush::parse_tool_object(tool, &self.names.quiet(&name), &params) {
Ok(d) => {
// Only the name of a brush that is read gets a note.
self.names.bytes(&name);
self.brush_drafts.push(d);
}
Err(_) => self.brushes_unread += 1,
}
}
@@ -756,8 +767,9 @@ impl<'a> Reader<'a> {
self.brush_art_sections += 1;
let mut lex = Lexer::new(section);
let Some(Tok::Str(name) | Tok::Hex(name)) = lex.next_token().map(|t| t.tok) else { return };
let name = obj::text(&name);
let name = self.names.bytes(&name);
let mut sub = Reader::new(lex.slice(lex.offset(), section.len()));
sub.names = obj::Names::new(self.names.encoding);
// In a space of its own (y down), with no head to take.
sub.pattern = Some(PatternHead { taken: true, ..PatternHead::default() });
sub.subreader_depth = self.subreader_depth + 1;
@@ -779,6 +791,7 @@ impl<'a> Reader<'a> {
self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles);
self.v7_patterns = std::mem::take(&mut sub.v7_patterns);
self.global_names = std::mem::take(&mut sub.global_names);
self.names.absorb(std::mem::take(&mut sub.names));
// Images aren't kept: the document's images don't count a brush's art among their users. Art
// read with a note (something left out of it) isn't kept either.
let whole = read.is_ok()
@@ -834,7 +847,8 @@ impl<'a> Reader<'a> {
head.taken = true;
let Some(at) = vals.iter().position(|v| matches!(v, V::Str(_))) else { return vals };
let tile = Self::nums(vals.get(at + 1..at + 5).unwrap_or_default());
let ([x0, y0, x1, y1], Some(name)) = (tile.as_slice(), vals.get(at).and_then(V::text)) else { return vals };
let [x0, y0, x1, y1] = tile.as_slice() else { return vals };
let Some(name) = vals.get(at).and_then(|v| self.names.text(v)) else { return vals };
head.name = name;
head.tile = Some(Rect::new(*x0, *y0, *x1, *y1));
vals.split_off(at + 5)
@@ -853,7 +867,7 @@ const MAX_LAYERS: usize = 65_536;
/// A pattern's definition in the version 7 form: its head, then a list of layers painted in order,
/// the first the lowest.
struct LegacyPattern {
name: String,
name: Vec<u8>,
/// The tile in the pattern's space (y up).
tile: Rect,
layers: Vec<LegacyLayer>,
@@ -892,7 +906,7 @@ fn legacy_pattern(section: &[u8]) -> Legacy {
let mut lex = super::Lexer::new(section);
let mut next = || next_operand(&mut lex).ok().flatten().map(|t| (t.tok, t.hidden));
let name = match next() {
Some((Tok::Str(s), _)) => super::obj::text(&s),
Some((Tok::Str(s), _)) => s,
_ => return Legacy::No,
};
let mut tile = [0.0; 4];
@@ -961,6 +975,11 @@ const MAX_STRING: usize = 4096;
/// The PostScript string `v` starts with (after spaces), its escapes read, when it ends on the line
/// and holds at most [`MAX_STRING`] bytes.
fn ps_string(v: &[u8]) -> Option<String> {
ps_bytes(v).map(|bytes| obj::text(&bytes))
}
/// [`ps_string`] as the string's bytes.
fn ps_bytes(v: &[u8]) -> Option<Vec<u8>> {
let mut bytes = v.trim_ascii_start().iter().copied().peekable();
if bytes.next()? != b'(' {
return None;
@@ -997,7 +1016,7 @@ fn ps_string(v: &[u8]) -> Option<String> {
out.push(b);
}
b')' => {
let Some(d) = depth.checked_sub(1) else { return Some(super::obj::text(&out)) };
let Some(d) = depth.checked_sub(1) else { return Some(out) };
depth = d;
out.push(b);
}
+167 -37
View File
@@ -7,6 +7,7 @@ use super::{
Affine, Arc, Artboard, CANVAS_CENTRE, ColorMode, Document, Global, HashMap, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect,
Structure, Swatch, Unit, V, obj,
};
use crate::import::ai::NameEncoding;
use vectorcraft_doc::{DataSet, DataValue, GraphicStyle, Guide, ImageBlob, PatternDef, Symbol, TextWrap, Variable, VariableKind, Variables};
/// `%AI5_RulerUnits` → [`Unit`] (Illustrator 7 spec table 3; centimeters is 4; pixels is 6 in later files).
@@ -141,21 +142,31 @@ pub(crate) const LOOK_SLOT: &str = "\u{0}text:look";
/// The artboards (names, and rects in art space) of the editing data `data` that [`read`] can't
/// read as a whole, as far as it gets: where to put the pages of its PDF part instead, and what to
/// call them (#1068); and the index among them of the active artboard (`CropAreaActive`).
pub fn artboards(data: &[u8]) -> (Vec<(String, Rect)>, Option<usize>) {
let found = artboards_read(data);
/// call them (#1068); and the index among them of the active artboard (`CropAreaActive`). `names`
/// reads their names and keeps the notes on them.
pub fn artboards(data: &[u8], names: &mut obj::Names) -> (Vec<(String, Rect)>, Option<usize>) {
let mut from_start = obj::Names::new(names.encoding);
let found = artboards_read(data, &mut from_start);
if !found.0.is_empty() && found.1.is_some() {
names.absorb(from_start);
return found;
}
// Reading can stop before the artboards (art kept in the document's data comes first), or
// between them and the active artboard's entry: read their array on its own.
let Some((boards, active)) = artboard_array_read(data) else { return found };
let mut from_array = obj::Names::new(names.encoding);
let Some((boards, active)) = artboard_array_read(data, &mut from_array) else {
names.absorb(from_start);
return found;
};
if found.0.is_empty() {
names.absorb(from_array);
(boards, active)
} else if boards == found.0 {
// The same array: its names and rects read alike.
names.absorb(from_start);
(found.0, active)
} else {
names.absorb(from_start);
found
}
}
@@ -163,7 +174,7 @@ pub fn artboards(data: &[u8]) -> (Vec<(String, Rect)>, Option<usize>) {
/// The index of the active artboard (`CropAreaActive`) in the `ArtboardArray` of the editing data
/// `data`, as [`artboards`] reads it, from that array and the entry beside it alone.
pub fn active_artboard(data: &[u8]) -> Option<usize> {
artboard_array_read(data)?.1
artboard_array_read(data, &mut obj::Names::default())?.1
}
/// Artboards as [`artboards`] gives them: names and rects in art space, and the active one's index.
@@ -171,7 +182,7 @@ type ArtboardsRead = (Vec<(String, Rect)>, Option<usize>);
/// The `ArtboardArray` entry of the editing data `data` ([`artboard_array`]), with the
/// `CropAreaActive` entry beside it, read on their own as [`artboards_read`] reads them.
fn artboard_array_read(data: &[u8]) -> Option<ArtboardsRead> {
fn artboard_array_read(data: &[u8], names: &mut obj::Names) -> Option<ArtboardsRead> {
let (array, active) = artboard_array(data)?;
let mut alone = b"%_/Document :\n%_/Dictionary :\n".to_vec();
alone.extend_from_slice(array);
@@ -180,7 +191,7 @@ fn artboard_array_read(data: &[u8]) -> Option<ArtboardsRead> {
alone.extend_from_slice(active);
}
alone.extend_from_slice(b"\n%_; /NotRecorded ,\n%_;\n");
Some(artboards_read(&alone))
Some(artboards_read(&alone, names))
}
/// The key that ends the `ArtboardArray` entry of the editing data.
@@ -278,6 +289,26 @@ fn beside(mut defined: Vec<PatternDef>, have: &[PatternDef]) -> (Vec<PatternDef>
(defined, renamed)
}
/// The names of the objects in `art` and what they hold, masks included.
fn art_names<'a>(art: impl IntoIterator<Item = &'a Node>) -> Vec<&'a str> {
let mut stack: Vec<&Node> = art.into_iter().collect();
let mut names = vec![];
while let Some(n) = stack.pop() {
stack.extend(n.children().into_iter().flatten().chain(n.extras().mask.as_ref().map(|m| &m.art)).map(|c| &**c));
names.extend(n.name.as_deref());
}
names
}
/// The names read for the patterns `added` that the patterns don't show as their own: those
/// `renamed` replaced, and the names of the objects of their art.
fn pattern_names_read<'a>(added: &'a [PatternDef], renamed: &'a std::collections::BTreeMap<String, String>) -> Vec<&'a str> {
let shown: std::collections::HashSet<&str> = added.iter().map(|p| p.name.as_str()).collect();
let mut names: Vec<&str> = renamed.iter().filter(|(_, new)| shown.contains(new.as_str())).map(|(old, _)| old.as_str()).collect();
names.extend(art_names(added.iter().flat_map(|p| p.art.iter().map(|a| &**a))));
names
}
/// `n` and what it holds painting with the patterns `renamed` renames (old to new) by their new names.
fn repoint(n: &mut Node, renamed: &std::collections::BTreeMap<String, String>) {
for p in vectorcraft_doc::swatches::node_paints_mut(n) {
@@ -301,9 +332,10 @@ fn repoint(n: &mut Node, renamed: &std::collections::BTreeMap<String, String>) {
/// layers aren't read: the swatches its PDF part has are the defaults (#4036). They come as
/// [`read`] makes them, with pattern swatches only for the patterns in `patterns` and those the
/// editing data defines, which are named apart from `patterns` ([`beside`]); `None` when the
/// palette is empty or reading stops before it.
pub fn palette(data: &[u8], patterns: &[PatternDef]) -> Option<PaletteSwatches> {
let mut r = Reader::with_names(data);
/// palette is empty or reading stops before it. `names` reads their names and keeps the notes on
/// those the swatches take.
pub fn palette(data: &[u8], patterns: &[PatternDef], names: &mut obj::Names) -> Option<PaletteSwatches> {
let mut r = Reader::with_names(data, names.encoding);
// The palette, the gradients and the patterns it names come before the art, so an error in the
// art leaves them read.
let _ = r.run();
@@ -331,6 +363,15 @@ pub fn palette(data: &[u8], patterns: &[PatternDef]) -> Option<PaletteSwatches>
images.insert(im.key.clone(), blob.clone());
}
});
let used: Vec<&str> = swatches
.iter()
.chain(groups.iter().flat_map(|g| &g.swatches))
.map(|s| s.name.as_str())
.chain(groups.iter().map(|g| g.name.as_str()))
.chain(added.iter().map(|p| p.name.as_str()))
.chain(pattern_names_read(&added, &renamed))
.collect();
names.absorb_among(std::mem::take(&mut r.names), &used);
Some(PaletteSwatches { swatches, groups, patterns: added, images })
}
@@ -349,11 +390,12 @@ pub struct Brushes {
/// The brushes of the editing data `data`, for a file whose layers aren't read (a brush library
/// has none), as [`read`] makes them, with the patterns of the editing data their art paints with,
/// named apart from `patterns` ([`beside`]) as [`palette`] names them. `None` when the file has no
/// brush objects or reading stops before them.
pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option<Brushes> {
/// brush objects or reading stops before them. `names` reads their names and keeps the notes on
/// those it brings in.
pub fn brushes(data: &[u8], patterns: &[PatternDef], names: &mut obj::Names) -> Option<Brushes> {
// Brush objects are plug-in objects: data without one isn't read again.
memchr::memmem::find(data, b"BeginPluginObject")?;
let mut r = Reader::with_names(data);
let mut r = Reader::with_names(data, names.encoding);
// The brushes come before the art, so an error in the art leaves them read.
let _ = r.run();
let (mut lib, unread) = r.brush_library()?;
@@ -386,6 +428,14 @@ pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option<Brushes> {
images.insert(im.key.clone(), blob.clone());
}
});
let used: Vec<&str> = lib
.iter()
.map(|b| b.name.as_str())
.chain(added.iter().map(|p| p.name.as_str()))
.chain(pattern_names_read(&added, &renamed))
.chain(art_names(lib.iter().flat_map(|b| b.art())))
.collect();
names.absorb_among(std::mem::take(&mut r.names), &used);
Some(Brushes { brushes: lib, patterns: added, images, note: (unread > 0).then(|| brush::left_out_note(unread)) })
}
@@ -393,16 +443,19 @@ pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option<Brushes> {
/// style library has none), as [`read`] makes them, with ids from 1, and the data's declared large
/// canvas scale (1 when it declares none). `large_canvas`: as [`read`] takes it. The styles are
/// those the list names before reading stops, and none when the data has no style list or lists no
/// style this reads.
pub fn graphic_styles(data: &[u8], large_canvas: bool) -> (Vec<GraphicStyle>, f64) {
/// style this reads. `names` reads their names and keeps the notes on them.
pub fn graphic_styles(data: &[u8], large_canvas: bool, names: &mut obj::Names) -> (Vec<GraphicStyle>, f64) {
if crate::import::ai::find(data, b"BeginArtStyleList").is_none() {
return (vec![], 1.0);
}
let mut r = Reader::with_names(data);
let mut r = Reader::with_names(data, names.encoding);
r.large_canvas = large_canvas.then_some(1.0);
// The styles come before the art, so an error in the art leaves them read.
let _ = r.run();
(r.graphic_styles().0, r.canvas_scale)
let styles = r.graphic_styles().0;
let used: Vec<&str> = styles.iter().map(|s| s.name.as_str()).collect();
names.absorb_among(std::mem::take(&mut r.names), &used);
(styles, r.canvas_scale)
}
/// The symbols of a `.ai` file's editing data, as [`symbols`] reads them.
@@ -421,10 +474,10 @@ pub struct Symbols {
/// instance of a symbol the data doesn't define, and with each object of their art that is linked
/// to a listed graphic style linked to it by the id [`graphic_styles`] gives that style. The
/// symbols are those defined before reading stops and before the first layer; `None` when there
/// are none.
pub fn symbols(data: &[u8]) -> Option<Symbols> {
/// are none. `names` reads their names and keeps the notes on those it brings in.
pub fn symbols(data: &[u8], names: &mut obj::Names) -> Option<Symbols> {
crate::import::ai::find(data, b"BeginSymbol")?;
let mut r = Reader::with_names(data);
let mut r = Reader::with_names(data, names.encoding);
// The symbols come before the art, so an error in the art leaves them read.
let _ = r.run();
r.check_symbols();
@@ -468,14 +521,22 @@ pub fn symbols(data: &[u8]) -> Option<Symbols> {
let reg = r.doc.symbol_registration(&s.name);
(s, reg)
})
.collect::<Vec<_>>();
let used: Vec<&str> = symbols
.iter()
.map(|(s, _)| s.name.as_str())
.chain(swatches.iter().map(|s| s.name.as_str()))
.chain(art_names(symbols.iter().map(|(s, _)| &*s.art)))
.collect();
names.absorb_among(std::mem::take(&mut r.names), &used);
Some(Symbols { symbols, images, swatches })
}
/// [`artboards`] as far as reading `data` from its start gets: those read before an error, and
/// those of a `/Document` still open when it stopped (its art can be what stopped it).
fn artboards_read(data: &[u8]) -> (Vec<(String, Rect)>, Option<usize>) {
fn artboards_read(data: &[u8], names: &mut obj::Names) -> (Vec<(String, Rect)>, Option<usize>) {
let mut r = Reader::new(data);
r.names = obj::Names::new(names.encoding);
let _ = r.run();
let open: Vec<Obj> = r.frames.iter().filter_map(|f| if let Kind::Obj(o) = &f.kind { Some((**o).clone()) } else { None }).collect();
for o in &open {
@@ -484,6 +545,8 @@ fn artboards_read(data: &[u8]) -> (Vec<(String, Rect)>, Option<usize>) {
}
}
let active = r.active_board.filter(|i| *i < r.artboards.len());
let used: Vec<&str> = r.artboards.iter().map(|b| b.name.as_str()).collect();
names.absorb_among(std::mem::take(&mut r.names), &used);
(r.artboards.into_iter().map(|b| (b.name, b.rect)).collect(), active)
}
@@ -535,20 +598,27 @@ impl VariableRead {
}
/// The variable library of the editing data `data` ([`VariableRead`]), for a file whose layers
/// [`read`] can't read. Data without a `variableSets` element isn't read.
pub fn variables(data: &[u8]) -> VariableRead {
/// [`read`] can't read. Data without a `variableSets` element isn't read. `names` reads the
/// library's names and keeps the notes on them.
pub fn variables(data: &[u8], names: &mut obj::Names) -> VariableRead {
if crate::import::ai::find(data, b"variableSets").is_none() {
return VariableRead::default();
}
let mut r = Reader::new(data);
r.names = obj::Names::new(names.encoding);
let _ = r.run();
if r.variables.present {
absorb_library_names(&r.variables, r.names, names);
return r.variables;
}
// A `/Document` still open when reading stopped.
let open: Vec<Obj> = r.frames.iter().filter_map(|f| if let Kind::Obj(o) = &f.kind { Some((**o).clone()) } else { None }).collect();
if let Some(found) = open.iter().filter(|o| o.ty == "Document").map(variable_library).find(|v| v.present) {
return found;
for o in open.iter().filter(|o| o.ty == "Document") {
let found = variable_library(o, &mut r.names);
if found.present {
absorb_library_names(&found, r.names, names);
return found;
}
}
// Reading can stop before the library: read its node on its own.
variable_sets_node(data).map_or(r.variables, |node| {
@@ -556,11 +626,20 @@ pub fn variables(data: &[u8]) -> VariableRead {
alone.extend_from_slice(node);
alone.extend_from_slice(b"\n%_; (xmlnode-children) ,\n%_; /Recorded ,\n%_;\n");
let mut r = Reader::new(&alone);
r.names = obj::Names::new(names.encoding);
let _ = r.run();
absorb_library_names(&r.variables, r.names, names);
r.variables
})
}
/// Take into `names` the notes of `read` on the names of the variables and data sets of `library`.
fn absorb_library_names(library: &VariableRead, read: obj::Names, names: &mut obj::Names) {
let used: Vec<&str> =
library.variables.variables.iter().map(|v| v.name.as_str()).chain(library.variables.datasets.iter().map(|d| d.name.as_str())).collect();
names.absorb_among(read, &used);
}
impl<'a> Reader<'a> {
/// Take the author and custom colors that the header of a program gives (`outer`, from
/// [`Self::header_of`]), where the editing data's own header gives none: the program of an EPS
@@ -569,6 +648,7 @@ impl<'a> Reader<'a> {
if self.author.is_none() {
self.author = outer.author;
}
self.names.absorb(outer.names);
for n in outer.custom_colors {
if self.custom_colors.len() < super::directives::MAX_CUSTOM_COLORS && !self.custom_colors.iter().any(|c| c.name == n.name) {
self.custom_colors.push(n);
@@ -577,8 +657,8 @@ impl<'a> Reader<'a> {
}
/// A reader that has read the header of the program `ps` (its comment lines up to
/// `%%EndComments`).
pub(super) fn header_of(ps: &[u8]) -> Reader<'_> {
/// `%%EndComments`), its names that aren't UTF-8 read in `names`.
pub(super) fn header_of(ps: &[u8], names: NameEncoding) -> Reader<'_> {
let mut end = 0;
for line in ps.split_inclusive(|&b| b == b'\n' || b == b'\r') {
if !line.starts_with(b"%") && !line.trim_ascii().is_empty() {
@@ -590,6 +670,7 @@ impl<'a> Reader<'a> {
}
}
let mut outer = Reader::new(ps.get(..end).unwrap_or_default());
outer.names = obj::Names::new(names);
let _ = outer.run();
outer
}
@@ -732,10 +813,10 @@ impl<'a> Reader<'a> {
{
super::remember_xml_id(&mut self.xml_ids, &mut self.xml_id_bytes, uid, id);
}
let name = match o.text("AIArtName") {
let name = match self.names.entry(o, "AIArtName") {
Some(name) => name,
None => match o.obj("AI10_ArtUID").and_then(Obj::content_text) {
Some(id) => obj::xml_name(&id),
None => match o.obj("AI10_ArtUID").and_then(|id| self.names.xml_id_name(id)) {
Some(name) => name,
None => return,
},
};
@@ -753,7 +834,7 @@ impl<'a> Reader<'a> {
/// Effects Settings, its variable library (the first one read), and its Objects on Path records.
pub(super) fn document(&mut self, o: &Obj) {
if !self.variables.present {
self.variables = variable_library(o);
self.variables = variable_library(o, &mut self.names);
}
self.constraint_data(o);
if let Some(r) = find_entry(o, "AI Auto Rasterize", 0) {
@@ -769,7 +850,7 @@ impl<'a> Reader<'a> {
if !sane(r) || r.area() <= 0.0 {
continue;
}
let name = ab.text("Name").unwrap_or_else(|| format!("Artboard {}", i + 1));
let name = self.names.entry(ab, "Name").unwrap_or_else(|| format!("Artboard {}", i + 1));
let mut board = AiArtboard::new(name, r);
display_options(ab, &mut board);
if active == Some(i as f64) {
@@ -1057,7 +1138,7 @@ impl<'a> Reader<'a> {
let mut styles: Vec<GraphicStyle> = vec![];
let mut ids = HashMap::new();
for raw in &self.style_list {
let name = obj::text(raw);
let name = self.names.quiet(raw);
if name.is_empty() || ids.contains_key(&name) {
continue;
}
@@ -1227,7 +1308,7 @@ impl<'a> Reader<'a> {
self.drawn_looks += self.pattern_looks.values().sum::<usize>();
if self.drawn_looks > 0 {
warnings.push(format!(
"objects with several fills or strokes, effects or brushes came in as their drawn look ({}): their appearance isn't editable yet",
"objects with several fills or strokes, variable-width strokes, effects or brushes came in as their drawn look ({}): their appearance isn't editable yet",
self.drawn_looks
));
}
@@ -1242,6 +1323,7 @@ impl<'a> Reader<'a> {
if !doc.symbols.is_empty() {
doc.limit_depth_noting(&mut warnings);
}
warnings.extend(self.names.notes());
Ok(Structure {
doc,
to_doc,
@@ -1399,9 +1481,57 @@ const MAX_LIBRARY_BYTES: usize = 8 << 20;
/// variable holds its value: `p` elements of text, one paragraph each; a `/Bool` text, whether its
/// objects show; a linked file's URL (`file://`) or path. Graph values aren't read. What is
/// malformed, repeated or past the caps (a declaration, a data set, a value, a setting, a second
/// `variableSet`) is left out and counted; a library past [`MAX_LIBRARY_NODES`] isn't read.
fn variable_library(o: &Obj) -> VariableRead {
find_variable_sets(o, 0).map_or_else(VariableRead::default, read_variable_sets)
/// `variableSet`) is left out and counted; a library past [`MAX_LIBRARY_NODES`] isn't read. Text
/// that isn't UTF-8 is read in the encoding of `names`, which gets a note on each such name of a
/// variable or a data set.
fn variable_library(o: &Obj, names: &mut obj::Names) -> VariableRead {
let Some(sets) = find_variable_sets(o, 0) else { return VariableRead::default() };
let mut legacy = HashMap::new();
let read = read_variable_sets(&library_in_utf8(sets, names.encoding, &mut legacy, 0));
for name in read.variables.variables.iter().map(|v| &v.name).chain(read.variables.datasets.iter().map(|d| &d.name)) {
if let Some(replaced) = legacy.get(name) {
names.note(name, *replaced);
}
}
read
}
/// The XML nodes of a variable library with their text (a `/String` or `/UnicodeString` entry, whose
/// strings a long one is written across are joined first: a string may end inside a character) in
/// UTF-8, so that an element named after a variable and that variable's name are alike whatever
/// the encoding. `legacy` gets the text that wasn't UTF-8, trimmed as [`library_name`] trims it, and
/// whether parts of it weren't valid in the encoding either.
fn library_in_utf8(o: &Obj, encoding: NameEncoding, legacy: &mut HashMap<String, bool>, depth: usize) -> Obj {
let mut out = o.clone();
if depth > MAX_DEPTH {
return out;
}
for (_, values) in &mut out.entries {
match values.split_last_mut() {
Some((V::Name(ty), strings)) if matches!(ty.as_str(), "String" | "UnicodeString") && strings.iter().all(|v| matches!(v, V::Str(_))) => {
let bytes: Vec<u8> = strings.iter().flat_map(|v| if let V::Str(s) = v { s.as_slice() } else { &[] }).copied().collect();
let (text, not_utf8, replaced) = encoding.decoded(&bytes);
if not_utf8 {
legacy.insert(text.trim().to_string(), replaced);
}
let ty = V::Name(ty.clone());
*values = vec![V::Str(text.into_bytes()), ty];
}
_ => {
for v in values.iter_mut() {
if let V::Obj(child) = v {
*child = std::rc::Rc::new(library_in_utf8(child, encoding, legacy, depth + 1));
}
}
}
}
}
for v in &mut out.content {
if let V::Obj(child) = v {
*child = std::rc::Rc::new(library_in_utf8(child, encoding, legacy, depth + 1));
}
}
out
}
/// The `variableSets` XML node in `o` or the dictionaries it holds.
+60 -10
View File
@@ -169,7 +169,7 @@ impl<'a> Reader<'a> {
}
if let Some(d) = self.gradient_def.as_mut() {
match w {
"Bs" => d.stop(&vals, &mut self.stop_spots),
"Bs" => d.stop(&vals, &mut self.stop_spots, &mut self.names),
"BD" => {
if let Some((name, g)) = self.gradient_def.take().and_then(GradientDef::finish) {
self.global_names.define(Global::Gradient, &name);
@@ -227,7 +227,7 @@ impl<'a> Reader<'a> {
"Lb" => self.layer_attrs(&vals),
"Ln" => {
if let Some(Frame { kind: Kind::Layer(a), .. }) = self.frames.last_mut() {
a.name = vals.iter().rev().find_map(V::text).unwrap_or_default();
a.name = vals.iter().rev().find_map(|v| self.names.text(v)).unwrap_or_default();
}
}
"LB" => self.layer_end()?,
@@ -319,12 +319,12 @@ impl<'a> Reader<'a> {
"A" => self.gs.locked = Self::nums(&vals).last() == Some(&1.0),
"XW" => self.state_marker(&vals, hidden),
// Gradients.
"Bd" => self.gradient_def = GradientDef::begin(&vals),
"Bd" => self.gradient_def = GradientDef::begin(&vals, &mut self.names),
"Bs" | "BD" => {}
"Bb" => self.instance = Some(Instance::begin(&vals)),
"Bg" => {
if let Some(i) = self.instance.as_mut() {
i.bg(&vals);
i.bg(&vals, &mut self.names);
}
}
"Bm" => {
@@ -479,7 +479,7 @@ impl<'a> Reader<'a> {
if self.frames.is_empty() {
return;
}
let name = vals.iter().find_map(|v| if let V::Str(_) = v { v.text() } else { None });
let name = vals.iter().find(|v| matches!(v, V::Str(_))).and_then(|v| self.names.text(v));
let Some(tile) = name.as_deref().and_then(|n| self.pattern_tiles.get(n)).copied() else {
self.unread_pattern(w);
return;
@@ -523,7 +523,7 @@ impl<'a> Reader<'a> {
}
fn color(&mut self, w: &str, vals: &[V]) {
let Some((p, named)) = paint::color_op(w, vals) else { return };
let Some((p, named)) = paint::color_op_in(w, vals, &mut self.names) else { return };
// Registration (`Xs`, `Xz`) says nothing of the document's colour model.
let registration = matches!(w, "Xs" | "XS" | "Xz" | "XZ") || p.is_registration();
match p.color().filter(|_| !registration) {
@@ -706,7 +706,7 @@ impl<'a> Reader<'a> {
/// follows an object.
fn style_marker(&mut self, vals: &[V], hidden: bool) {
let code = Self::nums(vals).last().copied().unwrap_or(0.0);
let style = vals.iter().rev().find_map(V::text).unwrap_or_default();
let style = vals.iter().rev().find_map(|v| self.names.text(v)).unwrap_or_default();
let after = std::mem::take(&mut self.after_object);
// An object's own state block ends `6 () XW` (a layer's `7 () XW`): an `Xy` before it isn't the layer's.
if code == 6.0 {
@@ -752,6 +752,24 @@ impl<'a> Reader<'a> {
{
return;
}
// A variable-width stroke's look that draws nothing but copies read from `%_` lines: an
// empty group, which [`styled`] takes the stroke for.
let drawn;
let look = if !hidden
&& slot_of(object.name.as_deref()).is_none()
&& matches!(look.kind, NodeKind::Group { .. })
&& self.styles.get(&style).is_some_and(|st| st.uneven)
&& !draws(look, &self.hidden_ids)
{
let mut copy = look.clone();
if let Some(children) = copy.children_mut() {
children.clear();
}
drawn = copy;
&drawn
} else {
look
};
// A style read here: the object, painted as it says.
if let Some(mut appearance) = self.styles.get(&style).and_then(|st| {
styled(
@@ -1062,10 +1080,13 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
use crate::import::ai::style::StyleItem;
// A text object's slot (an empty group standing for it) takes the style as the type will.
let slot = slot_of(object.name.as_deref()).is_some();
// Several fills and strokes, on a path or a compound path.
let stacked = !slot && !st.simple && st.stacked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
// A symbol instance draws its symbol's art: it keeps its drawn look.
if !st.plain
|| matches!(object.kind, NodeKind::SymbolInstance { .. })
|| (!slot && !st.simple)
// A look with no outline in it to keep takes a variable-width stroke as the object's own.
|| (!slot && !st.simple && !stacked && (!st.uneven || draws(look, &HashSet::new())))
|| (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty())
|| (st.pathfinder
&& (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. })))
@@ -1080,6 +1101,19 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
// drawn look has each where the app placed it.
let mut placed = HashMap::new();
placed_paints(look, &mut placed, 0);
// A stack's gradients are each its own swatch, placed where the drawn look has it: one fitted
// to the object's bounds instead could lie elsewhere, so such a stack keeps its drawn look.
if stacked {
let mut seen = HashSet::new();
let placed_apart = st.items.iter().all(|i| match i {
StyleItem::Gradient { name: Some(n), .. } => seen.insert(n) && placed.contains_key(paints.names.get(Global::Gradient, n)),
StyleItem::Gradient { name: None, .. } => false,
_ => true,
});
if !placed_apart {
return None;
}
}
let mut items = vec![];
for (n, item) in st.items.iter().enumerate() {
let mut layer = match item {
@@ -1087,8 +1121,9 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
StyleItem::Gradient { name, angle } => {
// The drawn look's gradients are keyed by the names they got in the document.
let paint = match (name.as_ref().and_then(|n| placed.get(paints.names.get(Global::Gradient, n))), gradients, own_gradient) {
// Other objects than type: the object's own, as they always were.
(_, 1, Some(own)) if !slot => own.paint.clone(),
// Other objects than type: the object's own, as they always were (a stack's
// where its drawn look places it).
(_, 1, Some(own)) if !slot && !stacked => own.paint.clone(),
(Some(p), ..) => p.clone(),
(None, 1, Some(own)) => own.paint.clone(),
_ => {
@@ -1259,6 +1294,21 @@ fn strip(n: &mut Node, hidden: &HashSet<NodeId>) {
}
}
/// Whether `n` holds anything that draws, apart from the children read from `%_` lines (`hidden`):
/// a path or a compound path with a paint of its own, or a node other than a group or those.
fn draws(n: &Node, hidden: &HashSet<NodeId>) -> bool {
if hidden.contains(&n.id) {
return false;
}
let paints = n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none());
match (&n.kind, n.children()) {
(NodeKind::Compound { .. }, Some(children)) => paints && children.iter().any(|c| c.visible && !hidden.contains(&c.id)),
(NodeKind::Group { .. }, Some(children)) => children.iter().any(|c| c.visible && draws(c, hidden)),
(NodeKind::Path { .. }, _) => paints,
_ => true,
}
}
/// Whether ASCII85 data in comment lines, up to its `~>`, follows the entry keyed `key` of a
/// dictionary of type `ty`: the `/ASCII85Decode` of a `/Binary` dictionary or a text document, or a
/// non-native art object's (`/ForeignObject`'s) `/Data`.
+50 -14
View File
@@ -47,7 +47,8 @@
//! with a pattern or gradient too; strokes with a Calligraphic or Art brush or aligned inside or outside too), each with its own
//! transparency and effects, and the effects of
//! [`effect`]. Such objects are read as themselves with an appearance of those fills, strokes and
//! effects; others keep their drawn look. Effect › Pathfinder effects (`(Adobe Pathfinder)` in the
//! effects (a path's stack of several fills and strokes when its drawn look places each of its
//! gradients); others keep their drawn look. Effect › Pathfinder effects (`(Adobe Pathfinder)` in the
//! object's chain) are read on a group with no fills or strokes of its own, which keeps its members.
use std::collections::HashMap;
@@ -59,7 +60,7 @@ use vectorcraft_effects::is_pathfinder;
use super::brush::PathBrush;
use super::lex::{Lexer, Tok};
use super::obj::{self, V};
use super::obj::{self, Names, V};
use super::paint;
const GLOW: &str = "Adobe Outer Glow"; // brand-ok: the filter's name in the files
@@ -173,13 +174,21 @@ const PATHFINDER_OPTIONS: [(&str, Kind, f64); 12] = [
pub(super) struct ArtStyle {
/// The style reads as [`Self::items`] and [`Self::effects`].
pub plain: bool,
/// It is one fill and one stroke at most, in solid colours or the object's own gradient, with
/// It is one fill and one stroke at most, none of them [`Self::uneven`], in solid colours or the object's own gradient, with
/// no transparency or effects of their own, and only Drop Shadow, Inner Glow, Outer Glow,
/// Feather, Round Corners, Scribble, Convert to Shape, the Path effects (Offset Path, Outline Object, Outline Stroke),
/// Bas Relief read from its settings block and some Distort & Transform effects ([`any_object_takes`]) on the object
/// (and Pathfinder effects when it has no fills or strokes): what any object is read with. Type takes the other plain styles too (its drawn look
/// can't be retyped); other objects keep their drawn look, which is the app's own rendering.
/// can't be retyped), paths and compound paths [`Self::stacked`] ones; other objects keep their drawn look, which is the app's own rendering.
pub simple: bool,
/// It would be [`Self::simple`] but for a Stroke Style filter's variable width written as one
/// centered array ([`centered_widths`]): an object whose drawn look is empty takes it with its profile.
pub uneven: bool,
/// It is several fills and strokes in solid colours or gradients (strokes without a brush),
/// each with its own visibility, opacity and blend mode but no effects of its own, under only
/// the effects any object takes that don't move the outline: what a path or compound path is
/// read with when each gradient is placed as its drawn look has it (`read::ops`' `styled`).
pub stacked: bool,
/// Its fills and strokes, bottom first.
pub items: Vec<StyleItem>,
/// Each item's own visibility, transparency and effects, in the order of [`Self::items`].
@@ -380,8 +389,14 @@ fn closes(data: &[u8]) -> bool {
false
}
/// The styles of the section `data` (between its markers), by name.
/// [`art_styles_in`], names read in the default encoding.
pub(super) fn art_styles(data: &[u8]) -> HashMap<String, ArtStyle> {
art_styles_in(data, &mut Names::default())
}
/// The styles of the section `data` (between its markers), by name: the names of the styles and of
/// the colours, gradients and patterns they paint with read by `names`.
pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap<String, ArtStyle> {
let mut styles = HashMap::new();
let mut name: Option<String> = None;
let mut filters: Vec<Filter> = vec![];
@@ -437,7 +452,7 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap<String, ArtStyle> {
}
b"FillStyle" => style_entry = Some(Kind::Fill),
b"StrokeStyle" | b"BlendStyle" => style_entry = Some(Kind::Other),
b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(V::text),
b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(|v| names.text(v)),
b"All" | b"[Registration]" | b"Registration" => operands.push(V::Name(obj::text(n))),
b"CompoundFilter" => pending = Some(true),
b"BasicFilter" => pending = Some(false),
@@ -464,7 +479,7 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap<String, ArtStyle> {
}
b"Array" => dict_array = Some(vec![]),
b"PluginObject" if in_basic => {
let mut texts = operands.iter().rev().filter_map(V::text);
let mut texts = operands.iter().rev().filter_map(|v| names.text(v));
if let (Some(plugin), Some(name), Some(f)) = (texts.next(), texts.next(), filters.last_mut()) {
f.plugin_object = Some((name, plugin));
}
@@ -535,7 +550,7 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap<String, ArtStyle> {
}
}
if let Some(f) = filters.last_mut() {
paint_op(f, op, &operands);
paint_op(f, op, &operands, names);
}
if op == "," || op == ";" || op.starts_with('X') || op.starts_with('B') || op.len() <= 2 {
operands.clear();
@@ -608,13 +623,13 @@ fn block_data(lex: &mut Lexer, encoded: &[u8]) -> Option<Vec<u8>> {
None
}
/// A paint operator of a fill's or stroke's style.
fn paint_op(f: &mut Filter, op: &str, vals: &[V]) {
/// A paint operator of a fill's or stroke's style, the names it gives read by `names`.
fn paint_op(f: &mut Filter, op: &str, vals: &[V], names: &mut Names) {
let last = vals.iter().rev().find_map(V::num);
match op {
"Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "xa" | "xx" | "xk" | "xs"
| "xz" => {
let Some((p, _)) = paint::color_op(op, vals) else { return };
let Some((p, _)) = paint::color_op_in(op, vals, names) else { return };
if op.ends_with(|c: char| c.is_ascii_lowercase()) {
f.fill = Some(p);
} else {
@@ -675,13 +690,13 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V]) {
"Bg" => {
f.gradient = true;
let at = vals.iter().rposition(|v| matches!(v, V::Str(_)));
let name = at.and_then(|i| vals.get(i)).and_then(V::text);
let name = at.and_then(|i| vals.get(i)).and_then(|v| names.text(v));
let n: Vec<f64> = at.map_or(&[][..], |i| vals.get(i + 1..).unwrap_or_default()).iter().filter_map(V::num).collect();
let angle = n.get(2).copied().filter(|a| a.is_finite()).unwrap_or(0.0);
f.gradient_of = Some((name, angle));
}
"p" => {
let name = vals.iter().find_map(|v| if let V::Str(_) = v { v.text() } else { None });
let name = vals.iter().find(|v| matches!(v, V::Str(_))).and_then(|v| names.text(v));
let matrix = vals.iter().rev().find_map(|v| match v {
V::Arr(a) => {
let n: Vec<f64> = a.iter().filter_map(V::num).collect();
@@ -1589,7 +1604,7 @@ fn style(filters: &[Filter]) -> ArtStyle {
st.plain = b.plain;
let bas_relief = bas_relief_read(filters);
let count = |stroke: bool| st.items.iter().filter(|i| matches!(i, StyleItem::Stroke { .. }) == stroke).count();
st.simple = st.plain
let simple = st.plain
&& count(true) <= 1
&& count(false) <= 1
&& st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Stroke { .. } | StyleItem::Gradient { .. }))
@@ -1600,9 +1615,30 @@ fn style(filters: &[Filter]) -> ArtStyle {
&& (!st.moves_outline() || st.effects.len() == 1)
// Pathfinder effects on a group with no fills or strokes of its own (`styled` checks the group).
&& (!st.pathfinder || st.items.is_empty());
// A stroke with one centered width array comes in as the drawn look, which holds the outline as the file draws it.
let centered = filters.iter().any(centered_widths);
(st.simple, st.uneven) = (simple && !centered, simple && centered);
st.stacked = !centered
&& st.plain
&& !st.pathfinder
&& !st.moves_outline()
&& st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Gradient { .. } | StyleItem::Stroke { brush: None, .. }))
&& st.looks.iter().all(|l| l.effects.is_empty())
&& st.effects.iter().all(any_object_takes);
st
}
/// Whether `f` is a painted Stroke Style filter with a variable width written as one centered array,
/// `BSCenteredWidthsArray`. A Stroke Offset filter's profile and one written as each side's widths
/// (`BSLeftWidthsArray` and `BSRightWidthsArray`, as VectorCraft saves it) are not.
fn centered_widths(f: &Filter) -> bool {
let each_side = f
.arrays
.get("BSVariableWidthTValuesArray")
.is_some_and(|at| ["BSLeftWidthsArray", "BSRightWidthsArray"].iter().all(|key| f.arrays.get(*key).is_some_and(|w| w.len() == at.len())));
f.name == STROKE && f.paints.0 && !each_side && width_profile(&f.arrays).is_some()
}
mod adapter;
#[cfg(test)]
mod tests;
+55 -12
View File
@@ -1,20 +1,63 @@
use super::*;
use vectorcraft_color::Color;
#[test]
fn a_variable_width_stroke_keeps_its_profile() {
let data = b"/KnownStyle :\n(Tapered) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
fn paint_op(f: &mut Filter, op: &str, vals: &[V]) {
super::paint_op(f, op, vals, &mut Names::default());
}
/// The style `Tapered`: a 30 pt stroke whose beautiful-strokes dictionary holds `arrays`.
fn width_style(arrays: &str) -> ArtStyle {
let data = format!(
"/KnownStyle :\n(Tapered) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 R\n0 0 0 0 0 0 1 XA\n0 J 0 j 30 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n\
/Dictionary : /NotRecorded ,\n2 /Int (BSWidthSource) ,\n/Array :\n0 /Real ,\n1 /Real ,\n; (BSVariableWidthTValuesArray) ,\n\
/Array :\n1 /Real ,\n0.1 /Real ,\n; (BSCenteredWidthsArray) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n; /Dict ;\n /Part ,\n\
/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n";
let styles = art_styles(data);
let style = &styles["Tapered"];
assert!(style.plain);
let [StyleItem::Stroke { width, profile, .. }] = style.items.as_slice() else { panic!("{:?}", style.items) };
assert_eq!(*width, 30.0);
assert_eq!(profile.as_ref().map(|p| p.points.clone()), Some(vec![(0.0, 1.0, 1.0), (1.0, 0.1, 0.1)]));
/Dictionary : /NotRecorded ,\n2 /Int (BSWidthSource) ,\n{arrays}; (kAIBeautifulStrokesParamsDictKey) ,\n; /Dict ;\n /Part ,\n\
/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n"
);
art_styles(data.as_bytes()).remove("Tapered").unwrap_or_default()
}
/// A beautiful-strokes array `key` of `values`.
fn bs_array(key: &str, values: &[&str]) -> String {
let items: String = values.iter().map(|v| format!("{v} /Real ,\n")).collect();
format!("/Array :\n{items}; ({key}) ,\n")
}
#[test]
fn a_centered_width_array_reads_as_uneven_with_its_profile() {
// GUARDS: the style counted as `simple`, and any object read with it dropped its drawn look.
let t = |v: &[&str]| bs_array("BSVariableWidthTValuesArray", v);
let w = |v: &[&str]| bs_array("BSCenteredWidthsArray", v);
for (arrays, points) in [
(t(&["0", "0.5", "1"]) + &w(&["0", "1", "0"]), vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)]),
(t(&["0", "1"]) + &w(&["1", "0.1"]), vec![(0.0, 1.0, 1.0), (1.0, 0.1, 0.1)]),
] {
let style = width_style(&arrays);
assert!(style.plain && !style.simple && style.uneven, "{arrays:?}: {style:?}");
let [StyleItem::Stroke { width, profile, .. }] = style.items.as_slice() else { panic!("{:?}", style.items) };
assert_eq!((*width, profile.as_ref().map(|p| p.points.clone())), (30.0, Some(points)), "{arrays:?}");
}
}
#[test]
fn a_uniform_or_unreadable_width_profile_stays_a_live_stroke() {
let t = |v: &[&str]| bs_array("BSVariableWidthTValuesArray", v);
let w = |v: &[&str]| bs_array("BSCenteredWidthsArray", v);
for arrays in [
String::new(),
t(&["0", "1"]) + &w(&["1", "1"]),
// No widths, widths of another length, widths that aren't numbers.
t(&["0", "0.5", "1"]),
t(&["0", "0.5", "1"]) + &w(&["0", "1"]),
t(&["0", "1"]) + "/Array :\n(x) /String ,\n(y) /String ,\n; (BSCenteredWidthsArray) ,\n",
// Positions that aren't numbers.
t(&["nan", "nan"]) + &w(&["0", "1"]),
] {
let style = width_style(&arrays);
assert!(style.plain && style.simple, "{arrays:?}: {style:?}");
let [StyleItem::Stroke { width, profile, .. }] = style.items.as_slice() else { panic!("{arrays:?}: {:?}", style.items) };
assert_eq!((*width, profile), (30.0, &None), "{arrays:?}");
}
}
#[test]
+482 -4
View File
@@ -783,7 +783,7 @@ fn pattern_names_are_shown_up_to_their_newline() {
// Nor the name of a custom color the program of an EPS gives, or None's.
let ps = b"%!PS-Adobe-3.0\n%%CMYKCustomColor: 0 0 1 0 (Outer Ink)\n%%EndComments\n";
let data = stream(&format!("{}{}{}", def("Outer Ink\\n1", 8), def("[None]\\n1", 8), layer(&filled("Outer Ink\\n1"))));
let doc = super::read_beside(data.as_bytes(), true, ps, false).unwrap().doc;
let doc = super::read_beside(data.as_bytes(), true, ps, false, NameEncoding::default()).unwrap().doc;
assert_eq!(doc.patterns.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Outer Ink 2", "[None] 2"]);
assert!(matches!(doc.swatch("Outer Ink").unwrap().paint, Paint::Solid { .. }));
assert!(matches!(fill(&art(&doc)[0]), Paint::Pattern { pattern, .. } if pattern == "Outer Ink 2"));
@@ -2510,6 +2510,7 @@ fn ai_variable_library_without_the_layers() {
let library = variable_library_data(&sample_variable_sets("variableAndTypes", &[]));
let unread = stream(&format!("{library}{}", layer("1 Zz\n")));
assert!(read(unread.as_bytes()).is_err());
let variables = |data: &[u8]| variables(data, &mut Names::default());
let found = variables(unread.as_bytes());
assert!(found.present && found.variables.locked && found.skipped == 0);
assert_eq!((found.variables.variables.len(), found.variables.datasets.len()), (5, 3));
@@ -5724,7 +5725,7 @@ fn artboards_after_what_stops_the_reading() {
let array = format!("%_/Array :\n{}{}%_; (ArtboardArray) ,\n", board("one", 0), board("two", 200));
// Art in the document's own data that the reader can't follow comes before the artboards.
let data = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n%_/Dictionary :\nLB\n{array}%_; /NotRecorded ,\n%_;\n");
let boards: Vec<_> = super::artboards(data.as_bytes()).0.into_iter().map(|(n, r)| (n, r.x0)).collect();
let boards: Vec<_> = super::artboards(data.as_bytes(), &mut Names::default()).0.into_iter().map(|(n, r)| (n, r.x0)).collect();
assert_eq!(boards, [("one".to_string(), 0.0), ("two".to_string(), 200.0)]);
}
@@ -5925,6 +5926,115 @@ fn a_symbol_defined_before_the_art_styles_reads_its_styled_objects() {
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
}
/// An art style named `Glow`: a path filled with gradient swatch `under`, then gradient swatch
/// `over` at 50 % Screen above it.
fn two_gradient_style(under: &str, over: &str) -> String {
let fill = |name: &str| {
format!(
"/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\
/FillStyle : 0 O\n1 ({name}) 0 0 0 1 1 0 0 1 0 0 Bg\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n"
)
};
format!(
"/KnownStyle :\n(Glow) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{}\
/BasicFilter :\n(Blend Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\
/BlendStyle : 2 0.5 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d0 XR\n/Def ;\n (BlendStyle) ,\n; /Dict ;\n /Part ,\n;\n /Part ,\n\
{}/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n",
fill(over),
fill(under)
)
}
#[test]
fn a_path_with_several_gradient_fills_comes_in_as_itself_where_its_look_places_them() {
// GUARDS: a path whose style stacks fills with their own opacity and blend mode came in as its drawn look.
let defs = "%AI5_BeginGradient: (A)\n(A) 0 2 Bd\n[\n<00FF>\n0\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n\
%AI5_BeginGradient: (B)\n(B) 0 2 Bd\n[\n<00FF>\n0\n%_0 0 0 0 0 1 0 2 1 6 50 0 Bs\n%_0 0 0 0 1 1 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
let rect = rect_path(0.0, 0.0, 100.0, 50.0);
let hidden_rect = rect.replace('\n', "\n%_");
// The drawn look: the path filled with each gradient where the app placed it (its transparency
// left out: only where the gradients lie is read from it).
let look = |name: &str, x0: f64| format!("{rect}Bb\n1 ({name}) {x0} 25 0 50 1 0 0 1 0 0 Bg\nf\n0 BB\n");
let square = |under: &str, over: &str| format!("0 Ae\nu\n{}{}U\n%_{hidden_rect}f\n1 (Glow) XW\n", look(under, 0.0), look(over, 50.0));
let r = read_ok(&format!("%AI9_BeginArtStyles\n{}%AI9_EndArtStyles\n{defs}{}", two_gradient_style("A", "B"), layer(&square("A", "B"))));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{a:#?}");
assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {a:#?}");
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
let fills: Vec<_> = a[0]
.appearance
.items
.iter()
.map(|i| match (i, i.paint()) {
(AppearanceItem::Fill(f), Paint::Gradient(g)) => (g.swatch.clone(), g.geom.map(|g| g.start.x), f.opacity, f.blend),
_ => panic!("{i:?}"),
})
.collect();
assert_eq!(fills, [(Some("A".into()), Some(0.0), 1.0, BlendMode::Normal), (Some("B".into()), Some(50.0), 0.5, BlendMode::Screen)]);
// Two fills of one swatch: which placement is whose isn't known, so the drawn look stays.
let same = read_ok(&format!("%AI9_BeginArtStyles\n{}%AI9_EndArtStyles\n{defs}{}", two_gradient_style("A", "A"), layer(&square("A", "A"))));
assert!(same.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", same.warnings);
// One gradient over a solid fill, on a path filled with that gradient placed elsewhere: the
// gradient lies where the drawn look has it, not where the path's own fill does.
let one = two_gradient_style("A", "B").replace("1 (A) 0 0 0 1 1 0 0 1 0 0 Bg\n", "0 0 0 1 0 0 0 Xa\n");
let own = format!(
"0 Ae\nu\n0 0 0 1 0 0 0 Xa\n{rect}f\n{}U\n%_{hidden_rect}Bb\n%_1 (B) 0 25 0 100 1 0 0 1 0 0 Bg\n%_f\n%_0 BB\n1 (Glow) XW\n",
look("B", 50.0)
);
let one = read_ok(&format!("%AI9_BeginArtStyles\n{one}%AI9_EndArtStyles\n{defs}{}", layer(&own)));
let a = art(&one.doc);
assert_eq!(a.len(), 1, "{a:#?}");
let placed: Vec<_> = a[0]
.appearance
.items
.iter()
.map(|i| match i.paint() {
Paint::Gradient(g) => g.geom.map(|g| g.start.x),
_ => None,
})
.collect();
assert_eq!(placed, [None, Some(50.0)], "{:?}", one.warnings);
// A look that doesn't paint the gradient (a raster, say): the drawn look stays.
let flat = format!("0 Ae\nu\n{RED}{rect}f\nU\n%_{hidden_rect}f\n1 (Glow) XW\n");
let flat = read_ok(&format!("%AI9_BeginArtStyles\n{}%AI9_EndArtStyles\n{defs}{}", two_gradient_style("A", "B"), layer(&flat)));
assert!(flat.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", flat.warnings);
}
/// A stack of solid colours comes in live too: a path whose style is a solid fill under a stroke
/// without a brush at 50 % Screen comes in as itself with both, each with its own transparency.
#[test]
fn a_path_with_a_solid_fill_under_a_screened_stroke_comes_in_as_itself() {
let stroke = "/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\
/StrokeStyle : 0 R\n0 1 1 0 1 0 0 XA\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n";
let over = "/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\
/FillStyle : 0 O\n1 (B) 0 0 0 1 1 0 0 1 0 0 Bg\n0 1 Xd\n/Def ;\n (FillStyle) ,\n";
let style = two_gradient_style("A", "B");
assert!(style.contains(over));
let style = style.replace(over, stroke).replace("1 (A) 0 0 0 1 1 0 0 1 0 0 Bg\n", "0 0 0 1 0 0 0 Xa\n");
let rect = rect_path(0.0, 0.0, 100.0, 50.0);
let hidden_rect = rect.replace('\n', "\n%_");
let square = format!("0 Ae\nu\n0 0 0 1 0 0 0 Xa\n{rect}f\n0 1 1 0 1 0 0 XA\n2 w\n{rect}S\nU\n%_{hidden_rect}f\n1 (Glow) XW\n");
let r = read_ok(&format!("%AI9_BeginArtStyles\n{style}%AI9_EndArtStyles\n{}", layer(&square)));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{a:#?}");
assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {a:#?}");
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
let items: Vec<_> = a[0]
.appearance
.items
.iter()
.map(|i| match i {
AppearanceItem::Fill(f) => ("fill", matches!(f.paint, Paint::Solid { .. }), f.opacity, f.blend),
AppearanceItem::Stroke(s) => {
("stroke", matches!(s.paint, Paint::Solid { .. }) && s.brush.is_none() && s.width == 2.0, s.opacity, s.blend)
}
})
.collect();
assert_eq!(items, [("fill", true, 1.0, BlendMode::Normal), ("stroke", true, 0.5, BlendMode::Screen)]);
}
/// `node` is the red square of [`styled_square`] read as itself with [`ART_STYLES`]' `Blue`: a blue
/// fill and a drop shadow, not the look it draws.
fn assert_blue_square(node: &Node) {
@@ -6239,7 +6349,7 @@ fn a_symbol_library_without_layers_gives_its_symbols() {
);
let list = "%AI24_BeginSymbolList\n(Tile)\n(Pair)\n(Lost)\n(Dot)\n%AI24_EndSymbolList\n";
let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{styles}{defs}{list}");
let read = super::symbols(stream(&body).as_bytes()).expect("the library's symbols");
let read = super::symbols(stream(&body).as_bytes(), &mut Names::default()).expect("the library's symbols");
let names: Vec<&str> = read.symbols.iter().map(|(s, _)| s.name.as_str()).collect();
assert_eq!(names, ["Tile", "Pair", "Dot", "Pic"]);
let registrations: Vec<u8> = read.symbols.iter().map(|(_, r)| r.0).collect();
@@ -6256,7 +6366,7 @@ fn a_symbol_library_without_layers_gives_its_symbols() {
assert_eq!(keys.len(), 1);
assert_eq!(read.images.keys().cloned().collect::<Vec<_>>(), keys);
// Without symbols there are none to give.
assert!(super::symbols(stream(&styles).as_bytes()).is_none());
assert!(super::symbols(stream(&styles).as_bytes(), &mut Names::default()).is_none());
}
#[test]
@@ -6342,6 +6452,31 @@ fn an_object_with_a_feather_style_comes_in_with_a_live_effect() {
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
}
/// The art style `Tapered`: a 4 pt stroke with width points `widths` (position, width) along it,
/// their widths written as one centered array.
fn width_profile_style(widths: &[(f64, f64)]) -> String {
width_arrays_style(widths, &["BSCenteredWidthsArray"])
}
/// The art style `Tapered`: a 4 pt stroke with width points `widths` (position, width) along it,
/// their widths written under each of `keys`.
fn width_arrays_style(widths: &[(f64, f64)], keys: &[&str]) -> String {
let array = |values: Vec<f64>| values.iter().map(|v| format!("{v} /Real ,\n")).collect::<String>();
let width_arrays: String = keys.iter().map(|key| format!("/Array :\n{}; ({key}) ,\n", array(widths.iter().map(|w| w.1).collect()))).collect();
format!(
"%AI9_BeginArtStyles\n\
/KnownStyle :\n(Tapered) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\
/StrokeStyle : 0 R\n0 0 0 0 0 0 1 XA\n0 J 0 j 4 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n\
/Dictionary : /NotRecorded ,\n2 /Int (BSWidthSource) ,\n/Array :\n{}; (BSVariableWidthTValuesArray) ,\n{width_arrays}\
; (kAIBeautifulStrokesParamsDictKey) ,\n; /Dict ;\n /Part ,\n\
/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n\
%AI9_EndArtStyles\n",
array(widths.iter().map(|w| w.0).collect()),
)
}
/// An art style section with style `PF`: an Effect › Pathfinder filter with `Command` `command`
/// and `Mix` `mix` in the object's chain, over a fill and stroke that paint nothing.
fn pathfinder_styles(command: u32, mix: f64) -> String {
@@ -6372,6 +6507,73 @@ fn pathfinder_group() -> String {
)
}
#[test]
fn a_variable_width_stroke_comes_in_as_its_drawn_outline() {
// GUARDS: the object came in as a live stroke drawn from its profile, and the outline in the file was dropped.
let hidden_line = "0 5 m\n10 5 L\n".replace('\n', "\n%_");
let fills = format!("{RED}{}f\n", rect_path(30.0, 0.0, 40.0, 10.0));
let art_ = format!("{fills}0 Ae\nu\n{RED}{}f\nU\n%_{hidden_line}S\n1 (Tapered) XW\n{fills}", rect_path(0.0, 3.0, 10.0, 7.0));
let lens = width_profile_style(&[(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)]);
let r = read_ok(&format!("{lens}{}", layer(&art_)));
let a = art(&r.doc);
assert_eq!(a.len(), 3, "{a:#?}");
let look = &a[1];
assert!(matches!(look.kind, NodeKind::Group { .. }), "{look:#?}");
let [outline] = look.children().unwrap().as_slice() else { panic!("{look:#?}") };
assert!(matches!(outline.kind, NodeKind::Path { .. }) && outline.appearance.fill().is_some(), "{outline:#?}");
assert!(outline.appearance.stroke().is_none_or(|s| s.profile.is_none()), "{outline:#?}");
assert!([&a[0], &a[2]].iter().all(|n| matches!(n.kind, NodeKind::Path { .. })), "the objects beside it stay in place");
assert!(r.warnings.iter().any(|w| w.contains("drawn look (1)")), "{:?}", r.warnings);
// A uniform profile is a plain stroke: the object comes in as itself.
let uniform = width_profile_style(&[(0.0, 1.0), (1.0, 1.0)]);
let r = read_ok(&format!("{uniform}{}", layer(&art_)));
let a = art(&r.doc);
assert_eq!(a.len(), 3, "{a:#?}");
assert!(matches!(a[1].kind, NodeKind::Path { .. }), "{:#?}", a[1]);
assert_eq!(a[1].appearance.stroke().map(|s| (s.width, s.profile.is_none())), Some((4.0, true)), "{:#?}", a[1]);
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
}
/// Only a Stroke Style filter's widths written as one centered array come in as the drawn look.
/// A Stroke Offset stroke and widths written for each side, as VectorCraft saves them, stay live.
#[test]
fn only_centered_widths_on_a_plain_stroke_come_in_as_the_drawn_outline() {
// GUARDS: every stroke with a profile went to its drawn look, so a Stroke Offset stroke and the
// app's own files lost their live profile.
let hidden_line = "0 5 m\n10 5 L\n".replace('\n', "\n%_");
let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_{hidden_line}S\n1 (Tapered) XW\n", rect_path(0.0, 3.0, 10.0, 7.0));
let lens = [(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)];
let r = read_ok(&format!("{}{}", width_profile_style(&lens), layer(&art_)));
let a = art(&r.doc);
let [look] = a.as_slice() else { panic!("{a:#?}") };
assert!(matches!(look.kind, NodeKind::Group { .. }), "{look:#?}");
assert!(r.warnings.iter().any(|w| w.contains("drawn look (1)")), "{:?}", r.warnings);
// One side's array alone doesn't replace the centered one, so the widths are still centered.
let r = read_ok(&format!("{}{}", width_arrays_style(&lens, &["BSCenteredWidthsArray", "BSLeftWidthsArray"]), layer(&art_)));
let a = art(&r.doc);
let [look] = a.as_slice() else { panic!("{a:#?}") };
assert!(matches!(look.kind, NodeKind::Group { .. }), "{look:#?}");
let sides = width_arrays_style(&lens, &["BSLeftWidthsArray", "BSRightWidthsArray"]);
let profile = "/Dictionary : /NotRecorded ,\n/Array :\n0 /Real ,\n0.5 /Real ,\n1 /Real ,\n; (BSVariableWidthTValuesArray) ,\n\
/Array :\n0 /Real ,\n1 /Real ,\n0 /Real ,\n; (BSCenteredWidthsArray) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n";
let offset = format!(
"%AI9_BeginArtStyles\n{}%AI9_EndArtStyles\n",
offset_stroke_style_with("Tapered", &format!("0 /Bool (StrokeOffsetInside) ,\n{profile}"), OFFSET_STROKE)
);
for (why, style) in [("each side's widths", sides), ("a Stroke Offset stroke", offset)] {
let r = read_ok(&format!("{style}{}", layer(&art_)));
let a = art(&r.doc);
let [object] = a.as_slice() else { panic!("{why}: {a:#?}") };
assert!(matches!(object.kind, NodeKind::Path { .. }), "{why}: {object:#?}");
assert!(object.appearance.stroke().is_some_and(|s| s.profile.is_some()), "{why}: {object:#?}");
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?}", r.warnings);
}
}
#[test]
fn a_group_with_a_pathfinder_effect_keeps_its_members_and_the_effect() {
// GUARDS: the style was not read, and the group came in as its drawn look: one path, with no effect.
@@ -6388,6 +6590,27 @@ fn a_group_with_a_pathfinder_effect_keeps_its_members_and_the_effect() {
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
}
#[test]
fn a_variable_width_stroke_with_an_empty_look_comes_in_as_itself() {
// GUARDS: with no outline in its look to keep, the object was dropped.
let hidden_line = "0 5 m\n10 5 L\n".replace('\n', "\n%_");
let hidden_fill = format!("{}f\n", rect_path(0.0, 3.0, 10.0, 7.0)).replace('\n', "\n%_");
let lens = width_profile_style(&[(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)]);
// An empty look, ones whose group or compound path holds only a copy read from `%_` lines, and
// ones that hold only a path painted with nothing or a hidden painted path.
let unpainted = format!("u\n{}n\nU\n", rect_path(0.0, 3.0, 10.0, 7.0));
let invisible = format!("u\n1 Xw\n{RED}{}f\n0 Xw\nU\n", rect_path(0.0, 3.0, 10.0, 7.0));
for look in ["u\nU\n".to_string(), format!("u\nu\n%_{hidden_fill}\nU\nU\n"), format!("u\n*u\n%_{hidden_fill}\n*U\nU\n"), unpainted, invisible] {
let art_ = format!("{look}%_{hidden_line}S\n1 (Tapered) XW\n");
let r = read_ok(&format!("{lens}{}", layer(&art_)));
let a = art(&r.doc);
let [object] = a.as_slice() else { panic!("{look:?}: {a:#?}") };
assert!(matches!(object.kind, NodeKind::Path { .. }), "{look:?}: {object:#?}");
assert_eq!(object.appearance.stroke().map(|s| (s.width, s.profile.is_some())), Some((4.0, true)), "{look:?}: {object:#?}");
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{look:?}: {:?}", r.warnings);
}
}
#[test]
fn each_pathfinder_operation_on_a_group_draws_as_vectorcraft_draws_it() {
// GUARDS: only Add (`Command` 0) was read; the other operations came in as the drawn look's one path.
@@ -10119,3 +10342,258 @@ fn copies_of_a_multi_layer_mask_count_toward_the_limit() {
let e = read(mask_stream7(&filled).as_bytes()).unwrap_err();
assert!(e.contains("objects"), "{e}");
}
// ---- names that aren't UTF-8 ----------------------------------------------------------------
/// `body` read with its names that aren't UTF-8 in `encoding`.
fn read_names(body: &str, encoding: &str) -> Structure {
let encoding = NameEncoding::from_label(encoding).unwrap();
match super::read_in(stream(body).as_bytes(), true, encoding) {
Ok(s) => s,
Err(e) => panic!("{e}"),
}
}
/// The notes on names that weren't UTF-8.
fn name_notes(s: &Structure) -> Vec<&str> {
s.warnings.iter().map(String::as_str).filter(|w| w.contains("isn't UTF-8") || w.contains("aren't UTF-8")).collect()
}
/// A layer's name in a legacy code page (`(name) Ln`, the bytes as octal escapes) is read in the
/// encoding picked, with a note that names it and the encoding; one in UTF-8 is read as it is in
/// every encoding, without a note.
#[test]
fn layer_names_are_read_in_the_legacy_encoding_picked() {
let layer_named = |name: &str| {
format!(
"%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n({name}) Ln\n{RED}{}f\nLB\n%AI5_EndLayer--\n",
rect_path(0.0, 0.0, 10.0, 10.0)
)
};
for (encoding, bytes, want) in [
("windows-949", r"\267\271\300\314\276\356 1", "레이어 1"),
("shift_jis", r"\203\214\203C\203\204\201[ 1", "レイヤー 1"),
("gbk", r"\315\274\262\343 1", "图层 1"),
("big5", r"\271\317\274h 1", "圖層 1"),
("macintosh", r"Caf\216", "Café"),
("windows-1252", r"Caf\351", "Café"),
] {
let s = read_names(&layer_named(bytes), encoding);
assert_eq!(s.doc.layers[0].name.as_deref(), Some(want), "{encoding}");
assert_eq!(
name_notes(&s),
[format!("the name `{want}` isn't UTF-8 and was read as {encoding}: if it looks wrong, open the file with another legacyNameEncoding")],
"{encoding}"
);
let utf8 = read_names(&layer_named(r"\353\240\210\354\235\264\354\226\264 1"), encoding);
assert_eq!(utf8.doc.layers[0].name.as_deref(), Some("레이어 1"), "{encoding}");
assert!(name_notes(&utf8).is_empty(), "{encoding}: {:?}", utf8.warnings);
}
// By default the Korean bytes come in as Windows-1252, as before, now with the note. A comment
// in UTF-8 doesn't change how the names are read.
let s = read_names(&format!("%%Title: 레이어\n{}", layer_named(r"\267\271\300\314\276\356 1")), "windows-1252");
assert_eq!(s.doc.layers[0].name.as_deref(), Some("·¹À̾î 1"));
assert_eq!(
name_notes(&s),
["the name `·¹À̾î 1` isn't UTF-8 and was read as windows-1252: if it looks wrong, open the file with another legacyNameEncoding"]
);
// Bytes the encoding doesn't define come in as U+FFFD, and the note says so.
let s = read_names(&layer_named(r"\267\271\300 1"), "windows-949");
assert_eq!(s.doc.layers[0].name.as_deref(), Some("레\u{fffd} 1"));
assert_eq!(
name_notes(&s),
["the name `레\u{fffd} 1` isn't UTF-8, and parts of it aren't valid windows-949 either: open the file with another legacyNameEncoding"]
);
}
/// An object's name, an artboard's, a spot colour's and a pattern's are read in the encoding
/// picked too, and a fill names the pattern as its definition does, whichever encoding is picked.
#[test]
fn object_artboard_colour_and_pattern_names_are_read_in_the_encoding_picked() {
// 그라 (a pattern and a group), 빨강 (an artboard and a spot colour), 레이어 1 (the layer).
let (pattern, red, layer_name) = (r"\261\327\266\363", r"\273\241\260\255", r"\267\271\300\314\276\356 1");
let boards = format!(
"%_/Document :\n%_/Dictionary :\n%_/Array :\n\
%_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_200 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_({red}) /UnicodeString (Name) ,\n%_; ,\n\
%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"
);
let tile = DOTS.replace("(Dots)", &format!("({pattern})"));
let art_ = format!(
"0 Ae\nu\n0 1 1 0 ({red}) 0 x\n{}f\n({pattern}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\nU\n%_/ArtDictionary :\n%_({pattern}) /String (AIArtName) ,\n%_;\n9 () XW\n",
rect_path(0.0, 0.0, 10.0, 10.0),
rect_path(20.0, 0.0, 30.0, 10.0),
);
let body = format!("{boards}{tile}%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n({layer_name}) Ln\n{art_}LB\n%AI5_EndLayer--\n");
for (encoding, [pattern, red, layer_name]) in [("windows-949", ["그라", "빨강", "레이어 1"]), ("windows-1252", ["±×¶ó", "»¡°\u{ad}", "·¹À̾î 1"])]
{
let s = read_names(&body, encoding);
let doc = &s.doc;
assert_eq!(doc.layers[0].name.as_deref(), Some(layer_name), "{encoding}");
assert_eq!(doc.artboards.first().map(|a| a.name.as_str()), Some(red), "{encoding}");
let group = &art(doc)[0];
assert_eq!(group.name.as_deref(), Some(pattern), "{encoding}");
let kids = group.children().unwrap();
assert!(matches!(fill(&kids[0]), Paint::Solid { swatch: Some(s), .. } if s == red), "{encoding}: {:?}", fill(&kids[0]));
assert!(doc.swatch(red).is_some_and(|s| s.spot), "{encoding}");
assert!(matches!(fill(&kids[1]), Paint::Pattern { pattern: p, .. } if p == pattern), "{encoding}: {:?}", fill(&kids[1]));
assert!(doc.pattern(pattern).is_some(), "{encoding}");
assert!(s.unread.is_empty(), "{encoding}: {:?}", s.unread);
assert_eq!(name_notes(&s).len(), 3, "{encoding}: {:?}", s.warnings);
}
}
/// Past three names, the notes count the others in one.
#[test]
fn notes_on_names_that_arent_utf8_are_capped() {
let layers: String = (0..6)
.map(|i| {
format!(
"%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L{i} Caf\\216) Ln\n{RED}{}f\nLB\n%AI5_EndLayer--\n",
rect_path(0.0, 0.0, 10.0, 10.0)
)
})
.collect();
let s = read_names(&layers, "macintosh");
let names: Vec<_> = s.doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert!(names.iter().all(|n| n.ends_with(" Café")), "{names:?}");
let notes = name_notes(&s);
assert_eq!(notes.len(), 4, "{notes:?}");
assert_eq!(notes[3], "more names that aren't UTF-8 were read as macintosh (3)");
}
/// 빨강 and 그라 in code page 949, as octal escapes.
const KO_RED: &str = r"\273\241\260\255";
const KO_GRA: &str = r"\261\327\266\363";
/// A brush's name, the art it names and the brush manager's order are read in the encoding picked:
/// the brush finds its art and the order finds the brush, with a note on the brush and on its art.
#[test]
fn brush_names_are_read_in_the_encoding_picked() {
let params = SPRAY.replace("Dot art", KO_GRA);
let scatter = format!("%AI8_BeginPluginObject\n({SCATTER})\n({KO_RED})\n({params}) .\n%AI8_EndPluginObject\n");
let manager = brush::MANAGER;
let order = format!("%AI8_BeginPluginObject\n({manager})\n({manager})\n( {SCATTER}/ {KO_RED}/) .\n%AI8_EndPluginObject\n");
let body = format!("{}{order}{scatter}{}", brush_art(KO_GRA, 4.0), layer(""));
for (encoding, name) in [("windows-949", "빨강"), ("windows-1252", "»¡°\u{ad}")] {
let s = read_names(&body, encoding);
let lib = vectorcraft_brush::library(&s.doc);
assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), [name], "{encoding}: {:?}", s.warnings);
assert!(matches!(brush_named(&lib, name), vectorcraft_brush::BrushKind::Scatter(_)), "{encoding}");
assert_eq!(name_notes(&s).len(), 2, "{encoding}: {:?}", s.warnings);
}
}
/// A symbol's name, the instances that name it and the symbol list are read in the encoding
/// picked, with a note on each symbol.
#[test]
fn symbol_names_are_read_in_the_encoding_picked() {
let list = format!("%AI24_BeginSymbolList\n({KO_GRA})\n({KO_RED})\n%AI24_EndSymbolList\n");
let defs = symbols(&format!("{}{}{list}", symbol(KO_RED, &dot(), 5), symbol(KO_GRA, &dot(), 5)));
let s = read_names(&(defs + &layer(&instance(KO_RED, [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))), "windows-949");
let names: Vec<&str> = s.doc.symbols.iter().map(|d| d.name.as_str()).collect();
assert_eq!(names, ["그라", "빨강"], "{:?}", s.warnings);
assert!(matches!(&art(&s.doc)[0].kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "빨강"), "{:?}", art(&s.doc)[0].kind);
assert_eq!(name_notes(&s).len(), 2, "{:?}", s.warnings);
}
/// A symbol library read without its layers has notes on the names of the objects in its art.
#[test]
fn a_symbol_librarys_art_has_notes_on_its_object_names() {
let inner = format!("{}{}", dot(), vectorcraft_testkit::ai::named(KO_GRA));
let data = stream(&symbols(&symbol(KO_RED, &inner, 5)));
let mut names = obj::Names::new(NameEncoding::Korean);
assert!(super::symbols(data.as_bytes(), &mut names).is_some());
let notes = names.notes();
assert_eq!(notes.len(), 2, "{notes:?}");
assert!(notes.iter().any(|n| n.contains("`그라`")), "{notes:?}");
}
/// An object without a name of its own takes the one its XML id gives it, read in the encoding
/// picked, with a note on that name.
#[test]
fn an_object_named_by_its_xml_id_is_read_in_the_encoding_picked() {
let square = format!("{RED}{}f\n{}", rect_path(0.0, 0.0, 10.0, 10.0), vectorcraft_testkit::ai::named(&format!("{KO_RED}_1")));
let s = read_names(&layer(&square), "windows-949");
assert_eq!(art(&s.doc)[0].name.as_deref(), Some("빨강 1"), "{:?}", s.warnings);
let notes = name_notes(&s);
assert_eq!(notes.len(), 1, "{notes:?}");
assert!(notes[0].contains("`빨강 1`"), "{notes:?}");
}
/// The strings of a plug-in object that isn't a brush, and the name of a brush that isn't read,
/// have no notes.
#[test]
fn plug_in_objects_that_are_not_read_have_no_name_notes() {
let other = format!("%AI8_BeginPluginObject\n(Other Tool)\n({KO_RED})\n(x) .\n%AI8_EndPluginObject\n");
let broken = format!("%AI8_BeginPluginObject\n({SCATTER})\n({KO_GRA})\n(not a brush) .\n%AI8_EndPluginObject\n");
let s = read_names(&format!("{other}{broken}{}", layer("")), "windows-949");
assert!(name_notes(&s).is_empty(), "{:?}", s.warnings);
}
/// A graphic style's name, in the art styles and in the style list, and an object's link to it are
/// read in the encoding picked, with a note on the style.
#[test]
fn graphic_style_names_are_read_in_the_encoding_picked() {
let defs = [fill_style(KO_RED, "0 0 0 0 1 0 0 Xa\n")];
let s = read_names(&format!("{}{}", styles_and_list(&defs, &[KO_RED]), layer(&styled_square(KO_RED))), "windows-949");
assert_eq!(style_names(&s.doc), [("빨강".to_string(), 1)], "{:?}", s.warnings);
assert_eq!(art(&s.doc)[0].extras().graphic_style, Some(1), "{:?}", s.warnings);
assert_eq!(name_notes(&s).len(), 1, "{:?}", s.warnings);
}
/// A variable's and a data set's names are read in the encoding picked, each with a note, a name
/// written across two strings that end inside a character included. The element named after the
/// variable still names it, and the data set's text is read in the encoding too, without a note.
#[test]
fn variable_and_data_set_names_are_read_in_the_encoding_picked() {
let split_red = "\\273)\n%_(\\241\\260\\255";
let library = vectorcraft_testkit::ai::variable_library(&["QVARQ"], &["QSETQ"]).replace("QVARQ", split_red).replace("QSETQ", KO_GRA);
let s = read_names(&format!("{library}{}", layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0)))), "windows-949");
let vars = &s.doc.variables;
assert_eq!(vars.variables.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["빨강"], "{:?}", s.warnings);
assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(), ["그라"], "{:?}", s.warnings);
assert_eq!(vars.dataset("그라").and_then(|d| d.values.get("빨강")), Some(&vectorcraft_doc::DataValue::Text("그라 빨강".into())));
assert_eq!(name_notes(&s).len(), 2, "{:?}", s.warnings);
}
/// A binding names its variable by the name read in the encoding picked.
#[test]
fn a_bound_variables_name_is_read_in_the_encoding_picked() {
use vectorcraft_testkit::ai::{XmlValue, named, variable_library_data, xml_element, xml_node};
let attributes =
[("trait", XmlValue::Str("textcontent")), ("varName", XmlValue::Unicode("QVARQ")), ("docRef", XmlValue::Raw("/XMLUIDREF : (one) ;"))];
let variable = xml_node(1, "variable", XmlValue::Str(""), &attributes, &[]);
let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &[variable])]);
let library = variable_library_data(&xml_element("variableSets", &[], &[set])).replace("QVARQ", KO_RED);
let square = layer(&format!("{RED}{}f\n{}", rect_path(0.0, 0.0, 10.0, 10.0), named("one")));
let s = read_names(&format!("{library}{square}"), "windows-949");
assert_eq!(s.bindings, [BindingRef { variable: "빨강".into(), target: Some("one".into()) }], "{:?}", s.warnings);
assert_eq!(s.doc.variables.variables.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["빨강"]);
assert_eq!(name_notes(&s).len(), 1, "{:?}", s.warnings);
}
/// A custom color of the header is read in the encoding picked, so it is the color an object
/// names: one swatch comes in, with a note.
#[test]
fn a_custom_color_of_the_header_is_read_in_the_encoding_picked() {
let body = format!(
"%!PS-Adobe-3.0\n%%CMYKCustomColor: 0 1 1 0 ({KO_RED})\n%%EndComments\n{}",
layer(&format!("0 1 1 0 ({KO_RED}) 0 x\n{}f\n", rect_path(0.0, 0.0, 10.0, 10.0)))
);
let s = super::read_in(body.as_bytes(), true, NameEncoding::Korean).unwrap();
assert_eq!(s.doc.swatches.iter().filter(|w| w.spot).map(|w| w.name.as_str()).collect::<Vec<_>>(), ["빨강"], "{:?}", s.warnings);
assert_eq!(name_notes(&s).len(), 1, "{:?}", s.warnings);
}
/// A pattern's name in the version 7 form is read in the encoding picked, with a note, and a fill
/// that names it finds it.
#[test]
fn a_version_7_pattern_name_is_read_in_the_encoding_picked() {
let layers = "(0 g) @ (2 2 m 9 2 L 9 9 L f) &\n";
let fill_it = format!("({KO_RED}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(0.0, 0.0, 10.0, 10.0));
let stream = pattern_stream7(&pattern7(KO_RED, layers), &pattern_layer7("Art", &fill_it));
let s = super::read_in(stream.as_bytes(), true, NameEncoding::Korean).unwrap();
assert!(s.doc.pattern("빨강").is_some(), "{:?}", s.doc.patterns.iter().map(|p| &p.name).collect::<Vec<_>>());
assert!(matches!(fill(&art(&s.doc)[0]), Paint::Pattern { pattern, .. } if pattern == "빨강"), "{:?}", s.warnings);
assert_eq!(name_notes(&s).len(), 1, "{:?}", s.warnings);
}
+322 -61
View File
@@ -25,7 +25,10 @@ use std::collections::BTreeMap;
use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{CharStyle, Justify, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TextKind, TextObject, TextRun};
use vectorcraft_doc::{
CharStyle, HyphenationOptions, JustificationOptions, Justify, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TabAlign,
TabStop, TextKind, TextObject, TextRun,
};
use vectorcraft_geom::{Affine, PathData, Point, Rect};
/// Longest story read (bytes).
@@ -383,8 +386,33 @@ struct Para {
space_before: f64,
space_after: f64,
hyphenate: bool,
/// Key 7: the share of its type size a line takes as its auto leading (1.2: 120%, the default;
/// Justification… sets 0 to 500%:
/// https://helpx.adobe.com/illustrator/using/line-character-spacing.html). `None`: the default.
auto_leading: Option<f64>,
/// Keys 10 to 15, in the order of Paragraph panel menu › Hyphenation…: Words Longer Than,
/// After First, Before Last, Hyphen Limit, Hyphenation Zone (pt) and Hyphenate Capitalized
/// Words. A value that can't be read, or is out of its range, keeps the default.
hyphenation: HyphenationOptions,
/// Key 30, its list (key 0): the tab stops, each its position from the frame's left edge (key
/// 0) and alignment (key 1: 0 left, the default, 1 center, 2 right, 3 decimal, in the order of
/// the Tabs panel's buttons), sorted. A stop that can't be read is left out, and so are those
/// past the first [`MAX_TABS`]. Leaders aren't read.
tabs: Vec<TabStop>,
/// The paragraph has more than [`MAX_TABS`] stops: those past them were left out.
tabs_truncated: bool,
}
/// Most tab stops read for one paragraph.
const MAX_TABS: usize = 1024;
/// Largest tab stop position read (in the text document's units), as `text.tabs.set` takes it.
const MAX_TAB_POSITION: f64 = 100_000.0;
/// Most tab stops a story's paragraphs take in all: a paragraph style's stops are copied into
/// every paragraph that has them. The paragraphs past it take the default stops, with a warning.
const MAX_STORY_TABS: usize = 1 << 20;
/// The warning when [`MAX_STORY_TABS`] leaves tab stops out.
pub(crate) const TABS_LEFT_OUT: &str = "tab stops past VectorCraft's limits were left out";
/// The text of one story, in the units of the text document.
#[derive(Debug)]
pub(super) struct Story {
@@ -405,6 +433,20 @@ pub(super) struct Story {
/// Vertical type (Type › Type Orientation › Vertical): its lines are columns, from right to
/// left. Its layout's lines run down from the anchor, each column further left.
vertical: bool,
/// Tab stops past [`MAX_STORY_TABS`] were left out of its paragraphs.
tabs_left_out: std::cell::Cell<bool>,
}
/// Spend `budget` on the tab stops `tabs`: when there aren't enough left, they're left out (the
/// default stops apply). Whether they were.
fn spend_tabs(tabs: &mut Vec<TabStop>, budget: &mut usize) -> bool {
if tabs.len() <= *budget {
*budget -= tabs.len();
false
} else {
tabs.clear();
true
}
}
#[derive(Clone, Debug)]
@@ -607,7 +649,12 @@ impl Texts {
if runs.is_empty() {
runs.push((text.chars().count(), self.style(None)));
}
Some(Story { text, anchor, lines, frames, paras, runs, path_spacing, vertical })
let mut budget = MAX_STORY_TABS;
let mut tabs_left_out = false;
for (_, p) in &mut paras {
tabs_left_out |= p.tabs_truncated | spend_tabs(&mut p.tabs, &mut budget);
}
Some(Story { text, anchor, lines, frames, paras, runs, path_spacing, vertical, tabs_left_out: tabs_left_out.into() })
}
/// A paragraph's attributes (`run`: its attributes, key 5, and the paragraph style it is based
@@ -633,6 +680,46 @@ impl Texts {
space_before: num("4"),
space_after: num("5"),
hyphenate: !matches!(pick("9"), Some(Val::Bool(false))),
auto_leading: pick("7").and_then(Val::num).filter(|v| v.is_finite() && *v > 0.0 && *v <= 5.0),
hyphenation: {
let d = HyphenationOptions::default();
let count = |k: &str, lo: f64, hi: f64, or: u32| {
pick(k).and_then(Val::num).filter(|v| v.is_finite() && v.fract() == 0.0 && (lo..=hi).contains(v)).map_or(or, |v| v as u32)
};
HyphenationOptions {
words_longer_than: count("10", 1.0, 25.0, d.words_longer_than),
after_first: count("11", 1.0, 15.0, d.after_first),
before_last: count("12", 1.0, 15.0, d.before_last),
hyphen_limit: count("13", 0.0, 25.0, d.hyphen_limit),
zone: pick("14").and_then(Val::num).filter(|v| v.is_finite() && (0.0..=1296.0).contains(v)).unwrap_or(d.zone),
capitalized: match pick("15") {
Some(Val::Bool(b)) => *b,
_ => d.capitalized,
},
}
},
tabs_truncated: pick("30").and_then(|t| t.get("0")).map(Val::list).is_some_and(|list| list.len() > MAX_TABS),
tabs: {
let list = pick("30").and_then(|t| t.get("0")).map(Val::list).unwrap_or_default();
let mut tabs: Vec<TabStop> = list
.iter()
.take(MAX_TABS)
.filter_map(|t| {
let position = t.get("0").and_then(Val::num).filter(|p| (0.0..=MAX_TAB_POSITION).contains(p))?;
let align = match t.get("1").map(Val::num) {
None | Some(Some(0.0)) => TabAlign::Left,
Some(Some(1.0)) => TabAlign::Center,
Some(Some(2.0)) => TabAlign::Right,
Some(Some(3.0)) => TabAlign::Decimal,
_ => return None,
};
Some(TabStop { position, align, leader: String::new(), align_on: '.' })
})
.collect();
tabs.sort_by(|a, b| a.position.total_cmp(&b.position));
tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
tabs
},
}
}
@@ -1001,7 +1088,6 @@ impl Story {
// The text document measures in the art's units too: the document's scale carries its
// sizes and spacings onto the page (a Large Canvas copy is written at 1:10; #2031).
let scale = scale * art_scale(to_doc);
let leading = self.line_leading(scale);
let chars: Vec<char> = text.chars().collect();
let mut runs = vec![];
let mut from = 0usize;
@@ -1012,13 +1098,13 @@ impl Story {
if piece.is_empty() {
continue;
}
runs.push(TextRun::new(piece, char_style(st, scale, leading)));
runs.push(TextRun::new(piece, char_style(st, scale)));
}
if from < chars.len() {
let last = self.runs.last().map(|r| &r.1)?;
runs.push(TextRun::new(chars.get(from..).unwrap_or_default().iter().collect::<String>(), char_style(last, scale, leading)));
runs.push(TextRun::new(chars.get(from..).unwrap_or_default().iter().collect::<String>(), char_style(last, scale)));
}
let first = self.runs.first().map(|r| char_style(&r.1, scale, leading))?;
let first = self.runs.first().map(|r| char_style(&r.1, scale))?;
let mut t = TextObject::point(Point::ZERO, "", first);
if !runs.is_empty() {
t.runs = runs;
@@ -1065,6 +1151,21 @@ impl Story {
!self.lines.is_empty() && vectorcraft_text::fit_first_line(vectorcraft_text::FontDb::global(), t)
}
/// Area type of one frame that the file lays more lines out in than fit here: in the fallback
/// font, or a last line whose descent the file lets pass the frame's bottom. The frame is made
/// taller from its bottom (`vectorcraft_text::fit_source_lines`) so the file's lines show.
/// Whether it was.
pub(super) fn fit_last_lines(&self, t: &mut TextObject) -> bool {
matches!(self.frames.as_slice(), [FrameKind::Area(..)])
&& vectorcraft_text::fit_source_lines(vectorcraft_text::FontDb::global(), t, self.lines.len())
}
/// Were tab stops past [`MAX_STORY_TABS`] left out of its paragraphs (so far: making its text
/// object counts them again)?
pub(super) fn tabs_left_out(&self) -> bool {
self.tabs_left_out.get()
}
/// Area type (`node`, the story's first frame as [`Self::node`] makes it with `template` and
/// `to_doc`) whose first line the file lays out higher or lower than it is laid out here, as its
/// page draws it: its first baseline is fixed where the file has it. The font's ascent below the
@@ -1103,38 +1204,6 @@ impl Story {
true
}
/// The leading the file's own line positions imply: the distance from one line to the next, less
/// the space between paragraphs that is part of it (a paragraph's space after and the next one's
/// space before; a layout's lines are where that space has put them, and the text object adds it
/// again).
fn line_leading(&self, scale: f64) -> Option<f64> {
let para_at = |c: usize| {
let mut end = 0usize;
for (n, p) in &self.paras {
end = end.saturating_add(*n);
if c < end {
return Some(p);
}
}
self.paras.last().map(|(_, p)| p)
};
let chars: Vec<char> = self.text.chars().collect();
let breaks: Vec<usize> = chars.iter().enumerate().filter(|(_, c)| matches!(c, '\r' | '\x03')).map(|(i, _)| i).collect();
// More lines than breaks: area type wraps, and which break ends which line is unknown.
let wraps = self.lines.len() > breaks.len() + 1;
self.lines.windows(2).enumerate().find_map(|(i, w)| {
let pitch = w[1].1 - w[0].1;
let between = match breaks.get(i) {
Some(&at) if !wraps && chars.get(at) == Some(&'\r') => {
para_at(at).map_or(0.0, |p| p.space_after) + para_at(at + 1).map_or(0.0, |p| p.space_before)
}
_ => 0.0,
};
let l = (pitch - between) * scale;
(l.is_finite() && l > 0.0).then_some(l)
})
}
/// The style of each paragraph of `text` (paragraphs split at `\n`).
fn paragraph_styles(&self, text: &str, scale: f64) -> Vec<ParaStyle> {
let count = text.split('\n').count();
@@ -1142,9 +1211,13 @@ impl Story {
let mut runs = self.paras.iter();
let mut current = runs.next();
let mut left = current.map_or(usize::MAX, |r| r.0);
let mut budget = MAX_STORY_TABS;
for p in text.split('\n') {
let para = current.map(|r| r.1.clone()).unwrap_or_default();
out.push(para_style(&para, scale));
let mut style = current.map_or_else(|| para_style(&Para::default(), scale), |r| para_style(&r.1, scale));
if spend_tabs(&mut style.tabs, &mut budget) {
self.tabs_left_out.set(true);
}
out.push(style);
// Each paragraph and its ending `\r` count.
let mut used = p.chars().count() + 1;
while used > 0 {
@@ -1165,6 +1238,8 @@ impl Story {
}
}
/// The paragraph style of paragraph attributes `p`, its lengths (indents, spacing, the
/// hyphenation zone) scaled by `scale`, as sizes are.
fn para_style(p: &Para, scale: f64) -> ParaStyle {
ParaStyle {
justify: match p.justify {
@@ -1184,21 +1259,33 @@ fn para_style(p: &Para, scale: f64) -> ParaStyle {
space_before: p.space_before * scale,
space_after: p.space_after * scale,
hyphenate: p.hyphenate,
hyphenation: HyphenationOptions { zone: p.hyphenation.zone * scale, ..p.hyphenation.clone() },
tabs: p.tabs.iter().map(|t| TabStop { position: t.position * scale, ..t.clone() }).collect(),
// A right-to-left paragraph lays its text out from the right whatever letters it has
// (" 120.5 mm " reads "mm 120.5"); without the key, from its first strong letter.
direction: p.rtl.then_some(ParaDirection::RightToLeft),
justification: JustificationOptions {
// Rounded, so the file's 1.2 is the default 120% exactly.
auto_leading: p.auto_leading.map_or(JustificationOptions::default().auto_leading, |a| (a * 1e6).round() / 1e4),
..JustificationOptions::default()
},
..ParaStyle::default()
}
}
fn char_style(s: &Style, scale: f64, leading: Option<f64>) -> CharStyle {
/// The character style of character attributes `s`: its font from the fonts the app has, its
/// lengths (size, leading, baseline shift, stroke width) scaled by `scale`.
fn char_style(s: &Style, scale: f64) -> CharStyle {
let (family, style) = s.font.as_deref().map_or_else(|| (CharStyle::default().font_family, "Regular".to_string()), crate::family_style);
let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family);
CharStyle {
font_family: family,
font_style: style,
size: s.size * scale,
leading: s.leading.map(|l| l * scale).or(leading),
// Auto leading stays auto: the layout gives each line the paragraph's share of the largest
// type on it, as the file's own layout does ("The largest leading value in a line of type
// determines the leading for that line": https://helpx.adobe.com/illustrator/using/line-character-spacing.html).
leading: s.leading.map(|l| l * scale),
tracking: s.tracking,
baseline_shift: s.baseline_shift * scale,
h_scale: s.h_scale * 100.0,
@@ -1247,6 +1334,130 @@ mod tests {
assert_eq!(justify(b"/0 1 /33 0"), Justify::Right);
}
/// Key 7 is the paragraph's auto leading, a share of the type size; one that can't be read
/// leaves the default, 120%.
#[test]
fn a_paragraph_keeps_its_auto_leading() {
let texts = Texts {
stories: vec![],
fonts: vec![],
defaults: Val::Dict(BTreeMap::new()),
para_defaults: read(b"/7 1.2").unwrap(),
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
};
let auto = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justification.auto_leading;
assert_eq!(auto(b""), JustificationOptions::default().auto_leading);
assert_eq!(auto(b"/7 1.5"), 150.0);
assert_eq!(auto(b"/7 1.15"), 115.0);
for unreadable in [b"/7 0".as_slice(), b"/7 -1", b"/7 1e9", b"/7 /nil"] {
assert!((auto(unreadable) - 120.0).abs() < 1e-9, "{}", String::from_utf8_lossy(unreadable));
}
}
/// Keys 10 to 15 are the paragraph's hyphenation options; one that can't be read, or is out of
/// its range, keeps the default. The zone is in points of the text document, scaled as sizes are.
#[test]
fn a_paragraph_keeps_its_hyphenation_options() {
let texts = Texts {
stories: vec![],
fonts: vec![],
defaults: Val::Dict(BTreeMap::new()),
para_defaults: read(b"/10 6 /11 2 /12 2 /13 0 /14 36.0 /15 true").unwrap(),
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
};
let options = |own: &[u8], scale: f64| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), scale).hyphenation;
let want = HyphenationOptions { words_longer_than: 6, after_first: 2, before_last: 2, hyphen_limit: 0, zone: 36.0, capitalized: true };
assert_eq!(options(b"", 1.0), want);
assert_eq!(
options(b"/10 8 /13 3 /15 false", 0.5),
HyphenationOptions { words_longer_than: 8, hyphen_limit: 3, zone: 18.0, capitalized: false, ..want.clone() }
);
let d = HyphenationOptions::default();
let bare = Texts {
stories: vec![],
fonts: vec![],
defaults: Val::Dict(BTreeMap::new()),
para_defaults: Val::Dict(BTreeMap::new()),
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
};
let own = |own: &[u8]| para_style(&bare.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).hyphenation;
assert_eq!(own(b""), d);
assert_eq!(own(b"/10 0 /11 99 /12 2.5 /13 -1 /14 -3 /15 1"), d);
}
/// Key 30 holds the paragraph's tab stops: their positions (key 0), sorted, and alignments (key
/// 1: 0 left, 1 center, 2 right, 3 decimal), scaled as sizes are. A stop that can't be read is
/// left out. A user's price list keeps a right stop at 269.29 and a left one at 272.13.
#[test]
fn a_paragraph_keeps_its_tab_stops() {
let texts = Texts {
stories: vec![],
fonts: vec![],
defaults: Val::Dict(BTreeMap::new()),
para_defaults: Val::Dict(BTreeMap::new()),
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
};
let tabs = |own: &[u8], scale: f64| {
para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), scale)
.tabs
.iter()
.map(|t| (t.position, t.align))
.collect::<Vec<_>>()
};
assert_eq!(tabs(b"", 1.0), []);
assert_eq!(
tabs(b"/30 << /0 [ << /0 272.12598 /1 0 >> << /0 269.29135 /1 2 >> ] >>", 1.0),
[(269.29135, TabAlign::Right), (272.12598, TabAlign::Left)]
);
assert_eq!(
tabs(b"/30 << /0 [ << /0 10 /1 1 >> << /0 20 /1 3 >> << /0 30 >> ] >>", 0.5),
[(5.0, TabAlign::Center), (10.0, TabAlign::Decimal), (15.0, TabAlign::Left)]
);
// Past MAX_TABS stops, the rest are left out, and the paragraph says so (the story's warning).
let many = |n: usize| {
let stops: String = (0..n).map(|i| format!("<< /0 {i} >> ")).collect();
texts.para(Some(&read(format!("/5 << /30 << /0 [ {stops}] >> >>").as_bytes()).unwrap()))
};
let p = many(MAX_TABS + 6);
assert!(p.tabs_truncated && p.tabs.len() == MAX_TABS);
let p = many(MAX_TABS);
assert!(!p.tabs_truncated && p.tabs.len() == MAX_TABS);
// Unreadable: a position out of range or not a number, an unknown alignment.
assert_eq!(
tabs(b"/30 << /0 [ << /0 -1 >> << /0 1e9 >> << /0 /nil >> << /0 5 /1 7 >> << /0 6 /1 /x >> << /0 7 /1 2 >> ] >>", 1.0),
[(7.0, TabAlign::Right)]
);
}
/// A story's paragraphs take at most [`MAX_STORY_TABS`] tab stops in all (a paragraph style's
/// are copied into each paragraph): those past it take the default stops, and the story says so.
#[test]
fn a_story_s_tab_stops_are_bounded() {
let mut budget = 3;
let mut tabs = vec![TabStop { position: 1.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }; 2];
assert!(!spend_tabs(&mut tabs, &mut budget) && tabs.len() == 2 && budget == 1);
assert!(spend_tabs(&mut tabs, &mut budget) && tabs.is_empty() && budget == 1);
// Paragraphs of a style with MAX_TABS stops each, more than the story takes.
let stop = TabStop { position: 1.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
let para = Para { tabs: vec![stop; MAX_TABS], ..Para::default() };
let count = MAX_STORY_TABS / MAX_TABS + 2;
let s = story(&"a\r".repeat(count), &[0.0], &para);
assert!(!s.tabs_left_out());
let styles = s.paragraph_styles(&format!("{}a", "a\n".repeat(count - 1)), 1.0);
assert_eq!(styles.len(), count);
assert!(s.tabs_left_out());
assert_eq!(styles.iter().map(|p| p.tabs.len()).sum::<usize>(), MAX_STORY_TABS);
assert!(styles.last().is_some_and(|p| p.tabs.is_empty()));
}
/// Where point type lies runs along its baseline: a label turned a quarter (as a vertical
/// dimension's is) lies in a tall box, not a wide one.
#[test]
@@ -1636,6 +1847,7 @@ mod tests {
)],
path_spacing: 0.0,
vertical: false,
tabs_left_out: false.into(),
}
}
@@ -1882,25 +2094,54 @@ mod tests {
}
}
/// The baselines of the text object `story` comes in as, laid out.
fn baselines_of(story: &Story) -> Vec<f64> {
let Some(node) = story.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY) else { return vec![] };
let NodeKind::Text(t) = &node.kind else { return vec![] };
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).baselines().iter().map(|b| b.0.y).collect()
}
/// Auto leading stays auto: each line takes the paragraph's share of the largest type on it, as
/// the file's own layout does, not the distance between the first two lines for every line. A
/// 15 pt heading over 10 pt type at 120%: 18 pt between the heading's lines, then 12 pt.
#[test]
fn auto_leading_follows_the_size_of_each_line() {
let mut s = story("Big\x03Bigger\rsmall\r", &[0.0, 18.0, 30.0], &Para::default());
let base = s.runs[0].1.clone();
s.runs = vec![(11, Style { size: 15.0, ..base.clone() }), (6, Style { size: 10.0, ..base })];
assert_eq!(leading_of(&s), None);
let ys = baselines_of(&s);
assert_eq!(ys.len(), 3, "{ys:?}");
assert!(((ys[1] - ys[0]).abs() - 18.0).abs() < 1e-6, "{ys:?}");
assert!(((ys[2] - ys[1]).abs() - 12.0).abs() < 1e-6, "{ys:?}");
// At a share the paragraph sets (key 7) of 150%: 22.5 pt, then 15 pt.
let share = Para { auto_leading: Some(1.5), ..Para::default() };
s.paras = s.paras.iter().map(|(n, _)| (*n, share.clone())).collect();
let ys = baselines_of(&s);
assert!(((ys[1] - ys[0]).abs() - 22.5).abs() < 1e-6, "{ys:?}");
assert!(((ys[2] - ys[1]).abs() - 15.0).abs() < 1e-6, "{ys:?}");
}
#[test]
fn leading_leaves_out_the_space_between_paragraphs_that_the_lines_already_have() {
// Lines 10.6 apart that are three paragraphs with 5 less after each: auto leading (15.6) less 5.
let para = Para { space_after: -5.0, ..Para::default() };
// The text object keeps auto leading and the spacing, so its lines are where the file's are.
let s = story("one\rtwo\rthree\r", &[0.0, 10.6, 21.2], &para);
assert!((s.line_leading(1.0).unwrap() - 15.6).abs() < 1e-9);
assert!((leading_of(&s).unwrap() - 15.6).abs() < 1e-9);
// Space after and space before both count; the scale of the frame carries onto the leading.
assert_eq!(leading_of(&s), None);
let ys = baselines_of(&s);
assert!(ys.len() == 3 && ys.windows(2).all(|w| ((w[1] - w[0]).abs() - 10.6).abs() < 1e-6), "{ys:?}");
// Space after and space before both count.
let para = Para { space_after: 4.0, space_before: 2.0, ..Para::default() };
let s = story("one\rtwo\r", &[0.0, 20.0], &para);
assert!((s.line_leading(1.0).unwrap() - 14.0).abs() < 1e-9);
assert!((s.line_leading(0.5).unwrap() - 7.0).abs() < 1e-9);
let ys = baselines_of(&story("one\rtwo\r", &[0.0, 21.6], &para));
assert!(((ys[1] - ys[0]).abs() - 21.6).abs() < 1e-6, "{ys:?}");
}
/// #2031: a Large Canvas editing copy measures its text document in its art's units, a tenth
/// of the page's: the story's size and leading reach the page through `to_doc`'s scale.
#[test]
fn a_story_in_a_scaled_art_space_keeps_its_size_and_leading() {
let s = story("one\rtwo\r", &[0.0, 20.0], &Para::default());
let s = story("one\rtwo\r", &[0.0, 15.6], &Para::default());
// A copy written at 1:10 (see `ai::read::ensure_space`): its art's units reach the
// document, 100 points to the page, through `to_doc`'s scale.
let to_doc = Affine::scale(10.0) * Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]);
@@ -1909,24 +2150,18 @@ mod tests {
_ => panic!("not text"),
};
assert_eq!(t.runs[0].style.size, 130.0, "13 pt at the page's scale");
assert_eq!(t.runs[0].style.leading, Some(200.0), "a 20-unit line pitch at the page's scale");
assert_eq!(t.runs[0].style.leading, None, "auto leading: 120% of its size at the page's scale");
assert_eq!(t.para.justification.auto_leading, 120.0);
}
#[test]
fn leading_between_lines_of_a_paragraph_is_their_distance() {
// A line break inside a paragraph has no paragraph spacing between its lines.
let para = Para { space_after: -5.0, space_before: 3.0, ..Para::default() };
let s = story("one\x03two\x03three\r", &[0.0, 15.6, 31.2], &para);
assert!((s.line_leading(1.0).unwrap() - 15.6).abs() < 1e-9);
// Paragraphs without spacing: the distance as it was.
let s = story("one\rtwo\r", &[0.0, 15.6], &Para::default());
assert!((s.line_leading(1.0).unwrap() - 15.6).abs() < 1e-9);
// Area type whose paragraph wraps: lines and breaks don't pair up, so nothing is taken off.
let para = Para { space_after: -5.0, ..Para::default() };
let s = story("one two three\rfour\r", &[0.0, 15.6, 31.2, 41.8], &para);
assert!((s.line_leading(1.0).unwrap() - 15.6).abs() < 1e-9);
// One line has no distance to read.
assert_eq!(story("one\r", &[0.0], &Para::default()).line_leading(1.0), None);
let ys = baselines_of(&story("one\x03two\x03three\r", &[0.0, 15.6, 31.2], &para));
assert!(ys.len() == 3 && ys.windows(2).all(|w| ((w[1] - w[0]).abs() - 15.6).abs() < 1e-6), "{ys:?}");
// One line.
assert_eq!(baselines_of(&story("one\r", &[0.0], &Para::default())).len(), 1);
}
/// A `\x03` ends a line inside its paragraph: it comes in as a forced line break, and the
@@ -1970,6 +2205,32 @@ mod tests {
assert!(!story("Heading\r", &[], &Para::default()).fit_first_line(&mut t) && height(&t).unwrap().3 == 13.0);
}
/// The file sets three lines in a frame whose third line's descent passes its bottom: the frame
/// grows from its bottom so the third shows. Only when the story's one frame is area type.
#[test]
fn the_last_lines_the_file_sets_in_its_frame_show() {
let db = vectorcraft_text::FontDb::global();
let area = |height: f64| {
let mut t = TextObject::point(Point::ZERO, "one\ntwo\nthree", CharStyle { size: 13.0, ..CharStyle::default() });
t.kind = TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 20.0, 210.0, 20.0 + height)) };
t
};
let tall = vectorcraft_text::layout(db, &area(400.0));
let third = &tall.lines[2];
let mut t = area(third.baseline - 20.0 + third.descent / 2.0);
assert_eq!(vectorcraft_text::layout(db, &t).lines.len(), 2);
let mut s = story("one\rtwo\rthree\r", &[0.0, 15.6, 31.2], &Para::default());
// A point-type frame (the helper's) isn't fitted.
assert!(!s.fit_last_lines(&mut t));
s.frames = vec![FrameKind::Area(vec![], AreaFrame::default())];
assert!(s.fit_last_lines(&mut t));
assert_eq!(vectorcraft_text::layout(db, &t).lines.len(), 3);
// A story threaded through two frames: its lines are the first frame's alone.
let mut t = area(third.baseline - 20.0 + third.descent / 2.0);
s.frames.push(FrameKind::Area(vec![], AreaFrame::default()));
assert!(!s.fit_last_lines(&mut t));
}
#[test]
fn area_type_s_first_line_goes_where_the_file_lays_it_out() {
// GUARDS: area type's first baseline was the font's ascent below the frame's top, where the
+971
View File
@@ -0,0 +1,971 @@
//! CID-keyed fonts (PLRM 3rd ed., §5.11): CMaps built with the operators of the `CIDInit`
//! procedure set (and the predefined `Identity-H` and `Identity-V`), `composefont`, Type 0
//! fonts with `FMapType` 9 that map a show string's codes through their CMap to CIDs, and the
//! glyphs of the CIDFonts they select: Type 0 CIDFonts (Type 1 charstrings in the binary data
//! `StartData` reads, or in a `GlyphDirectory`: PLRM 3rd ed., §5.11.3, and Adobe Technical Note
//! #5014, "Adobe CMap and CIDFont Files Specification") and Type 2 CIDFonts (TrueType glyphs in
//! `sfnts`, picked through `CIDMap`). CIDs carry no characters: the glyphs are drawn from the
//! font's outlines, as a composite font's are.
use std::rc::Rc;
use skrifa::raw::ps::cff::CffFontRef;
use skrifa::raw::ps::cff::index::Index;
use skrifa::raw::ps::cs::{CharstringContext, CharstringKind, CommandSink, NopFilterSink, TransformSink};
use skrifa::raw::ps::error::Error as CsError;
use skrifa::raw::types::{Fixed, GlyphId};
use vectorcraft_geom::BezPath;
use super::interp::{Interp, matrix_obj};
use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err};
/// Most codespace ranges, character and notdef mappings a CMap may hold.
const MAX_RANGES: usize = 1 << 16;
/// Most bytes of glyph data a Type 0 CIDFont may carry.
const MAX_GLYPH_DATA: usize = 64 << 20;
/// Most CMaps whose mappings are kept read between shows.
const MAX_CMAPS: usize = 8;
/// Longest code a codespace range may give (PLRM 3rd ed., §5.11.5: the bytes of an integer).
const MAX_CODE: usize = 4;
/// The CMap entries the CIDInit operators fill: codespace ranges (`[lo hi …]`, strings), and
/// character and notdef mappings to CIDs (`[lo hi cid font …]`, the codes as strings).
const CODESPACE: &str = "CodeSpaceRange";
const CIDS: &str = "CIDRange";
const NOTDEFS: &str = "NotDefRange";
/// Mappings to a base font's character codes or glyph names (`[lo hi dst font …]`: `dst` a
/// string, a name, or an array of them, one a code).
const BASES: &str = "BFRange";
/// The mappings of the CMaps shown with so far, by their character mapping, codespace, notdef
/// mapping and base-font mapping arrays, the most recent last.
pub(super) type CMaps = Vec<([Option<Shared<Obj>>; 4], Rc<CMap>)>;
/// A CMap's mappings, read from its dictionary.
pub(super) struct CMap {
/// Codespace ranges: each byte's bounds.
space: Vec<Vec<(u8, u8)>>,
/// Character mappings (code length, first code, last code, first CID, font), latest first.
cids: Vec<(usize, u32, u32, u32, usize)>,
/// Notdef mappings, latest first.
notdefs: Vec<(usize, u32, u32, u32, usize)>,
/// Mappings to base-font codes or glyph names (code length, first code, last code, what
/// the first code maps to, font), latest first.
bases: Vec<(usize, u32, u32, Obj, usize)>,
}
/// What a code maps to in a base font (`beginbfchar`, `beginbfrange`).
#[derive(Clone)]
pub(super) enum Base {
Code(u8),
Name(Rc<str>),
}
/// A character of an `FMapType` 9 font: its code's descendant font and CID, and the notdef
/// mapping's CID for when that font has no glyph for it.
pub(super) struct CidChar {
pub font: usize,
pub cid: u32,
pub notdef: Option<u32>,
/// The base-font code or glyph name a `bfchar` or `bfrange` mapping gives it, instead of a
/// CID.
pub base: Option<Base>,
}
impl CMap {
/// The mappings of CMap dictionary `d`.
fn read(d: &Dict) -> Self {
let items = |k: &str| d.get(&Key::name(k)).and_then(|a| a.items().map(|i| i.to_vec())).unwrap_or_default();
let bytes = |o: &Obj| match o {
Obj::Str(s) => Some(s.to_vec()),
_ => None,
};
let space = items(CODESPACE)
.as_chunks::<2>()
.0
.iter()
.filter_map(|[lo, hi]| {
let (lo, hi) = (bytes(lo)?, bytes(hi)?);
(!lo.is_empty() && lo.len() == hi.len() && lo.len() <= MAX_CODE).then(|| lo.into_iter().zip(hi).collect())
})
.collect();
let maps = |k: &str| -> Vec<(usize, u32, u32, u32, usize)> {
items(k)
.as_chunks::<4>()
.0
.iter()
.rev()
.filter_map(|[lo, hi, cid, font]| {
let (lo, hi) = (bytes(lo)?, bytes(hi)?);
let cid = cid.as_num().filter(|c| (0.0..=f64::from(u32::MAX)).contains(c))? as u32;
let font = font.as_num().filter(|f| (0.0..=255.0).contains(f))? as usize;
(!lo.is_empty() && lo.len() == hi.len() && lo.len() <= MAX_CODE).then(|| (lo.len(), code(&lo), code(&hi), cid, font))
})
.collect()
};
let bases = items(BASES)
.as_chunks::<4>()
.0
.iter()
.rev()
.filter_map(|[lo, hi, dst, font]| {
let (lo, hi) = (bytes(lo)?, bytes(hi)?);
let font = font.as_num().filter(|f| (0.0..=255.0).contains(f))? as usize;
(!lo.is_empty() && lo.len() == hi.len() && lo.len() <= MAX_CODE).then(|| (lo.len(), code(&lo), code(&hi), dst.clone(), font))
})
.collect();
Self { space, cids: maps(CIDS), notdefs: maps(NOTDEFS), bases }
}
/// The characters of show string `s` (PLRM 3rd ed., §5.11.5 "CMap Mapping" and "Handling
/// Undefined Characters"), and how many ranges and mappings were compared to find them. It
/// stops once that passes `limit` (the characters found so far, and the work done).
pub fn decode(&self, s: &[u8], limit: u64) -> (Vec<CidChar>, u64) {
let mut out = Vec::with_capacity(s.len() / 2);
let mut work = 0u64;
let mut i = 0;
while let Some(rest) = s.get(i..).filter(|r| !r.is_empty() && work <= limit) {
let matched = (1..=MAX_CODE.min(rest.len())).find(|&n| {
work += self.space.len() as u64;
self.space.iter().any(|r| r.len() == n && fits(r, rest))
});
let n = match matched {
Some(n) => n,
// An invalid code: as many bytes as the best partly matching range's codes.
None => self.partial(rest),
};
let n = n.clamp(1, rest.len());
let c = code(rest.get(..n).unwrap_or_default());
let find = |maps: &[(usize, u32, u32, u32, usize)], work: &mut u64| {
let at = maps.iter().position(|m| m.0 == n && (m.1..=m.2).contains(&c));
*work += at.map_or(maps.len(), |k| k + 1) as u64;
at.and_then(|k| maps.get(k)).map(|m| (m.4, m.3.saturating_add(c - m.1), m.3))
};
let notdef = find(&self.notdefs, &mut work).map(|(_, _, base)| base);
let at = self.bases.iter().position(|m| m.0 == n && (m.1..=m.2).contains(&c));
work += at.map_or(self.bases.len(), |k| k + 1) as u64;
let base = at.and_then(|k| self.bases.get(k)).and_then(|m| Some((m.4, base_of(&m.3, c - m.1)?)));
out.push(match (matched.is_some(), find(&self.cids, &mut work), base) {
(true, Some((font, cid, _)), _) => CidChar { font, cid, notdef, base: None },
(true, None, Some((font, base))) => CidChar { font, cid: 0, notdef: None, base: Some(base) },
// No character mapping: the notdef mapping's CID, else font 0's CID 0.
_ => match find(&self.notdefs, &mut work) {
Some((font, _, base)) if matched.is_some() => CidChar { font, cid: base, notdef: None, base: None },
_ => CidChar { font: 0, cid: 0, notdef: None, base: None },
},
});
i += n;
}
(out, work)
}
/// How many bytes an invalid code at the start of `rest` takes: the length of the codes of
/// the range matching the most of its first bytes (the shortest of those), or of the
/// shortest range when none matches its first byte.
fn partial(&self, rest: &[u8]) -> usize {
let prefix = |r: &[(u8, u8)]| r.iter().zip(rest).take_while(|((lo, hi), b)| (lo..=hi).contains(b)).count();
let best = self.space.iter().map(|r| prefix(r)).max().unwrap_or(0);
let pick = self.space.iter().filter(|r| best == 0 || prefix(r) == best).map(Vec::len).min();
pick.unwrap_or(1)
}
}
/// What the code `k` codes after the first of a base-font mapping to `dst` maps to: a string's
/// code with its last byte that much higher, the `k`th of an array of codes and names, or a
/// name (TN #5099, `beginbfrange`).
fn base_of(dst: &Obj, k: u32) -> Option<Base> {
match dst {
// An array's elements are read as codes and names only: an array may hold itself, so
// reading its arrays in turn could recurse without end.
Obj::Array { items, .. } => base_of_leaf(items.borrow().get(usize::try_from(k).ok()?)?, 0),
_ => base_of_leaf(dst, k),
}
}
/// [`base_of`] for a string or a name.
fn base_of_leaf(dst: &Obj, k: u32) -> Option<Base> {
match dst {
Obj::Str(s) => {
let last = u32::from(s.len().checked_sub(1).and_then(|i| s.get(i))?).checked_add(k)?;
Some(Base::Code(u8::try_from(last).ok()?))
}
Obj::Name(n) if k == 0 => Some(Base::Name(n.clone())),
_ => None,
}
}
/// Does code `bytes` (as long as `range`, at least) start in codespace range `range`?
fn fits(range: &[(u8, u8)], bytes: &[u8]) -> bool {
range.len() <= bytes.len() && range.iter().zip(bytes).all(|((lo, hi), b)| (lo..=hi).contains(&b))
}
/// The number a code's bytes make, the first byte highest.
fn code(bytes: &[u8]) -> u32 {
bytes.iter().take(MAX_CODE).fold(0u32, |c, b| c << 8 | u32::from(*b))
}
/// The number `n` bytes at `at` of `data` make, the first byte highest.
fn number(data: &[u8], at: usize, n: usize) -> Option<u64> {
let bytes = data.get(at..at.checked_add(n)?)?;
(n <= 8).then(|| bytes.iter().fold(0u64, |v, b| v << 8 | u64::from(*b)))
}
/// How a predefined Unicode CMap's codes encode their characters.
#[derive(Clone, Copy, PartialEq, Debug)]
pub(super) enum Unicode {
/// Two bytes a character (`UCS2`) or a UTF-16 surrogate pair, the high byte first.
Utf16,
Utf8,
/// Four bytes, the high byte first.
Utf32,
}
/// The encoding of predefined Unicode CMap `name` and whether it is vertical: one of Adobe's
/// public CMap resources whose name says its codes are Unicode: `Uni` and a character
/// collection, then `-UCS2`, `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms),
/// then `-H` or `-V` (`UniJIS-UCS2-H`, `UniGB-UTF16-V`:
/// <https://github.com/adobe-type-tools/cmap-resources>).
pub(super) fn unicode_cmap(name: &str) -> Option<(Unicode, bool)> {
let (rest, dir) = name.rsplit_once('-')?;
let vertical = match dir {
"H" => false,
"V" => true,
_ => return None,
};
let rest = rest.strip_suffix("-HW").unwrap_or(rest);
let (collection, form) = rest.rsplit_once('-')?;
if !(collection.len() > 3 && collection.starts_with("Uni") && !collection.contains('-')) {
return None;
}
let form = match form {
"UCS2" | "UTF16" => Unicode::Utf16,
"UTF8" => Unicode::Utf8,
"UTF32" => Unicode::Utf32,
_ => return None,
};
Some((form, vertical))
}
/// The characters show string `s` encodes in Unicode form `form` (invalid codes left out).
pub(super) fn unicode_text(s: &[u8], form: Unicode) -> String {
match form {
Unicode::Utf16 => {
let units = s.as_chunks::<2>().0.iter().map(|b| u16::from_be_bytes(*b));
char::decode_utf16(units).filter_map(Result::ok).collect()
}
Unicode::Utf8 => String::from_utf8_lossy(s).chars().filter(|c| *c != char::REPLACEMENT_CHARACTER).collect(),
Unicode::Utf32 => s.as_chunks::<4>().0.iter().filter_map(|b| char::from_u32(u32::from_be_bytes(*b))).collect(),
}
}
/// A predefined Identity CMap: two-byte codes, each the CID of its own value; vertical for
/// `Identity-V`.
pub(super) fn identity(name: &str, vertical: bool) -> Obj {
let full = || Obj::string(vec![0xff, 0xff]);
let zero = || Obj::string(vec![0, 0]);
let mut d = Dict::new();
d.insert(Key::name("CMapName"), Obj::name(name));
d.insert(Key::name("CMapType"), Obj::Int(1));
d.insert(Key::name("WMode"), Obj::Int(i64::from(vertical)));
d.insert(Key::name(CODESPACE), Obj::array(vec![zero(), full()]));
d.insert(Key::name(CIDS), Obj::array(vec![zero(), full(), Obj::Int(0), Obj::Int(0)]));
Obj::dict(d)
}
impl Interp<'_> {
/// `composefont` and the operators of the `CIDInit` and `FontSetInit` procedure sets.
pub fn cid_op(&mut self, op: Op) -> Res {
use Op::*;
match op {
// A CMap's mappings take font 0 until its own `usefont` (Adobe Technical Note #5014).
BeginCMap => self.cmap_font = 0,
EndCMap | EndRearrangedFont => {}
BeginCodeSpaceRange | BeginBfChar | BeginBfRange | BeginCidChar | BeginCidRange | BeginNotDefChar | BeginNotDefRange => {
self.pop_int()?;
self.push(Obj::Mark)?;
}
EndCodeSpaceRange => {
let items = self.pop_mark_items()?;
if items.len() % 2 != 0 || !items.iter().all(|o| matches!(o, Obj::Str(_))) {
return ps_err("typecheck", "endcodespacerange");
}
self.cmap_append(CODESPACE, items)?;
}
EndCidChar | EndCidRange | EndNotDefChar | EndNotDefRange => {
let items = self.pop_mark_items()?;
let per = if matches!(op, EndCidChar | EndNotDefChar) { 2 } else { 3 };
if items.len() % per != 0 {
return ps_err("rangecheck", op.name());
}
let mut out = Vec::with_capacity(items.len() / per * 4);
for m in items.chunks_exact(per) {
let (lo, hi, cid) = match m {
[lo, cid] => (lo, lo, cid),
[lo, hi, cid] => (lo, hi, cid),
_ => return ps_err("rangecheck", op.name()),
};
if !(matches!(lo, Obj::Str(_)) && matches!(hi, Obj::Str(_)) && cid.as_num().is_some()) {
return ps_err("typecheck", op.name());
}
out.extend([lo.clone(), hi.clone(), cid.clone(), Obj::Int(self.cmap_font)]);
}
self.cmap_append(if matches!(op, EndCidChar | EndCidRange) { CIDS } else { NOTDEFS }, out)?;
}
// Mappings to character codes or names in base fonts (TN #5099, §§3.3 and 4).
EndBfChar | EndBfRange => {
let items = self.pop_mark_items()?;
let per = if op == EndBfChar { 2 } else { 3 };
if items.len() % per != 0 {
return ps_err("rangecheck", op.name());
}
let mut out = Vec::with_capacity(items.len() / per * 4);
for m in items.chunks_exact(per) {
let (lo, hi, dst) = match m {
[lo, dst] => (lo, lo, dst),
[lo, hi, dst] => (lo, hi, dst),
_ => return ps_err("rangecheck", op.name()),
};
if !(matches!(lo, Obj::Str(_)) && matches!(hi, Obj::Str(_)) && matches!(dst, Obj::Str(_) | Obj::Name(_) | Obj::Array { .. })) {
return ps_err("typecheck", op.name());
}
out.extend([lo.clone(), hi.clone(), dst.clone(), Obj::Int(self.cmap_font)]);
}
self.cmap_append(BASES, out)?;
}
UseFont => {
let n = self.pop_int()?;
self.cmap_font = n.clamp(0, 255);
}
UseCMap => {
let name = self.pop()?;
let parent = self.find_cmap(&name)?;
let d = self.dicts.last().cloned().ok_or(PsError::Ps("dictstackunderflow", "usecmap".into()))?;
for k in [CODESPACE, CIDS, NOTDEFS, BASES] {
// Both arrays are copied into a new one: charged by its size first, as
// `cmap_append` charges its copy, so `usecmap` of a large CMap in a loop runs
// out of the budgets instead of the memory.
let len = |c: &DictRef| c.borrow().get(&Key::name(k)).and_then(|a| a.items().map(|i| i.len())).unwrap_or(0);
let n = len(&parent).saturating_add(len(&d));
if n > MAX_RANGES * 4 {
return Err(PsError::Limit("a CMap has too many mappings"));
}
self.alloc(n.saturating_mul(std::mem::size_of::<Obj>()))?;
self.spend_bytes(n.saturating_mul(std::mem::size_of::<Obj>()))?;
let theirs = parent.borrow().get(&Key::name(k)).and_then(|a| a.items().map(|i| i.to_vec())).unwrap_or_default();
let ours = d.borrow().get(&Key::name(k)).and_then(|a| a.items().map(|i| i.to_vec())).unwrap_or_default();
// The parent's mappings first: the CMap's own come later and win.
let all: Vec<Obj> = theirs.into_iter().chain(ours).collect();
if all.len() > MAX_RANGES * 4 {
return Err(PsError::Limit("a CMap has too many mappings"));
}
self.insert(&d, Key::name(k), Some(Obj::array(all)))?;
}
let w = parent.borrow().get(&Key::name("WMode")).cloned();
if let Some(w) = w
&& !d.borrow().contains_key(&Key::name("WMode"))
{
self.insert(&d, Key::name("WMode"), Some(w))?;
}
}
BeginRearrangedFont => {
self.pop()?;
self.pop()?;
}
BeginUseMatrix => {
self.pop_int()?;
}
EndUseMatrix => {
self.pop()?;
}
StartData => self.start_data()?,
ComposeFont => self.compose_font()?,
_ => return ps_err("undefined", op.name()),
}
Ok(())
}
/// The operands down to the mark that a `begin…` operator pushed.
fn pop_mark_items(&mut self) -> Res<Vec<Obj>> {
let at = self.stack.iter().rposition(|o| matches!(o, Obj::Mark)).ok_or(PsError::Ps("unmatchedmark", String::new()))?;
self.spend((self.stack.len() - at) as u64)?;
let items = self.stack.split_off(at + 1);
self.stack.pop();
Ok(items)
}
/// `items` added to the CMap being defined (the current dictionary) under `key`.
fn cmap_append(&mut self, key: &str, items: Vec<Obj>) -> Res {
let d = self.dicts.last().cloned().ok_or(PsError::Ps("dictstackunderflow", key.into()))?;
let mut all = d.borrow().get(&Key::name(key)).and_then(|a| a.items().map(|i| i.to_vec())).unwrap_or_default();
if all.len().saturating_add(items.len()) > MAX_RANGES * 4 {
return Err(PsError::Limit("a CMap has too many mappings"));
}
self.alloc(items.len() * std::mem::size_of::<Obj>())?;
// The mappings so far are copied too: a CMap of many small blocks pays for each copy.
self.spend_bytes(all.len().saturating_mul(std::mem::size_of::<Obj>()))?;
all.extend(items);
self.insert(&d, Key::name(key), Some(Obj::array(all)))
}
/// CMap `name` (a name, or a CMap dictionary itself).
pub(super) fn find_cmap(&mut self, name: &Obj) -> Res<DictRef> {
if let Obj::Dict(d) = name {
return Ok(d.clone());
}
let key = name.key().ok_or(PsError::Ps("typecheck", "CMap".into()))?;
if let Some(Obj::Dict(d)) = self.instances(&Obj::name("CMap"))?.borrow().get(&key) {
return Ok(d.clone());
}
let text = name.text().map(|t| t.to_string()).unwrap_or_default();
match unicode_cmap(&text) {
Some((_, vertical)) => {
let mut d = Dict::new();
d.insert(Key::name("CMapName"), Obj::name(&text));
d.insert(Key::name("CMapType"), Obj::Int(1));
d.insert(Key::name("WMode"), Obj::Int(i64::from(vertical)));
Ok(DictRef::new(d))
}
None => Err(PsError::Ps("undefinedresource", text)),
}
}
/// CIDFont `name` (a name, or a dictionary itself): one the program defined, in the CIDFont
/// category or as a font, else a CIDFont of that name without glyphs (its glyphs show
/// nothing).
pub(super) fn find_cid_font(&mut self, name: &Obj) -> Res<DictRef> {
if let Obj::Dict(d) = name {
return Ok(d.clone());
}
let key = name.key().ok_or(PsError::Ps("typecheck", "composefont".into()))?;
if let Some(Obj::Dict(d)) = self.instances(&Obj::name("CIDFont"))?.borrow().get(&key) {
return Ok(d.clone());
}
if let Some(Obj::Dict(d)) = self.fonts.borrow().get(&key) {
return Ok(d.clone());
}
let mut d = Dict::new();
d.insert(Key::name("CIDFontName"), key.obj());
d.insert(Key::name("CIDFontType"), Obj::Int(0));
d.insert(Key::name("FontType"), Obj::Int(9));
d.insert(Key::name("FontMatrix"), matrix_obj(vectorcraft_geom::Affine::scale(0.001)));
Ok(DictRef::new(d))
}
/// `key cmap [fonts] composefont font`: a Type 0 font with `FMapType` 9 over `cmap` and the
/// CIDFonts (or fonts) named, defined as a font (PLRM 3rd ed., `composefont` in chapter 8).
fn compose_font(&mut self) -> Res {
let fonts = self.pop()?;
let cmap = self.pop()?;
let key = self.pop()?.key().ok_or(PsError::Ps("typecheck", "composefont".into()))?;
let names = fonts.items().map(|i| i.to_vec()).ok_or(PsError::Ps("typecheck", "composefont".into()))?;
let cmap = self.find_cmap(&cmap)?;
let mut deps = Vec::with_capacity(names.len());
for n in &names {
deps.push(Obj::Dict(self.find_cid_font(n)?));
}
let font = self.composed(key, cmap, deps);
self.push(Obj::Dict(font))
}
/// The Type 0 font `key` with `FMapType` 9 over CMap `cmap` and descendants `deps`, defined
/// as a font.
pub(super) fn composed(&mut self, key: Key, cmap: DictRef, deps: Vec<Obj>) -> DictRef {
let mut d = Dict::new();
d.insert(Key::name("FontName"), key.obj());
d.insert(Key::name("FontType"), Obj::Int(0));
d.insert(Key::name("FMapType"), Obj::Int(9));
d.insert(Key::name("FontMatrix"), matrix_obj(vectorcraft_geom::Affine::IDENTITY));
d.insert(Key::name("Encoding"), Obj::array((0..deps.len() as i64).map(Obj::Int).collect()));
d.insert(Key::name("FDepVector"), Obj::array(deps));
if let Some(w) = cmap.borrow().get(&Key::name("WMode")).cloned() {
d.insert(Key::name("WMode"), w);
}
d.insert(Key::name("CMap"), Obj::Dict(cmap));
let font = DictRef::new(d);
self.fonts.borrow_mut().insert(key, Obj::Dict(font.clone()));
font
}
/// `StartData`: `(Binary) n StartData` in a Type 0 CIDFont file reads its binary data section
/// (`n` bytes after the space that ends the name, or `n` bytes in hexadecimal for `(Hex)`)
/// into the CIDFont's `GlyphData`, defines the CIDFont (the current dictionary) as a resource
/// and ends it and the CIDInit dictionary under it (Adobe Technical Note #5014, §4.3). A
/// FontSet's `/name n StartData` (Compact Font Format data: PLRM 3rd ed., §5.8.1) defines its
/// CID-keyed fonts as CIDFonts (see [`Self::font_set`]); its other fonts are set as type by
/// name.
fn start_data(&mut self) -> Res {
// Glyph data is often larger than the most other operators take (`pop_count`).
let n = self.pop_int()?;
let kind = self.pop()?;
let f = self.running.last().cloned().unwrap_or_else(|| Rc::new(std::cell::RefCell::new(super::data::Stream::Current)));
if n < 0 {
return ps_err("rangecheck", "StartData");
}
let n = usize::try_from(n).unwrap_or(usize::MAX);
if n > MAX_GLYPH_DATA {
return Err(PsError::Limit("a font's data is too large"));
}
self.alloc(n)?;
self.spend((n / 256) as u64)?;
let hex = match &kind {
Obj::Str(s) => s.to_vec() == b"Hex",
_ => false,
};
let data = if hex {
let d = self.read_hex(&f, n)?;
// The data can end with the `>` of a hexadecimal string.
self.skip_hex_end(&f)?;
d
} else {
self.read(&f, n)?
};
if !matches!(kind, Obj::Str(_)) {
return self.font_set(data);
}
let d = self.dicts.last().cloned().ok_or(PsError::Ps("dictstackunderflow", "StartData".into()))?;
self.insert(&d, Key::name("GlyphData"), Some(Obj::string(data)))?;
// A Type 0 CIDFont without a matrix of its own: the 1000-unit glyph space of Type 1
// fonts, and each FDArray matrix scaled to it (PLRM 3rd ed., §5.11.3).
// The changes go through the journal, so `restore` undoes them as it does the program's.
if !d.borrow().contains_key(&Key::name("FontMatrix")) {
self.insert(&d, Key::name("FontMatrix"), Some(matrix_obj(vectorcraft_geom::Affine::scale(0.001))))?;
let fds = d.borrow().get(&Key::name("FDArray")).and_then(|a| a.items().map(|i| i.to_vec())).unwrap_or_default();
for fd in fds {
if let Obj::Dict(fd) = fd {
let m = fd.borrow().get(&Key::name("FontMatrix")).and_then(|o| o.items().and_then(|i| super::interp::matrix_of(&i.borrow())));
if let Some(m) = m {
self.insert(&fd, Key::name("FontMatrix"), Some(matrix_obj(vectorcraft_geom::Affine::scale(1000.0) * m)))?;
}
}
}
}
let name = d.borrow().get(&Key::name("CIDFontName")).and_then(Obj::key);
if let Some(k) = name {
self.instances(&Obj::name("CIDFont"))?.borrow_mut().insert(k, Obj::Dict(d.clone()));
}
if self.dicts.len() > 3 && self.dicts.last().is_some_and(|t| t.same(&d)) {
self.dicts.pop();
let cid_init = self.instances(&Obj::name("ProcSet"))?.borrow().get(&Key::name("CIDInit")).cloned();
if let (Some(Obj::Dict(p)), Some(top)) = (cid_init, self.dicts.last())
&& top.same(&p)
&& self.dicts.len() > 3
{
self.dicts.pop();
}
}
Ok(())
}
/// The CID-keyed fonts of FontSet data `data` (Compact Font Format: Adobe Technical Note
/// #5176, a top DICT with `ROS`), each defined as a Type 0 CIDFont of its name in the CFF's
/// Name INDEX, in glyph space of its units an em, whose glyphs are its Type 2 charstrings
/// picked by the CIDs its charset gives them.
fn font_set(&mut self, data: Vec<u8>) -> Res {
let data: Rc<[u8]> = data.into();
for index in 0..MAX_FONT_SET {
let Ok(font) = CffFontRef::new_cff(&data, index, None) else { break };
let Some(name) = font.metadata().and_then(|m| m.name().map(str::to_string)) else { continue };
if !font.is_cid() || self.cff.len() >= MAX_CFF {
continue;
}
let upem = f64::from(font.upem());
let upem = if upem.is_finite() && upem >= 1.0 { upem } else { 1000.0 };
let mut d = Dict::new();
d.insert(Key::name("CIDFontName"), Obj::name(&name));
d.insert(Key::name("CIDFontType"), Obj::Int(0));
d.insert(Key::name("FontType"), Obj::Int(9));
d.insert(Key::name("FontMatrix"), matrix_obj(vectorcraft_geom::Affine::scale(1.0 / upem)));
let d = DictRef::new(d);
self.instances(&Obj::name("CIDFont"))?.borrow_mut().insert(Key::name(&name), Obj::Dict(d.clone()));
self.cff.push((d, Rc::new(Cff::new(data.clone(), index))));
}
Ok(())
}
/// The mappings of CMap dictionary `d` (read once while it stays the same).
pub(super) fn cmap(&mut self, d: &DictRef) -> Res<Rc<CMap>> {
let array = |k: &str| d.borrow().get(&Key::name(k)).and_then(|a| a.items().cloned());
let key = [array(CIDS), array(CODESPACE), array(NOTDEFS), array(BASES)];
let same = |a: &Option<Shared<Obj>>, b: &Option<Shared<Obj>>| match (a, b) {
(Some(a), Some(b)) => a.same(b),
(None, None) => true,
_ => false,
};
if let Some((_, m)) = self.cmaps.iter().find(|(k, _)| k.iter().zip(&key).all(|(a, b)| same(a, b))) {
return Ok(m.clone());
}
let m = Rc::new(CMap::read(&d.borrow()));
self.spend((m.cids.len() + m.space.len() + m.notdefs.len() + m.bases.len()) as u64)?;
if self.cmaps.len() >= MAX_CMAPS {
self.cmaps.remove(0);
}
self.cmaps.push((key, m.clone()));
Ok(m)
}
/// Glyph `cid` of CIDFont `font`: its outline in the CIDFont's glyph space and its width
/// there, or `None` when the font has no glyph for it (or isn't a CIDFont with glyphs).
pub(super) fn cid_glyph(&mut self, font: &DictRef, cid: u32) -> Res<Option<(BezPath, f64)>> {
let (kind, count) = {
let f = font.borrow();
let num = |k: &str| f.get(&Key::name(k)).and_then(Obj::as_num);
(num("CIDFontType"), num("CIDCount"))
};
if count.is_some_and(|c| f64::from(cid) >= c) {
return Ok(None);
}
let glyph = match kind {
Some(2.0) => self.cid_type2(font, cid)?,
Some(0.0) => self.cid_type0(font, cid)?,
_ => None,
};
// Widths from the font's `Metrics` override the glyph's own (PLRM 3rd ed., §5.9.2).
Ok(glyph.map(|(outline, w)| {
let m = font.borrow().get(&Key::name("Metrics")).cloned();
let w = match m {
Some(Obj::Dict(m)) => match m.borrow().get(&Key::Int(i64::from(cid))) {
Some(o) => match o.as_num() {
Some(v) => v,
None => o
.items()
.and_then(|i| match i.len() {
2 => i.get(1).and_then(|v| v.as_num()),
4 => i.get(2).and_then(|v| v.as_num()),
_ => None,
})
.unwrap_or(w),
},
None => w,
},
_ => w,
};
(outline, if w.is_finite() { w } else { 0.0 })
}))
}
/// Glyph `cid` of a Type 2 CIDFont: the TrueType glyph its `CIDMap` gives it (a string, or
/// strings, of `GDBytes`-byte glyph indices by CID; a dictionary; or an integer added to the
/// CID: PLRM 3rd ed., §5.11.3), its width in ems.
fn cid_type2(&mut self, font: &DictRef, cid: u32) -> Res<Option<(BezPath, f64)>> {
let Some(data) = self.type42_data(font)? else { return Ok(None) };
let gid = {
let f = font.borrow();
let gd = f.get(&Key::name("GDBytes")).and_then(Obj::as_num).filter(|n| (1.0..=4.0).contains(n)).map_or(2, |n| n as usize);
match f.get(&Key::name("CIDMap")) {
None => Some(u64::from(cid)),
Some(Obj::Int(off)) => u64::try_from(i64::from(cid).saturating_add(*off)).ok(),
Some(Obj::Dict(d)) => d.borrow().get(&Key::Int(i64::from(cid))).and_then(Obj::as_num).filter(|g| *g >= 0.0).map(|g| g as u64),
Some(Obj::Str(s)) => (cid as usize).checked_mul(gd).and_then(|at| number(&s.borrow(), at, gd)),
Some(Obj::Array { items, .. }) => {
// The strings one after another, each a whole number of entries.
let Some(mut at) = (cid as usize).checked_mul(gd) else { return Ok(None) };
let mut found = None;
for s in items.borrow().iter() {
let Obj::Str(s) = s else { continue };
let s = s.borrow();
let len = s.len() - s.len() % gd;
if at < len {
found = number(&s, at, gd);
break;
}
at -= len;
}
found
}
Some(_) => None,
}
};
let Some(gid) = gid.and_then(|g| u32::try_from(g).ok()).filter(|g| *g <= u32::from(u16::MAX)) else { return Ok(None) };
if gid == 0 && cid != 0 {
return Ok(None);
}
Ok(super::type42::glyph(&data.data, gid))
}
/// Glyph `cid` of a Type 0 CIDFont: the Type 1 charstring its `GlyphDirectory` entry or
/// its binary data section's offset table gives it, run with the subroutines of its
/// FDArray dictionary's `Private` dictionary, in the FDArray dictionary's glyph space under
/// the CIDFont's; its width in the CIDFont's glyph space.
fn cid_type0(&mut self, font: &DictRef, cid: u32) -> Res<Option<(BezPath, f64)>> {
if let Some(cff) = self.cff.iter().find(|(k, _)| k.same(font)).map(|(_, c)| c.clone()) {
self.spend(64)?;
let read = cff.gids_read().is_some();
let glyph = cff.glyph(cid);
self.spend(cff.take_work())?;
// Reading the charset visits each of its glyphs.
if !read {
self.spend(cff.gids_read().unwrap_or(0) as u64)?;
}
return Ok(glyph);
}
let f = font.borrow();
let num = |k: &str, default: f64| f.get(&Key::name(k)).and_then(Obj::as_num).unwrap_or(default);
let fd_bytes = num("FDBytes", 0.0);
let gd_bytes = num("GDBytes", 0.0);
if !(0.0..=4.0).contains(&fd_bytes) || !(0.0..=4.0).contains(&gd_bytes) {
return Ok(None);
}
let (fd_bytes, gd_bytes) = (fd_bytes as usize, gd_bytes as usize);
let data: Option<Shared<u8>> = match f.get(&Key::name("GlyphData")) {
Some(Obj::Str(s)) => Some(s.clone()),
_ => None,
};
// The FDArray index and the charstring.
let found: Option<(usize, Vec<u8>)> = match f.get(&Key::name("GlyphDirectory")) {
Some(dir @ (Obj::Array { .. } | Obj::Dict(_))) => {
let entry = match dir {
Obj::Dict(d) => d.borrow().get(&Key::Int(i64::from(cid))).cloned(),
_ => dir.items().and_then(|i| i.get(cid as usize)),
};
match entry {
Some(Obj::Str(s)) => {
let s = s.to_vec();
let fd = number(&s, 0, fd_bytes).unwrap_or(0) as usize;
Some((fd, s.get(fd_bytes..).unwrap_or_default().to_vec()))
}
_ => None,
}
}
_ => data.as_ref().and_then(|data| {
let data = data.borrow();
let map = num("CIDMapOffset", 0.0);
if !(0.0..=data.len() as f64).contains(&map) {
return None;
}
let at = (map as usize).checked_add((cid as usize).checked_mul(fd_bytes + gd_bytes)?)?;
let fd = if fd_bytes == 0 { 0 } else { number(&data, at, fd_bytes)? as usize };
let start = number(&data, at + fd_bytes, gd_bytes)? as usize;
let end = number(&data, at + 2 * fd_bytes + gd_bytes, gd_bytes)? as usize;
Some((fd, data.get(start..end)?.to_vec()))
}),
};
let Some((fd, charstring)) = found.filter(|(_, c)| !c.is_empty()) else { return Ok(None) };
let Some(Obj::Dict(fd)) = f.get(&Key::name("FDArray")).and_then(|a| a.items().and_then(|i| i.get(fd))) else { return Ok(None) };
drop(f);
let fd = fd.borrow();
let fdm = fd
.get(&Key::name("FontMatrix"))
.and_then(|o| o.items().and_then(|i| super::interp::matrix_of(&i.borrow())))
.unwrap_or(vectorcraft_geom::Affine::IDENTITY);
let Some(Obj::Dict(private)) = fd.get(&Key::name("Private")).cloned() else { return Ok(None) };
drop(fd);
let len_iv = private.borrow().get(&Key::name("lenIV")).and_then(Obj::as_num).unwrap_or(4.0);
let subrs = self.cid_subrs(&private, data.as_ref(), len_iv)?;
self.spend((charstring.len() as u64).saturating_add(64))?;
let charstring = decrypt(&charstring, len_iv);
let (glyph, work) = type1_glyph(&charstring, &subrs);
// The subroutines it ran, which the evaluator limits for each glyph, not for the file.
self.spend(work)?;
let Some((outline, width)) = glyph else { return Ok(None) };
let mut outline = outline;
outline.apply_affine(fdm);
let w = fdm * vectorcraft_geom::Point::new(width, 0.0) - fdm * vectorcraft_geom::Point::ZERO;
Ok(Some((outline, w.x)))
}
/// The subroutines of a Type 0 CIDFont's FDArray `Private` dictionary `private`, decrypted
/// with `len_iv`: its `Subrs` array, else the subroutine table of the CIDFont's binary data
/// `data` (Adobe Technical Note #5014). Read once while they stay the same, and counted
/// against the budgets before they are copied.
fn cid_subrs(&mut self, private: &DictRef, data: Option<&Shared<u8>>, len_iv: f64) -> Res<Rc<Vec<Vec<u8>>>> {
let same_data = |d: &Option<Shared<u8>>| match (d, data) {
(Some(a), Some(b)) => a.same(b),
(None, None) => true,
_ => false,
};
if let Some(i) = self.cid_subrs.iter().position(|(p, d, _)| p.same(private) && same_data(d)) {
let hit = self.cid_subrs.remove(i);
let subrs = hit.2.clone();
self.cid_subrs.push(hit);
return Ok(subrs);
}
let p = private.borrow();
// Each subroutine's bytes: a string of `Subrs`, or a range of the binary data.
let strings: Option<Vec<Option<Shared<u8>>>> = match p.get(&Key::name("Subrs")) {
Some(Obj::Array { items, .. }) => Some(
items
.borrow()
.iter()
.map(|s| match s {
Obj::Str(s) => Some(s.clone()),
_ => None,
})
.collect(),
),
_ => None,
};
let mut ranges: Vec<Option<(usize, usize)>> = Vec::new();
if strings.is_none() {
let num = |k: &str| p.get(&Key::name(k)).and_then(Obj::as_num).filter(|n| *n >= 0.0);
if let (Some(map), Some(sd), Some(count), Some(data)) = (num("SubrMapOffset"), num("SDBytes"), num("SubrCount"), data) {
let data = data.borrow();
let (map, sd, count) = (map as usize, (sd as usize).min(4), (count as usize).min(MAX_RANGES));
for i in 0..count {
let at = map.saturating_add(i.saturating_mul(sd));
let range = number(&data, at, sd).zip(number(&data, at.saturating_add(sd), sd));
ranges.push(range.map(|(a, b)| (a as usize, b as usize)).filter(|(a, b)| a <= b && *b <= data.len()));
}
}
}
drop(p);
let total = match &strings {
Some(strings) => strings.iter().flatten().fold(0usize, |t, s| t.saturating_add(s.len())),
None => ranges.iter().flatten().fold(0usize, |t, (a, b)| t.saturating_add(b - a)),
};
if total > MAX_GLYPH_DATA {
return Err(PsError::Limit("a font's subroutines are too large"));
}
self.alloc(total)?;
self.spend_bytes(total)?;
self.spend((strings.as_ref().map_or(ranges.len(), Vec::len) / 16) as u64)?;
let subrs: Vec<Vec<u8>> = match (&strings, data) {
(Some(strings), _) => strings.iter().map(|s| s.as_ref().map(|s| decrypt(&s.borrow(), len_iv)).unwrap_or_default()).collect(),
(None, Some(data)) => {
let data = data.borrow();
ranges.iter().map(|r| r.and_then(|(a, b)| data.get(a..b)).map(|s| decrypt(s, len_iv)).unwrap_or_default()).collect()
}
(None, None) => vec![],
};
let subrs = Rc::new(subrs);
if self.cid_subrs.len() >= MAX_SUBR_SETS {
self.cid_subrs.remove(0);
}
self.cid_subrs.push((private.clone(), data.cloned(), subrs.clone()));
Ok(subrs)
}
}
/// Most fonts read from one FontSet.
const MAX_FONT_SET: u32 = 64;
/// Most CIDFonts read from FontSets.
const MAX_CFF: usize = 256;
/// A CID-keyed font in Compact Font Format data: the data and the font's index in it, and the
/// glyph its charset gives each CID (read when first asked).
pub(super) struct Cff {
data: Rc<[u8]>,
index: u32,
gids: std::cell::OnceCell<std::collections::HashMap<u16, GlyphId>>,
/// The charstring bytes glyphs entered, not yet charged.
work: std::cell::Cell<u64>,
}
impl Cff {
pub(super) fn new(data: Rc<[u8]>, index: u32) -> Self {
Self { data, index, gids: std::cell::OnceCell::new(), work: std::cell::Cell::new(0) }
}
/// Whether the CID-to-glyph map has been read, and the glyphs it holds.
fn gids_read(&self) -> Option<usize> {
self.gids.get().map(std::collections::HashMap::len)
}
/// Glyph `cid`: the glyph the charset gives that CID, drawn from its Type 2 charstring with
/// the subroutines and widths of its FDSelect subfont, in font units; `None` when the font
/// has no glyph for it.
pub(super) fn glyph(&self, cid: u32) -> Option<(BezPath, f64)> {
let font = CffFontRef::new_cff(&self.data, self.index, None).ok()?;
// The charset read once into a map, instead of searched for each glyph.
let gids = self.gids.get_or_init(|| font.charset().map(|c| c.iter().map(|(g, sid)| (sid.to_u16(), g)).collect()).unwrap_or_default());
let gid = *gids.get(&u16::try_from(cid).ok()?)?;
if gid.to_u32() == 0 && cid != 0 {
return None;
}
let sub = font.subfont(font.subfont_index(gid)?, &[]).ok()?;
// Run as `CffFontRef::draw` does, through the counting context, so the subroutines a
// glyph enters (up to a million operations each time) are paid for.
let subrs = match sub.subrs_offset() {
0 => Index::Empty,
at => Index::new(self.data.get(at as usize..)?, false).ok()?,
};
let charstrings = font.charstrings().clone();
let data = charstrings.get(gid.to_u32() as usize)?;
let ctx = (&self.data[..], &charstrings, font.global_subrs(), &subrs);
let mut pen = super::type42::Pen(BezPath::new(), 1.0);
let transform = font.transform(&sub, None);
let mut filter = NopFilterSink::new(&mut pen);
let mut sink = TransformSink::new(&mut filter, transform);
let (w, work) = super::type1::evaluate(&ctx, data, &mut sink);
self.work.set(self.work.get().saturating_add(work));
let w = w.ok()?.map(|w| w + sub.nominal_width()).or(sub.default_width());
let w = w.map_or(0.0, |w| f64::from(transform.transform_h_metric(w).to_f32().max(0.0)));
Some((pen.0, if w.is_finite() { w } else { 0.0 }))
}
/// The charstring bytes entered since the last call (see [`super::type1::evaluate`]).
pub(super) fn take_work(&self) -> u64 {
self.work.take()
}
}
/// Most FDArray dictionaries whose subroutines are kept decrypted between glyphs.
const MAX_SUBR_SETS: usize = 32;
/// The decrypted subroutines of FDArray `Private` dictionaries, by the dictionary and the
/// CIDFont's binary data (see [`Interp::cid_subrs`]), the most recently used last.
pub(super) type CidSubrs = Vec<(DictRef, Option<Shared<u8>>, Rc<Vec<Vec<u8>>>)>;
/// Type 1 charstring `data` decrypted (the charstring key 4330, the first `len_iv` bytes
/// dropped: Adobe Type 1 Font Format, §7.2); as it is when `len_iv` is negative.
pub(super) fn decrypt(data: &[u8], len_iv: f64) -> Vec<u8> {
if len_iv < 0.0 {
return data.to_vec();
}
let mut r: u16 = 4330;
let plain = data.iter().map(|&c| {
let p = c ^ (r >> 8) as u8;
r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719);
p
});
plain.skip(len_iv.min(64.0) as usize).collect()
}
/// The outline (glyph space) and width of decrypted Type 1 charstring `data`, with
/// subroutines `subrs`, or `None` when it can't be run; and the bytes of the charstrings it
/// entered (see [`super::type1::evaluate`]).
pub(super) fn type1_glyph(data: &[u8], subrs: &[Vec<u8>]) -> (Option<(BezPath, f64)>, u64) {
let ctx = Type1 { subrs };
let mut sink = Sink(BezPath::new());
let (w, work) = super::type1::evaluate(&ctx, data, &mut sink);
(w.ok().map(|w| (sink.0, w.map_or(0.0, |w| f64::from(w.to_f32())))), work)
}
/// What a Type 1 charstring runs with: its font's subroutines (no `seac` accents: a CIDFont's
/// glyphs have no names to build them from).
struct Type1<'a> {
subrs: &'a [Vec<u8>],
}
impl CharstringContext for Type1<'_> {
fn kind(&self) -> CharstringKind {
CharstringKind::Type1
}
fn seac_components(&self, base: i32, _accent: i32) -> Result<[&[u8]; 2], CsError> {
Err(CsError::InvalidSeacCode(base))
}
fn global_subr(&self, _index: i32) -> Result<&[u8], CsError> {
Err(CsError::MissingSubroutines)
}
fn subr(&self, index: i32) -> Result<&[u8], CsError> {
usize::try_from(index).ok().and_then(|i| self.subrs.get(i)).map(Vec::as_slice).ok_or(CsError::MissingSubroutines)
}
}
/// A charstring's path, in glyph space.
struct Sink(BezPath);
impl CommandSink for Sink {
fn move_to(&mut self, x: Fixed, y: Fixed) {
self.0.move_to((f64::from(x.to_f32()), f64::from(y.to_f32())));
}
fn line_to(&mut self, x: Fixed, y: Fixed) {
self.0.line_to((f64::from(x.to_f32()), f64::from(y.to_f32())));
}
fn curve_to(&mut self, cx0: Fixed, cy0: Fixed, cx1: Fixed, cy1: Fixed, x: Fixed, y: Fixed) {
let p = |a: Fixed, b: Fixed| (f64::from(a.to_f32()), f64::from(b.to_f32()));
self.0.curve_to(p(cx0, cy0), p(cx1, cy1), p(x, y));
}
fn close(&mut self) {
self.0.close_path();
}
}
+80 -14
View File
@@ -196,7 +196,7 @@ impl Interp<'_> {
}
/// Up to `n` bytes of file `f`.
fn read(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
pub(in super::super) fn read(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
self.materialize(f)?;
Ok(match &mut *f.borrow_mut() {
Stream::Current => {
@@ -236,7 +236,7 @@ impl Interp<'_> {
}
/// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped).
fn read_hex(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
pub(in super::super) fn read_hex(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
let mut out = Vec::with_capacity(n);
let mut high: Option<u8> = None;
while out.len() < n {
@@ -250,6 +250,31 @@ impl Interp<'_> {
Ok(out)
}
/// Skip the whitespace and the `>` that end hexadecimal data in `f`, if a `>` is next: the
/// rest is left unread.
pub(in super::super) fn skip_hex_end(&mut self, f: &Rc<RefCell<Stream>>) -> Res {
self.materialize(f)?;
let blank = |b: &u8| b.is_ascii_whitespace() || *b == 0;
match &mut *f.borrow_mut() {
Stream::Current => {
let rest = self.lex.data();
let n = rest.iter().take_while(|b| blank(b)).count();
if rest.get(n) == Some(&b'>') {
self.lex.advance(n + 1);
}
}
Stream::Buf { data, pos, .. } => {
let rest = data.get(*pos..).unwrap_or_default();
let n = rest.iter().take_while(|b| blank(b)).count();
if rest.get(n) == Some(&b'>') {
*pos += n + 1;
}
}
Stream::Pending { .. } => {}
}
Ok(())
}
/// Read bytes `got` into string `s` and push the part of `s` they fill.
fn fill(&mut self, s: Shared<u8>, got: &[u8]) -> Res {
if !s.write(0, got) {
@@ -451,6 +476,10 @@ impl Interp<'_> {
continue;
}
let want = step.min(n - o.len());
// The bytes of this read's own copy of a procedure's string: counted while it
// lives, released once it is appended (the string itself is the program's, and
// stays counted as long as the program can hold it).
let mut copied = 0;
let chunk = match src {
Source::File(f) => self.read(f, want)?,
// A string gives its bytes over and over.
@@ -462,26 +491,31 @@ impl Interp<'_> {
self.call(p.clone())?;
let s = self.pop_str()?.to_vec();
self.alloc(s.len())?;
copied = s.len();
s
}
};
*e = chunk.is_empty();
o.extend_from_slice(chunk.get(..chunk.len().min(n - o.len())).unwrap_or_default());
drop(chunk);
self.unalloc(copied);
}
}
Ok(out)
}
/// `file eexec`: an encrypted font program follows in `file`. It is skipped there, up to the
/// `cleartomark` that ends it (type is drawn in the app's fonts, by name): the font
/// dictionary it would complete is defined as it is.
/// `file eexec`: an encrypted font program follows in `file`. It isn't run: it is skipped
/// there, up to the `cleartomark` that ends it, and the font dictionary it would complete is
/// defined as it is, with the glyphs the Type 1 font parser reads from it (see `type1`).
fn eexec(&mut self) -> Res {
let src = self.pop()?;
let mut font = None;
if let Some(Obj::Dict(d)) = self.stack.last().cloned() {
let name = d.borrow().get(&Key::name("FontName")).cloned();
if let Some(k) = name.and_then(|n| n.key()) {
self.pop()?;
self.fonts.borrow_mut().insert(k, Obj::Dict(d));
self.fonts.borrow_mut().insert(k, Obj::Dict(d.clone()));
font = Some(d);
}
}
// `currentfile eexec`: the program's own file or the file being run. A string operand
@@ -492,15 +526,31 @@ impl Interp<'_> {
};
self.materialize(&f)?;
let missing = || PsError::Ps("ioerror", "eexec".into());
match &mut *f.borrow_mut() {
// The encrypted part, for the font's glyphs (a font's, of a size that can be read).
// Copied only when the font can still be kept (it is dropped otherwise).
let room = font.is_some() && self.type1_room();
let keep = |part: &[u8]| (room && part.len() <= super::super::type1::MAX_PROGRAM).then(|| part.to_vec());
let (encrypted, scanned) = match &mut *f.borrow_mut() {
Stream::Buf { data, pos, .. } => {
let at = find(data.get(*pos..).unwrap_or_default(), b"cleartomark").ok_or_else(missing)?;
let rest = data.get(*pos..).unwrap_or_default();
let at = find(rest, b"cleartomark").ok_or_else(missing)?;
let part = keep(rest.get(..at).unwrap_or_default());
*pos += at;
(part, at)
}
_ => {
let at = find(self.lex.data(), b"cleartomark").ok_or_else(missing)?;
let rest = self.lex.data();
let at = find(rest, b"cleartomark").ok_or_else(missing)?;
let part = keep(rest.get(..at).unwrap_or_default());
self.lex.advance(at);
(part, at)
}
};
// The search for `cleartomark` read the part: charged by its length (as `search` is), so `eexec` on a
// large reusable file in a loop runs out of the budget.
self.spend((scanned / 64) as u64)?;
if let (Some(d), Some(part)) = (font, encrypted) {
self.attach_type1(&d, &part)?;
}
self.push(Obj::Mark)
}
@@ -549,12 +599,16 @@ impl Interp<'_> {
}
return Ok(None);
}
// Interleaved data is read into this decoder's own buffers, split into the two images'
// samples: those stop counting once both are decoded (their pixels still count).
let mut charged = 0;
if interleave != 3.0 {
let src = image.sources.first().cloned().ok_or(PsError::Ps("undefined", "DataSource".into()))?;
let (pixels, samples) = if interleave == 2.0 {
let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n));
let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h));
self.alloc(total)?;
charged = total;
let raw = self.source_bytes(&src, total.min(MAX_DATA))?;
by_rows(&raw, (mrow, stencil.h), (drow, image.h))
} else {
@@ -562,15 +616,21 @@ impl Interp<'_> {
stencil.bpc = image.bpc;
(stencil.w, stencil.h) = (image.w, image.h);
let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8);
self.alloc(row.saturating_mul(image.h))?;
let raw = self.source_bytes(&src, row.saturating_mul(image.h).min(MAX_DATA))?;
charged = row.saturating_mul(image.h);
self.alloc(charged)?;
let raw = self.source_bytes(&src, charged.min(MAX_DATA))?;
by_samples(&raw, image.w, image.h, n, image.bpc)
};
stencil.sources = vec![Source::Str(pixels)];
image.sources = vec![Source::Str(samples)];
}
let Some(mut img) = self.decode_image(image)? else { return Ok(None) };
let Some(m) = self.decode_image(stencil)? else { return Ok(Some(img)) };
let decoded = match self.decode_image(image) {
Ok(Some(img)) => self.decode_image(stencil).map(|m| Some((img, m))),
other => other.map(|_| None),
};
self.unalloc(charged);
let Some((mut img, m)) = decoded? else { return Ok(None) };
let Some(m) = m else { return Ok(Some(img)) };
let (w, h, mw, mh) = (img.w as usize, img.h as usize, m.w as usize, m.h as usize);
for (i, px) in img.rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let (x, y) = (i % w, i / w);
@@ -689,7 +749,11 @@ impl Interp<'_> {
return ps_err("rangecheck", "DataSource");
}
let plane = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA).ok_or(PsError::Limit("decoded data is too large"))?;
self.alloc(plane.saturating_mul(sources.len()))?;
// The sample planes are this decoder's own and live only while the image is decoded: they
// stop counting once it is (the pixels made from them still count). What the data source
// procedures allocate is the program's and stays counted.
let plane_bytes = plane.saturating_mul(sources.len());
self.alloc(plane_bytes)?;
let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?;
for p in &mut planes {
p.resize(row * s.h, 0);
@@ -766,6 +830,8 @@ impl Interp<'_> {
rgba.extend([rgb[0], rgb[1], rgb[2], if masked { 0 } else { 255 }]);
}
}
drop(planes);
self.unalloc(plane_bytes);
Ok(Some(Pixels { w: s.w as u32, h: s.h as u32, rgba, inks, matrix: s.matrix }))
}
+20 -1
View File
@@ -292,7 +292,9 @@ impl Interp<'_> {
// there are too many).
let mut visits = 0;
let points = linear_points(&f, 0, &mut visits).filter(|p| p.len() <= MAX_STITCH_STOPS);
let stitched = points.is_some();
// A sampled function is continuous: no hard colour changes at its samples.
let stitched =
points.is_some() && !matches!(&f, Obj::Dict(d) if d.borrow().get(&Key::name("FunctionType")).and_then(Obj::as_num) == Some(0.0));
let ts: Vec<f64> = match points {
Some(mut pts) => {
pts.retain(|t| (d0.min(d1)..=d0.max(d1)).contains(t));
@@ -452,6 +454,23 @@ fn linear_points(f: &Obj, depth: u32, visits: &mut usize) -> Option<Vec<f64>> {
let num = |k: &str| d.get(&Key::name(k)).and_then(Obj::as_num);
match num("FunctionType")? {
2.0 if num("N").unwrap_or(1.0) == 1.0 => Some(vec![]),
// A sampled function of one input, interpolated linearly: straight between its samples.
0.0 if depth == 0 && num("Order").unwrap_or(1.0) == 1.0 => {
let nums = |k: &str| -> Vec<f64> {
d.get(&Key::name(k)).and_then(Obj::items).map(|i| i.borrow().iter().filter_map(Obj::as_num).collect()).unwrap_or_default()
};
let (domain, size, encode) = (nums("Domain"), nums("Size"), nums("Encode"));
let ([a, b], [s]) = (<[f64; 2]>::try_from(domain).ok()?, <[f64; 1]>::try_from(size).ok()?);
if !(1.0..=MAX_STITCH_STOPS as f64).contains(&s) || !a.is_finite() || !b.is_finite() {
return None;
}
let (e0, e1) = (encode.first().copied().unwrap_or(0.0), encode.get(1).copied().unwrap_or(s - 1.0));
if e1 == e0 || !e0.is_finite() || !e1.is_finite() {
return None;
}
// Where each sample index `k` falls in the domain, through `Encode`.
Some((0..s as usize).map(|k| a + (k as f64 - e0) * (b - a) / (e1 - e0)).filter(|x| x.is_finite()).collect())
}
3.0 => {
let items = d.get(&Key::name("Functions"))?.items()?;
// More pieces than the stop cap allows: sample the function instead (tested before
+14
View File
@@ -115,6 +115,9 @@ impl Default for GState {
}
}
/// Most families listed in the warning about fonts that aren't available.
const MAX_MISSING_FONTS: usize = 64;
/// What the program draws.
pub(crate) struct Out {
/// The document being made: ids, images and swatches.
@@ -152,6 +155,9 @@ pub(crate) struct Out {
pub(super) tilings: HashMap<u64, Vec<Tiling>>,
/// How deep art drawn apart (a pattern's cell, a Type 3 glyph) is nested.
pub apart: u32,
/// The families type was set in that aren't available (it shows in the fallback font), each
/// once in the order first set, for the import's warning.
pub missing_fonts: Vec<String>,
}
fn sane(r: Rect) -> bool {
@@ -201,6 +207,14 @@ impl Out {
shadings: HashSet::new(),
tilings: HashMap::new(),
apart: 0,
missing_fonts: vec![],
}
}
/// Note that type was set in `family`, which isn't available (at most [`MAX_MISSING_FONTS`]).
pub fn missing_font(&mut self, family: &str) {
if !family.is_empty() && self.missing_fonts.len() < MAX_MISSING_FONTS && !self.missing_fonts.iter().any(|f| f == family) {
self.missing_fonts.push(family.to_string());
}
}
Loaded 100 of 279 files, more files were not shown because too many files have changed in this diff. Show more