diff --git a/Cargo.lock b/Cargo.lock index 404abacf88..93ae3be0f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index 6dbf4a4d0a..375b17a3e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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 diff --git a/ROADMAP.md b/ROADMAP.md index 1bedf0b95c..fbe2334000 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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 | diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 8fc2661dc1..734f8a0569 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -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 = None; let mut headless = false; + let mut allow_grants = false; let (mut read_roots, mut write_roots): (Vec, Vec) = (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 `".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::, None::, None::, false, false, false, false); let mut ppi = None::; let mut decimals = None::; + // 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::; // 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::; let mut ppi = None::; + 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::().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. diff --git a/apps/vectorcraft-cli/tests/it/cli.rs b/apps/vectorcraft-cli/tests/it/cli.rs index 05a5cc5fc6..f2600d9b4f 100644 --- a/apps/vectorcraft-cli/tests/it/cli.rs +++ b/apps/vectorcraft-cli/tests/it/cli.rs @@ -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 = 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(); diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 4ab382d5cb..dfd9b16719 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -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" diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 2dfc4e6f4c..fa0f0dca29 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -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. diff --git a/apps/vectorcraft/src/mac_cursor.rs b/apps/vectorcraft/src/mac_cursor.rs new file mode 100644 index 0000000000..85fea6c78a --- /dev/null +++ b/apps/vectorcraft/src/mac_cursor.rs @@ -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> { + 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; + 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; + fn current(&self) -> Option; + fn set(&mut self, cursor: &Self::Cursor); +} + +struct State { + backend: B, + candidate: Option, + cache: Vec<(Key, Option)>, + // Retain the active object independently of cache eviction. + active: Option<(Key, B::Window, B::Cursor)>, +} + +impl State { + 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) { + 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, +} +impl Backend for AppKit { + type Window = Retained; + type Cursor = Retained; + fn window(&self) -> Option { + 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 { + build(&request.bitmap) + } + fn current(&self) -> Option { + Some(NSCursor::currentCursor()) + } + fn set(&mut self, cursor: &Self::Cursor) { + cursor.set(); + } +} + +thread_local! { static STATE: RefCell> = RefCell::new(State::new(AppKit::default())); } + +fn with_state(f: impl FnOnce(&mut State)) { + // 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, +} + +struct Delivery { + begin: fn(), + finish: fn(Option), + release: fn(), + tracking: fn() -> bool, + ended: Vec, +} + +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>) { + 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; diff --git a/apps/vectorcraft/src/mac_cursor/tests.rs b/apps/vectorcraft/src/mac_cursor/tests.rs new file mode 100644 index 0000000000..648492c4b2 --- /dev/null +++ b/apps/vectorcraft/src/mac_cursor/tests.rs @@ -0,0 +1,236 @@ +use super::*; +use egui::{CursorIcon, RawInput}; +use std::cell::Cell; + +#[derive(Default)] +struct Fake { + window: Option, + suspended: Vec, + current: Option, + sets: usize, + builds: usize, + restores: Vec, + fail: bool, +} +impl Backend for Fake { + type Window = u8; + type Cursor = Key; + fn window(&self) -> Option { + 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 { + self.builds += 1; + (!self.fail).then_some(r.key) + } + fn current(&self) -> Option { + self.current + } + fn set(&mut self, cursor: &Key) { + self.current = Some(*cursor); + self.sets += 1; + } +} +fn fake_state() -> State { + 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, request: Option) { + 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> = RefCell::new(fake_state()); + static TRACKING: Cell = 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 +} diff --git a/apps/vectorcraft/src/mac_menu.rs b/apps/vectorcraft/src/mac_menu.rs index 0b94fa03c2..f90e4f7304 100644 --- a/apps/vectorcraft/src/mac_menu.rs +++ b/apps/vectorcraft/src/mac_menu.rs @@ -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| { 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); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index b3a1fd06b9..7e4f245d3e 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -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"))] { diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 919a044557..8e64027031 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -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::*; diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index 555d829e0b..6e61cbe31f 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -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> { ["CFBundleTypeExtensions", "public.filename-extension"] diff --git a/apps/vectorcraft/src/titlebar.rs b/apps/vectorcraft/src/titlebar.rs index 6e7451ed9c..fc6e395927 100644 --- a/apps/vectorcraft/src/titlebar.rs +++ b/apps/vectorcraft/src/titlebar.rs @@ -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, 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); diff --git a/contributors/people.toml b/contributors/people.toml index 69c412f8b9..420177ffb6 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -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 diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 8e947c1436..03d0f5670c 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -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> { + 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::>()?; + 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 + 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 + 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( + &self, + ramp: Ramp, + bounds: Rect, + area: Rect, + cols: u16, + rows: u16, + cells: [std::ops::Range; 2], + fill: bool, + inks: bool, + ) -> impl Iterator + use { 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 { + stops: Vec<(f32, [f32; N])>, } impl Ramp { @@ -932,10 +993,13 @@ impl Ramp { .collect(); Self { stops } } +} + +impl Ramp { /// 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) } } diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 1005b84300..87372a1c24 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -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()); +} diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 5de064d6bc..03e7dc10e7 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -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 { diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index d25be2c419..5ea0ff9bd5 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -904,12 +904,16 @@ pub struct Spine { cum: Vec, anchors: Vec, 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 { let sp = path.subpaths.first()?; let mut pts: Vec = 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 { diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index f099b5f95a..14bda9a00b 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -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)>, patterns: Vec, + swatches: crate::Shared>, + swatch_groups: crate::Shared>, inputs: u64, art: Rc>, 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> { let inputs = live_inputs(); let kept = EVALUATED.with_borrow_mut(|kept| { @@ -206,7 +211,16 @@ fn live_art(doc: &Document, n: &Node) -> Rc> { 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); diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index d6f4cafe79..cb5b19d1a4 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -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. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 363000ca33..3394585bb9 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -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 } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 6ef4918e16..625aa52329 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -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()); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index be452f6c6d..45b23a0cb1 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "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 { } 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 { 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| { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 53f373a3bd..13b6ab8814 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -272,7 +272,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/brushsym/dynamic.rs b/crates/engine/src/cmd/brushsym/dynamic.rs index 89c7c3c522..32edc44f86 100644 --- a/crates/engine/src/cmd/brushsym/dynamic.rs +++ b/crates/engine/src/cmd/brushsym/dynamic.rs @@ -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 { diff --git a/crates/engine/src/cmd/buildcmds/shape_builder.rs b/crates/engine/src/cmd/buildcmds/shape_builder.rs index 5cbcdea970..fea79a0e6a 100644 --- a/crates/engine/src/cmd/buildcmds/shape_builder.rs +++ b/crates/engine/src/cmd/buildcmds/shape_builder.rs @@ -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 { 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 { 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::>(), 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 { // What goes in place of each object the map was made from (none: it stays as it is). let mut outs: Vec>> = 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 = 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 { } 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). diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index b721fc0edc..5809835e3b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1027,6 +1027,12 @@ fn cut(s: &mut Session, p: &Value) -> Result { 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 { let st = s.doc()?; let sel = st.selection.clone(); @@ -1035,6 +1041,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { 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 { 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 { 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(); diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index d11df03be4..b913720f10 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -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. diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 52478ac13c..ce7a82d2b6 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "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.\" (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 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.\" (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 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)", always, load::open ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "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 for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,