diff --git a/Cargo.lock b/Cargo.lock index 93ae3be0f0..b77485ae02 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -975,12 +975,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7 [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" +source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" +source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1049,7 +1049,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" +source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -6367,6 +6367,13 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "vectorcraft-apischema" +version = "0.21.0" +dependencies = [ + "serde_json", +] + [[package]] name = "vectorcraft-brush" version = "0.21.0" @@ -6492,8 +6499,10 @@ dependencies = [ "ruzstd", "serde", "serde_json", + "skrifa 0.47.0", "thiserror 2.0.21", "vectorcraft-affinity", + "vectorcraft-apischema", "vectorcraft-brush", "vectorcraft-cad", "vectorcraft-color", @@ -6643,6 +6652,8 @@ dependencies = [ "kurbo 0.13.1", "log", "md-5", + "objc2-core-foundation", + "objc2-core-graphics", "roxmltree 0.21.2", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 375b17a3e9..9b4b99c92d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ repository = "https://github.com/storytold/vectorcraft" craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } 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-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", 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 @@ -55,6 +55,7 @@ vectorcraft-plugins = { path = "crates/plugins" } vectorcraft-affinity = { path = "crates/affinity" } vectorcraft-scriptcheck = { path = "crates/scriptcheck" } vectorcraft-js = { path = "crates/js" } +vectorcraft-apischema = { path = "crates/apischema" } # foundation kurbo = { version = "0.13", features = ["serde"] } diff --git a/ROADMAP.md b/ROADMAP.md index fbe2334000..327036c371 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,21 +1,8 @@ # VectorCraft Roadmap -- Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. -- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. - -- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. -- UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged. - -- PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. -- PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned. - -- UI.5: Shared docking adds tab reordering, docking into other groups, dock splits and resizable floating panel groups. Panel positions and return locations persist with workspaces; the native icon rail and Tools panel remain available. - -- UI.4: Dock and floating-panel headers use shared accessible tabs with bounded overflow. Widget-state theme application uses `craft-ui`; all four palettes, font stacks and preferences remain app-owned. - **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-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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -35,7 +22,6 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | | Value | Kind | |---|---|---| -| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. | | **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | | **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated | | **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated | @@ -83,7 +69,7 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so | Strokes, brushes, width profiles | 88% | 8–15 | | Appearance, transparency, graphic styles, masks | 97% | 1–2 | | Live vector effects | 85% | 4–8 | -| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 85% | 1–2 | +| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 88% | — | | 3D and Materials | ~25% | 30–55 | | Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 | | Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 | @@ -131,8 +117,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap 2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h. 3. **Launch and stability on real machines** (G10): 20–35 h. 4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h. -5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h. -6. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). +5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2). ## Progress log @@ -226,6 +211,13 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. | +| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. | +| 2026-11-05 | minor | Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. | +| 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. | +| 2026-11-03 | minor | Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. | +| 2026-11-03 | minor | UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged. | +| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. | | 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. | | 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged | | 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. | @@ -262,10 +254,14 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | 2026-10-13 | minor | Bounded synthetic control input (#1709): counts and queued events validated before mutation; control-channel bursts yield between frames. Scores and hours unchanged. | | 2026-10-14 | minor | Progress log row for the merges of 2026-10-14 (#1641–#1808 as listed there) and Image Trace's #1647 and #1657; the 2026-10-13 row now says that a guide's position in the Transform panel (#1659) is not established by the documentation found and is kept as a convenience pending the owner's decision; headline numbers unchanged. | | 2026-10-13 | minor | Control transport deadlines (#1726): idle and partial clients and blocked replies release connection slots; parity scores and estimates unchanged. | +| 2026-10-13 | minor | PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. | +| 2026-10-13 | minor | PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned. | | 2026-10-10 | minor | Method changed, no new evidence: full ready for real work is the additive weighted sum, ~62%; hours per audience; beta ~13 points away | | 2026-10-10 | minor | Added the essentials-user readiness score (~75%) | | 2026-10-10 | minor | Ready for real work re-examined against the issue tracker and user feedback: 50% → 55% (full), 65% mainstream added; see target-app-parity.md | | 2026-10-10 | minor | Applied the core-workflow gate (docs/roadmap.md › Alpha gate): passes, stage stays alpha | | 2026-10-10 | major | Re-measured against Illustrator 2026 (30.x) from code counts, 71 open issues and public docs; stage set to alpha; moved the parity estimate, honest assessment and "Shipped so far" to `docs/target-app-parity.md`, the gap list to `docs/gaps.md`, milestones to `docs/roadmap.md`, the `.ai` scope to `docs/file-format-parity.md` | +| 2026-10-10 | minor | UI.5: Shared docking adds tab reordering, docking into other groups, dock splits and resizable floating panel groups. Panel positions and return locations persist with workspaces; the native icon rail and Tools panel remain available. | +| 2026-10-10 | minor | UI.4: Dock and floating-panel headers use shared accessible tabs with bounded overflow. Widget-state theme application uses `craft-ui`; all four palettes, font stacks and preferences remain app-owned. | | 2026-10-05 | major | Honest assessment by dimension and the prioritized gap list | | 2026-10-02 | major | First 22-area weighted parity estimate | diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 734f8a0569..57b3d41224 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -236,11 +236,12 @@ fn main() -> ExitCode { } /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the -/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541) and the custom dictionary's words (#4936), in the folders +/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), 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_color_settings(&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); diff --git a/apps/vectorcraft-cli/tests/it/cli.rs b/apps/vectorcraft-cli/tests/it/cli.rs index f2600d9b4f..5bdd2bf631 100644 --- a/apps/vectorcraft-cli/tests/it/cli.rs +++ b/apps/vectorcraft-cli/tests/it/cli.rs @@ -597,7 +597,7 @@ fn exercise_mcp_core( assert!(r["result"]["completion"]["values"].as_array().is_some_and(|v| v.contains(&json!("svg"))), "{r}"); mcp_send(stdin, json!({"jsonrpc":"2.0","id":5,"method":"resources/list","params":{}})); - assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 3)); + assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 4)); mcp_send(stdin, json!({"jsonrpc":"2.0","id":6,"method":"resources/templates/list","params":{}})); assert!(mcp_recv(lines, notes, 6)["result"]["resourceTemplates"].as_array().is_some_and(|v| v.len() >= 4)); diff --git a/apps/vectorcraft-cli/tests/it/main.rs b/apps/vectorcraft-cli/tests/it/main.rs index 6918ea19b6..07e5a3a70d 100644 --- a/apps/vectorcraft-cli/tests/it/main.rs +++ b/apps/vectorcraft-cli/tests/it/main.rs @@ -5,3 +5,4 @@ mod cli; mod fileio; mod mcp_e2e; +mod script; diff --git a/apps/vectorcraft-cli/tests/it/script.rs b/apps/vectorcraft-cli/tests/it/script.rs new file mode 100644 index 0000000000..d68716f7b3 --- /dev/null +++ b/apps/vectorcraft-cli/tests/it/script.rs @@ -0,0 +1,39 @@ +use std::process::Command; + +use serde_json::{Value, json}; + +const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli"); + +/// `run` with `script.run` after `file.new`, with `params`. +fn run_script(params: &Value) -> std::process::Output { + Command::new(BIN).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", ¶ms.to_string()]).output().unwrap() +} + +/// `run` runs a script headless: the reply holds the report, with what the script logged and the +/// documents it changed. +#[test] +fn run_gives_the_report_of_a_script() { + let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.log(vc.args.n * 2);"; + let out = run_script(&json!({"source": source, "name": "double.js", "args": {"n": 21}})); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let lines: Vec = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(lines.len(), 2, "{lines:?}"); + assert_eq!(lines[1]["command"], "script.run"); + let report = &lines[1]["result"]; + assert_eq!(report["ok"], true, "{report}"); + assert_eq!(report["name"], "double.js"); + assert_eq!(report["log"], json!([42]), "{report}"); + assert_eq!(report["changed"].as_array().map(Vec::len), Some(1), "{report}"); +} + +/// A script that throws fails its step with the script's message, and the steps before it ran. +#[test] +fn run_fails_the_step_of_a_script_that_throws() { + let out = run_script(&json!({"source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); throw new Error('no margin given');"})); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("step 1 (script.run)") && stderr.contains("no margin given"), "{stderr}"); + let printed: Vec = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(printed.len(), 1, "only file.new printed: {printed:?}"); + assert_eq!(printed[0]["command"], "file.new"); +} diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 6e4dbd7f00..eb35a110c7 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -26,7 +26,7 @@ log = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } -rfd = { workspace = true } +rfd = { workspace = true, features = ["file-handle-inner"] } wasm-bindgen = "0.2" serde_json = { workspace = true } wasm-bindgen-futures = "0.4" diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 60682d6986..b4ca434d90 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -9,6 +9,9 @@ use vectorcraft_engine::Session; use vectorcraft_engine::cmd::clipboard::{FILE_HEAD, Flavour, PASTE_ORDER, file_flavour, is_address}; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::cmd::recovery::{self, Hold, RecoveryStore}; +use vectorcraft_engine::cmd::scripts::RUN_EXTS; +use vectorcraft_engine::script::MAX_SOURCE_BYTES; +use vectorcraft_ui_egui::dialogs::script_run::ScriptInbox; use vectorcraft_ui_egui::graphics::GraphicsLoss; use vectorcraft_ui_egui::i18n; use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox}; @@ -47,6 +50,7 @@ struct Host { runner: eframe::WebRunner, inbox: Inbox, place_inbox: PlaceInbox, + script_inbox: ScriptInbox, drag: DragPos, pasted: Rc>, /// Pen and finger input read from the page's Pointer Events (`crate::pencil`). @@ -75,6 +79,7 @@ pub fn start() { runner: eframe::WebRunner::new(), inbox: Arc::default(), place_inbox: Arc::default(), + script_inbox: Arc::default(), drag: DragPos::default(), pasted: Rc::default(), pointers: SharedPointers::default(), @@ -120,7 +125,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option { // The old services asked the old context for frames. @@ -425,12 +431,35 @@ impl eframe::App for WebShell { } } -fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Option, stylus: StylusFeed) -> Services { +fn services( + inbox: Inbox, + place_inbox: PlaceInbox, + script_inbox: ScriptInbox, + ctx: egui::Context, + locks: Option, + stylus: StylusFeed, +) -> Services { let open_inbox = inbox.clone(); let picked = place_inbox.clone(); let place_ctx = ctx.clone(); let screen_color = eye_dropper(ctx.clone()); + let (script_picked, script_ctx) = (script_inbox.clone(), ctx.clone()); Services { + // File › Scripts › Other Script…: the picked file goes to the warning before it runs. + script_async: Some(Box::new(move || { + let inbox = script_picked.clone(); + let ctx = script_ctx.clone(); + wasm_bindgen_futures::spawn_local(async move { + let filter = vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", "Scripts"); + let Some(file) = rfd::AsyncFileDialog::new().add_filter(filter, RUN_EXTS).pick_file().await else { + return; + }; + let bytes = if file.inner().size() > MAX_SOURCE_BYTES as f64 { None } else { Some(file.read().await) }; + inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes)); + ctx.request_repaint(); + }); + })), + script_inbox: Some(script_inbox), // File → Place…: the picked files go to the Place dialog. place_async: Some(Box::new(move || { let inbox = picked.clone(); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 7e4f245d3e..b97ee681fe 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -456,6 +456,8 @@ fn main() -> std::process::ExitCode { let mut session = Session::new(); // The profiles loaded before come back before the preferences name any of them. prefs_dir::attach_profile_store(&mut session); + // Then Edit › Color Settings, which may name one of those profiles. + prefs_dir::attach_color_settings(&mut session); // Before any plug-in loads: this launch's marker in the Launch folder next to the // preferences (none for runs without preferences), and Safe Mode. let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch"))); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 8e64027031..063d9b1aa1 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -41,6 +41,14 @@ pub fn attach_profile_store(session: &mut vectorcraft_engine::Session) { } } +/// Make Edit › Color Settings kept in `Color Settings.json` the active ones (#6335), and keep them +/// there when they change. After [`attach_profile_store`]: they may name a loaded profile. +pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) { + if let Some(path) = store_dir("Color Settings.json") { + session.attach_color_settings(path); + } +} + /// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones /// installed from now on there. pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) { diff --git a/crates/apischema/Cargo.toml b/crates/apischema/Cargo.toml new file mode 100644 index 0000000000..ce462c04fe --- /dev/null +++ b/crates/apischema/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "vectorcraft-apischema" +description = "Machine-readable parameter schemas for VectorCraft commands, with a validator and a params text writer" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +serde_json = { workspace = true } diff --git a/crates/apischema/src/conformance.rs b/crates/apischema/src/conformance.rs new file mode 100644 index 0000000000..878359846a --- /dev/null +++ b/crates/apischema/src/conformance.rs @@ -0,0 +1,174 @@ +//! For tests: a check of JSON Schema 2020-12 documents, and a validator of instances against them, +//! written from the keyword rules of the Core and Validation specifications +//! (). It reads only the JSON and shares no code with the +//! writer it checks. It covers the keywords the writer uses and reports any other keyword that +//! isn't an `x-` annotation. + +use serde_json::Value; + +const TYPES: &[&str] = &["null", "boolean", "object", "array", "number", "string", "integer"]; + +fn unique(items: &[Value]) -> bool { + items.iter().enumerate().all(|(i, x)| items.iter().take(i).all(|y| y != x)) +} + +fn schema_list(items: &Value, at: &str, key: &str) -> Result<(), String> { + let list = items.as_array().filter(|l| !l.is_empty()).ok_or_else(|| format!("{at}: `{key}` must be a nonempty array"))?; + for (i, x) in list.iter().enumerate() { + check_schema(x, &format!("{at}/{key}/{i}"))?; + } + Ok(()) +} + +/// Whether `schema` follows the 2020-12 rules for the keywords it uses, with where it doesn't. +pub fn check_schema(schema: &Value, at: &str) -> Result<(), String> { + let object = match schema { + Value::Bool(_) => return Ok(()), + Value::Object(o) => o, + other => return Err(format!("{at}: a schema must be an object or a boolean, not {other}")), + }; + for (key, value) in object { + let number = || if value.is_number() { Ok(()) } else { Err(format!("{at}: `{key}` must be a number")) }; + match key.as_str() { + "$schema" => { + let uri = value.as_str().ok_or_else(|| format!("{at}: `$schema` must be a string"))?; + if !uri.contains("://") || uri.ends_with('#') { + return Err(format!("{at}: `$schema` must be a normalized URI")); + } + } + "type" => { + let known = |v: &Value| v.as_str().is_some_and(|s| TYPES.contains(&s)); + let ok = known(value) || value.as_array().is_some_and(|l| !l.is_empty() && unique(l) && l.iter().all(known)); + if !ok { + return Err(format!("{at}: `type` must name JSON types, not {value}")); + } + } + "enum" => { + if !value.as_array().is_some_and(|l| !l.is_empty() && unique(l)) { + return Err(format!("{at}: `enum` must be a nonempty array of unique values")); + } + } + "properties" => { + let props = value.as_object().ok_or_else(|| format!("{at}: `properties` must be an object"))?; + for (name, x) in props { + check_schema(x, &format!("{at}/properties/{name}"))?; + } + } + "required" => { + if !value.as_array().is_some_and(|l| unique(l) && l.iter().all(Value::is_string)) { + return Err(format!("{at}: `required` must be an array of unique strings")); + } + } + "additionalProperties" | "items" => check_schema(value, &format!("{at}/{key}"))?, + "prefixItems" | "anyOf" => schema_list(value, at, key)?, + "minimum" | "maximum" | "exclusiveMinimum" | "exclusiveMaximum" => number()?, + "minItems" => { + if value.as_u64().is_none() { + return Err(format!("{at}: `minItems` must be a non-negative integer")); + } + } + "description" => { + if !value.is_string() { + return Err(format!("{at}: `description` must be a string")); + } + } + "deprecated" => { + if !value.is_boolean() { + return Err(format!("{at}: `deprecated` must be a boolean")); + } + } + "default" => { + if !instance_valid(schema, value) { + return Err(format!("{at}: `default` {value} does not validate against its schema")); + } + } + k if k.starts_with("x-") => {} + other => return Err(format!("{at}: unexpected keyword `{other}`")), + } + } + Ok(()) +} + +fn has_type(v: &Value, name: &str) -> bool { + match name { + "null" => v.is_null(), + "boolean" => v.is_boolean(), + "object" => v.is_object(), + "array" => v.is_array(), + "string" => v.is_string(), + "number" => v.is_number(), + "integer" => v.is_i64() || v.is_u64() || v.as_f64().is_some_and(|x| x.fract() == 0.0), + _ => false, + } +} + +/// Whether the instance `v` is valid against `schema`. +pub fn instance_valid(schema: &Value, v: &Value) -> bool { + let s = match schema { + Value::Bool(b) => return *b, + Value::Object(o) => o, + _ => return false, + }; + let type_ok = match s.get("type") { + None => true, + Some(Value::String(t)) => has_type(v, t), + Some(Value::Array(l)) => l.iter().filter_map(Value::as_str).any(|t| has_type(v, t)), + Some(_) => false, + }; + if !type_ok { + return false; + } + if let Some(list) = s.get("enum").and_then(Value::as_array) + && !list.contains(v) + { + return false; + } + if let Some(any) = s.get("anyOf").and_then(Value::as_array) + && !any.iter().any(|x| instance_valid(x, v)) + { + return false; + } + if let Some(x) = v.as_f64() { + let bound = |key: &str| s.get(key).and_then(Value::as_f64); + if bound("minimum").is_some_and(|m| x < m) + || bound("maximum").is_some_and(|m| x > m) + || bound("exclusiveMinimum").is_some_and(|m| x <= m) + || bound("exclusiveMaximum").is_some_and(|m| x >= m) + { + return false; + } + } + if let Some(items) = v.as_array() { + if s.get("minItems").and_then(Value::as_u64).is_some_and(|n| (items.len() as u64) < n) { + return false; + } + let prefix = s.get("prefixItems").and_then(Value::as_array).map_or(&[][..], Vec::as_slice); + if items.iter().zip(prefix).any(|(x, p)| !instance_valid(p, x)) { + return false; + } + if let Some(rest) = s.get("items") + && items.iter().skip(prefix.len()).any(|x| !instance_valid(rest, x)) + { + return false; + } + } + if let Some(object) = v.as_object() { + let required = s.get("required").and_then(Value::as_array).map_or(&[][..], Vec::as_slice); + if required.iter().filter_map(Value::as_str).any(|k| !object.contains_key(k)) { + return false; + } + let props = s.get("properties").and_then(Value::as_object); + for (key, x) in object { + match props.and_then(|p| p.get(key)) { + Some(p) if !instance_valid(p, x) => return false, + Some(_) => {} + None => { + if s.get("additionalProperties").is_some_and(|a| !instance_valid(a, x)) { + return false; + } + } + } + } + } + true +} diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs new file mode 100644 index 0000000000..5db24230e1 --- /dev/null +++ b/crates/apischema/src/lib.rs @@ -0,0 +1,940 @@ +//! Machine-readable parameter schemas for VectorCraft commands. A [`ParamSchema`] lists what each +//! parameter of a command is ([`Param`], [`Type`]): its type, whether it is required, what an +//! omitted value means, whether null counts as omitted, and the API levels it was added and +//! deprecated at. From one schema come: +//! +//! - [`ParamSchema::validate`], which checks a params object and names the parameter of the first +//! problem it finds ([`ParamError`]), and fills in the defaults of omitted values; +//! - [`ParamSchema::definition_problem`], which checks the schema itself; +//! - [`ParamSchema::params_text`], the params text a command lists; +//! - [`ParamSchema::to_json`], the schema as a JSON object in the shape of a JSON Schema 2020-12 +//! object schema (), with VectorCraft's own fields as +//! `x-` keywords; +//! - [`hash`], a hash of a set of command schemas, which changes whenever any of them changes. +//! +//! Checking a value walks the schema, so its depth is the schema's, at most [`MAX_DEPTH`]. An error +//! shows a bounded part of a refused value and of a refused key, and the value is not written out +//! first, so a huge or deeply nested value costs no more to refuse than a small one. +//! +//! The crate knows no command and depends on no other VectorCraft crate. +#![forbid(unsafe_code)] + +use std::fmt; + +use serde_json::{Map, Value, json}; + +/// The JSON Schema dialect [`ParamSchema::to_json`] names in `$schema`. +pub const DIALECT: &str = "https://json-schema.org/draft/2020-12/schema"; + +/// How many objects and lists may nest inside a schema's params object. +pub const MAX_DEPTH: usize = 16; + +/// The largest object id [`Type::Id`] takes: 2^53 - 1, the largest integer every JSON reader holds +/// exactly. +pub const MAX_ID: u64 = (1 << 53) - 1; + +/// How many characters of a refused value an error shows. +const SHOWN_CHARS: usize = 40; + +/// How many characters of a key an error shows. +const KEY_CHARS: usize = 64; + +/// One end of a number's range. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Bound { + /// The value may equal the bound. + Inclusive(f64), + /// The value must be past the bound. + Exclusive(f64), +} + +/// The type of a parameter's value. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Type { + /// A JSON number in the range the bounds give, measured in `unit` (`"pt"`, `"deg"`) when set. + Number { min: Option, max: Option, unit: Option<&'static str> }, + /// A JSON number with no fractional part, in the range given. [`ParamSchema::validate`] gives + /// the command `2.0` as `2`. + Integer { min: Option, max: Option }, + /// `true` or `false`. + Boolean, + /// Any string. + String, + /// One of the strings listed. + Enum(&'static [&'static str]), + /// An object id: an integer from 0 to [`MAX_ID`], read as [`Type::Integer`] reads one. + Id, + /// A list of object ids. + Ids, + /// A color: a string (`"#rrggbb"`, a color key), `[r, g, b]` or an object. The command reads + /// which color it is. + Color, + /// A point: `[x, y]`, two numbers. + Point, + /// An object with the parameters listed and no other key. + Object(&'static [Param]), + /// A list of values of one type. + Array(&'static Type), +} + +impl Type { + /// A number with no range and no unit. + pub const NUMBER: Type = Type::Number { min: None, max: None, unit: None }; +} + +/// What an omitted value means. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Omitted { + /// The parameter is required, or the command describes the omitted case in its summary. + Nothing, + /// The value, as JSON text, that [`ParamSchema::validate`] fills in. + Value(&'static str), + /// A default the command works out itself (`"toggle"`, `"the selected text"`). + Note(&'static str), +} + +/// What a command changes when it runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Writes { + /// Nothing: the command only reads. + Nothing, + /// State of the running app outside the document and the preferences (view state, the Caps + /// Lock state). + Session, + /// The preferences. + Preferences, + /// The document, with an undo step. + Document, +} + +impl Writes { + fn name(self) -> &'static str { + match self { + Writes::Nothing => "nothing", + Writes::Session => "session", + Writes::Preferences => "preferences", + Writes::Document => "document", + } + } +} + +/// One parameter of a command. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Param { + pub name: &'static str, + pub ty: Type, + pub required: bool, + pub omitted: Omitted, + /// A null value is read as if the parameter were omitted. Otherwise null is refused as a value + /// of the wrong type. + pub null_omitted: bool, + /// What the params text says about the value, in parentheses after its type. + pub doc: &'static str, + /// The API level the parameter was added at. + pub since: u32, + /// The API level the parameter was deprecated at. + pub deprecated: Option, + /// A value of the wrong type or out of range is not refused here: the command reads it as it + /// did before it had a schema. [`ParamSchema::to_json`] still writes the documented type, so a + /// JSON Schema validator refuses a value this passes. + pub lenient: bool, +} + +impl Param { + /// A required parameter, added at API level 1. + pub const fn new(name: &'static str, ty: Type) -> Param { + Param { name, ty, required: true, omitted: Omitted::Nothing, null_omitted: false, doc: "", since: 1, deprecated: None, lenient: false } + } + /// The parameter may be omitted. + pub const fn optional(self) -> Param { + Param { required: false, ..self } + } + /// The parameter may be omitted, and then takes the value `json` (JSON text). + pub const fn defaults_to(self, json: &'static str) -> Param { + Param { required: false, omitted: Omitted::Value(json), ..self } + } + /// The parameter may be omitted, and the command then works out the value `note` describes. + pub const fn default_note(self, note: &'static str) -> Param { + Param { required: false, omitted: Omitted::Note(note), ..self } + } + /// A null value reads as an omitted one. + pub const fn null_omitted(self) -> Param { + Param { null_omitted: true, ..self } + } + pub const fn doc(self, doc: &'static str) -> Param { + Param { doc, ..self } + } + pub const fn since(self, level: u32) -> Param { + Param { since: level, ..self } + } + pub const fn deprecated(self, level: u32) -> Param { + Param { deprecated: Some(level), ..self } + } + pub const fn lenient(self) -> Param { + Param { lenient: true, ..self } + } +} + +/// The parameters of one command, and what the command does with them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ParamSchema { + pub params: &'static [Param], + /// What the command does, after the params object in the params text. + pub summary: &'static str, + /// What the command returns, after `→` in the params text; empty when the text leaves it out. + pub returns: &'static str, + /// The API level the command was added at. + pub since: u32, + /// The API level the command was deprecated at. + pub deprecated: Option, + /// What one run costs, in units of a light command (1), for callers that limit a script's work. + pub cost: u32, + pub writes: Writes, +} + +impl ParamSchema { + /// A command added at API level 1, costing 1, that changes the document. + pub const fn new(params: &'static [Param], summary: &'static str) -> ParamSchema { + ParamSchema { params, summary, returns: "", since: 1, deprecated: None, cost: 1, writes: Writes::Document } + } + pub const fn returns(self, returns: &'static str) -> ParamSchema { + ParamSchema { returns, ..self } + } + pub const fn writes(self, writes: Writes) -> ParamSchema { + ParamSchema { writes, ..self } + } + pub const fn cost(self, cost: u32) -> ParamSchema { + ParamSchema { cost, ..self } + } + pub const fn since(self, level: u32) -> ParamSchema { + ParamSchema { since: level, ..self } + } + pub const fn deprecated(self, level: u32) -> ParamSchema { + ParamSchema { deprecated: Some(level), ..self } + } + + /// The parameter named `name`. + pub fn param(&self, name: &str) -> Option<&'static Param> { + self.params.iter().find(|p| p.name == name) + } + + /// The names of the top-level parameters, in order. + pub fn names(&self) -> Vec<&'static str> { + self.params.iter().map(|p| p.name).collect() + } + + /// `params` checked against the schema: the first problem as an error naming the parameter, + /// or, when it has none, `params` with the defaults of its omitted values filled in (`None` + /// when no default was filled in, so `params` is used as it is). Null params read as `{}`. + pub fn validate(&self, params: &Value) -> Result, ParamError> { + self.validate_as(params, false) + } + + /// [`ParamSchema::validate`] for saved steps recorded by this version or an older one: a key + /// the schema doesn't name passes, at any depth, and the command does not read it. Values of + /// the parameters the schema names are checked as `validate` checks them. + pub fn validate_saved(&self, params: &Value) -> Result, ParamError> { + self.validate_as(params, true) + } + + fn validate_as(&self, params: &Value, saved: bool) -> Result, ParamError> { + static EMPTY: std::sync::OnceLock> = std::sync::OnceLock::new(); + let given = match params { + Value::Object(o) => o, + Value::Null => EMPTY.get_or_init(Map::new), + v => return Err(ParamError { path: String::new(), problem: Problem::NotAnObject { got: shown(v) } }), + }; + Ok(check_object(&At::Root, 0, self.params, given, saved)?.map(Value::Object)) + } + + /// What is wrong with the schema itself, or `None`: a parameter name that is empty, repeated + /// or holds `.`, `[` or `]`; a required parameter with a default; a default that isn't JSON or + /// doesn't pass its parameter's type; an enum with no names or a repeated name; a range with + /// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`]. + pub fn definition_problem(&self) -> Option { + object_problem("", self.params, 0) + } + + /// The params text: the params object (`{name?: string, zoom: number > 0}`), then the summary, + /// then `→` and what the command returns. + pub fn params_text(&self) -> String { + let mut s = object_text(self.params, 0); + if !self.summary.is_empty() { + s.push(' '); + s.push_str(self.summary); + } + if !self.returns.is_empty() { + s.push_str(" → "); + s.push_str(self.returns); + } + s + } + + /// The schema as a JSON Schema 2020-12 object schema. Defaults written as JSON go in + /// `default`, a parameter that accepts null as omitted is an `anyOf` with `{"type": "null"}`, + /// and VectorCraft's own fields are `x-since`, `x-deprecatedSince`, `x-lenient`, `x-unit`, + /// `x-kind`, `x-cost`, `x-writes` and `x-returns`. The root `type` is `["object", "null"]` when + /// no parameter is required, because null params read as `{}`, and `"object"` otherwise. A JSON + /// Schema validator accepts the values [`ParamSchema::validate`] accepts, except that an + /// `x-lenient` parameter's schema states only the documented type. + pub fn to_json(&self) -> Value { + let mut o = object_schema(self.params, 0); + if !self.params.iter().any(|p| p.required) { + o.insert("type".into(), json!(["object", "null"])); + } + o.insert("$schema".into(), DIALECT.into()); + if !self.summary.is_empty() { + o.insert("description".into(), self.summary.into()); + } + if !self.returns.is_empty() { + o.insert("x-returns".into(), self.returns.into()); + } + o.insert("x-since".into(), self.since.into()); + if let Some(level) = self.deprecated { + o.insert("deprecated".into(), true.into()); + o.insert("x-deprecatedSince".into(), level.into()); + } + o.insert("x-cost".into(), self.cost.into()); + o.insert("x-writes".into(), self.writes.name().into()); + Value::Object(o) + } +} + +/// A problem [`ParamSchema::validate`] found, at `path`: the parameter's name, with the keys and +/// indices leading to a value inside one (`edits[1].name`). The path is empty for the params +/// object itself. +#[derive(Clone, Debug, PartialEq)] +pub struct ParamError { + pub path: String, + pub problem: Problem, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Problem { + /// The params are not an object. + NotAnObject { got: String }, + /// The key at `path` is not a parameter of the object it is in, which takes `keys`. + Unknown { keys: Vec<&'static str> }, + /// A required parameter is missing. + Missing, + /// The value is not of the parameter's type: `expected` says what it must be. + WrongType { expected: String, got: String }, + /// The schema nests deeper than [`MAX_DEPTH`] here ([`ParamSchema::definition_problem`]). + TooDeep, +} + +impl fmt::Display for ParamError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let path = &self.path; + match &self.problem { + Problem::NotAnObject { got } => write!(f, "the params must be an object, not {got}"), + Problem::Unknown { keys } if keys.is_empty() => write!(f, "unknown parameter `{path}`; the object takes no keys"), + Problem::Unknown { keys } => write!(f, "unknown parameter `{path}`; it takes: {}", keys.join(", ")), + Problem::Missing => write!(f, "missing `{path}`"), + Problem::WrongType { expected, got } => write!(f, "`{path}` must be {expected}, not {got}"), + Problem::TooDeep => write!(f, "`{path}` is nested too deeply"), + } + } +} + +impl std::error::Error for ParamError {} + +/// FNV-1a over the bytes of `text`, from `h`. +fn fnv1a(mut h: u64, text: &str) -> u64 { + for b in text.bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + h +} + +/// `v` as JSON text with the keys of each object in sorted order, whichever order the map keeps +/// them in. +fn canonical(v: &Value, out: &mut String) { + match v { + Value::Object(o) => { + let mut keys: Vec<&String> = o.keys().collect(); + keys.sort(); + out.push('{'); + for (i, k) in keys.into_iter().enumerate() { + if i > 0 { + out.push(','); + } + out.push_str(&Value::from(k.as_str()).to_string()); + out.push(':'); + if let Some(x) = o.get(k) { + canonical(x, out); + } + } + out.push('}'); + } + Value::Array(a) => { + out.push('['); + for (i, x) in a.iter().enumerate() { + if i > 0 { + out.push(','); + } + canonical(x, out); + } + out.push(']'); + } + other => out.push_str(&other.to_string()), + } +} + +/// A 64-bit FNV-1a hash of the commands' schemas, taken in the order of their ids: each id and +/// its [`ParamSchema::to_json`] text, with the keys of each object sorted. Any change to a schema, +/// or a schema added or removed, changes it. +pub fn hash<'a>(schemas: impl IntoIterator) -> u64 { + let mut all: Vec<(&str, &ParamSchema)> = schemas.into_iter().collect(); + all.sort_by_key(|(id, _)| *id); + all.iter().fold(0xcbf2_9ce4_8422_2325, |h, (id, schema)| { + let mut text = String::new(); + canonical(&schema.to_json(), &mut text); + let h = fnv1a(h, id); + let h = fnv1a(h, "\n"); + let h = fnv1a(h, &text); + fnv1a(h, "\n") + }) +} + +/// `key` as an error message shows it: cut to [`KEY_CHARS`] characters. +pub fn shown_key(key: &str) -> String { + let mut chars = key.chars(); + let head: String = chars.by_ref().take(KEY_CHARS).collect(); + if chars.next().is_some() { format!("{head}…") } else { head } +} + +/// The JSON text of a value, stopping when its characters run out. +struct Shown { + text: String, + left: usize, +} + +impl Shown { + /// Adds `s`; false when it didn't fit. + fn push(&mut self, s: &str) -> bool { + for c in s.chars() { + if self.left == 0 { + return false; + } + self.left -= 1; + self.text.push(c); + } + true + } + + /// Adds the JSON text of string `s`, reading no more of it than can be shown. + fn push_string(&mut self, s: &str) -> bool { + let head: String = s.chars().take(self.left + 1).collect(); + self.push(&Value::from(head).to_string()) + } + + /// Adds the JSON text of `v`; false when it didn't fit. Each object or list writes a bracket, + /// so the characters left bound the recursion. + fn push_value(&mut self, v: &Value) -> bool { + match v { + Value::String(s) => self.push_string(s), + Value::Array(items) => { + self.push("[") && items.iter().enumerate().all(|(i, x)| (i == 0 || self.push(",")) && self.push_value(x)) && self.push("]") + } + Value::Object(o) => { + self.push("{") + && o.iter() + .enumerate() + .all(|(i, (k, x))| (i == 0 || self.push(",")) && self.push_string(k) && self.push(":") && self.push_value(x)) + && self.push("}") + } + other => self.push(&other.to_string()), + } + } +} + +/// A value as an error message shows it: its JSON, cut to [`SHOWN_CHARS`] characters. Only what is +/// shown is read, however large the value is. +fn shown(v: &Value) -> String { + let mut out = Shown { text: String::new(), left: SHOWN_CHARS }; + if !out.push_value(v) { + out.text.push('…'); + } + out.text +} + +fn join(path: &str, key: &str) -> String { + if path.is_empty() { key.to_string() } else { format!("{path}.{key}") } +} + +/// Where a value is, from the value up to the params object. The path's text is written only for +/// an error. +#[derive(Clone, Copy)] +enum At<'a> { + Root, + Key(&'a At<'a>, &'a str), + Index(&'a At<'a>, usize), +} + +impl At<'_> { + /// The path, `edits[1].name`, with each key as [`shown_key`] shows it. + fn text(&self) -> String { + let mut steps = Vec::new(); + let mut at = self; + while let At::Key(up, _) | At::Index(up, _) = at { + steps.push(at); + at = up; + } + let mut out = String::new(); + for step in steps.into_iter().rev() { + match step { + At::Key(_, key) => { + if !out.is_empty() { + out.push('.'); + } + out.push_str(&shown_key(key)); + } + At::Index(_, i) => out.push_str(&format!("[{i}]")), + At::Root => {} + } + } + out + } +} + +/// Whether `v` nests no deeper than [`MAX_DEPTH`] counted from `depth`. The walk stops at the +/// limit, so it recurses at most [`MAX_DEPTH`] levels and allocates nothing. +fn nests_within(v: &Value, depth: usize) -> bool { + match v { + Value::Array(a) => depth < MAX_DEPTH && a.iter().all(|x| nests_within(x, depth + 1)), + Value::Object(o) => depth < MAX_DEPTH && o.values().all(|x| nests_within(x, depth + 1)), + _ => true, + } +} + +/// The object `given` checked against `params` (unknown keys first, then each parameter in +/// order): with the defaults of omitted values filled in when there are any. `saved` keeps a key +/// the schema doesn't name, unless its value nests past [`MAX_DEPTH`]. +fn check_object( + at: &At<'_>, + depth: usize, + params: &'static [Param], + given: &Map, + saved: bool, +) -> Result>, ParamError> { + let refused = |key: &String, v: &Value| !params.iter().any(|p| p.name == key.as_str()) && (!saved || !nests_within(v, depth)); + if let Some((key, _)) = given.iter().find(|(k, v)| refused(k, v)) { + return Err(ParamError { path: At::Key(at, key).text(), problem: Problem::Unknown { keys: params.iter().map(|p| p.name).collect() } }); + } + // The changes are applied once every value has passed, so no refused value is ever copied. + let mut changes: Vec<(&'static str, Value)> = Vec::new(); + for p in params { + let here = At::Key(at, p.name); + match given.get(p.name) { + Some(Value::Null) if p.null_omitted => {} + Some(v) => { + if let Some(changed) = check_value(&here, depth, &p.ty, v, p.lenient, saved)? { + changes.push((p.name, changed)); + } + continue; + } + None if p.required => return Err(ParamError { path: here.text(), problem: Problem::Missing }), + None => {} + } + // Omitted, or null read as omitted. + if let Omitted::Value(json) = p.omitted + && let Ok(v) = serde_json::from_str::(json) + { + changes.push((p.name, v)); + } + } + if changes.is_empty() { + return Ok(None); + } + let mut filled = given.clone(); + for (name, v) in changes { + filled.insert(name.to_string(), v); + } + Ok(Some(filled)) +} + +/// What a value of type `ty` must be, as an error message says it. +fn expected(ty: &Type) -> String { + match ty { + Type::Number { min, max, unit } => { + format!("a number{}{}", range_text(min.as_ref(), max.as_ref()), unit.map(|u| format!(" ({u})")).unwrap_or_default()) + } + Type::Integer { min, max } => { + format!("an integer{}", range_text(min.map(|m| Bound::Inclusive(m as f64)).as_ref(), max.map(|m| Bound::Inclusive(m as f64)).as_ref())) + } + Type::Boolean => "true or false".into(), + Type::String => "a string".into(), + Type::Enum(names) => format!("one of {}", names.iter().map(|n| format!("\"{n}\"")).collect::>().join(", ")), + Type::Id => "an object id (a non-negative integer)".into(), + Type::Ids => "a list of object ids".into(), + Type::Color => "a color (a string, [r, g, b] or an object)".into(), + Type::Point => "[x, y] (two numbers)".into(), + Type::Object(_) => "an object".into(), + Type::Array(_) => "a list".into(), + } +} + +/// ` > 0`, ` 0 to 100`, ` >= 1 and < 10`: the range text after a number's type. +fn range_text(min: Option<&Bound>, max: Option<&Bound>) -> String { + match (min, max) { + (Some(Bound::Inclusive(a)), Some(Bound::Inclusive(b))) => format!(" {a} to {b}"), + (Some(a), Some(b)) => format!("{} and{}", low_text(a), high_text(b)), + (Some(a), None) => low_text(a), + (None, Some(b)) => high_text(b), + (None, None) => String::new(), + } +} + +fn low_text(b: &Bound) -> String { + match b { + Bound::Inclusive(a) => format!(" >= {a}"), + Bound::Exclusive(a) => format!(" > {a}"), + } +} + +fn high_text(b: &Bound) -> String { + match b { + Bound::Inclusive(a) => format!(" <= {a}"), + Bound::Exclusive(a) => format!(" < {a}"), + } +} + +fn in_range(x: f64, min: Option<&Bound>, max: Option<&Bound>) -> bool { + let low = match min { + Some(Bound::Inclusive(a)) => x >= *a, + Some(Bound::Exclusive(a)) => x > *a, + None => true, + }; + let high = match max { + Some(Bound::Inclusive(b)) => x <= *b, + Some(Bound::Exclusive(b)) => x < *b, + None => true, + }; + low && high +} + +/// The integer a JSON number with no fractional part stands for, as an integer value when it fits +/// in one (`2.0` is `2`); `None` for anything else. +fn whole(v: &Value) -> Option { + if v.is_i64() || v.is_u64() { + return Some(v.clone()); + } + const TWO_63: f64 = 9_223_372_036_854_775_808.0; + const TWO_64: f64 = 18_446_744_073_709_551_616.0; + let x = v.as_f64().filter(|x| x.fract() == 0.0)?; + Some(if (-TWO_63..TWO_63).contains(&x) { + json!(x as i64) + } else if (0.0..TWO_64).contains(&x) { + json!(x as u64) + } else { + v.clone() + }) +} + +/// Whether the [`whole`] value `w` is in the range. +fn whole_in_range(w: &Value, min: Option, max: Option) -> bool { + match (w.as_i64(), w.as_u64(), w.as_f64()) { + (Some(x), _, _) => min.is_none_or(|m| x >= m) && max.is_none_or(|m| x <= m), + // Past i64::MAX: above any i64 bound. + (None, Some(_), _) => max.is_none(), + // Past what u64 holds: above any i64 bound. + (None, None, Some(x)) if x > 0.0 => max.is_none(), + // Below what i64 holds: under any i64 bound, so it meets every maximum and no minimum. + (None, None, Some(_)) => min.is_none(), + _ => false, + } +} + +fn is_number(v: &Value) -> bool { + v.as_f64().is_some_and(f64::is_finite) +} + +/// `v` checked against `ty` at `at`: with the defaults of omitted values inside it filled in, and +/// whole numbers written with a fraction made integers, when there are any. A lenient value of +/// the wrong type passes as it is, unless it nests past [`MAX_DEPTH`]. +fn check_value(at: &At<'_>, depth: usize, ty: &Type, v: &Value, lenient: bool, saved: bool) -> Result, ParamError> { + let done = |ok: bool| { + if ok || (lenient && nests_within(v, depth)) { + Ok(None) + } else { + Err(ParamError { path: at.text(), problem: Problem::WrongType { expected: expected(ty), got: shown(v) } }) + } + }; + let too_deep = || ParamError { path: at.text(), problem: Problem::TooDeep }; + if matches!(ty, Type::Ids | Type::Color | Type::Point) && v.is_array() && depth >= MAX_DEPTH { + return Err(too_deep()); + } + match ty { + Type::Number { min, max, .. } => done(v.as_f64().is_some_and(|x| x.is_finite() && in_range(x, min.as_ref(), max.as_ref()))), + Type::Integer { min, max } => match whole(v).filter(|w| whole_in_range(w, *min, *max)) { + Some(w) => Ok((w != *v).then_some(w)), + None => done(false), + }, + Type::Boolean => done(v.is_boolean()), + Type::String => done(v.is_string()), + Type::Enum(names) => done(v.as_str().is_some_and(|s| names.contains(&s))), + Type::Id => match whole(v).filter(|w| w.as_u64().is_some_and(|x| x <= MAX_ID)) { + Some(w) => Ok((w != *v).then_some(w)), + None => done(false), + }, + Type::Ids => match v.as_array() { + Some(items) => check_items(at, depth, &Type::Id, items, lenient, saved), + None => done(false), + }, + Type::Color => done(match v { + Value::String(_) => true, + Value::Object(_) => nests_within(v, depth), + Value::Array(a) => a.len() >= 3 && a.iter().all(is_number), + _ => false, + }), + Type::Point => done(v.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(is_number))), + Type::Object(params) => match v { + Value::Object(_) if depth >= MAX_DEPTH => Err(too_deep()), + Value::Object(o) => Ok(check_object(at, depth + 1, params, o, saved)?.map(Value::Object)), + _ => done(false), + }, + Type::Array(item) => match v.as_array() { + Some(_) if depth >= MAX_DEPTH => Err(too_deep()), + Some(items) => check_items(at, depth + 1, item, items, lenient, saved), + None => done(false), + }, + } +} + +/// Each of `items` checked against `item`: the list with what [`check_value`] changed, when it +/// changed anything. +fn check_items(at: &At<'_>, depth: usize, item: &Type, items: &[Value], lenient: bool, saved: bool) -> Result, ParamError> { + let mut changes: Vec<(usize, Value)> = Vec::new(); + for (i, x) in items.iter().enumerate() { + if let Some(changed) = check_value(&At::Index(at, i), depth, item, x, lenient, saved)? { + changes.push((i, changed)); + } + } + if changes.is_empty() { + return Ok(None); + } + let mut filled = items.to_vec(); + for (i, v) in changes { + if let Some(slot) = filled.get_mut(i) { + *slot = v; + } + } + Ok(Some(Value::Array(filled))) +} + +/// What is wrong with `params`, the object at `path` nested `depth` objects and lists deep. +fn object_problem(path: &str, params: &[Param], depth: usize) -> Option { + if depth > MAX_DEPTH { + return Some(format!("`{path}` nests deeper than {MAX_DEPTH} levels")); + } + for (i, p) in params.iter().enumerate() { + let at = join(path, p.name); + if p.name.is_empty() || p.name.contains(['.', '[', ']']) { + return Some(format!("the parameter name `{at}` is empty or holds a path character")); + } + if params.iter().take(i).any(|q| q.name == p.name) { + return Some(format!("`{at}` is listed twice")); + } + if p.required && p.omitted != Omitted::Nothing { + return Some(format!("`{at}` is required and has a default")); + } + if let Some(problem) = type_problem(&at, &p.ty, depth) { + return Some(problem); + } + if let Omitted::Value(text) = p.omitted { + let Ok(v) = serde_json::from_str::(text) else { return Some(format!("the default of `{at}` isn't JSON: {text}")) }; + if let Err(e) = check_value(&At::Root, 0, &p.ty, &v, false, false) { + return Some(format!("the default of `{at}` doesn't pass its type: {e}")); + } + } + } + None +} + +fn type_problem(at: &str, ty: &Type, depth: usize) -> Option { + let bound = |b: &Bound| match *b { + Bound::Inclusive(x) => (x, false), + Bound::Exclusive(x) => (x, true), + }; + match ty { + Type::Number { min, max, .. } => { + let (low, high) = (min.as_ref().map(bound), max.as_ref().map(bound)); + if low.iter().chain(high.iter()).any(|(x, _)| !x.is_finite()) { + return Some(format!("the range of `{at}` has an end that isn't finite")); + } + match (low, high) { + (Some((a, open_a)), Some((b, open_b))) if a > b || (a == b && (open_a || open_b)) => { + Some(format!("no value can be in the range of `{at}`")) + } + _ => None, + } + } + Type::Integer { min: Some(a), max: Some(b) } if a > b => Some(format!("no value can be in the range of `{at}`")), + Type::Enum([]) => Some(format!("the enum of `{at}` has no names")), + Type::Enum(names) if names.iter().enumerate().any(|(i, n)| names.iter().take(i).any(|m| m == n)) => { + Some(format!("the enum of `{at}` repeats a name")) + } + Type::Object(params) => object_problem(at, params, depth + 1), + Type::Array(_) if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")), + Type::Array(item) => type_problem(&format!("{at}[]"), item, depth + 1), + _ => None, + } +} + +/// `{a: number, b?: bool}`: the params object of a params text, `depth` objects and lists deep. +fn object_text(params: &[Param], depth: usize) -> String { + format!("{{{}}}", params.iter().map(|p| param_text(p, depth)).collect::>().join(", ")) +} + +fn param_text(p: &Param, depth: usize) -> String { + let mut s = format!("{}{}: {}", p.name, if p.required { "" } else { "?" }, type_text(&p.ty, depth)); + match p.omitted { + Omitted::Value(v) | Omitted::Note(v) => s.push_str(&format!(" (default: {v})")), + Omitted::Nothing => {} + } + if !p.doc.is_empty() { + s.push_str(&format!(" ({})", p.doc)); + } + if p.deprecated.is_some() { + s.push_str(" (deprecated)"); + } + s +} + +fn type_text(ty: &Type, depth: usize) -> String { + match ty { + Type::Object(_) | Type::Array(_) if depth >= MAX_DEPTH => "…".into(), + Type::Number { min, max, unit } => { + format!("number{}{}", range_text(min.as_ref(), max.as_ref()), unit.map(|u| format!(" {u}")).unwrap_or_default()) + } + Type::Integer { min, max } => { + format!("integer{}", range_text(min.map(|m| Bound::Inclusive(m as f64)).as_ref(), max.map(|m| Bound::Inclusive(m as f64)).as_ref())) + } + Type::Boolean => "bool".into(), + Type::String => "string".into(), + Type::Enum(names) => names.iter().map(|n| format!("\"{n}\"")).collect::>().join("|"), + Type::Id => "id".into(), + Type::Ids => "[id…]".into(), + Type::Color => "color".into(), + Type::Point => "[x, y]".into(), + Type::Object(params) => object_text(params, depth + 1), + Type::Array(item) => format!("[{}…]", type_text(item, depth + 1)), + } +} + +/// `{"type": "object", "properties": …, "required": […], "additionalProperties": false}`. +fn object_schema(params: &[Param], depth: usize) -> Map { + let mut o = Map::new(); + o.insert("type".into(), "object".into()); + o.insert("properties".into(), Value::Object(params.iter().map(|p| (p.name.to_string(), param_schema(p, depth))).collect())); + let required: Vec = params.iter().filter(|p| p.required).map(|p| p.name.into()).collect(); + if !required.is_empty() { + o.insert("required".into(), required.into()); + } + o.insert("additionalProperties".into(), false.into()); + o +} + +fn param_schema(p: &Param, depth: usize) -> Value { + let inner = type_schema(&p.ty, depth); + let mut o = if p.null_omitted { + let mut o = Map::new(); + o.insert("anyOf".into(), json!([inner, {"type": "null"}])); + o + } else { + match inner { + Value::Object(o) => o, + _ => Map::new(), + } + }; + if !p.doc.is_empty() { + o.insert("description".into(), p.doc.into()); + } + match p.omitted { + Omitted::Value(json) => { + if let Ok(v) = serde_json::from_str::(json) { + o.insert("default".into(), v); + } + } + Omitted::Note(note) => { + o.insert("x-default".into(), note.into()); + } + Omitted::Nothing => {} + } + o.insert("x-since".into(), p.since.into()); + if let Some(level) = p.deprecated { + o.insert("deprecated".into(), true.into()); + o.insert("x-deprecatedSince".into(), level.into()); + } + if p.lenient { + o.insert("x-lenient".into(), true.into()); + } + Value::Object(o) +} + +fn bound_keywords(o: &mut Map, min: Option<&Bound>, max: Option<&Bound>) { + let low = match min { + Some(Bound::Inclusive(a)) => Some(("minimum", a)), + Some(Bound::Exclusive(a)) => Some(("exclusiveMinimum", a)), + None => None, + }; + let high = match max { + Some(Bound::Inclusive(b)) => Some(("maximum", b)), + Some(Bound::Exclusive(b)) => Some(("exclusiveMaximum", b)), + None => None, + }; + for (key, x) in low.into_iter().chain(high) { + o.insert(key.into(), json!(x)); + } +} + +fn type_schema(ty: &Type, depth: usize) -> Value { + match ty { + Type::Object(_) | Type::Array(_) if depth >= MAX_DEPTH => Value::Bool(true), + Type::Number { min, max, unit } => { + let mut o = Map::new(); + o.insert("type".into(), "number".into()); + bound_keywords(&mut o, min.as_ref(), max.as_ref()); + if let Some(u) = unit { + o.insert("x-unit".into(), (*u).into()); + } + Value::Object(o) + } + Type::Integer { min, max } => { + let mut o = Map::new(); + o.insert("type".into(), "integer".into()); + if let Some(m) = min { + o.insert("minimum".into(), (*m).into()); + } + if let Some(m) = max { + o.insert("maximum".into(), (*m).into()); + } + Value::Object(o) + } + Type::Boolean => json!({"type": "boolean"}), + Type::String => json!({"type": "string"}), + Type::Enum(names) => json!({"enum": names}), + Type::Id => json!({"type": "integer", "minimum": 0, "maximum": MAX_ID, "x-kind": "id"}), + Type::Ids => json!({"type": "array", "items": {"type": "integer", "minimum": 0, "maximum": MAX_ID, "x-kind": "id"}}), + Type::Color => json!({ + "anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "number"}, "minItems": 3}, {"type": "object"}], + "x-kind": "color", + }), + Type::Point => json!({ + "type": "array", + "prefixItems": [{"type": "number"}, {"type": "number"}], + "items": false, + "minItems": 2, + "x-kind": "point", + }), + Type::Object(params) => Value::Object(object_schema(params, depth + 1)), + Type::Array(item) => json!({"type": "array", "items": type_schema(item, depth + 1)}), + } +} + +#[cfg(test)] +mod conformance; +#[cfg(test)] +mod tests; diff --git a/crates/apischema/src/tests.rs b/crates/apischema/src/tests.rs new file mode 100644 index 0000000000..30b939879a --- /dev/null +++ b/crates/apischema/src/tests.rs @@ -0,0 +1,536 @@ +//! Tests of the validator, the params text and the JSON form, on schemas written here. + +use serde_json::{Value, json}; + +use crate::*; + +/// The schema with the one parameter `x` of type `ty`. +fn one(ty: Type) -> ParamSchema { + let params: &'static [Param] = Box::leak(Box::new([Param::new("x", ty)])); + ParamSchema::new(params, "") +} + +/// Whether `{x: v}` passes the schema of `ty`; on a refusal, the error must name `x`. +fn passes(ty: Type, v: Value) -> bool { + match one(ty).validate(&json!({ "x": v })) { + Ok(_) => true, + Err(e) => { + assert!(e.path.starts_with('x'), "{e}"); + assert!(e.to_string().contains("`x"), "{e}"); + false + } + } +} + +#[test] +fn numbers_are_checked_against_their_range() { + let any = Type::NUMBER; + assert!(passes(any, json!(-3.5)) && passes(any, json!(7))); + assert!(!passes(any, json!("7")) && !passes(any, json!(null)) && !passes(any, json!(true))); + let positive = Type::Number { min: Some(Bound::Exclusive(0.0)), max: None, unit: None }; + assert!(passes(positive, json!(0.001))); + assert!(!passes(positive, json!(0)) && !passes(positive, json!(-1))); + let percent = Type::Number { min: Some(Bound::Inclusive(0.0)), max: Some(Bound::Inclusive(100.0)), unit: Some("%") }; + assert!(passes(percent, json!(0)) && passes(percent, json!(100))); + assert!(!passes(percent, json!(100.5))); + let below = Type::Number { min: None, max: Some(Bound::Exclusive(1.0)), unit: None }; + assert!(passes(below, json!(0.99)) && !passes(below, json!(1))); + assert_eq!(one(positive).validate(&json!({"x": 0})).unwrap_err().to_string(), "`x` must be a number > 0, not 0"); + assert_eq!(one(percent).validate(&json!({"x": 101})).unwrap_err().to_string(), "`x` must be a number 0 to 100 (%), not 101"); +} + +#[test] +fn integers_take_no_fraction_and_keep_their_range() { + let any = Type::Integer { min: None, max: None }; + assert!(passes(any, json!(-4)) && passes(any, json!(u64::MAX))); + assert!(!passes(any, json!(1.5)) && !passes(any, json!("2"))); + let small = Type::Integer { min: Some(1), max: Some(25) }; + assert!(passes(small, json!(1)) && passes(small, json!(25))); + assert!(!passes(small, json!(0)) && !passes(small, json!(26)) && !passes(small, json!(u64::MAX))); + assert!(passes(small, json!(25.0)) && !passes(small, json!(26.0)) && !passes(small, json!(1e300)) && !passes(small, json!(-1e300))); + let negative = Type::Integer { min: None, max: Some(-1_000_000_000_000_000_000) }; + assert!(passes(negative, json!(-1e20)) && !passes(negative, json!(1e20))); + let lowest = Type::Integer { min: Some(i64::MIN), max: None }; + assert!(!passes(lowest, json!(-1e20)) && passes(lowest, json!(1e20))); +} + +/// JSON Schema counts a number with no fractional part as an integer: `2.0` passes, and the +/// command gets `2`. +#[test] +fn a_whole_number_written_with_a_fraction_is_an_integer() { + let any = Type::Integer { min: None, max: None }; + assert_eq!(one(any).validate(&json!({"x": 2.0})).unwrap(), Some(json!({"x": 2}))); + assert_eq!(one(any).validate(&json!({"x": 2})).unwrap(), None); + assert!(passes(any, json!(1e300))); + assert_eq!(one(Type::Id).validate(&json!({"x": 7.0})).unwrap(), Some(json!({"x": 7}))); + assert_eq!(one(Type::Ids).validate(&json!({"x": [1, 2.0]})).unwrap(), Some(json!({"x": [1, 2]}))); + assert!(passes(Type::Id, json!(MAX_ID)) && !passes(Type::Id, json!(MAX_ID + 1)) && !passes(Type::Id, json!(1e300))); + assert_eq!(one(Type::Ids).validate(&json!({"x": [1, "2"]})).unwrap_err().path, "x[1]"); +} + +/// A value with no finite number in it reads as null in JSON, and a number refuses it; the largest +/// finite numbers pass a number with no range. +#[test] +fn numbers_at_the_edges() { + assert!(!passes(Type::NUMBER, json!(f64::NAN)) && !passes(Type::NUMBER, json!(f64::INFINITY))); + assert!(passes(Type::NUMBER, json!(f64::MAX)) && passes(Type::NUMBER, json!(f64::MIN))); + let unit = Type::Number { min: Some(Bound::Inclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: None }; + assert!(passes(unit, json!(0.0)) && passes(unit, json!(1.0)) && !passes(unit, json!(-1e-300)) && !passes(unit, json!(1.0000001))); +} + +/// A list too long to name one path per entry costs one pass, and the error names the entry. +#[test] +fn a_huge_list_is_checked_once_and_names_the_entry() { + let mut ids: Vec = (0..200_000u64).map(Value::from).collect(); + assert_eq!(one(Type::Ids).validate(&json!({ "x": ids })).unwrap(), None); + ids.push(json!("no")); + let e = one(Type::Ids).validate(&json!({ "x": ids })).unwrap_err(); + assert_eq!(e.path, "x[200000]"); + assert!(e.to_string().chars().count() < 120, "{e}"); +} + +/// A list nested far past anything the schema can take: dropping or writing it out recurses per +/// level, which is why the test leaks it rather than dropping it. +fn nested_lists(levels: usize) -> Value { + (0..levels).fold(json!(1), |inner, _| Value::Array(vec![inner])) +} + +/// A refused value is shown from its start only, however deep or long it is, so an error costs +/// the same for a hostile value as for a small one. +#[test] +fn a_refused_value_is_read_only_as_far_as_it_is_shown() { + let deep = nested_lists(500_000); + let params = json!({}); + let mut map = params.as_object().unwrap().clone(); + map.insert("x".into(), deep); + let params = Value::Object(map); + let e = one(Type::String).validate(¶ms).unwrap_err(); + assert!(e.to_string().starts_with("`x` must be a string, not [[[[") && e.to_string().ends_with('…'), "{e}"); + assert!(e.to_string().chars().count() <= 100, "{e}"); + std::mem::forget(params); + + let huge = "x".repeat(5_000_000); + let e = one(Type::Boolean).validate(&json!({ "x": huge })).unwrap_err(); + assert!(e.to_string().chars().count() <= 100, "{}", e.to_string().len()); + assert!(e.to_string().ends_with('…')); + + let e = one(Type::Boolean).validate(&json!({"x": {"a": 1, "b": [1, 2]}})).unwrap_err(); + assert_eq!(e.to_string(), "`x` must be true or false, not {\"a\":1,\"b\":[1,2]}"); + let e = ParamSchema::new(&[], "").validate(&nested_lists(3)).unwrap_err(); + assert_eq!(e.to_string(), "the params must be an object, not [[[1]]]"); +} + +/// A list entry made an integer, and a default filled in, don't copy a value that is still to be +/// checked: copying recurses per level. +#[test] +fn a_list_with_a_change_is_not_copied_before_all_of_it_is_checked() { + let params = Value::Object([("x".to_string(), Value::Array(vec![json!(2.0), nested_lists(500_000)]))].into_iter().collect()); + assert_eq!(one(Type::Ids).validate(¶ms).unwrap_err().path, "x[1]"); + std::mem::forget(params); +} + +#[test] +fn an_object_with_a_default_is_not_copied_before_all_of_it_is_checked() { + const FILLED_FIRST: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::String)]; + let params = Value::Object([("b".to_string(), nested_lists(500_000))].into_iter().collect()); + assert_eq!(ParamSchema::new(FILLED_FIRST, "").validate(¶ms).unwrap_err().path, "b"); + std::mem::forget(params); +} + +/// A value the schema doesn't look inside is measured before a default copies the object it is in. +const WITH_DEFAULT: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::Color).optional()]; +const LENIENT_AFTER_DEFAULT: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::Boolean).optional().lenient()]; + +fn holding(key: &str, v: Value) -> Value { + Value::Object([(key.to_string(), v)].into_iter().collect()) +} + +/// The lists of fixed shape count toward the nesting limit as the other lists do. +#[test] +fn id_lists_points_and_color_lists_count_toward_the_nesting_limit() { + let check = |depth, ty: &Type, v: &Value| check_value(&At::Root, depth, ty, v, false, false); + for (ty, v) in [(Type::Ids, json!([1])), (Type::Point, json!([1, 2])), (Type::Color, json!([1, 0, 0]))] { + assert!(check(MAX_DEPTH - 1, &ty, &v).is_ok(), "{ty:?}"); + assert_eq!(check(MAX_DEPTH, &ty, &v).unwrap_err().problem, Problem::TooDeep, "{ty:?}"); + } + assert!(check(MAX_DEPTH, &Type::Color, &json!("#ff0000")).is_ok()); +} + +#[test] +fn a_saved_retired_key_past_the_nesting_limit_is_refused() { + let params = holding("older", nested_lists(500_000)); + let e = ParamSchema::new(WITH_DEFAULT, "").validate_saved(¶ms).unwrap_err(); + assert_eq!(e.path, "older"); + assert!(matches!(e.problem, Problem::Unknown { .. })); + std::mem::forget(params); + let kept = ParamSchema::new(WITH_DEFAULT, "").validate_saved(&holding("older", nested_lists(MAX_DEPTH))).unwrap().unwrap(); + assert_eq!(kept["a"], json!(0)); + assert_eq!(kept["older"], nested_lists(MAX_DEPTH)); + assert!(ParamSchema::new(WITH_DEFAULT, "").validate_saved(&holding("older", nested_lists(MAX_DEPTH + 1))).is_err()); +} + +#[test] +fn a_color_object_past_the_nesting_limit_is_refused() { + let params = holding("b", holding("k", nested_lists(500_000))); + let e = ParamSchema::new(WITH_DEFAULT, "").validate(¶ms).unwrap_err(); + assert_eq!(e.path, "b"); + assert!(matches!(e.problem, Problem::WrongType { .. })); + std::mem::forget(params); + assert!(ParamSchema::new(WITH_DEFAULT, "").validate(&json!({"b": {"r": 1, "g": 0, "b": 0}})).is_ok()); +} + +#[test] +fn a_lenient_value_past_the_nesting_limit_is_refused() { + let params = holding("b", nested_lists(500_000)); + let e = ParamSchema::new(LENIENT_AFTER_DEFAULT, "").validate(¶ms).unwrap_err(); + assert_eq!(e.path, "b"); + assert!(matches!(e.problem, Problem::WrongType { .. })); + std::mem::forget(params); + assert_eq!(ParamSchema::new(LENIENT_AFTER_DEFAULT, "").validate(&json!({"b": [1]})).unwrap().unwrap()["b"], json!([1])); +} + +/// A key is cut in the error, and an unknown key is refused whatever it holds. +#[test] +fn a_hostile_key_is_cut_and_refused() { + let key = "k".repeat(1_000_000); + let e = one(Type::Boolean).validate(&json!({ key: true, "x": true })).unwrap_err(); + assert_eq!(e.path.chars().count(), KEY_CHARS + 1); + assert!(e.path.ends_with('…') && e.to_string().chars().count() < 200, "{}", e.path.len()); + for key in ["", "a.b", "a[0]", "`", "\u{0}", "名前"] { + let e = one(Type::Boolean).validate(&json!({ key: true, "x": true })).unwrap_err(); + assert_eq!(e.path, key); + assert!(matches!(e.problem, Problem::Unknown { .. })); + } + assert_eq!(shown_key("short"), "short"); +} + +/// A schema that refers to itself, which only a mistake can write: checking values stops at the +/// nesting limit, and the writers finish. +static ENDLESS: Type = Type::Array(&ENDLESS); + +#[test] +fn a_schema_that_refers_to_itself_stops_at_the_nesting_limit() { + let s = one(ENDLESS); + let e = s.validate(&json!({ "x": nested_lists(MAX_DEPTH + 2) })).unwrap_err(); + assert_eq!(e.problem, Problem::TooDeep); + assert!(e.path.starts_with("x[0][0]")); + assert!(s.definition_problem().is_some_and(|p| p.contains("nests deeper"))); + assert!(s.params_text().contains('…')); + assert!(s.to_json()["properties"]["x"].is_object()); + assert_ne!(hash([("a", &s)]), 0); +} + +const BAD_DEFAULT: &[Param] = &[Param::new("x", Type::NUMBER).defaults_to("\"zero\"")]; +const NOT_JSON: &[Param] = &[Param::new("x", Type::NUMBER).defaults_to("{")]; +const TWICE: &[Param] = &[Param::new("x", Type::NUMBER), Param::new("x", Type::String)]; +const EMPTY_NAME: &[Param] = &[Param::new("", Type::NUMBER)]; +const PATH_NAME: &[Param] = &[Param::new("a.b", Type::NUMBER)]; +const NO_NAMES: &[Param] = &[Param::new("x", Type::Enum(&[]))]; +const SAME_NAMES: &[Param] = &[Param::new("x", Type::Enum(&["a", "a"]))]; +const EMPTY_RANGE: &[Param] = &[Param::new("x", Type::Number { min: Some(Bound::Exclusive(1.0)), max: Some(Bound::Inclusive(1.0)), unit: None })]; +const BACKWARD: &[Param] = &[Param::new("x", Type::Integer { min: Some(2), max: Some(1) })]; +const NOT_FINITE: &[Param] = &[Param::new("x", Type::Number { min: None, max: Some(Bound::Inclusive(f64::INFINITY)), unit: None })]; +const REQUIRED_DEFAULT: &[Param] = &[Param { required: true, omitted: Omitted::Value("1"), ..Param::new("x", Type::NUMBER) }]; +const DEEP_FAULT: &[Param] = &[Param::new("edits", Type::Array(&Type::Object(TWICE)))]; + +#[test] +fn a_schema_that_is_wrong_in_itself_is_reported() { + for (params, why) in [ + (BAD_DEFAULT, "doesn't pass its type"), + (NOT_JSON, "isn't JSON"), + (TWICE, "listed twice"), + (EMPTY_NAME, "empty or holds"), + (PATH_NAME, "empty or holds"), + (NO_NAMES, "no names"), + (SAME_NAMES, "repeats"), + (EMPTY_RANGE, "no value can be"), + (BACKWARD, "no value can be"), + (NOT_FINITE, "isn't finite"), + (REQUIRED_DEFAULT, "required"), + (DEEP_FAULT, "`edits[].x` is listed twice"), + ] { + let problem = ParamSchema::new(params, "").definition_problem(); + assert!(problem.as_deref().is_some_and(|p| p.contains(why)), "{params:?}: {problem:?}"); + } + assert_eq!(ParamSchema::new(VIEW, "").definition_problem(), None); + assert_eq!(ParamSchema::new(&[], "").definition_problem(), None); +} + +/// Saved steps keep keys the schema doesn't name, at any depth; the values it names are checked. +#[test] +fn saved_steps_pass_retired_keys_and_check_their_values() { + let edits = one(Type::Array(&Type::Object(EDIT))); + let retired = json!({"x": [{"name": "A", "old": 1}], "older": true}); + assert!(edits.validate(&retired).is_err()); + let filled = edits.validate_saved(&retired).unwrap().unwrap(); + assert_eq!(filled["x"][0]["delete"], json!(false), "defaults are filled in"); + assert_eq!(filled["older"], json!(true), "the keys stay"); + assert_eq!(edits.validate_saved(&json!({"x": [{"name": 5}], "older": true})).unwrap_err().path, "x[0].name"); + assert_eq!(edits.validate_saved(&json!({"older": true})).unwrap_err().problem, Problem::Missing); +} + +/// Every type's JSON form follows the 2020-12 rules, and an independent validator of those rules +/// agrees with [`ParamSchema::validate`] on each value. +#[test] +fn the_json_form_and_the_validator_agree_with_the_2020_12_rules() { + const NULLABLE: &[Param] = &[Param::new("a", Type::String).optional().null_omitted(), Param::new("b", Type::Boolean).defaults_to("true")]; + let types = [ + Type::NUMBER, + Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: Some("pt") }, + Type::Number { min: Some(Bound::Inclusive(-1.0)), max: Some(Bound::Exclusive(1.0)), unit: None }, + Type::Integer { min: None, max: None }, + Type::Integer { min: Some(1), max: Some(25) }, + Type::Boolean, + Type::String, + Type::Enum(&["a", "b"]), + Type::Id, + Type::Ids, + Type::Color, + Type::Point, + Type::Object(EDIT), + Type::Object(NULLABLE), + Type::Object(&[]), + Type::Array(&Type::NUMBER), + Type::Array(&Type::Object(EDIT)), + ]; + let values = [ + json!(null), + json!(true), + json!(0), + json!(1), + json!(2.0), + json!(25.5), + json!(-1), + json!(-1.0), + json!(1e300), + json!(MAX_ID), + json!(MAX_ID + 1), + json!(u64::MAX), + json!(""), + json!("a"), + json!("c"), + json!([]), + json!([1, 2]), + json!([1, 2, 3]), + json!([1, "2"]), + json!([[1]]), + json!({}), + json!({"name": "A"}), + json!({"name": "A", "delete": false}), + json!({"name": "A", "delete": null}), + json!({"name": "A", "other": 1}), + json!({"a": null, "b": false}), + json!({"a": 5}), + json!([{"name": "A"}]), + json!([{"name": 1}]), + ]; + for ty in types { + let schema = one(ty); + let written = schema.to_json(); + conformance::check_schema(&written, "#").unwrap_or_else(|e| panic!("{ty:?}: {e}\n{written:#}")); + assert_eq!(written["$schema"], "https://json-schema.org/draft/2020-12/schema"); + for v in &values { + let params = json!({ "x": v }); + let local = schema.validate(¶ms).is_ok(); + assert_eq!(local, conformance::instance_valid(&written, ¶ms), "{ty:?} on {v}: {written}"); + } + } + for params in [VIEW, EDIT, NULLABLE] { + let schema = ParamSchema::new(params, "").deprecated(1); + conformance::check_schema(&schema.to_json(), "#").unwrap(); + } +} + +/// The independent checker refuses what the 2020-12 rules refuse, so its passes above mean +/// something. +#[test] +fn the_2020_12_checker_refuses_invalid_schemas() { + for bad in [ + json!(5), + json!({"type": "float"}), + json!({"enum": []}), + json!({"enum": [1, 1]}), + json!({"required": ["a", "a"]}), + json!({"required": [1]}), + json!({"properties": []}), + json!({"properties": {"a": 5}}), + json!({"items": 1}), + json!({"prefixItems": []}), + json!({"anyOf": []}), + json!({"minimum": "0"}), + json!({"minItems": -1}), + json!({"description": 5}), + json!({"deprecated": "yes"}), + json!({"type": "number", "default": "zero"}), + json!({"$schema": "not a uri"}), + json!({"minimun": 0}), + ] { + assert!(conformance::check_schema(&bad, "#").is_err(), "{bad}"); + } + assert!(conformance::instance_valid(&json!({"type": "integer"}), &json!(2.0))); + assert!(!conformance::instance_valid(&json!({"type": "integer"}), &json!(2.5))); + assert!(!conformance::instance_valid(&json!({"prefixItems": [{"type": "number"}], "items": false}), &json!([1, 2]))); +} + +#[test] +fn booleans_and_strings_take_only_their_own_type() { + assert!(passes(Type::Boolean, json!(true)) && passes(Type::Boolean, json!(false))); + assert!(!passes(Type::Boolean, json!("true")) && !passes(Type::Boolean, json!(1)) && !passes(Type::Boolean, json!(null))); + assert!(passes(Type::String, json!("")) && passes(Type::String, json!("View 1"))); + assert!(!passes(Type::String, json!(5)) && !passes(Type::String, json!(["a"]))); + assert_eq!(one(Type::Boolean).validate(&json!({"x": "yes"})).unwrap_err().to_string(), "`x` must be true or false, not \"yes\""); +} + +#[test] +fn an_enum_takes_one_of_its_names() { + let modes = Type::Enum(&["rgb", "cmyk"]); + assert!(passes(modes, json!("rgb")) && passes(modes, json!("cmyk"))); + assert!(!passes(modes, json!("RGB")) && !passes(modes, json!("lab")) && !passes(modes, json!(0))); + assert_eq!(one(modes).validate(&json!({"x": "lab"})).unwrap_err().to_string(), "`x` must be one of \"rgb\", \"cmyk\", not \"lab\""); +} + +#[test] +fn ids_are_non_negative_integers() { + assert!(passes(Type::Id, json!(0)) && passes(Type::Id, json!(42))); + assert!(!passes(Type::Id, json!(-1)) && !passes(Type::Id, json!(1.5)) && !passes(Type::Id, json!("42"))); + assert!(passes(Type::Ids, json!([])) && passes(Type::Ids, json!([3, 4]))); + assert!(!passes(Type::Ids, json!(3)) && !passes(Type::Ids, json!([3, "4"])) && !passes(Type::Ids, json!([-3]))); +} + +#[test] +fn colors_and_points_have_their_shapes() { + assert!(passes(Type::Color, json!("#ff0000")) && passes(Type::Color, json!([1, 0, 0])) && passes(Type::Color, json!({"gray": 50}))); + assert!(!passes(Type::Color, json!(5)) && !passes(Type::Color, json!([1, 0])) && !passes(Type::Color, json!([1, 0, "x"]))); + assert!(passes(Type::Point, json!([0, -2.5]))); + assert!(!passes(Type::Point, json!([1])) && !passes(Type::Point, json!([1, 2, 3])) && !passes(Type::Point, json!([1, "2"]))); + assert!(!passes(Type::Point, json!({"x": 1, "y": 2}))); +} + +const EDIT: &[Param] = &[Param::new("name", Type::String), Param::new("delete", Type::Boolean).defaults_to("false")]; + +#[test] +fn objects_and_arrays_name_the_path_of_the_value_inside() { + let edits = Type::Array(&Type::Object(EDIT)); + assert!(passes(edits, json!([])) && passes(edits, json!([{"name": "A"}, {"name": "B", "delete": true}]))); + let err = |v: Value| one(edits).validate(&json!({ "x": v })).unwrap_err(); + assert_eq!(err(json!([{"name": "A"}, {"name": "B", "delete": "no"}])).path, "x[1].delete"); + assert_eq!(err(json!([{"name": "A"}, {"delete": true}])).to_string(), "missing `x[1].name`"); + let unknown = err(json!([{"name": "A", "nmae": "B"}])); + assert_eq!((unknown.path.as_str(), unknown.problem), ("x[0].nmae", Problem::Unknown { keys: vec!["name", "delete"] })); + assert_eq!(err(json!({"name": "A"})).to_string(), "`x` must be a list, not {\"name\":\"A\"}"); + assert_eq!(err(json!(["A"])).to_string(), "`x[0]` must be an object, not \"A\""); + // Defaults inside are filled in too. + let filled = one(edits).validate(&json!({"x": [{"name": "A"}]})).unwrap(); + assert_eq!(filled, Some(json!({"x": [{"name": "A", "delete": false}]}))); +} + +const VIEW: &[Param] = &[ + Param::new("name", Type::String).default_note("\"View N\"").null_omitted(), + Param::new("center", Type::Point), + Param::new("rotation", Type::Number { min: None, max: None, unit: Some("deg") }).defaults_to("0"), +]; + +#[test] +fn keys_requirements_nulls_and_defaults() { + let s = ParamSchema::new(VIEW, "save a view").returns("{name}"); + // Unknown keys are refused first, naming the key and the keys the command takes. + let e = s.validate(&json!({"centre": [0, 0]})).unwrap_err(); + assert_eq!((e.path.as_str(), e.problem), ("centre", Problem::Unknown { keys: vec!["name", "center", "rotation"] })); + assert_eq!(s.validate(&json!({})).unwrap_err(), ParamError { path: "center".into(), problem: Problem::Missing }); + // Null counts as omitted only where the schema says so. + assert_eq!(s.validate(&json!({"center": [1, 2], "name": null, "rotation": 15})).unwrap(), None); + assert_eq!(s.validate(&json!({"center": [1, 2], "rotation": null})).unwrap_err().path, "rotation"); + // An omitted value with a default gets it; one with a note is left to the command. + assert_eq!(s.validate(&json!({"center": [1, 2]})).unwrap(), Some(json!({"center": [1, 2], "rotation": 0}))); + // Params that aren't an object are refused; null params are `{}`. + assert_eq!(s.validate(&json!(5)).unwrap_err().to_string(), "the params must be an object, not 5"); + assert_eq!(s.validate(&Value::Null).unwrap_err().path, "center"); + let none = ParamSchema::new(&[], ""); + assert_eq!(none.validate(&Value::Null).unwrap(), None); + assert_eq!(none.validate(&json!({"a": 1})).unwrap_err().to_string(), "unknown parameter `a`; the object takes no keys"); +} + +const LENIENT: &[Param] = &[Param::new("on", Type::Boolean).optional().lenient(), Param::new("size", Type::NUMBER).optional().lenient()]; + +#[test] +fn lenient_parameters_pass_values_of_another_type_to_the_command() { + let s = ParamSchema::new(LENIENT, ""); + assert_eq!(s.validate(&json!({"on": "yes", "size": "12"})).unwrap(), None); + // Unknown keys are still refused. + assert!(s.validate(&json!({"of": true})).is_err()); + // The JSON form states the documented type, so a validator of that form refuses what passes here. + let written = s.to_json(); + assert_eq!(written["properties"]["on"]["x-lenient"], true); + assert!(!conformance::instance_valid(&written, &json!({"on": "yes"}))); + assert!(conformance::instance_valid(&written, &json!({"on": true}))); +} + +#[test] +fn the_params_text_lists_each_parameter_with_its_type() { + let s = ParamSchema::new(VIEW, "save a view").returns("{name}"); + assert_eq!(s.params_text(), "{name?: string (default: \"View N\"), center: [x, y], rotation?: number deg (default: 0)} save a view → {name}"); + const ALL: &[Param] = &[ + Param::new("a", Type::Integer { min: Some(1), max: Some(25) }), + Param::new("b", Type::Enum(&["x", "y"])).optional(), + Param::new("c", Type::Ids).optional().doc("instead of the selection"), + Param::new("d", Type::Color).optional().deprecated(2), + Param::new("e", Type::Array(&Type::Object(EDIT))).optional(), + Param::new("f", Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(10.0)), unit: Some("pt") }).optional(), + ]; + assert_eq!( + ParamSchema::new(ALL, "").params_text(), + "{a: integer 1 to 25, b?: \"x\"|\"y\", c?: [id…] (instead of the selection), d?: color (deprecated), \ + e?: [{name: string, delete?: bool (default: false)}…], f?: number > 0 and <= 10 pt}" + ); +} + +#[test] +fn the_json_form_is_an_object_schema() { + let s = ParamSchema::new(VIEW, "save a view").returns("{name}").writes(Writes::Document).cost(2); + let j = s.to_json(); + assert_eq!(j["$schema"], DIALECT); + assert_eq!(j["type"], "object"); + assert_eq!(j["additionalProperties"], false); + assert_eq!(j["required"], json!(["center"])); + assert_eq!(j["properties"]["name"]["anyOf"], json!([{"type": "string"}, {"type": "null"}])); + assert_eq!(j["properties"]["name"]["x-default"], "\"View N\""); + assert_eq!(j["properties"]["rotation"], json!({"type": "number", "x-unit": "deg", "default": 0, "x-since": 1})); + assert_eq!(j["properties"]["center"]["prefixItems"], json!([{"type": "number"}, {"type": "number"}])); + assert_eq!((j["x-cost"].clone(), j["x-writes"].clone(), j["x-returns"].clone()), (json!(2), json!("document"), json!("{name}"))); + let range = one(Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: None }).to_json(); + assert_eq!(range["properties"]["x"], json!({"type": "number", "exclusiveMinimum": 0.0, "maximum": 1.0, "x-since": 1})); +} + +/// Null params read as `{}`, so the root of the JSON form allows null exactly when `{}` passes. +/// A nested object does not read null as `{}`. +#[test] +fn the_json_form_allows_null_params_when_no_parameter_is_required() { + const OPTIONAL: &[Param] = &[Param::new("inner", Type::Object(&[Param::new("y", Type::Boolean).optional()])).optional()]; + let optional = ParamSchema::new(OPTIONAL, ""); + let written = optional.to_json(); + conformance::check_schema(&written, "#").unwrap(); + assert_eq!(written["type"], json!(["object", "null"])); + assert_eq!(written["properties"]["inner"]["type"], "object"); + let required = one(Type::Boolean); + assert_eq!(required.to_json()["type"], "object"); + for schema in [optional, required] { + let written = schema.to_json(); + for params in [json!(null), json!({}), json!(5), json!([]), json!("x"), json!({"inner": null}), json!({"inner": {}})] { + assert_eq!(schema.validate(¶ms).is_ok(), conformance::instance_valid(&written, ¶ms), "{params} against {written}"); + } + } + assert!(optional.validate(&json!(null)).is_ok()); + assert!(required.validate(&json!(null)).is_err()); +} + +#[test] +fn the_hash_follows_every_schema_but_not_their_order() { + let a = ParamSchema::new(VIEW, "save a view"); + let b = ParamSchema::new(LENIENT, ""); + let h = hash([("view.a", &a), ("view.b", &b)]); + assert_eq!(h, hash([("view.b", &b), ("view.a", &a)])); + assert_ne!(h, hash([("view.a", &a)])); + assert_ne!(h, hash([("view.a", &a), ("view.c", &b)])); + let changed = ParamSchema::new(VIEW, "save a view").since(2); + assert_ne!(h, hash([("view.a", &changed), ("view.b", &b)])); +} diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 3ac145fd22..2e19ad44a3 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -8,7 +8,6 @@ mod layers; mod profile; mod stroke_style; -pub(crate) use layers::HEAD_REACH; pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds}; pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile}; pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign}; diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index 880f3490da..923275999b 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -139,10 +139,6 @@ impl StrokeGradientMode { } } -/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are -/// cut square a little behind its 4 × 4 box). -pub(crate) const HEAD_REACH: f64 = 4.6; - fn ten() -> f64 { 10.0 } @@ -188,7 +184,8 @@ impl StrokeLayer { } } /// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least - /// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide. + /// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see + /// [`Arrowhead::reach`] and [`Arrowhead::half_width`]). pub fn arrow_weight(&self, end: bool) -> f64 { let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 }; (self.width * pct / 100.0).max(0.25) @@ -197,7 +194,7 @@ impl StrokeLayer { /// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap. pub fn head_reach(&self, end: bool) -> f64 { let head = if end { self.end_arrow } else { self.start_arrow }; - head.map_or(0.0, |_| HEAD_REACH * self.arrow_weight(end) + self.width / 2.0) + head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0) } /// How far the arrowheads can reach from the path's end points (0 without heads). pub fn arrow_reach(&self) -> f64 { diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs index acd4d81890..46a0c30c33 100644 --- a/crates/doc/src/appearance/stroke_style.rs +++ b/crates/doc/src/appearance/stroke_style.rs @@ -49,6 +49,10 @@ impl Dash { } } +/// How far the arrowheads drawn in the 4 × 4 box reach from their tip, in units of their weight +/// (the open arrow's arms are cut square a little behind the box). +const HEAD_REACH: f64 = 4.6; + /// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Arrowhead { @@ -94,13 +98,18 @@ pub enum Arrowhead { Kite, TriangleBar, Oval, + /// Two arms of the head's weight (the line's weight at 100 % scale, for lines of 0.25 pt or + /// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as + /// the other heads. + LineArrow, } impl Arrowhead { /// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks). - pub const ALL: [Arrowhead; 40] = [ + pub const ALL: [Arrowhead; 41] = [ Arrowhead::Arrow, Arrowhead::ArrowOpen, + Arrowhead::LineArrow, Arrowhead::Barbed, Arrowhead::Concave, Arrowhead::DoubleArrow, @@ -141,6 +150,22 @@ impl Arrowhead { Arrowhead::Fork, ]; + /// How far any part of the head can be from its tip, in units of its weight. + pub fn reach(self) -> f64 { + match self { + // Its farthest corners are 4 + ½√2 back and 4 − ½√2 out. + Arrowhead::LineArrow => 5.75, + _ => HEAD_REACH, + } + } + /// How far the head spreads either side of its line, in units of its weight. + pub fn half_width(self) -> f64 { + match self { + Arrowhead::LineArrow => 4.0, + _ => 2.0, + } + } + /// The name the arrowhead menus show. pub fn label(self) -> &'static str { match self { @@ -184,6 +209,7 @@ impl Arrowhead { Arrowhead::Kite => "Kite", Arrowhead::TriangleBar => "Triangle to Bar", Arrowhead::Oval => "Oval", + Arrowhead::LineArrow => "Line Arrow", } } } diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index c297b34759..0a1b3e1a5d 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -219,7 +219,7 @@ fn profile_presets_round_trip_their_ids() { #[test] fn arrowhead_names_are_stable_and_every_one_is_listed_once() { // Saved files store these names: they may only ever be appended to. - const SAVED: [&str; 40] = [ + const SAVED: [&str; 41] = [ "Triangle", "TriangleOpen", "Circle", @@ -260,6 +260,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() { "Kite", "TriangleBar", "Oval", + "LineArrow", ]; for name in SAVED { let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap(); @@ -293,9 +294,15 @@ fn outset_covers_arrowheads() { st.arrow_scale = (100.0, 200.0); assert_eq!(st.arrow_weight(false), 4.0); assert_eq!(st.arrow_weight(true), 8.0); - assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0)); + let reach = Arrowhead::Triangle.reach(); + assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, reach * 8.0 + 2.0)); // A 32 pt head whose tip sits up to its length (plus the cap) past the end point. - assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0); + assert_eq!(a.outset(), reach * 8.0 + 2.0); + // The line arrow's arms spread twice as wide, so it reaches further from its tip. + a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::LineArrow); + assert!(Arrowhead::LineArrow.reach() > reach); + assert_eq!(a.outset(), Arrowhead::LineArrow.reach() * 8.0 + 2.0); + a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::Triangle); a.stroke_mut().unwrap().width = 0.01; assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size"); } diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 5ea0ff9bd5..d6b7eda2c5 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -750,6 +750,7 @@ fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64 if resized { o.cached_bounds = None; o.cached_baselines.clear(); + o.cached_ink = None; } } diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index ebd27fd87f..2a2f8a8d7a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -276,6 +276,11 @@ impl Document { self.next_id } + /// Makes the next id at least `id`, so ids below it are not given out again. + pub fn raise_next_id(&mut self, id: u64) { + self.next_id = self.next_id.max(id); + } + /// Ensure `next_id` is above every id in the tree (after deserializing foreign data). pub fn fix_next_id(&mut self) { // Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index c40dcf9f21..ebb2fc44eb 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -123,18 +123,33 @@ impl Document { std::borrow::Cow::Owned(d) } - /// Does `wants` hold for a node anywhere in the document's art: the layers, symbol definitions, - /// graph designs, pattern swatches (the one being edited included) and their opacity masks? - pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool { - let roots = self - .layers + /// The roots of every tree of the document's art: the layers, symbol definitions, graph designs, + /// pattern swatches and the original of the pattern being edited. Opacity masks hang off nodes + /// in these trees. + pub fn art_roots(&self) -> impl Iterator> { + self.layers .iter() .chain(self.symbols.iter().map(|s| &s.art)) .chain(self.graph_designs.iter().map(|g| &g.art)) .chain(self.patterns.iter().flat_map(|p| p.art.iter())) - .chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter())); + .chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter())) + } + + /// [`Self::art_roots`], to change. + pub fn art_roots_mut(&mut self) -> impl Iterator> { + self.layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())) + } + + /// Does `wants` hold for a node anywhere in the document's art ([`Self::art_roots`]) or its + /// opacity masks? + pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool { let mut any = false; - for root in roots { + for root in self.art_roots() { crate::swatches::walk_with_masks(root, &mut |n| any |= wants(n)); } any @@ -144,14 +159,7 @@ impl Document { /// [`Self::any_node`] looks). Only the trees that hold such a node are copied out of the art /// they share. pub fn edit_nodes_where(&mut self, wants: impl Fn(&Node) -> bool, mut f: impl FnMut(&mut Node)) { - let roots = self - .layers - .iter_mut() - .chain(self.symbols.iter_mut().map(|s| &mut s.art)) - .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) - .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) - .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); - for root in roots { + for root in self.art_roots_mut() { edit_branches_where(root, &wants, &mut f); } } diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index f4a037f365..510de3a4de 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -347,6 +347,7 @@ impl Document { t.first_para_continues = false; t.cached_bounds = None; t.cached_baselines.clear(); + t.cached_ink = None; } let on_path = n.extras().objects_on_path.is_some(); let mut renamed = std::collections::HashMap::new(); diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs index 3ab3eb6553..c5bf1972d8 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -71,6 +71,7 @@ impl Document { } if changed { t.cached_bounds = None; + t.cached_ink = None; } changed } diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 4a864a6e9f..304c4e70f6 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -643,6 +643,168 @@ mod tests { assert!(e.p1.distance(Point::new(30.0, 0.0)) < 1e-6 && e.p2.distance(Point::new(60.0, 0.0)) < 1e-6, "{e:?}"); } + /// The polylines of `bp` flattened to 0.01 pt. + fn flattened(bp: &BezPath) -> Vec> { + let mut out: Vec> = vec![]; + vectorcraft_geom::kurbo::flatten(bp.iter(), 0.01, |el| match el { + vectorcraft_geom::PathEl::MoveTo(p) => out.push(vec![p]), + vectorcraft_geom::PathEl::LineTo(p) => out.last_mut().into_iter().for_each(|v| v.push(p)), + vectorcraft_geom::PathEl::ClosePath => out.last_mut().into_iter().for_each(|v| v.push(v[0])), + _ => {} + }); + out + } + + /// The distance from `p` to the nearest of `lines`. + fn off_lines(lines: &[Vec], p: Point) -> f64 { + lines + .iter() + .flat_map(|v| v.windows(2)) + .map(|w| { + let d = w[1] - w[0]; + let t = if d.hypot2() > 0.0 { ((p - w[0]).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 }; + p.distance(w[0] + d * t) + }) + .fold(f64::INFINITY, f64::min) + } + + /// How far apart the border of `m` and the outline of `path` are, in points: the larger of the + /// farthest a point of either lies from the other. + fn mesh_border_off_path(m: &GradientMesh, path: &PathData) -> f64 { + let (border, outline) = (flattened(&m.outline().to_bezpath()), flattened(&path.to_bezpath())); + let one = border.iter().flatten().map(|p| off_lines(&outline, *p)).fold(0.0, f64::max); + let other = outline.iter().flatten().map(|p| off_lines(&border, *p)).fold(0.0, f64::max); + one.max(other) + } + + /// #2752: a gradient mesh keeps the exact outline of the path it is made from, sharp corners + /// included, whether made by Create Gradient Mesh (1×1 and 4×4) or by a Mesh tool click at a + /// point inside. Before, the border of each mesh was one cubic per edge between four corners + /// near the bounding box's: up to 49 pt off a five-point star, 54 pt off a notched rectangle. + #[test] + fn a_mesh_keeps_the_outline_of_every_shape() { + const OFF: f64 = 0.1; + let poly = |pts: &[(f64, f64)]| PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), true)); + let curves = |start: (f64, f64), cubics: &[[(f64, f64); 3]]| { + let mut bp = BezPath::new(); + bp.move_to(start); + for [a, b, c] in cubics { + bp.curve_to(*a, *b, *c); + } + bp.close_path(); + PathData::from_bezpath(&bp) + }; + let box_ = Rect::new(100.0, 100.0, 500.0, 400.0); + let heart = curves( + (300.0, 400.0), + &[ + [(200.0, 320.0), (100.0, 250.0), (100.0, 170.0)], + [(100.0, 100.0), (180.0, 70.0), (230.0, 90.0)], + [(270.0, 105.0), (290.0, 130.0), (300.0, 150.0)], + [(310.0, 130.0), (330.0, 105.0), (370.0, 90.0)], + [(420.0, 70.0), (500.0, 100.0), (500.0, 170.0)], + [(500.0, 250.0), (400.0, 320.0), (300.0, 400.0)], + ], + ); + let teardrop = curves( + (300.0, 100.0), + &[ + [(350.0, 200.0), (420.0, 250.0), (420.0, 320.0)], + [(420.0, 386.0), (366.0, 440.0), (300.0, 440.0)], + [(234.0, 440.0), (180.0, 386.0), (180.0, 320.0)], + [(180.0, 250.0), (250.0, 200.0), (300.0, 100.0)], + ], + ); + let shapes: [(&str, PathData, Point); 14] = [ + ("rectangle", shapes::rectangle(box_), Point::new(260.0, 230.0)), + ("rotated rectangle", shapes::rectangle(box_).transformed(Affine::rotate_about(0.5, box_.center())), Point::new(280.0, 240.0)), + ("triangle", poly(&[(300.0, 100.0), (500.0, 400.0), (100.0, 400.0)]), Point::new(300.0, 320.0)), + ("five-point star", shapes::star(Point::new(300.0, 300.0), 200.0, 80.0, 5, 0.0), Point::new(300.0, 300.0)), + ("twelve-point star", shapes::star(Point::new(300.0, 300.0), 200.0, 140.0, 12, 0.0), Point::new(300.0, 300.0)), + ( + "L-shape", + poly(&[(100.0, 100.0), (200.0, 100.0), (200.0, 300.0), (400.0, 300.0), (400.0, 400.0), (100.0, 400.0)]), + Point::new(150.0, 350.0), + ), + ("rounded rectangle", shapes::rounded_rectangle(box_, 40.0), Point::new(260.0, 230.0)), + ("heart", heart, Point::new(300.0, 250.0)), + ("teardrop", teardrop, Point::new(300.0, 330.0)), + ("ellipse", shapes::ellipse(box_), Point::new(200.0, 330.0)), + ("thin rectangle", shapes::rectangle(Rect::new(100.0, 100.0, 500.0, 110.0)), Point::new(260.0, 104.0)), + ( + "notched rectangle", + poly(&[(100.0, 100.0), (250.0, 100.0), (300.0, 200.0), (350.0, 100.0), (500.0, 100.0), (500.0, 400.0), (100.0, 400.0)]), + Point::new(260.0, 300.0), + ), + // A notch shorter than the steps along the outline an edge is checked at, and deeper + // than the tolerance. + ( + "rectangle with a tiny notch", + poly(&[(100.0, 100.0), (301.1, 100.0), (301.2, 100.3), (301.3, 100.0), (500.0, 100.0), (500.0, 400.0), (100.0, 400.0)]), + Point::new(260.0, 300.0), + ), + // An outline that crosses itself, whose two lobes' areas cancel. + ("bow tie", poly(&[(100.0, 100.0), (500.0, 400.0), (500.0, 100.0), (100.0, 400.0)]), Point::new(150.0, 250.0)), + ]; + // Every shape and way of making the mesh is checked, and all that stray are named. + let mut strays = vec![]; + for (name, path, click) in shapes { + for (rows, cols) in [(1, 1), (4, 4)] { + let m = GradientMesh::for_path(&path, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let off = mesh_border_off_path(&m, &path); + if off >= OFF { + strays.push(format!("{name}, {rows}×{cols}: border {off:.2} pt off the outline")); + } + } + let mut m = GradientMesh::for_path(&path, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + assert!(m.add_lines_at(click, 0.0).is_some(), "{name}: the click at {click:?} is outside the mesh"); + let off = mesh_border_off_path(&m, &path); + if off >= OFF { + strays.push(format!("{name}, Mesh tool click: border {off:.2} pt off the outline")); + } + } + assert!(strays.is_empty(), "{strays:#?}"); + } + + /// The lines a mesh takes to keep a path's outline are as few as do it: a rectangle's and an + /// ellipse's meshes keep the rows and columns asked for, and a star's 1×1 mesh takes lines + /// through its points, at most one each way per anchor. Paths without an outline to follow + /// still give a mesh (an open path closes straight; a line there and back maps onto its box), + /// and a point that isn't finite gives none. + #[test] + fn a_mesh_takes_lines_only_where_the_outline_needs_them() { + let box_ = Rect::new(100.0, 100.0, 500.0, 400.0); + for path in [shapes::rectangle(box_), shapes::ellipse(box_)] { + for (rows, cols) in [(1, 1), (4, 4), (2, 5)] { + let m = GradientMesh::for_path(&path, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + assert_eq!((m.rows, m.cols), (rows, cols)); + } + } + let star = shapes::star(Point::new(300.0, 300.0), 200.0, 80.0, 5, 0.0); + let m = GradientMesh::for_path(&star, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + assert!(m.rows > 1 && m.cols > 1 && m.rows <= 10 && m.cols <= 10 && m.is_valid(), "{}×{}", m.rows, m.cols); + // Every anchor of the star is a point of the mesh. + for a in &star.subpaths[0].anchors { + assert!(m.points.iter().any(|q| q.p.distance(a.p) < 1e-6), "{:?} is not a mesh point", a.p); + } + // An open path closes with a straight segment. + let open = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], false)); + let m = GradientMesh::for_path(&open, 2, 2, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let closed = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], true)); + assert!(mesh_border_off_path(&m, &closed) < 0.1); + // A line there and back. + let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 50.0)], true)); + let m = GradientMesh::for_path(&line, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + assert!(m.is_valid() && m.points.iter().all(|q| q.p.is_finite())); + let mut nan = shapes::rectangle(box_); + nan.subpaths[0].anchors[1].p.x = f64::NAN; + assert!(GradientMesh::for_path(&nan, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).is_none()); + // A path of many anchors stays within the line limit and keeps its outline. + let many = shapes::star(Point::new(300.0, 300.0), 200.0, 190.0, 400, 0.0); + let m = GradientMesh::for_path(&many, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + assert!(m.is_valid() && m.rows as usize <= mesh::MAX_BORDER_LINES && m.cols as usize <= mesh::MAX_BORDER_LINES, "{}×{}", m.rows, m.cols); + } + #[test] fn mesh_insert_and_remove_lines() { let mut m = diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index 3fdddd6807..8f9b197048 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -236,6 +236,7 @@ impl TypeInks { text.xf = Affine::new([a, b, c, d, 0.0, 0.0]); text.cached_bounds = None; text.cached_baselines.clear(); + text.cached_ink = None; let content = content_hash(&text).map(|hash| (hash, by_node.1, inputs)); match content.and_then(|key| self.content.get(&key)) { Some(ink) => { diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index ca08a3a2a2..c59374dee9 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -470,6 +470,384 @@ fn fit_edge(side: &[Point], span: (f64, f64), ends: (Point, Point)) -> Option<(V fit } +/// The cubic from `p0` to `p3` leaving `p0` along `d0` and reaching `p3` against `d1` (unit +/// vectors; `d1` points from `p3` back into the curve) that comes closest (least squares) to the +/// points `qs`, which lie along the way in order; `None` when no such cubic has handles of positive +/// length. Each point is matched to the curve's nearest point, refined over a few rounds, as in +/// [`fit_edge`]. +fn fit_tangents(qs: &[Point], (p0, d0): (Point, Vec2), (p3, d1): (Point, Vec2)) -> Option { + const ROUNDS: usize = 6; + let n = qs.len() + 1; + let mut ts: Vec = (1..n).map(|i| i as f64 / n as f64).collect(); + let mut fit = None; + for _ in 0..ROUNDS { + let (mut c11, mut c12, mut c22, mut x1, mut x2) = (0.0, 0.0, 0.0, 0.0, 0.0); + for (q, &t) in qs.iter().zip(&ts) { + let s = 1.0 - t; + let (b0, b1, b2, b3) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t); + let (a1, a2) = (d0 * b1, d1 * b2); + let r = q.to_vec2() - (b0 + b1) * p0.to_vec2() - (b2 + b3) * p3.to_vec2(); + c11 += a1.dot(a1); + c12 += a1.dot(a2); + c22 += a2.dot(a2); + x1 += r.dot(a1); + x2 += r.dot(a2); + } + let det = c11 * c22 - c12 * c12; + if det.abs() < 1e-12 { + break; + } + let (l1, l2) = ((c22 * x1 - c12 * x2) / det, (c11 * x2 - c12 * x1) / det); + if !(l1.is_finite() && l2.is_finite() && l1 > 0.0 && l2 > 0.0) { + break; + } + let c = CubicBez::new(p0, p0 + d0 * l1, p3 + d1 * l2, p3); + fit = Some(c); + let (a, b, k) = (c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2); + for (q, t) in qs.iter().zip(ts.iter_mut()) { + let s = 1.0 - *t; + let v = 3.0 * (s * s * a + 2.0 * s * *t * b + *t * *t * k); + let acc = 6.0 * (s * (b - a) + *t * (k - b)); + let e = c.eval(*t) - *q; + let den = v.hypot2() + e.dot(acc); + if den.abs() > 1e-12 { + *t = (*t - e.dot(v) / den).clamp(0.0, 1.0); + } + } + } + fit +} + +/// How far (in points) a border edge of a mesh made from a path may stray from the path's outline +/// before the mesh takes a line through an anchor of the outline there; a thousandth of the outline's +/// size when that is less. +const BORDER_TOLERANCE: f64 = 0.1; + +/// The most lines each way a mesh made from a path takes to keep its border on the outline +/// ([`BORDER_TOLERANCE`]); past that, each border edge keeps its closest fit. +pub(super) const MAX_BORDER_LINES: usize = 256; + +/// The most rounds of new lines a mesh made from a path takes to keep its border on the outline. +const MAX_BORDER_ROUNDS: usize = 64; + +/// An anchor whose directions in and out differ by more than this (radians) is a corner: a border +/// edge that can't follow the outline takes a mesh line through its sharpest corner first. +const SHARP_TURN: f64 = 0.01; + +/// Steps of each segment's parameter at which [`Outline`] measures the segment's length. +const LENGTH_STEPS: usize = 32; + +/// Points of the outline each border edge of a mesh made from a path is fitted to +/// ([`Outline::fit`]). +const FIT_POINTS: usize = 32; + +/// Points of the outline, and of the fitted edge, at which [`Outline::fit`] measures how far the +/// two stray from each other. +const CHECK_POINTS: usize = 128; + +/// The outline a gradient mesh is made from: the largest subpath of a path, running clockwise on +/// screen, an open one closed by a straight segment, without segments of no length. A place on it +/// is a length from its first anchor, measured along a polyline through even steps of each +/// segment's parameter; the same length always gives the same point. +struct Outline { + segs: Vec, + /// Where each segment starts, and the whole length last. + starts: Vec, + /// For each segment, the length from its start at each of [`LENGTH_STEPS`] + 1 even steps of + /// its parameter. + table: Vec<[f64; LENGTH_STEPS + 1]>, + /// Lengths closer than this are the same place. + eps: f64, +} + +/// One side of the patch a mesh made from a path spans: the stretch of the outline from `start`, +/// `len` long, run backwards when `reversed` (the bottom and left sides run against the outline). +#[derive(Clone, Copy)] +struct Side { + start: f64, + len: f64, + reversed: bool, +} + +impl Side { + /// The place on the outline at `f` (0 to 1) along the side. + fn at(&self, f: f64) -> f64 { + self.start + if self.reversed { (1.0 - f) * self.len } else { f * self.len } + } +} + +/// The direction a cubic leaves its start in (`false`) or reaches its end in (`true`), from the +/// first handle or point that is not at the end; zero when all its points are together. +fn cubic_tangent(c: &CubicBez, end: bool) -> Vec2 { + let near = 1e-12 * (c.p0.to_vec2().hypot() + c.p3.to_vec2().hypot() + 1.0); + let options = if end { [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0] } else { [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0] }; + options.into_iter().find(|v| v.hypot() > near).unwrap_or(Vec2::ZERO) +} + +impl Outline { + /// The outline of `path`; `None` when it has no subpath of two anchors or more, a point that + /// isn't finite, or all its points on one line (a line there and back). + fn new(path: &PathData) -> Option { + let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?; + if !sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) { + return None; + } + let mut sp = sp.clone(); + if sp.signed_area() < 0.0 { + sp.reverse(); + } + // A straight segment's parameter runs evenly along it. + let line = |a: Point, b: Point| CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b); + let mut segs: Vec = + (0..sp.segment_count()).map(|i| if sp.segment_is_line(i) { line(sp.segment(i).p0, sp.segment(i).p3) } else { sp.segment(i) }).collect(); + if !sp.closed + && let (Some(a), Some(b)) = (sp.anchors.last(), sp.anchors.first()) + { + segs.push(line(a.p, b.p)); + } + segs.retain(|c| [c.p1, c.p2, c.p3].iter().any(|p| p.distance(c.p0) > 1e-9)); + if segs.len() < 2 { + return None; + } + let mut starts = Vec::with_capacity(segs.len() + 1); + let mut table = Vec::with_capacity(segs.len()); + let mut total = 0.0; + for c in &segs { + let mut lens = [0.0; LENGTH_STEPS + 1]; + let mut prev = c.p0; + for (k, len) in lens.iter_mut().enumerate().skip(1) { + let p = c.eval(k as f64 / LENGTH_STEPS as f64); + *len = prev.distance(p); + prev = p; + } + for k in 1..=LENGTH_STEPS { + lens[k] += lens[k - 1]; + } + starts.push(total); + total += lens[LENGTH_STEPS]; + table.push(lens); + } + starts.push(total); + if !(total.is_finite() && total > 0.0) { + return None; + } + // An outline whose points all lie on one line encloses nothing; one that crosses itself + // (a bow tie) may have areas that cancel, and is still followed. + let pts: Vec = segs.iter().flat_map(|c| [c.p0, c.p1, c.p2, c.p3]).collect(); + let first = pts.first().copied()?; + let far = pts.iter().copied().max_by(|a, b| a.distance_squared(first).total_cmp(&b.distance_squared(first)))?; + let dir = far - first; + let width = pts.iter().map(|p| ((*p - first).cross(dir) / dir.hypot()).abs()).fold(0.0, f64::max); + if !(dir.hypot() > 0.0 && width > 1e-9 * total) { + return None; + } + Some(Self { segs, starts, table, eps: total * 1e-9 }) + } + + fn total(&self) -> f64 { + self.starts.last().copied().unwrap_or_default() + } + + /// The bounding box of the outline. + fn bounds(&self) -> Option { + self.segs.iter().map(|c| c.bounding_box()).reduce(|a, b| a.union(b)) + } + + /// The parameter of segment `i` `local` along it (clamped to the segment). + fn seg_t(&self, i: usize, local: f64) -> f64 { + let Some(lens) = self.table.get(i) else { return 0.0 }; + let k = lens.partition_point(|x| *x <= local).clamp(1, LENGTH_STEPS) - 1; + let (l0, l1) = (lens[k], lens[k + 1]); + let f = if l1 > l0 { ((local - l0) / (l1 - l0)).clamp(0.0, 1.0) } else { 0.0 }; + (k as f64 + f) / LENGTH_STEPS as f64 + } + + /// The segment and its parameter at place `s` (wrapping around); a place at the very end of a + /// segment is the start of the next. + fn locate(&self, s: f64) -> (usize, f64) { + let n = self.segs.len(); + let s = s.rem_euclid(self.total()); + let mut i = self.starts.partition_point(|x| *x <= s).clamp(1, n) - 1; + if self.starts.get(i + 1).is_some_and(|end| end - s <= self.eps) { + i = (i + 1) % n; + return (i, 0.0); + } + (i, self.seg_t(i, s - self.starts[i])) + } + + fn point(&self, s: f64) -> Point { + let (i, t) = self.locate(s); + self.segs.get(i).map_or(Point::ZERO, |c| c.eval(t)) + } + + /// The anchors strictly inside the stretch from `a`, `len` long: each one's distance from `a` + /// and the segment it starts. + fn anchors_in(&self, a: f64, len: f64) -> Vec<(f64, usize)> { + let (total, n) = (self.total(), self.segs.len()); + let a = a.rem_euclid(total); + let (lo, hi) = (a + self.eps, a + len - self.eps); + let mut out = vec![]; + for lap in [0.0, total] { + let from = self.starts[..n].partition_point(|x| x + lap <= lo); + for (i, start) in self.starts[..n].iter().enumerate().skip(from) { + let p = start + lap; + if p >= hi { + break; + } + out.push((p - a, i)); + } + } + out + } + + /// The piece of the outline from `a`, `len` long, which no anchor lies inside. + fn piece(&self, a: f64, len: f64) -> CubicBez { + let (i, t0) = self.locate(a); + let Some(c) = self.segs.get(i) else { return CubicBez::new(Point::ZERO, Point::ZERO, Point::ZERO, Point::ZERO) }; + // At a segment's start (a place at the end of the one before counts as that), none of it is behind. + let behind = if t0 == 0.0 { 0.0 } else { a.rem_euclid(self.total()) - self.starts[i] }; + let t1 = self.seg_t(i, behind + len); + c.subsegment(t0..t1.max(t0)) + } + + /// The direction the outline leaves place `s` in (`into` false) or reaches it in (`into` true). + fn tangent(&self, s: f64, into: bool) -> Vec2 { + let n = self.segs.len(); + let (i, t) = self.locate(s); + let c = match (into, t <= 0.0) { + (true, true) => self.segs[(i + n - 1) % n], + (true, false) => self.segs[i].subsegment(0.0..t), + (false, _) => self.segs[i].subsegment(t..1.0), + }; + cubic_tangent(&c, into) + } + + /// How sharply the outline turns at the anchor starting segment `i` (radians, 0 to π). + fn turn(&self, i: usize) -> f64 { + let s = self.starts[i]; + let (din, dout) = (self.tangent(s, true), self.tangent(s, false)); + din.cross(dout).atan2(din.dot(dout)).abs() + } + + /// The place on the outline nearest `q`. + fn nearest(&self, q: Point) -> f64 { + use vectorcraft_geom::kurbo::ParamCurveNearest; + let mut best = (f64::INFINITY, 0.0); + for (i, c) in self.segs.iter().enumerate() { + let near = c.nearest(q, 1e-9); + if near.distance_sq < best.0 { + // The length at that parameter, from the table. + let lens = &self.table[i]; + let x = near.t * LENGTH_STEPS as f64; + let k = (x.floor() as usize).min(LENGTH_STEPS - 1); + let local = lens[k] + (lens[k + 1] - lens[k]) * (x - k as f64); + best = (near.distance_sq, self.starts[i] + local); + } + } + best.1 + } + + /// The cubic standing for the stretch from `a`, `len` long, and how far it strays from it: the + /// piece of the segment when no anchor lies inside, otherwise a cubic fitted to the outline with + /// its ends along the outline's own directions there. + fn fit(&self, a: f64, len: f64) -> (CubicBez, f64) { + let (p0, p3) = (self.point(a), self.point(a + len)); + if len <= self.eps { + return (CubicBez::new(p0, p0, p0, p0), 0.0); + } + let anchors = self.anchors_in(a, len); + if anchors.is_empty() { + return (self.piece(a, len), 0.0); + } + let qs: Vec = (1..FIT_POINTS).map(|i| self.point(a + len * i as f64 / FIT_POINTS as f64)).collect(); + let (d0, d1) = (self.tangent(a, false), -self.tangent(a + len, true)); + let unit = |v: Vec2| if v.hypot() > 0.0 { Some(v / v.hypot()) } else { None }; + let straight = CubicBez::new(p0, p0.lerp(p3, 1.0 / 3.0), p0.lerp(p3, 2.0 / 3.0), p3); + let c = match (unit(d0), unit(d1)) { + (Some(d0), Some(d1)) => fit_tangents(&qs, (p0, d0), (p3, d1)), + _ => None, + } + .unwrap_or(straight); + // Both ways: the outline's points from the cubic, and the cubic's points from the outline. + // The outline is checked at even steps and at every anchor inside, so a spike or a notch + // narrower than a step is not missed. + use vectorcraft_geom::kurbo::ParamCurveNearest; + let mut at: Vec = (0..=CHECK_POINTS).map(|i| len * i as f64 / CHECK_POINTS as f64).chain(anchors.iter().map(|(o, _)| *o)).collect(); + at.sort_by(f64::total_cmp); + let line: Vec = at.iter().map(|o| self.point(a + o)).collect(); + let off_outline = line.iter().map(|q| c.nearest(*q, 1e-9).distance_sq.sqrt()).fold(0.0, f64::max); + let off_cubic = (0..=CHECK_POINTS) + .map(|i| { + let p = c.eval(i as f64 / CHECK_POINTS as f64); + line.windows(2) + .map(|w| { + let (u, v) = (w[0], w[1]); + let d = v - u; + let t = if d.hypot2() > 0.0 { ((p - u).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 }; + p.distance(u + d * t) + }) + .fold(f64::INFINITY, f64::min) + }) + .fold(0.0, f64::max); + (c, off_outline.max(off_cubic)) + } + + /// The border edge of `side` from `f0` to `f1` (0 to 1 along it, rising), run the way the side + /// runs, and when it strays from the outline by more than `tol`, where along the side (0 to 1) + /// a mesh line through an anchor would help: the sharpest corner inside it, or the anchor + /// nearest its middle when none is sharp. + fn edge(&self, side: &Side, f0: f64, f1: f64, tol: f64) -> (CubicBez, Option) { + let len = (f1 - f0) * side.len; + let a = side.at(if side.reversed { f1 } else { f0 }); + let (c, off) = self.fit(a, len); + let c = if side.reversed { CubicBez::new(c.p3, c.p2, c.p1, c.p0) } else { c }; + if off <= tol || side.len <= 0.0 { + return (c, None); + } + let anchors = self.anchors_in(a, len); + let sharpest = anchors.iter().map(|&(o, i)| (self.turn(i), o)).max_by(|x, y| x.0.total_cmp(&y.0)); + let at = match sharpest { + Some((turn, o)) if turn > SHARP_TURN => Some(o), + _ => anchors.iter().map(|&(o, _)| o).min_by(|x, y| (x - len / 2.0).abs().total_cmp(&(y - len / 2.0).abs())), + }; + let split = at.map(|o| if side.reversed { f1 - o / side.len } else { f0 + o / side.len }); + (c, split.filter(|f| *f > f0 && *f < f1)) + } + + /// The cuts (0 to 1) of the lines across sides `one` and `other`: `even`, and as many more as + /// keep every border edge along them within `tol` of the outline (see [`Self::edge`]), at most + /// [`MAX_BORDER_LINES`] in all. + fn cuts(&self, one: &Side, other: &Side, even: Vec, tol: f64) -> Vec { + let mut cuts = even; + for _ in 0..MAX_BORDER_ROUNDS { + let mut add: Vec = + [one, other].iter().flat_map(|s| cuts.windows(2).filter_map(|w| self.edge(s, w[0], w[1], tol).1).collect::>()).collect(); + add.retain(|f| cuts.iter().all(|c| (c - f).abs() > 1e-9)); + add.truncate((MAX_BORDER_LINES + 1).saturating_sub(cuts.len())); + if add.is_empty() { + break; + } + cuts.extend(add); + cuts.sort_by(f64::total_cmp); + cuts.dedup_by(|x, y| (*x - *y).abs() <= 1e-9); + } + cuts + } + + /// The points along `side` at `knots` (rising, 0 to 1). + fn side_points(&self, side: &Side, knots: &[f64]) -> Vec { + knots.iter().map(|f| self.point(side.at(*f))).collect() + } +} + +/// The sorted union of `cuts` and `SIDE` even steps. +fn side_knots(cuts: &[f64]) -> Vec { + let mut k: Vec = (0..SIDE).map(|i| i as f64 / (SIDE - 1) as f64).chain(cuts.iter().copied()).collect(); + k.sort_by(f64::total_cmp); + k.dedup_by(|x, y| (*x - *y).abs() <= 1e-9); + k +} + /// The handles of one cubic standing for two edges that meet at point `mid.0`, whose handles /// towards them are `mid.1` (towards `a`) and `mid.2` (towards `b`), as offsets from their outer /// ends: each outer handle grown back by the share of the curve its edge had, which undoes the @@ -599,19 +977,104 @@ impl GradientMesh { /// Create Gradient Mesh for a path: the outline split at its corners, coloured per `appearance`. pub fn for_path(path: &PathData, rows: u32, cols: u32, base: Color, appearance: MeshAppearance, highlight: f64) -> Option { - let mut m = Self::for_path_with(path, rows, cols, &|_| (base, 1.0))?; - m.highlight(appearance, highlight); + Self::for_path_shaded(path, rows, cols, &|_| (base, 1.0), appearance, highlight) + } + + /// As [`Self::for_path_with`], then lightened per `appearance` ([`Self::highlight`]), measured + /// by where each line crosses the patch. + pub fn for_path_shaded( + path: &PathData, + rows: u32, + cols: u32, + color_at: &dyn Fn(Point) -> (Color, f32), + appearance: MeshAppearance, + highlight: f64, + ) -> Option { + let (mut m, us, vs) = Self::build_for_path(path, rows, cols, color_at)?; + m.highlight_at(appearance, highlight, &us, &vs); Some(m) } /// Create Gradient Mesh for a path: the outline split at its corners, each point taking the /// colour and opacity `color_at` gives at its position (a gradient fill's, say). pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option { - let coons = Coons::from_path(path)?; + Self::build_for_path(path, rows, cols, color_at).map(|(m, ..)| m) + } + + /// The mesh of [`Self::for_path_with`] and where its column and row lines cross the patch (0 + /// to 1). Its border lies on the outline of the path's largest subpath (#2752): the patch's + /// corners are the outline's places nearest the corners of its bounding box (when those don't + /// come in order round the outline, the top left one and the places a quarter, a half and three + /// quarters of the way round from it), its points on the + /// border sit on the outline, and each border edge is the piece of the outline between its + /// points, a single cubic. Where the outline bends through an anchor between two of the `rows` + /// × `cols` lines and no single cubic follows it within [`BORDER_TOLERANCE`], the mesh takes a + /// line through that anchor (its sharpest corner first), as many as that needs up to + /// [`MAX_BORDER_LINES`] each way. `None` when the path has no outline or a point that isn't + /// finite; an outline whose points all lie on one line gives the mesh of its bounding box. + fn build_for_path(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<(Self, Vec, Vec)> { + if !path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) { + return None; + } let (us, vs) = (even_steps(cols), even_steps(rows)); + let Some((o, sides)) = Outline::new(path).and_then(|o| { + let r = o.bounds()?; + let [tl, mut tr, mut br, mut bl] = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| o.nearest(Point::new(x, y))); + let span = |a: f64, b: f64| (b - a).rem_euclid(o.total()); + // Corners met out of order around the outline would make sides that overlap: the + // other three then go a quarter of the way round from the top left each. + let around = span(tl, tr) + span(tr, br) + span(br, bl) + span(bl, tl); + if (around - o.total()).abs() > 1e-6 * o.total() { + let quarter = o.total() / 4.0; + (tr, br, bl) = (tl + quarter, tl + 2.0 * quarter, tl + 3.0 * quarter); + } + let sides = [ + Side { start: tl, len: span(tl, tr), reversed: false }, + Side { start: tr, len: span(tr, br), reversed: false }, + Side { start: br, len: span(br, bl), reversed: true }, + Side { start: bl, len: span(bl, tl), reversed: true }, + ]; + Some((o, sides)) + }) else { + // No outline to follow: the patch of the flattened outline (its bounding box when it + // encloses nothing), with each border edge fitted. + let coons = Coons::from_path(path)?; + let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p)); + m.fit_border(&coons, &us, &vs); + return Some((m, us, vs)); + }; + let [top, right, bottom, left] = sides; + let size = o.bounds().map_or(0.0, |r| r.width() + r.height()); + let tol = BORDER_TOLERANCE.min(size * 1e-3).max(o.eps); + let us = o.cuts(&top, &bottom, us, tol); + let vs = o.cuts(&left, &right, vs, tol); + let (ku, kv) = (side_knots(&us), side_knots(&vs)); + let coons = Coons { + top: o.side_points(&top, &ku), + right: o.side_points(&right, &kv), + bottom: o.side_points(&bottom, &ku), + left: o.side_points(&left, &kv), + knots: Some(Box::new([ku.clone(), kv.clone(), ku, kv])), + }; let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p)); - m.fit_border(&coons, &us, &vs); - Some(m) + let (rows, cols) = (m.rows as usize, m.cols as usize); + let edges = [(0, &top), (rows, &bottom)] + .map(|(r, side)| (r, side, true)) + .into_iter() + .chain([(0, &left), (cols, &right)].map(|(c, side)| (c, side, false))); + for (line, side, along_u) in edges { + let steps = if along_u { &us } else { &vs }; + for (k, w) in steps.windows(2).enumerate() { + let (a, b, out, back) = + if along_u { (m.idx(line, k), m.idx(line, k + 1), H_RIGHT, H_LEFT) } else { (m.idx(k, line), m.idx(k + 1, line), H_DOWN, H_UP) }; + let (c, _) = o.edge(side, w[0], w[1], tol); + m.points[a].p = c.p0; + m.points[b].p = c.p3; + m.points[a].handles[out] = c.p1 - c.p0; + m.points[b].handles[back] = c.p2 - c.p3; + } + } + Some((m, us, vs)) } /// Give each edge on the mesh's border the handles that make it follow the outline it stands @@ -657,11 +1120,21 @@ impl GradientMesh { /// the edges, by at most `highlight` %. Each point lightens towards white in its own colour /// model (paper white, no ink, for CMYK), so a CMYK or grey mesh keeps its inks (#3232). pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) { + let even = |n: u32| (0..=n).map(|i| f64::from(i) / f64::from(n)).collect::>(); + let (us, vs) = (even(self.cols), even(self.rows)); + self.highlight_at(appearance, highlight, &us, &vs); + } + + /// As [`Self::highlight`], with the column lines at `us` and the row lines at `vs` (0 to 1 + /// across the patch); a mesh whose lines don't match them is left as it is. + fn highlight_at(&mut self, appearance: MeshAppearance, highlight: f64, us: &[f64], vs: &[f64]) { let h = (highlight / 100.0).clamp(0.0, 1.0) as f32; let (rows, cols) = (self.rows as usize, self.cols as usize); - for r in 0..=rows { - for c in 0..=cols { - let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64); + if !self.is_valid() || us.len() != cols + 1 || vs.len() != rows + 1 { + return; + } + for (r, &v) in vs.iter().enumerate() { + for (c, &u) in us.iter().enumerate() { let d = ((u - 0.5).abs().max((v - 0.5).abs()) * 2.0) as f32; // 0 centre … 1 edge let w = match appearance { MeshAppearance::Flat => 0.0, diff --git a/crates/doc/src/pixels.rs b/crates/doc/src/pixels.rs index 2264e66ce0..30d8a7a63b 100644 --- a/crates/doc/src/pixels.rs +++ b/crates/doc/src/pixels.rs @@ -60,6 +60,38 @@ impl ImageBlob { img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; Some(Self::png(png)) } + + /// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and + /// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct + /// color. `None` when the image can't be decoded, or when its file stores grayscale already + /// and no visible pixel changed. + pub fn map_gray(&self, mut f: impl FnMut([u8; 3]) -> u8) -> Option { + let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?; + let (width, height) = img.dimensions(); + let mut memo: HashMap<[u8; 3], u8> = HashMap::new(); + let mut changed = self.gray_source().is_none(); + let mut opaque = true; + let mut gray_alpha = Vec::with_capacity(img.len() / 2); + for px in img.pixels() { + let rgb = [px.0[0], px.0[1], px.0[2]]; + let level = *memo.entry(rgb).or_insert_with(|| f(rgb)); + changed |= px.0[3] > 0 && [level; 3] != rgb; + opaque &= px.0[3] == 255; + gray_alpha.extend_from_slice(&[level, px.0[3]]); + } + if !changed { + return None; + } + let mut png = Vec::new(); + let mut out = Cursor::new(&mut png); + if opaque { + let levels = gray_alpha.iter().step_by(2).copied().collect(); + image::GrayImage::from_raw(width, height, levels)?.write_to(&mut out, image::ImageFormat::Png).ok()?; + } else { + image::GrayAlphaImage::from_raw(width, height, gray_alpha)?.write_to(&mut out, image::ImageFormat::Png).ok()?; + } + Some(Self::png(png)) + } } /// How a grayscale image's file stores its pixels ([`ImageBlob::gray_source`]). diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index 0c4ef497f3..f6b9a4d013 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -1,13 +1,12 @@ //! Where a path's strokes paint, from the path's geometry without building their outlines: the //! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes -//! up to the miter limit, projecting caps and arrowheads. +//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points. use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit}; use vectorcraft_geom::hit::fill_contains; -use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest}; +use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest}; use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2}; -use crate::appearance::HEAD_REACH; use crate::{Appearance, ArrowAlign, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile}; /// Arc-length accuracy for placing a point along a profile (document points). @@ -101,6 +100,82 @@ fn profile_at(profile: &WidthProfile, segs: &[PathSeg], closed: bool, i: usize, w } +/// Does the curvature of `seg` stay below one over `side` all along it? A curve's first derivative +/// is a mix of its three control differences, and its second a mix of their two differences, which +/// bound the curvature from above. Then the edges of a stroke reaching `side` from it do not fold +/// back, and those edges reach farthest at the ends of `seg` or where its tangent is square to an +/// axis. +fn gentle(seg: &PathSeg, side: f64) -> bool { + let c = seg.to_cubic(); + let d = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2].map(|v| v * 3.0); + let along = unit(d[0] + d[1] + d[2]); + let slowest = d.iter().map(|v| v.dot(along)).fold(f64::INFINITY, f64::min); + let bend = 2.0 * (d[1] - d[0]).hypot().max((d[2] - d[1]).hypot()); + slowest > 0.0 && side * bend < slowest * slowest +} + +/// The box a stroke reaching `side` from `seg` paints across it, from the directions its tangent +/// can take: the tangent is a mix of the nonzero control differences, so when their directions all +/// lie within a quarter turn of the directions' sum, every point across the stroke is in `seg`'s +/// box moved `side` along a normal of one of those directions. `None` when they do not. A handle on +/// its end point adds no direction, so a straight curve with one measures as a line. +fn turning_box(seg: &PathSeg, side: f64) -> Option { + let c = seg.to_cubic(); + let d = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2]; + let moving = || d.iter().map(|v| (*v, v.hypot())).filter(|(_, h)| *h > 0.0).map(|(v, h)| v / h); + let along = unit(moving().fold(Vec2::ZERO, |s, v| s + v)); + if moving().any(|v| v.dot(along) <= 0.0) { + return None; + } + let angle = |v: &Vec2| along.cross(*v).atan2(along.dot(*v)); + let lo = moving().min_by(|a, b| angle(a).total_cmp(&angle(b)))?; + let hi = moving().max_by(|a, b| angle(a).total_cmp(&angle(b)))?; + let n = |t: Vec2| (Vec2::new(t.y, -t.x) * side).to_point(); + let one_side = round_join_box(Point::ZERO, lo, hi, side).unwrap_or_else(|| Rect::from_points(n(lo), n(hi))); + let reach = one_side.union(Rect::new(-one_side.x1, -one_side.y1, -one_side.x0, -one_side.y0)); + let b = ParamCurveExtrema::bounding_box(seg); + Some(Rect::new(b.x0 + reach.x0, b.y0 + reach.y0, b.x1 + reach.x1, b.y1 + reach.y1)) +} + +/// The box a stroke reaching `side` from `seg` paints when it stops square at both ends of `seg`: +/// the corners at the ends and the points across the stroke where the tangent is square to an axis. +/// A curve that bends tighter than `side` is halved up to `depth` times, and a piece still bending +/// that much is measured by [`turning_box`], or grown by `side` on every side when its tangent +/// turns too far. +fn swept_box(seg: &PathSeg, side: f64, depth: u32) -> Rect { + if !matches!(seg, PathSeg::Line(_)) && !gentle(seg, side) { + if depth == 0 { + return turning_box(seg, side).unwrap_or_else(|| ParamCurveExtrema::bounding_box(seg).inflate(side, side)); + } + return swept_box(&seg.subsegment(0.0..0.5), side, depth - 1).union(swept_box(&seg.subsegment(0.5..1.0), side, depth - 1)); + } + let across = |t: f64| { + let (p, tn) = (seg.eval(t), tangent(seg, t)); + let n = Vec2::new(-tn.y, tn.x) * side; + [p + n, p - n] + }; + let [a, b] = across(0.0); + seg.extrema().into_iter().chain([1.0]).flat_map(across).fold(Rect::from_points(a, b), |r, p| r.union_pt(p)) +} + +/// The box of the arc a round join paints `side` from `at`, where the path turns from tangent +/// `t_in` to `t_out`: the arc runs on the outer side of the turn, and its box comes from its ends +/// and the points on it square to an axis. A joint where the path turns back on itself is given +/// the whole disc's box, and one where it does not turn paints no arc (`None`). +fn round_join_box(at: Point, t_in: Vec2, t_out: Vec2, side: f64) -> Option { + let (t_in, t_out) = (unit(t_in), unit(t_out)); + let turn = t_in.cross(t_out); + if turn.abs() < 1e-12 { + return (t_in.dot(t_out) < 0.0).then(|| Rect::from_center_size(at, (2.0 * side, 2.0 * side))); + } + let s = turn.signum(); + let outer = |t: Vec2| Vec2::new(t.y, -t.x) * s; + let (a, b) = (outer(t_in), outer(t_out)); + let axes = [Vec2::new(1.0, 0.0), Vec2::new(-1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.0, -1.0)]; + let arc = Rect::from_points(at + a * side, at + b * side); + Some(axes.into_iter().filter(|d| a.cross(*d) * s >= 0.0 && d.cross(b) * s >= 0.0).fold(arc, |r, d| r.union_pt(at + d * side))) +} + /// Is `p` inside the convex polygon `pts` (either winding), or within `tol` of it? fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool { let n = pts.len(); @@ -115,39 +190,81 @@ fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool { impl StrokeLayer { /// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads, - /// or an alignment that depends on whether the path is closed? Else it reaches evenly round it. + /// an alignment that depends on whether the path is closed, or butt caps, which stop at the + /// ends of an open path? Else it reaches evenly round it. fn needs_shape(&self) -> bool { self.join == LineJoin::Miter - || self.cap == LineCap::Square + || self.cap != LineCap::Round || self.start_arrow.is_some() || self.end_arrow.is_some() || self.align != StrokeAlign::Center } - /// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown - /// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of + /// The box this stroke paints along `segs`, the segments with length of an open subpath, when + /// its caps are butt caps: each segment's [`swept_box`] and, with round joins, the arc each + /// joint between segments paints ([`round_join_box`]), a shallow one included. + /// `None` when `segs` is empty. Butt dashes stop inside the same box. The heads and miter tips + /// are measured apart. A segment in the middle is measured only when its own box grown by + /// `side`, which holds everything it paints, is not inside the box so far. + fn butt_body(&self, segs: &[PathSeg], side: f64) -> Option { + let (first, last) = (segs.first()?, segs.last()?); + let ends = swept_box(first, side, 3).union(swept_box(last, side, 3)); + let body = segs.iter().skip(1).take(segs.len().saturating_sub(2)).fold(ends, |b, s| { + if b.contains_rect(ParamCurveExtrema::bounding_box(s).inflate(side, side)) { b } else { b.union(swept_box(s, side, 3)) } + }); + if self.join != LineJoin::Round { + return Some(body); + } + Some(joints(segs, false).fold(body, |b, (at, t_in, t_out)| round_join_box(at, t_in, t_out, side).map_or(b, |j| b.union(j)))) + } + + /// The box this stroke paints along `bp` (geometric bounds `bounds`): an open subpath with butt + /// caps by [`Self::butt_body`], every other subpath by the box of its segments grown by its + /// reach, with `tips` and, when `measure_tips`, the miter spikes the limit keeps, the corners of /// projecting caps and the reach of the arrowheads round their end points. - pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect { + fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option, measure_tips: bool) -> Rect { let els = bp.elements(); - let mut out = bounds; + let subs = subpaths(bp); + let mut out = tips.map_or(bounds, |t| bounds.union(t)); let mut side_max: f64 = 0.0; + // Every subpath reaches evenly unless one is open and butt-capped; only then is each + // subpath's own box needed. + let even_only = self.cap != LineCap::Butt || subs.iter().all(|s| s.1); + let mut even = even_only.then_some(bounds); // Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere. let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed); - for (r, closed) in subpaths(bp) { + for (r, closed) in subs { let side = self.side_reach(closed); - side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side }); + let butt = self.cap == LineCap::Butt && !closed; + if !butt { + side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side }); + } if side <= 0.0 { continue; } + let square = self.cap == LineCap::Square && !closed; + let miters = measure_tips && self.join == LineJoin::Miter; + if !(butt || square || miters || !even_only) { + continue; + } let segs = drawn(&els[r]); - if self.join == LineJoin::Miter { + if miters { for (at, t_in, t_out) in joints(&segs, closed) { if let Some([_, tip, _]) = miter(at, t_in, t_out, side, self.miter_limit) { out = out.union_pt(tip); } } } - if self.cap == LineCap::Square && !closed { + if butt { + if let Some(body) = self.butt_body(&segs, side) { + out = out.union(body); + } + continue; + } + if !even_only { + even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b))); + } + if square { for (at, dir) in ends(&segs).into_iter().flatten() { let n = Vec2::new(-dir.y, dir.x) * side; out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n); @@ -158,7 +275,15 @@ impl StrokeLayer { let r = self.head_reach(end); out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r))); } - out.union(bounds.inflate(side_max, side_max)) + even.map_or(out, |e| out.union(e.inflate(side_max, side_max))) + } + + /// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown + /// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of + /// projecting caps and the reach of the arrowheads round their end points. An open subpath + /// with butt caps does not reach past its ends ([`Self::butt_body`]). + pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect { + self.reach_along(bp, bounds, None, true) } /// The tip of the miter spike this stroke paints where segment `b` follows segment `a` in a @@ -176,30 +301,7 @@ impl StrokeLayer { /// every joint of `bp` ([`Self::miter_tip`]) or `None` when there are none, instead of measured /// along `bp`. It measures the projecting caps and arrowheads as [`Self::bounds_on`] does. pub fn bounds_with_tips(&self, bp: &BezPath, bounds: Rect, tips: Option) -> Rect { - let els = bp.elements(); - let mut out = tips.map_or(bounds, |t| bounds.union(t)); - let mut side_max: f64 = 0.0; - // Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere. - let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed); - for (r, closed) in subpaths(bp) { - let side = self.side_reach(closed); - side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side }); - if side <= 0.0 { - continue; - } - if self.cap == LineCap::Square && !closed { - let segs = drawn(&els[r]); - for (at, dir) in ends(&segs).into_iter().flatten() { - let n = Vec2::new(-dir.y, dir.x) * side; - out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n); - } - } - } - for (at, _, end) in head_ends(self, bp) { - let r = self.head_reach(end); - out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r))); - } - out.union(bounds.inflate(side_max, side_max)) + self.reach_along(bp, bounds, tips, false) } /// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and @@ -283,18 +385,19 @@ impl StrokeLayer { } /// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path - /// leaving along `out`) can paint? Heads are at most about 4.6 weights long and 4 wide. With + /// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and + /// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With /// [`ArrowAlign::Extend`] a head points along `out` with its tip up to its length (or the cap) /// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the /// chord the path bends through under it, so anywhere within its length of the end. fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool { - let hw = self.arrow_weight(end); - let v = p - at; + let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false }; + let (hw, v) = (self.arrow_weight(end), p - at); match self.arrow_align { - ArrowAlign::Tip => v.hypot() <= HEAD_REACH * hw + tol, + ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol, ArrowAlign::Extend => { let along = v.dot(out); - v.cross(out).abs() <= 2.0 * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -HEAD_REACH * hw - tol + v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol } } } @@ -314,7 +417,7 @@ impl Appearance { } /// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape - /// (miter spikes, projecting caps, arrowheads or an alignment) given by `shaped`. + /// (miter spikes, projecting or butt caps, arrowheads or an alignment) given by `shaped`. pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect { self.painted_strokes().fold(bounds, |acc, s| { if !s.needs_shape() { @@ -325,6 +428,30 @@ impl Appearance { }) } + /// Does this appearance have a visible butt-capped stroke? + pub fn has_butt_stroke(&self) -> bool { + self.painted_strokes().any(|s| s.cap == LineCap::Butt) + } + + /// Does a visible butt-capped stroke of this appearance run along an open subpath of `bp` with + /// a segment that starts or ends at a slant, not square to the axes, once placed by `a`? The + /// visual box's margin at the stroke's corners there depends on their direction, which a scale + /// out of proportion changes. + pub fn has_slanted_butt_stroke(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool { + if !self.has_butt_stroke() { + return false; + } + let slanted = |v: Vec2| { + let d = unit(a * v.to_point() - a * Point::ZERO); + (d.x * d.y).abs() > 1e-9 + }; + let els = bp.elements(); + subpaths(bp) + .into_iter() + .filter(|(_, closed)| !closed) + .any(|(r, _)| drawn(&els[r]).iter().any(|s| slanted(tangent(s, 0.0)) || slanted(tangent(s, 1.0)))) + } + /// Does a visible stroke of this appearance along `bp` (filled with `rule`) paint within /// `tol` of `p` ([`StrokeLayer::hits`])? pub fn stroke_hit(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool { @@ -332,6 +459,31 @@ impl Appearance { } } +/// How many symbol instances [`crate::Node::has_slanted_butt_stroke`] looks into for one object +/// before it answers yes without looking further. +pub const SLANT_INSTANCES: usize = 4096; + +impl crate::Node { + /// Does a visible butt-capped stroke of this object, of an object in it or of an object in a + /// symbol instance's art from `symbols`, placed by `a`, run along an open path with a segment + /// at a slant ([`Appearance::has_slanted_butt_stroke`])? Past [`SLANT_INSTANCES`] instances it + /// answers yes. + pub fn has_slanted_butt_stroke(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool { + self.slanted_butt(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES)) + } + + /// [`Self::has_slanted_butt_stroke`] with `left` instances still to look into. + fn slanted_butt(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell) -> bool { + if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind { + let Some(l) = left.get().checked_sub(1) else { return true }; + left.set(l); + return symbols.measure_art(symbol, |art| art.slanted_butt(symbols, a * *xf, left)).unwrap_or(false); + } + (self.appearance.has_butt_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_butt_stroke(&bp, a))) + || self.children().is_some_and(|c| c.iter().any(|c| c.slanted_butt(symbols, a, left))) + } +} + #[cfg(test)] mod tests { use vectorcraft_color::{Color, Paint}; @@ -378,7 +530,7 @@ mod tests { let (small, big) = (at(100.0).bounds_on(&l, b), at(300.0).bounds_on(&l, b)); assert!(big.x1 > small.x1 + 15.0 && big.y1 > small.y1 + 7.0, "{small:?} → {big:?}"); // A 300% head on a 2 pt stroke is 24 pt long and wide: its tip, past the end, is inside. - assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == -1.0, "{big:?}"); + assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == 0.0, "{big:?}"); // The start has no head. assert_eq!(at(300.0).head_reach(false), 0.0); } @@ -405,6 +557,203 @@ mod tests { assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Outside).bounds_on(&sq, b), b.inflate(4.0, 4.0)); } + /// An open path through `points`. + fn polyline(points: &[(f64, f64)]) -> BezPath { + let mut bp = BezPath::new(); + for (i, p) in points.iter().enumerate() { + if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) } + } + bp + } + + #[test] + fn butt_caps_stop_at_the_ends_of_an_open_path() { + let butt = |f: fn(&mut StrokeLayer)| { + stroke(2.0, |s| { + s.cap = LineCap::Butt; + f(s); + }) + }; + // A vertical line reaches sideways only. + let v = polyline(&[(50.0, 10.0), (50.0, 60.0)]); + assert_eq!(butt(|_| {}).bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0)); + // A 3-4-5 diagonal: its corners reach 0.8 pt across x and 0.6 pt across y. + let d = polyline(&[(0.0, 0.0), (30.0, 40.0)]); + let b = butt(|_| {}).bounds_on(&d, d.bounding_box()); + for (got, want) in [(b.x0, -0.8), (b.y0, -0.6), (b.x1, 30.8), (b.y1, 40.6)] { + assert!((got - want).abs() < 1e-9, "{b:?}"); + } + // The dashes of a butt stroke stop inside the line as well, and an open path ignores the + // alignment. + let dashed = butt(|s| s.dash = Some(Dash { pattern: vec![4.0, 2.0], offset: 0.0, align_corners: false })); + assert_eq!(dashed.bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0)); + assert_eq!(butt(|s| s.align = StrokeAlign::Inside).bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0)); + // A round cap reaches half the weight past each end, a square one the corners. + let round = butt(|s| s.cap = LineCap::Round).bounds_on(&v, v.bounding_box()); + assert_eq!(round, Rect::new(49.0, 9.0, 51.0, 61.0)); + let square = butt(|s| s.cap = LineCap::Square).bounds_on(&v, v.bounding_box()); + assert_eq!(square, Rect::new(49.0, 9.0, 51.0, 61.0)); + // Two strokes union. + let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); + ap.stroke_mut().unwrap().cap = LineCap::Butt; + let wide = stroke(10.0, |s| s.cap = LineCap::Round); + ap.items.push(crate::AppearanceItem::Stroke(wide)); + let vb = v.bounding_box(); + assert_eq!(ap.stroked_bounds(vb, || v.clone()), Rect::new(45.0, 5.0, 55.0, 65.0)); + } + + #[test] + fn a_butt_paths_joins_and_curves_stay_inside_the_box() { + // A corner in the middle: the round join reaches a full half weight straight down, outside + // the turn, the ends do not, and a miter reaches its tip. + let zig = polyline(&[(0.0, 0.0), (20.0, 20.0), (40.0, 0.0)]); + let round = stroke(4.0, |s| { + s.cap = LineCap::Butt; + s.join = LineJoin::Round; + }) + .bounds_on(&zig, zig.bounding_box()); + assert!((round.y1 - 22.0).abs() < 1e-9, "the round join's reach: {round:?}"); + assert!((round.x0 + 2.0_f64.sqrt()).abs() < 1e-9 && (round.x1 - 40.0 - 2.0_f64.sqrt()).abs() < 1e-9, "the ends' corners: {round:?}"); + // A round join paints its arc on the outer side of a turn too shallow to count as a + // corner, and nothing where the path goes straight on. + let round_butt = stroke(4.0, |s| { + s.cap = LineCap::Butt; + s.join = LineJoin::Round; + }); + let shallow = polyline(&[(0.0, 0.25), (50.0, 0.0), (100.0, 0.25)]); + let b = round_butt.bounds_on(&shallow, shallow.bounding_box()); + assert!((b.y0 + 2.0).abs() < 1e-12, "{b:?}"); + let straight = polyline(&[(0.0, 0.0), (0.1, 0.0), (100.0, 0.0)]); + assert_eq!(round_butt.bounds_on(&straight, straight.bounding_box()), Rect::new(0.0, -2.0, 100.0, 2.0)); + let miter = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&zig, zig.bounding_box()); + assert!((miter.y1 - (20.0 + 2.0 * 2.0_f64.sqrt())).abs() < 1e-9, "the miter tip: {miter:?}"); + // An arc over the top whose ends leave the page straight down: the top reaches half the + // weight past the path, and the bottom stops at the ends. + let mut arc = BezPath::new(); + arc.move_to((0.0, 50.0)); + arc.curve_to((0.0, 22.4), (22.4, 0.0), (50.0, 0.0)); + arc.curve_to((77.6, 0.0), (100.0, 22.4), (100.0, 50.0)); + let b = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&arc, arc.bounding_box()); + assert!((b.y0 + 2.0).abs() < 1e-9 && (b.x0 + 2.0).abs() < 1e-9 && (b.x1 - 102.0).abs() < 1e-9, "{b:?}"); + assert!((b.y1 - 50.0).abs() < 1e-9, "{b:?}"); + } + + #[test] + fn a_butt_curve_with_a_handle_on_its_end_point_stops_near_that_end() { + let butt = stroke(2.0, |s| s.cap = LineCap::Butt); + // A straight curve whose first or last handle sits on its end point measures like a line. + let mut first = BezPath::new(); + first.move_to((50.0, 10.0)); + first.curve_to((50.0, 10.0), (50.0, 40.0), (50.0, 60.0)); + let mut last = BezPath::new(); + last.move_to((50.0, 10.0)); + last.curve_to((50.0, 20.0), (50.0, 60.0), (50.0, 60.0)); + for bp in [first, last] { + assert_eq!(butt.bounds_on(&bp, bp.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0)); + } + // A bend that leaves its start straight up from a handle on the start point: the stroke + // reaches only a little below the start, not half the weight. + let mut bend = BezPath::new(); + bend.move_to((0.0, 50.0)); + bend.curve_to((0.0, 50.0), (0.0, 0.0), (50.0, 0.0)); + let b = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&bend, bend.bounding_box()); + assert!(b.y1 >= 50.0 && b.y1 < 50.2, "{b:?}"); + assert!((b.x0 + 2.0).abs() < 1e-9 && (b.y0 + 2.0).abs() < 1e-9 && (b.x1 - 50.0).abs() < 1e-9, "{b:?}"); + // Nearly a cusp: the curve turns back at its lowest point, where its tangent is level and + // the stroke reaches the full half weight below it. + let (a0, a1, a2) = (1e5 * 81.0 / 256.0, -1e5 * 9.0 / 8.0, 1e5); + let x = |i: f64| 2e-9 * i / 3.0; + let mut cusp = BezPath::new(); + cusp.move_to((x(0.0), a0)); + cusp.curve_to((x(1.0), a0 + a1 / 3.0), (x(2.0), a0 + 2.0 * a1 / 3.0 + a2 / 3.0), (x(3.0), a0 + a1 + a2)); + let b = butt.bounds_on(&cusp, cusp.bounding_box()); + assert!(b.y0 <= -1.0 + 1e-6, "{b:?}"); + // A curve far shorter than the weight still reaches half the weight above where its + // tangent is level. + let mut tiny = BezPath::new(); + tiny.move_to((0.0, 0.9e-12)); + tiny.curve_to((0.3e-12, -0.5e-12), (1.7e-12, -0.2e-12), (2e-12, 1e-12)); + let b = butt.bounds_on(&tiny, tiny.bounding_box()); + assert!(b.y0 <= -1.0 + 1e-9, "{b:?}"); + } + + #[test] + fn a_butt_stroke_is_slanted_where_a_segment_starts_or_ends_at_a_slant() { + let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); + ap.stroke_mut().unwrap().cap = LineCap::Butt; + let id = vectorcraft_geom::Affine::IDENTITY; + assert!(!ap.has_slanted_butt_stroke(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id)); + // Square ends, slanted segments in the middle. + let apex = polyline(&[(0.0, 50.0), (0.0, 40.0), (10.0, 0.0), (20.0, 40.0), (20.0, 50.0)]); + assert!(ap.has_slanted_butt_stroke(&apex, id)); + // A rotation slants a vertical line; a round cap is never slanted. + let v = polyline(&[(0.0, 0.0), (0.0, 50.0)]); + assert!(ap.has_slanted_butt_stroke(&v, vectorcraft_geom::Affine::rotate(0.3))); + ap.stroke_mut().unwrap().cap = LineCap::Round; + assert!(!ap.has_slanted_butt_stroke(&apex, id)); + } + + #[test] + fn the_slant_check_looks_into_at_most_4096_symbol_instances() { + // S0 is a vertical butt line. Each of S1 to S12 holds two instances of the symbol before + // it, so an instance of S12 holds 8,191 instances and none of them is slanted. Past 4,096 + // the check answers yes. + let mut d = Document::new(400.0, 400.0); + let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); + ap.stroke_mut().unwrap().cap = LineCap::Butt; + let line = Node::path(d.alloc_id(), PathData::from_bezpath(&polyline(&[(0.0, 0.0), (0.0, 10.0)])), ap); + d.symbols.push(crate::Symbol { dynamic: false, name: "S0".into(), art: std::sync::Arc::new(line) }); + for k in 1..=12 { + let mut instance = |dx: f64| { + let xf = vectorcraft_geom::Affine::translate((dx, 0.0)); + std::sync::Arc::new(Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: format!("S{}", k - 1), xf })) + }; + let pair = vec![instance(0.0), instance(20.0)]; + let art = Node::group(d.alloc_id(), pair); + d.symbols.push(crate::Symbol { dynamic: false, name: format!("S{k}"), art: std::sync::Arc::new(art) }); + } + let top = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S12".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let symbols = d.symbol_boxes(); + assert!(top.has_slanted_butt_stroke(&symbols, vectorcraft_geom::Affine::IDENTITY)); + assert!(symbols.art_measured() <= SLANT_INSTANCES, "{}", symbols.art_measured()); + // One instance of S1 holds three instances, all looked into. + let one = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S1".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + assert!(!one.has_slanted_butt_stroke(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY)); + } + + #[test] + fn a_compound_path_measures_each_of_its_subpaths_by_its_own_ends() { + // A closed square at the top and an open line below it: only the square reaches past its + // own edges. + let mut bp = BezPath::new(); + bp.extend(square().elements().iter().copied()); + bp.move_to((50.0, 150.0)); + bp.line_to((50.0, 200.0)); + let st = stroke(4.0, |s| s.cap = LineCap::Butt); + assert_eq!(st.bounds_on(&bp, bp.bounding_box()), Rect::new(-2.0, -2.0, 102.0, 200.0)); + } + + #[test] + fn a_middle_segment_can_set_the_box_of_a_butt_path() { + // The flat middle segment reaches a full half weight above the path, and the ends' corners + // reach 10/51 of it below. + let hat = polyline(&[(0.0, 50.0), (10.0, 0.0), (20.0, 0.0), (30.0, 50.0)]); + let b = stroke(2.0, |s| { + s.cap = LineCap::Butt; + s.join = LineJoin::Bevel; + }) + .bounds_on(&hat, hat.bounding_box()); + let corner = 10.0 / (10.0_f64 * 10.0 + 50.0 * 50.0).sqrt(); + assert!((b.y0 + 1.0).abs() < 1e-9 && (b.y1 - 50.0 - corner).abs() < 1e-9, "{b:?}"); + } + + #[test] + fn bounds_with_tips_measures_a_butt_line_as_bounds_on_does() { + let v = polyline(&[(50.0, 10.0), (50.0, 60.0)]); + let st = stroke(2.0, |s| s.cap = LineCap::Butt); + assert_eq!(st.bounds_with_tips(&v, v.bounding_box(), None), Rect::new(49.0, 10.0, 51.0, 60.0)); + } + #[test] fn clicks_hit_outside_strokes_on_their_side_only() { let sq = square(); diff --git a/crates/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index 6eda3acef1..90424d5bc2 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -158,6 +158,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[ BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes }, BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects }, BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency }, + BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud }, ]; /// Built-in library `id`, made once. @@ -453,6 +454,34 @@ fn blends_transparency() -> Vec { ] } +/// Game HUD: fills and glows for health, mana, damage and quest chrome (original arcade/HUD look). +fn game_hud() -> Vec { + vec![ + style("Health Fill", vec![F(fill("#e74c3c")), S(stroke("#5c1a1a", 1.25))], vec![]), + style( + "Mana Glow", + vec![F(fill("#3498db"))], + vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 7.0, "color": "#5dade2"}))], + ), + style( + "Damage Flash", + vec![F(fill("#ff6b35"))], + vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 80.0, "blur": 8.0, "color": "#ffe66d", "source": "edge"}))], + ), + style("Quest Outline", vec![F(fill("#f7f3e8")), S(round("#2c3e50", 3.0))], vec![]), + style( + "Coin Shine", + vec![F(fill("#f1c40f")), S(stroke("#b7950b", 1.5))], + vec![fx("stylize.dropShadow", json!({"mode": "multiply", "opacity": 40.0, "x": 2.0, "y": 3.0, "blur": 4.0, "color": "#1d1b2a"}))], + ), + style( + "Boss Alert", + vec![F(fill("#1a1a2e")), S(round("#e94560", 2.5))], + vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 6.0, "color": "#e94560"}))], + ), + ] +} + #[cfg(test)] mod tests { use super::*; @@ -475,6 +504,10 @@ mod tests { } assert!(Arc::ptr_eq(&builtin_style_library("hand-drawn").unwrap(), &builtin_style_library("hand-drawn").unwrap()), "made once"); assert!(builtin_style_library("nope").is_none()); + let game = builtin_style_library("game-hud").unwrap(); + assert_eq!(game.name, "Game HUD"); + let names: Vec<&str> = game.styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]); } #[test] diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 249b46d554..74aa5f4440 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -121,6 +121,12 @@ pub struct TextObject { /// vertical column's centre line), filled in with `cached_bounds` (not serialized). #[serde(skip)] pub cached_baselines: Vec<(Point, Point)>, + /// Cached ink of the glyphs in text space, underline and strikethrough bars included + /// (`vectorcraft_effects::preview::laid_out_ink`, `None` when nothing draws), + /// with the `cached_bounds` it was measured with: filled in with `cached_bounds` by the engine's + /// text edits, and stale once `cached_bounds` differs ([`Self::ink`]). Not serialized. + #[serde(skip)] + pub cached_ink: Option<(Rect, Option)>, } /// Conversion from stored character attributes to document-space type controls. diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index dc83c33cca..bb1fa0eb2c 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -71,6 +71,7 @@ impl TextObject { self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy); self.cached_bounds = None; self.cached_baselines.clear(); + self.cached_ink = None; true } @@ -97,6 +98,7 @@ impl TextObject { list_level_counts: Vec::new(), cached_bounds: None, cached_baselines: Vec::new(), + cached_ink: None, } } /// The list counts the story's earlier frames carry into this frame at each level @@ -288,6 +290,12 @@ impl TextObject { TextKind::Point => Some(self.xf.transform_rect_bbox(self.cached_bounds.unwrap_or_else(|| self.estimate_bounds()))), } } + /// The cached ink of the glyphs in text space ([`Self::cached_ink`]): `Some(None)` when nothing + /// draws, and `None` when it was not measured with the current `cached_bounds`. + pub fn ink(&self) -> Option> { + let (bounds, ink) = self.cached_ink?; + (self.cached_bounds == Some(bounds)).then_some(ink) + } /// How far the characters' strokes paint past their glyphs, in document space: they scale /// with the type. pub fn char_stroke_outset(&self) -> f64 { @@ -359,6 +367,24 @@ impl TextObject { pub fn move_path_anchors(&mut self, refs: &[(usize, usize)], d: Vec2) -> bool { matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| move_anchors(path, to_text, refs, d)) } + /// Move the out (`out`) or in direction handle of anchor `ai` of subpath `si` of type on a + /// path's path to `pos` in document space, as a path's anchor takes it + /// ([`vectorcraft_geom::Anchor::set_handle`]; `independent`: that side only, the anchor a + /// corner): a Direct Selection drag of a handle (#3565). The handle is set in document space, + /// so a smooth anchor keeps its other handle's length as drawn; the brackets keep their + /// fractions of the path. False, changing nothing, for other type, when the anchor doesn't + /// exist, a degenerate `xf` or a path that would not be finite. + pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool { + let xf = self.xf; + matches!(self.kind, TextKind::OnPath { .. }) + && self.reshape_local(|path, to_text| { + let Some(a) = path.anchor_mut(si, ai) else { return false }; + let mut drawn = a.transform(xf); + drawn.set_handle(out, pos, independent); + *a = drawn.transform(to_text); + true + }) + } /// Edit a copy of the area frame with `f` (given the document → text space map) and keep it /// when `f` succeeds and the result is finite. fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool { diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index f669374465..afe256e596 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -124,7 +124,7 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { if let Some(m) = crate::addons::halftone::halftone_art(d, n) { return Some(bake_pieces(d, m)); } - if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) { + if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } @@ -481,7 +481,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, & /// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and /// effects are dropped. `None` for other kinds of objects. pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option { - if let Some(m) = crate::revolve::expand_revolve_art(n).or_else(|| crate::solid_art(n)) { + if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } @@ -551,7 +551,7 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) { /// painting their pieces name are looked up in `doc`. `None` when it has neither a stroke to /// outline nor a geometry effect, so bending first changes nothing. pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option { - if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) { + if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) { return Some(m); } if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) { diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index a2959a843a..4751b137c9 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -603,7 +603,7 @@ fn a_baked_transform_copy_keeps_its_scaled_stroke() { let m = bake_appearance(None, &n).unwrap(); let w = widths(&m); assert_eq!(w.len(), 2, "{w:?}"); - assert!((w[0] - 102.0).abs() < 0.5 && (w[1] - 204.0).abs() < 0.5, "{w:?}"); + assert!((w[1] - 102.0).abs() < 0.5 && (w[0] - 204.0).abs() < 0.5, "the original on top: {w:?}"); assert!(baked_paths(&m).iter().all(|p| p.appearance.stroke().is_none()), "the strokes are outlined"); } @@ -619,7 +619,7 @@ fn a_baked_transform_copy_keeps_its_moved_pattern() { p => panic!("not a pattern: {p:?}"), }) .collect(); - assert_eq!(xs, vec![0.0, 30.0]); + assert_eq!(xs, vec![30.0, 0.0], "the original on top"); } #[test] diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index a8176880bd..e9bbaf4bbf 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -247,7 +247,7 @@ pub fn effect_catalog() -> Vec { "distort.transform", "Transform…", DT, - "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}", + "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}", json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}), ), g( diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 619d06a911..94456c7d57 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -594,7 +594,7 @@ fn a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills() { }; for kind in [image as fn() -> NodeKind, instance] { assert_eq!(starts(kind(), serde_json::json!({"moveH": 30})), [30.0], "{:?}", kind()); - assert_eq!(starts(kind(), serde_json::json!({"moveH": 30, "copies": 2})), [0.0, 30.0, 60.0], "{:?}", kind()); + assert_eq!(starts(kind(), serde_json::json!({"moveH": 30, "copies": 2})), [60.0, 30.0, 0.0], "{:?}", kind()); } } @@ -677,7 +677,8 @@ fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() { let art = evaluate_container(None, &g).unwrap(); let copies = art.children().unwrap()[0].children().expect("the object and its copies are objects of their own"); assert_eq!(copies.len(), 3); - for (i, c) in copies.iter().enumerate() { + // The original is on top, after the copies below it. + for (i, c) in copies.iter().rev().enumerate() { // Each copy's own box: an unplaced gradient fits it, a placed one moved with it. assert!((c.geometric_bounds().unwrap().x0 - 30.0 * i as f64).abs() < 1e-6); match c.appearance.fill_paint() { diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index e5b3201a45..ae8b7d9e90 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -83,11 +83,12 @@ pub use reshape::{ SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape, }; -pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve}; +pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in}; pub use solids::{ CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, - classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, three_d_meshes, three_d_meshes_of, three_d_params_as, - validate_solid, validate_three_d, validate_three_d_params, view_options, + classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, solid_art_in, three_d_meshes, three_d_meshes_in, + three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, + validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; diff --git a/crates/effects/src/preview.rs b/crates/effects/src/preview.rs index 5a619f8acd..ad36ab56dc 100644 --- a/crates/effects/src/preview.rs +++ b/crates/effects/src/preview.rs @@ -17,6 +17,8 @@ //! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows, //! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured //! with its geometry effects, and the other instances in it are measured without them. +//! [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure as these do and, +//! with [`Measure::glyphs`], take point type by the ink of its glyphs (Measure Type by Glyph Bounds). use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -74,6 +76,121 @@ pub fn anchor_bounds(selection: &Selection, doc: &Document, preview: bool) -> Op union_opt(bounds_of(doc, &selection.whole(), preview), selection.anchors_box(doc)) } +/// How [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure objects: +/// `preview` as in [`bounds_of`], and with `glyphs` (Preferences › Type › Measure Type by Glyph +/// Bounds), point type, horizontal or vertical, by the ink of its glyphs instead of its em box +/// ([`text_ink_in`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Measure { + pub preview: bool, + pub glyphs: bool, +} + +impl Measure { + /// See [`by_glyphs`]. + fn by_glyphs(self, drawn: &Drawn, n: &Node) -> bool { + self.glyphs + && matches!(&n.kind, NodeKind::Text(t) if matches!(t.kind, vectorcraft_doc::TextKind::Point)) + && n.projection().is_none() + && !(self.preview && drawn.draws_geometry(n)) + } +} + +/// Whether `m` measures `n` by the ink of its glyphs: point type, not in perspective, and with +/// `preview` only when no geometry effect changes what it draws. +pub fn by_glyphs(symbols: &SymbolBoxes, n: &Node, m: Measure) -> bool { + m.by_glyphs(&Drawn::new(symbols), n) +} + +/// [`bounds_of`] measured by `m`. +pub fn bounds_of_with(doc: &Document, ids: &[NodeId], m: Measure) -> Option { + if !m.glyphs { + return bounds_of(doc, ids, m.preview); + } + let symbols = doc.symbol_boxes(); + let drawn = Drawn::new(&symbols); + if !ids.iter().filter_map(|id| doc.node(*id)).any(|n| m.by_glyphs(&drawn, n)) { + return bounds_of(doc, ids, m.preview); + } + ids.iter().filter_map(|id| doc.node(*id)).fold(None, |acc, n| union_opt(acc, measured_in(&drawn, n, Affine::IDENTITY, m))) +} + +/// [`oriented_bounds`] measured by `m`. +pub fn oriented_bounds_with(doc: &Document, ids: &[NodeId], m: Measure) -> Option { + if !m.glyphs { + return oriented_bounds(doc, ids, m.preview); + } + let symbols = doc.symbol_boxes(); + let drawn = Drawn::new(&symbols); + if !ids.iter().filter_map(|id| doc.node(*id)).any(|n| m.by_glyphs(&drawn, n)) { + return oriented_bounds(doc, ids, m.preview); + } + let angle = doc.bbox_angle(ids); + let to_local = if angle == 0.0 { Affine::IDENTITY } else { OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse() }; + let rect = ids.iter().filter_map(|id| doc.node(*id)).fold(None, |acc, n| union_opt(acc, measured_in(&drawn, n, to_local, m)))?; + Some(OrientedBox { angle, rect }) +} + +/// [`anchor_bounds`] with the objects selected whole measured by `m`. +pub fn anchor_bounds_with(selection: &Selection, doc: &Document, m: Measure) -> Option { + if selection.anchors.is_empty() { + return None; + } + union_opt(bounds_of_with(doc, &selection.whole(), m), selection.anchors_box(doc)) +} + +/// The box of `n` as `a` would place it, without changing it, measured by `m`: [`bounds_in`] with +/// `preview`, else [`Node::bounds_in`] of its geometric bounds, and point type by its glyphs as +/// [`Measure`] says. +pub fn bounds_in_with(symbols: &SymbolBoxes, n: &Node, a: Affine, m: Measure) -> Option { + measured_in(&Drawn::new(symbols), n, a, m) +} + +/// See [`bounds_in_with`]. +fn measured_in(drawn: &Drawn, n: &Node, a: Affine, m: Measure) -> Option { + if m.by_glyphs(drawn, n) + && let NodeKind::Text(t) = &n.kind + && let Some(r) = text_ink_in(t, a) + { + // The fills' and characters' strokes paint around the glyphs, as in `Node::visual_bounds`. + let o = if m.preview { n.appearance.outset().max(t.char_stroke_outset()) } else { 0.0 }; + return Some(r.inflate(o, o)); + } + match (m.preview, a == Affine::IDENTITY) { + (true, _) => drawn.next().bounds_in(n, a), + (false, true) => n.geometric_bounds_with(drawn.symbols), + (false, false) => n.bounds_in(drawn.symbols, a, false), + } +} + +/// The box of the ink of type `t`'s glyphs with its text space mapped by `a * t.xf`: the cached +/// ink ([`vectorcraft_doc::TextObject::ink`]) when that map keeps a rectangle square, else the +/// glyph outlines and the underline and strikethrough bars mapped point by point +/// ([`vectorcraft_text::envelope_ink`]). `None` when nothing draws (no text, only spaces without +/// underline or strikethrough, or glyphs without outlines). +pub fn text_ink_in(t: &vectorcraft_doc::TextObject, a: Affine) -> Option { + let m = a * t.xf; + let [p, q, r, s, _, _] = m.as_coeffs(); + let square = (q.abs() <= 1e-12 && r.abs() <= 1e-12) || (p.abs() <= 1e-12 && s.abs() <= 1e-12); + if square { + let ink = match t.ink() { + Some(ink) => ink, + None => vectorcraft_text::envelope_ink(t, Affine::IDENTITY, None), + }; + return ink.map(|i| m.transform_rect_bbox(i)); + } + vectorcraft_text::envelope_ink(t, m, None) +} + +/// The ink of type `t` laid out as `layout`, in text space: its glyphs +/// ([`vectorcraft_text::TextLayout::ink_bounds`]) and its underline and strikethrough bars +/// ([`vectorcraft_text::decorations`]), what [`text_ink_in`] measures. `None` when nothing draws. +pub fn laid_out_ink(layout: &vectorcraft_text::TextLayout, t: &vectorcraft_doc::TextObject) -> Option { + vectorcraft_text::decorations(layout, vectorcraft_text::FontDb::global(), t) + .into_iter() + .fold(layout.ink_bounds(), |acc, (_, bar)| union_opt(acc, Some(bar.bounding_box()))) +} + /// The visual bounds of `n` as drawn: those of its [`drawn_art`], else /// [`Node::visual_bounds_with`]. pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 070060dcf9..f6c5cf2aea 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -46,8 +46,8 @@ pub fn has_gradient_copies(n: &Node) -> bool { /// Is `n` a path or compound path with a visible Transform effect that makes copies and fills and /// strokes that paint the copies differently as one path than as separate objects /// ([`paints_copies_apart`])? Such an object is drawn through its art ([`outline_art`]), each copy -/// an object of its own above the one before ([`copy_leaf`]), as Expand Appearance makes it -/// (#5920). +/// an object of its own below the one before ([`copy_leaf`]), as Expand Appearance makes it +/// (#5920, #6316). pub(crate) fn has_layered_copies(n: &Node) -> bool { leaf_geometry(n).is_some_and(|(_, rule)| paints_copies_apart(&n.appearance, rule)) && has_transform_copies(n) } @@ -698,6 +698,8 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b let seed = art.id.0; let mut used = art_cost(art); let max = budget.at_least(used); + // Read before the effects run: a path's own copies don't make it art of several objects. + let copy_whole = copies_whole(art); for e in fx { let Some(bounds) = art.geometric_bounds() else { break }; let params = merged_params(&e.id, &e.params); @@ -738,6 +740,14 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b let options = crate::distort::TransformOptions::of(¶ms); (m, copies, options, crate::distort::transform_affine(bounds, ¶ms, seed)) }); + // Art of several objects is copied whole, so the copies don't interleave member by member. + if let Some((m, copies, options, _)) = transform + && copies > 0 + && copy_whole + { + used = copy_art(art, m, copies, copy_scaling(options), max); + continue; + } for_each_leaf(art, &mut |leaf| { let Some((path, rule)) = leaf_geometry(leaf) else { return }; // What the other paths leave of the budget. @@ -747,7 +757,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b // Transform Patterns and Scale Strokes & Effects change each copy's fills and // strokes; a gradient paints each copy by itself, not the one piece the copies // make together; and Expand Appearance (`apart`) makes each copy an object. - // Fills and strokes that stack paint each copy above the one before (#5920). + // Fills and strokes that stack paint each copy below the one before (#5920, #6316). let separate = copies > 0 && (apart || leaf.appearance.has_unplaced_gradient() @@ -813,6 +823,19 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b /// doesn't grow with them (a horizontal line stretched vertically). const MAX_STROKE_SCALE: f64 = 1.0e6; +/// How a Transform effect with `options` scales what it maps: strokes, effects and patterns as +/// its options say. +fn copy_scaling(options: crate::distort::TransformOptions) -> vectorcraft_doc::Scaling { + vectorcraft_doc::Scaling { + strokes: options.strokes, + effects: options.strokes.then_some(crate::scale_effect as fn(&mut Effect, f64)), + patterns: options.patterns, + // A map that flattens the path leaves its fitted gradients fitted, as `fixes_fit` does. + keep_fit_when_flat: true, + ..Default::default() + } +} + /// A Transform effect whose Transform Patterns or Scale Strokes & Effects is on (`options`), with /// map `m` and `copies`, applied to `leaf` (a path or compound path with geometry `path`) as Object /// › Transform with those options transforms an object (#885): the strokes' weights and dashes @@ -829,14 +852,7 @@ fn transform_leaf( options: crate::distort::TransformOptions, budget: Budget, ) -> (Budget, bool) { - let scaling = vectorcraft_doc::Scaling { - strokes: options.strokes, - effects: options.strokes.then_some(crate::scale_effect as fn(&mut Effect, f64)), - patterns: options.patterns, - // A map that flattens the path leaves its fitted gradients fitted, as `fixes_fit` does. - keep_fit_when_flat: true, - ..Default::default() - }; + let scaling = copy_scaling(options); if !options.objects { if options.strokes && let Some(k) = vectorcraft_doc::Scaling::factor(m).filter(|k| k.is_finite() && *k > 0.0) @@ -861,36 +877,172 @@ fn transform_leaf( (copy_leaf(leaf, path, m, copies, scaling, budget), true) } -/// Replace `leaf` (a path or compound path with geometry `path`) by a group of it and `copies` -/// more, each mapped once more by `m` than the last (with `scaling`), as a Transform effect copies -/// an object. Each copy is an object of its own, so its gradients fit it (a placed gradient moves -/// with it) rather than spanning every copy, and its strokes and patterns can differ from the -/// others'. The copies stop where [`crate::distort::transform_within`]'s would, before they pass -/// `budget`, and before one's strokes would scale past [`MAX_STROKE_SCALE`]. Returns what the -/// copies cost, the original included. -fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget { - let mut made = Budget::of(path); - let mut placements: Vec> = vec![Arc::new(leaf.clone())]; +/// Does a Transform effect's copies of `art` copy it whole ([`copy_art`])? They do when `art` is a +/// group or layer of several objects, at least one of which paints, with no type left in it and no +/// fill or stroke of its own that paints. Type that stays type is copied in its place by the baking +/// that keeps it, a clipping group's first member is its clip, and the art's own fills and strokes +/// paint the shape of everything under it, copies included. A member that [`makes_art`] is copied +/// in its place as well: each copy would make that art again, past what [`copy_art`] counts. +fn copies_whole(art: &Node) -> bool { + fn parts(n: &Node, count: &mut usize, painted: &mut bool, text: &mut bool) { + match &n.kind { + NodeKind::Text(_) => *text = true, + NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => { + *count += 1; + *painted |= n.appearance.items.iter().any(crate::paints); + } + NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { + *count += 1; + *painted = true; + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + *painted |= n.appearance.items.iter().any(crate::paints); + children.iter().for_each(|c| parts(c, count, painted, text)); + } + _ => {} + } + } + if art.clips() || !matches!(art.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || art.appearance.items.iter().any(crate::paints) { + return false; + } + let (mut count, mut painted, mut text) = (0, false, false); + parts(art, &mut count, &mut painted, &mut text); + count > 1 && painted && !text && !art.children().into_iter().flatten().any(|c| makes_art(c)) +} + +/// Does `n` or anything visible under it, the art of its opacity masks included, carry a visible +/// effect that makes art when it is drawn (its own or that of a fill or stroke that paints), or is +/// any of them a compound shape? Raster effects, color adjustments and unknown effects make none. +fn makes_art(n: &Node) -> bool { + let makes = |e: &Effect| { + e.visible + && (is_geometry(&e.id) + || crate::is_pathfinder(&e.id) + || crate::is_three_d(&e.id) + || e.id == crate::CROP_MARKS + || e.id == crate::addons::halftone::HALFTONE) + }; + n.visible + && (n.is_compound_shape() + || n.appearance.effects.iter().any(makes) + || n.appearance.items.iter().any(|i| crate::paints(i) && i.effects().iter().any(makes)) + || n.extras().mask.as_deref().is_some_and(|m| makes_art(&m.art)) + || n.children().into_iter().flatten().any(|c| makes_art(c))) +} + +/// What the paths under `n` cost together, those of its opacity masks included. +fn copy_cost(n: &Node) -> Budget { + let mut cost = Budget { anchors: 0, lines: 0 }; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| { + if let NodeKind::Path { guide: false, path, .. } = &c.kind { + cost = cost.plus(Budget::of(path)); + } + }); + cost +} + +/// What the geometry effects of `leaf` (with geometry `path`) and of its fills and strokes add to +/// what `path` costs when it is drawn. +fn effects_cost(leaf: &Node, path: &PathData) -> Budget { + let none = Budget { anchors: 0, lines: 0 }; + let items: Vec<&AppearanceItem> = leaf.appearance.items.iter().filter(|i| crate::paints(i) && crate::has_geometry(i.effects())).collect(); + if items.is_empty() && !crate::has_geometry(&leaf.appearance.effects) { + return none; + } + let Some(bounds) = path.bounds() else { return none }; + let ctx = GeomContext { seed: leaf.id.0, ..GeomContext::of(leaf) }; + let own = crate::apply_geometry_with(&leaf.appearance.effects, path, bounds, &ctx); + let item_cost = |i: &&AppearanceItem| { + let b = own.bounds()?; + Some(Budget::of(&crate::apply_geometry_with(i.effects(), &own, b, &ctx.item(i)))) + }; + // The object's geometry is drawn as it is only by what has no geometry effect of its own. + let plain = items.is_empty() || leaf.appearance.items.iter().any(|i| crate::paints(i) && !crate::has_geometry(i.effects())); + let base = if plain { Budget::of(&own) } else { none }; + base.plus(items.iter().filter_map(item_cost).fold(none, Budget::plus)).minus(Budget::of(path)) +} + +/// Remove the guides anywhere under `n`. +fn without_guides(n: &mut Node) { + let Some(children) = n.children_mut() else { return }; + children.retain(|c| !matches!(c.kind, NodeKind::Path { guide: true, .. })); + children.iter_mut().for_each(|c| without_guides(Arc::make_mut(c))); +} + +/// Replace the members of `art` by groups of them: the original on top and `copies` more below it, +/// each mapped once more by `m` than the last (with `scaling`), as a Transform effect copies a +/// group, without its guides. The copies stop where [`copy_leaf`]'s would, before they pass `budget` or +/// [`crate::distort::MAX_COPY_OBJECTS`] nodes in all, the art of opacity masks counted. Returns what +/// the art costs after. +fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget { + let Some(members) = art.children().cloned() else { return art_cost(art) }; + let original = Node::group(art.id, members); + let mut made = copy_cost(&original); + let mut drawn = original.clone(); + without_guides(&mut drawn); + let mut nodes = original.count_with_masks(); + let one = drawn.count_with_masks(); + let mut placements: Vec> = vec![]; let mut xf = Affine::IDENTITY; for _ in 0..copies { xf *= m; - // A copy scaled up is drawn with more lines. - let cost = Budget::of(&path.transformed(xf)); - if !budget.fits(made.plus(cost)) { - break; - } if scaling.strokes && vectorcraft_doc::Scaling::factor(xf).is_some_and(|k| !(k.is_finite() && k <= MAX_STROKE_SCALE)) { break; } - let mut copy = leaf.clone(); + nodes = nodes.saturating_add(one); + if nodes > crate::distort::MAX_COPY_OBJECTS { + break; + } + let mut copy = drawn.clone(); copy.transform(xf, scaling); - if !copy.geometric_bounds().is_some_and(crate::distort::within_reach) { + let cost = copy_cost(©); + if !budget.fits(made.plus(cost)) || !copy.geometric_bounds().is_some_and(crate::distort::within_reach) { break; } placements.push(Arc::new(copy)); made = made.plus(cost); } - // The copies become nodes of their own under a group with the object's id and name. + // The last copy is the lowest. + placements.reverse(); + placements.push(Arc::new(original)); + if let Some(children) = art.children_mut() { + *children = placements; + } + made +} + +/// Replace `leaf` (a path or compound path with geometry `path`) by a group of it and `copies` +/// more below it, each mapped once more by `m` than the last (with `scaling`), as a Transform effect +/// copies an object. Each copy is an object of its own, so its gradients fit it (a placed gradient +/// moves with it) rather than spanning every copy, and its strokes and patterns can differ from the +/// others'. The copies stop where [`crate::distort::transform_within`]'s would, before they pass +/// `budget` with what each copy's own geometry effects make ([`effects_cost`]), and before one's +/// strokes would scale past [`MAX_STROKE_SCALE`]. Returns what the copies cost, the original +/// included. +fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget { + let mut made = Budget::of(path).plus(effects_cost(leaf, path)); + let mut placements: Vec> = vec![Arc::new(leaf.clone())]; + let mut xf = Affine::IDENTITY; + for _ in 0..copies { + xf *= m; + // A copy scaled up is drawn with more lines. + let moved = path.transformed(xf); + if scaling.strokes && vectorcraft_doc::Scaling::factor(xf).is_some_and(|k| !(k.is_finite() && k <= MAX_STROKE_SCALE)) { + break; + } + let mut copy = leaf.clone(); + copy.transform(xf, scaling); + // Each copy's own geometry effects make a different amount, as the copy and its effects scale. + let cost = Budget::of(&moved).plus(effects_cost(©, &moved)); + if !budget.fits(made.plus(cost)) || !copy.geometric_bounds().is_some_and(crate::distort::within_reach) { + break; + } + placements.push(Arc::new(copy)); + made = made.plus(cost); + } + // The copies become nodes of their own under a group with the object's id and name, the object + // on top. + placements.reverse(); let mut g = Node::group(leaf.id, placements); g.name = leaf.name.clone(); *leaf = g; @@ -1463,6 +1615,8 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) { placements.push(Arc::new(copy)); } *room -= placements.len() - 1; + // The object stays on top of its copies, as a path does. + placements.reverse(); let mut g = Node::group(src.id, placements); g.name = src.name.clone(); *c = Arc::new(g); diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index fd423689f7..a5004ab996 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -3,10 +3,11 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, LineJoin, Node, NodeKind, StrokeLayer}; -use vectorcraft_geom::{PathData, Rect}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2}; use vectorcraft_three_d::{Edge, Revolve}; +use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, resolve_for, solid_paints, union_bounds}; use crate::util::{flag, num, text}; use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params}; @@ -17,6 +18,13 @@ pub const REVOLVE: &str = "threeD.revolve"; /// thousands of faces took gigabytes; past this the source path is drawn. const MAX_PAINT_COPIES: usize = 256 << 20; +/// The most face and box tests a group's transparent members' faces take together to rejoin their +/// members' last runs; past them each starts a run of its own. +const MAX_OVERLAP_TESTS: usize = 1 << 22; + +/// The width of the stroke around each face that covers the seams between faces. +const SEAM_WIDTH: f64 = 0.75; + /// About the bytes one copy of `paint` takes. fn paint_bytes(paint: &Paint) -> usize { use std::mem::size_of; @@ -60,19 +68,109 @@ pub fn revolve_options(p: &Value) -> Revolve { shade: flag(p, "shade", true), smooth_shading: true, cap_ends: flag(p, "cap", true), + curve_samples: None, } } /// Validate before a command mutates the document. Loading external files is still bounded /// by the evaluator; unsupported source kinds remain unchanged when rendered. pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> { + validate_revolve_in(None, n, p) +} + +/// [`validate_revolve`] with the symbols of `doc`: a symbol instance, a blend and a clipping group +/// revolve the art they show ([`resolve_for`]), cut for Revolve whatever 3D effect `n` carries now. +pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Result<(), String> { validate_revolve_params(p)?; - let path = profile(n).ok_or("Revolve currently requires a path or compound path. Select a profile drawn with the Pen tool.")?; - let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?; - if !path.subpaths.iter().any(|sp| sp.anchors.len() >= 2) { - return Err("Revolve requires at least two anchors".into()); + let n = &*resolve_for(doc, n, "Revolve", false)?; + let effects = &n.appearance.effects; + // The profile is measured before the object's one Revolve, hidden or shown. + let before = effects.iter().position(|e| e.id == REVOLVE).and_then(|i| effects.get(..i)).unwrap_or(effects); + if is_container(n) { + const EMPTY: &str = "Revolve requires a group holding a shape with at least two anchors"; + let mut shapes = members(n, "Revolve")?; + if !shapes.iter().any(|s| has_two_anchors(&s.path)) { + return Err(EMPTY.into()); + } + reshape_members(n, before, &mut shapes); + let b = union_bounds(&shapes).ok_or(EMPTY)?; + let options = shared_options(&shapes, revolve_options(p))?; + let mut copies = 0; + return shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies)); } - vectorcraft_three_d::revolve(&path, b, revolve_options(p)).map(|_| ()) + let (path, _) = object_profile(n, "Revolve")?; + if !has_two_anchors(&path) { + return Err("Revolve requires a shape with at least two anchors".into()); + } + let path = geometry(&path, before, &GeomContext::of(n)); + let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; + let paints = solid_paints(n); + check_surface(&path, b, revolve_options(p), surface_item(&paints), &mut 0) +} + +/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of +/// appearance item `target` of `n`. The surfaces of every fill and stroke that carries a Revolve, +/// `target`'s included, share one budget of paint copies, as in [`art`]. A visible object-level +/// Revolve draws in place of those surfaces. +pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> { + if is_container(n) || visible(&n.appearance.effects) || target >= n.appearance.items.len() { + return validate_revolve(n, p); + } + validate_revolve_params(p)?; + const EMPTY: &str = "Revolve requires a shape with at least two anchors"; + let (path, _) = object_profile(n, "Revolve")?; + if !has_two_anchors(&path) { + return Err(EMPTY.into()); + } + let ctx = GeomContext::of(n); + let path = geometry(&path, &n.appearance.effects, &ctx); + let mut copies = 0; + for (i, item) in n.appearance.items.iter().enumerate() { + let effects = item.effects(); + let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && e.id == REVOLVE) }; + let options = match at.and_then(|at| effects.get(at)) { + _ if i == target => revolve_options(p), + Some(fx) if crate::paints(item) => revolve_options(&merged_params(REVOLVE, &fx.params)), + _ => continue, + }; + let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item)); + let b = path.bounds().ok_or(EMPTY)?; + check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?; + } + Ok(()) +} + +fn has_two_anchors(path: &PathData) -> bool { + path.subpaths.iter().any(|sp| sp.anchors.len() >= 2) +} + +/// The bytes the copies of `paint` take on `faces` faces: a face's fill, its shadow and their seam +/// strokes make up to four copies. +fn paint_copies(faces: usize, paint: &Paint) -> usize { + faces.saturating_mul(4).saturating_mul(paint_bytes(paint)) +} + +/// An error when `path` does not revolve or when its surface in `item`'s paint takes `copies`, the +/// bytes of an object's paint copies so far, past [`MAX_PAINT_COPIES`]. +fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&AppearanceItem>, copies: &mut usize) -> Result<(), String> { + let faces = vectorcraft_three_d::revolve(path, b, options)?; + *copies = copies.saturating_add(item.map_or(0, |i| paint_copies(faces.len(), &paint_of(i).0))); + if *copies > MAX_PAINT_COPIES { + return Err("Revolve paint is too complex for this surface; reduce Segments or simplify the gradient".into()); + } + Ok(()) +} + +/// `options` with one number of samples for every curve of `shapes`, the members of one group: the +/// members share Revolve's limits. +fn shared_options(shapes: &[Profile], options: Revolve) -> Result { + let samples = vectorcraft_three_d::revolve_curve_samples(shapes.iter().map(|s| &s.path), options)?; + Ok(Revolve { curve_samples: Some(samples), ..options }) +} + +/// The item whose paint an object's surface takes: its top fill, else its top stroke. +fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> { + items.iter().rev().find(|i| matches!(i, AppearanceItem::Fill(_))).or_else(|| items.last()) } /// Check Revolve's parameter values `p` alone: its lights, `edge` and `cap`. @@ -87,38 +185,31 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> { Ok(()) } -fn profile(n: &Node) -> Option { - match &n.kind { - NodeKind::Path { path, guide: false, clipping: false, .. } => Some(path.clone()), - NodeKind::Compound { children, .. } => { - Some(PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect())) - } - _ => None, - } -} - fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { apply_geometry_with(fx, path, path.bounds().unwrap_or(Rect::ZERO), ctx) } +/// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts +/// the bytes of the paint copies of every surface of the object. #[allow(clippy::too_many_arguments)] fn surface( n: &Node, path: &PathData, + b: Rect, + options: Revolve, fx: &Effect, paint: Paint, opacity: f32, blend: vectorcraft_doc::color::BlendMode, expand: bool, -) -> Option { - let b = path.bounds()?; + copies: &mut usize, +) -> Option<(Vec, Node)> { // A loaded file or a profile edited past the limits keeps drawing its source path instead // of crashing the frame. Commands validate the same evaluator and report its errors. - let options = revolve_options(&merged_params(REVOLVE, &fx.params)); let colored = options.light_color != [1.0; 3] || options.lights.is_some(); let faces = vectorcraft_three_d::revolve(path, b, options).ok()?; - // A face's fill, its shadow and their seam strokes: up to four copies of the paint. - if faces.len().saturating_mul(4).saturating_mul(paint_bytes(&paint)) > MAX_PAINT_COPIES { + *copies = copies.saturating_add(paint_copies(faces.len(), &paint)); + if *copies > MAX_PAINT_COPIES { return None; } // Visibility is an expansion option, never a change to live geometry or export baking. @@ -146,6 +237,7 @@ fn surface( }) .collect() }); + let depths: Vec = faces.iter().map(|f: &vectorcraft_three_d::VisibleFace| f.depth).collect(); let children = faces .into_iter() .map(|face| { @@ -188,7 +280,7 @@ fn surface( .into_iter() .flat_map(|item| { let AppearanceItem::Fill(fill) = &item else { return vec![item] }; - let mut edge = StrokeLayer::new(fill.paint.clone(), 0.75); + let mut edge = StrokeLayer::new(fill.paint.clone(), SEAM_WIDTH); // Acute face corners must stay within the overlap width. Miter joins // amplify this seam stroke into visible spikes along the silhouette. edge.join = LineJoin::Round; @@ -202,7 +294,16 @@ fn surface( let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; - Some(group) + Some((depths, group)) +} + +/// A surface of one object about the bounds of `path`, built with options derived from `fx`. +/// `copies` is the count [`surface`] adds to. +fn object_surface(n: &Node, path: &PathData, fx: &Effect, item: &AppearanceItem, expand: bool, copies: &mut usize) -> Option { + let b = path.bounds()?; + let (paint, opacity, blend) = paint_of(item); + let options = revolve_options(&merged_params(REVOLVE, &fx.params)); + surface(n, path, b, options, fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) } fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> Color, opacity: impl Fn(f64) -> f32) -> Paint { @@ -224,12 +325,26 @@ fn paint_of(item: &AppearanceItem) -> (Paint, f32, vectorcraft_doc::color::Blend /// Evaluated art keeps the source's identity and transparency. Each item's opacity belongs /// to its entire surface, not to each face, so overlapping faces don't accumulate alpha. pub fn revolve_art(n: &Node) -> Option { - art(n, false) + revolve_art_in(None, n) } -/// Revolve's own Expand Appearance path. The shared command and UI remain unchanged. +/// [`revolve_art`] with the symbols of `doc`: a symbol instance, a blend and a clipping group, alone +/// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be +/// resolved. +pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { + art(doc, n, false) +} + +/// [`expand_revolve_art_in`] without a document. +#[cfg(test)] pub(crate) fn expand_revolve_art(n: &Node) -> Option { - art(n, true) + expand_revolve_art_in(None, n) +} + +/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared +/// command and UI remain unchanged. +pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { + art(doc, n, true) } /// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on @@ -237,26 +352,23 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option { /// each of them. Each mesh adds its triangles to `total` as it is built, and the first that takes /// `total` past `limit` stops with an error before the next is built. pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, String> { - let path = profile(n).ok_or("Revolve currently requires a path or compound path")?; + if is_container(n) { + return group_meshes(n, total, limit); + } + let (path, rule) = object_profile(n, "Revolve")?; let ctx = GeomContext::of(n); let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result { - let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?; + let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let (paint, opacity, _) = paint_of(item); - let mesh = vectorcraft_three_d::revolve_mesh(path, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?; Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) }) }; if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) { let before = n.appearance.effects.get(..index).unwrap_or_default(); let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; let path = geometry(&path, before, &ctx); - let item = n - .appearance - .items - .iter() - .rev() - .find(|i| matches!(i, AppearanceItem::Fill(_)) && crate::paints(i)) - .or_else(|| n.appearance.items.iter().rev().find(|i| crate::paints(i))) - .ok_or("the revolved object has no fill or stroke")?; + let paints = solid_paints(n); + let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?; let mut out = vec![]; crate::solids::keep_mesh(&mut out, total, mesh(&path, fx, item)?, limit)?; return Ok(out); @@ -274,28 +386,50 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul Ok(out) } -fn art(n: &Node, expand: bool) -> Option { +/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis. +fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, String> { + let index = n + .appearance + .effects + .iter() + .position(|e| e.visible && e.id == REVOLVE) + .ok_or("a 3D effect on a group's fill or stroke draws nothing to export")?; + let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; + let mut shapes = members(n, "Revolve")?; + reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); + let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?; + let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + let mut out = vec![]; + for s in &shapes { + let Some(item) = surface_item(&s.items) else { continue }; + let (paint, opacity, _) = paint_of(item); + let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?; + crate::solids::keep_mesh(&mut out, total, crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity * s.opacity) }, limit)?; + } + Ok(out) +} + +fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { if !has_revolve(n) { return None; } - let path = profile(n)?; + let n = &*resolve_for(doc, n, "Revolve", false).ok()?; + if is_container(n) { + return group_art(n, expand); + } + let (path, _) = profile(n)?; let ctx = GeomContext::of(n); let mut children = vec![]; + let mut copies = 0; let mut remaining = n.appearance.effects.clone(); if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) { let fx = n.appearance.effects.get(index)?; let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); // An object's surface uses its top visible fill, falling back to its stroke. - let item = n - .appearance - .items - .iter() - .rev() - .find(|i| matches!(i, AppearanceItem::Fill(_)) && crate::paints(i)) - .or_else(|| n.appearance.items.iter().rev().find(|i| crate::paints(i)))?; - let (paint, opacity, blend) = paint_of(item); + let paints = solid_paints(n); + let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - children.push(Arc::new(surface(n, &path, fx, paint, opacity, blend, expand)?)); + children.push(Arc::new(object_surface(n, &path, fx, item, expand, &mut copies)?)); // Later geometry acts on the projected art as a whole through container evaluation. remaining = n .appearance @@ -312,9 +446,8 @@ fn art(n: &Node, expand: bool) -> Option { if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE) { let fx = item.effects().get(index)?; let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item)); - let (paint, opacity, blend) = paint_of(item); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let mut art = surface(n, &p, fx, paint, opacity, blend, expand)?; + let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?; art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| e.id != REVOLVE).cloned().collect(); children.push(Arc::new(art)); } else { @@ -328,6 +461,244 @@ fn art(n: &Node, expand: bool) -> Option { Some(art) } +/// The members' `surfaces`, or runs of their faces, in order, from the [`Scope`] at `level` of each +/// one's `Profile::scopes` inward: consecutive surfaces that share a scope go in one group with its +/// opacity and blending mode, so each applies once, to the faces it holds together. +fn scoped(id: NodeId, surfaces: Vec<(&[Scope], Arc)>, level: usize) -> Vec> { + fn close(id: NodeId, run: &mut Vec<(&[Scope], Arc)>, scope: Option, level: usize, out: &mut Vec>) { + if let Some(scope) = scope { + let mut group = Node::group(id, scoped(id, std::mem::take(run), level + 1)); + group.opacity = scope.opacity; + group.blend = scope.blend; + out.push(Arc::new(group)); + } + } + let mut out = vec![]; + let mut run = vec![]; + let mut scope = None; + for (scopes, s) in surfaces { + let at = scopes.get(level).copied(); + if at.map(|a| a.key) != scope.map(|s: Scope| s.key) { + close(id, &mut run, scope, level, &mut out); + scope = at; + } + if scope.is_some() { + run.push((scopes, s)); + } else { + out.push(s); + } + } + close(id, &mut run, scope, level, &mut out); + out +} + +/// What a face can paint, to tell whether two faces overlap: the convex hull of the points and +/// control points of its outline, which holds the outline, and the hull's box grown by half the +/// seam stroke. +struct Coverage { + bounds: Rect, + hull: Vec, +} + +impl Coverage { + /// `None` for a face with no outline and no box. + fn of(face: &Node) -> Option { + let points: Vec = match face.path_data() { + Some(path) => path + .to_bezpath() + .elements() + .iter() + .flat_map(|e| match *e { + PathEl::MoveTo(p) | PathEl::LineTo(p) => vec![p], + PathEl::QuadTo(a, b) => vec![a, b], + PathEl::CurveTo(a, b, c) => vec![a, b, c], + PathEl::ClosePath => vec![], + }) + .collect(), + None => { + let b = face.visual_bounds()?; + vec![Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] + } + }; + let hull = convex_hull(points); + let first = *hull.first()?; + let reach = SEAM_WIDTH / 2.0; + let bounds = hull.iter().fold(Rect::from_points(first, first), |b, p| b.union_pt(*p)).inflate(reach, reach); + Some(Coverage { bounds, hull }) + } + + /// Do the two faces' hulls, each grown by half the seam stroke, overlap? A test of the + /// separating axes of their edges and of the page's axes: `true` whenever they overlap, and + /// sometimes near a corner when they don't. + fn meets(&self, other: &Coverage) -> bool { + fn normals(hull: &[Point]) -> impl Iterator + '_ { + (0..hull.len()).filter_map(|i| { + let (a, b) = (hull.get(i)?, hull.get((i + 1) % hull.len())?); + Some(Vec2::new(a.y - b.y, b.x - a.x)) + }) + } + let axes = [Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)].into_iter().chain(normals(&self.hull)).chain(normals(&other.hull)); + let span = |hull: &[Point], axis: Vec2| { + hull.iter().map(|p| p.to_vec2().dot(axis)).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v))) + }; + axes.filter(|axis| axis.hypot() > 0.0).all(|axis| { + let ((a0, a1), (b0, b1)) = (span(&self.hull, axis), span(&other.hull, axis)); + let gap = SEAM_WIDTH * axis.hypot(); + b0 - a1 < gap && a0 - b1 < gap + }) + } +} + +/// The convex hull of `points`, counterclockwise in a y-up frame, without repeated points. +fn convex_hull(mut points: Vec) -> Vec { + points.retain(|p| p.is_finite()); + points.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); + points.dedup(); + if points.len() < 3 { + return points; + } + // One side of the hull from the first point to the last, without the last. + fn side<'a>(points: impl Iterator) -> Vec { + let mut chain: Vec = vec![]; + for &p in points { + while let [.., o, a] = chain[..] + && (a - o).cross(p - o) <= 0.0 + { + chain.pop(); + } + chain.push(p); + } + chain.pop(); + chain + } + let mut hull = side(points.iter()); + hull.extend(side(points.iter().rev())); + hull +} + +/// Do boxes `a` and `b` overlap with some area? +fn overlaps(a: Rect, b: Rect) -> bool { + a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1 +} + +/// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them, +/// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when +/// the effect is only on the group's own fills or strokes or when its members can't be revolved. +fn group_art(n: &Node, expand: bool) -> Option { + let index = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE)?; + let fx = n.appearance.effects.get(index)?; + let mut shapes = members(n, "").ok()?; + reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); + let b = union_bounds(&shapes)?; + let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params))).ok()?; + let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); + let mut copies = 0; + let mut surfaces = vec![]; + let mut opaque = true; + for s in &shapes { + let Some(item) = surface_item(&s.items) else { continue }; + // The opacity and blending of the member and the groups it is in apply through its scopes. + let (paint, opacity, blend) = paint_of(item); + opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); + // A member with transparency of its own keeps every face, as a transparent object does. + let expand = expand && s.scopes.is_empty(); + let (depths, art) = surface(n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?; + surfaces.push((depths, art, s.scopes.as_slice())); + } + if surfaces.is_empty() { + return None; + } + let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())); + let children = if !plain { + scoped(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect(), 0) + } else { + let count = surfaces.len(); + let mut faces = vec![]; + for (member, (depths, s, scopes)) in surfaces.into_iter().enumerate() { + let (opacity, blend) = (s.opacity, s.blend); + if let NodeKind::Group { children, .. } = s.kind { + faces.extend(depths.into_iter().zip(children).map(|(depth, face)| (depth, member, opacity, blend, scopes, face))); + } + } + // A stable sort: faces at the same depth keep the members' order. + faces.sort_by(|a, b| a.0.total_cmp(&b.0)); + if opaque { + vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(.., face)| face).collect()))] + } else { + // An opaque member's face goes in the order on its own. The faces of a member with + // transparency share a run, one group with the opacity and blending mode of its fill or + // stroke, and its scopes group runs further. Such a face joins its member's last run + // unless a face drawn after that run overlaps it: only then does the member split, + // where one group can't be both behind and in front of another face. + struct Run<'a> { + member: Option, + scopes: &'a [Scope], + bounds: Rect, + faces: Vec>, + cover: Vec, + opacity: f32, + blend: vectorcraft_doc::color::BlendMode, + } + let mut runs: Vec = vec![]; + let mut last_run = vec![None; count]; + // Past this many tests a face starts a run of its own, which never draws out of order. + let mut budget = MAX_OVERLAP_TESTS; + for (_, member, opacity, blend, scopes, face) in faces { + let paints = opacity > 0.0 && scopes.iter().all(|s| s.opacity > 0.0); + let Some(cover) = Coverage::of(&face).filter(|_| paints) else { + // A face that paints nothing goes in the order on its own and overlaps nothing. + runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend }); + continue; + }; + if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() { + runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend }); + continue; + } + let mut clear = |r: &Run| { + budget = budget.saturating_sub(1); + if !overlaps(r.bounds, cover.bounds) { + return budget > 0; + } + budget = budget.saturating_sub(r.cover.len()); + budget > 0 && r.cover.iter().all(|c| !overlaps(c.bounds, cover.bounds) || !c.meets(&cover)) + }; + let joins = + last_run.get(member).copied().flatten().filter(|&i: &usize| runs.get(i + 1..).is_some_and(|later| later.iter().all(&mut clear))); + match joins.and_then(|i| runs.get_mut(i)) { + Some(run) => { + run.bounds = run.bounds.union(cover.bounds); + run.faces.push(face); + run.cover.push(cover); + } + None => { + if let Some(last) = last_run.get_mut(member) { + *last = Some(runs.len()); + } + runs.push(Run { member: Some(member), scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend }); + } + } + } + let runs = runs.into_iter().filter_map(|mut r| { + // A face on its own needs a group only for the opacity or blending mode of its fill or stroke. + if r.member.is_none() && r.opacity >= 1.0 && r.blend == Default::default() { + return r.faces.pop().map(|face| (r.scopes, face)); + } + let mut group = Node::group(n.id, r.faces); + group.opacity = r.opacity; + group.blend = r.blend; + Some((r.scopes, Arc::new(group))) + }); + scoped(n.id, runs.collect(), 0) + } + }; + let remaining = + n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect(); + let mut art = n.clone(); + art.kind = NodeKind::Group { children, clip: false }; + art.appearance = Appearance { effects: remaining, ..Default::default() }.into(); + Some(art) +} + #[cfg(test)] mod tests { use super::*; @@ -495,6 +866,386 @@ mod tests { assert_eq!(expand_revolve_art(&n).unwrap().children().unwrap()[0], expanded.children().unwrap()[0]); } + /// A closed rectangle `x` to `x + 10` across, filled solid. + fn member(id: u64, x: f64) -> Arc { + let mut b = BezPath::new(); + b.move_to((x, 0.0)); + b.line_to((x + 10.0, 0.0)); + b.line_to((x + 10.0, 40.0)); + b.line_to((x, 40.0)); + b.close_path(); + Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.8, 0.2, 0.1)), Paint::None, 0.0))) + } + + fn group_with(params: Value, children: Vec>) -> Node { + let mut g = Node::group(NodeId(9), children); + g.appearance.effects.push(crate::new_effect(REVOLVE, ¶ms).unwrap()); + g + } + + #[test] + fn a_groups_members_share_the_axis_on_the_edge_of_them_all() { + let mut hidden = (*member(3, -500.0)).clone(); + hidden.visible = false; + let nested = Arc::new(Node::group(NodeId(5), vec![member(4, 90.0)])); + let children = vec![member(1, 0.0), nested, Arc::new(hidden)]; + // Left edge, 5 pt out: the axis at -5, the far wall (100) 105 from it. + let g = group_with(json!({"segments":32,"offset":5,"rotationX":0}), children.clone()); + let b = revolve_art(&g).unwrap().visual_bounds().unwrap(); + assert!((b.x0 + 110.0).abs() < 1.5 && (b.x1 - 100.0).abs() < 1.5, "{b:?}"); + // Right edge, 5 pt out: the axis at 105, the far wall (0) 105 from it. + let g = group_with(json!({"segments":32,"offset":5,"edge":"right","rotationX":0}), children); + let b = revolve_art(&g).unwrap().visual_bounds().unwrap(); + assert!((b.x1 - 210.0).abs() < 1.5 && (b.x0 - 0.0).abs() < 1.5, "{b:?}"); + } + + #[test] + fn opaque_members_share_one_back_to_front_order() { + let g = group_with(json!({"segments":16}), vec![member(1, 0.0), member(2, 50.0)]); + let art = revolve_art(&g).unwrap(); + assert_eq!(art.children().unwrap().len(), 1, "one order for every face"); + assert!(art.children().unwrap()[0].children().unwrap().len() > 16); + } + + /// The opacities and blending modes of the groups a face is drawn in, outermost first, leaving + /// out groups with neither. + type Chain = Vec<(f32, vectorcraft_doc::color::BlendMode)>; + + /// The faces of `art` in drawing order, each with its [`Chain`]. + fn faces_in_order(art: &Node) -> Vec<(Node, Chain)> { + fn visit(n: &Node, mut scopes: Chain, out: &mut Vec<(Node, Chain)>) { + match n.children() { + Some(children) => { + if n.opacity != 1.0 || n.blend != Default::default() { + scopes.push((n.opacity, n.blend)); + } + for c in children { + visit(c, scopes.clone(), out); + } + } + None => out.push((n.clone(), scopes)), + } + } + let mut out = vec![]; + visit(art, vec![], &mut out); + out + } + + #[test] + fn a_transparent_member_leaves_every_face_in_one_back_to_front_order() { + let faces_of = |members| faces_in_order(&revolve_art(&group_with(json!({"segments":16}), members)).unwrap()); + let alone = faces_of(vec![member(1, 0.0), member(2, 50.0)]); + let mut faded = (*member(3, 20.0)).clone(); + faded.opacity = 0.5; + let faces = faces_of(vec![member(1, 0.0), member(2, 50.0), Arc::new(faded)]); + let opaque: Vec<_> = faces.iter().filter(|(_, s)| s.is_empty()).map(|(f, _)| f).collect(); + assert_eq!(opaque, alone.iter().map(|(f, _)| f).collect::>(), "the opaque members' faces keep their shared order"); + assert!(faces.iter().all(|(_, s)| s.is_empty() || s == &[(0.5, Default::default())]), "the member's opacity applies once to each face"); + let first = faces.iter().position(|(_, s)| !s.is_empty()).unwrap(); + let last = faces.iter().rposition(|(_, s)| !s.is_empty()).unwrap(); + assert!(first > 0 && last + 1 < faces.len(), "the ring between the others draws in front of the back ones and behind the front ones"); + let groups = |art: &Node| { + let mut count = 0; + art.walk(&mut |n| count += usize::from(n.children().is_some() && n.opacity == 0.5)); + count + }; + // Rings one above the other: their faces alternate in the order but none overlaps the + // other ring, so each ring's opacity applies once, to all its faces. + let faded = |id, y: f64| { + let mut n = (*member(id, 40.0)).clone(); + n.opacity = 0.5; + if let NodeKind::Path { path, .. } = &mut n.kind { + *path = PathData::from_bezpath(&(Affine::translate((0.0, y)) * path.to_bezpath())); + } + Arc::new(n) + }; + let art = revolve_art(&group_with(json!({"segments":16}), vec![faded(1, 0.0), faded(2, 200.0)])).unwrap(); + assert!(faces_in_order(&art).iter().all(|(_, s)| s == &[(0.5, Default::default())])); + assert_eq!(groups(&art), 2, "one group for each ring"); + // A tall cylinder inside both that paints nothing splits neither. + let mut hidden = (*member(3, 0.0)).clone(); + hidden.opacity = 0.0; + if let NodeKind::Path { path, .. } = &mut hidden.kind { + *path = PathData::from_bezpath(&(Affine::translate((0.0, -20.0)) * Affine::scale_non_uniform(1.0, 7.0) * path.to_bezpath())); + } + let art = revolve_art(&group_with(json!({"segments":16}), vec![faded(1, 0.0), faded(2, 200.0), Arc::new(hidden)])).unwrap(); + assert_eq!(groups(&art), 2, "one group for each faded ring"); + } + + #[test] + fn a_member_whose_fill_or_stroke_paints_nothing_stays_invisible() { + let clear_fill = { + let mut n = (*member(3, 20.0)).clone(); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) { + f.opacity = 0.0; + } + n + }; + let clear_stroke = { + let mut n = (*member(4, 20.0)).clone(); + n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into(); + for item in n.appearance.items.iter_mut() { + if let AppearanceItem::Stroke(s) = item { + s.opacity = 0.0; + } + } + n + }; + for clear in [clear_fill, clear_stroke] { + let art = revolve_art(&group_with(json!({"segments":16}), vec![member(1, 0.0), member(2, 50.0), Arc::new(clear)])).unwrap(); + let faces = faces_in_order(&art); + let alone = faces_in_order(&revolve_art(&group_with(json!({"segments":16}), vec![member(1, 0.0), member(2, 50.0)])).unwrap()); + let opaque: Vec<_> = faces.iter().filter(|(_, s)| s.is_empty()).map(|(f, _)| f).collect(); + assert_eq!(opaque, alone.iter().map(|(f, _)| f).collect::>(), "only the opaque members' faces draw without transparency"); + assert!(faces.len() > alone.len(), "the clear member's faces stay in the art"); + assert!(faces.iter().all(|(_, s)| s.is_empty() || s.iter().any(|(o, _)| *o == 0.0)), "each clear face is drawn at 0% opacity"); + } + } + + fn star(id: u64) -> Arc { + let anchors = (0..1200) + .map(|i| { + let (s, c) = (i as f64 * std::f64::consts::PI / 600.0).sin_cos(); + let r = if i % 2 == 0 { 100.0 } else { 60.0 }; + vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(200.0 + r * c, 200.0 + r * s)) + }) + .collect(); + Arc::new(Node::path( + NodeId(id), + PathData::new(vec![vectorcraft_geom::SubPath::new(anchors, true)]), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + )) + } + + #[test] + fn faces_overlap_by_their_painted_shapes_and_seams_not_only_their_boxes() { + let face = |points: &[(f64, f64)]| { + let mut b = BezPath::new(); + b.move_to(points[0]); + for &p in &points[1..] { + b.line_to(p); + } + b.close_path(); + Coverage::of(&Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::default())).unwrap() + }; + let a = face(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)]); + assert_eq!(a.hull.len(), 3); + assert_eq!( + face(&[(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (10.0, 10.0), (5.0, 5.0), (0.0, 10.0)]).hull.len(), + 4, + "a point on an edge or inside is left out" + ); + // Across the diagonal 2 / sqrt(2) apart: their boxes overlap, their shapes and seams don't. + let b = face(&[(10.0, 10.0), (10.0, 2.0), (2.0, 10.0)]); + assert!(overlaps(a.bounds, b.bounds) && !a.meets(&b) && !b.meets(&a)); + // 1 / sqrt(2) apart, within the two half seam strokes. + let c = face(&[(10.0, 10.0), (10.0, 1.0), (1.0, 10.0)]); + assert!(a.meets(&c) && c.meets(&a)); + assert!(a.meets(&a), "a face meets itself"); + } + + #[test] + fn a_groups_members_share_revolves_limits() { + let alone = group_with(json!({}), vec![star(1)]); + assert!(validate_revolve(&alone, &json!({})).is_ok()); + let both = group_with(json!({}), vec![star(1), star(2)]); + let refused = validate_revolve(&both, &json!({})).unwrap_err(); + assert!(refused.contains("reduce Segments"), "{refused}"); + assert_eq!(revolve_art(&both), None, "past the limits the source draws"); + } + + #[test] + fn blending_modes_apply_once_to_the_member_or_group_that_has_them() { + use vectorcraft_doc::color::BlendMode; + let blend = |n: Arc, mode: BlendMode| { + let mut n = (*n).clone(); + n.blend = mode; + Arc::new(n) + }; + let inner = blend(member(4, 60.0), BlendMode::Multiply); + let screened = blend(Arc::new(Node::group(NodeId(5), vec![member(3, 40.0), inner])), BlendMode::Screen); + let group = group_with(json!({}), vec![blend(member(1, 0.0), BlendMode::Multiply), member(2, 20.0), screened]); + let art = revolve_art(&group).expect("revolved"); + let faces = faces_in_order(&art); + let modes = |s: &[(f32, BlendMode)]| s.iter().map(|(_, b)| *b).collect::>(); + let chains = [vec![BlendMode::Multiply], vec![], vec![BlendMode::Screen], vec![BlendMode::Screen, BlendMode::Multiply]]; + for chain in &chains { + assert!(faces.iter().any(|(_, s)| &modes(s) == chain), "faces drawn in {chain:?}"); + } + assert!(faces.iter().all(|(_, s)| chains.contains(&modes(s))), "each mode applies once, to the member or group that has it"); + // Faces of the screened group's members that come together in the drawing order share one Screen group. + let runs = |faces: &[(Node, Chain)], inside: &dyn Fn(&Chain) -> bool| { + faces.windows(2).filter(|w| inside(&w[1].1) && !inside(&w[0].1)).count() + usize::from(faces.first().is_some_and(|f| inside(&f.1))) + }; + let groups = |art: &Node, pick: &dyn Fn(&Node) -> bool| { + let mut count = 0; + art.walk(&mut |n| count += usize::from(n.children().is_some() && pick(n))); + count + }; + let screened = |s: &Chain| s.first().is_some_and(|(_, b)| *b == BlendMode::Screen); + assert_eq!(groups(&art, &|n| n.blend == BlendMode::Screen), runs(&faces, &screened)); + let plain = group_with(json!({}), vec![member(1, 0.0)]); + assert_ne!(expand_revolve_art(&plain), revolve_art(&plain), "an opaque member's hidden faces are removed"); + let multiplied = group_with(json!({}), vec![blend(member(1, 0.0), BlendMode::Multiply)]); + assert_eq!(expand_revolve_art(&multiplied), revolve_art(&multiplied), "a blended member keeps every face"); + // A nested group's opacity applies once, to its members' faces that come together. + let mut faded = Node::group(NodeId(6), vec![member(3, 40.0), member(4, 45.0)]); + faded.opacity = 0.5; + let art = revolve_art(&group_with(json!({}), vec![member(1, 0.0), Arc::new(faded)])).expect("revolved"); + let faces = faces_in_order(&art); + assert!(faces.iter().all(|(_, s)| s.is_empty() || s == &[(0.5, BlendMode::Normal)]), "the faded group's opacity applies once"); + let half = |s: &Chain| !s.is_empty(); + assert!(faces.iter().any(|(_, s)| half(s)) && faces.iter().any(|(_, s)| !half(s))); + assert_eq!(groups(&art, &|n| n.opacity == 0.5), runs(&faces, &half), "the faded group's members, together"); + } + + #[test] + fn a_3d_effect_on_a_groups_fill_is_refused() { + let mut group = Node::group(NodeId(9), vec![member(1, 0.0)]); + group.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into(); + for id in [REVOLVE, crate::EXTRUDE] { + assert!(crate::validate_three_d(&group, id, &json!({})).is_ok(), "{id} on the group itself"); + let refused = crate::validate_three_d_at(&group, id, &json!({}), Some((0, 0))).unwrap_err(); + assert!(refused.contains("on the group itself"), "{id}: {refused}"); + } + } + + #[test] + fn validation_measures_the_profile_after_the_geometry_effects_before_revolve() { + let roughen = crate::new_effect("distort.roughen", &json!({"size": 1, "detail": 100})).unwrap(); + let mut group = group_with(json!({}), vec![star(1)]); + assert!(validate_revolve(&group, &json!({})).is_ok()); + group.appearance.effects.insert(0, roughen.clone()); + assert!(validate_revolve(&group, &json!({})).is_err(), "the group's reshaped member"); + assert_eq!(revolve_art(&group), None); + let mut object = (*star(1)).clone(); + assert!(validate_revolve(&object, &json!({})).is_ok()); + object.appearance.effects.insert(0, roughen); + assert!(validate_revolve(&object, &json!({})).is_err(), "a reshaped object not yet revolved"); + } + + #[test] + fn validation_of_a_hidden_revolve_leaves_out_the_geometry_effects_after_it() { + let roughen = crate::new_effect("distort.roughen", &json!({"size": 1, "detail": 100})).unwrap(); + let mut hidden = crate::new_effect(REVOLVE, &json!({})).unwrap(); + hidden.visible = false; + let mut object = (*star(1)).clone(); + object.appearance.effects = vec![hidden.clone(), roughen.clone()]; + assert_eq!(validate_revolve(&object, &json!({})), Ok(()), "an object whose Revolve is shown again"); + let mut group = group_with(json!({}), vec![star(1)]); + group.appearance.effects = vec![hidden, roughen]; + assert_eq!(validate_revolve(&group, &json!({})), Ok(()), "a group whose Revolve is shown again"); + for n in [&mut object, &mut group] { + n.appearance.effects[0].visible = true; + assert!(revolve_art(n).is_some(), "shown, the Revolve draws"); + } + } + + #[test] + fn paint_copies_past_the_budget_are_refused_for_the_whole_group() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let painted = |id: u64, x: f64, stops: usize| { + let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect(); + let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut node = (*member(id, x)).clone(); + node.appearance = Appearance::basic(paint, Paint::None, 0.0).into(); + Arc::new(node) + }; + let plain = member(1, 0.0); + let NodeKind::Path { path: profile, .. } = &plain.kind else { panic!("a path") }; + let faces = vectorcraft_three_d::revolve(profile, profile.bounds().unwrap(), revolve_options(&json!({}))).unwrap().len(); + let stops = MAX_PAINT_COPIES * 6 / 10 / (faces * 4) / std::mem::size_of::(); + let one = group_with(json!({}), vec![painted(1, 0.0, stops)]); + assert_eq!(validate_revolve(&one, &json!({})), Ok(())); + let two = group_with(json!({}), vec![painted(1, 0.0, stops), painted(2, 20.0, stops)]); + let refused = validate_revolve(&two, &json!({})).unwrap_err(); + assert!(refused.contains("simplify the gradient"), "{refused}"); + assert_eq!(revolve_art(&two), None, "past the budget the source draws"); + let object = painted(3, 0.0, stops * 2); + assert!(validate_revolve(&object, &json!({})).is_err(), "one object past the budget"); + } + + #[test] + fn the_art_of_symbol_instances_and_blends_shares_the_budget_of_paint_copies() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + use vectorcraft_doc::{BlendSpacing, BlendSpec, Symbol}; + let plain = member(1, 0.0); + let NodeKind::Path { path: profile, .. } = &plain.kind else { panic!("a path") }; + let faces = vectorcraft_three_d::revolve(profile, profile.bounds().unwrap(), revolve_options(&json!({}))).unwrap().len(); + let stops = MAX_PAINT_COPIES * 6 / 10 / (faces * 4) / std::mem::size_of::(); + let painted = |id: u64, x: f64| { + let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect(); + let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut node = (*member(id, x)).clone(); + node.appearance = Appearance::basic(paint, Paint::None, 0.0).into(); + Arc::new(node) + }; + let mut d = Document::new(500.0, 500.0); + d.symbols.push(Symbol { dynamic: false, name: "P".into(), art: painted(0, 0.0) }); + let instance = |id: u64| Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "P".into(), xf: Affine::IDENTITY })); + // One instance's art fits; two in the same place, each of whose surfaces fits alone, pass + // the budget together, as two paths would. + assert_eq!(validate_revolve_in(Some(&d), &group_with(json!({}), vec![instance(1)]), &json!({})), Ok(())); + let two = group_with(json!({}), vec![instance(1), instance(2)]); + let refused = validate_revolve_in(Some(&d), &two, &json!({})).unwrap_err(); + assert!(refused.contains("simplify the gradient"), "{refused}"); + assert_eq!(revolve_art_in(Some(&d), &two), None, "past the budget the source draws"); + // A blend's keys and step count together too. + let spec = Box::new(BlendSpec { spacing: BlendSpacing::Steps(1), ..Default::default() }); + let blend = Arc::new(Node::new(NodeId(3), NodeKind::Blend { children: vec![painted(4, 0.0), painted(5, 0.0)], spec })); + let refused = validate_revolve_in(Some(&d), &group_with(json!({}), vec![blend]), &json!({})).unwrap_err(); + assert!(refused.contains("simplify the gradient"), "{refused}"); + } + + #[test] + fn the_fills_of_one_object_share_the_budget_of_paint_copies() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let source = profile_node(); + let NodeKind::Path { path: profile, .. } = &source.kind else { panic!("a path") }; + let faces = vectorcraft_three_d::revolve(profile, profile.bounds().unwrap(), revolve_options(&json!({}))).unwrap().len(); + let stops = MAX_PAINT_COPIES * 6 / 10 / (faces * 4) / std::mem::size_of::(); + let fill = |stops: usize, revolved: bool| { + let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect(); + let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut item = AppearanceItem::Fill(FillLayer::new(paint)); + if revolved { + item.effects_mut().push(fx()); + } + item + }; + let with = |items: Vec| { + let mut n = source.clone(); + n.appearance = Appearance { items, ..Default::default() }.into(); + n + }; + let one = with(vec![fill(stops, true)]); + assert!(revolve_art(&one).is_some()); + assert_eq!(validate_item_revolve(&one, &json!({}), 0, 0), Ok(())); + let two = with(vec![fill(stops, true), fill(stops, true)]); + assert_eq!(revolve_art(&two), None, "past the budget the source draws"); + let refused = validate_item_revolve(&two, &json!({}), 1, 0).unwrap_err(); + assert!(refused.contains("simplify the gradient"), "{refused}"); + let second = with(vec![fill(stops, true), fill(stops, false)]); + assert!(validate_item_revolve(&second, &json!({}), 1, 0).is_err(), "the item the effect goes on counts"); + assert_eq!(validate_item_revolve(&second, &json!({}), 0, 0), Ok(()), "an item without a Revolve does not"); + let below = with(vec![fill(stops * 2, false), fill(1, false)]); + assert!(validate_item_revolve(&below, &json!({}), 0, 0).is_err(), "the item's own paint, not the top fill"); + assert_eq!(validate_item_revolve(&below, &json!({}), 1, 0), Ok(())); + } + + #[test] + fn an_items_revolve_is_validated_after_only_the_geometry_effects_before_it() { + let roughen = crate::new_effect("distort.roughen", &json!({"size": 1, "detail": 100})).unwrap(); + let mut object = (*star(1)).clone(); + let mut hidden = fx(); + hidden.visible = false; + let item = object.appearance.items.first_mut().unwrap(); + item.effects_mut().push(hidden); + item.effects_mut().push(roughen); + assert_eq!(validate_item_revolve(&object, &json!({}), 0, 0), Ok(()), "the roughen after it is not swept"); + assert!(validate_item_revolve(&object, &json!({}), 0, 2).is_err(), "a Revolve added after the roughen"); + } + #[test] fn transparency_unknown_paints_and_later_distortion_keep_complete_surfaces() { let mut n = profile_node(); diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 3390cc71fa..4ac4628b17 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{BlendMode, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeKind, StrokeLayer}; use vectorcraft_geom::{FillRule, PathData, Rect}; use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View}; @@ -17,6 +17,9 @@ use crate::{GeomContext, apply_geometry_with, is_geometry}; mod classic; pub use classic::{CLASSIC_EXTRUDE, SHADING_COLORS, classic_extrude_options, classic_shading}; +mod source; +pub(crate) use source::{resolve, resolve_for}; + pub const EXTRUDE: &str = "threeD.extrude"; pub const INFLATE: &str = "threeD.inflate"; pub const ROTATE: &str = "threeD.rotate"; @@ -138,7 +141,7 @@ pub fn inflate_options(p: &Value) -> Inflate { } /// The shape a solid is made from: a path's or a compound path's outline. -fn profile(n: &Node) -> Option<(PathData, FillRule)> { +pub(crate) fn profile(n: &Node) -> Option<(PathData, FillRule)> { match &n.kind { NodeKind::Path { path, rule, guide: false, clipping: false, .. } => Some((path.clone(), *rule)), NodeKind::Compound { children, rule } => { @@ -156,7 +159,7 @@ fn profile(n: &Node) -> Option<(PathData, FillRule)> { /// What a 3D effect paints `n` with: its own fills and strokes, else, for type that has none, the /// fill and stroke of its first painted run (its characters' colours). -fn solid_paints(n: &Node) -> Vec { +pub(crate) fn solid_paints(n: &Node) -> Vec { let own: Vec = n.appearance.items.iter().filter(|i| crate::paints(i)).cloned().collect(); if !own.is_empty() || !matches!(n.kind, NodeKind::Text(_)) { return own; @@ -198,38 +201,72 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { Ok(()) } +/// The name an error gives 3D effect `id`. +pub(crate) fn label_of(id: &str) -> &'static str { + crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…')) +} + /// Validate before a command changes the document; the evaluator bounds loaded files too. pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { + validate_solid_in(None, n, id, p) +} + +/// [`validate_solid`] with the symbols of `doc`: a symbol instance, a blend and a clipping group +/// build from the art they show ([`resolve`]). +pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { validate_solid_params(id, p)?; - let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…')); + let label = label_of(id); + let n = &*source::resolve_for(doc, n, label, id == ROTATE)?; if is_container(n) { let shapes = members(n, label)?; let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; return shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ())); } - let (path, rule) = profile(n).ok_or_else(|| { - format!("{label} currently requires a path, compound path, type or group. Convert images and other objects to paths first.") - })?; + let (path, rule) = object_profile(n, label)?; let b = path.bounds().ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; facets(id, &path, rule, b, p).map(|_| ()) } +/// [`profile`], or the error a command reports for object `n`: type with no outlines to build from +/// (empty, or only spaces) is a shape without anchors, an image is traced first, and any other +/// object is the wrong kind. +pub(crate) fn object_profile(n: &Node, label: &str) -> Result<(PathData, FillRule), String> { + profile(n).ok_or_else(|| match n.kind { + NodeKind::Text(_) => format!("{label} requires a shape with at least two anchors"), + NodeKind::Image(_) => source::image_refusal(label), + _ => format!("{label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first."), + }) +} + +/// A group in a 3D effect's group, or a member of it, whose opacity is below 100% or whose blending +/// mode is not Normal. The members of one group share its `key`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Scope { + pub(crate) key: usize, + pub(crate) opacity: f32, + pub(crate) blend: BlendMode, +} + /// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint -/// it, and the opacity of the objects it is in (1 for the object with the effect itself). -struct Profile { - path: PathData, - rule: FillRule, - items: Vec, - opacity: f32, +/// it, and the opacity of the objects it is in multiplied together (1 for the object with the +/// effect itself). `scopes` lists those objects with transparency of their own ([`Scope`]), from +/// the outermost group down to the member itself (none for the object itself). Group Revolve +/// applies each once, to the surfaces of the members it holds together. +pub(crate) struct Profile { + pub(crate) path: PathData, + pub(crate) rule: FillRule, + pub(crate) items: Vec, + pub(crate) opacity: f32, + pub(crate) scopes: Vec, } /// Is `n` a group or layer (a 3D effect on it turns its members about one shared axis)? -fn is_container(n: &Node) -> bool { +pub(crate) fn is_container(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. }) } /// The bounds of every shape together: the centre a group's members turn about. -fn union_bounds(shapes: &[Profile]) -> Option { +pub(crate) fn union_bounds(shapes: &[Profile]) -> Option { shapes.iter().filter_map(|s| s.path.bounds()).reduce(|a, c| a.union(c)) } @@ -241,51 +278,95 @@ const MAX_MEMBERS: usize = 4096; const MAX_MESH_TRIANGLES: usize = 2_000_000; /// The shapes a 3D effect on group or layer `n` builds its solids from: every visible path, -/// compound path and type in it, at any depth of its groups, each through its own geometry -/// effects and painted with its own fills and strokes. Like the effect on a group in the +/// compound path and type in it (after [`resolve`] gives it the art of its symbol instances, blends +/// and clipping groups), at any depth of its groups, each through its own geometry +/// effects, then those of each group it is in (on that group's members together), and painted +/// with its own fills and strokes. Like the effect on a group in the /// reference app, they turn about one shared axis (the centre of their bounds together) rather /// than each about its own. An error names what the group holds that can't become a solid. -fn members(n: &Node, label: &str) -> Result, String> { - fn walk(n: &Node, opacity: f32, label: &str, out: &mut Vec) -> Result<(), String> { +pub(crate) fn members(n: &Node, label: &str) -> Result, String> { + struct Walk<'a> { + label: &'a str, + out: Vec, + keys: usize, + } + fn walk(n: &Node, opacity: f32, scopes: &[Scope], w: &mut Walk) -> Result<(), String> { + let label = w.label; for c in n.children().into_iter().flatten() { if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) { continue; } let opacity = opacity * c.opacity; + let mut scopes = scopes.to_vec(); + if c.blend != BlendMode::Normal || c.opacity < 1.0 { + w.keys += 1; + scopes.push(Scope { key: w.keys, opacity: c.opacity, blend: c.blend }); + } if is_container(c) { - walk(c, opacity, label, out)?; + let first = w.out.len(); + walk(c, opacity, &scopes, w)?; + // The group's own geometry effects reshape its members together, as it is drawn. + if let Some(shapes) = w.out.get_mut(first..) { + reshape_members(c, &c.appearance.effects, shapes); + } continue; } let Some((path, rule)) = profile(c) else { let what = match &c.kind { - NodeKind::Group { clip: true, .. } => "clipping groups", - NodeKind::Image(_) => "images", - NodeKind::SymbolInstance { .. } => "symbol instances", + NodeKind::Image(_) => return Err(source::image_refusal(label)), NodeKind::Path { clipping: true, .. } => "clipping paths", - _ => "objects other than paths, compound paths and type", + _ => "other objects", }; - return Err(format!("{label} on a group needs paths, compound paths and type: release or expand its {what} first.")); + return Err(format!( + "{label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first." + )); }; - if out.len() >= MAX_MEMBERS { + if w.out.len() >= MAX_MEMBERS { return Err(format!("{label} on a group takes at most {MAX_MEMBERS} objects")); } let path = geometry(&path, &c.appearance.effects, &GeomContext::of(c)); if path.bounds().is_some() { - out.push(Profile { path, rule, items: solid_paints(c), opacity }); + w.out.push(Profile { path, rule, items: solid_paints(c), opacity, scopes }); } } Ok(()) } - let mut out = vec![]; - walk(n, 1.0, label, &mut out)?; - Ok(out) + let mut w = Walk { label, out: vec![], keys: 0 }; + walk(n, 1.0, &[], &mut w)?; + Ok(w.out) } /// Can 3D effect `id` (Revolve included, [`is_three_d`]) with parameters `p` draw `n`? Checked /// before a command changes the document: Revolve by [`crate::validate_revolve`], the others by /// [`validate_solid`]. pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> { - if id == crate::REVOLVE { crate::validate_revolve(n, p) } else { validate_solid(n, id, p) } + validate_three_d_in(None, n, id, p) +} + +/// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]). +pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { + if id == crate::REVOLVE { crate::revolve::validate_revolve_in(doc, n, p) } else { validate_solid_in(doc, n, id, p) } +} + +/// [`validate_three_d`] for an effect at `(item, index)`, index `index` of the effects of +/// appearance item `item` of `n` (the effects' length for a new effect), or on the object itself +/// when `at` is `None`. A Revolve on a fill or stroke is checked in that item's paint, after the +/// item's geometry effects before it, together with the object's other items that carry a Revolve. +/// A group's or layer's fills and strokes take no 3D effect: only the group's own effect draws. +pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> { + validate_three_d_at_in(None, n, id, p, at) +} + +/// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a +/// blend and a clipping group take a 3D effect as groups do: on the object itself. +pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> { + match at { + Some(_) if is_container(n) || source::resolves(n) => { + Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()) + } + Some((item, index)) if id == crate::REVOLVE => crate::revolve::validate_item_revolve(n, p, item, index), + _ => validate_three_d_in(doc, n, id, p), + } } /// Are 3D effect `id`'s parameter values `p` valid? The checks of [`validate_three_d`] that do not @@ -385,7 +466,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<(&AppearanceItem, f32 /// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before` /// its 3D effect, about the bounds of all of them. -fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) { +pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) { if before.iter().any(|e| e.visible && is_geometry(&e.id)) && let Some(b) = union_bounds(shapes) { @@ -488,9 +569,17 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { /// On a group or layer the effect builds a solid from each path, compound path and type in it, /// all turned about one shared axis ([`members`]). pub fn solid_art(n: &Node) -> Option { + solid_art_in(None, n) +} + +/// [`solid_art`] with the symbols of `doc`: a symbol instance, a blend and a clipping group, alone +/// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be +/// resolved. +pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { if !has_solid(n) { return None; } + let n = &*resolve(doc, n, "").ok()?; if is_container(n) { return group_solid_art(n); } @@ -501,7 +590,7 @@ pub fn solid_art(n: &Node) -> Option { let remaining: Vec; if let Some((index, fx)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - children.extend(art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0 }])?); + children.extend(art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?); // Later geometry effects act on the projected art as a whole. remaining = n .appearance @@ -517,7 +606,7 @@ pub fn solid_art(n: &Node) -> Option { for item in &paints { if let Some((index, fx)) = solid(item.effects()) { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item)); - for mut art in art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0 }])? { + for mut art in art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])? { Arc::make_mut(&mut art).appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); children.push(art); @@ -642,28 +731,44 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) /// such effect, its solids can't be built, none has a triangle, or together they have more than /// [`MAX_MESH_TRIANGLES`]. pub fn three_d_meshes(n: &Node) -> Result, String> { - meshes_within(n, &mut 0, MAX_MESH_TRIANGLES) + three_d_meshes_in(None, n) +} + +/// [`three_d_meshes`] with the symbols of `doc`: a symbol instance, a blend and a clipping group +/// build from the art they show ([`resolve`]). +pub fn three_d_meshes_in(doc: Option<&Document>, n: &Node) -> Result, String> { + meshes_within(doc, n, &mut 0, MAX_MESH_TRIANGLES) } /// The meshes of every object in `nodes` ([`three_d_meshes`]), in order, as one 3D asset exports /// them: the objects share one budget of [`MAX_MESH_TRIANGLES`]. pub fn three_d_meshes_of<'a>(nodes: impl IntoIterator) -> Result, String> { - meshes_of_within(nodes, MAX_MESH_TRIANGLES) + three_d_meshes_of_in(None, nodes) } -/// [`three_d_meshes_of`] with a budget of `limit` triangles. -fn meshes_of_within<'a>(nodes: impl IntoIterator, limit: usize) -> Result, String> { +/// [`three_d_meshes_of`] with the symbols of `doc` ([`three_d_meshes_in`]). +pub fn three_d_meshes_of_in<'a>(doc: Option<&Document>, nodes: impl IntoIterator) -> Result, String> { + meshes_of_within(doc, nodes, MAX_MESH_TRIANGLES) +} + +/// [`three_d_meshes_of_in`] with a budget of `limit` triangles. +fn meshes_of_within<'a>(doc: Option<&Document>, nodes: impl IntoIterator, limit: usize) -> Result, String> { let mut total = 0usize; let mut out = vec![]; for n in nodes { - out.extend(meshes_within(n, &mut total, limit)?); + out.extend(meshes_within(doc, n, &mut total, limit)?); } Ok(out) } -/// [`three_d_meshes`], with the triangles of every solid added to `total` as it is built and an +/// [`three_d_meshes_in`], with the triangles of every solid added to `total` as it is built and an /// error as soon as `total` passes `limit`. -fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result, String> { +fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usize) -> Result, String> { + if !crate::has_revolve(n) && !has_solid(n) { + return Err("the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)".into()); + } + let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id)); + let n = &*resolve(doc, n, label)?; let meshes = if crate::has_revolve(n) { crate::revolve::revolve_meshes(n, total, limit)? } else if !has_solid(n) { @@ -675,19 +780,19 @@ fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result String { + format!("{label} can't build a solid from an image: trace it first with Object › Image Trace › Make.") +} + +/// Is `n` a symbol instance, a blend or a clipping group or layer? +pub(crate) fn resolves(n: &Node) -> bool { + matches!(n.kind, NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. }) || n.clips() +} + +/// Is `n`, or a visible member of `n` at any depth of its groups and layers, one [`resolves`] takes? +fn needs(n: &Node) -> bool { + let mut stack = vec![n]; + while let Some(n) = stack.pop() { + if resolves(n) { + return true; + } + if is_container(n) { + stack.extend(kids(n).iter().filter(|c| c.visible).map(|c| &**c)); + } + } + false +} + +/// `n` as a 3D effect builds from it: unchanged when neither it nor a visible member of its groups +/// is a symbol instance, a blend or a clipping group, otherwise a group with `n`'s id, appearance +/// and transparency holding that art (a symbol instance's symbol art from `doc`). An error names +/// what can't be resolved: an image, a missing symbol, art nested or numbering past the limits, or +/// a clipping path too complex to cut the art with. `label` is the effect's name. The art is cut +/// for the solid effect `n` carries ([`resolve_for`]). +pub(crate) fn resolve<'a>(doc: Option<&Document>, n: &'a Node, label: &str) -> Result, String> { + let every_fill = super::solid(&n.appearance.effects).is_some_and(|(_, fx)| fx.id == super::ROTATE); + resolve_for(doc, n, label, every_fill) +} + +/// [`resolve`] for the 3D effect that builds from `n`: `every_fill` for Rotate, which turns every +/// fill, so each fill a clipping path cuts keeps its own place among the strokes. Otherwise the +/// effect builds from the top fill, and the fills cut go together in the top fill's place. +pub(crate) fn resolve_for<'a>(doc: Option<&Document>, n: &'a Node, label: &str, every_fill: bool) -> Result, String> { + if !needs(n) { + return Ok(Cow::Borrowed(n)); + } + let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, shown: None }; + let children = r.content(n, 0); + #[cfg(test)] + WORK.with(|w| w.set(r.work)); + let mut out = n.clone(); + out.kind = NodeKind::Group { children: children?, clip: false }; + Ok(Cow::Owned(out)) +} + +#[cfg(test)] +thread_local! { + /// The objects the last [`resolve`] on this thread visited or made ([`Resolver::work`]). + pub(super) static WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +struct Resolver<'a> { + doc: Option<&'a Document>, + label: &'a str, + /// Does each fill a clipping path cuts become a piece of its own ([`resolve_for`])? + every_fill: bool, + /// The objects other than groups and layers kept so far, counted against [`MAX_MEMBERS`]. + leaves: usize, + /// The objects visited or made so far, counted against [`MAX_WORK`]. + work: usize, + /// Inside clipping groups, the box of what their clipping paths show together. + shown: Option, +} + +impl Resolver<'_> { + /// Count `steps` more objects visited or made, or an error past [`MAX_WORK`]. + fn spend(&mut self, steps: usize) -> Result<(), String> { + self.work = self.work.saturating_add(steps); + if self.work > MAX_WORK { + return Err(self.too_much_work()); + } + Ok(()) + } + + fn too_much_work(&self) -> String { + format!("{} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects", self.label) + } + + /// `f` run on the art of `c`. The effects of an object or group can move its art into a clip, + /// so inside one with effects no image is left out for lying outside the clip ([`Self::shown`]). + fn inside(&mut self, c: &Node, f: impl FnOnce(&mut Self) -> Result) -> Result { + let outer = self.shown; + if has_effects(c) { + self.shown = None; + } + let out = f(self); + self.shown = outer; + out + } + + /// The art `n`, a symbol instance, a blend, a clipping group or layer, or a group holding one, + /// shows, as the members of a plain group. + fn content(&mut self, n: &Node, depth: usize) -> Result>, String> { + let label = self.label; + if depth > MAX_DEPTH { + return Err(self.too_deep()); + } + self.spend(1)?; + match &n.kind { + NodeKind::SymbolInstance { symbol, xf } => { + let missing = || format!("{label} can't build a solid from the instance of symbol \"{symbol}\": the symbol's art isn't available"); + let doc = self.doc.ok_or_else(missing)?; + let sym = doc.symbols.iter().find(|s| s.name == *symbol).ok_or_else(missing)?; + // Counted before the art is placed, so a symbol past the limit is never copied: + // first its own objects, which the instance's overrides keep, then the most + // objects placing makes, with those overrides and the symbol's 9-slice guides. + if self.work.saturating_add(sym.art.count_with_masks()) > MAX_WORK { + return Err(self.too_much_work()); + } + let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); + let most = doc.symbol_slice_map(symbol, *xf).map_or(art.count_with_masks() as u64, |m| m.most_placed(&art, doc)); + if (self.work as u64).saturating_add(most) > MAX_WORK as u64 { + return Err(self.too_much_work()); + } + let placed = doc.place_symbol_art(symbol, &art, *xf).ok_or_else(missing)?; + Ok(self.list(&[Arc::new(placed)], depth + 1)?.0) + } + NodeKind::Blend { children, spec } => { + // Counted before the steps are made, so a blend past the limit is never expanded. + let made = vectorcraft_doc::blend::blend_steps(children, spec).into_iter().fold(children.len(), usize::saturating_add); + if self.leaves.saturating_add(made) > MAX_MEMBERS { + return Err(self.too_many()); + } + self.spend(made)?; + let steps: Vec> = crate::expand_live(self.doc, n).into_iter().map(Arc::new).collect(); + Ok(self.list(&steps, depth + 1)?.0) + } + _ if n.clips() => { + let Some((first, rest)) = kids(n).split_first() else { return Ok(vec![]) }; + if clip_nested_past(first, MAX_DEPTH.saturating_sub(depth)) { + return Err(self.too_deep()); + } + let clip = clip_area(first); + // An image wholly outside every clip around it shows nothing and is left out. + let outer = self.shown; + let here = clip.0.bounds().unwrap_or(Rect::ZERO); + self.shown = Some(outer.map_or(here, |o| o.intersect(here))); + let listed = self.list(rest, depth + 1); + self.shown = outer; + let (inner, _) = listed?; + let mut out = vec![]; + for c in &inner { + if let Some(c) = self.clipped(c, &clip, depth + 1)? { + out.push(Arc::new(c)); + } + } + Ok(out) + } + _ => Ok(self.list(kids(n), depth + 1)?.0), + } + } + + /// The visible members of `children` as plain art: images refused, guides left out, symbol + /// instances, blends and clipping groups resolved into groups with their transparency and + /// geometry effects, groups holding them rebuilt. Also whether any member changed: a group + /// whose members did not is kept as it is. Each object is visited once. + fn list(&mut self, children: &[Arc], depth: usize) -> Result<(Vec>, bool), String> { + let mut out = Vec::with_capacity(children.len()); + let mut changed = false; + for c in children { + self.spend(1)?; + if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) { + continue; + } + if matches!(c.kind, NodeKind::Image(_)) { + // Only an image with no effects or fills and strokes of its own is measured by its + // frame; any other one may draw inside the clip. + let plain = !has_effects(c) && c.appearance.items.iter().all(|i| !i.visible()); + let hidden = plain && self.shown.is_some_and(|k| c.visual_bounds().is_none_or(|b| b.intersect(k).area() <= 0.0)); + if hidden { + changed = true; + continue; + } + return Err(image_refusal(self.label)); + } + if resolves(c) { + let kids = self.inside(c, |r| r.content(c, depth))?; + out.push(Arc::new(with_effects(wrap(c, kids), c))); + changed = true; + continue; + } + if is_container(c) { + // At the depth limit a group is kept, and not walked further, only when it holds no + // group with members and nothing in it needs resolving. + if depth >= MAX_DEPTH { + if nested_past(c, 1) || needs(c) { + return Err(self.too_deep()); + } + out.push(c.clone()); + continue; + } + let (kids, inner) = self.inside(c, |r| r.list(kids(c), depth + 1))?; + if inner { + out.push(Arc::new(with_effects(wrap(c, kids), c))); + changed = true; + } else { + out.push(c.clone()); + } + continue; + } + self.leaves += 1; + if self.leaves > MAX_MEMBERS { + return Err(self.too_many()); + } + out.push(c.clone()); + } + Ok((out, changed)) + } + + fn too_complex(&self) -> String { + format!("{}: the clipping path is too complex to cut the art with", self.label) + } + + fn too_many(&self) -> String { + format!("{} takes at most {MAX_MEMBERS} objects", self.label) + } + + fn too_deep(&self) -> String { + format!("{} can't build solids from art nested more than {MAX_DEPTH} levels deep", self.label) + } + + /// `n`, plain art inside a clipping group, cut to `clip`: each shape's fills as its area inside + /// the clip and each stroke as the part of its outline inside it, filled in the stroke's paint, + /// after the geometry effects of the shape and of the groups it is in; hidden objects and guides + /// left out. `None` when nothing of it is inside. Objects that build no solid stay as they are. + fn clipped(&mut self, n: &Node, clip: &(PathData, FillRule), depth: usize) -> Result, String> { + if depth > MAX_DEPTH { + return Err(self.too_deep()); + } + self.spend(1)?; + if is_container(n) { + let mut kids = vec![]; + if n.appearance.effects.iter().any(|e| e.visible && is_geometry(&e.id)) { + // The group's geometry effects reshape its members together before the clip cuts + // them, as they are drawn: each member becomes its reshaped outline. + if nested_past(n, MAX_DEPTH.saturating_sub(depth)) { + return Err(self.too_deep()); + } + let mut shapes = members(n, self.label)?; + reshape_members(n, &n.appearance.effects, &mut shapes); + let mut cut = vec![]; + for s in shapes { + if let Some(c) = self.clipped(&shape(n, s.path, s.rule, s.items), clip, depth + 1)? { + cut.push((s.scopes, c)); + } + } + kids = nest(n, cut, 0); + } else { + for c in n.children().into_iter().flatten() { + if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) { + continue; + } + if let Some(c) = self.clipped(c, clip, depth + 1)? { + kids.push(Arc::new(c)); + } + } + } + return Ok((!kids.is_empty()).then(|| wrap(n, kids))); + } + let Some((path, rule)) = profile(n) else { return Ok(Some(n.clone())) }; + let items = solid_paints(n); + // The fills' piece goes where the top fill is, the one Extrude & Bevel and Inflate build + // their solid from, so the strokes above and below it keep their places. Rotate turns + // every fill, so each fill is a piece in its own place. + let top_fill = items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_))); + let fill_pieces = + if self.every_fill { items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count() } else { usize::from(top_fill.is_some()) }; + // Each cut makes a piece, counted before it is made: the shape was counted once already. + let made = fill_pieces + items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count(); + self.spend(made)?; + self.leaves = self.leaves.saturating_add(made.saturating_sub(1)); + if self.leaves > MAX_MEMBERS { + return Err(self.too_many()); + } + let path = geometry(&path, &n.appearance.effects, &GeomContext::of(n)); + let cut = |area: &PathData, rule: FillRule| -> Result, String> { + let inside = + po::try_boolean(area, rule, &clip.0, clip.1, po::BoolOp::Intersect, po::DEFAULT_PRECISION).map_err(|_| self.too_complex())?; + Ok(inside.bounds().is_some().then_some(inside)) + }; + let fills: Vec = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).cloned().collect(); + // Every fill paints the same area: it is cut once. + let mut fill_area: Option> = None; + let mut pieces = vec![]; + for (k, item) in items.iter().enumerate() { + match item { + AppearanceItem::Fill(_) if self.every_fill || Some(k) == top_fill => { + let area = match &fill_area { + Some(area) => area.clone(), + None => fill_area.insert(cut(&path, rule)?).clone(), + }; + if let Some(area) = area { + let painted = if self.every_fill { vec![item.clone()] } else { fills.clone() }; + pieces.push(Arc::new(shape(n, area, FillRule::NonZero, painted))); + } + } + AppearanceItem::Fill(_) => {} + AppearanceItem::Stroke(s) => { + let (outline, outline_rule) = region(&path, rule, item); + if let Some(area) = cut(&outline, outline_rule)? { + let mut fill = FillLayer::new(s.paint.clone()); + fill.opacity = s.opacity; + fill.blend = s.blend; + pieces.push(Arc::new(shape(n, area, FillRule::NonZero, vec![AppearanceItem::Fill(fill)]))); + } + } + } + } + Ok((!pieces.is_empty()).then(|| wrap(n, pieces))) + } +} + +/// The area clipping path `first` keeps, as the renderer clips by it ([`crate::clip_outline`]): a +/// nested clipping group's own clipping path, the union of a group's members. Empty when it keeps +/// nothing. +fn clip_area(first: &Node) -> (PathData, FillRule) { + crate::clip_outline(first).map_or_else(|| (PathData::default(), FillRule::NonZero), |(bp, rule)| (PathData::from_bezpath(&bp), rule)) +} + +/// `pieces`, each with the [`Scope`]s of the groups it was in, back in groups of `n`'s id with +/// those groups' opacity and blending mode: consecutive pieces sharing the scope at `level` go into +/// one group, so its transparency applies to them together. `level` stays below the nesting the +/// pieces came from ([`nested_past`]). +fn nest(n: &Node, pieces: Vec<(Vec, Node)>, level: usize) -> Vec> { + let mut out = vec![]; + let mut run: Vec<(Vec, Node)> = vec![]; + let mut key = None; + let close = |run: &mut Vec<(Vec, Node)>, scope: Option, out: &mut Vec>| { + let Some(scope) = scope else { return }; + let mut g = Node::group(n.id, nest(n, std::mem::take(run), level + 1)); + g.opacity = scope.opacity; + g.blend = scope.blend; + out.push(Arc::new(g)); + }; + for (scopes, piece) in pieces { + let here = scopes.get(level).copied(); + if here.map(|s| s.key) != key.map(|s: Scope| s.key) { + close(&mut run, key, &mut out); + key = here; + } + match here { + Some(_) => run.push((scopes, piece)), + None => out.push(Arc::new(piece)), + } + } + close(&mut run, key, &mut out); + out +} + +/// Does `n` carry a visible effect? +fn has_effects(n: &Node) -> bool { + n.appearance.effects.iter().any(|e| e.visible) +} + +/// Does the group `n` hold shown objects nested more than `levels` deep in groups and layers? +/// Only the members [`members`] walks are followed: hidden members are skipped, and the paths of +/// a compound path are one shape. Walked without recursion. +fn nested_past(n: &Node, levels: usize) -> bool { + let mut stack = vec![(n, 0usize)]; + while let Some((n, level)) = stack.pop() { + if level > levels { + return true; + } + if level == 0 || is_container(n) { + stack.extend(kids(n).iter().filter(|c| c.visible).map(|c| (&**c, level + 1))); + } + } + false +} + +/// Does the clipping path `n` reach objects nested more than `levels` deep along the members that +/// [`Node::clip_shapes`] visits: the first member of a clipping group, the shown members of other +/// groups and layers (not a group's shaper), and every member of a live object. Walked without +/// recursion. +fn clip_nested_past(n: &Node, levels: usize) -> bool { + let mut stack = vec![(n, 0usize)]; + while let Some((n, level)) = stack.pop() { + if level > levels { + return true; + } + match &n.kind { + NodeKind::Group { children, clip: true } => stack.extend(children.first().map(|c| (&**c, level + 1))), + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + let skip = usize::from(n.extras().shaper.is_some()); + stack.extend(children.iter().skip(skip).filter(|c| c.visible).map(|c| (&**c, level + 1))); + } + NodeKind::Compound { .. } | NodeKind::SymbolInstance { .. } => {} + _ => stack.extend(kids(n).iter().map(|c| (&**c, level + 1))), + } + } + false +} + +/// The members of `n`, none for an object without members. +fn kids(n: &Node) -> &[Arc] { + n.children().map_or(&[], Vec::as_slice) +} + +/// A path of `n`'s id on `path`, painted by `items` under `rule`. +fn shape(n: &Node, path: PathData, rule: FillRule, items: Vec) -> Node { + let mut piece = Node::path(n.id, path, Appearance { items, ..Default::default() }); + if let NodeKind::Path { rule: r, .. } = &mut piece.kind { + *r = rule; + } + piece +} + +/// A plain group of `children` with `n`'s id, visibility, opacity and blending mode. +fn wrap(n: &Node, children: Vec>) -> Node { + let mut g = Node::group(n.id, children); + g.name = n.name.clone(); + g.opacity = n.opacity; + g.blend = n.blend; + g +} + +/// `g`, the group `n` was resolved into, with `n`'s appearance: a 3D effect's group reshapes its +/// members with its geometry effects ([`members`]), which read its stroke as they do when `n` is +/// drawn. A group's own fills and strokes build no solid. +fn with_effects(mut g: Node, n: &Node) -> Node { + g.appearance = n.appearance.clone(); + g +} diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 29bbdb3bd2..7273a44b22 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -205,12 +205,12 @@ fn a_stroked_open_path_builds_a_ribbon() { /// still draws. #[test] fn a_stroke_past_the_limits_is_left_out() { - // 1,500 corners: within the 2,048 points of the fill's solid, but not the stroke's outline. - let points: Vec = (0..1500) + // 40,000 corners: within the 65,536 points of the fill's solid, but not the stroke's outline. + let points: Vec = (0..40_000) .map(|k| { - let (s, c) = (k as f64 * std::f64::consts::TAU / 1500.0).sin_cos(); - let r = if k % 2 == 0 { 100.0 } else { 96.0 }; - Point::new(200.0 + r * c, 200.0 + r * s) + let (s, c) = (k as f64 * std::f64::consts::TAU / 40_000.0).sin_cos(); + let r = if k % 2 == 0 { 10_000.0 } else { 9_999.0 }; + Point::new(20_000.0 + r * c, 20_000.0 + r * s) }) .collect(); let path = PathData::single(vectorcraft_geom::SubPath::polyline(&points, true)); @@ -591,13 +591,14 @@ fn a_3d_effect_on_a_group_turns_every_member_about_one_shared_axis() { // Hidden members and guides are left out; a group holding what can't become a solid is // refused with what to do. let mut g = group(EXTRUDE, json!({})); - let mut clip = Node::group(NodeId(5), vec![Arc::new(square_at(6, 0.0, RED))]); - clip.kind = NodeKind::Group { children: clip.children().unwrap().clone(), clip: true }; + let mut woven = Node::group(NodeId(5), vec![Arc::new(square_at(6, 0.0, RED))]); + woven.kind = NodeKind::Intertwine { children: woven.children().unwrap().clone() }; if let NodeKind::Group { children, .. } = &mut g.kind { - children.push(Arc::new(clip)); + children.push(Arc::new(woven)); } let err = validate_solid(&g, EXTRUDE, &json!({})).unwrap_err(); - assert!(err.contains("clipping groups"), "{err}"); + assert!(err.contains("release or expand its other objects"), "{err}"); + assert!(err.contains("type, groups, clipping groups, blends and symbol instances"), "{err}"); assert!(solid_art(&g).is_none(), "drawn as the group it is"); } diff --git a/crates/effects/src/solids/tests_mesh.rs b/crates/effects/src/solids/tests_mesh.rs index 70706e0682..1ae347c978 100644 --- a/crates/effects/src/solids/tests_mesh.rs +++ b/crates/effects/src/solids/tests_mesh.rs @@ -51,7 +51,7 @@ fn the_meshes_of_one_object_share_one_triangle_budget() { assert!(keep_mesh(&mut out, &mut total, meshes[1].clone(), first).is_err()); assert_eq!(out.len(), 1); // Building past the budget stops with an error instead of holding every mesh. - let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0 }]; + let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }]; let Some(effect) = n.appearance.effects.first() else { panic!("no effect") }; let mut total = 0; assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_ok()); @@ -79,7 +79,7 @@ fn revolve_stops_at_the_first_mesh_past_the_budget() { assert!(whole.as_ref().is_err_and(|e| !e.contains("to export")), "the stroke's own error: {whole:?}"); // With room for less than the fill's mesh, the stroke's is never built. let mut total = 0; - let capped = meshes_within(&n, &mut total, triangles - 1); + let capped = meshes_within(None, &n, &mut total, triangles - 1); assert!(capped.as_ref().is_err_and(|e| e.contains("too complex to export")), "{capped:?}"); assert_eq!(total, triangles); } @@ -92,10 +92,10 @@ fn the_objects_of_one_asset_share_one_triangle_budget() { b.appearance.effects.push(fx(EXTRUDE, json!({}))); let triangles = |n: &Node| three_d_meshes(n).unwrap().iter().map(|m| m.mesh.triangles.len()).sum::(); let (ta, tb) = (triangles(&a), triangles(&b)); - assert!(meshes_of_within([&a], ta).is_ok()); - assert!(meshes_of_within([&b], tb).is_ok()); - assert!(meshes_of_within([&a, &b], ta.max(tb)).is_err_and(|e| e.contains("too complex to export"))); - assert_eq!(meshes_of_within([&a, &b], ta + tb).map(|m| m.len()), Ok(4)); + assert!(meshes_of_within(None, [&a], ta).is_ok()); + assert!(meshes_of_within(None, [&b], tb).is_ok()); + assert!(meshes_of_within(None, [&a, &b], ta.max(tb)).is_err_and(|e| e.contains("too complex to export"))); + assert_eq!(meshes_of_within(None, [&a, &b], ta + tb).map(|m| m.len()), Ok(4)); assert_eq!(three_d_meshes_of([&a, &b]).map(|m| m.len()), Ok(4)); } diff --git a/crates/effects/src/solids/tests_sources.rs b/crates/effects/src/solids/tests_sources.rs new file mode 100644 index 0000000000..4957f88fa4 --- /dev/null +++ b/crates/effects/src/solids/tests_sources.rs @@ -0,0 +1,535 @@ +use serde_json::json; +use vectorcraft_doc::color::Color; +use vectorcraft_doc::{AppearanceItem, BlendSpacing, BlendSpec, Document, FillLayer, ImageObject, NodeId, StrokeLayer, Symbol}; +use vectorcraft_geom::{Affine, shapes}; + +use super::*; + +const TYPES: [&str; 5] = [EXTRUDE, CLASSIC_EXTRUDE, INFLATE, ROTATE, crate::REVOLVE]; + +/// Rotate facing the viewer: the art drawn where it is. +fn front() -> Value { + json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}) +} + +fn rect(id: u64, x0: f64, y0: f64, x1: f64, y1: f64, stroke: f64) -> Node { + let path = shapes::rectangle(Rect::new(x0, y0, x1, y1)); + let stroke_paint = if stroke > 0.0 { Paint::solid(Color::BLACK) } else { Paint::None }; + Node::path(NodeId(id), path, Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), stroke_paint, stroke)) +} + +fn with(mut n: Node, id: &str, params: Value) -> Node { + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + n +} + +fn art(d: &Document, n: &Node, id: &str) -> Option { + if id == crate::REVOLVE { crate::revolve_art_in(Some(d), n) } else { solid_art_in(Some(d), n) } +} + +fn bounds(n: &Node) -> Rect { + n.visual_bounds().unwrap() +} + +fn close(a: Rect, b: Rect, tolerance: f64) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() <= tolerance) +} + +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(rect(0, 0.0, 0.0, 100.0, 100.0, 2.0)) }); + d +} + +/// A rectangular clipping path covering `clip`. +fn clipping_path(id: u64, clip: Rect) -> Node { + let mut path = Node::path(NodeId(id), shapes::rectangle(clip), Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut path.kind { + *clipping = true; + } + path +} + +/// A clipping group: `art` inside a rectangular clipping path covering `clip`. +fn clip_group(id: u64, clip: Rect, art: Node) -> Node { + Node::new(NodeId(id), NodeKind::Group { children: vec![Arc::new(clipping_path(id + 1, clip)), Arc::new(art)], clip: true }) +} + +fn blend(id: u64, steps: u32) -> Node { + let keys = vec![Arc::new(rect(id + 1, 100.0, 100.0, 140.0, 140.0, 0.0)), Arc::new(rect(id + 2, 300.0, 120.0, 360.0, 180.0, 0.0))]; + let spec = BlendSpec { spacing: BlendSpacing::Steps(steps), ..Default::default() }; + Node::new(NodeId(id), NodeKind::Blend { children: keys, spec: Box::new(spec) }) +} + +fn instance(id: u64, symbol: &str, xf: Affine) -> Node { + Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: symbol.into(), xf }) +} + +fn image(id: u64) -> Node { + Node::new( + NodeId(id), + NodeKind::Image(Box::new(ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + })), + ) +} + +fn sources() -> [(&'static str, Node); 3] { + [ + ("clipping group", clip_group(10, Rect::new(100.0, 100.0, 150.0, 200.0), rect(12, 100.0, 100.0, 200.0, 200.0, 2.0))), + ("blend", blend(20, 3)), + ("symbol instance", instance(30, "Box", Affine::translate((300.0, 0.0)))), + ] +} + +#[test] +fn every_three_d_type_builds_clipping_groups_blends_and_symbol_instances_alone_and_in_a_group() { + let d = document(); + for (what, source) in sources() { + for id in TYPES { + let n = with(source.clone(), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id} on a {what}"); + assert!(art(&d, &n, id).is_some_and(|a| a.visual_bounds().is_some()), "{id} on a {what} draws"); + assert!(three_d_meshes_in(Some(&d), &n).is_ok_and(|m| !m.is_empty()), "{id} on a {what} exports"); + let g = with(Node::group(NodeId(90), vec![Arc::new(source.clone()), Arc::new(rect(91, 600.0, 600.0, 650.0, 650.0, 0.0))]), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding a {what}"); + assert!(art(&d, &g, id).is_some(), "{id} on a group holding a {what} draws"); + assert!(three_d_meshes_in(Some(&d), &g).is_ok_and(|m| !m.is_empty()), "{id} on a group holding a {what} exports"); + } + } +} + +#[test] +fn a_clipping_groups_solid_is_built_from_its_art_inside_the_clip() { + let d = document(); + let clip = Rect::new(100.0, 100.0, 150.0, 200.0); + let fill_only = with(clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 0.0)), ROTATE, front()); + let cut = with(Node::group(NodeId(10), vec![Arc::new(rect(12, 100.0, 100.0, 150.0, 200.0, 0.0))]), ROTATE, front()); + assert!(close(bounds(&solid_art_in(Some(&d), &fill_only).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01)); + // The stroke is cut to the clip too: nothing reaches past it but the faces' seams. + let stroked = with(clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 8.0)), EXTRUDE, front()); + let b = bounds(&solid_art_in(Some(&d), &stroked).unwrap()); + let outside = b.x0 < clip.x0 - 1.0 || b.x1 > clip.x1 + 1.0; + let extruded = + bounds(&solid_art(&with(Node::group(NodeId(10), vec![Arc::new(rect(12, 100.0, 100.0, 150.0, 200.0, 0.0))]), EXTRUDE, front())).unwrap()); + assert!(!outside && close(b, extruded, 1.0), "{b:?} within {clip:?}"); + // A clip inside a clip keeps what both show. + let nested = + with(clip_group(40, Rect::new(120.0, 0.0, 400.0, 400.0), clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))), ROTATE, front()); + let both = with(Node::group(NodeId(10), vec![Arc::new(rect(12, 120.0, 100.0, 150.0, 200.0, 0.0))]), ROTATE, front()); + assert!(close(bounds(&solid_art_in(Some(&d), &nested).unwrap()), bounds(&solid_art(&both).unwrap()), 0.01)); + // A clipping group used as the clipping path clips by its own clipping path, not by its art. + let mask = Arc::new(clip_group(70, clip, rect(72, 100.0, 100.0, 110.0, 110.0, 0.0))); + let by_mask = with( + Node::new(NodeId(10), NodeKind::Group { children: vec![mask, Arc::new(rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))], clip: true }), + ROTATE, + front(), + ); + assert!(close(bounds(&solid_art_in(Some(&d), &by_mask).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01)); + // A stroke between two fills keeps its place below the top fill's solid. + let mut layered = rect(12, 100.0, 100.0, 150.0, 200.0, 0.0); + layered.appearance = Appearance { + items: vec![ + AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))), + AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 6.0)), + AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)))), + ], + ..Default::default() + } + .into(); + let colors = |n: &Node| three_d_meshes_in(Some(&d), &with(n.clone(), EXTRUDE, json!({}))).unwrap().iter().map(|m| m.color).collect::>(); + let plain = colors(&Node::group(NodeId(10), vec![Arc::new(layered.clone())])); + assert_eq!(plain.len(), 2, "the stroke's solid and the top fill's"); + assert_eq!(colors(&clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), layered.clone())), plain); + // Rotate turns both fills and the stroke, each in its own place. + let turned = |n: &Node| three_d_meshes_in(Some(&d), &with(n.clone(), ROTATE, front())).unwrap().iter().map(|m| m.color).collect::>(); + let plain = turned(&Node::group(NodeId(10), vec![Arc::new(layered.clone())])); + assert_eq!(plain.len(), 3, "both fills' surfaces and the stroke's"); + let clipped = clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), layered); + assert_eq!(turned(&clipped), plain); + assert_eq!(validate_three_d_in(Some(&d), &clipped, ROTATE, &json!({})), Ok(())); + // Each fill Rotate turns counts against the limit on objects; another effect takes the top + // fill only, whatever 3D effect the object carries before it changes type. + let mut many = rect(12, 100.0, 100.0, 150.0, 200.0, 0.0); + many.appearance = + Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK))); MAX_MEMBERS + 1], ..Default::default() }.into(); + let rotated = with(clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), many), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &rotated, ROTATE, &json!({})).is_err_and(|e| e.contains("takes at most"))); + for id in [EXTRUDE, crate::REVOLVE] { + assert_eq!(validate_three_d_in(Some(&d), &rotated, id, &json!({})), Ok(()), "Rotate changed to {id}"); + } + // Art nested past the limit inside a clipping group is refused, not followed to any depth. + let mut deep = rect(12, 100.0, 100.0, 200.0, 200.0, 0.0); + for i in 0..200 { + deep = Node::group(NodeId(1000 + i), vec![Arc::new(deep)]); + } + let n = with(clip_group(10, clip, deep.clone()), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep"))); + assert!(solid_art_in(Some(&d), &n).is_none()); + // So is a clipping path nested past the limit, and a symbol's art nested past it. + let by_deep = + Node::new(NodeId(10), NodeKind::Group { children: vec![Arc::new(deep.clone()), Arc::new(rect(12, 0.0, 0.0, 10.0, 10.0, 0.0))], clip: true }); + let mut deep_symbol = d.clone(); + deep_symbol.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(deep) }); + for n in [with(by_deep, ROTATE, front()), with(instance(30, "Deep", Affine::IDENTITY), ROTATE, front())] { + assert!(validate_three_d_in(Some(&deep_symbol), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep")), "{:?}", n.id); + assert!(three_d_meshes_in(Some(&deep_symbol), &n).is_err()); + } + // A compound path counts as one shape at the depth limit: a symbol's art nested as deep as a + // path may be also takes a compound path there. + let square = rect(80, 0.0, 0.0, 10.0, 10.0, 0.0); + let mut compound = + Node::new(NodeId(81), NodeKind::Compound { children: vec![Arc::new(square.clone())], rule: vectorcraft_geom::FillRule::NonZero }); + compound.appearance = square.appearance.clone(); + let mut seen = vec![]; + for levels in 60..70 { + let ok = |leaf: &Node| { + let mut art = leaf.clone(); + for i in 0..levels { + art = Node::group(NodeId(2000 + i), vec![Arc::new(art)]); + } + let mut doc = d.clone(); + doc.symbols.push(Symbol { dynamic: false, name: "Nested".into(), art: Arc::new(art) }); + validate_three_d_in(Some(&doc), &with(instance(30, "Nested", Affine::IDENTITY), ROTATE, front()), ROTATE, &json!({})).is_ok() + }; + let path_ok = ok(&square); + assert_eq!(ok(&compound), path_ok, "{levels} levels"); + seen.push(path_ok); + } + assert!(seen.contains(&true) && seen.contains(&false), "the levels cross the limit: {seen:?}"); + // A clipping group used as the clipping path clips by its first member only, so deep art it + // clips is not walked for the clip. + let mask = Node::new( + NodeId(70), + NodeKind::Group { children: vec![Arc::new(clipping_path(71, clip)), Arc::new(deep_symbol.symbols[1].art.as_ref().clone())], clip: true }, + ); + let by_deep_mask = with( + Node::new(NodeId(10), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))], clip: true }), + ROTATE, + front(), + ); + assert_eq!(validate_three_d_in(Some(&d), &by_deep_mask, ROTATE, &json!({})), Ok(())); + assert!(close(bounds(&solid_art_in(Some(&d), &by_deep_mask).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01)); + // A clip that shows none of the art builds nothing, and says so. + let empty = clip_group(10, Rect::new(500.0, 500.0, 550.0, 550.0), rect(12, 100.0, 100.0, 200.0, 200.0, 2.0)); + for id in TYPES { + let n = with(empty.clone(), id, json!({})); + assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("at least two anchors")), "{id}"); + assert!(art(&d, &n, id).is_none(), "{id}"); + } +} + +#[test] +fn a_symbol_instances_solid_is_its_symbols_art_where_the_instance_places_it() { + let d = document(); + let placed = with(instance(30, "Box", Affine::translate((300.0, 50.0))), EXTRUDE, json!({})); + let same = with(Node::group(NodeId(30), vec![Arc::new(rect(31, 300.0, 50.0, 400.0, 150.0, 2.0))]), EXTRUDE, json!({})); + assert!(close(bounds(&solid_art_in(Some(&d), &placed).unwrap()), bounds(&solid_art(&same).unwrap()), 0.01)); + // A redefined symbol reshapes the solid. + let mut wider = d.clone(); + wider.symbols[0].art = Arc::new(rect(0, 0.0, 0.0, 200.0, 100.0, 2.0)); + assert!(bounds(&solid_art_in(Some(&wider), &placed).unwrap()).width() > bounds(&solid_art_in(Some(&d), &placed).unwrap()).width() + 50.0); + // Without the symbol there is nothing to build from. + let missing = with(instance(30, "Gone", Affine::IDENTITY), EXTRUDE, json!({})); + assert!(validate_three_d_in(Some(&d), &missing, EXTRUDE, &json!({})).is_err_and(|e| e.contains("\"Gone\""))); + assert!(validate_three_d(&placed, EXTRUDE, &json!({})).is_err(), "no document: no symbol art"); + // A symbol holding an instance of itself is refused, not followed without end. + let mut looped = d.clone(); + let inner = Arc::new(instance(0, "Loop", Affine::translate((10.0, 10.0)))); + looped.symbols.push(Symbol { + dynamic: false, + name: "Loop".into(), + art: Arc::new(Node::group(NodeId(0), vec![Arc::new(rect(0, 0.0, 0.0, 10.0, 10.0, 0.0)), inner])), + }); + let n = with(instance(30, "Loop", Affine::IDENTITY), EXTRUDE, json!({})); + assert!(validate_three_d_in(Some(&looped), &n, EXTRUDE, &json!({})).is_err()); + assert!(solid_art_in(Some(&looped), &n).is_none()); +} + +#[test] +fn a_blends_solid_is_built_from_its_keys_and_steps() { + let d = document(); + for steps in [1, 3, 8] { + let n = with(blend(20, steps), ROTATE, front()); + let expanded = Node::group(NodeId(20), crate::expand_live(Some(&d), &blend(20, steps)).into_iter().map(Arc::new).collect()); + assert_eq!(expanded.children().unwrap().len(), steps as usize + 2); + let same = with(expanded, ROTATE, front()); + let (a, b) = (solid_art_in(Some(&d), &n).unwrap(), solid_art(&same).unwrap()); + assert_eq!(a.children().unwrap().len(), b.children().unwrap().len(), "a surface for each key and step"); + assert!(close(bounds(&a), bounds(&b), 0.01)); + } + // A blend making more objects than a 3D effect takes is refused. + let keys = (0..6).map(|i| Arc::new(rect(21 + i, 100.0 * i as f64, 0.0, 100.0 * i as f64 + 40.0, 40.0, 0.0))).collect(); + let spec = BlendSpec { spacing: BlendSpacing::Steps(1000), ..Default::default() }; + let n = with(Node::new(NodeId(20), NodeKind::Blend { children: keys, spec: Box::new(spec) }), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("at most 4096 objects"))); +} + +#[test] +fn images_are_refused_alone_and_in_a_group_with_image_trace_named() { + let d = document(); + for id in TYPES { + for n in [ + with(image(50), id, json!({})), + with(Node::group(NodeId(51), vec![Arc::new(rect(52, 0.0, 0.0, 10.0, 10.0, 0.0)), Arc::new(image(53))]), id, json!({})), + with(clip_group(60, Rect::new(0.0, 0.0, 10.0, 10.0), image(62)), id, json!({})), + ] { + let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err(); + assert!(err.contains("Object › Image Trace › Make"), "{id}: {err}"); + assert!(art(&d, &n, id).is_none(), "{id}"); + assert!(three_d_meshes_in(Some(&d), &n).is_err_and(|e| e.contains("Image Trace")), "{id}"); + } + // An image wholly outside the clip, alone or in a group, shows nothing and is left out; + // one the clip shows part of is refused. + let clip = Rect::new(100.0, 100.0, 150.0, 150.0); + let masked = |inside: bool| { + let mut img = image(63); + if let NodeKind::Image(i) = &mut img.kind { + i.xf = Affine::translate(if inside { (95.0, 95.0) } else { (300.0, 300.0) }); + } + img + }; + for img in [masked(false), Node::group(NodeId(64), vec![Arc::new(masked(false))])] { + let children = vec![Arc::new(clipping_path(61, clip)), Arc::new(rect(62, 100.0, 100.0, 200.0, 200.0, 0.0)), Arc::new(img)]; + let n = with(Node::new(NodeId(60), NodeKind::Group { children, clip: true }), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}"); + assert!(art(&d, &n, id).is_some(), "{id}"); + } + let partly = with(clip_group(60, clip, masked(true)), id, json!({})); + assert!(validate_three_d_in(Some(&d), &partly, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}"); + // An effect on the image, or on a group holding it, can move it into the clip: refused. + let moved = |n: Node| with(n, "distort.transform", json!({"moveH": -200.0, "moveV": -200.0})); + for img in [moved(masked(false)), moved(Node::group(NodeId(64), vec![Arc::new(masked(false))]))] { + let n = with(clip_group(60, clip, img), id, json!({})); + assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}"); + } + // A hidden image is not drawn, so it builds nothing and refuses nothing. + let mut hidden = image(53); + hidden.visible = false; + let g = with(Node::group(NodeId(51), vec![Arc::new(rect(52, 0.0, 0.0, 10.0, 10.0, 0.0)), Arc::new(hidden)]), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id}"); + } +} + +/// Symbols `L0` to `L{levels}`: `L0` holds `leaf`, each later one `fan` instances of the one +/// before it. +fn nested_symbols(levels: usize, fan: usize, leaf: Node) -> Document { + let mut d = document(); + d.symbols.push(Symbol { dynamic: false, name: "L0".into(), art: Arc::new(Node::group(NodeId(0), vec![Arc::new(leaf)])) }); + for level in 1..=levels { + let below = format!("L{}", level - 1); + let members = (0..fan).map(|i| Arc::new(instance(0, &below, Affine::translate((i as f64 * 2.0, 0.0))))).collect(); + d.symbols.push(Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(Node::group(NodeId(0), members)) }); + } + d +} + +#[test] +fn nested_symbol_instances_that_repeat_hidden_art_are_refused_past_the_work_limit() { + // Four instances at each of ten levels repeat the hidden path about a million times, with no + // object to count against the 4,096-object limit. + let mut hidden = rect(0, 0.0, 0.0, 10.0, 10.0, 0.0); + hidden.visible = false; + let d = nested_symbols(10, 4, hidden); + for id in TYPES { + let n = with(instance(30, "L10", Affine::IDENTITY), id, json!({})); + let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err(); + assert!(err.contains("hold too many objects"), "{id}: {err}"); + assert!(source::WORK.with(std::cell::Cell::get) <= source::MAX_WORK + 1, "{id}: stopped at the limit"); + assert!(art(&d, &n, id).is_none(), "{id}"); + assert!(three_d_meshes_in(Some(&d), &n).is_err(), "{id}"); + } + // A clipped shape with more strokes than a 3D effect takes objects is refused before its + // strokes are cut into pieces. + let mut stroked = rect(12, 100.0, 100.0, 200.0, 200.0, 0.0); + let strokes = (0..5000).map(|_| AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0))).collect(); + stroked.appearance = Appearance { items: strokes, ..Default::default() }.into(); + let n = with(clip_group(10, Rect::new(100.0, 100.0, 150.0, 200.0), stroked), ROTATE, front()); + let err = validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).unwrap_err(); + assert!(err.contains("takes at most 4096 objects") && !err.contains("on a group"), "{err}"); + // The same nesting with 1,024 visible squares stays far below the limit and builds: each + // square, group and instance is visited once (an instance twice: listed, then resolved). + let d = nested_symbols(5, 4, rect(0, 0.0, 0.0, 10.0, 10.0, 0.0)); + let n = with(instance(30, "L5", Affine::IDENTITY), ROTATE, front()); + assert_eq!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})), Ok(())); + let work = source::WORK.with(std::cell::Cell::get); + assert!(work <= 1024 + 1365 * 3, "{work}"); + assert!(solid_art_in(Some(&d), &n).is_some()); +} + +#[test] +fn a_symbol_holding_more_objects_than_the_work_limit_is_refused_before_its_art_is_placed() { + let mut d = document(); + let members = (0..=source::MAX_WORK).map(|i| Arc::new(rect(0, i as f64, 0.0, i as f64 + 1.0, 1.0, 0.0))).collect(); + d.symbols.push(Symbol { dynamic: false, name: "Big".into(), art: Arc::new(Node::group(NodeId(0), members)) }); + let n = with(instance(30, "Big", Affine::IDENTITY), EXTRUDE, json!({})); + let err = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({})).unwrap_err(); + assert!(err.contains("hold too many objects"), "{err}"); + let work = source::WORK.with(std::cell::Cell::get); + assert!(work <= 2, "refused before the symbol's art is placed and listed: {work}"); +} + +/// A gradient fill: a path filled with one is drawn in clip groups where it crosses 9-slice guides. +fn gradient() -> Paint { + use vectorcraft_doc::color::{Gradient, GradientPaint}; + Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))) +} + +/// A document whose symbol "Sliced" has 9-slice guides and holds `count` paths across all of them, +/// each filled with `fill`, and an Extrude on an instance of it at twice its size. +fn sliced(count: usize, fill: impl Fn() -> Paint) -> (Document, Node) { + let mut d = document(); + let members = (0..count).map(|i| { + Arc::new(Node::path(NodeId(i as u64 + 1), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(fill(), Paint::None, 0.0))) + }); + d.symbols.push(Symbol { dynamic: true, name: "Sliced".into(), art: Arc::new(Node::group(NodeId(0), members.collect())) }); + d.set_symbol_nine_slice("Sliced", Some(vectorcraft_doc::SymbolNineSlice::default())); + let n = with(instance(30, "Sliced", Affine::scale(2.0)), EXTRUDE, json!({})); + (d, n) +} + +#[test] +fn a_symbol_whose_9_slice_guides_would_place_too_many_objects_is_refused_before_its_art_is_placed() { + // Each gradient path becomes a group of nine clip groups, so the art placed is far past the + // limit while the symbol itself holds less than a tenth of it. + let (d, n) = sliced(source::MAX_WORK / 20, gradient); + assert!(d.symbols[1].art.count_with_masks() < source::MAX_WORK); + let err = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({})).unwrap_err(); + assert!(err.contains("hold too many objects"), "{err}"); + let work = source::WORK.with(std::cell::Cell::get); + assert!(work <= 2, "refused before the symbol's art is placed and listed: {work}"); +} + +#[test] +fn a_dynamic_symbol_whose_overrides_would_place_too_many_objects_is_refused_before_its_art_is_placed() { + // Solid paths are cut at the guides and stay one path each; the instance's overrides fill them + // with a gradient, which places each in nine clip groups. + let (d, mut n) = sliced(source::MAX_WORK / 20, || Paint::solid(Color::BLACK)); + n.extras_mut().symbol_overrides = (0..source::MAX_WORK / 20) + .map(|i| vectorcraft_doc::SymbolOverride { path: vec![i as u32], fill: Some(gradient()), ..Default::default() }) + .collect(); + let err = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({})).unwrap_err(); + assert!(err.contains("hold too many objects"), "{err}"); + let work = source::WORK.with(std::cell::Cell::get); + assert!(work <= 2, "refused before the instance's art is placed and listed: {work}"); + // A few such paths build. + let (d, n) = sliced(4, || Paint::solid(Color::BLACK)); + assert!(solid_art_in(Some(&d), &n).is_some()); +} + +#[test] +fn empty_sources_and_sources_inside_sources_build_or_refuse_cleanly() { + let mut d = document(); + d.symbols.push(Symbol { dynamic: false, name: "Empty".into(), art: Arc::new(Node::group(NodeId(0), vec![])) }); + let clip = Rect::new(0.0, 0.0, 50.0, 100.0); + d.symbols.push(Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(clip_group(0, clip, rect(0, 0.0, 0.0, 100.0, 100.0, 0.0))) }); + let empty_clip = Node::new(NodeId(10), NodeKind::Group { children: vec![], clip: true }); + let empty_symbol = instance(30, "Empty", Affine::IDENTITY); + let no_keys = Node::new(NodeId(20), NodeKind::Blend { children: vec![], spec: Box::default() }); + for id in TYPES { + // Alone, an empty clipping group, an instance of an empty symbol and a blend without keys + // build nothing and say so. + for empty in [&empty_clip, &empty_symbol, &no_keys] { + let n = with(empty.clone(), id, json!({})); + let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err(); + assert!(err.contains("at least two anchors"), "{id} on {:?}: {err}", empty.kind); + assert!(art(&d, &n, id).is_none(), "{id}"); + assert!(three_d_meshes_in(Some(&d), &n).is_err(), "{id}"); + // In a group they add nothing, and the group's other members still build. + let g = with(Node::group(NodeId(90), vec![Arc::new(empty.clone()), Arc::new(rect(91, 0.0, 0.0, 50.0, 50.0, 0.0))]), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding {:?}", empty.kind); + assert!(art(&d, &g, id).is_some(), "{id}"); + } + // A blend set to no steps draws one step, and builds from its keys and that step. + let n = with(blend(20, 0), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}"); + } + let drawn = Node::group(NodeId(20), crate::expand_live(Some(&d), &blend(20, 0)).into_iter().map(Arc::new).collect()); + assert_eq!(drawn.children().unwrap().len(), 3); + let (a, b) = (solid_art_in(Some(&d), &with(blend(20, 0), ROTATE, front())).unwrap(), solid_art(&with(drawn, ROTATE, front())).unwrap()); + assert_eq!(a.children().unwrap().len(), b.children().unwrap().len()); + assert!(close(bounds(&a), bounds(&b), 0.01)); + // A symbol holding a clipping group builds from the art inside the clip, where the instance + // places it. + let placed = with(instance(30, "Clipped", Affine::translate((200.0, 0.0))), ROTATE, front()); + let cut = with(Node::group(NodeId(30), vec![Arc::new(rect(31, 200.0, 0.0, 250.0, 100.0, 0.0))]), ROTATE, front()); + assert!(close(bounds(&solid_art_in(Some(&d), &placed).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01)); +} + +#[test] +fn resolved_objects_and_groups_in_a_three_d_group_keep_their_geometry_effects() { + let mut d = document(); + d.symbols.push(Symbol { dynamic: false, name: "Left".into(), art: Arc::new(rect(0, 0.0, 100.0, 50.0, 200.0, 0.0)) }); + let moved = |n: Node| with(n, "distort.transform", json!({"moveH": 100.0})); + let clip = Rect::new(100.0, 100.0, 150.0, 200.0); + let target = rect(1, 100.0, 100.0, 150.0, 200.0, 0.0); + let expected = bounds(&solid_art(&with(Node::group(NodeId(90), vec![Arc::new(target.clone())]), ROTATE, front())).unwrap()); + let left = || rect(2, 0.0, 100.0, 50.0, 200.0, 0.0); + let members = [ + ("a symbol instance", moved(instance(30, "Left", Affine::IDENTITY))), + ("a clipping group", moved(clip_group(40, Rect::new(0.0, 100.0, 50.0, 200.0), left()))), + ("a plain group", moved(Node::group(NodeId(50), vec![Arc::new(left())]))), + ("a group in a clipping group", clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(left())])))), + ]; + for (what, member) in members { + for id in TYPES { + let g = with(Node::group(NodeId(90), vec![Arc::new(member.clone())]), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding {what}"); + } + let g = with(Node::group(NodeId(90), vec![Arc::new(member)]), ROTATE, front()); + assert!(close(bounds(&solid_art_in(Some(&d), &g).unwrap()), expected, 0.01), "{what} moved by its Transform effect"); + } + // A blend's effect moves its keys and steps together. + let blended = with(Node::group(NodeId(90), vec![Arc::new(moved(blend(20, 3)))]), ROTATE, front()); + let unmoved = with(Node::group(NodeId(90), vec![Arc::new(blend(20, 3))]), ROTATE, front()); + let (a, b) = (bounds(&solid_art_in(Some(&d), &blended).unwrap()), bounds(&solid_art_in(Some(&d), &unmoved).unwrap())); + assert!(close(a, Rect::new(b.x0 + 100.0, b.y0, b.x1 + 100.0, b.y1), 0.01), "{a:?} is {b:?} moved"); + // A geometry effect that reads the object's stroke reads the resolved object's, as a group's. + let stroked = |kind: NodeKind| { + let mut n = Node::new(NodeId(20), kind); + n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0).into(); + with(n, "path.outlineStroke", json!({})) + }; + let NodeKind::Blend { children, spec } = blend(20, 3).kind else { panic!("a blend") }; + let steps = crate::expand_live(Some(&d), &blend(20, 3)).into_iter().map(Arc::new).collect(); + let group_of = |n: Node| with(Node::group(NodeId(90), vec![Arc::new(n)]), ROTATE, front()); + let resolved = bounds(&solid_art_in(Some(&d), &group_of(stroked(NodeKind::Blend { children, spec }))).unwrap()); + let plain = bounds(&solid_art(&group_of(stroked(NodeKind::Group { children: steps, clip: false }))).unwrap()); + assert!(close(resolved, plain, 0.01), "{resolved:?} {plain:?}"); + // A member's opacity and blending mode stay on it when its group's effects reshape it in a clip. + let mut multiplied = left(); + multiplied.opacity = 0.5; + multiplied.blend = BlendMode::Multiply; + let n = clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(multiplied), Arc::new(left())]))); + let resolved = resolve(Some(&d), &n, "").unwrap().into_owned(); + let mut found = vec![]; + resolved.walk(&mut |c| { + if c.blend == BlendMode::Multiply { + found.push((c.opacity, c.children().map_or(0, Vec::len))); + } + }); + assert_eq!(found, vec![(0.5, 1)], "one Multiply group at 50% holding the one member's piece"); + // Groups nested past the limit under a group with geometry effects in a clipping group are + // refused before the effects reshape them. + let mut deep = left(); + for i in 0..200 { + deep = Node::group(NodeId(1000 + i), vec![Arc::new(deep)]); + } + let n = with(clip_group(60, clip, moved(deep.clone())), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep"))); + // A hidden member nested past the limit is left out, as it is drawn, and does not refuse. + deep.visible = false; + let n = with(clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(deep), Arc::new(left())]))), ROTATE, front()); + assert_eq!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})), Ok(())); + // Hidden members of a group inside a clipping group build nothing. + let mut hidden = rect(63, 100.0, 100.0, 150.0, 200.0, 0.0); + hidden.visible = false; + let n = with(clip_group(60, clip, Node::group(NodeId(62), vec![Arc::new(hidden)])), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("at least two anchors"))); +} diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index 1a5c900954..c96dcb477c 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -1,5 +1,5 @@ //! Arrowheads. A head of weight `hw` (stroke weight × scale) fits a box `4·hw` long and `4·hw` -//! wide. Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms. +//! wide; the line arrow's arms reach twice as far out ([`Arrowhead::half_width`]). Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms. //! The stroke ends under the head at the head's *inset* from the tip: halfway into solid heads, //! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner //! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by @@ -8,7 +8,7 @@ use std::borrow::Cow; -use std::f64::consts::{FRAC_PI_2, PI}; +use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, PI}; use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen, PathSeg, Point, Shape, Vec2}; use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer}; @@ -252,6 +252,7 @@ const HEX: f64 = 2.0 * 1.732_050_807_568_877_2; /// Flattening tolerance of the curved local heads, in units. const LOCAL_TOL: f64 = 1e-3; +/// Where the stroke ends under a head drawn in local units ([`local`]), in those units. fn local_stop(kind: Arrowhead) -> Stop { match kind { Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0), @@ -261,7 +262,7 @@ fn local_stop(kind: Arrowhead) -> Stop { Arrowhead::Fork => Stop::At(2.7), Arrowhead::HalfArrowLeft | Arrowhead::HalfArrowRight | Arrowhead::Feather => Stop::At(1.3), Arrowhead::Swallowtail => Stop::At(1.4), - Arrowhead::Chevron => Stop::At(1.0), + Arrowhead::Chevron | Arrowhead::LineArrow => Stop::At(1.0), Arrowhead::Slash => Stop::At(1.2), Arrowhead::DoubleSlash => Stop::At(1.05), Arrowhead::DoubleArrow => Stop::At(1.7), @@ -273,8 +274,9 @@ fn local_stop(kind: Arrowhead) -> Stop { } /// The outline of a head added after the first ten, in local units: x from the tip (0) back -/// along the line (to at most 4), y across it (−2 to 2, positive to the right of the direction -/// the head points). Every shape is generated here. +/// along the line (to at most 4; the line arrow's square-cut arms 4.71), y across it (−2 to 2, +/// the line arrow −4 to 4; positive to the right of the direction the head points). Every shape +/// is generated here. fn local(kind: Arrowhead) -> BezPath { let mut p = BezPath::new(); let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::>()); @@ -363,6 +365,14 @@ fn local(kind: Arrowhead) -> BezPath { poly(&mut p, &[(0.0, 2.0), (0.6, 2.0), (0.6, 0.25), (4.0, 1.8), (4.0, -1.8), (0.6, -0.25), (0.6, -2.0), (0.0, -2.0)]) } Arrowhead::Oval => p.extend(kurbo::Ellipse::new((2.0, 0.0), (2.0, 1.2), 0.0).path_elements(LOCAL_TOL)), + Arrowhead::LineArrow => { + // Arms one unit thick (the head's weight: the line's at 100 % for lines of 0.25 pt or + // more) at right angles to each other, from a sharp tip to their outer corners at + // (4, ±4), cut square across: a unit across an arm at 45° is ½√2 along each axis, and + // the arms' inner edges meet √2 behind the tip. + let t = FRAC_1_SQRT_2; + poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]); + } // The first ten are drawn by `shape`. Arrowhead::Triangle | Arrowhead::TriangleOpen diff --git a/crates/effects/src/stroke/tests_arrows.rs b/crates/effects/src/stroke/tests_arrows.rs index 39d6d9d57d..4328048991 100644 --- a/crates/effects/src/stroke/tests_arrows.rs +++ b/crates/effects/src/stroke/tests_arrows.rs @@ -1,6 +1,6 @@ -//! Every arrowhead's outline: drawn, inside its box (4 × 4 weights; the open arrow's square-cut -//! arms reach a little further back), without self-intersections, and covering the end of the -//! stroke under it. +//! Every arrowhead's outline: drawn, inside its reach and half width (4 × 4 weights for most; the +//! open arrow's square-cut arms reach a little further back, the line arrow's twice as far out), +//! without self-intersections, and covering the end of the stroke under it. use kurbo::{BezPath, PathEl, Point, Shape}; use vectorcraft_color::{Color, Paint}; @@ -53,7 +53,13 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() { let h = head(kind); assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn"); let b = h.outline.bounding_box(); - assert!(b.x0 >= 91.0 - 1e-6 && b.x1 <= 100.0 + 1e-6 && b.y0 >= -4.0 - 1e-6 && b.y1 <= 4.0 + 1e-6, "{kind:?} leaves its box: {b:?}"); + let (reach, side) = (2.0 * kind.reach(), 2.0 * kind.half_width()); + assert!(b.x1 <= 100.0 + 1e-6 && b.y0 >= -side - 1e-6 && b.y1 <= side + 1e-6, "{kind:?} leaves its box: {b:?}"); + if kind.half_width() == 2.0 { + assert!(b.x0 >= 91.0 - 1e-6, "{kind:?} is longer than the 4 × 4 box: {b:?}"); + } + let far = contours(&h.outline).iter().flatten().map(|p| p.distance(h.tip)).fold(0.0, f64::max); + assert!(far <= reach + 1e-6, "{kind:?} reaches {far} from its tip, past {reach}"); let edges: Vec<(Point, Point)> = contours(&h.outline).iter().flat_map(|c| (0..c.len()).map(|i| (c[i], c[(i + 1) % c.len()]))).collect(); assert!(edges.len() >= 3, "{kind:?}"); for (i, a) in edges.iter().enumerate() { @@ -74,6 +80,31 @@ fn the_stroke_ends_inside_every_head() { } } +#[test] +fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() { + // Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt. + let h = head(Arrowhead::LineArrow); + let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y); + // A sharp tip on the end point; outer corners 4 units back and out, square-cut ends. + let pts: Vec = contours(&h.outline).concat(); + for (corner, name) in [(at(0.0, 0.0), "tip"), (at(4.0, 4.0), "right corner"), (at(4.0, -4.0), "left corner")] { + assert!(pts.iter().any(|p| p.distance(corner) < 1e-9), "{name} {corner:?} in {pts:?}"); + } + // Open between the arms, solid at the tip. + assert_eq!(h.outline.winding(at(2.5, 0.0)), 0); + assert_ne!(h.outline.winding(at(0.7, 0.0)), 0); + // Halfway along each arm, 45° off the line, it is one unit (the line's weight) across. + let s = std::f64::consts::FRAC_1_SQRT_2; + for side in [1.0, -1.0] { + let (mx, my) = (2.0 + 0.5 * s, side * (2.0 - 0.5 * s)); + let (nx, ny) = (-side * s, s); + for (d, inside) in [(0.45, true), (-0.45, true), (0.55, false), (-0.55, false)] { + let w = h.outline.winding(at(mx + nx * d, my + ny * d)); + assert_eq!(w != 0, inside, "arm {side} at {d} across"); + } + } +} + #[test] fn half_arrows_barb_on_their_own_side() { // Pointing along +x on a y-down page, left is −y. diff --git a/crates/effects/src/stroke/tests_reach.rs b/crates/effects/src/stroke/tests_reach.rs index 859d8b1c0e..29a48343ed 100644 --- a/crates/effects/src/stroke/tests_reach.rs +++ b/crates/effects/src/stroke/tests_reach.rs @@ -56,6 +56,28 @@ fn check(bp: &BezPath, st: &StrokeLayer, what: &str) { assert!(checked > 0, "{what}: no samples"); } +#[test] +fn a_butt_capped_open_path_is_measured_where_it_paints() { + let mut vertical = BezPath::new(); + vertical.move_to((50.0, 10.0)); + vertical.line_to((50.0, 90.0)); + let mut diagonal = BezPath::new(); + diagonal.move_to((10.0, 10.0)); + diagonal.line_to((40.0, 50.0)); + let mut arc = BezPath::new(); + arc.move_to((10.0, 50.0)); + arc.curve_to((10.0, 22.4), (32.4, 0.0), (60.0, 0.0)); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0); + stroke.cap = LineCap::Butt; + for (name, bp) in [("vertical", vertical), ("diagonal", diagonal), ("arc", arc)] { + let painted = outline_region(&PathData::from_bezpath(&bp), FillRule::NonZero, &stroke).to_bezpath().bounding_box(); + let bounds = stroke.bounds_on(&bp, bp.bounding_box()); + for (got, want) in [(bounds.x0, painted.x0), (bounds.y0, painted.y0), (bounds.x1, painted.x1), (bounds.y1, painted.y1)] { + assert!((got - want).abs() < 0.05, "{name}: measured {bounds:?}, paints {painted:?}"); + } + } +} + #[test] fn bounds_and_clicks_cover_what_every_stroke_paints() { let profiles = [None, Some(WidthProfile::lens()), Some(WidthProfile { points: vec![(0.0, 2.0, 0.5), (0.6, 0.8, 1.6), (1.0, 1.2, 0.3)] })]; diff --git a/crates/effects/src/tests/transformfx.rs b/crates/effects/src/tests/transformfx.rs index 84368b6f64..de69116b79 100644 --- a/crates/effects/src/tests/transformfx.rs +++ b/crates/effects/src/tests/transformfx.rs @@ -105,7 +105,7 @@ fn each_copy_scales_its_stroke_once_more() { let n = stroked(json!({"scaleH": 200, "scaleV": 200, "copies": 2, "strokes": true})); let art = reshape(None, &n, None).unwrap(); let widths: Vec = leaves(&art).iter().map(|p| stroke_of(p).0).collect(); - assert_eq!(widths, vec![2.0, 4.0, 8.0]); + assert_eq!(widths, vec![8.0, 4.0, 2.0], "the original on top"); // Without the option the copies keep the original's weight. let plain = stroked(json!({"scaleH": 200, "scaleV": 200, "copies": 2})); assert!(!has_transform_art(&plain)); @@ -127,7 +127,7 @@ fn transform_patterns_moves_each_copys_pattern() { assert!(has_transform_options(&n)); let art = reshape(None, &n, None).unwrap(); let xs: Vec = leaves(&art).iter().map(|p| pattern_xf(p).as_coeffs()[4]).collect(); - assert_eq!(xs, vec![0.0, 30.0, 60.0]); + assert_eq!(xs, vec![60.0, 30.0, 0.0], "the original on top"); // Without it, every copy's pattern stays put (the tiles don't follow the copies). let n = patterned(json!({"moveH": 30, "patterns": false, "strokes": false, "objects": true})); assert!(!has_transform_art(&n)); @@ -218,7 +218,7 @@ fn each_copy_of_a_strokes_own_transform_scales_its_weight_once_more() { let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "copies": 2, "strokes": true})); let art = reshape(None, &n, None).unwrap(); let widths: Vec = stroked_leaves(&art).iter().map(|p| stroke_of(p).0).collect(); - assert_eq!(widths, vec![2.0, 4.0, 8.0]); + assert_eq!(widths, vec![8.0, 4.0, 2.0], "the original on top"); } #[test] @@ -268,7 +268,7 @@ fn a_fills_own_transform_moves_each_copys_pattern_with_transform_patterns() { assert!(has_transform_options(&n)); let art = reshape(None, &n, None).unwrap(); let xs: Vec = pattern_leaves(&art).iter().map(|p| pattern_xf(p).as_coeffs()[4]).collect(); - assert_eq!(xs, vec![0.0, 30.0, 60.0]); + assert_eq!(xs, vec![60.0, 30.0, 0.0], "the original on top"); // Off, the pattern stays put. assert!(!has_transform_art(&fill_with_effect(json!({"moveH": 30, "copies": 2})))); } @@ -294,7 +294,7 @@ fn a_strokes_own_transform_draws_bakes_expands_and_measures_alike() { let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "copies": 1, "strokes": true})); let drawn = reshape(None, &n, None).unwrap(); let widths = |art: &Node| stroked_leaves(art).iter().map(|p| stroke_of(p).0).collect::>(); - assert_eq!(widths(&drawn), vec![2.0, 4.0]); + assert_eq!(widths(&drawn), vec![4.0, 2.0], "the original on top"); // Expand Appearance. assert_eq!(widths(&expand_outlined(None, &n, None).unwrap()), widths(&drawn)); // Export. @@ -394,9 +394,9 @@ fn filled_and_stroked(fill: Paint, params: Value) -> Node { } #[test] -fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() { - // Black fill, white stroke, each copy scaled and turned (#5920): each copy is an object of its - // own above the one before, so its fill covers the strokes of the copies below. +fn copies_with_a_fill_and_a_stroke_are_drawn_one_below_another() { + // Black fill, white stroke, each copy scaled and turned (#5920, #6316): each copy is an object + // of its own below the one before, so the fills above cover the strokes of the copies below. let params = json!({"scaleH": 97, "scaleV": 97, "rotate": 10, "copies": 25}); let n = filled_and_stroked(Paint::solid(Color::BLACK), params.clone()); assert!(has_transform_art(&n)); @@ -407,10 +407,10 @@ fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() { assert!(matches!(p.kind, NodeKind::Path { .. }), "one shape each, not one path of every copy"); assert!(!p.appearance.fill_paint().is_none() && p.appearance.stroke().is_some()); } - // The original is at the bottom, the smallest copy on top. - assert_eq!(paths[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)); - let top = paths[25].geometric_bounds().unwrap(); - assert!(top.width() < 100.0 && top.height() < 100.0, "{top:?}"); + // The smallest copy is at the bottom, the original on top. + assert_eq!(paths[25].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)); + let bottom = paths[0].geometric_bounds().unwrap(); + assert!(bottom.width() < 100.0 && bottom.height() < 100.0, "{bottom:?}"); // Drawn as Expand Appearance makes it. assert_eq!(leaves(&expand_outlined(None, &n, None).unwrap()).len(), 26); @@ -427,3 +427,252 @@ fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() { // No copies: nothing to stack. assert!(!has_transform_art(&filled_and_stroked(Paint::solid(Color::BLACK), json!({"rotate": 10})))); } + +/// A group of two squares side by side, each with a black fill and a white stroke, with the +/// Transform effect `params`. +fn two_squares(params: Value) -> Node { + let square = |id, x| { + let a = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::WHITE), 4.0); + std::sync::Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)), a)) + }; + let mut g = Node::group(NodeId(20), vec![square(21, 0.0), square(22, 120.0)]); + g.appearance.effects.push(transform(params)); + g +} + +#[test] +fn a_groups_copies_are_whole_groups_below_the_original() { + let art = crate::evaluate_container(None, &two_squares(json!({"scaleH": 95, "scaleV": 95, "copies": 10}))).unwrap(); + let copies = art.children().unwrap(); + assert_eq!(copies.len(), 11, "the original and 10 copies"); + for c in copies { + assert_eq!(c.children().map(Vec::len), Some(2), "each copy holds both squares"); + } + // The smallest copy is at the bottom, the original on top with its members in their order. + let width = |i: usize| copies[i].geometric_bounds().unwrap().width(); + assert!((0..10).all(|i| width(i) < width(i + 1)), "{:?}", (0..11).map(width).collect::>()); + assert_eq!(copies[10].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 220.0, 100.0)); + let members = copies[10].children().unwrap(); + assert_eq!(members[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)); + assert_eq!(members[1].geometric_bounds().unwrap(), Rect::new(120.0, 0.0, 220.0, 100.0)); + + // Without copies the members stay members of the art. + let art = crate::evaluate_container(None, &two_squares(json!({"scaleH": 50, "scaleV": 50}))).unwrap(); + assert_eq!(art.children().unwrap().iter().map(|c| c.id).collect::>(), [NodeId(21), NodeId(22)]); + + // A group's own fill paints the shape of all its copies, so each member keeps its place. + let mut own_fill = two_squares(json!({})); + own_fill.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into(); + let copies = transform(json!({"moveH": 300, "copies": 2})); + crate::reshape::reshape_leaves_within(&mut own_fill, &[&copies], crate::geometry::Budget::EFFECTS, None); + assert_eq!(own_fill.children().map(Vec::len), Some(2), "a stack of copies per member"); + + // A guide in the group stays one guide. + let mut guided = two_squares(json!({})); + let mut guide = Node::path(NodeId(23), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default()); + if let NodeKind::Path { guide: on, .. } = &mut guide.kind { + *on = true; + } + if let Some(members) = guided.children_mut() { + members.push(std::sync::Arc::new(guide)); + } + guided.appearance.effects.clear(); + crate::reshape::reshape_leaves_within(&mut guided, &[&copies], crate::geometry::Budget::EFFECTS, None); + assert_eq!(guided.children().map(Vec::len), Some(3), "the original and 2 copies"); + let mut guides = 0; + guided.walk(&mut |n| guides += usize::from(matches!(n.kind, NodeKind::Path { guide: true, .. }))); + assert_eq!(guides, 1); + + // A clipping group's first member stays its clip. + let mut clipping = two_squares(json!({})); + if let NodeKind::Group { clip, .. } = &mut clipping.kind { + *clip = true; + } + clipping.appearance.effects.clear(); + crate::reshape::reshape_leaves_within(&mut clipping, &[&copies], crate::geometry::Budget::EFFECTS, None); + assert_eq!(clipping.children().map(Vec::len), Some(2), "the clip and the clipped member"); +} + +#[test] +fn a_groups_copies_stop_at_the_node_limit() { + // Empty groups cost no anchors, so only the count of nodes stops their copies. + let empties = (0..5_000).map(|i| std::sync::Arc::new(Node::group(NodeId(100 + i), vec![]))); + let mut g = two_squares(json!({})); + if let Some(members) = g.children_mut() { + members.extend(empties); + } + g.appearance.effects.clear(); + let copies = transform(json!({"moveH": 1, "copies": 1000})); + crate::reshape::reshape_leaves_within(&mut g, &[&copies], crate::geometry::Budget::EFFECTS, None); + let mut nodes = 0usize; + g.walk(&mut |_| nodes += 1); + assert!(nodes <= crate::distort::MAX_COPY_OBJECTS + 1, "{nodes}"); + assert!(g.children().unwrap().len() < 1001, "the limit stopped the copies"); +} + +#[test] +fn a_groups_copies_count_the_art_of_opacity_masks() { + let empties = (0..5_000).map(|i| std::sync::Arc::new(Node::group(NodeId(100 + i), vec![]))).collect(); + let mut g = two_squares(json!({})); + if let Some(members) = g.children_mut() { + let mask = vectorcraft_doc::OpacityMask::new(Node::group(NodeId(99), empties), true); + std::sync::Arc::make_mut(&mut members[0]).extras_mut().mask = Some(Box::new(mask)); + } + g.appearance.effects.clear(); + let copies = transform(json!({"moveH": 1, "copies": 1000})); + crate::reshape::reshape_leaves_within(&mut g, &[&copies], crate::geometry::Budget::EFFECTS, None); + let nodes = g.count_with_masks(); + assert!(nodes <= crate::distort::MAX_COPY_OBJECTS + 1, "{nodes}"); +} + +/// The anchors `n` draws with every effect inside it evaluated, group by group and member by +/// member as drawing and baking evaluate them. The count stops once it passes `limit`. +fn drawn_anchors(n: &Node, limit: usize) -> usize { + fn count(n: &Node, limit: usize, total: &mut usize) { + if *total > limit { + return; + } + if n.children().is_some() && !matches!(n.kind, NodeKind::Compound { .. }) { + let art = crate::evaluate_container(None, n).unwrap_or_else(|| n.clone()); + art.children().into_iter().flatten().for_each(|c| count(c, limit, total)); + return; + } + if let Some(art) = reshape(None, n, None) { + count(&art, limit, total); + return; + } + let Some((path, _)) = crate::reshape::leaf_geometry(n) else { return }; + let Some(bounds) = path.bounds() else { return }; + let own = crate::apply_geometry(&n.appearance.effects, &path, bounds); + let items: Vec = n + .appearance + .items + .iter() + .filter(|i| crate::has_geometry(i.effects())) + .filter_map(|i| Some(crate::apply_geometry(i.effects(), &own, own.bounds()?).anchor_count())) + .collect(); + *total += if items.is_empty() { own.anchor_count() } else { items.iter().sum() }; + } + let mut total = 0; + count(n, limit, &mut total); + total +} + +#[test] +fn a_groups_copies_keep_what_the_effects_inside_them_make_to_the_budget() { + let most = crate::geometry::MAX_EFFECT_ANCHORS; + let copies = |key: &str| transform(json!({key: 1, "copies": 1000})); + + // Copies of a group whose member group makes copies of its own. + let inner = two_squares(json!({"moveH": 1, "copies": 1000})); + let mut outer = Node::group(NodeId(30), vec![std::sync::Arc::new(inner)]); + outer.appearance.effects.push(copies("moveV")); + let drawn = drawn_anchors(&outer, 2 * most); + assert!(drawn <= most, "a group inside: {drawn}"); + + // Copies of a group whose member path makes copies of its own. + let mut own = two_squares(json!({"moveH": 1, "copies": 1000})); + if let Some(members) = own.children_mut() { + std::sync::Arc::make_mut(&mut members[0]).appearance.effects.push(copies("moveV")); + } + let drawn = drawn_anchors(&own, 2 * most); + assert!(drawn <= most, "a path's own effect: {drawn}"); + + // Copies of a group whose member's fill makes copies of its own. + let mut item = two_squares(json!({"moveH": 1, "copies": 1000})); + if let Some(members) = item.children_mut() { + std::sync::Arc::make_mut(&mut members[0]).appearance.items[0].effects_mut().push(copies("moveV")); + } + let drawn = drawn_anchors(&item, 2 * most); + assert!(drawn <= most, "a fill's own effect: {drawn}"); +} + +#[test] +fn copies_with_scaled_effects_keep_what_each_one_makes_to_the_budget() { + // Each copy's Roughen is twice as large as the last's, and the rough edges take more lines. + let roughen = Effect { id: "distort.roughen".into(), params: json!({"size": 40, "relative": false, "detail": 20}), visible: true }; + let lines = |budget: crate::geometry::Budget| { + let mut g = two_squares(json!({})); + if let Some(members) = g.children_mut() { + let m = std::sync::Arc::make_mut(&mut members[0]); + m.appearance.items.retain(AppearanceItem::is_fill); + m.appearance.effects.push(roughen.clone()); + members.truncate(1); + } + g.appearance.effects.clear(); + let copies = transform(json!({"scaleH": 200, "scaleV": 200, "copies": 5, "strokes": true})); + crate::reshape::reshape_leaves_within(&mut g, &[&copies], budget, None); + let (mut count, mut lines) = (0, 0); + for leaf in leaves(&g) { + count += 1; + let Some((path, _)) = crate::reshape::leaf_geometry(leaf) else { continue }; + let drawn = crate::apply_geometry(&leaf.appearance.effects, &path, path.bounds().unwrap()); + lines += crate::geometry::Budget::of(&drawn).lines; + } + (count, lines) + }; + let (all, most) = lines(crate::geometry::Budget::EFFECTS); + assert_eq!(all, 6, "the original and 5 copies"); + let cap = most / 2; + let budget = crate::geometry::Budget { anchors: crate::geometry::MAX_EFFECT_ANCHORS, lines: cap }; + let (count, drawn) = lines(budget); + assert!(count < all, "the budget stopped the copies"); + assert!(drawn <= cap, "{drawn} > {cap}"); +} + +#[test] +fn a_groups_copies_are_whole_only_when_nothing_inside_makes_more_art() { + let copies = transform(json!({"moveH": 300, "copies": 2})); + let effect = |id: &str| Effect { id: id.into(), params: json!({}), visible: true }; + let roughen = effect("distort.roughen"); + // Two squares under a group with `change` made to the first member. + let whole = |change: &dyn Fn(&mut Node)| { + let mut g = two_squares(json!({})); + if let Some(members) = g.children_mut() { + change(std::sync::Arc::make_mut(&mut members[0])); + } + g.appearance.effects.clear(); + crate::reshape::reshape_leaves_within(&mut g, &[&copies], crate::geometry::Budget::EFFECTS, None); + g.children().unwrap().len() == 3 + }; + // A group of one square with effect `e`, in place of the member. + let in_group = |m: &mut Node, e: &Effect| { + let square = Node::path(NodeId(40), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default()); + let mut g = Node::group(NodeId(41), vec![std::sync::Arc::new(square), std::sync::Arc::new(m.clone())]); + g.appearance.effects.push(e.clone()); + *m = g; + }; + assert!(whole(&|_| {})); + // Effects that only change pixels, and effects turned off, are copied with the art. + assert!(whole(&|m| m.appearance.effects.push(effect("stylize.dropShadow")))); + assert!(whole(&|m| m.appearance.effects.push(Effect { visible: false, ..roughen.clone() }))); + // Effects that draw nothing are copied with the art as well. + assert!( + whole(&|m| { + m.visible = false; + m.appearance.effects.push(roughen.clone()); + }), + "a hidden member's effect" + ); + assert!( + whole(&|m| { + *m.appearance.items[0].paint_mut() = Paint::None; + m.appearance.items[0].effects_mut().push(roughen.clone()); + }), + "the effect of a fill that paints nothing" + ); + assert!(whole(&|m| m.appearance.effects.push(effect("no.such.effect"))), "an unknown effect"); + // Effects that make more art than a copy holds keep each member's copies in its place. + assert!(!whole(&|m| m.appearance.effects.push(roughen.clone())), "a member's own effect"); + assert!(!whole(&|m| m.appearance.items[0].effects_mut().push(roughen.clone())), "a fill's own effect"); + assert!(!whole(&|m| in_group(m, &roughen)), "a group's own effect"); + assert!(!whole(&|m| in_group(m, &effect("pathfinder.add"))), "a Pathfinder effect"); + assert!( + !whole(&|m| { + let mut art = Node::group(NodeId(43), vec![]); + in_group(&mut art, &roughen); + m.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + }), + "an effect in an opacity mask" + ); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 3394585bb9..836d4b7448 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -40,6 +40,9 @@ vectorcraft-metafile = { workspace = true } vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } vectorcraft-scriptcheck = { workspace = true } +vectorcraft-js = { workspace = true } +# The commands' parameter schemas (schemas.rs). +vectorcraft-apischema = { workspace = true } image = { workspace = true } jxl-oxide = { workspace = true } jxl-color = { workspace = true } @@ -86,3 +89,5 @@ zune-jpegxl = { workspace = true } zune-core = { workspace = true } # The JavaScript parser's lexer, compared with the script checker's on the same scripts. vectorcraft-js = { workspace = true } +# A bundled font's own glyph boxes, for the glyph bounds tests. +skrifa = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 625aa52329..c76492f454 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -2,6 +2,7 @@ pub mod actionset; mod addons; +mod apiref; pub(crate) mod appearance; mod assets; mod attributes; @@ -69,6 +70,7 @@ pub mod pdfcmds; pub mod perspgrid; pub mod place; pub mod plugin; +pub(crate) mod plugin_call; pub mod prefscmds; pub mod print; pub(crate) mod printadvanced; @@ -130,6 +132,9 @@ pub struct CommandSpec { pub run: Run, /// Record in the journal (false for queries and selection-only helpers). pub journal: bool, + /// The parameters' schema: [`Session::execute`] checks the params against it before the + /// command runs, and `params` is the text it writes ([`crate::schemas`]). + pub schema: Option<&'static vectorcraft_apischema::ParamSchema>, } /// Serializable command metadata. @@ -143,11 +148,29 @@ pub struct CommandInfo { pub enabled: bool, #[serde(skip_serializing_if = "Option::is_none")] pub disabled_reason: Option, + /// The parameters' schema as a JSON Schema 2020-12 object schema, for a command that has one. + #[serde(skip_serializing_if = "Option::is_none")] + pub schema: Option, + /// The same schema in the form an MCP tool's `inputSchema` takes ([`input_schema`]). + #[serde(rename = "inputSchema", skip_serializing_if = "Option::is_none")] + pub input_schema: Option, +} + +/// `schema` as an MCP tool input schema: the root `type` is `"object"`, since the arguments are +/// always an object, and every other keyword is kept. The root of [`CommandInfo::schema`] also +/// takes null when no parameter is required. +pub(crate) fn input_schema(schema: &Value) -> Value { + let mut o = schema.clone(); + if let Some(map) = o.as_object_mut() { + map.insert("type".into(), "object".into()); + } + o } impl CommandSpec { pub fn info(&self, s: &Session) -> CommandInfo { let e = (self.enabled)(s); + let schema = self.schema.map(vectorcraft_apischema::ParamSchema::to_json); CommandInfo { id: self.id, label: self.label, @@ -156,6 +179,8 @@ impl CommandSpec { params: self.params, enabled: e.is_ok(), disabled_reason: e.err(), + input_schema: schema.as_ref().map(input_schema), + schema, } } } @@ -238,10 +263,17 @@ pub fn has_clipboard(s: &Session) -> std::result::Result<(), String> { macro_rules! cmd { ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, schema: None } }; (query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, schema: None } + }; + // With a parameter schema: `schema: &SCHEMA` after the run function. + ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr, schema: $schema:expr) => { + $crate::cmd::CommandSpec { schema: Some($schema), ..$crate::cmd::cmd!($id, $label, [$($m),*], $sc, $params, $en, $run) } + }; + (query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr, schema: $schema:expr) => { + $crate::cmd::CommandSpec { schema: Some($schema), ..$crate::cmd::cmd!(query $id, $label, [$($m),*], $sc, $params, $en, $run) } }; } pub(crate) use cmd; @@ -354,6 +386,8 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(actionset::specs()); v.extend(importmatches::specs()); v.extend(addons::specs()); + // Last, so the reference it writes ends with its own section. + v.extend(apiref::specs()); v }) } @@ -370,6 +404,14 @@ pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) } } +/// [`run_spec`] for a command run outside [`Session::execute`]: with params checked against the +/// command's schema, and the defaults of omitted values filled in, as `execute` does +/// ([`crate::schemas::check`]). +pub(crate) fn run_checked(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result { + let checked = crate::schemas::check(spec, p, s.replaying())?; + run_spec(s, spec, checked.as_ref().unwrap_or(p)) +} + // ---------- param helpers ---------- pub(crate) fn bad(cmd: &str, msg: impl Into) -> EngineError { diff --git a/crates/engine/src/cmd/addons/cleanup/checks.rs b/crates/engine/src/cmd/addons/cleanup/checks.rs index 4b03f0e433..dfb450faed 100644 --- a/crates/engine/src/cmd/addons/cleanup/checks.rs +++ b/crates/engine/src/cmd/addons/cleanup/checks.rs @@ -275,6 +275,7 @@ fn same_art(a: &NodeKind, b: &NodeKind) -> bool { moved.xf = a.xf; moved.cached_bounds = a.cached_bounds; moved.cached_baselines.clone_from(&a.cached_baselines); + moved.cached_ink = a.cached_ink; **a == moved } } diff --git a/crates/engine/src/cmd/addons/contour.rs b/crates/engine/src/cmd/addons/contour.rs index 46df381edc..34b9443429 100644 --- a/crates/engine/src/cmd/addons/contour.rs +++ b/crates/engine/src/cmd/addons/contour.rs @@ -12,8 +12,8 @@ use vectorcraft_doc::NodeKind; use vectorcraft_render::effects; use super::super::edit::{copy_above, selected_roots}; -use super::super::pathops::{len_param, num_param}; -use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param}; +use super::super::pathops::{length_given, number_given}; +use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, text_param}; const C: &str = "addon.contour.set"; /// The live effect that does the offsetting (the one Effect › Path › Offset Path applies). @@ -44,12 +44,12 @@ fn joins_for(corners: Option<&str>) -> Result<&'static str> { } fn contour(s: &mut Session, p: &Value) -> Result { - let offset = len_param(p, "offset").ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?; + let offset = length_given(p, "offset", C)?.ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?; if offset.abs() > MAX_OFFSET { return Err(bad(C, "offset out of range")); } - let joins = joins_for(str_param(p, "corners"))?; - let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0); + let joins = joins_for(text_param(p, "corners", C)?)?; + let miter = number_given(p, "miterLimit", C)?.unwrap_or(4.0).clamp(1.0, 500.0); let effect = effects::new_effect(EFFECT, &json!({"offset": offset, "joins": joins, "miterLimit": miter})) .ok_or_else(|| EngineError::Other("Contour: the Offset Path effect is not available".into()))?; let roots = selected_roots(s)?; diff --git a/crates/engine/src/cmd/addons/contour/tests.rs b/crates/engine/src/cmd/addons/contour/tests.rs index 900d110d58..3983ed942d 100644 --- a/crates/engine/src/cmd/addons/contour/tests.rs +++ b/crates/engine/src/cmd/addons/contour/tests.rs @@ -158,6 +158,39 @@ fn contour_refuses_what_it_cannot_offset() { assert!(err.contains("select paths or shapes"), "{err}"); } +/// A param of the wrong type is an error naming the param, and leaves the document, the selection +/// and the undo history as they were. Null keeps a param's default, and `offset` still takes a +/// string with a unit. +#[test] +fn contour_refuses_a_param_of_the_wrong_type() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.selection.objects.clone(), st.history.undo.len()) + }; + let before = state(&s); + for (p, want) in [ + (json!({"offset": true}), "`offset` must be a number, not true"), + (json!({"offset": "abc"}), "`offset` must be a number, not \"abc\""), + (json!({"offset": [5]}), "`offset` must be a number, not [5]"), + (json!({"offset": 5, "corners": 3}), "`corners` must be a string"), + (json!({"offset": 5, "miterLimit": "high"}), "`miterLimit` must be a number, not \"high\""), + (json!({"offset": 5, "miterLimit": false}), "`miterLimit` must be a number, not false"), + ] { + let r = s.execute("addon.contour.set", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}"); + assert!(state(&s) == before, "{p} changed the document, the selection or the undo history"); + } + // A null `offset` is a missing one. + let err = s.execute("addon.contour.set", &json!({"offset": null})).unwrap_err().to_string(); + assert!(err.contains("missing `offset`"), "{err}"); + // Null corners and miter limit keep sharp corners at 4; the offset takes a unit. + let r = s.execute("addon.contour.set", &json!({"offset": "1 in", "corners": null, "miterLimit": null})).unwrap(); + let fx = effects_of(&s, ids_of(&r, "created")[0]); + assert_eq!((fx[0].1["offset"].clone(), fx[0].1["joins"].clone(), fx[0].1["miterLimit"].clone()), (json!(72.0), json!("miter"), json!(4.0))); +} + /// The border-with-a-gap recipe: two Contours of one shape (the gap, then the border), baked, then /// the gap taken out of the border with Minus Front, leaves a ring between the two. #[test] diff --git a/crates/engine/src/cmd/apiref.rs b/crates/engine/src/cmd/apiref.rs new file mode 100644 index 0000000000..54e07a1c8f --- /dev/null +++ b/crates/engine/src/cmd/apiref.rs @@ -0,0 +1,461 @@ +//! `engine.apiReference`: the command API reference in Markdown, written when it is asked for from +//! the parameter schemas of the built-in commands ([`crate::schemas`]). Each command that has a +//! schema gets a section, in registry order, with its parameters in the schema's order; a command +//! without a schema, a plug-in's included, is left out. The text depends only on the registry, so +//! every call in one build returns the same bytes. +//! +//! Text from a schema is escaped before it goes into a heading, a list item or a table cell: the +//! Markdown punctuation characters get a backslash (CommonMark 0.31.2, backslash escapes, +//! ), so a description shows as plain text and +//! cannot end a table cell or make a link, an image or HTML; line breaks, tabs and other control +//! characters become spaces. + +use serde_json::{Value, json}; +use vectorcraft_apischema::{Bound, MAX_DEPTH, MAX_ID, Omitted, Param, ParamSchema, Type, Writes}; + +use super::{CommandSpec, Result, Session, always, cmd, command_specs}; +use crate::EngineError; + +const ID: &str = "engine.apiReference"; + +/// The largest reference the command returns, in bytes of UTF-8. +pub const MAX_BYTES: usize = 1 << 20; + +static REFERENCE: ParamSchema = ParamSchema::new( + &[], + "the command API reference in Markdown, written from the built-in commands' parameter schemas: a section for each command that has one, in registry order", +) +.returns("{markdown: string}") +.writes(Writes::Nothing) +.since(2); + +pub fn specs() -> Vec { + vec![cmd!( + query "engine.apiReference", + "Command API Reference", + [], + None, + "{} the command API reference in Markdown, written from the built-in commands' parameter schemas: a section for each command that has one, in registry order → {markdown: string}", + always, + api_reference, + schema: &REFERENCE + )] +} + +fn api_reference(_: &mut Session, _: &Value) -> Result { + Ok(json!({ "markdown": reference(command_specs())? })) +} + +const HEADER: &str = "# VectorCraft command API reference\n\nThis reference lists only the commands that have a parameter schema, in registry order. `engine.commands` lists every command, with its params text and whether it can run now.\n"; + +/// The reference for the commands of `specs` that have a schema, or an error when it would be +/// larger than [`MAX_BYTES`]; a reference that is too large is never cut short. +pub(crate) fn reference(specs: &[CommandSpec]) -> Result { + let mut out = String::from(HEADER); + let mut sections = 0; + for spec in specs { + let Some(schema) = spec.schema else { continue }; + let text = section(spec, schema); + if out.len() + text.len() > MAX_BYTES { + return Err(EngineError::Other(format!("`{ID}`: the reference would be larger than {MAX_BYTES} bytes"))); + } + out.push_str(&text); + sections += 1; + } + if sections == 0 { + out.push_str("\nNo commands have parameter schemas.\n"); + } + Ok(out) +} + +/// One command's section: its heading, a list of what it is, and its parameters. +fn section(spec: &CommandSpec, schema: &ParamSchema) -> String { + let menu = if spec.menu.is_empty() { "None".to_string() } else { spec.menu.iter().map(|m| escape(m)).collect::>().join(" › ") }; + let mut s = format!("\n## {}\n\n", escape(spec.id)); + s.push_str(&format!("- Label: {}\n", escape(spec.label))); + s.push_str(&format!("- Menu: {menu}\n")); + s.push_str(&format!("- API level: {}\n", schema.since)); + s.push_str(&format!("- Deprecated: {}\n", level_text(schema.deprecated))); + s.push_str(&format!("- Writes: {}\n", writes_text(schema.writes))); + s.push_str(&format!("- Cost: {}\n", schema.cost)); + s.push_str(&format!("- Summary: {}\n", text_or_none(schema.summary))); + s.push_str(&format!("- Returns: {}\n\n", text_or_none(schema.returns))); + if schema.params.is_empty() { + s.push_str("No parameters.\n"); + return s; + } + s.push_str("| Parameter | Type | Range | Unit | Default | Required | Since | Deprecated | Description |\n"); + s.push_str("|---|---|---|---|---|---|---|---|---|\n"); + rows("", schema.params, 0, &mut s); + s +} + +/// A table row for each of `params`, and after each one the rows of the members of an object it +/// holds: `edits[].name` for an object in a list, `options.size` for an object. +fn rows(prefix: &str, params: &[Param], depth: usize, out: &mut String) { + for p in params { + let name = if prefix.is_empty() { p.name.to_string() } else { format!("{prefix}.{}", p.name) }; + let (range, unit) = range_and_unit(&p.ty); + out.push_str(&format!( + "| {} | {} | {range} | {unit} | {} | {} | {} | {} | {} |\n", + escape(&name), + type_text(&p.ty, depth), + default_text(p.omitted), + if p.required { "Yes" } else { "No" }, + p.since, + level_text(p.deprecated), + description(p), + )); + if depth < MAX_DEPTH + && let Some((members, path)) = members(&p.ty, name, depth) + { + rows(&path, members, depth + 1, out); + } + } +} + +/// The parameters of the object `ty` holds, directly or as the items of lists, with the path of +/// its members' prefix (`name`, `name[]`, `name[][]`). +fn members(ty: &Type, mut path: String, depth: usize) -> Option<(&'static [Param], String)> { + let mut ty = ty; + for _ in depth..MAX_DEPTH { + match ty { + Type::Object(params) => return Some((params, path)), + Type::Array(item) => { + path.push_str("[]"); + ty = item; + } + _ => return None, + } + } + None +} + +fn type_text(ty: &Type, depth: usize) -> String { + match ty { + Type::Number { .. } => "number".into(), + Type::Integer { .. } => "integer".into(), + Type::Boolean => "boolean".into(), + Type::String => "string".into(), + Type::Enum(names) => format!("one of {}", names.iter().map(|n| format!("\"{}\"", escape(n))).collect::>().join(", ")), + Type::Id => "object id (integer)".into(), + Type::Ids => "list of object ids".into(), + Type::Color => escape("color (a string, [r, g, b] or an object)"), + Type::Point => escape("point ([x, y], two numbers)"), + Type::Object(_) => "object".into(), + Type::Array(_) if depth >= MAX_DEPTH => "list".into(), + Type::Array(item) => format!("list of {}", type_text(item, depth + 1)), + } +} + +/// The range and unit cells of a value of type `ty`. +fn range_and_unit(ty: &Type) -> (String, String) { + let ends = |low: Option, high: Option| { + let both: Vec = low.into_iter().chain(high).collect(); + if both.is_empty() { "None".to_string() } else { both.join(", ") } + }; + match ty { + Type::Number { min, max, unit } => { + let low = min.map(|b| match b { + Bound::Inclusive(a) => format!("at least {a}"), + Bound::Exclusive(a) => format!("more than {a}"), + }); + let high = max.map(|b| match b { + Bound::Inclusive(a) => format!("at most {a}"), + Bound::Exclusive(a) => format!("less than {a}"), + }); + (ends(low, high), unit.map_or("None".to_string(), escape)) + } + Type::Integer { min, max } => (ends(min.map(|a| format!("at least {a}")), max.map(|a| format!("at most {a}"))), "None".into()), + Type::Id => (format!("at least 0, at most {MAX_ID}"), "None".into()), + _ => ("None".into(), "None".into()), + } +} + +fn default_text(omitted: Omitted) -> String { + match omitted { + Omitted::Nothing => "None".into(), + Omitted::Value(json) => format!("{} (JSON)", escape(json)), + Omitted::Note(note) => format!("{} (worked out by the command)", escape(note)), + } +} + +/// The parameter's doc text, and what the schema says about how its value is checked. +fn description(p: &Param) -> String { + let mut parts = Vec::new(); + if !p.doc.is_empty() { + parts.push(escape(p.doc)); + } + if p.null_omitted { + parts.push("null reads as omitted".to_string()); + } + if p.lenient { + parts.push("lenient (a value of another type or out of range is passed to the command, not refused)".to_string()); + } + if parts.is_empty() { "None".to_string() } else { parts.join("; ") } +} + +fn level_text(level: Option) -> String { + level.map_or("None".to_string(), |l| format!("API level {l}")) +} + +fn writes_text(writes: Writes) -> &'static str { + match writes { + Writes::Nothing => "nothing", + Writes::Session => "session", + Writes::Preferences => "preferences", + Writes::Document => "document", + } +} + +fn text_or_none(text: &str) -> String { + if text.is_empty() { "None".to_string() } else { escape(text) } +} + +/// The characters [`escape`] puts a backslash before. +const ESCAPED: &[char] = &['\\', '|', '[', ']', '<', '>', '`', '*', '_', '!', '&', '#', '~', ':', '@']; + +/// `text` as plain Markdown text on one line: each of [`ESCAPED`] with a backslash before it, the +/// `.` after `www` too (so no autolink starts), and each control character as a space. +pub(crate) fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + if c.is_control() { + out.push(' '); + continue; + } + let after_www = out.len().checked_sub(3).and_then(|at| out.as_bytes().get(at..)).is_some_and(|b| b.eq_ignore_ascii_case(b"www")); + if ESCAPED.contains(&c) || (c == '.' && after_www) { + out.push('\\'); + } + out.push(c); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(_: &mut Session, _: &Value) -> Result { + Ok(Value::Null) + } + + fn spec(id: &'static str, menu: &'static [&'static str], schema: Option<&'static ParamSchema>) -> CommandSpec { + CommandSpec { id, label: "Label", menu, shortcut: None, params: "", enabled: always, run, journal: false, schema } + } + + /// The cells of a table row as a GFM table reads them: split at each `|` that has no backslash + /// before it, with the outer pipes and the spaces around each cell taken off. + fn cells(row: &str) -> Vec { + let inner = row.strip_prefix('|').and_then(|r| r.strip_suffix('|')).unwrap_or_else(|| panic!("not a table row: {row}")); + let (mut out, mut cell, mut chars) = (Vec::new(), String::new(), inner.chars()); + while let Some(c) = chars.next() { + match c { + '\\' => { + cell.push(c); + cell.extend(chars.next()); + } + '|' => out.push(std::mem::take(&mut cell).trim().to_string()), + _ => cell.push(c), + } + } + out.push(cell.trim().to_string()); + out + } + + /// What `text` shows as: each escaped character as itself. Panics on a Markdown punctuation + /// character without its backslash, or a backslash before a character that needs none. + fn literal(text: &str) -> String { + let (mut out, mut chars) = (String::new(), text.chars()); + while let Some(c) = chars.next() { + assert!(!ESCAPED.contains(&c) || c == '\\', "`{c}` is not escaped in {text}"); + if c == '\\' { + let next = chars.next().unwrap_or_else(|| panic!("a backslash ends {text}")); + assert!(ESCAPED.contains(&next) || next == '.', "`\\{next}` in {text}"); + out.push(next); + } else { + out.push(c); + } + } + out + } + + /// The shown cells of the row of parameter `name`. + fn row(markdown: &str, name: &str) -> Vec { + let found = markdown.lines().filter(|l| l.starts_with('|')).find(|l| cells(l).first().map(|c| literal(c)).as_deref() == Some(name)); + let row = found.unwrap_or_else(|| panic!("no row for {name} in\n{markdown}")); + let cells = cells(row); + assert_eq!(cells.len(), 9, "{row}"); + cells.iter().map(|c| literal(c)).collect() + } + + /// The text after `- {label}: ` in the section's list. + fn item(markdown: &str, label: &str) -> String { + let prefix = format!("- {label}: "); + let line = markdown.lines().find_map(|l| l.strip_prefix(prefix.as_str())); + literal(line.unwrap_or_else(|| panic!("no {label} in\n{markdown}"))) + } + + /// Two calls give the same bytes, with no document open, and the reference has one section + /// for each built-in command that has a schema, in registry order, ending with this command's. + #[test] + fn the_reference_lists_each_schema_once_in_registry_order_and_is_the_same_each_time() { + let mut s = Session::new(); + let first = s.execute(ID, &json!({})).unwrap(); + let second = s.execute(ID, &Value::Null).unwrap(); + assert_eq!(first, second); + let markdown = first["markdown"].as_str().unwrap(); + assert_eq!(markdown, reference(command_specs()).unwrap()); + assert!(markdown.len() < MAX_BYTES / 10, "{} bytes", markdown.len()); + let headings: Vec = markdown.lines().filter_map(|l| l.strip_prefix("## ")).map(literal).collect(); + let expected: Vec<&str> = command_specs().iter().filter(|c| c.schema.is_some()).map(|c| c.id).collect(); + assert_eq!(headings, expected); + assert_eq!(headings.last().map(String::as_str), Some(ID)); + assert!(expected.contains(&"view.saved.new") && !headings.iter().any(|h| h == "file.new")); + let new_view = &markdown[markdown.find("## view.saved.new").unwrap()..]; + let names: Vec = new_view + .lines() + .skip_while(|l| !l.starts_with("|---")) + .skip(1) + .take_while(|l| l.starts_with('|')) + .map(|l| literal(&cells(l)[0])) + .collect(); + assert_eq!(names, ["name", "center", "zoom", "rotation"]); + let edit = &markdown[markdown.find("## view.saved.edit").unwrap()..]; + assert_eq!(row(edit, "edits[].newName")[8], "null reads as omitted"); + assert_eq!(row(edit, "newName")[8], "rename; null reads as omitted"); + } + + const INNER: &[Param] = + &[Param::new("size", Type::Integer { min: Some(1), max: Some(10) }), Param::new("mode", Type::Enum(&["a", "b"])).defaults_to("\"a\"")]; + + static FULL: ParamSchema = ParamSchema::new( + &[ + Param::new("zoom", Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(64.0)), unit: Some("pt") }) + .doc("1 = 100%"), + Param::new("name", Type::String).default_note("the first free name").null_omitted(), + Param::new("old", Type::Boolean).defaults_to("true").since(2).deprecated(3).lenient(), + Param::new("edits", Type::Array(&Type::Object(INNER))).optional(), + Param::new("ids", Type::Ids).optional(), + Param::new("at", Type::Point).optional(), + Param::new("color", Type::Color).optional(), + Param::new("id", Type::Id).optional(), + Param::new("ratio", Type::Number { min: Some(Bound::Inclusive(-1.5)), max: Some(Bound::Exclusive(2.0)), unit: None }).optional(), + ], + "do the thing", + ) + .returns("{done}") + .writes(Writes::Preferences) + .since(2) + .deprecated(4) + .cost(5); + + /// Each field of a schema shows, nested members in their order under dotted names. + #[test] + fn every_field_of_a_schema_is_shown() { + let markdown = reference(&[spec("test.full", &["View", "Saved"], Some(&FULL))]).unwrap(); + for (label, shown) in [ + ("Label", "Label"), + ("Menu", "View › Saved"), + ("API level", "2"), + ("Deprecated", "API level 4"), + ("Writes", "preferences"), + ("Cost", "5"), + ("Summary", "do the thing"), + ("Returns", "{done}"), + ] { + assert_eq!(item(&markdown, label), shown, "{label}"); + } + let lenient = "lenient (a value of another type or out of range is passed to the command, not refused)"; + let expected: [[&str; 9]; 11] = [ + ["zoom", "number", "more than 0, at most 64", "pt", "None", "Yes", "1", "None", "1 = 100%"], + ["name", "string", "None", "None", "the first free name (worked out by the command)", "No", "1", "None", "null reads as omitted"], + ["old", "boolean", "None", "None", "true (JSON)", "No", "2", "API level 3", lenient], + ["edits", "list of object", "None", "None", "None", "No", "1", "None", "None"], + ["edits[].size", "integer", "at least 1, at most 10", "None", "None", "Yes", "1", "None", "None"], + ["edits[].mode", "one of \"a\", \"b\"", "None", "None", "\"a\" (JSON)", "No", "1", "None", "None"], + ["ids", "list of object ids", "None", "None", "None", "No", "1", "None", "None"], + ["at", "point ([x, y], two numbers)", "None", "None", "None", "No", "1", "None", "None"], + ["color", "color (a string, [r, g, b] or an object)", "None", "None", "None", "No", "1", "None", "None"], + ["id", "object id (integer)", "at least 0, at most 9007199254740991", "None", "None", "No", "1", "None", "None"], + ["ratio", "number", "at least -1.5, less than 2", "None", "None", "No", "1", "None", "None"], + ]; + let names: Vec = + markdown.lines().filter(|l| l.starts_with("| ") && !l.starts_with("| Parameter")).map(|l| literal(&cells(l)[0])).collect(); + assert_eq!(names, expected.map(|r| r[0])); + for want in expected { + assert_eq!(row(&markdown, want[0]), want, "{}", want[0]); + } + } + + const HOSTILE: &str = "a | b [link](https://evil.example) `code` \\ *em* _u_ ![img](x) & ~~s~~ # h www.example.com me@example.com\r\nnext\tline"; + + static ESCAPES: ParamSchema = + ParamSchema::new(&[Param::new("a|b", Type::String).doc(HOSTILE).defaults_to("\"|\"")], HOSTILE).returns(HOSTILE); + + /// Markdown in a schema's text shows as plain text: a description stays in its own cell of a + /// nine-cell row, every punctuation character is escaped, and line breaks and tabs are spaces. + #[test] + fn markdown_in_schema_text_stays_literal_in_its_cell() { + let markdown = reference(&[spec("test.escapes", &["A|B", "[x](y)"], Some(&ESCAPES))]).unwrap(); + let shown = HOSTILE.replace(['\r', '\n', '\t'], " "); + let cells = row(&markdown, "a|b"); + assert_eq!(cells[4], "\"|\" (JSON)"); + assert_eq!(cells[8], shown); + assert_eq!(item(&markdown, "Summary"), shown); + assert_eq!(item(&markdown, "Returns"), shown); + assert_eq!(item(&markdown, "Menu"), "A|B › [x](y)"); + assert!(markdown.contains("www\\.example"), "{markdown}"); + let table: Vec<&str> = markdown.lines().filter(|l| l.starts_with('|')).collect(); + assert_eq!(table.len(), 3, "the header, the delimiter row and one row: {table:?}"); + assert!(!markdown.contains('\r') && !markdown.contains('\t')); + } + + /// A registry with no schema gives the header and a line that says so; a command without a + /// schema adds nothing. + #[test] + fn a_registry_without_schemas_gives_a_document_that_says_so() { + let empty = format!("{HEADER}\nNo commands have parameter schemas.\n"); + assert_eq!(reference(&[]).unwrap(), empty); + assert_eq!(reference(&[spec("test.none", &["View"], None)]).unwrap(), empty); + let one = reference(&[spec("test.none", &[], None), spec("test.full", &[], Some(&FULL)), spec("test.other", &[], None)]).unwrap(); + assert_eq!(one, reference(&[spec("test.full", &[], Some(&FULL))]).unwrap()); + } + + /// A reference of exactly [`MAX_BYTES`] is returned; one byte more is an error naming the + /// command, with no part of the reference. + #[test] + fn a_reference_past_the_limit_is_an_error() { + let with = |summary: String| -> Result { + let schema: &'static ParamSchema = Box::leak(Box::new(ParamSchema::new(&[], Box::leak(summary.into_boxed_str())))); + reference(&[spec("test.big", &[], Some(schema))]) + }; + let base = with("x".into()).unwrap().len(); + let fits = with("x".repeat(MAX_BYTES - base + 1)).unwrap(); + assert_eq!(fits.len(), MAX_BYTES); + let e = with("x".repeat(MAX_BYTES - base + 2)).unwrap_err().to_string(); + assert!(e.contains(ID) && e.contains("larger than 1048576 bytes"), "{e}"); + assert!(e.len() < 200, "{e}"); + } + + /// An unknown key is refused with a parameter error naming it, and the command needs no + /// document. + #[test] + fn an_unknown_parameter_is_refused_naming_it() { + let mut s = Session::new(); + let e = s.execute(ID, &json!({"prefix": "view."})).unwrap_err().to_string(); + assert!(e.contains(ID) && e.contains("`prefix`"), "{e}"); + assert!(s.execute(ID, &json!([])).is_err()); + assert!(s.active().is_none()); + assert!(s.execute(ID, &json!({})).is_ok()); + } + + #[test] + fn escape_marks_each_punctuation_character_and_flattens_control_characters() { + assert_eq!(escape("a|b"), "a\\|b"); + assert_eq!(escape("WWW.x and w.x"), "WWW\\.x and w.x"); + assert_eq!(escape("é\u{7}\u{85}z"), "é z"); + assert_eq!(escape("1.5 > 1"), "1.5 \\> 1"); + } +} diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index 8c225b877b..0b57565af4 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -44,7 +44,7 @@ pub fn specs() -> Vec { "Assets", [], None, - "{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included), format3D: usda|usdz|gltf|obj | null (a 3D asset's mesh format; null for art exported as pictures)}]} the Asset Export panel's assets, in order", + "{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included, with the clips of the groups and layers that hold it), format3D: usda|usdz|gltf|obj | null (a 3D asset's mesh format; null for art exported as pictures)}]} the Asset Export panel's assets, in order", has_doc, list ), @@ -213,7 +213,7 @@ fn add_3d(s: &mut Session, p: &Value) -> Result { ids.dedup(); for id in &ids { let n = d.node(*id).ok_or_else(|| bad(C, format!("no such object {0}", id.0)))?; - if let Err(e) = vectorcraft_render::effects::three_d_meshes(n) { + if let Err(e) = vectorcraft_render::effects::three_d_meshes_in(Some(d), n) { let what = n.name.clone().unwrap_or_else(|| format!("#{}", id.0)); return Err(bad(C, format!("{what} can't be exported in 3D: {e}"))); } @@ -281,7 +281,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { a.nodes.iter().map(|node| d.node(*node).ok_or_else(|| bad(C, format!("no such object {0}", node.0)))).collect::>>()?; // The asset's objects share one budget of triangles. let what = &a.name; - let parts = vectorcraft_render::effects::three_d_meshes_of(nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; + let parts = + vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into()); let mut stem = base.clone(); let mut k = 1; diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 8f36e16f61..a5ff58ddf8 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -165,13 +165,13 @@ pub struct BuiltinBrushLibrary { make: fn() -> BrushLibrary, } -/// The built-in brush libraries, in menu order: original brushes generated in code, one library -/// per kind of brush. +/// The built-in brush libraries, in menu order: original brushes generated in code. pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons }, BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, + BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, ]; /// Built-in library `id`, made once. @@ -378,6 +378,44 @@ fn scatter_shapes() -> BrushLibrary { built("Scatter Shapes", doc, brushes) } +/// Game Trails: art brushes for motion lines and impact streaks (original game HUD / VFX art). +fn game_trails() -> BrushLibrary { + let speed = { + let n = 32; + let half = |x: f64| 2.2 * (1.0 - x / 100.0).powf(1.2).max(0.08); + let xs = |i: usize| 100.0 * i as f64 / n as f64; + let mut pts: Vec = (0..=n).map(xs).map(|x| Point::new(x, -half(x))).collect(); + pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, half(x)))); + PathData::single(SubPath::polyline(&pts, true)) + }; + let dash = group(vec![ + black(shapes::rounded_rectangle(Rect::new(0.0, -1.0, 14.0, 1.0), 1.0)), + black(shapes::rounded_rectangle(Rect::new(22.0, -1.0, 36.0, 1.0), 1.0)), + black(shapes::rounded_rectangle(Rect::new(44.0, -1.0, 58.0, 1.0), 1.0)), + black(shapes::rounded_rectangle(Rect::new(66.0, -1.0, 80.0, 1.0), 1.0)), + black(shapes::rounded_rectangle(Rect::new(88.0, -1.0, 100.0, 1.0), 1.0)), + ]); + let burst = { + // A wedge that flares from a tip at x=0 to a wide end at x=100. + let tip = Point::new(0.0, 0.0); + let top = Point::new(100.0, -6.0); + let bot = Point::new(100.0, 6.0); + PathData::single(SubPath::polyline(&[tip, top, bot], true)) + }; + let zigzag = band(100.0, 1.8, 40, |x| { + let t = (x / 12.5).floor(); + let local = (x / 12.5) - t; + if (t as i32) % 2 == 0 { -3.0 + 6.0 * local } else { 3.0 - 6.0 * local } + }); + let brushes = vec![ + art("Speed Line", black(speed), Colorization::Tints), + art("Dash Trail", dash, Colorization::Tints), + art("Burst Ray", black(burst), Colorization::Tints), + art("Zigzag", black(zigzag), Colorization::Tints), + ]; + built("Game Trails", Document::new(100.0, 100.0), brushes) +} + // ---------- commands ---------- fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo { diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 9cc52c82c8..cf5dedb6bd 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -510,7 +510,7 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result { pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result { let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some())); let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?; - let r = (spec.run)(s, p)?; + let r = crate::cmd::run_checked(s, spec, p)?; let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) }; s.edit("Paintbrush", |d, _| { if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 6d1e7284c9..5ff09dc284 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -115,7 +115,8 @@ pub(crate) fn subpath_selected_segments( let n = sp.anchors.len(); let mut selected_segs = BTreeSet::new(); - let has_explicit_segs = seg_refs.is_some_and(|segments| segments.iter().any(|&(s, _)| s == si)); + // Segments picked anywhere on the path leave anchors out of it, as Clear does. + let has_explicit_segs = seg_refs.is_some_and(|segments| !segments.is_empty()); if has_explicit_segs { if let Some(segments) = seg_refs { for &(s, seg) in segments { @@ -209,6 +210,24 @@ pub(crate) fn extract_direct_selection(node: &Node, selection: &Selection) -> Op if pieces.is_empty() { None } else { Some(pieces) } } +/// Does Copy take `node` unchanged under direct selection, as [`extract_direct_selection`] +/// returning `None` means: no anchors or segments of it are picked, it is not a path, or the +/// picked ones cover every segment? +pub(crate) fn copied_whole(node: &Node, selection: &Selection) -> bool { + let seg_refs = selection.segments.get(&node.id); + let anchor_refs = selection.anchors.get(&node.id); + if seg_refs.is_none() && anchor_refs.is_none() { + return true; + } + let Some(path) = node.path_data() else { return true }; + let (mut total_segs, mut total_selected) = (0, 0); + for (si, sp) in path.subpaths.iter().enumerate() { + total_segs += sp.segment_count(); + total_selected += subpath_selected_segments(sp, si, seg_refs, anchor_refs).len(); + } + total_selected == 0 || total_selected == total_segs +} + impl Clipboard { pub fn is_empty(&self) -> bool { self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty() @@ -233,15 +252,47 @@ impl Clipboard { let d = &*st.doc; let mut nodes = vec![]; let mut source_layers = vec![]; + // Each compound's bounds, measured once however many of its members are copied. + let mut compound_bounds: std::collections::HashMap> = std::collections::HashMap::new(); for id in roots { let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue }; let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone()); let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. }))); + // Gradients fitted to the compound's bounds are pinned there, as a split pins them. + let gradient_box = compound_parent + .filter(|p| p.appearance.has_unplaced_gradient()) + .and_then(|p| *compound_bounds.entry(p.id).or_insert_with(|| p.geometric_bounds())); + // A compound's member or piece copied on its own takes the compound's look (its paint, + // transparency, opacity mask, pixel alignment and fill rule), so it pastes as it looked. + // It is linked to the compound's graphic style while it still has that style's look + // (a gradient pinned to the compound's bounds does not), else to none. let inherit_appearance = |mut piece: Node| { if let Some(parent) = compound_parent - && piece.appearance.items.is_empty() + && let (NodeKind::Compound { rule: compound_rule, .. }, NodeKind::Path { rule, .. }) = (&parent.kind, &mut piece.kind) { + *rule = *compound_rule; piece.appearance = parent.appearance.clone(); + if let Some(bounds) = gradient_box { + piece.appearance.pin_gradients(bounds); + } + piece.opacity = parent.opacity; + piece.blend = parent.blend; + piece.isolate = parent.isolate; + piece.knockout = parent.knockout; + piece.knockout_shape = parent.knockout_shape; + let (mask, pixel_aligned) = (parent.extras().mask.clone(), parent.extras().pixel_aligned); + { + let mut extras = piece.extras_mut(); + extras.mask = mask; + extras.pixel_aligned = pixel_aligned; + } + let link = parent + .extras() + .graphic_style + .and_then(|g| d.graphic_style_by_id(g)) + .filter(|g| super::style::in_sync(&piece, g)) + .map(|g| g.id); + piece.extras_mut().graphic_style = link; } piece }; diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 1d009a6b01..ac082d7a05 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -48,9 +48,9 @@ pub fn specs() -> Vec { "Convert to Grayscale", ["Edit", "Edit Colors"], None, - "{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed, notChanged, warning?}", + "{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert; an embedded image is stored with one gray channel) → {changed, notChanged, warning?}", has_selection, - |s, p| recolor(s, p, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray) + |s, p| recolor_gray(s, p, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray) ), cmd!( "edit.colors.toRGB", @@ -187,6 +187,8 @@ pub(crate) struct Recolor<'a> { /// Maps solid colours and gradient stops with their link and tint in place of `f`. links: Option<&'a LinkMap<'a>>, scope: Scope, + /// Recolored images are stored with one gray channel ([`ImageBlob::map_gray`]). + gray_images: bool, /// Image key → the key of its recoloured copy (`None`: unchanged). images: HashMap>, /// Pattern name → the name of its recoloured copy (`None`: unchanged, or being recoloured). @@ -198,7 +200,17 @@ pub(crate) struct Recolor<'a> { impl<'a> Recolor<'a> { pub(crate) fn new(scope: Scope, f: &'a dyn Fn(Color) -> Color) -> Self { - Self { f, links: None, scope, images: HashMap::new(), patterns: HashMap::new(), new_images: vec![], new_patterns: vec![], changed: 0 } + Self { + f, + links: None, + scope, + gray_images: false, + images: HashMap::new(), + patterns: HashMap::new(), + new_images: vec![], + new_patterns: vec![], + changed: 0, + } } /// A pass that maps only solid colours and gradient stops, with their swatch link and tint @@ -215,7 +227,7 @@ impl<'a> Recolor<'a> { /// A pass that maps colors as this one does, with nothing recolored yet. fn again(&self) -> Self { - Self { links: self.links, ..Self::new(self.scope, self.f) } + Self { links: self.links, gray_images: self.gray_images, ..Self::new(self.scope, self.f) } } /// The entries of `objects` (ids, each with a flag) whose object this pass would change, other @@ -313,10 +325,15 @@ impl<'a> Recolor<'a> { return done.clone(); } let f = self.f; - let new = d.images.get(key)?.map_rgb(|[r, g, b]| { - let [r, g, b, _] = f(Color::rgb8(r, g, b)).to_rgba8(1.0); - [r, g, b] - }); + let blob = d.images.get(key)?; + let new = if self.gray_images { + blob.map_gray(|[r, g, b]| f(Color::rgb8(r, g, b)).to_rgba8(1.0)[0]) + } else { + blob.map_rgb(|[r, g, b]| { + let [r, g, b, _] = f(Color::rgb8(r, g, b)).to_rgba8(1.0); + [r, g, b] + }) + }; let new = new.map(|blob| { let k = blob.content_key(); self.new_images.push((k.clone(), blob)); @@ -400,6 +417,11 @@ pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dy run_pass(s, p, cmd, label, Recolor::new(Scope::of(p), f)) } +/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel. +fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { + run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p), f) }) +} + /// [`recolor`] with solid colours and gradient stops mapped through `links`, with their swatch /// link and tint. pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result { @@ -575,10 +597,11 @@ fn adjust_balance(s: &mut Session, p: &Value) -> Result { other => return Err(bad(C, format!("unknown mode `{other}` (rgb|cmyk|gray|global)"))), }; let convert = bool_or(p, "convert", false); - recolor(s, p, C, "Adjust Colors", &move |c| { + let f = move |c| { let out = adjust(c); if convert { out } else { keep_model(c, out) } - }) + }; + if convert && mode == "gray" { recolor_gray(s, p, C, "Adjust Colors", &f) } else { recolor(s, p, C, "Adjust Colors", &f) } } enum BlendOrder { diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index d9b5784b68..03b171de71 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Color Settings…", ["Edit"], Some("Cmd+Shift+K"), - "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}", + "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", always, color_settings ), @@ -192,6 +192,8 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { st.bpc = switch_or(p, "bpc", st.bpc, C)?; if st != before { cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; + // Saved for the next start when the app attached a settings file (#6335). + s.store_color_settings(&st); touch_all(s); } Ok(settings_json(&st)) diff --git a/crates/engine/src/cmd/css.rs b/crates/engine/src/cmd/css.rs index 1780cf2beb..ed83a01410 100644 --- a/crates/engine/src/cmd/css.rs +++ b/crates/engine/src/cmd/css.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Export CSS", [], None, - "{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of the object's visual bounds, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: .css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once", + "{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of what the object draws, with the clips, masks and effects of the groups and layers that hold it, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: .css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once", has_doc, export ), diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index a561e50998..8c35254494 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -635,6 +635,7 @@ pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) { } }; st.change_unsaved(clear); + st.history.rewrites += 1; for e in st.history.undo.iter_mut().chain(st.history.redo.iter_mut()) { let saved = Arc::ptr_eq(&e.doc, &st.saved_doc); clear(&mut e.doc); diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index a475bc743b..5f8508f4e9 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -183,7 +183,7 @@ pub fn specs() -> Vec { "Lock Guides", ["View", "Guides"], Some("Cmd+Alt+;"), - "{locked?: bool} toggle (or set) the session's guide lock; locking deselects the ruler guides and guide paths in every open document → {locked}", + "{locked?: bool} toggle (or set) the session's guide lock, leaving the lockGuidesByDefault preference as it is; locking deselects the ruler guides and guide paths in every open document; guide.add and a guide dragged out of a ruler still make new guides while locked → {locked}", has_doc, lock_guides ), @@ -277,6 +277,27 @@ impl Session { pub fn guides_locked(&self) -> bool { self.menu.guides_locked } + + /// Set View → Guides → Lock Guides. Locked guides can't stay selected, ruler guides or guide + /// paths, in any open document ([`Session::select`] lets those go in the active one). + pub(crate) fn set_guides_locked(&mut self, locked: bool) { + self.menu.guides_locked = locked; + if !locked { + return; + } + let guides_selected = + self.doc().is_ok_and(|st| !st.selection.guides.is_empty() || st.selection.objects.iter().any(|id| crate::is_guide_path(&st.doc, *id))); + // It fails only without a document, and then no guide is selected. + if guides_selected { + let _ = self.select(|_, sel| sel.guides.clear()); + } + let active = self.active; + for (i, st) in self.docs.iter_mut().enumerate() { + if Some(i) != active && crate::deselect_hidden(&self.menu, &st.doc, &mut st.selection) { + st.revision += 1; + } + } + } } // ---------- Select ---------- @@ -717,21 +738,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result { fn lock_guides(s: &mut Session, p: &Value) -> Result { let v = switch_or(p, "locked", !s.menu.guides_locked, "view.guides.lock")?; - s.menu.guides_locked = v; - // Locked guides can't stay selected, ruler guides or guide paths, in any open document - // ([`Session::select`] lets those go in the active one). - let st = s.doc()?; - if v && (!st.selection.guides.is_empty() || st.selection.objects.iter().any(|id| crate::is_guide_path(&st.doc, *id))) { - s.select(|_, sel| sel.guides.clear())?; - } - if v { - let active = s.active; - for (i, st) in s.docs.iter_mut().enumerate() { - if Some(i) != active && crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection) { - st.revision += 1; - } - } - } + s.set_guides_locked(v); Ok(json!({ "locked": v })) } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 5809835e3b..024ba535b4 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -157,7 +157,7 @@ pub fn specs() -> Vec { "Cut", ["Edit"], Some("Cmd+X"), - "{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected", + "{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected", has_selection_guides_or_artboard_tool, cut ), @@ -166,7 +166,7 @@ pub fn specs() -> Vec { "Copy", ["Edit"], Some("Cmd+C"), - "{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}", + "{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}", has_selection_guides_or_artboard_tool, copy ), @@ -220,7 +220,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides); without ids, refused while an object of a symbol instance's art is selected", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected", has_selection_or_guides, clear ), @@ -931,7 +931,11 @@ fn without_inner(doc: &Document, placed: Vec<(NodeId, Option>)>) -> i }) } -/// The direct-selection flag and resolved root nodes for Copy and Cut operations. +/// The direct-selection flag and resolved root nodes for Copy and Cut operations. A compound-path +/// member selected on its own (whole, with Direct or Group Selection, or by some of its anchors or +/// segments) is taken as itself, so Copy copies it as an ordinary path and Cut removes it alone. The +/// compound is taken whole when it is selected, or when every one of its members is selected whole +/// outside isolation mode; in an isolated compound every member is taken as itself. fn copy_cut_targets(s: &Session) -> Result<(bool, Vec)> { let st = s.doc()?; // The Pen and the Curvature tool leave the anchor they placed or edited selected: Copy takes @@ -940,9 +944,19 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec)> { let in_drawing_tool = matches!(s.tool_id(), "pen" | "curvature") && !picked; let direct = !in_drawing_tool && (!st.selection.anchors.is_empty() || !st.selection.segments.is_empty()); let in_isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); - let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_compound, member| { - in_isolated_compound || (direct && (st.selection.partial(member).is_some() || st.selection.segments.contains_key(&member))) - }); + // A member counts as selected whole when Copy would take it unchanged: no anchors or segments + // of it are picked, the picked ones cover every segment, or a drawing tool's own anchor is + // all that is picked. + let selected: std::collections::HashSet = st.selection.objects.iter().copied().collect(); + let whole = |m: &vectorcraft_doc::Node| selected.contains(&m.id) && (!direct || super::clipboard::copied_whole(m, &st.selection)); + // Worked out once per compound: every selected member asks about its compound. + let checked = std::cell::RefCell::new(std::collections::HashMap::new()); + let all_members_whole = |compound: NodeId| { + *checked.borrow_mut().entry(compound).or_insert_with(|| { + st.doc.node(compound).and_then(|n| n.children()).is_some_and(|members| !members.is_empty() && members.iter().all(|m| whole(m))) + }) + }; + let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |compound, _member| in_isolated_compound || !all_members_whole(compound)); Ok((direct, roots)) } @@ -1016,8 +1030,8 @@ fn cut(s: &mut Session, p: &Value) -> Result { copy(s, p)?; return clear(s, &json!({})); } - // Copy promotes a compound member to its compound. Cut must remove the same objects it - // copied, while Clear on its own deletes exactly the selected members. + // Cut removes the same objects Copy takes: a compound member selected on its own, or the + // whole compound when it is selected or every member is selected whole. let (direct, roots) = copy_cut_targets(s)?; let res = copy(s, p)?; if res.get("copied").and_then(Value::as_u64) == Some(0) { @@ -1045,12 +1059,8 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { 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); - if !has_direct { - d.remove(*id)?; - continue; - } - if node.path_data().is_none() { - d.remove(*id)?; + if !has_direct || node.path_data().is_none() { + remove_leaving_no_empty_compound(d, *id)?; continue; } let original = super::path::deletion_source(d, *id)?; @@ -1063,19 +1073,17 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { let cuts = super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs); if cuts.is_empty() { subpaths.push(sp); - } else { + } else if seg_refs.is_some_and(|segments| !segments.is_empty()) { subpaths.extend(super::path::without_segments(sp, &cuts)); + } else { + // Picked anchors leave the path with their connections, as Clear removes them. + let gone: BTreeSet = anchor_refs.into_iter().flatten().filter_map(|&(s, a)| (s == si).then_some(a)).collect(); + subpaths.extend(super::path::without_anchors(sp, &gone)); } } subpaths.retain(|sp| sp.anchors.len() >= 2); if subpaths.is_empty() { - let parent = d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); - d.remove(*id)?; - if let Some(p) = parent - && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) - { - d.remove(p)?; - } + remove_leaving_no_empty_compound(d, *id)?; } else { survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); } @@ -1089,6 +1097,19 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { ok() } +/// Remove object `id`, and the compound path that held it when it was the compound's last member. +/// A compound left with one member stays a compound path, as after Clear. +fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> { + let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + d.remove(id)?; + if let Some(p) = parent + && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) + { + d.remove(p)?; + } + Ok(()) +} + fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 297279b64d..8bf5c9a3d7 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -280,9 +280,14 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } let item = item_target(s, p, C)?; if effects::is_three_d(id) { - for target in appearance_targets(s, p)? { - let n = s.doc()?.doc.node(target).ok_or(EngineError::NoNode(target))?; - effects::validate_three_d(n, id, &effect.params).map_err(|e| bad(C, e))?; + let targets = appearance_targets(s, p)?; + for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) { + let d = &s.doc()?.doc; + let n = d.node(target).ok_or(EngineError::NoNode(target))?; + // A new effect goes after the item's others. + let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten(); + let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len()))); + effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?; if id == effects::REVOLVE && effects::has_revolve(n) { return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead.")); } @@ -571,7 +576,8 @@ fn set_params(s: &mut Session, p: &Value) -> Result { params["name"] = json!(svg_filter_name(s, xml, C)?); } for &(id, target, index) in &targets { - let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?; + let d = &s.doc()?.doc; + let n = d.node(id).ok_or(EngineError::NoNode(id))?; let effect = n.appearance.effects_at(target).and_then(|fx| fx.get(index)); if warp_id.is_some() && effect.is_some_and(|e| e.id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_none()) { return Err(bad(C, "warpStyle can only edit an applied Warp effect")); @@ -589,7 +595,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result { cur.extend(new); } if visible != Some(false) { - effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?; + effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?; } else { // Hidden, the effect draws nothing, so its object need not fit. The values given are // checked, and after a change of 3D type so is every value it keeps. @@ -865,8 +871,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br // keeps it as its only member). Some((image, false)) => Some(rasterfx::replace_with_image(v, image)), image => { - let m = if container && effects::has_solid(&v) { - // A group's or layer's 3D effect: the shaded faces of its members' solids. + let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) { + // A 3D effect on a group or layer, or on type: the shaded faces of its solids. effects::expand_leaf(d, &v, &mut stroke_art) } else if container { // A group's or layer's own fills and strokes become art among its members. @@ -1002,6 +1008,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod lighting_presets_tests; +#[cfg(test)] +mod three_d_source_tests; + #[cfg(test)] mod three_d_type_tests; diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index e3fca957b8..e4c8d79450 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -130,7 +130,8 @@ fn solid_effects_apply_save_edit_export_expand_and_undo() { } /// #4506: a 3D effect on a group builds a solid from each member, turned about one shared axis; -/// the members stay editable, and a group holding what can't become a solid is refused. +/// the members stay editable. A group holding a clipping group builds from the art it shows, and a +/// group holding what can't become a solid is refused. #[test] fn solid_effects_apply_to_a_group_and_its_members_stay_editable() { for effect in effects::SOLIDS { @@ -151,17 +152,59 @@ fn solid_effects_apply_to_a_group_and_its_members_stay_editable() { s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap(); assert!(!effects::has_solid(&node(&s, g)), "{effect}: expanded"); } - // A clipping group in the group: refused, nothing changed. + // A clipping group in the group: each effect builds from the art it shows. + for effect in effects::SOLIDS { + let (mut s, _, g) = group_with_a_clipping_group(); + s.execute("effect.apply", &json!({"effect": effect, "ids": [g.0], "item": null})).unwrap_or_else(|e| panic!("{effect}: {e}")); + let n = node(&s, g); + assert_eq!(n.children().unwrap().len(), 2, "{effect}: the members stay as they were"); + let art = effects::solid_art_in(Some(&s.doc().unwrap().doc), &n); + assert!(art.is_some_and(|a| a.visual_bounds().is_some()), "{effect}: draws its solid"); + } + // An image in the group: refused, nothing changed. + let (mut s, _, g) = group_with_an_image(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [g.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("Image Trace"), "{err}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); +} + +/// A group of a clipping group (a rectangle clipped by an ellipse) and a rectangle: the session, +/// the clipping group and the group. +fn group_with_a_clipping_group() -> (Session, NodeId, NodeId) { let (mut s, a) = session_with_rect(); let b = s.execute("shape.ellipse", &json!({"x": 120, "y": 120, "width": 60, "height": 60})).unwrap()["id"].clone(); s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap(); - let clip = s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].clone(); + let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); let c = s.execute("shape.rectangle", &json!({"x": 250, "y": 250, "width": 50, "height": 50})).unwrap()["id"].clone(); - s.execute("select.set", &json!({"ids": [clip, c]})).unwrap(); + s.execute("select.set", &json!({"ids": [clip.0, c]})).unwrap(); let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); - let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [g.0], "item": null})).unwrap_err().to_string(); - assert!(err.contains("clipping groups"), "{err}"); - assert!(node(&s, g).appearance.effects.is_empty()); + (s, clip, g) +} + +/// A group of a rectangle and an image: the session, the image and the group. +fn group_with_an_image() -> (Session, NodeId, NodeId) { + let (mut s, a) = session_with_rect(); + let image = s + .edit("Place", |d, _| { + let id = d.alloc_id(); + let img = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 4, + height: 4, + xf: vectorcraft_geom::Affine::translate((250.0, 250.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let (parent, index, _) = d.position(a).unwrap(); + d.insert(parent, index + 1, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(img))))?; + Ok(id) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, image.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + (s, image, g) } /// #4715: type extrudes as its glyph outlines, painted with its characters' colour, and stays @@ -193,6 +236,173 @@ fn type_extrudes_as_its_glyphs_and_stays_editable() { assert_ne!(effects::solid_art(&node(&s, id)).unwrap(), art, "the solid follows the edited text"); } +/// #3617: Revolve takes live type and stays type, updating when the text changes, and saves, +/// exports, expands and undoes as one step. +#[test] +fn type_revolves_as_its_glyphs_and_stays_editable() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": "O", "size": 72})).unwrap(); + let id = NodeId(t["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#cc2200"})).unwrap(); + s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null, "params": {"segments": 16}})).unwrap(); + let n = node(&s, id); + assert!(matches!(n.kind, NodeKind::Text(_)), "still type"); + let art = effects::revolve_art(&n).expect("a surface of the glyphs"); + let mut tinted = false; + art.walk(&mut |c| { + if let Some([r, g, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) { + tinted |= r > g && r > b; + } + }); + assert!(tinted, "shaded from the characters' red"); + let doc = &s.doc().unwrap().doc; + let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); + assert_eq!(effects::revolve_art(restored.node(id).unwrap()).unwrap(), art, "the same art after a save"); + let meshes = effects::three_d_meshes(&n).unwrap(); + assert_eq!(meshes.len(), 1, "one mesh of every contour of the type"); + s.execute("text.setText", &json!({"ids": [id.0], "text": "OO"})).unwrap(); + assert_ne!(effects::revolve_art(&node(&s, id)).unwrap(), art, "the surface follows the edited text"); + s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); + assert!(!effects::has_revolve(&node(&s, id)), "expanded"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(matches!(node(&s, id).kind, NodeKind::Text(_))); + assert!(effects::has_revolve(&node(&s, id))); + // Extrude & Bevel on type expands the same way. + s.execute("effect.remove", &json!({"index": 0, "ids": [id.0], "item": null})).unwrap(); + s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap(); + s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); + assert!(!effects::has_solid(&node(&s, id)), "expanded"); +} + +/// Revolve refuses type with no outlines, and a group with no visible shape, without adding an +/// effect. Extrude & Bevel gives the same reason for empty type. +#[test] +fn revolve_refuses_type_and_groups_without_a_shape() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + for text in ["", " "] { + let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": text, "size": 72})).unwrap(); + let id = NodeId(t["id"].as_u64().unwrap()); + for effect in ["threeD.revolve", "threeD.extrude"] { + let err = s.execute("effect.apply", &json!({"effect": effect, "ids": [id.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("at least two anchors"), "{effect}, {text:?}: {err}"); + assert!(node(&s, id).appearance.effects.is_empty()); + } + } + let (mut s, a) = session_with_rect(); + let b = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + for member in [a.0, b] { + s.execute("select.set", &json!({"ids": [member]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + } + let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("group holding a shape"), "{err}"); + assert!(node(&s, g).appearance.effects.is_empty()); +} + +/// A Revolve on one fill is checked in that fill's paint, and `effect.setParams` on it as well. +#[test] +fn revolve_on_a_fill_is_checked_in_that_fills_paint() { + use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + use vectorcraft_doc::{AppearanceItem, FillLayer}; + let (mut s, id) = session_with_rect(); + // The paint copies of 100 faces reach the 256 MiB budget: 8 segments stay under, 64 pass it. + let count = (256 << 20) / (4 * 100 * std::mem::size_of::()); + let stops = (0..count).map(|i| GradientStop::new(i as f32 / count as f32, Color::rgb(1.0, 0.0, 0.0))).collect(); + let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + s.edit("fills", |d, _| { + let n = d.node_mut(id).unwrap(); + n.appearance.items = + vec![AppearanceItem::Fill(FillLayer::new(ramp)), AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0))))]; + Ok(()) + }) + .unwrap(); + let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": 0})).unwrap_err().to_string(); + assert!(err.contains("simplify the gradient"), "{err}"); + assert!(node(&s, id).appearance.items[0].effects().is_empty()); + s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": 0, "params": {"segments": 8}})).unwrap(); + let err = s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": 0, "params": {"segments": 128}})).unwrap_err().to_string(); + assert!(err.contains("simplify the gradient"), "{err}"); +} + +/// A hidden Revolve still counts as the object's one Revolve: a second one is refused, and the +/// hidden one can be shown again over the geometry effects after it. +#[test] +fn a_second_revolve_is_refused_over_a_hidden_one() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null})).unwrap(); + s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": null, "visible": false})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [id.0], "item": null})).unwrap(); + let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("one Revolve effect"), "{err}"); + let ids: Vec<_> = node(&s, id).appearance.effects.iter().map(|e| e.id.clone()).collect(); + assert_eq!(ids, ["threeD.revolve", "distort.roughen"]); + s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": null, "visible": true})).unwrap(); + assert!(node(&s, id).appearance.effects[0].visible); +} + +/// Revolve on a group sweeps every member about one axis on the left edge of their bounds, keeps +/// each member's paint, follows an edited member, expands and undoes as one step. +#[test] +fn revolve_on_a_group_shares_one_axis_and_members_stay_editable() { + let (mut s, a) = session_with_rect(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#cc2200"})).unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 250, "y": 100, "width": 50, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [b], "color": "#0022cc"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null, "params": {"segments": 16, "rotationX": 90}})).unwrap(); + assert_eq!(node(&s, g).children().unwrap().len(), 2, "the members stay as they were"); + let art = effects::revolve_art(&node(&s, g)).expect("a surface of the members"); + // The axis is the left edge of both members together (x = 100), so the right member's far + // wall sweeps out to 200 pt from it on either side: x = 300 and x = -100. + let bounds = art.visual_bounds().unwrap(); + assert!((bounds.x1 - 300.0).abs() < 2.0 && (bounds.x0 + 100.0).abs() < 2.0, "{bounds:?}"); + let (mut red, mut blue) = (false, false); + art.walk(&mut |c| { + if let Some([r, _, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) { + red |= r > b; + blue |= b > r; + } + }); + assert!(red && blue, "each member keeps its own paint"); + assert_eq!(effects::three_d_meshes(&node(&s, g)).unwrap().len(), 2, "a mesh for each member"); + let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string()); + assert!(vectorcraft_testkit::svg_shapes(&svg) >= 4, "both members exported as vector faces"); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.move", &json!({"dx": -40, "dy": 0})).unwrap(); + assert_ne!(effects::revolve_art(&node(&s, g)).unwrap(), art, "a moved member reshapes the surface"); + s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap(); + assert!(!effects::has_revolve(&node(&s, g)), "expanded"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(effects::has_revolve(&node(&s, g))); +} + +/// A group holding what can't be swept is refused as a whole, and an image is named. A clipping +/// group, alone or in a group, sweeps the art it shows. +#[test] +fn revolve_refuses_a_group_with_a_member_it_can_not_sweep() { + let (mut s, image, g) = group_with_an_image(); + let before = s.doc().unwrap().doc.clone(); + for target in [image, g] { + let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [target.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("Revolve") && err.contains("Image Trace"), "{err}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); + } + for clipping_group_itself in [true, false] { + let (mut s, clip, g) = group_with_a_clipping_group(); + let target = if clipping_group_itself { clip } else { g }; + s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [target.0], "item": null})) + .unwrap_or_else(|e| panic!("{clipping_group_itself}: {e}")); + let art = effects::revolve_art_in(Some(&s.doc().unwrap().doc), &node(&s, target)); + assert!(art.is_some_and(|a| a.visual_bounds().is_some()), "{clipping_group_itself}: draws its surface"); + } +} + /// Scripts from before the Perspective angle give `perspective` as a 0–100 % strength: it is /// stored as the angle that shows the same view, and a later angle replaces an earlier strength. #[test] @@ -581,7 +791,7 @@ fn expand_appearance_makes_each_copy_of_a_transform_an_object() { let copies = n.children().unwrap(); assert_eq!(copies.len(), 3, "the path and its two copies"); let xs: Vec = copies.iter().map(|c| c.geometric_bounds().unwrap().x0).collect(); - assert_eq!(xs, vec![100.0, 250.0, 400.0]); + assert_eq!(xs, vec![400.0, 250.0, 100.0], "the original on top"); for c in copies { assert!(matches!(c.kind, NodeKind::Path { .. }), "{}", c.kind_label()); assert_eq!(fill(c), Some(Color::rgb(1.0, 0.0, 0.0))); @@ -600,10 +810,10 @@ fn expand_appearance_makes_each_copy_of_a_transform_an_object() { s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); let columns = node(&s, id).children().unwrap().to_vec(); assert_eq!(columns.len(), 3); - for (col, x) in columns.iter().zip([100.0, 250.0, 400.0]) { + for (col, x) in columns.iter().zip([400.0, 250.0, 100.0]) { let cells = col.children().unwrap_or_else(|| panic!("a column is a group: {}", col.kind_label())); let ys: Vec<(f64, f64)> = cells.iter().map(|c| (c.geometric_bounds().unwrap().x0, c.geometric_bounds().unwrap().y0)).collect(); - assert_eq!(ys, vec![(x, 100.0), (x, 250.0)]); + assert_eq!(ys, vec![(x, 250.0), (x, 100.0)]); assert!(cells.iter().all(|c| matches!(c.appearance.fill_paint(), Paint::Solid { .. }))); } } diff --git a/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs b/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs new file mode 100644 index 0000000000..122d937b98 --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs @@ -0,0 +1,98 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::Session; + +const TYPES: [&str; 5] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.revolve"]; + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +/// A clipping group, a blend and a symbol instance, each made through its command. +fn sources(s: &mut Session) -> Vec<(&'static str, NodeId)> { + let art = rect(s, 20.0, 20.0, 60.0, 60.0); + let clip = rect(s, 40.0, 10.0, 20.0, 80.0); + select(s, &[art, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let clipped = s.doc().unwrap().selection.objects[0]; + let a = rect(s, 120.0, 20.0, 20.0, 20.0); + let b = rect(s, 200.0, 60.0, 30.0, 30.0); + select(s, &[a, b]); + let blend = id_of(&s.execute("object.blend.make", &json!({})).unwrap()); + let art = rect(s, 20.0, 200.0, 50.0, 40.0); + let instance = id_of(&s.execute("symbol.new", &json!({"name": "Box", "ids": [art.0]})).unwrap()); + vec![("clipping group", clipped), ("blend", blend), ("symbol instance", instance)] +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +#[test] +fn every_three_d_type_applies_to_clipping_groups_blends_and_symbol_instances_in_one_undo_step() { + for id in TYPES { + let mut s = session(); + for (what, target) in sources(&mut s) { + select(&mut s, &[target]); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("effect.apply", &json!({"effect": id, "item": null})).unwrap_or_else(|e| panic!("{id} on a {what}: {e}")); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{id} on a {what}"); + let n = s.doc().unwrap().doc.node(target).unwrap().clone(); + assert_eq!(n.appearance.effects.iter().filter(|e| e.id == id).count(), 1, "{id} on a {what}"); + // The object stays what it is, and the effect draws its solid. + assert!(!matches!(n.kind, NodeKind::Path { .. }), "{id} on a {what}"); + let d = &s.doc().unwrap().doc; + let art = vectorcraft_render::effects::revolve_art_in(Some(d), &n).or_else(|| vectorcraft_render::effects::solid_art_in(Some(d), &n)); + assert!(art.is_some_and(|a| a.visual_bounds().is_some()), "{id} on a {what} draws its solid"); + // Edited through the dialog's command too. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"rotationY": 20.0}})) + .unwrap_or_else(|e| panic!("{id} on a {what}: {e}")); + } + } +} + +#[test] +fn a_group_holding_an_image_refuses_every_three_d_type_and_names_image_trace() { + let mut s = session(); + let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0); + let image = s + .edit("Place", |d, _| { + let id = d.alloc_id(); + let img = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 4, + height: 4, + xf: vectorcraft_geom::Affine::translate((100.0, 100.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let (parent, index, _) = d.position(a).unwrap(); + d.insert(parent, index + 1, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(img))))?; + Ok(id) + }) + .unwrap(); + select(&mut s, &[a, image]); + s.execute("object.group", &json!({})).unwrap(); + for target in [image, s.doc().unwrap().selection.objects[0]] { + select(&mut s, &[target]); + for id in TYPES { + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("effect.apply", &json!({"effect": id, "item": null})).unwrap_err().to_string(); + assert!(err.contains("Object › Image Trace › Make"), "{id}: {err}"); + assert_eq!(s.doc().unwrap().doc, before, "{id}: nothing changed"); + } + } +} diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 8834e6a741..546b5a8258 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -25,7 +25,7 @@ use super::edit::selected_roots; use super::menucmds::{run_raw, squash}; use super::object::as_clipping_path; use super::pathops::{assemble, node_path, outline_strokes, replace_leaves, styled_copy, with_transparency}; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, f64_or, has_selection, str_param}; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selection, number_or, switch_or, text_param}; const C: &str = "object.expand"; /// Expand Gradient To → Specify … Objects: the default and the most. @@ -101,11 +101,11 @@ enum GradientTo { impl GradientTo { fn parse(p: &Value) -> Result { - let steps = f64_or(p, "steps", DEFAULT_STEPS as f64).round(); + let steps = number_or(p, "steps", DEFAULT_STEPS as f64, C)?.round(); if !(1.0..=MAX_STEPS as f64).contains(&steps) { return Err(bad(C, format!("steps must be 1..{MAX_STEPS}"))); } - match str_param(p, "gradient").unwrap_or("objects") { + match text_param(p, "gradient", C)?.unwrap_or("objects") { "objects" => Ok(Self::Objects(steps as u32)), "mesh" => Ok(Self::Mesh), _ => Err(bad(C, "gradient must be \"objects\" or \"mesh\"")), @@ -236,9 +236,9 @@ fn expand(s: &mut Session, p: &Value) -> Result { } fn expand_steps(s: &mut Session, p: &Value) -> Result { - let object = bool_or(p, "object", true); - let fill = bool_or(p, "fill", true); - let stroke = bool_or(p, "stroke", true); + let object = switch_or(p, "object", true, C)?; + let fill = switch_or(p, "fill", true, C)?; + let stroke = switch_or(p, "stroke", true, C)?; let to = GradientTo::parse(p)?; let from = s.doc()?.history.undo.len(); let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?); diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index b913720f10..04a443ed4c 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -184,6 +184,8 @@ mod tests_batch; #[cfg(test)] mod tests_screens; #[cfg(test)] +mod tests_selexport; +#[cfg(test)] mod tests_text; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index ce7a82d2b6..81e8168d06 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Serialize Document", [], None, - "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in their layers)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", + "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", has_doc, export::serialize ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path", has_doc, export::export ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Export Selection…", ["File"], None, - "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", + "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", has_selection, export::export_selection ), diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 0869ad850a..02dda6f0f0 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -94,27 +94,63 @@ pub fn export_source<'a>(st: &'a DocState, p: &Value) -> Result) -> Option { +/// The layers of `doc` with only the objects in `keep` (whole, with everything inside them), each +/// in the layers, groups and compound paths that hold it. Those keep what they apply to the object +/// on the canvas: their clipping paths, opacity masks, effects, opacity and blend modes. An object +/// of a blend, envelope, repeat or intertwine goes in on its own, without the art made from it. With +/// `shown`, the layers and groups that hold the objects are visible, and those layers print and are +/// not template layers. +fn enclosed(doc: &Document, keep: &HashSet, shown: bool) -> Vec> { + let holders: HashSet = keep.iter().filter_map(|id| doc.ancestry(*id)).flatten().filter(|id| !keep.contains(id)).collect(); + let mut out = vec![]; + for l in &doc.layers { + selected_part(l, keep, &holders, shown, &mut out); + } + out +} + +/// The parts of `n` in `keep` (whole, with everything inside them), added to `out`: `n` itself, or +/// `n` with only those parts when it is one of their `holders`, made visible, printable and not a +/// template with `shown`. +fn selected_part(n: &Arc, keep: &HashSet, holders: &HashSet, shown: bool, out: &mut Vec>) { if keep.contains(&n.id) { - return Some(n.clone()); + out.push(n.clone()); + return; + } + let Some(children) = n.children().filter(|_| holders.contains(&n.id)) else { return }; + let mut kept = vec![]; + for c in children { + selected_part(c, keep, holders, shown, &mut kept); + } + if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }) { + out.extend(kept); + return; } - let children = n.children()?; - let mut kept: Vec> = children.iter().filter_map(|c| selected_part(c, keep).map(Arc::new)).collect(); if kept.is_empty() { - return None; + return; } - let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }); - if let Some(first) = children.first().filter(|f| clip && kept.first().is_none_or(|k| k.id != f.id)) { + // A clipping group or layer keeps its clipping path; a Shaper group its source art, which + // draws nothing. + let first_stays = n.clips() || n.extras().shaper.is_some(); + if let Some(first) = children.first().filter(|f| first_stays && kept.first().is_none_or(|k| k.id != f.id)) { kept.insert(0, first.clone()); } - let mut out = n.clone(); - *out.children_mut()? = kept; - Some(out) + let mut part = Node::clone(n); + if let Some(ch) = part.children_mut() { + *ch = kept; + } + if shown { + part.visible = true; + if let NodeKind::Layer { template, printable, .. } = &mut part.kind { + *template = false; + *printable = true; + } + } + out.push(Arc::new(part)); } /// `doc` with only the art over `rect` (an artboard): objects whose visual bounds miss it are left @@ -126,13 +162,20 @@ fn selected_part(n: &Node, keep: &HashSet) -> Option { /// holds a symbol instance also stays when what the canvas paints for it reaches `rect` /// ([`vectorcraft_render::painted_bounds`]: the effects in the symbols' art and its own effects). A /// clipping layer keeps every object, its clipping path among them. An artboard's file then holds -/// its own art, not a whole document of artboards. -pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document { - fn kept(n: &Arc, doc: &Document, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect) -> Option> { +/// its own art, not a whole document of artboards. `renderer` measures the 3D art, and keeps it for +/// the next artboard of the same document. +pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Document { + fn kept( + n: &Arc, + doc: &Document, + symbols: &SymbolBoxes, + rect: vectorcraft_geom::Rect, + renderer: &mut vectorcraft_render::Renderer, + ) -> Option> { if matches!(n.kind, NodeKind::Layer { clip: false, .. }) { let mut layer = Node::clone(n); let children = layer.children_mut()?; - *children = children.iter().filter_map(|c| kept(c, doc, symbols, rect)).collect(); + *children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect(); return Some(Arc::new(layer)); } // A group that doesn't clip keeps only its members over the artboard, so art gathered in one @@ -141,19 +184,18 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() { let mut group = Node::clone(n); let children = group.children_mut()?; - *children = children.iter().filter_map(|c| kept(c, doc, symbols, rect)).collect(); + *children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect(); return (!children.is_empty()).then(|| Arc::new(group)); } let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1; let mut holds_instance = false; n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. })); - let drawn = || vectorcraft_render::effect_bounds(symbols, n).is_some_and(over); let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over); - (n.visual_bounds_with(symbols).is_none_or(over) || drawn() || painted()).then(|| n.clone()) + (n.visual_bounds_with(symbols).is_none_or(over) || renderer.effect_bounds(symbols, n).is_some_and(over) || painted()).then(|| n.clone()) } let symbols = doc.symbol_boxes().with_brush_art(); let mut d = doc.clone(); - d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect)).collect(); + d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect(); d } @@ -196,7 +238,7 @@ fn expand_presets<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(Cow<'a, Document>, bool)> { if f.id == "txt" && bool_or(p, "selectionOnly", false) { - let doc = selection(s, cmd)?.0; + let doc = selection(s, cmd, true)?.0; let display_doc_title = super::has_own_title(&doc); return Ok((Cow::Owned(doc), display_doc_title)); } @@ -206,11 +248,21 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title)) } -/// The selected objects (not on template layers) alone on one layer, with one artboard: their -/// visual bounds. -fn selection(s: &mut Session, cmd: &str) -> Result<(Document, vectorcraft_geom::Rect)> { +/// The selected objects (not on template layers) in the layers and groups that hold them +/// ([`isolated`]), with one artboard: their crop. With `text`, the objects alone on one layer, so a +/// text export holds the type of the selected objects and not that of a clipping path around them. +fn selection(s: &mut Session, cmd: &str, text: bool) -> Result<(Document, vectorcraft_geom::Rect)> { let ids = selected_artwork(s)?; - isolated(&s.doc()?.doc, &ids, "Selection").ok_or_else(|| bad(cmd, "select something to export")) + let doc = &s.doc()?.doc; + let (mut d, bounds) = isolated(doc, &ids, "Selection").ok_or_else(|| bad(cmd, "select something to export"))?; + if text { + let mut layer = Node::layer(d.alloc_id(), "Selection", vectorcraft_doc::LayerColor::Preset(0)); + if let Some(ch) = layer.children_mut() { + *ch = ids.iter().filter_map(|id| doc.node(*id).cloned().map(Arc::new)).collect(); + } + d.layers = vec![Arc::new(layer)]; + } + Ok((d, bounds)) } /// The selected objects (their top-most selected ancestors) that are artwork: those on template @@ -225,25 +277,30 @@ pub(crate) fn selected_artwork(s: &Session) -> Result> { Ok(ids.into_iter().filter(|id| !on_template(*id)).collect()) } -/// The crop of an export of objects `ids` of `doc` alone: the bounds the renderer measures for what -/// it draws for them, their effects included ([`vectorcraft_render::effect_bounds`]; symbol -/// instances are measured by their art), `None` when they have none. +/// The crop of an export of objects `ids` of `doc` alone ([`isolated`]): the bounds the renderer +/// measures for what it draws for them, their effects included ([`vectorcraft_render::effect_bounds`]; +/// symbol instances are measured by their art), with what the layers and groups that hold them +/// apply (a clipping group or layer is measured by its clip), `None` when they have none. pub(crate) fn export_crop(doc: &Document, ids: &[NodeId]) -> Option { - let symbols = doc.symbol_boxes(); - ids.iter().filter_map(|id| vectorcraft_render::effect_bounds(&symbols, doc.node(*id)?)).reduce(|a, b| a.union(b)) + isolated_art(doc, ids).1 } -/// Objects `ids` of `doc` alone on one layer (in that order, back to front), with one artboard -/// named `name`: their [`export_crop`] (`None` when they have none). +/// The layers of [`isolated`] and their crop. +fn isolated_art(doc: &Document, ids: &[NodeId]) -> (Vec>, Option) { + let keep: HashSet = ids.iter().copied().collect(); + let layers = enclosed(doc, &keep, true); + let symbols = doc.symbol_boxes(); + let bounds = layers.iter().filter_map(|l| vectorcraft_render::effect_bounds(&symbols, l)).reduce(|a, b| a.union(b)); + (layers, bounds) +} + +/// Objects `ids` of `doc` alone, each in the layers and groups that hold it ([`enclosed`], made +/// visible), with one artboard named `name`: their [`export_crop`] (`None` when they have none). pub(crate) fn isolated(doc: &Document, ids: &[NodeId], name: &str) -> Option<(Document, vectorcraft_geom::Rect)> { - let bounds = export_crop(doc, ids)?; - let nodes: Vec> = ids.iter().filter_map(|id| doc.node(*id).cloned().map(Arc::new)).collect(); + let (layers, bounds) = isolated_art(doc, ids); + let bounds = bounds?; let mut d = single_artboard(doc, bounds, name); - let mut layer = Node::layer(d.alloc_id(), name, vectorcraft_doc::LayerColor::Preset(0)); - if let Some(ch) = layer.children_mut() { - *ch = nodes; - } - d.layers = vec![Arc::new(layer)]; + d.layers = layers; Some((d, bounds)) } @@ -259,7 +316,7 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result { let f = writable(C, str_param(p, "format"), path)?; let expanded = expand_presets(s, C, p)?; let p = with_black_output(s, &expanded); - let (d, bounds) = selection(s, C)?; + let (d, bounds) = selection(s, C, f.id == "txt")?; // The encoder's warnings (options accepted but not applied, features approximated or left // out), as document.export reports them. let (bytes, warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?; diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 573a9ee165..23aeb83bb0 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -125,7 +125,7 @@ const BACKGROUND: FormatOption = FormatOption { name: "background", ty: "string", default: "\"transparent\"", - description: "transparent, white, black or a colour such as \"#ff8800\" (JPEG: white when transparent)", + description: "transparent, white, black or a colour such as \"#ff8800\" (JPEG: white when transparent); drawn under the finished art, so blend modes do not read it", }; const ANTI_ALIAS: FormatOption = FormatOption { diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 2387088b3f..e0acc2d52d 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), @@ -334,6 +334,8 @@ fn encode_carrying_at( let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect()); let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?; let doc = &*filled; + // A page the file can't hold fails the export before the thumbnails and the flattening. + vectorcraft_pdf::check_page_sizes(doc, &opts).map_err(|e| pdf_error(cmd, e))?; if opts.settings.thumbnails { opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?; } diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 56bfd0f7b6..3123fdcfb1 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -180,9 +180,11 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + s +} + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +fn id(v: &Value) -> u64 { + v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")) +} + +/// A red 300 pt square at (100, 100) clipped by a 200 pt circle at (150, 150): (square, clip group). +fn clipped(s: &mut Session) -> (u64, u64) { + let square = id(&run(s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300}))); + run(s, "paint.setFill", json!({"color": "#ff0000"})); + let circle = id(&run(s, "shape.ellipse", json!({"x": 150, "y": 150, "width": 200, "height": 200}))); + let group = id(&run(s, "object.clippingMask.make", json!({"ids": [circle, square]}))); + (square, group) +} + +fn b64(v: &Value) -> Vec { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap_or_else(|| panic!("no dataBase64 in {v}"))).unwrap() +} + +fn rect_of(v: &Value) -> Rect { + let n = |i: usize| v[i].as_f64().unwrap_or_else(|| panic!("bad bounds {v}")); + Rect::new(n(0), n(1), n(0) + n(2), n(1) + n(3)) +} + +/// What the canvas draws of the whole document over `r`, at 1 px per point. +fn canvas(s: &Session, r: Rect) -> image::RgbaImage { + let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, r, 1.0, false); + image::load_from_memory(&img.to_png().unwrap()).unwrap().to_rgba8() +} + +/// The pixels of `png` that differ from `want` by more than 64 in a channel (anti-aliased edges +/// differ by less), and every pixel when the sizes differ. +fn differing(png: &[u8], want: &image::RgbaImage) -> usize { + let got = image::load_from_memory(png).unwrap().to_rgba8(); + if got.dimensions() != want.dimensions() { + return (want.width() * want.height()) as usize; + } + got.pixels().zip(want.pixels()).filter(|(a, b)| a.0.iter().zip(b.0.iter()).any(|(x, y)| x.abs_diff(*y) > 64)).count() +} + +/// Export Selection of what is selected, as a PNG, matches the canvas over its crop: fewer than 200 +/// pixels differ (anti-aliased edges), or 200 times `edges` with [`selection_png_matches_canvas_with`]. +fn selection_png_matches_canvas(s: &mut Session, want: Rect, what: &str) { + selection_png_matches_canvas_with(s, want, what, 1); +} + +fn selection_png_matches_canvas_with(s: &mut Session, want: Rect, what: &str, edges: usize) { + let r = run(s, "document.exportSelection", json!({"format": "png", "scale": 1})); + let got = rect_of(&r["bounds"]); + assert!((got.x0 - want.x0).abs() < 1.5 && (got.y0 - want.y0).abs() < 1.5, "{what}: crop {got:?}, want {want:?}"); + assert!((got.width() - want.width()).abs() < 3.0 && (got.height() - want.height()).abs() < 3.0, "{what}: crop {got:?}, want {want:?}"); + let off = differing(&b64(&r), &canvas(s, got)); + assert!(off < 200 * edges, "{what}: {off} pixels differ from the canvas"); +} + +#[test] +fn export_selection_of_a_clipped_object_keeps_its_clip() { + let mut s = session(); + let (square, _) = clipped(&mut s); + run(&mut s, "select.set", json!({"ids": [square]})); + selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "the square alone"); + let svg = b64(&run(&mut s, "document.exportSelection", json!({"format": "svg"}))); + let text = String::from_utf8_lossy(&svg); + assert!(text.contains(" 352.0 && got.y1 > 352.0, "the crop takes in the clip group's shadow: {got:?}"); + assert!(differing(&b64(&r), &canvas(&s, got)) < 200, "with the shadow"); + run(&mut s, "edit.undo", json!({})); + // An opacity mask on the clip group. + let mask = id(&run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300}))); + run( + &mut s, + "paint.setFill", + json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]}}), + ); + run(&mut s, "transparency.makeOpacityMask", json!({"ids": [mask, group]})); + run(&mut s, "select.set", json!({"ids": [square]})); + let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1})); + let got = rect_of(&r["bounds"]); + assert!(differing(&b64(&r), &canvas(&s, got)) < 200, "with an opacity mask on the clip group"); +} + +#[test] +fn export_selection_across_clip_groups_and_of_whole_ones() { + let mut s = session(); + let (a, ga) = clipped(&mut s); + let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 90, "height": 90}))); + let c = id(&run(&mut s, "shape.rectangle", json!({"x": 420, "y": 420, "width": 50, "height": 50}))); + let gb = id(&run(&mut s, "object.clippingMask.make", json!({"ids": [c, b]}))); + // A member of each clip group: each keeps its own clip. + run(&mut s, "select.set", json!({"ids": [a, b]})); + selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 470.0, 470.0), "a member of each of two clip groups"); + // The clip groups themselves. + run(&mut s, "select.set", json!({"ids": [ga, gb]})); + selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 470.0, 470.0), "two clip groups"); + // Nested clip groups: the inner group's member is clipped by both, cropped to the outer clip. + let strip = id(&run(&mut s, "shape.rectangle", json!({"x": 0, "y": 200, "width": 500, "height": 100}))); + run(&mut s, "object.clippingMask.make", json!({"ids": [strip, ga]})); + run(&mut s, "select.set", json!({"ids": [a]})); + selection_png_matches_canvas(&mut s, Rect::new(0.0, 200.0, 500.0, 300.0), "a member of nested clip groups"); +} + +#[test] +fn a_selected_clipping_path_and_a_blend_object_export_on_their_own() { + let mut s = session(); + let (square, group) = clipped(&mut s); + let circle = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap()[0].id.0; + assert_ne!(circle, square); + // The clipping path alone: the clip group's other art stays out. + run(&mut s, "select.set", json!({"ids": [circle]})); + let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1})); + let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8(); + assert_eq!(img.dimensions(), (200, 200), "cropped to the clipping path"); + assert!(!img.pixels().any(|p| p[0] > 200 && p[1] < 80 && p[3] > 0), "the clipped square is left out"); + // An object of a blend goes in on its own, without the blend's steps. + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + let a = id(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 60}))); + let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 60, "height": 60}))); + run(&mut s, "select.set", json!({"ids": [a, b]})); + run(&mut s, "object.blend.make", json!({})); + run(&mut s, "select.set", json!({"ids": [a]})); + let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1})); + let got = rect_of(&r["bounds"]); + assert!(got.x1 < 90.0 && got.y1 < 90.0, "the blend object's own bounds: {got:?}"); + let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8(); + let centre = img.get_pixel(img.width() / 2, img.height() / 2); + assert!(centre[0] > 200 && centre[3] > 200, "the object is drawn: {centre:?}"); +} + +#[test] +fn a_css_picture_of_a_clipped_object_is_clipped() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + let star = id(&run(&mut s, "shape.star", json!({"cx": 250, "cy": 250, "radius1": 150, "radius2": 70, "points": 5}))); + let circle = id(&run(&mut s, "shape.ellipse", json!({"x": 200, "y": 200, "width": 100, "height": 100}))); + run(&mut s, "object.clippingMask.make", json!({"ids": [circle, star]})); + let r = run(&mut s, "css.export", json!({"ids": [star], "rasterize": true, "unnamed": true})); + let image = r["images"].as_array().and_then(|i| i.first()).unwrap_or_else(|| panic!("no picture: {r}")); + let png = b64(image); + let size = image::load_from_memory(&png).unwrap().to_rgba8().dimensions(); + assert_eq!(size, (100, 100), "the picture is cropped to the clip"); + assert!(differing(&png, &canvas(&s, Rect::new(200.0, 200.0, 300.0, 300.0))) < 100, "the picture matches the canvas"); +} + +#[test] +fn an_asset_on_a_hidden_layer_is_drawn_clipped() { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id.0; + let (square, _) = clipped(&mut s); + let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap(); + run(&mut s, "layer.setProps", json!({"id": layer, "visible": false})); + let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]})); + let img = image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8(); + assert_eq!(img.dimensions(), (200, 200), "cropped to the clip"); + let (centre, corner) = (img.get_pixel(100, 100), img.get_pixel(3, 3)); + assert!(centre[0] > 200 && centre[3] > 200, "the square is drawn: {centre:?}"); + assert_eq!(corner[3], 0, "outside the circle stays clear: {corner:?}"); +} + +#[test] +fn export_for_screens_and_assets_by_selection_keep_the_clip() { + let mut s = session(); + let (square, _) = clipped(&mut s); + run(&mut s, "select.set", json!({"ids": [square]})); + let r = run(&mut s, "document.exportForScreens", json!({"selection": "one", "formats": [{"format": "png", "scale": 1}, {"format": "svg"}]})); + let want = canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0)); + let png = r["files"].as_array().unwrap().iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(".png"))).unwrap(); + assert!(differing(&b64(png), &want) < 200, "Export for Screens by selection: {}", png["name"]); + let svg = r["files"].as_array().unwrap().iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(".svg"))).unwrap(); + let text = String::from_utf8(b64(svg)).unwrap(); + assert!(text.contains(" usize { + image::load_from_memory(png).unwrap().to_rgba8().pixels().filter(|p| p[0] > 200 && p[1] < 80 && p[3] > 200).count() +} + +#[test] +fn a_selection_on_a_non_printing_layer_exports_to_pdf() { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id.0; + let (square, _) = clipped(&mut s); + run(&mut s, "layer.setProps", json!({"id": layer, "printable": false})); + run(&mut s, "select.set", json!({"ids": [square]})); + let pdf = b64(&run(&mut s, "document.exportSelection", json!({"format": "pdf", "createLayers": false, "preserveEditing": false}))); + let mut t = Session::new(); + run(&mut t, "document.open", json!({"name": "sel.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)})); + let page = t.doc().unwrap().doc.artboards[0].rect; + let mut png = vec![]; + canvas(&t, page).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + assert!(red(&png) > 20_000, "the PDF draws the square: {} red pixels", red(&png)); + assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 300, "the PDF draws what the canvas draws"); +} + +#[test] +fn export_for_screens_of_layers_draws_them_as_the_canvas_does() { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id.0; + clipped(&mut s); + // A layer at 50% opacity: its art is drawn at 50%. + run(&mut s, "transparency.set", json!({"ids": [layer], "opacity": 50})); + let r = run(&mut s, "document.exportForScreens", json!({"layers": [layer], "formats": [{"format": "png", "scale": 1}]})); + let png = b64(&r["files"][0]); + assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 200, "the layer's opacity applies"); + // A template layer's art is still drawn. + run(&mut s, "transparency.set", json!({"ids": [layer], "opacity": 100})); + run(&mut s, "layer.setProps", json!({"id": layer, "template": true})); + let r = run(&mut s, "document.exportForScreens", json!({"layers": [layer], "formats": [{"format": "png", "scale": 1}, {"format": "svg"}]})); + let files = r["files"].as_array().unwrap(); + let file = |ext: &str| b64(files.iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(ext))).unwrap()); + assert!(red(&file(".png")) > 20_000, "the template layer's art is drawn: {} red pixels", red(&file(".png"))); + assert!(String::from_utf8(file(".svg")).unwrap().contains(" Result { super::panelcmds::refuse_locked(d, &indices)?; } let mut fits = vec![]; + // One renderer measures every artboard: each 3D solid is built once. + let mut renderer = vectorcraft_render::Renderer::new(); for i in unlocked { let was = d.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?; - if let Some(b) = vectorcraft_render::encode::art_bounds_on(d, was) { + if let Some(b) = renderer.art_bounds_on(d, was) { // At least 1 pt a side, as `rect_from` makes Artboard Options' sizes. fits.push((i, was, Rect::new(b.x0, b.y0, b.x0 + b.width().max(1.0), b.y0 + b.height().max(1.0)))); } diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs index 87a7af3578..70c2d9f348 100644 --- a/crates/engine/src/cmd/live/mesh.rs +++ b/crates/engine/src/cmd/live/mesh.rs @@ -49,10 +49,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result { match n.appearance.fill_paint() { // The points take the colours the gradient paints there. Paint::Gradient(g) => { - path.bounds().and_then(|b| GradientMesh::for_path_with(&path, rows, cols, &*gradient_sampler(&g, b, model))).map(|mut m| { - m.highlight(app, highlight); - m - }) + path.bounds().and_then(|b| GradientMesh::for_path_shaded(&path, rows, cols, &*gradient_sampler(&g, b, model), app, highlight)) } p => GradientMesh::for_path(&path, rows, cols, p.color().unwrap_or(Color::WHITE), app, highlight), } diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 6d8e82e8d7..0a4c93dc5e 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -203,10 +203,11 @@ pub(crate) fn whole_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result< } } -/// Run a command's implementation without the enablement check or journaling. +/// Run a command's implementation without the enablement check or journaling. A command with a +/// parameter schema runs with its params checked ([`super::run_checked`]). pub(crate) fn run_raw(s: &mut Session, id: &str, p: &Value) -> Result { let c = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; - super::run_spec(s, c, p) + super::run_checked(s, c, p) } /// Merge the undo entries pushed since the history had `from` entries into one labelled step. @@ -952,6 +953,40 @@ fn polygon_path(pts: &[Point]) -> PathData { PathData::single(vectorcraft_geom::SubPath::new(pts.iter().map(|p| Anchor::corner(*p)).collect(), true)) } +/// The part of an image under `r` (in document space) copied out of its pixels, as PNG bytes, with its size and +/// placement. `None` when the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or +/// `r` not on the pixel grid), so the caller draws it instead. +fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(Vec, u32, u32, Affine)> { + let blob = doc.images.get(&im.key)?; + let [a, b, c, d, _, _] = im.xf.as_coeffs(); + if blob.is_cmyk() || b.abs() > 1e-9 || c.abs() > 1e-9 || a.abs() < 1e-9 || d.abs() < 1e-9 { + return None; + } + let inv = im.xf.inverse(); + let (p0, p1) = (inv * Point::new(r.x0, r.y0), inv * Point::new(r.x1, r.y1)); + // Only a rect on the pixel grid is cut from the pixels; one between pixels keeps its exact bounds by being drawn. + // Checked before decoding, so an off-grid crop of a large image doesn't decode it for nothing. + let on_grid = |v: f64| (v - v.round()).abs() < 1e-3; + if ![p0.x, p0.y, p1.x, p1.y].into_iter().all(on_grid) { + return None; + } + let px = decode_rgba("object.cropImage", blob).ok()?; + let (w, h) = px.dimensions(); + if w == 0 || h == 0 || (w, h) != (im.width, im.height) { + return None; + } + let lo = |v: f64, max: u32| v.round().clamp(0.0, f64::from(max)) as u32; + let (x0, x1) = (lo(p0.x.min(p1.x), w), lo(p0.x.max(p1.x), w)); + let (y0, y1) = (lo(p0.y.min(p1.y), h), lo(p0.y.max(p1.y), h)); + if x1 <= x0 || y1 <= y0 { + return None; + } + let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image(); + let mut png = Vec::new(); + cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))) +} + fn crop_image(s: &mut Session, p: &Value) -> Result { const C: &str = "object.cropImage"; let st = s.doc()?; @@ -992,6 +1027,11 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { if (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6 { return Err(bad(C, "nothing to crop")); } + // A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled. + if let Some((png, cw, ch, xf)) = crop_pixels(&st.doc, im, r) { + put_pixels(s, id, png, cw, ch, xf)?; + return Ok(json!({ "id": id.0, "width": cw, "height": ch })); + } // Keep the image's pixel density. let scale = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9)); let mut bare = node.clone(); @@ -1026,6 +1066,27 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The image's pixels as RGBA, held to the allowance opening a raster has. +fn decode_rgba(c: &str, blob: &vectorcraft_doc::ImageBlob) -> Result { + // Print rasters run to gigabytes decoded: the same allowance opening them has. + let reader = || { + image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())) + .with_guessed_format() + .map_err(|_| bad(c, "the image's pixels can't be read")) + }; + // The image's size as RGBA, read from its header, is held to that allowance before anything + // is decoded (#1717). + let (w, h) = reader()?.into_dimensions().map_err(|e| bad(c, format!("the image's pixels can't be read: {e}")))?; + if u64::from(w) * u64::from(h) > crate::cmd::fileio::MAX_RASTER_ALLOC / 4 { + return Err(bad(c, format!("an image of {w} × {h} pixels is too large to draw"))); + } + let mut reader = reader()?; + let mut limits = image::Limits::default(); + limits.max_alloc = Some(crate::cmd::fileio::MAX_RASTER_ALLOC); + reader.limits(limits); + Ok(reader.decode().map_err(|e| bad(c, format!("the image's pixels can't be read: {e}")))?.to_rgba8()) +} + /// Crop Image's trim: the image cut to the box of its pixels that aren't fully transparent, the /// pixels copied as they are (no resampling) and placed where they were. fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result { @@ -1036,23 +1097,7 @@ fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result { if blob.is_cmyk() { return Ok(json!({ "id": id.0, "width": im.width, "height": im.height, "trimmed": false })); } - // Print rasters run to gigabytes decoded: the same allowance opening them has. - let reader = || { - image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())) - .with_guessed_format() - .map_err(|_| bad(C, "the image's pixels can't be read")) - }; - // The image's size as RGBA, read from its header, is held to that allowance before anything - // is decoded (#1717). - let (w, h) = reader()?.into_dimensions().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?; - if u64::from(w) * u64::from(h) > crate::cmd::fileio::MAX_RASTER_ALLOC / 4 { - return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw"))); - } - let mut reader = reader()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(crate::cmd::fileio::MAX_RASTER_ALLOC); - reader.limits(limits); - let px = reader.decode().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?.to_rgba8(); + let px = decode_rgba(C, blob)?; let (w, h) = px.dimensions(); let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0); for (x, y, p) in px.enumerate_pixels() { @@ -1071,23 +1116,22 @@ fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result { let mut png = Vec::new(); cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad(C, e.to_string()))?; let (cw, ch) = (x1 - x0, y1 - y0); + put_pixels(s, id, png, cw, ch, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))?; + Ok(json!({ "id": id.0, "width": cw, "height": ch, "trimmed": true })) +} + +/// Crop Image's edit for a cut made from the image's own pixels: `png` (`w` × `h` px) takes the +/// image's place, mapped into the document by `xf`. +fn put_pixels(s: &mut Session, id: NodeId, png: Vec, w: u32, h: u32, xf: Affine) -> Result<()> { s.edit("Crop Image", |d, _| { let key = unique_key(d, "crop"); d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png)); if let Some(n) = d.node_mut(id) { - n.kind = NodeKind::Image(Box::new(ImageObject { - key, - width: cw, - height: ch, - xf: im.xf * Affine::translate((f64::from(x0), f64::from(y0))), - link: None, - placement: Default::default(), - pixels: None, - })); + n.kind = NodeKind::Image(Box::new(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None })); } Ok(()) })?; - Ok(json!({ "id": id.0, "width": cw, "height": ch, "trimmed": true })) + Ok(()) } /// The Control bar's Mask for an image: a clip group of the image and a clipping path on its diff --git a/crates/engine/src/cmd/object/align.rs b/crates/engine/src/cmd/object/align.rs index 82a61b02af..b32275d1b7 100644 --- a/crates/engine/src/cmd/object/align.rs +++ b/crates/engine/src/cmd/object/align.rs @@ -6,16 +6,23 @@ use super::{ use vectorcraft_doc::{NodeKind, TextKind}; impl Session { - /// The bounds of `ids` the Transform panel, the bounding box, Align and Distribute measure: - /// with Use Preview Bounds on, visual bounds as drawn (strokes and geometry effects included, - /// see [`effects::preview`]), else geometric bounds. + /// The bounds of `ids` the Transform panel and the bounding box measure: with Use Preview + /// Bounds on, visual bounds as drawn (strokes and geometry effects included, see + /// [`effects::preview`]), else geometric bounds; with Measure Type by Glyph Bounds on, point + /// type by the ink of its glyphs ([`Session::bounds_measure`]). pub fn transform_bounds(&self, ids: &[NodeId]) -> Option { - effects::preview::bounds_of(&self.doc().ok()?.doc, ids, self.prefs.use_preview_bounds) + effects::preview::bounds_of_with(&self.doc().ok()?.doc, ids, self.bounds_measure()) } /// [`Session::transform_bounds`] square to the objects' own angle (their rotated bounding /// box, see [`Document::oriented_bounds`]). pub fn transform_box(&self, ids: &[NodeId]) -> Option { - effects::preview::oriented_bounds(&self.doc().ok()?.doc, ids, self.prefs.use_preview_bounds) + effects::preview::oriented_bounds_with(&self.doc().ok()?.doc, ids, self.bounds_measure()) + } + /// How the bounding box, the Transform panel and `object.setBounds` measure objects: Use + /// Preview Bounds, and point type by its glyphs with Measure Type by Glyph Bounds + /// (`typeGlyphBounds`). + pub fn bounds_measure(&self) -> effects::preview::Measure { + effects::preview::Measure { preview: self.prefs.use_preview_bounds, glyphs: self.prefs.type_glyph_bounds } } } diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index 9d4795235f..3dc1c37dad 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -59,24 +59,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor let st = s.doc()?; check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?; check_switches(p, &["proportional"], "object.setBounds")?; + let how = s.bounds_measure(); if anchors && transforms_objects(p) && !bool_or(p, "copy", false) - && let Some(b) = effects::preview::anchor_bounds(&st.selection, &st.doc, s.prefs.use_preview_bounds) + && let Some(b) = effects::preview::anchor_bounds_with(&st.selection, &st.doc, how) { return Ok(Bounds::Anchors(ids, b)); } let d = &s.doc()?.doc; // Sizes are measured square to the bounding box, which a rotation turns with the objects: - // the math below runs in its frame. - let frame = d.oriented_bounds(&ids, false).ok_or_else(|| EngineError::Other("no bounds".into()))?; + // the math below runs in its frame. With Measure Type by Glyph Bounds, point type is measured + // by its glyphs' ink, which a transform of the type moves and scales with it. + let geometric = effects::preview::Measure { preview: false, ..how }; + let frame = effects::preview::oriented_bounds_with(d, &ids, geometric).ok_or_else(|| EngineError::Other("no bounds".into()))?; let g = frame.rect; + let symbols = d.symbol_boxes(); + let by_glyphs = how.glyphs && ids.iter().filter_map(|id| d.node(*id)).any(|n| effects::preview::by_glyphs(&symbols, n, how)); // With Use Preview Bounds the values measure the visual box as drawn, whose margins around the // geometric box (left, top, right, bottom) scale with the strokes or stay. The margins of // `vs`, the visual box without the strokes in symbols' art, scale; those strokes keep their - // weight when an instance scales, so the rest of the margins stay. + // weight when an instance scales, so the rest of the margins stay. Type measured by its glyphs + // is measured as drawn after each scale tried instead (below). let (v, vs) = if s.prefs.use_preview_bounds { - (effects::preview::oriented_bounds(d, &ids, true).map_or(g, |b| b.rect), scaling_box(d, &ids, &frame).unwrap_or(g)) + let v = effects::preview::oriented_bounds_with(d, &ids, how).map_or(g, |b| b.rect); + (v, if by_glyphs { v } else { scaling_box(d, &ids, &frame).unwrap_or(g) }) } else { (g, g) }; @@ -125,22 +132,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor // The scales and the point above can miss the size or the reference point when the margins of // the objects differ, the members of groups and the objects in symbols' art included, and with // strokes that scale, when the sizes are out of proportion. The objects are then measured one - // by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects are - // measured as drawn after each scale tried instead ([`refit_drawn`]). - let symbols = d.symbol_boxes(); - let drawn = || ids.iter().filter_map(|id| d.node(*id)).any(|n| effects::preview::draws_geometry(&symbols, n)); + // by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects, + // objects with a butt-capped stroke along a segment at a slant, whose margins change with the + // segment's direction, and type measured by its glyphs, are measured as drawn after each scale + // tried instead ([`refit_drawn`]). + let to_local = frame.to_doc().inverse(); + let drawn = || { + by_glyphs + || ids + .iter() + .filter_map(|id| d.node(*id)) + .any(|n| effects::preview::draws_geometry(&symbols, n) || n.has_slanted_butt_stroke(&symbols, to_local)) + }; + // Without Use Preview Bounds the box has no margins (`v`, `vs` and `g` are one box, glyph ink + // included), so the scales above are exact and nothing is refitted. let solved = if !(s.prefs.use_preview_bounds && w >= 0.0 && h >= 0.0) { None } else if transforms_objects(p) && !bool_or(p, "typeAreas", false) && drawn() { let options = scaling_options(s, p); - let to_local = frame.to_doc().inverse(); let measure = |sx: f64, sy: f64| { let xf = frame.conjugate(about(rp, Affine::scale_non_uniform(sx, sy))); let sc = if Scaling::factor(xf).is_some() { options } else { Scaling::default() }; ids.iter().filter_map(|id| d.node(*id)).fold(None, |acc, n| { let mut n = n.clone(); n.transform(xf, sc); - vectorcraft_geom::union_opt(acc, effects::preview::bounds_in(&symbols, &n, to_local)) + vectorcraft_geom::union_opt(acc, effects::preview::bounds_in_with(&symbols, &n, to_local, how)) }) }; // The scales above keep the effects' reach as a margin that stays, and give 0 for a size diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index a923ab2eb4..2f0aa742d1 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -287,7 +287,7 @@ pub fn specs() -> Vec { "Set Bounds", [], None, - "{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", + "{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", has_selection, set_bounds ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index ae45f4d977..6184860979 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -12,7 +12,7 @@ fn origin_of(s: &Session, p: &Value, ids: &[NodeId]) -> Result { // Direct-selected anchors transform alone (see [`apply_transform`]), about their own centre. let st = s.doc()?; if !bool_or(p, "copy", false) - && let Some(b) = effects::preview::anchor_bounds(&st.selection, &st.doc, s.prefs.use_preview_bounds) + && let Some(b) = effects::preview::anchor_bounds_with(&st.selection, &st.doc, s.bounds_measure()) { return Ok(b.center()); } diff --git a/crates/engine/src/cmd/opacitymask.rs b/crates/engine/src/cmd/opacitymask.rs index 9d81576b0a..75d5852ea2 100644 --- a/crates/engine/src/cmd/opacitymask.rs +++ b/crates/engine/src/cmd/opacitymask.rs @@ -14,7 +14,7 @@ use vectorcraft_doc::{Document, Knockout, Node, NodeId, NodeKind, OpacityMask, S use super::maskedit::{begin, finish, mask_group, mask_parts, show_editing}; use super::pathops::{Beside, separate}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ids_param, ok, targets}; +use super::{CommandSpec, Result, Session, always, bad, cmd, has_doc, ids_param, ok, switch_or, targets}; use crate::EngineError; pub fn specs() -> Vec { @@ -246,8 +246,8 @@ fn make(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, why)); } - let clip = bool_or(p, "clip", !s.menu.new_masks_unclipped); - let invert = bool_or(p, "invert", s.menu.new_masks_inverted); + let clip = switch_or(p, "clip", !s.menu.new_masks_unclipped, C)?; + let invert = switch_or(p, "invert", s.menu.new_masks_inverted, C)?; // Several objects: the top one is the mask. One: an empty mask, drawn in mask editing. let (art, mask_id) = if below.is_empty() { (&ids[..], None) } else { (below, Some(top)) }; // Several objects go into a new group, and a layer can't: the group takes a layer's art. @@ -330,8 +330,13 @@ fn release(s: &mut Session, p: &Value) -> Result { /// Set the mask flags given in `p` on the masked objects among `target`'s targets. fn set_flags(s: &mut Session, target: &Value, label: &str, p: &Value) -> Result { - let get = |k: &str| p.get(k).and_then(Value::as_bool); - let (clip, invert, disabled, linked) = (get("clip"), get("invert"), get("disabled"), get("linked")); + let get = |k: &str| -> Result> { + match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(_) => switch_or(p, k, false, "transparency.setOpacityMask").map(Some), + } + }; + let (clip, invert, disabled, linked) = (get("clip")?, get("invert")?, get("disabled")?, get("linked")?); if clip.is_none() && invert.is_none() && disabled.is_none() && linked.is_none() { return Err(bad("transparency.setOpacityMask", "give at least one of clip, invert, disabled, linked")); } @@ -363,7 +368,7 @@ fn set_flags(s: &mut Session, target: &Value, label: &str, p: &Value) -> Result< } fn toggle_new_clip(s: &mut Session, p: &Value) -> Result { - let v = bool_or(p, "value", s.menu.new_masks_unclipped); + let v = switch_or(p, "value", s.menu.new_masks_unclipped, "transparency.toggleNewMasksClipping")?; s.menu.new_masks_unclipped = !v; Ok(json!({ "value": v })) } @@ -376,7 +381,7 @@ fn toggle_page(s: &mut Session, p: &Value, knockout: bool) -> Result { } let d = &s.doc()?.doc; let cur = if knockout { d.page_knockout } else { d.page_isolate }; - let v = bool_or(p, "value", !cur); + let v = switch_or(p, "value", !cur, if knockout { "transparency.togglePageKnockoutGroup" } else { "transparency.togglePageIsolatedBlending" })?; if v != cur { s.edit(if knockout { "Page Knockout Group" } else { "Page Isolated Blending" }, |d, _| { *flag(d, knockout) = v; @@ -387,7 +392,7 @@ fn toggle_page(s: &mut Session, p: &Value, knockout: bool) -> Result { } fn toggle_new_invert(s: &mut Session, p: &Value) -> Result { - let v = bool_or(p, "value", !s.menu.new_masks_inverted); + let v = switch_or(p, "value", !s.menu.new_masks_inverted, "transparency.toggleNewMasksInverted")?; s.menu.new_masks_inverted = v; Ok(json!({ "value": v })) } diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 7d58a9043e..c9f51e0654 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -18,13 +18,24 @@ //! `effect.setParams` answer a key the effect doesn't take, or a value of another type than its //! default, with a parameter error ([`check_effect_params`]). //! +//! A command with a parameter schema (`CommandSpec::schema`) is also checked against the schema +//! before it runs ([`crate::schemas::check`]): the schema refuses a value of the wrong type or out +//! of range, a missing required parameter and an unknown key at any depth, and fills in declared +//! defaults, so the command runs with the filled-in params. The check here still runs first for +//! such a command, so a misspelled top-level key gets the same error from either, and a +//! `command.batch` or an `action.batch` checks each step's schema before the first step runs. The +//! keys of commands without a schema, and the options of exports and effects, are checked only as +//! this module describes. +//! //! Saved steps play through [`Session::replay`] instead: a journal or an action recorded by an older //! version, with a key a command no longer reads or an effect parameter it no longer takes, still -//! plays. Even there, an effect's `color` that the effect can't read and a Levels or Curves +//! plays. A key a schema doesn't name passes there too, and the values of the parameters it names +//! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` //! themselves ([`check_effect_color`], [`check_effect_channel`]). use serde_json::Value; +use vectorcraft_apischema::shown_key; use super::{bad, command_specs, find_command}; use crate::Result; @@ -239,9 +250,11 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> { /// The parameter error of command `id` for `key`, which isn't one of `keys`: with the nearest of /// them, or all of them. pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError { + let near = nearest(key, keys); + let key = shown_key(key); bad( id, - match nearest(key, keys) { + match near { Some(near) => format!("unknown parameter `{key}`; did you mean `{near}`?"), None if keys.is_empty() => format!("unknown parameter `{key}`; the command takes no parameters"), None => format!("unknown parameter `{key}`; the command takes: {}", keys.join(", ")), @@ -522,6 +535,7 @@ fn check_option_tree(id: &str, within: &str, given: &serde_json::Map format!("did you mean `{within}{near}`?"), None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")), }; + let key = shown_key(key); return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}"))); } (Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?, @@ -538,9 +552,11 @@ fn check_option_tree(id: &str, within: &str, given: &serde_json::Map, keys: &[&str], why_not: &str, trees: &Value) -> Result<()> { for (key, value) in given { if !keys.contains(&key.as_str()) { + let near = nearest(key, keys); + let key = shown_key(key); return Err(bad( id, - match nearest(key, keys) { + match near { Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"), None => format!("unknown parameter `{within}{key}`; {why_not}"), }, @@ -647,6 +663,7 @@ fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map) Some(near) => format!("did you mean `{within}settings.{near}`?"), None => format!("`{within}settings` takes: {}", formats.join(", ")), }; + let format = shown_key(format); return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}"))); } if let Value::Object(options) = options { @@ -758,10 +775,13 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { return Ok(()); } check_keys(id, spec.params, params)?; + if in_batch { + crate::schemas::check(spec, params, false)?; + } if matches!(id, "command.batch" | "action.batch") && !in_batch { for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() { - if let (Some(step_id), Some(step_params)) = (step.get("command").and_then(Value::as_str), step.get("params")) { - check_params_in(step_id, step_params, true)?; + if let Some(step_id) = step.get("command").and_then(Value::as_str) { + check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?; } } } @@ -778,8 +798,8 @@ pub(crate) fn nearest_command(id: &str) -> Option<&'static str> { /// The error for `id`, which names no command: with the nearest command id, when one is near. pub(crate) fn unknown_command(id: &str) -> crate::EngineError { match nearest_command(id) { - Some(near) => crate::EngineError::UnknownCommandNear(id.to_string(), near.to_string()), - None => crate::EngineError::UnknownCommand(id.to_string()), + Some(near) => crate::EngineError::UnknownCommandNear(shown_key(id), near.to_string()), + None => crate::EngineError::UnknownCommand(shown_key(id)), } } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index cb82cfe3fa..2b529a84bb 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1232,6 +1232,12 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { .copied() .filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor))) .collect(); + // The compound paths that hold a deleted object; one left with no members goes too. + let compounds: BTreeSet = whole_ids + .iter() + .chain(sel.keys()) + .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) + .collect(); if !whole_ids.is_empty() { d.remove_many(&whole_ids)?; } @@ -1280,6 +1286,11 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { } } emptied.finish(d)?; + for p in compounds { + if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) { + d.remove(p)?; + } + } selection.set(survivors); Ok(()) })?; @@ -1329,7 +1340,7 @@ pub(super) fn replace_deleted_pieces(d: &mut Document, beside: &mut Beside, orig /// Remove anchors and their incident segments, keeping each surviving stretch as an open path. /// Only a closed path can have a surviving stretch that wraps past the last anchor. -fn without_anchors(sp: SubPath, removed: &BTreeSet) -> Vec { +pub(super) fn without_anchors(sp: SubPath, removed: &BTreeSet) -> Vec { let n = sp.anchors.len(); let gone: BTreeSet = removed.iter().copied().filter(|&i| i < n).collect(); if gone.is_empty() { diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index c18412c1da..a8306d25c7 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -16,8 +16,8 @@ use vectorcraft_pathops::{BoolOp, PathfinderOp}; use super::edit::selected_roots; use super::expand::{fill_shape, reshaped, seeded}; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection, - number_or, str_param, switch_or, + CommandSpec, EngineError, Result, Session, always, bad, check_switches, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection, + number_or, switch_or, text_param, }; pub fn specs() -> Vec { @@ -221,6 +221,25 @@ pub(crate) fn len_param(p: &Value, key: &str) -> Option { } } +/// The number `p` gives `cmd` for `key`, as [`num_param`] reads it, or `None` when `p` leaves it out +/// or gives null. Any other value, such as `true` or `"wide"`, is an error: "`{key}` must be a +/// number, not {v}". +pub(crate) fn number_given(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => num_param(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))), + } +} + +/// The distance `p` gives `cmd` for `key`, as [`len_param`] reads it (`"5 mm"` included), or `None` +/// when `p` leaves it out or gives null. Any other value is an error, as [`number_given`] gives it. +pub(crate) fn length_given(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => len_param(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))), + } +} + fn ids_json(ids: &[NodeId]) -> Value { json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) } @@ -687,18 +706,19 @@ fn trap(s: &mut Session, p: &Value) -> Result { use vectorcraft_render::effects::trap::{TRAP_LABEL, TrapOptions, TrapSource, trap_appearance, traps}; const ID: &str = "object.pathfinder.trap"; let mut q = p.clone(); - if let Some(t) = len_param(p, "thickness") { + if let Some(t) = length_given(p, "thickness", ID)? { if !(po::TRAP_MIN_WIDTH..=po::TRAP_MAX_WIDTH).contains(&t) { return Err(bad(ID, "thickness must be from 0.01 to 5000 pt")); } q["thickness"] = json!(t); } - if num_param(p, "heightWidth").is_some_and(|v| !(1.0..=1000.0).contains(&v)) { + if number_given(p, "heightWidth", ID)?.is_some_and(|v| !(1.0..=1000.0).contains(&v)) { return Err(bad(ID, "heightWidth must be from 1 to 1000 %")); } - if num_param(p, "tintReduction").is_some_and(|v| !(0.0..=100.0).contains(&v)) { + if number_given(p, "tintReduction", ID)?.is_some_and(|v| !(0.0..=100.0).contains(&v)) { return Err(bad(ID, "tintReduction must be from 0 to 100 %")); } + check_switches(p, &["trapsWithProcessColor", "reverseTraps"], ID)?; // The effect-only settings stay at their defaults. if let Some(o) = q.as_object_mut() { o.remove("precision"); @@ -743,21 +763,23 @@ fn trap(s: &mut Session, p: &Value) -> Result { // ---------- Offset Path ---------- -fn join_param(p: &Value, key: &str) -> po::Join { - match str_param(p, key).map(str::to_ascii_lowercase).as_deref() { - Some("round") => po::Join::Round, - Some("bevel") => po::Join::Bevel, - _ => po::Join::Miter, +fn join_param(p: &Value, key: &str, cmd: &str) -> Result { + match text_param(p, key, cmd)?.map(str::to_ascii_lowercase).as_deref() { + None | Some("miter") => Ok(po::Join::Miter), + Some("round") => Ok(po::Join::Round), + Some("bevel") => Ok(po::Join::Bevel), + Some(_) => Err(bad(cmd, format!("`{key}` must be one of miter, round, bevel"))), } } fn offset_path(s: &mut Session, p: &Value) -> Result { - let delta = len_param(p, "offset").unwrap_or(10.0); + const C: &str = "object.path.offsetPath"; + let delta = length_given(p, "offset", C)?.unwrap_or(10.0); if delta.abs() > 1e5 { - return Err(bad("object.path.offsetPath", "offset out of range")); + return Err(bad(C, "offset out of range")); } - let join = join_param(p, "joins"); - let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0); + let join = join_param(p, "joins", C)?; + let miter = number_given(p, "miterLimit", C)?.unwrap_or(4.0).clamp(1.0, 500.0); let roots = selected_roots(s)?; let ids = s.edit("Offset Path", |d, sel| { let (mut out, mut above) = (vec![], vec![]); @@ -1167,23 +1189,21 @@ pub fn auto_simplify_level(s: &Session) -> Result { } fn simplify(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.path.simplify"; + let (auto, given_level, given_tolerance) = (switch_or(p, "auto", false, C)?, number_given(p, "level", C)?, length_given(p, "tolerance", C)?); + let corner_angle = number_given(p, "cornerAngle", C)?.unwrap_or(30.0).clamp(0.0, 180.0); + let (straight_lines, whole) = (switch_or(p, "straightLines", false, C)?, switch_or(p, "wholePaths", false, C)?); // With auto, the slider's level is Auto-Simplify's for the selection's size; otherwise it is the level given. - let level = if bool_or(p, "auto", false) { + let level = if auto { Some(auto_simplify_level(s)?) } else { - num_param(p, "level").map(|l| if l.is_finite() { l.round().clamp(0.0, 100.0) } else { po::SIMPLIFY_LEVEL }) + given_level.map(|l| if l.is_finite() { l.round().clamp(0.0, 100.0) } else { po::SIMPLIFY_LEVEL }) }; let tolerance = match level { Some(l) => po::simplify_level_tolerance(l), - None => len_param(p, "tolerance").unwrap_or(1.0), + None => given_tolerance.unwrap_or(1.0), }; - let opts = po::SimplifyOptions { - tolerance: tolerance.clamp(1e-4, 1e4), - corner_angle_deg: num_param(p, "cornerAngle").unwrap_or(30.0).clamp(0.0, 180.0), - straight_lines: bool_or(p, "straightLines", false), - smooth: 0.0, - }; - let whole = bool_or(p, "wholePaths", false); + let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, smooth: 0.0 }; // A path with segments direct-selected simplifies only their runs, and keeps those runs (and the // other anchors it had selected) direct-selected. let roots = selected_roots(s)?; @@ -1257,10 +1277,17 @@ fn grid_axis(p: &Value, n: f64, [size, gutter, total]: [&str; 3], extent: f64) - } fn split_into_grid(s: &mut Session, p: &Value) -> Result { - let rows = num_param(p, "rows").unwrap_or(2.0).round(); - let cols = num_param(p, "columns").unwrap_or(2.0).round(); + const C: &str = "object.path.splitIntoGrid"; + let rows = number_given(p, "rows", C)?.unwrap_or(2.0).round(); + let cols = number_given(p, "columns", C)?.unwrap_or(2.0).round(); if !(1.0..=500.0).contains(&rows) || !(1.0..=500.0).contains(&cols) { - return Err(bad("object.path.splitIntoGrid", "rows and columns must be 1..500")); + return Err(bad(C, "rows and columns must be 1..500")); + } + let add_guides = switch_or(p, "addGuides", false, C)?; + // Each distance [`grid_axis`] reads is a number, a string with a unit or null, checked before the + // selection, so a bad one is an error whatever is selected. + for key in ["height", "rowGutter", "totalHeight", "width", "columnGutter", "totalWidth", "gutter"] { + length_given(p, key, C)?; } let too_small = || EngineError::Other("Split Into Grid: select paths large enough for the grid".into()); // The selected paths, back to front: one grid over them all replaces them, where the topmost @@ -1281,7 +1308,7 @@ fn split_into_grid(s: &mut Session, p: &Value) -> Result { return Err(too_small()); } let mut edges: Vec<(bool, f64)> = Vec::new(); - if bool_or(p, "addGuides", false) { + if add_guides { // Row-major cells: the first row has the column edges, each row's first cell the row edges. let bounds = cells.iter().filter_map(PathData::bounds); edges.extend(bounds.clone().take(cols).flat_map(|c| [(true, c.x0), (true, c.x1)])); @@ -1316,9 +1343,10 @@ fn is_painted(a: &Appearance) -> bool { } fn clean_up(s: &mut Session, p: &Value) -> Result { - let stray = bool_or(p, "strayPoints", true); - let unpainted = bool_or(p, "unpaintedObjects", true); - let empty_text = bool_or(p, "emptyTextPaths", true); + const C: &str = "object.path.cleanUp"; + let stray = switch_or(p, "strayPoints", true, C)?; + let unpainted = switch_or(p, "unpaintedObjects", true, C)?; + let empty_text = switch_or(p, "emptyTextPaths", true, C)?; let found = { let d = &s.doc()?.doc; let mut v = vec![]; diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index cd2f72e275..d583f6fe34 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -88,6 +88,9 @@ pub fn describe(p: &Plugin) -> Value { if m.paint_output { v["paintOutput"] = json!(true); } + if !m.command_allowlist.is_empty() { + v["commandAllowlist"] = json!(m.command_allowlist); + } if !m.commands.is_empty() { let commands: Vec = m .commands @@ -258,6 +261,37 @@ impl FilterRun { self.plugin.run(&self.input, &self.params).map_err(err) } + /// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the + /// session ([`FilterRun::run_with_calls`]). + pub fn calls(&self) -> bool { + !self.plugin.manifest().command_allowlist.is_empty() + } + + /// Runs the plug-in in `s`, making the command calls it asks for on the active document + /// ([`super::plugin_call::call`]) → its output. + fn run_calling(&self, s: &mut Session) -> Result> { + let may = self.plugin.manifest().permissions(); + let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite)); + let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args); + self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err) + } + + /// Runs a plug-in that calls commands and applies its output: the calls and the output are one + /// undo step, and a run that fails changes nothing ([`super::plugin_call::transaction`]). + fn run_with_calls(self, s: &mut Session) -> Result { + let label = self.label(); + super::plugin_call::transaction(s, &label, |s| { + let output = self.run_calling(s)?; + self.finish(s, &output) + }) + } + + /// The name of its undo step: the plug-in's, or its command's. + fn label(&self) -> String { + let m = self.plugin.manifest(); + self.command.as_ref().map_or_else(|| m.name.trim_end_matches('…').to_string(), Command::shown_label) + } + /// Hands in `output`, which [`FilterRun::run`] returned: the next `plugin.run` that makes this /// same run (same plug-in, `ids` and parameters, the document unchanged) applies it instead of /// running the plug-in. Any other run drops it. @@ -277,9 +311,9 @@ impl FilterRun { return Err(not_granted(&m.name, Permission::State)); } let may_write = may.contains(&Permission::DocWrite); - let (inputs, parent) = (self.inputs, self.parent); // A command's undo step is named after the command. - let label = self.command.as_ref().map_or_else(|| m.name.trim_end_matches('…').to_string(), Command::shown_label); + let label = self.label(); + let (inputs, parent) = (self.inputs, self.parent); let ids = s.edit(&label, |d, sel| { let before = (!may_write).then(|| d.layers.clone()); let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?; @@ -316,6 +350,12 @@ fn run(s: &mut Session, p: &Value) -> Result { // An output handed in is for this run only (the app hands it in just before), whatever it does. let handed = s.plugin_output.take(); let r = FilterRun::prepare(s, p)?; + // One that calls commands runs here, where it can make them, on the document with any edit in + // progress committed. + if r.calls() { + let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r }; + return r.run_with_calls(s); + } // Handed in for this very run (the app ran it in the background), it is what running the // plug-in again would return. let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params)); @@ -433,6 +473,7 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { enabled: has_doc, run: unrouted, journal: true, + schema: None, })); made.push(spec); spec @@ -462,6 +503,16 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result } }; let r = FilterRun::prepare_with(s, plugin, Some(command), id, p)?; + if r.calls() { + let r = match super::plugin_call::settle(s)? { + true => { + let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; + FilterRun::prepare_with(s, plugin, Some(command), id, p)? + } + false => r, + }; + return r.run_with_calls(s).map_err(failed); + } let output = r.run().map_err(&failed)?; r.finish(s, &output).map_err(failed) } @@ -653,6 +704,16 @@ fn install(s: &mut Session, p: &Value) -> Result { "`grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app", )); } + // A plug-in never calls a command no plug-in may call, whatever its manifest lists. + let (unknown, refused) = super::plugin_call::check_allowlist(plugin.manifest()); + if let Some(id) = refused.first() { + let (name, id) = ( + permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME), + permissions::display_text(id, permissions::MAX_SHOWN_FIELD), + ); + return Err(bad(C, format!("“{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call"))); + } + let unknown: Vec = unknown.into_iter().map(str::to_string).collect(); // A heavy plug-in is installed once a person agrees. if plugin.manifest().budget == Budget::Heavy && !allow_heavy { let (minutes, times) = vectorcraft_plugins::heavy_terms(); @@ -725,7 +786,11 @@ fn install(s: &mut Session, p: &Value) -> Result { if changed { s.store_disabled_plugins(); } - Ok(describe_installed(®istry::install(plugin))) + let mut v = describe_installed(®istry::install(plugin)); + if !unknown.is_empty() { + v["unknownCommands"] = json!(unknown); + } + Ok(v) } /// `plugin.inspect`: what installing the module would install, without installing it, whether that @@ -736,6 +801,13 @@ fn inspect(s: &mut Session, p: &Value) -> Result { let mut v = describe(&plugin); v["needsApproval"] = json!(!s.plugin_approved(&plugin)); v["needsReplace"] = json!(takes_over(s, &plugin)); + let (unknown, refused) = super::plugin_call::check_allowlist(plugin.manifest()); + if !unknown.is_empty() { + v["unknownCommands"] = json!(unknown); + } + if !refused.is_empty() { + v["refusedCommands"] = json!(refused); + } v }) } @@ -970,7 +1042,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -988,7 +1060,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", has_doc, run ), @@ -997,7 +1069,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry", + "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), @@ -1006,7 +1078,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)", + "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", always, inspect ), diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs new file mode 100644 index 0000000000..b151adcea2 --- /dev/null +++ b/crates/engine/src/cmd/plugin_call.rs @@ -0,0 +1,577 @@ +//! Commands a filter plug-in calls with `vc_call` ([`vectorcraft_plugins::host`]): which commands a +//! plug-in may never call ([`denied`]), the call itself ([`call`]), and the run around the calls +//! ([`transaction`]). +//! +//! A filter whose manifest's `commandAllowlist` names commands runs on the session's thread. Each +//! call it makes runs that command on the document the run is for, through [`Session::execute`] with +//! its params checked as any request's are, and sees the selection the calls before it left. The +//! calls and the filter's output are one undo step, named after the plug-in or its command; a run +//! that fails, traps, runs out of budget or is canceled, or makes a call that fails, leaves every +//! document, its selection and its history as they were. +//! +//! A plug-in never calls a command that reads or writes a file or folder, uses the clipboard, +//! changes preferences, runs a script, an action or a plug-in (a plug-in command, or an effect a +//! plug-in adds), opens, closes or switches documents, or undoes or redoes, whatever its manifest +//! lists. A command whose params name a file or folder is refused unless [`NOT_FILES`] says that +//! key names part of the document in it, and so is a call whose arguments carry such a key at any +//! depth ([`names_file`]); a call runs with no file or folder readable or writable +//! ([`execute_confined`]). Every other command is refused too unless +//! [`reviewed::ALLOWED`] lists it, so a command added to the registry later is refused until +//! someone decides. + +mod reviewed; + +use std::sync::Arc; + +use serde_json::Value; +use vectorcraft_plugins::host::{CALL_COMMAND_FAILED, CALL_DENIED_COMMAND, CALL_DISABLED, CALL_UNKNOWN_COMMAND, CallFailure}; + +use super::CommandSpec; +use crate::{EngineError, Result, Session}; + +/// Command ids a plug-in may never call, by their start: plug-ins, scripts and actions, files, +/// documents and links, the clipboard, preferences, the view and the app, and the undo history. +const DENIED_PREFIXES: &[&str] = &[ + "plugin.", + "script.", + "action.", + "actionSet.", + "command.", + "prefs.", + "help.", + "engine.", + "file.", + "document.", + "addon.document.", + "library.", + "links.", + "recovery.", + "shortcutSet.", + "clipboard.", + "view.", + "print.", + "pdf.", + "webExport.", + "css.", + "assets.", + "importMatches.", + "edit.undo", + "edit.redo", + "edit.clearHistory", + "edit.copy", + "edit.cut", + "edit.paste", + "edit.newDocument", + "edit.colorSettings", + "edit.dropSelection", + "artboard.copy", + "artboard.cut", + "text.rescanFonts", + "text.fontList", + "text.spelling.", + "colorTheme.", + "magicWand.", + "eyedropper.", + "layer.pasteRemembersLayers", + "type.systemLayout", + "type.fractionalWidths", + "appearance.setNewArtBasic", + "appearance.newArt", + "perspective.widget", + "transparency.toggleNewMasks", +]; + +/// Words in a command id that name a file or the clipboard (any case): a command with one of them +/// in its id may read or write a file a plug-in can't see. +const FILE_WORDS: &[&str] = &[ + "export", + "import", + "save", + "load", + "open", + "file", + "folder", + "link", + "librar", + "preset", + "recover", + "package", + "print", + "profile", + "clipboard", +]; + +/// Param keys that name a file or a folder. +const FILE_KEYS: &[&str] = &["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url"]; + +/// Commands and the param key in [`FILE_KEYS`] that, in them, names part of the document (a path of +/// its art, a setting, an attribute it stores or a result field), not a file. +pub(crate) const NOT_FILES: &[(&str, &str)] = &[ + ("object.setLiveShape", "path"), + ("path.reverse", "paths"), + ("object.pathfinder.options", "paths"), + ("object.maskImage", "path"), + ("text.createInPath", "path"), + ("imageTrace.make", "paths"), + ("symbol.instance.setAppearance", "path"), + ("symbol.instance.selectPart", "path"), + ("object.objectsOnPath.attach", "path"), + ("attributes.set", "url"), + ("svgInteractivity.info", "files"), + ("addon.cleanup.rejoin", "paths"), +]; + +/// Is command id `id` one a plug-in may never call, from its id alone ([`DENIED_PREFIXES`], +/// [`FILE_WORDS`])? +fn denied_id(id: &str) -> bool { + let lower = id.to_ascii_lowercase(); + DENIED_PREFIXES.iter().any(|p| id.starts_with(p)) || FILE_WORDS.iter().any(|w| lower.contains(w)) +} + +/// Why a plug-in may never call `spec`, or `None` when it may (when its manifest lists it): its id +/// or a file key ([`denied_by_rule`]), [`reviewed::DENIED`], or no place in [`reviewed::ALLOWED`]. +pub(crate) fn denied(spec: &CommandSpec) -> Option<&'static str> { + if let Some(why) = denied_by_rule(spec) { + return Some(why); + } + if reviewed::DENIED.binary_search(&spec.id).is_ok() { + return Some("reviewed"); + } + if reviewed::ALLOWED.binary_search(&spec.id).is_err() { + return Some("not reviewed"); + } + None +} + +/// Why a plug-in may never call `spec` from its id ([`denied_id`]) or its params (a key in +/// [`FILE_KEYS`] that [`NOT_FILES`] doesn't name for it), or `None`. +fn denied_by_rule(spec: &CommandSpec) -> Option<&'static str> { + let id = spec.id; + if denied_id(id) { + return Some("id"); + } + let mut keys = FILE_KEYS.iter().filter(|k| !NOT_FILES.contains(&(id, **k))); + let in_schema = |k: &str| spec.schema.is_some_and(|s| s.params.iter().any(|p| p.name == k)); + if keys.any(|k| names_key(spec.params, k) || in_schema(k)) { + return Some("file key"); + } + None +} + +/// The ids `m`'s `commandAllowlist` names that no command has (a later version may add them; a +/// call of one fails), and those a plug-in may never call ([`denied`]). +pub(crate) fn check_allowlist(m: &vectorcraft_plugins::Manifest) -> (Vec<&str>, Vec<&str>) { + let (mut unknown, mut refused) = (Vec::new(), Vec::new()); + for id in &m.command_allowlist { + match super::find_command(id) { + Some(spec) if denied(spec).is_some() => refused.push(id.as_str()), + Some(_) => {} + None if denied_id(id) => refused.push(id.as_str()), + None => unknown.push(id.as_str()), + } + } + (unknown, refused) +} + +/// Does params text `text` name the key `key`: `key:` or `key?:`, not as the end of a longer word? +pub(crate) fn names_key(text: &str, key: &str) -> bool { + text.match_indices(key).any(|(at, _)| { + let before = text[..at].chars().next_back(); + let after = &text[at + key.len()..]; + before.is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '.')) && (after.starts_with(':') || after.starts_with("?:")) + }) +} + +/// Does `args`, the arguments of a call of command `id`, carry a key in [`FILE_KEYS`] at any depth +/// (in objects and in arrays), such as an effect's `textureImage.path`? Only a key [`NOT_FILES`] +/// names for `id`, at the top level, isn't counted. The walk keeps its own stack, so deep +/// arguments can't overflow the thread's. +fn names_file(id: &str, args: &Value) -> bool { + let mut stack = vec![(args, true)]; + while let Some((v, top)) = stack.pop() { + match v { + Value::Array(a) => stack.extend(a.iter().map(|x| (x, false))), + Value::Object(o) => { + for (k, x) in o { + let k = k.as_str(); + if FILE_KEYS.contains(&k) && !(top && NOT_FILES.contains(&(id, k))) { + return true; + } + stack.push((x, false)); + } + } + _ => {} + } + } + false +} + +/// Param keys whose value names an effect or a command (`id` is `effect.apply`'s other name for +/// `effect`). +const PLUGIN_KEYS: &[&str] = &["effect", "effects", "id", "command", "commands"]; + +/// Does `v` name a plug-in anywhere: an effect or a command ([`PLUGIN_KEYS`]) whose id starts with +/// `plugin.`, at any depth? A call that does is refused, so a plug-in never runs another, or +/// itself. Other strings, such as text, may start with `plugin.`. +fn names_plugin(v: &Value) -> bool { + names_plugin_in(v, false) +} + +/// [`names_plugin`] for `v`, the value of a key in [`PLUGIN_KEYS`] (or an item of one) when +/// `named`. +fn names_plugin_in(v: &Value, named: bool) -> bool { + match v { + Value::String(s) => named && s.starts_with(vectorcraft_plugins::PREFIX), + Value::Array(a) => a.iter().any(|x| names_plugin_in(x, named)), + Value::Object(o) => o.iter().any(|(k, x)| names_plugin_in(x, PLUGIN_KEYS.contains(&k.as_str()))), + _ => false, + } +} + +/// Commits an edit in progress in the active document (not a preview's), as [`transaction`] does → +/// whether that changed the document or its selection. A run that calls commands is prepared again +/// then, so its input is the document its calls change. +pub(crate) fn settle(s: &mut Session) -> Result { + if s.previewing { + return Ok(false); + } + let Some(before) = s.active().map(|d| (d.doc.clone(), d.selection.clone())) else { return Ok(false) }; + super::edit::settle_interaction(s)?; + Ok(s.active().is_none_or(|d| !Arc::ptr_eq(&before.0, &d.doc) || before.1 != d.selection)) +} + +/// What a run that makes command calls keeps fixed: the document it runs in, the documents open, +/// whether an interaction holds its changes (its own, or a preview's), and whether the plug-in may +/// read and change the document. +pub(crate) struct Calls { + document: Option, + open: Vec, + interaction: bool, + may_read: bool, + may_write: bool, +} + +impl Calls { + /// The run's fixed state in `s` as it is now; `may_read` and `may_write` are whether it has + /// `doc.read` and `doc.write`. + pub(crate) fn of(s: &Session, may_read: bool, may_write: bool) -> Calls { + let (document, open) = (s.active().map(|d| d.uid), s.docs.iter().map(|d| d.uid).collect()); + Calls { document, open, interaction: s.in_interaction(), may_read, may_write } + } + + /// Is `s` still as the run needs it: the same documents open, the same one active and the + /// interaction holding the run's changes still open? + fn kept(&self, s: &Session) -> bool { + s.active().map(|d| d.uid) == self.document + && s.docs.iter().map(|d| d.uid).eq(self.open.iter().copied()) + && (!self.interaction || s.in_interaction()) + } +} + +/// Makes plug-in call `id` with `args` in `s` → its result, or why it didn't run or failed. A +/// command a plug-in may never call ([`denied`]), one whose args name a plug-in, one that changes +/// which documents are open or active or ends the run's edit, and one that changes the document for +/// a plug-in without `doc.write` are refused, and so is every call of a plug-in without `doc.read`: +/// a command's result describes the document. +pub(crate) fn call(s: &mut Session, run: &Calls, id: &str, args: &Value) -> std::result::Result { + let refused = || CallFailure { code: CALL_DENIED_COMMAND, why: EngineError::Other("a plug-in may not call this command".into()).to_string() }; + if !run.may_read { + return Err(refused()); + } + let Some(spec) = super::find_command(id) else { + return Err(CallFailure { code: CALL_UNKNOWN_COMMAND, why: super::params::unknown_command(id).to_string() }); + }; + if denied(spec).is_some() || names_plugin(args) || names_file(id, args) { + return Err(refused()); + } + let before = s.active().map(|d| d.doc.clone()); + let r = execute_confined(s, id, args); + let value = match r { + Ok(v) => v, + Err(e @ EngineError::Disabled(..)) => return Err(CallFailure { code: CALL_DISABLED, why: e.to_string() }), + Err(e) => return Err(CallFailure { code: CALL_COMMAND_FAILED, why: e.to_string() }), + }; + let changed = before.is_some_and(|b| s.active().is_some_and(|d| !Arc::ptr_eq(&b, &d.doc))); + if !run.kept(s) || (changed && !run.may_write) { + return Err(refused()); + } + Ok(value) +} + +/// Runs command `id` with `args` in `s` with no file or folder readable or writable: every path the +/// command reaches through the checked file access ([`crate::file_access`]) is refused, whatever +/// param carries it. +fn execute_confined(s: &mut Session, id: &str, args: &Value) -> Result { + crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || s.execute(id, args)) +} + +/// Runs `f`, a plug-in run that makes command calls, as one undo step named `label` in the active +/// document: the commands it calls and the output it applies change the document inside one +/// interaction, which is kept when `f` succeeds. When `f` fails, every document goes back to how it +/// was (its art, selection, interaction and history), and so does the session state the commands a +/// plug-in may call change ([`Saved`]). During a preview the preview's own interaction holds the +/// changes. A trace handed in for the next Image Trace is set aside while `f` runs, so a call +/// traces anew, and handed back after; the next Image Trace still checks it was made of its inputs. +pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { + if s.active().is_some() && !s.previewing { + super::edit::settle_interaction(s)?; + } + let own = s.active().is_some() && !s.previewing && !s.in_interaction(); + if own { + s.begin_interaction(label)?; + } + let saved = Saved::of(s); + let start = s.docs.clone(); + let active = s.active; + let trace = s.trace_hand_off.take(); + let r = f(s); + s.trace_hand_off = trace; + match r { + Ok(v) => { + if own + && let Some(st) = s.active_mut() + && let Some(it) = st.interaction.take() + { + st.keep_interaction(it); + } + Ok(v) + } + Err(e) => { + let open = std::mem::replace(&mut s.docs, start); + for st in &mut s.docs { + // Past the newest revision the document reached, so the restored one redraws. + let newest = open.iter().filter(|d| d.uid == st.uid).map(|d| d.revision).max().unwrap_or(st.revision); + st.revision = newest.max(st.revision).saturating_add(1); + crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection); + } + s.active = active; + if own && let Some(st) = s.active_mut() { + st.interaction = None; + } + saved.restore(s); + Err(e) + } + } +} + +/// The session state outside the documents that a command a plug-in may call changes: the paint +/// defaults and the colors it remembers, the drawing mode, the clipboard, the undo group, the +/// preferences and menu checks, the selected gradient stop, mesh point and Appearance item, and the +/// options a command keeps for its next run. [`transaction`] puts it back when a run fails. +struct Saved { + paint: crate::PaintDefaults, + fill_active: bool, + draw_mode: crate::DrawMode, + draw_inside: Option, + clipboard: crate::Clipboard, + untitled_counter: u32, + explicit_undo_group: Option>, + prefs: crate::Prefs, + menu: super::menucmds::MenuState, + gradient_stop: Option<(usize, super::gradient::StopOwner)>, + freeform_point: Option<(usize, super::gradient::StopOwner)>, + active_appearance_item: Option, + eyedropper_sample: Option>, + last_solid: vectorcraft_color::Color, + last_gradient: vectorcraft_color::GradientPaint, + recent_colors: Vec, + recent_urls: Vec, + global_edit_options: super::globaledit::Options, + envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>, +} + +impl Saved { + fn of(s: &Session) -> Saved { + Saved { + paint: s.paint.clone(), + fill_active: s.fill_active, + draw_mode: s.draw_mode, + draw_inside: s.draw_inside, + clipboard: s.clipboard.clone(), + untitled_counter: s.untitled_counter, + explicit_undo_group: s.explicit_undo_group.clone(), + prefs: s.prefs.clone(), + menu: s.menu.clone(), + gradient_stop: s.gradient_stop, + freeform_point: s.freeform_point, + active_appearance_item: s.active_appearance_item.clone(), + eyedropper_sample: s.eyedropper_sample.clone(), + last_solid: s.last_solid, + last_gradient: s.last_gradient.clone(), + recent_colors: s.recent_colors.clone(), + recent_urls: s.recent_urls.clone(), + global_edit_options: s.global_edit_options.clone(), + envelope_defaults: s.envelope_defaults, + } + } + + fn restore(self, s: &mut Session) { + s.paint = self.paint; + s.fill_active = self.fill_active; + s.draw_mode = self.draw_mode; + s.draw_inside = self.draw_inside; + s.clipboard = self.clipboard; + s.untitled_counter = self.untitled_counter; + s.explicit_undo_group = self.explicit_undo_group; + s.prefs = self.prefs; + s.menu = self.menu; + s.gradient_stop = self.gradient_stop; + s.freeform_point = self.freeform_point; + s.active_appearance_item = self.active_appearance_item; + s.eyedropper_sample = self.eyedropper_sample; + s.last_solid = self.last_solid; + s.last_gradient = self.last_gradient; + s.recent_colors = self.recent_colors; + s.recent_urls = self.recent_urls; + s.global_edit_options = self.global_edit_options; + s.envelope_defaults = self.envelope_defaults; + s.pending_paint = None; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every command in the registry is sorted: the ones a plug-in may call name no file, folder, + /// clipboard, preference or script in their params text, and the known file, document, script + /// and history commands are refused. + #[test] + fn every_command_is_sorted() { + let specs = crate::cmd::command_specs(); + for id in [ + "document.save", + "file.revert", + "document.serialize", + "links.update", + "graphicStyle.libraries", + "symbol.libraries", + "brush.libraries", + "text.findFontFiles", + "plugin.run", + "plugin.install", + "command.batch", + "edit.undo", + "edit.redo", + "edit.copy", + "edit.paste", + "prefs.set", + ] { + let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; + assert!(denied(spec).is_some(), "{id} is allowed"); + } + for id in ["select.all", "object.transform", "path.reverse", "symbol.instance.selectPart"] { + let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; + assert_eq!(denied(spec), None, "{id} is refused"); + } + for (id, key) in NOT_FILES { + let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; + assert!(names_key(spec.params, key), "{id} has no `{key}` param"); + } + let leaks: Vec<&str> = specs + .iter() + .filter(|c| denied(c).is_none()) + .filter(|c| { + let lower = c.id.to_ascii_lowercase(); + FILE_WORDS.iter().any(|w| lower.contains(w)) + || FILE_KEYS.iter().any(|k| names_key(c.params, k) && !NOT_FILES.contains(&(c.id, *k))) + || names_key(c.params, "sourceDocument") + }) + .map(|c| c.id) + .collect(); + assert!(leaks.is_empty(), "allowed commands that name a file or another document: {leaks:?}"); + let allowed = specs.iter().filter(|c| denied(c).is_none()).count(); + assert!(allowed > 0 && allowed < specs.len()); + } + + /// Every command no rule refuses is in exactly one of [`reviewed::ALLOWED`] and + /// [`reviewed::DENIED`], and they name only such commands, in order: a command added to the + /// registry fails here until someone puts it in one. + #[test] + fn every_command_is_reviewed() { + for list in [reviewed::ALLOWED, reviewed::DENIED] { + assert!(list.windows(2).all(|w| w[0] < w[1]), "a reviewed list is out of order or names a command twice"); + } + let (allowed, refused) = (|id: &str| reviewed::ALLOWED.binary_search(&id).is_ok(), |id: &str| reviewed::DENIED.binary_search(&id).is_ok()); + let unreviewed: Vec<&str> = + crate::cmd::command_specs().iter().filter(|c| denied_by_rule(c).is_none() && allowed(c.id) == refused(c.id)).map(|c| c.id).collect(); + assert!(unreviewed.is_empty(), "commands in neither or both of reviewed::ALLOWED and reviewed::DENIED: {unreviewed:?}"); + let stale: Vec<&str> = reviewed::ALLOWED + .iter() + .chain(reviewed::DENIED) + .copied() + .filter(|id| crate::cmd::find_command(id).is_none_or(|c| denied_by_rule(c).is_some())) + .collect(); + assert!(stale.is_empty(), "reviewed commands that no command has or a rule refuses: {stale:?}"); + } + + /// Only an effect or a command naming a plug-in counts, at any depth; text that happens to + /// start with `plugin.` doesn't. + #[test] + fn a_plugin_is_named_only_as_an_effect_or_a_command() { + use serde_json::json; + assert!(names_plugin(&json!({"effect": "plugin.test.fx"}))); + assert!(names_plugin(&json!({"id": "plugin.test.fx"}))); + assert!(names_plugin(&json!({"effects": ["builtin.blur", "plugin.test.fx"]}))); + assert!(names_plugin(&json!({"items": [{"effect": "plugin.test.fx", "params": {}}]}))); + assert!(names_plugin(&json!({"command": "plugin.test.run"}))); + assert!(!names_plugin(&json!({"text": "plugin.example"}))); + assert!(!names_plugin(&json!({"name": "plugin.style", "effect": "drop-shadow"}))); + assert!(!names_plugin(&json!({"effect": {"name": "plugin.style"}}))); + } + + /// A file or folder key counts at any depth, in objects and in arrays; a key [`NOT_FILES`] names + /// for the command only at the top level; ordinary nested params don't count. + #[test] + fn a_file_key_counts_at_any_depth() { + use serde_json::json; + let texture = json!({"effect": "distort.glass", "params": {"textureImage": {"path": "/tmp/t.png"}}}); + assert!(names_file("effect.apply", &texture)); + assert!(names_file("effect.setParams", &texture)); + assert!(names_file("effect.apply", &json!({"params": {"layers": [{"name": "a"}, {"folder": "/tmp"}]}}))); + assert!(names_file("select.all", &json!([[[{"url": "file:///etc/hosts"}]]]))); + assert!(!names_file("effect.apply", &json!({"effect": "distort.glass", "params": {"distortion": 5, "textureImage": "frosted"}}))); + assert!(!names_file("object.move", &json!({"dx": 5, "dy": 0, "ids": [1, 2], "opts": {"copy": false}}))); + // `path` is a shape's path in object.setLiveShape, but only as its own param. + assert!(!names_file("object.setLiveShape", &json!({"path": [[0, 0], [1, 1]]}))); + assert!(names_file("object.setLiveShape", &json!({"options": {"path": "/tmp/x"}}))); + assert!(names_file("object.move", &json!({"path": [[0, 0]]}))); + // Deep nesting is walked without recursion. + let mut deep = json!({"file": "/tmp/x"}); + for _ in 0..10_000 { + deep = Value::Array(vec![deep]); + } + assert!(names_file("select.all", &deep)); + std::mem::forget(deep); + } + + /// A call reads no file even when a param the checks above don't know carries its path: the + /// command runs with no file readable. Run as an ordinary request, the same texture loads. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_confined_call_reads_no_file() { + use serde_json::json; + let file = std::env::temp_dir().join(format!("vc-plugin-call-texture-{}.png", std::process::id())); + let png = vectorcraft_trace::Raster::from_fn(8, 8, |x, y| if (x + y) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }).encode_png(); + std::fs::write(&file, png).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let p = json!({"effect": "distort.glass", "params": {"textureImage": {"path": file.to_string_lossy()}}}); + let e = execute_confined(&mut s, "effect.apply", &p).map(|_| ()).unwrap_err().to_string(); + let read = s.execute("effect.apply", &p).map(|_| ()); + let _ = std::fs::remove_file(&file); + assert!(e.contains("read authority is absent"), "{e}"); + read.unwrap(); + } + + #[test] + fn keys_are_found_as_whole_keys() { + assert!(names_key("{path: a .wasm file}", "path")); + assert!(names_key("{ids?: [id], path?: string}", "path")); + assert!(!names_key("{subpath: 1}", "path")); + assert!(!names_key("{x} on the path: the art", "the")); + assert!(!names_key("{pathData: 1}", "path")); + assert!(names_key("path: x", "path")); + } +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs new file mode 100644 index 0000000000..7759a57f00 --- /dev/null +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -0,0 +1,675 @@ +//! The commands no rule in [`super::denied`] refuses, each placed in one list: those a plug-in may +//! call ([`ALLOWED`]) and those it may not ([`DENIED`]). A command in neither is refused, and the +//! test `every_command_is_reviewed` fails until it is placed. + +/// Commands a plug-in may call when its manifest lists them, in order. +pub(super) const ALLOWED: &[&str] = &[ + "addon.arrange.grid", + "addon.arrange.groupOverlapping", + "addon.arrange.randomizeOpacity", + "addon.arrange.replace", + "addon.arrange.size", + "addon.arrange.sort", + "addon.arrange.swap", + "addon.cleanup.alignInPlace", + "addon.cleanup.breakText", + "addon.cleanup.check", + "addon.cleanup.combineText", + "addon.cleanup.deepUngroup", + "addon.cleanup.fix", + "addon.cleanup.joinText", + "addon.cleanup.rejoin", + "addon.cleanup.removeBreaks", + "addon.cleanup.replaceFonts", + "addon.cleanup.resetTextTransform", + "addon.cleanup.show", + "addon.cleanup.simplify", + "addon.color.applyNearestSwatch", + "addon.color.fillToStroke", + "addon.color.filter", + "addon.color.nearestSwatch", + "addon.color.select", + "addon.color.strokeToFill", + "addon.color.swatchLegend", + "addon.contour.set", + "addon.pathtools.addPoints", + "addon.pathtools.close", + "addon.pathtools.corner", + "addon.pathtools.cornerRemove", + "addon.pathtools.cornerSet", + "addon.pathtools.crossings", + "addon.pathtools.divideDashes", + "addon.pathtools.equalize", + "addon.pathtools.erase", + "addon.pathtools.expandDashes", + "addon.pathtools.extend", + "addon.pathtools.inspect", + "addon.pathtools.mergeEdge", + "addon.pathtools.removeKeepShape", + "addon.pathtools.setAnchor", + "addon.pathtools.shape.convert", + "addon.pathtools.shape.create", + "addon.pathtools.shape.set", + "addon.pathtools.slideAnchor", + "addon.pathtools.smooth", + "addon.pen.append", + "addon.pen.close", + "addon.pen.closeJoin", + "addon.pen.removePoint", + "addon.pen.reshape", + "addon.pen.segment", + "addon.pen.togglePoint", + "addon.select.byArtboards", + "addon.shapes.box3d", + "addon.shapes.configure", + "addon.shapes.ellipse", + "addon.shapes.polygon", + "addon.shapes.rectangle", + "addon.shapes.spiral", + "addon.shapes.star", + "addon.type.releasePath", + "addon.type.textTweaker", + "appearance.addEffect", + "appearance.addFill", + "appearance.addStroke", + "appearance.clear", + "appearance.copyFrom", + "appearance.duplicateItem", + "appearance.moveItem", + "appearance.reduceToBasic", + "appearance.removeItem", + "appearance.setActiveItem", + "appearance.setItem", + "appearance.showAllHidden", + "appearance.targetContents", + "appearance.transfer", + "artboard.convertToArtboards", + "artboard.delete", + "artboard.deleteEmpty", + "artboard.duplicate", + "artboard.fitToArt", + "artboard.fitToSelection", + "artboard.move", + "artboard.new", + "artboard.rearrange", + "artboard.rename", + "artboard.reorder", + "artboard.setProps", + "artboard.switchOrientation", + "attributes.info", + "attributes.set", + "brush.apply", + "brush.delete", + "brush.duplicate", + "brush.freehand", + "brush.get", + "brush.list", + "brush.move", + "brush.new", + "brush.options", + "brush.remove", + "brush.selectionArt", + "brush.setCurrent", + "brush.unused", + "charStyle.apply", + "charStyle.delete", + "charStyle.duplicate", + "charStyle.edit", + "charStyle.list", + "charStyle.new", + "charStyle.redefine", + "charStyle.rename", + "charStyle.setAttrs", + "charStyle.unused", + "color.convert", + "color.gamutCheck", + "color.harmony", + "color.plates", + "dataset.capture", + "dataset.delete", + "dataset.list", + "dataset.new", + "dataset.next", + "dataset.prev", + "dataset.rename", + "dataset.select", + "dataset.set", + "dataset.update", + "dimension.applyToAll", + "dimension.create", + "dimension.update", + "edit.clear", + "edit.colors.adjustBalance", + "edit.colors.blendFrontToBack", + "edit.colors.blendHorizontally", + "edit.colors.blendVertically", + "edit.colors.invert", + "edit.colors.saturate", + "edit.colors.toCMYK", + "edit.colors.toGrayscale", + "edit.colors.toRGB", + "edit.duplicate", + "edit.findNext", + "edit.findReplace", + "effect.apply", + "effect.duplicate", + "effect.expandAppearance", + "effect.list", + "effect.move", + "effect.remove", + "effect.setParams", + "flattener.preview", + "gradient.selectStop", + "graph.column", + "graph.create", + "graph.design", + "graph.marker", + "graph.setData", + "graph.setType", + "graphicStyle.apply", + "graphicStyle.delete", + "graphicStyle.duplicate", + "graphicStyle.list", + "graphicStyle.merge", + "graphicStyle.move", + "graphicStyle.new", + "graphicStyle.redefine", + "graphicStyle.rename", + "graphicStyle.sortByName", + "graphicStyle.unused", + "guide.add", + "guide.list", + "guide.move", + "guide.remove", + "guide.select", + "guide.setLayer", + "image.info", + "imageTrace.expand", + "imageTrace.make", + "imageTrace.makeAndExpand", + "imageTrace.release", + "imageTrace.setView", + "layer.clippingMask.toggle", + "layer.collectInNew", + "layer.delete", + "layer.duplicate", + "layer.flatten", + "layer.hideOthers", + "layer.highlight", + "layer.locate", + "layer.lockOthers", + "layer.merge", + "layer.move", + "layer.new", + "layer.newSublayer", + "layer.outlineOthers", + "layer.previewAll", + "layer.releaseToLayers", + "layer.releaseToLayersBuild", + "layer.reverse", + "layer.selectAll", + "layer.setCurrent", + "layer.setProps", + "layer.showAll", + "layer.target", + "layer.template", + "layer.unlockAll", + "livePaint.expand", + "livePaint.fill", + "livePaint.gapOptions", + "livePaint.info", + "livePaint.make", + "livePaint.merge", + "livePaint.release", + "livePaint.strokeEdge", + "node.move", + "object.align", + "object.arrange.bringForward", + "object.arrange.bringToFront", + "object.arrange.sendBackward", + "object.arrange.sendToBack", + "object.arrange.sendToCurrentLayer", + "object.blend.expand", + "object.blend.info", + "object.blend.make", + "object.blend.release", + "object.blend.replaceSpine", + "object.blend.reverseFrontToBack", + "object.blend.reverseSpine", + "object.blend.spine.addAnchor", + "object.blend.spine.convertAnchor", + "object.blend.spine.moveAnchor", + "object.blend.spine.removeAnchor", + "object.blend.spine.reshapeSegment", + "object.clippingMask.editContents", + "object.clippingMask.editMask", + "object.clippingMask.make", + "object.clippingMask.release", + "object.compoundPath.make", + "object.compoundPath.release", + "object.compoundShape.expand", + "object.compoundShape.make", + "object.compoundShape.release", + "object.compoundShape.setMode", + "object.convertDocumentColorMode", + "object.createObjectMosaic", + "object.createTrimMarks", + "object.cropImage", + "object.distort", + "object.distribute", + "object.distributeSpacing", + "object.envelope.editContents", + "object.envelope.expand", + "object.envelope.info", + "object.envelope.makeWithMesh", + "object.envelope.makeWithTopObject", + "object.envelope.makeWithWarp", + "object.envelope.options", + "object.envelope.release", + "object.envelope.resetWithMesh", + "object.envelope.resetWithWarp", + "object.envelope.setMeshPoint", + "object.exitIsolation", + "object.expand", + "object.expand.info", + "object.expandBrush", + "object.expandShape", + "object.flattenTransparency", + "object.group", + "object.hide", + "object.hide.above", + "object.hide.otherLayers", + "object.hide.unselected", + "object.intertwine.arrange", + "object.intertwine.edit", + "object.intertwine.make", + "object.intertwine.release", + "object.isolate", + "object.lock", + "object.lock.above", + "object.lock.otherLayers", + "object.lock.unselected", + "object.makePixelPerfect", + "object.maskImage", + "object.mesh.addLine", + "object.mesh.create", + "object.mesh.deletePoint", + "object.mesh.expand", + "object.mesh.movePoint", + "object.mesh.movePoints", + "object.mesh.setPointColor", + "object.move", + "object.nudge", + "object.objectsOnPath.attach", + "object.objectsOnPath.expand", + "object.objectsOnPath.options", + "object.path.addAnchorPoints", + "object.path.cleanUp", + "object.path.divideObjectsBelow", + "object.path.offsetPath", + "object.path.outlineStroke", + "object.path.simplify", + "object.path.smooth", + "object.path.splitIntoGrid", + "object.pathfinder.crop", + "object.pathfinder.divide", + "object.pathfinder.exclude", + "object.pathfinder.intersect", + "object.pathfinder.merge", + "object.pathfinder.minusBack", + "object.pathfinder.minusFront", + "object.pathfinder.outline", + "object.pathfinder.trap", + "object.pathfinder.trim", + "object.pathfinder.unite", + "object.pattern.cancel", + "object.pattern.done", + "object.pattern.edit", + "object.pattern.make", + "object.puppetWarp", + "object.puppetWarp.pins", + "object.rasterize", + "object.reflect", + "object.repeat.expand", + "object.repeat.grid", + "object.repeat.mirror", + "object.repeat.options", + "object.repeat.radial", + "object.repeat.release", + "object.resetBoundingBox", + "object.rotate", + "object.scale", + "object.setBounds", + "object.setLiveShape", + "object.setPixelAligned", + "object.setProps", + "object.shape.convertToShape", + "object.shear", + "object.showAll", + "object.slice.clipToArtboard", + "object.slice.combine", + "object.slice.create", + "object.slice.delete", + "object.slice.deleteAll", + "object.slice.divide", + "object.slice.duplicate", + "object.slice.fromGuides", + "object.slice.fromSelection", + "object.slice.make", + "object.slice.move", + "object.slice.options", + "object.slice.release", + "object.slice.select", + "object.slice.setRect", + "object.textWrap.make", + "object.textWrap.options", + "object.textWrap.release", + "object.transform", + "object.transformAgain", + "object.transformEach", + "object.ungroup", + "object.unlockAll", + "object.vectorHalftone", + "paint.complement", + "paint.default", + "paint.editGradient", + "paint.freeform.addLine", + "paint.freeform.addPoint", + "paint.freeform.deletePoint", + "paint.freeform.get", + "paint.freeform.selectPoint", + "paint.freeform.setPoint", + "paint.freeform.splitLine", + "paint.invert", + "paint.lastColor", + "paint.lastGradient", + "paint.none", + "paint.proxies", + "paint.recent", + "paint.sampleColor", + "paint.setFill", + "paint.setGradientGeom", + "paint.setStroke", + "paint.swap", + "paint.toggleActive", + "paraStyle.apply", + "paraStyle.delete", + "paraStyle.duplicate", + "paraStyle.list", + "paraStyle.new", + "paraStyle.redefine", + "paraStyle.rename", + "paraStyle.setAttrs", + "paraStyle.unused", + "path.appendAnchor", + "path.average", + "path.averageJoin", + "path.blob", + "path.close", + "path.convertAnchor", + "path.convertAnchors", + "path.create", + "path.curvature", + "path.curvatureEdit", + "path.cutAtAnchors", + "path.deleteAnchors", + "path.eraseRegion", + "path.eraseSegments", + "path.freehand", + "path.insertAnchor", + "path.join", + "path.joinScrub", + "path.knife", + "path.lineCut", + "path.mirrorCut", + "path.moveAnchor", + "path.moveAnchors", + "path.rectCut", + "path.removeAnchor", + "path.removeAnchors", + "path.reshape", + "path.reshapeSegment", + "path.reverse", + "path.setAnchors", + "path.setFillRule", + "path.setHandle", + "path.smoothRegion", + "path.split", + "pattern.delete", + "pattern.list", + "pattern.options", + "pattern.transform", + "perspective.attach", + "perspective.draw", + "perspective.editText", + "perspective.grid.define", + "perspective.grid.get", + "perspective.grid.lock", + "perspective.grid.lockStation", + "perspective.grid.rulers", + "perspective.grid.set", + "perspective.grid.show", + "perspective.grid.snap", + "perspective.move", + "perspective.nudge", + "perspective.plane.matchObject", + "perspective.plane.move", + "perspective.plane.set", + "perspective.release", + "perspective.transform", + "recolor.apply", + "recolor.colors", + "recolor.randomize", + "recolor.reduce", + "select.add", + "select.all", + "select.allOnArtboard", + "select.anchors", + "select.anchorsMany", + "select.color", + "select.font", + "select.globalEdit", + "select.globalEditExclude", + "select.globalEditOptions", + "select.inverse", + "select.key", + "select.magicWand", + "select.nextAbove", + "select.nextBelow", + "select.none", + "select.object.allOnSameLayers", + "select.object.areaText", + "select.object.bristleBrushStrokes", + "select.object.brushStrokes", + "select.object.clippingMasks", + "select.object.directionHandles", + "select.object.pointText", + "select.object.slices", + "select.object.strayPoints", + "select.object.textObjects", + "select.recall", + "select.reselect", + "select.same.appearance", + "select.same.appearanceAttribute", + "select.same.blendingMode", + "select.same.fillAndStroke", + "select.same.fillColor", + "select.same.fontFamily", + "select.same.fontFamilyStyle", + "select.same.fontFamilyStyleSize", + "select.same.fontSize", + "select.same.graphicStyle", + "select.same.opacity", + "select.same.shapeType", + "select.same.strokeColor", + "select.same.strokeWeight", + "select.same.symbolInstance", + "select.same.textFillAndStrokeColor", + "select.same.textFillColor", + "select.same.textStrokeColor", + "select.segments", + "select.set", + "select.toggle", + "select.update", + "shape.arc", + "shape.ellipse", + "shape.flare", + "shape.line", + "shape.polarGrid", + "shape.polygon", + "shape.rectangle", + "shape.rectangularGrid", + "shape.spiral", + "shape.star", + "shapeBuilder.merge", + "shapeBuilder.regions", + "shaper.expand", + "shaper.release", + "shaper.releaseSource", + "shaper.scribble", + "shaper.select", + "slice.list", + "stroke.set", + "stroke.setAdvanced", + "stroke.weightDown", + "stroke.weightUp", + "stroke.widthPoint.copy", + "stroke.widthPoint.remove", + "stroke.widthPoint.set", + "svgFilter.apply", + "svgFilter.define", + "svgFilter.delete", + "svgFilter.list", + "svgInteractivity.clearEvents", + "svgInteractivity.info", + "svgInteractivity.removeEvent", + "svgInteractivity.setEvent", + "swatch.addUsedColors", + "swatch.delete", + "swatch.duplicate", + "swatch.edit", + "swatch.editGroup", + "swatch.list", + "swatch.merge", + "swatch.move", + "swatch.new", + "swatch.newGroup", + "swatch.resetDefaults", + "swatch.setSpot", + "swatch.sortByKind", + "swatch.sortByName", + "swatch.spotOptions", + "swatch.ungroup", + "swatch.unused", + "symbol.adjust", + "symbol.delete", + "symbol.duplicate", + "symbol.edit", + "symbol.exitEditing", + "symbol.instance.reset", + "symbol.instance.resetTransform", + "symbol.instance.selectPart", + "symbol.instance.setAppearance", + "symbol.list", + "symbol.new", + "symbol.options", + "symbol.place", + "symbol.replace", + "symbol.selectInstances", + "symbol.setCurrent", + "symbol.spray", + "symbol.unused", + "symbol.update", + "text.areaOptions", + "text.convertListToText", + "text.create", + "text.createInPath", + "text.discardEmpty", + "text.editRange", + "text.fitHeadline", + "text.fonts", + "text.getRange", + "text.glyphAlternates", + "text.insertInline", + "text.missingFonts", + "text.replaceFont", + "text.reshapeArea", + "text.reshapePath", + "text.setFormat", + "text.setGlyphAlternate", + "text.setPathHandle", + "text.setRangeStyle", + "text.setStyle", + "text.setText", + "text.startList", + "text.tabs.clear", + "text.tabs.get", + "text.tabs.set", + "text.thread.add", + "text.thread.break", + "text.thread.create", + "text.thread.info", + "text.thread.releaseSelection", + "text.thread.remove", + "text.touchType", + "transparency.disableOpacityMask", + "transparency.editOpacityMask", + "transparency.enableOpacityMask", + "transparency.info", + "transparency.makeOpacityMask", + "transparency.opacityMaskInfo", + "transparency.releaseOpacityMask", + "transparency.set", + "transparency.setOpacityMask", + "transparency.stopEditingOpacityMask", + "transparency.togglePageIsolatedBlending", + "transparency.togglePageKnockoutGroup", + "transparency.viewOpacityMask", + "type.changeCase", + "type.compositeFonts.list", + "type.convertToAreaType", + "type.convertToPointType", + "type.createOutlines", + "type.fillPlaceholder", + "type.fitHeadline", + "type.insert", + "type.opticalMarginAlignment", + "type.orientation.horizontal", + "type.orientation.vertical", + "type.pathOptions", + "type.resetHorizontalScale", + "type.resetTracking", + "type.ruby", + "type.scaleTextAttributes", + "type.size.decrease", + "type.size.decreaseByFive", + "type.size.increase", + "type.size.increaseByFive", + "type.smartPunctuation", + "type.step", + "variable.bind", + "variable.define", + "variable.delete", + "variable.highlight", + "variable.list", + "variable.lock", + "variable.makeGraphDynamic", + "variable.makeImageDynamic", + "variable.makeTextDynamic", + "variable.makeVisibilityDynamic", + "variable.rename", + "variable.unbind", +]; + +/// Commands a plug-in may not call although no rule refuses them, in order: they change the +/// preferences, a tool's options, a drag's state or the font names the whole app knows. +pub(super) const DENIED: &[&str] = &[ + "addon.cleanup.splitText", + "addon.pathtools.movePointsTogether", + "addon.pen.nextSegment", + "graphicStyle.setOptions", + "object.blend.options", + "object.liquify", + "object.pathfinder.options", + "type.compositeFonts.set", +]; diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index f3cf6416f8..ef8b156b69 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -140,6 +140,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool), p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool), p!("showToolTips", "General", "Options", "Show Tool Tips", bool), + p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool), p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool), p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool), p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool), @@ -227,6 +228,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ // Guides & Grid p!("guideColor", "Guides & Grid", "Guides", "Color", color), p!("guideStyle", "Guides & Grid", "Guides", "Style", choice(LINE_STYLE)), + p!("lockGuidesByDefault", "Guides & Grid", "Guides", "Lock Guides by Default", bool), p!("gridColor", "Guides & Grid", "Grid", "Color", color), p!("gridStyle", "Guides & Grid", "Grid", "Style", choice(LINE_STYLE)), p!("gridlineEvery", "Guides & Grid", "Grid", "Gridline every", len(1.0, 16383.0, General)), @@ -434,6 +436,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ // The Align panel menu's Align to Glyph Bounds: Align and Distribute measure type by its glyphs' ink. p!("alignGlyphBoundsPoint", "Type", "Align to Glyph Bounds", "Point Text", bool), p!("alignGlyphBoundsArea", "Type", "Align to Glyph Bounds", "Area Text", bool), + // The bounding box and the Transform panel measure point type by its glyphs' ink (also in the Transform panel menu). + p!("typeGlyphBounds", "Type", "Glyph Bounds", "Measure Type by Glyph Bounds", bool), // Artboard Options › Global: the canvas darkens the area outside the artboards while the Artboard tool is active. p!("fadeRegionOutsideArtboard", "General", "Artboard Options", "Fade Region Outside Artboard", bool), p!("artboardUpdateWhileDragging", "General", "Artboard Options", "Update While Dragging", bool), @@ -690,10 +694,16 @@ impl Session { let fonts_folder_changed = p.fonts_folder != self.prefs.fonts_folder; let hyphen_exceptions_changed = p.hyphenation_exceptions != self.prefs.hyphenation_exceptions; let corner_radius_changed = p.corner_radius != self.prefs.corner_radius; + let lock_guides_changed = p.lock_guides_by_default != self.prefs.lock_guides_by_default; if p.trace_presets != self.prefs.trace_presets { self.trace_preset_changes.replaced(); } self.prefs = p; + // Guides & Grid › Lock Guides by Default sets the lock when it changes, the saved value at + // start included. Otherwise the lock stays as View › Guides › Lock Guides left it. + if lock_guides_changed { + self.set_guides_locked(self.prefs.lock_guides_by_default); + } if corner_radius_changed { // General › Corner Radius is the Rounded Rectangle tool's radius (#394): a tool already // made (active, or lent a selection tool for a drag) takes the new value. diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index a06597ac8a..4cf070c6ae 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -766,11 +766,14 @@ pub fn skip_reason(s: &Session, st: &DocState) -> Option<&'static str> { return Some("unchanged since its last recovery copy"); } if s.prefs.recovery_off_for_complex && object_count(&st.doc) > COMPLEX_OBJECTS { - return Some("complex document (Data Recovery is off for complex documents)"); + return Some(COMPLEX_SKIP); } None } +/// Why a complex document with unsaved changes gets no copy. +const COMPLEX_SKIP: &str = "complex document (Data Recovery is off for complex documents)"; + /// A file name part from a title: letters, digits, `-`, `_` and spaces (others as `-`). fn safe_stem(title: &str) -> String { let stem: String = fileio::file_stem(title).chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ') { c } else { '-' }).collect(); @@ -866,8 +869,35 @@ fn remove_copy(s: &Session, file: &str) { } } -/// Document `uid` was saved, reverted or closed: its recovery copy goes. +/// Closed document `st`'s recovery copy goes. +pub(crate) fn forget_closed(s: &Session, st: &crate::DocState) { + if let Some(copy) = &st.recovery { + remove_copy(s, ©.file); + } +} + +/// Writes a copy of every document that needs one now. An error when a document with unsaved +/// changes would be left without a current copy. +pub(crate) fn save_copies(s: &mut Session) -> Result<()> { + let store = need_store(s, "script.run")?; + let (jobs, _) = jobs(s, &store)?; + let uncopied = s.documents().iter().any(|st| skip_reason(s, st) == Some(COMPLEX_SKIP)); + if uncopied { + return Err(EngineError::Other("a document with unsaved changes has no recovery copy".into())); + } + for j in jobs { + j.write(store.as_ref()).map_err(EngineError::Other)?; + j.finish(s); + } + Ok(()) +} + +/// Document `uid` was saved, reverted or closed: its recovery copy goes. While a script runs the +/// run's commit settles that. pub fn forget(s: &mut Session, uid: u64) { + if s.script_in_run { + return; + } let Some(copy) = s.document_mut(uid).and_then(|st| st.recovery.take()) else { return }; remove_copy(s, ©.file); } diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 45f2670488..b8b5448817 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -11,21 +11,139 @@ use vectorcraft_scriptcheck::{Limits, Loaded, Loader, Report}; /// The ids a reply can hold, for the windows that show it. pub use vectorcraft_scriptcheck::{IncludeStatus, Need, OUTSIDE, PROBLEMS}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, str_param}; +use crate::script; /// The extensions of the scripts File › Open shows a check for. pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"]; +/// The extensions of the scripts `script.run` takes as a file, in any case. +pub const RUN_EXTS: &[&str] = &["js", "jsx"]; + +/// Does `path` name a file `script.run` takes? +pub fn runs(path: &str) -> bool { + std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| RUN_EXTS.iter().any(|x| e.eq_ignore_ascii_case(x))) +} + pub fn specs() -> Vec { - vec![cmd!( - query "script.check", - "Check Script", - [], - None, - "{path? | data?: the script's text | dataBase64?, name?: the file's name (default: the path's; with a path, only the reply's name), includes?: false (with a path: also check the files its #include lines name, inside the script's folder; not on the web)} check a script written for the reference app (.jsx, .jsxinc, .js, or a compiled .jsxbin) without running any of it → {name, kind: script|compiled|module|notText|tooLarge, needs: [language|dom|files|menuCommands|dialogs|hostOnly], lines, targets: [{value, app, instance?, version?, locale?, line, file?}], directives: [{name, value, line, form: \"#\"|\"//@\", file?}], includes: [{value, line, status: checked|missing|notFollowed|cycle|notRead|limit|unreadable, path?, file?}], features: [{id, count, lines}], dom: {members: [{path, count}], types: [{name, count}]}, menuCommands: {strings: [{value, count, lines}], dynamic}, outside: [{id: filesWritten|filesOpened|network|nativeCode|otherApps|environment|unseenCode|preferences, count, lines, modes?}], problems: [{code, line?, file?, detail?}], truncated} (file: the included file it is in; lines: at most 20 of the script's own, while counts include the included files; at most 8 MiB a file and 32 MiB in all, 64 included files 16 deep, 1,024 paths looked up for them, 1,000 entries a list, text echoed cut to 120 characters)", - always, - check - )] + vec![ + cmd!( + query "script.run", + "Run Script", + [], + None, + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport", + always, + run + ), + cmd!( + query "script.stop", + "Stop Script", + [], + None, + "{} stop the running script, which puts every document back as it was before the run; asking again while it stops is harmless → {stopped: whether a script was running}", + always, + stop + ), + cmd!( + query "script.check", + "Check Script", + [], + None, + "{path? | data?: the script's text | dataBase64?, name?: the file's name (default: the path's; with a path, only the reply's name), includes?: false (with a path: also check the files its #include lines name, inside the script's folder; not on the web)} check a script written for the reference app (.jsx, .jsxinc, .js, or a compiled .jsxbin) without running any of it → {name, kind: script|compiled|module|notText|tooLarge, needs: [language|dom|files|menuCommands|dialogs|hostOnly], lines, targets: [{value, app, instance?, version?, locale?, line, file?}], directives: [{name, value, line, form: \"#\"|\"//@\", file?}], includes: [{value, line, status: checked|missing|notFollowed|cycle|notRead|limit|unreadable, path?, file?}], features: [{id, count, lines}], dom: {members: [{path, count}], types: [{name, count}]}, menuCommands: {strings: [{value, count, lines}], dynamic}, outside: [{id: filesWritten|filesOpened|network|nativeCode|otherApps|environment|unseenCode|preferences, count, lines, modes?}], problems: [{code, line?, file?, detail?}], truncated} (file: the included file it is in; lines: at most 20 of the script's own, while counts include the included files; at most 8 MiB a file and 32 MiB in all, 64 included files 16 deep, 1,024 paths looked up for them, 1,000 entries a list, text echoed cut to 120 characters)", + always, + check + ), + ] +} + +/// A refusal of `script.run`'s parameters, which only a program's own call can give. +fn param(msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: "script.run".into(), msg: msg.into() } +} + +/// `maxFuel`: a whole number from 1 to [`script::MAX_FUEL`], or the default when omitted. +fn max_fuel(p: &Value) -> Result { + let Some(v) = p.get("maxFuel") else { return Ok(script::DEFAULT_FUEL) }; + v.as_u64() + .filter(|n| (1..=script::MAX_FUEL).contains(n)) + .ok_or_else(|| param(format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL))) +} + +/// The text of a script read as bytes: a byte order mark is left out, and compiled scripts and +/// bytes that are not UTF-8 are refused. +fn script_text(bytes: &[u8]) -> Result { + if bytes.starts_with(b"@JSXBIN@") { + return Err(EngineError::Other(COMPILED.to_string())); + } + let text = std::str::from_utf8(bytes).map_err(|_| EngineError::Other(NOT_TEXT.to_string()))?; + Ok(text.strip_prefix('\u{feff}').unwrap_or(text).to_string()) +} + +const COMPILED: &str = "this is a compiled script, which cannot be run; use its source text"; +const NOT_TEXT: &str = "the script is not UTF-8 text"; +/// The error for a script over [`script::MAX_SOURCE_BYTES`]. +pub const TOO_LARGE: &str = "the script is too large to run"; + +fn run(s: &mut Session, p: &Value) -> Result { + let optional_str = |key: &str| match p.get(key) { + None => Ok(None), + Some(Value::String(t)) => Ok(Some(t.as_str())), + Some(_) => Err(param(format!("`{key}` must be a string"))), + }; + let (path, source, given_name) = (optional_str("path")?, optional_str("source")?, optional_str("name")?); + // Checked before anything copies or writes out `args`, which would go one call deeper per level. + if let Some(place) = p.get("args").and_then(script::too_deep) { + return Err(param(format!("`args{place}` is nested more than 64 levels deep"))); + } + let args = match p.get("args") { + None => serde_json::Map::new(), + Some(Value::Object(o)) => o.clone(), + Some(_) => return Err(param("`args` must be an object")), + }; + if serde_json::to_vec(&args).map_or(true, |b| b.len() > script::MAX_ARGS_BYTES) { + return Err(param("`args` is larger than 1 MiB")); + } + match p.get("answers") { + None => {} + Some(Value::Object(o)) if o.is_empty() => {} + Some(_) => return Err(param("`answers` must be an empty object: scripts cannot ask questions yet")), + } + let fuel = max_fuel(p)?; + let text = match (path, source) { + (Some(""), None) => return Err(param("`path` is empty")), + (Some(path), None) => { + if path.to_ascii_lowercase().ends_with(".jsxbin") { + return Err(EngineError::Other(COMPILED.to_string())); + } + if !runs(path) { + return Err(param("`path` must name a .js or .jsx file")); + } + // One byte more than a script may have shows that the file is too large. + let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?; + if bytes.len() > script::MAX_SOURCE_BYTES { + return Err(EngineError::Other(TOO_LARGE.to_string())); + } + script_text(&bytes)? + } + (None, Some(source)) => { + if source.len() > script::MAX_SOURCE_BYTES { + return Err(EngineError::Other(TOO_LARGE.to_string())); + } + script_text(source.as_bytes())? + } + _ => return Err(param("give exactly one of `path` and `source`")), + }; + let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string()); + s.script_start(script::Request { name: name.clone(), source: text, args, fuel })?; + if s.script_frames { + return Ok(json!({"running": true, "name": name})); + } + s.script_run_to_end() +} + +fn stop(s: &mut Session, _: &Value) -> Result { + Ok(json!({"stopped": s.script_request_stop()})) } /// The folder a script is in, which its included files are read from. diff --git a/crates/engine/src/cmd/spelling.rs b/crates/engine/src/cmd/spelling.rs index 8ae2a49c29..35d1a12774 100644 --- a/crates/engine/src/cmd/spelling.rs +++ b/crates/engine/src/cmd/spelling.rs @@ -85,6 +85,15 @@ pub fn specs() -> Vec { always, change_word ), + cmd!( + query "text.spelling.editDictionary", + "Edit Custom Dictionary", + [], + None, + "{remove?: [word…], add?: [word…] (each one word, at most 64 characters; at most 10000 of each)} deletes the words of remove that are there and adds those of add, then saves once: all of it, or none of it when the save fails (Edit Custom Dictionary's Done) → {removed: [word…], added: [word…]}", + always, + edit_dictionary + ), cmd!( query "text.spelling.ignoreAll", "Ignore All", @@ -223,6 +232,12 @@ fn suggest(_s: &mut Session, p: &Value) -> Result { Ok(json!({ "suggestions": suggestions })) } +/// `w` as the custom dictionary keeps it (trimmed, lower case), or None when it isn't one word of at +/// most `craft_proof::MAX_CUSTOM_WORD_CHARS` characters: what `text.spelling.addWord` takes. +pub fn custom_word(w: &str) -> Option { + craft_proof::custom_word(w) +} + /// `p`'s `key` as a custom-dictionary word (trimmed, lower case), or an error naming what it must be. fn word_param(p: &Value, key: &str, command: &str) -> Result { let w = str_param(p, key).ok_or_else(|| bad(command, format!("missing `{key}`")))?; @@ -342,6 +357,62 @@ fn change_word(s: &mut Session, p: &Value) -> Result { Ok(json!({ "word": to })) } +/// Most words `text.spelling.editDictionary` takes in each of its lists. +const MAX_EDIT_WORDS: usize = 10_000; + +/// `p`'s `key`, a list of custom-dictionary words (none when it is missing), deduplicated. +fn word_list(p: &Value, key: &str, command: &str) -> Result> { + let Some(v) = p.get(key) else { return Ok(BTreeSet::new()) }; + let words = v.as_array().ok_or_else(|| bad(command, format!("`{key}` must be a list of words")))?; + if words.len() > MAX_EDIT_WORDS { + return Err(bad(command, format!("`{key}` holds more than {MAX_EDIT_WORDS} words"))); + } + words + .iter() + .map(|w| { + w.as_str() + .and_then(craft_proof::custom_word) + .ok_or_else(|| bad(command, format!("`{key}` must hold single words of at most {} characters", craft_proof::MAX_CUSTOM_WORD_CHARS))) + }) + .collect() +} + +/// `text.spelling.editDictionary`: Edit Custom Dictionary's Done. Every delete and add is made, +/// then saved once; when the save fails, all of them are taken back, so a failed Done leaves the +/// dictionary as it was rather than half changed. +fn edit_dictionary(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.spelling.editDictionary"; + let (remove, add) = (word_list(p, "remove", C)?, word_list(p, "add", C)?); + let before: BTreeSet = craft_proof::user_dictionary().into_iter().collect(); + // A word in both lists stays; a word to delete that another window deleted already is skipped. + let removed: Vec = remove.iter().filter(|w| !add.contains(*w) && before.contains(*w)).cloned().collect(); + let added: Vec = add.iter().filter(|w| !before.contains(*w)).cloned().collect(); + if removed.is_empty() && added.is_empty() { + return Ok(json!({ "removed": removed, "added": added })); + } + for w in &removed { + craft_proof::remove_word(w); + } + for w in &added { + craft_proof::add_word(w); + } + let saved = save_dictionary(s, &removed, C); + dictionary_changed(); + saved.inspect_err(|_| { + for w in &added { + craft_proof::remove_word(w); + } + for w in &removed { + craft_proof::add_word(w); + } + // Words the save took in from the file stay, as for one word. + if !added.is_empty() { + retake_file_words(s); + } + })?; + Ok(json!({ "removed": removed, "added": added })) +} + /// `text.spelling.ignoreAll`: Ignore All, for the active document. fn ignore_all(s: &mut Session, p: &Value) -> Result { const C: &str = "text.spelling.ignoreAll"; diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 1fb3373c7a..e97659bfc9 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index a3745975b0..22cfc74e9f 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -140,7 +140,7 @@ pub(crate) fn enter(s: &mut Session, p: &Value) -> Result { } s.end_text_edit(); let st = s.doc()?; - let back = Return { redo: st.history.redo.clone(), before: Some(st.doc.clone()) }; + let back = Return { redo: Arc::new(st.history.redo.clone()), before: Some(st.doc.clone()) }; let (isolation, active_layer) = (st.isolation, st.active_layer); let layer = s.edit(ENTER, |d, sel| { let layer = begin(d, sel, &name, xf, instance)?; @@ -229,7 +229,7 @@ pub(crate) fn leave(s: &mut Session, _: &Value) -> Result { } st.selection = Arc::unwrap_or_clone(entry.selection); st.selection.prune(&st.doc); - st.history.redo = redo; + st.history.redo = Arc::unwrap_or_clone(redo); st.revision += 1; } else { s.edit("Exit Symbol Editing Mode", |d, sel| { @@ -257,9 +257,10 @@ pub(crate) fn finish(d: &mut Document, sel: &mut Selection) { /// The redo steps entering symbol editing mode cleared, which leaving without an edit gives back, /// and the document entering started from, which tells the entering step apart from any other. +/// Copies of the document's state share the redo steps. #[derive(Clone, Debug, Default)] pub(crate) struct Return { - redo: Vec, + redo: Arc>, before: Option>, } diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 1e74eb4563..fe3f1149da 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -157,6 +157,7 @@ pub struct BuiltinSymbolLibrary { pub const BUILTIN: &[BuiltinSymbolLibrary] = &[ BuiltinSymbolLibrary { id: "basic-shapes", name: "Basic Shapes", make: basic_shapes }, BuiltinSymbolLibrary { id: "ui-frames", name: "UI Frames", make: ui_frames }, + BuiltinSymbolLibrary { id: "map-markers", name: "Map Markers", make: map_markers }, ]; /// Built-in library `id`, made once. @@ -221,6 +222,33 @@ fn ui_frames() -> SymbolLibrary { SymbolLibrary { name: "UI Frames".into(), doc } } +/// Map Markers: pin, flag, crosshair and checkpoint for map/HUD art (original, no 9-slice). +fn map_markers() -> SymbolLibrary { + let c = Point::ZERO; + let pin = [(0.0, 22.0), (-9.0, 4.0), (-12.0, -6.0), (-8.0, -16.0), (0.0, -20.0), (8.0, -16.0), (12.0, -6.0), (9.0, 4.0)]; + let flag = [(-16.0, 22.0), (-12.0, 22.0), (-12.0, -8.0), (18.0, -14.0), (-12.0, -20.0), (-12.0, -22.0), (-16.0, -22.0)]; + let pin: Vec = pin.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let flag: Vec = flag.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let markers = [ + ("Pin", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pin, true)), "#e74c3c"), + ("Flag", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&flag, true)), "#3498db"), + ("Crosshair", shapes::star(c, 20.0, 5.0, 4, 0.0), "#2c3e50"), + ("Checkpoint", shapes::polygon(c, 18.0, 4, 0.0), "#27ae60"), + ]; + let mut doc = Document::new(100.0, 100.0); + for (name, path, hex) in markers { + let fill = Color::from_hex(hex).unwrap_or(Color::BLACK); + let edge = fill.lerp(&Color::BLACK, 0.35); + let id = doc.alloc_id(); + let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.25)); + let Ok((art, size, _)) = normalize(art) else { continue }; + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + set_natural_size(&mut doc, name, Some(size)); + } + doc.title = "Map Markers".into(); + SymbolLibrary { name: "Map Markers".into(), doc } +} + /// An instance of symbol `name` (what the resource gathering follows). fn instance(name: &str) -> Node { Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index a1bb2c64eb..b6d20999a0 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1611,6 +1611,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { list_level_counts: Vec::new(), cached_bounds: None, cached_baselines: Vec::new(), + cached_ink: None, }; super::create::new_type_alignment(s, p, C, &mut t)?; if !on_path { @@ -1901,6 +1902,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option { list_level_counts: Vec::new(), cached_bounds: None, cached_baselines: Vec::new(), + cached_ink: None, }; for r in &mut h.runs { r.style.tracking = tr; diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index b877a130ce..3fd8e8f231 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -48,7 +48,7 @@ impl Kind { /// One command spec (the `cmd!` macro wants literals; these ids are built with `concat!`). const fn spec(id: &'static str, label: &'static str, menu: &'static [&'static str], params: &'static str, run: Run, journal: bool) -> CommandSpec { - CommandSpec { id, label, menu, shortcut: None, params, enabled: has_doc, run, journal } + CommandSpec { id, label, menu, shortcut: None, params, enabled: has_doc, run, journal, schema: None } } macro_rules! style_cmds { diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index c0e5b37fea..2257b1a8ae 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -115,6 +115,15 @@ pub fn specs() -> Vec { has_doc, reshape_path ), + cmd!( + "text.setPathHandle", + "Move Type Path Handle", + [], + None, + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path)", + has_doc, + set_path_handle + ), cmd!( "text.fitHeadline", "Fit Headline", @@ -304,6 +313,7 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); t.cached_baselines = lay.baselines(); + t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t))); } /// [`refresh_bounds`] for a document that is opening: the first frame takes the layout @@ -315,6 +325,7 @@ pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) { let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); t.cached_baselines = lay.baselines(); + t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t))); vectorcraft_text::keep_layout(t, stamp, lay); } @@ -1266,6 +1277,35 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result { ok() } +fn set_path_handle(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.setPathHandle"; + let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let si = super::draw2::usize_opt(p, "subpath", C)?.unwrap_or(0); + let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad(C, "missing anchor"))?; + let out = str_param(p, "which") != Some("in"); + let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); + let independent = switch_or(p, "independent", false, C)?; + let node = s.doc()?.doc.node(id); + let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })); + if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) { + return Err(bad(C, "not type on a path outside perspective")); + } + s.edit("Reshape Type Path", |doc, _| { + let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; + let before = t.kind.clone(); + let within = |t: &TextObject| { + t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD)) + }; + if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) { + t.kind = before; + return Err(bad(C, "no such path anchor, or the path would reach past the canvas")); + } + refresh_bounds(t); + Ok(()) + })?; + ok() +} + #[cfg(test)] mod area_tests; diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 88ccb36da5..571c9c3469 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -2081,3 +2081,35 @@ fn fit_min_percent_for_several_frames_keeps_each_frames_fit() { assert_eq!(fit(&s, plain), vectorcraft_doc::AreaFit::None, "the plain frame doesn't start shrinking"); assert_eq!(fit(&s, shrink), vectorcraft_doc::AreaFit::ShrinkText { min_percent: 30.0 }); } + +/// #3565: `text.setPathHandle` moves a direction handle of type on a path's path, in document +/// space, as `path.setHandle` moves a path's: a smooth anchor's other handle turns with it at +/// its length, `independent` leaves it and makes the anchor a corner; one undo step. +#[test] +fn set_path_handle_reshapes_type_on_a_path() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let path = + s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 300, "in": [50, 300], "out": [150, 300]}, {"x": 400, "y": 300}]})).unwrap(); + let text = s.execute("text.createInPath", &json!({"path": path["id"], "mode": "onPath", "text": "Along the curve"})).unwrap(); + let id = NodeId(text["id"].as_u64().unwrap()); + let first = |s: &Session| match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => *t.type_path().unwrap().subpaths[0].anchors.first().unwrap(), + _ => panic!("not text"), + }; + let smooth = first(&s).kind == vectorcraft_geom::AnchorKind::Smooth; + s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 0, "which": "out", "x": 100, "y": 250})).unwrap(); + let a = first(&s); + assert!((a.h_out.x - 100.0).abs() < 1e-6 && (a.h_out.y - 250.0).abs() < 1e-6, "{a:?}"); + if smooth { + assert!((a.h_in.x - 100.0).abs() < 1e-6 && (a.h_in.y - 350.0).abs() < 1e-6, "smooth: the in handle turns with it at its length: {a:?}"); + } + s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 0, "which": "in", "x": 60, "y": 300, "independent": true})).unwrap(); + let b = first(&s); + assert_eq!(b.h_out, a.h_out, "independent: the other handle stays"); + assert_eq!(b.kind, vectorcraft_geom::AnchorKind::Corner); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(first(&s), a, "one undo step each"); + assert!(s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 9, "which": "out", "x": 0, "y": 0})).is_err(), "no such anchor"); + assert!(s.execute("text.setPathHandle", &json!({"id": path["id"], "anchor": 0, "which": "out", "x": 0, "y": 0})).is_err(), "not type"); +} diff --git a/crates/engine/src/cmd/views.rs b/crates/engine/src/cmd/views.rs index fd9e11bcf7..f4db493d66 100644 --- a/crates/engine/src/cmd/views.rs +++ b/crates/engine/src/cmd/views.rs @@ -2,33 +2,106 @@ //! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options. use serde_json::{Value, json}; +use vectorcraft_apischema::{Bound, Param, ParamSchema, Type, Writes}; use vectorcraft_doc::SavedView; use vectorcraft_geom::Point; use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_req, finite_numbers, has_doc, str_param, switch_or}; +// The parameter schemas. Each command's params text is the text its schema writes +// (`ParamSchema::params_text`), which a test in `crate::schemas` checks. + +static CAPS_LOCK: ParamSchema = ParamSchema::new( + &[Param::new("on", Type::Boolean).optional()], + "set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value", +) +.returns("{on}") +.writes(Writes::Session); + +static NEW_VIEW: ParamSchema = ParamSchema::new( + &[ + Param::new("name", Type::String).default_note("the first free \"View N\"").null_omitted(), + Param::new("center", Type::Point), + Param::new("zoom", Type::Number { min: Some(Bound::Exclusive(0.0)), max: None, unit: None }).doc("1 = 100%"), + Param::new("rotation", Type::Number { min: None, max: None, unit: Some("deg") }).defaults_to("0"), + ], + "save a view in the document (the app fills in the current one; at most 25, names up to 255 characters, each name once)", +) +.returns("{name, index}"); + +/// One rename or delete of Edit Views…. +const VIEW_EDIT: &[Param] = &[ + Param::new("name", Type::String), + Param::new("newName", Type::String).optional().null_omitted(), + Param::new("delete", Type::Boolean).optional().null_omitted(), +]; + +static EDIT_VIEWS: ParamSchema = ParamSchema::new( + &[ + Param::new("name", Type::String).optional().null_omitted(), + Param::new("newName", Type::String).optional().null_omitted().doc("rename"), + Param::new("delete", Type::Boolean).optional().null_omitted(), + Param::new("edits", Type::Array(&Type::Object(VIEW_EDIT))).optional().null_omitted().doc("instead of name"), + ], + "rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}", +); + +static LIST_VIEWS: ParamSchema = ParamSchema::new(&[], "").returns("{views: [{name, center, zoom, rotation}]}").writes(Writes::Nothing); + +static TRANSPARENCY_GRID: ParamSchema = ParamSchema::new( + &[Param::new("on", Type::Boolean).default_note("toggle").null_omitted()], + "show the transparency grid behind the active document's artboards (each document has its own setting)", +) +.returns("{on}") +.writes(Writes::Session); + +static GLYPH_SNAP: ParamSchema = ParamSchema::new( + &[ + Param::new("baseline", Type::Boolean).optional(), + Param::new("xHeight", Type::Boolean).optional(), + Param::new("bounds", Type::Boolean).optional(), + Param::new("proximity", Type::Boolean).optional(), + Param::new("angular", Type::Boolean).optional(), + Param::new("anchors", Type::Boolean).optional(), + ], + "the Character panel's Snap to Glyph options, kept in the preferences (the glyphSnap group, all on by default): which guides View › Snap to Glyph gives: the baseline and x-height of a single line of type, Glyph Bounds (each glyph's edges), Proximity Guides (both edges of each character's width), Angular Guides (a glyph's slanted strokes, and every guide of rotated type) and the glyphs' anchor points; {} reads them", +) +.returns("the options") +.writes(Writes::Preferences); + pub fn specs() -> Vec { vec![ - cmd!(query "view.capsLock", "Caps Lock Cursor State", [], None, "{on?: bool} set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value → {on}", always, caps_lock), + cmd!( + query "view.capsLock", + "Caps Lock Cursor State", + [], + None, + "{on?: bool} set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value → {on}", + always, + caps_lock, + schema: &CAPS_LOCK + ), cmd!( "view.saved.new", "New View…", ["View"], None, - "{name?, center: [x, y], zoom: (1 = 100%), rotation?: deg} save a view in the document (the app fills in the current one; default \"View N\"; at most 25, names up to 255 characters, each name once) → {name, index}", + "{name?: string (default: the first free \"View N\"), center: [x, y], zoom: number > 0 (1 = 100%), rotation?: number deg (default: 0)} save a view in the document (the app fills in the current one; at most 25, names up to 255 characters, each name once) → {name, index}", has_doc, - new_view + new_view, + schema: &NEW_VIEW ), cmd!( "view.saved.edit", "Edit Views…", ["View"], None, - "{name, newName?: rename, delete?: bool} | {edits: [{name, newName?, delete?}…]} rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}", + "{name?: string, newName?: string (rename), delete?: bool, edits?: [{name: string, newName?: string, delete?: bool}…] (instead of name)} rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}", has_views, - edit_views + edit_views, + schema: &EDIT_VIEWS ), - cmd!(query "view.saved.list", "Saved Views", [], None, "{} → {views: [{name, center, zoom, rotation}]}", has_doc, list_views), + cmd!(query "view.saved.list", "Saved Views", [], None, "{} → {views: [{name, center, zoom, rotation}]}", has_doc, list_views, schema: &LIST_VIEWS), cmd!( query "view.transparencyGrid", "Show Transparency Grid", @@ -36,16 +109,18 @@ pub fn specs() -> Vec { Some("Cmd+Shift+D"), "{on?: bool (default: toggle)} show the transparency grid behind the active document's artboards (each document has its own setting) → {on}", has_doc, - transparency_grid + transparency_grid, + schema: &TRANSPARENCY_GRID ), cmd!( query "view.snapToGlyph.options", "Snap to Glyph Options", [], None, - "{baseline?: bool, xHeight?: bool, bounds?: bool, proximity?: bool, angular?: bool, anchors?: bool} the Character panel's Snap to Glyph options, kept in the preferences (the glyphSnap group, all on by default): which guides View › Snap to Glyph gives — the baseline and x-height of a single line of type, Glyph Bounds (each glyph's edges), Proximity Guides (both edges of each character's width), Angular Guides (a glyph's slanted strokes, and every guide of rotated type) and the glyphs' anchor points; {} reads them → the options", + "{baseline?: bool, xHeight?: bool, bounds?: bool, proximity?: bool, angular?: bool, anchors?: bool} the Character panel's Snap to Glyph options, kept in the preferences (the glyphSnap group, all on by default): which guides View › Snap to Glyph gives: the baseline and x-height of a single line of type, Glyph Bounds (each glyph's edges), Proximity Guides (both edges of each character's width), Angular Guides (a glyph's slanted strokes, and every guide of rotated type) and the glyphs' anchor points; {} reads them → the options", always, - glyph_snap_options + glyph_snap_options, + schema: &GLYPH_SNAP ), ] } @@ -280,6 +355,92 @@ mod tests { assert_eq!(s.execute("view.saved.new", &json!({"name": long, "center": [0, 0], "zoom": 1})).unwrap()["name"], "x".repeat(255)); } + /// Each command refuses a value its schema doesn't take with an error naming the parameter, and + /// leaves the document, its views, its undo history and the settings as they were. + #[test] + fn each_view_command_refuses_a_bad_value_naming_the_parameter() { + let mut s = session_with_views(&["A"]); + for (id, params, named) in [ + ("view.capsLock", json!({"on": "yes"}), "`on`"), + ("view.capsLock", json!({"of": true}), "`of`"), + ("view.saved.new", json!({"center": [0, 0], "zoom": 0}), "`zoom`"), + ("view.saved.new", json!({"center": [0, "0"], "zoom": 1}), "`center`"), + ("view.saved.new", json!({"center": [0, 0], "zoom": 1, "rotation": "15"}), "`rotation`"), + ("view.saved.new", json!({"name": 5, "center": [0, 0], "zoom": 1}), "`name`"), + ("view.saved.new", json!({"zoom": 1}), "`center`"), + ("view.saved.edit", json!({"name": "A", "delete": "yes"}), "`delete`"), + ("view.saved.edit", json!({"name": "A", "newName": 7}), "`newName`"), + ("view.saved.edit", json!({"edits": [{"name": "A", "delete": 1}]}), "`edits[0].delete`"), + ("view.saved.edit", json!({"edits": [{"newName": "B"}]}), "`edits[0].name`"), + ("view.saved.edit", json!({"edits": "A"}), "`edits`"), + ("view.saved.list", json!({"all": true}), "`all`"), + ("view.transparencyGrid", json!({"on": 1}), "`on`"), + ("view.snapToGlyph.options", json!({"bounds": "off"}), "`bounds`"), + ] { + let st = s.doc().unwrap(); + let doc = (st.doc.views.clone(), st.history.undo.len(), st.is_dirty()); + let (grid, caps, snap) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap); + let e = s.execute(id, ¶ms).unwrap_err().to_string(); + assert!(e.contains(id) && e.contains(named), "{id} {params}: {e}"); + let st = s.doc().unwrap(); + assert_eq!((&st.doc.views, st.history.undo.len(), st.is_dirty()), (&doc.0, doc.1, doc.2), "{id} {params}"); + assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap), (grid, caps, snap), "{id} {params}"); + } + } + + /// A command run by another command's implementation has its params checked against its schema + /// too, with nothing changed when they are refused. + #[test] + fn a_raw_run_is_checked_against_the_schema() { + let mut s = session_with_views(&[]); + let e = super::super::menucmds::run_raw(&mut s, "view.saved.new", &json!({"center": [0, 0], "zoom": -1})).unwrap_err().to_string(); + assert!(e.contains("view.saved.new") && e.contains("`zoom` must be a number > 0, not -1"), "{e}"); + assert!(s.doc().unwrap().doc.views.is_empty()); + assert!(s.doc().unwrap().history.undo.is_empty()); + super::super::menucmds::run_raw(&mut s, "view.saved.new", &json!({"center": [0, 0], "zoom": 1})).unwrap(); + assert_eq!(s.doc().unwrap().doc.views.len(), 1); + } + + /// An edit list with nothing in it and an edit that leaves a view as it is add no undo step; + /// names with path characters are only names; a key with one is refused and named. + #[test] + fn edit_views_edges() { + let mut s = session_with_views(&["a.b[0]", "plain"]); + let steps = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("view.saved.edit", &json!({"edits": []})).unwrap()["views"].as_array().map(Vec::len), Some(2)); + s.execute("view.saved.edit", &json!({"name": "plain", "newName": "plain"})).unwrap(); + s.execute("view.saved.edit", &json!({"edits": [{"name": "plain", "newName": "plain"}]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + s.execute("view.saved.edit", &json!({"name": "a.b[0]", "newName": "c[1].d"})).unwrap(); + assert_eq!(names(&mut s), ["c[1].d", "plain"]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let e = s.execute("view.saved.edit", &json!({"a.b": 1})).unwrap_err().to_string(); + assert!(e.contains("`a.b`"), "{e}"); + let e = s.execute("view.saved.edit", &json!({"edits": [{"name": "plain", "a.b": 1}]})).unwrap_err().to_string(); + assert!(e.contains("`edits[0].a.b`; it takes: name, newName, delete"), "{e}"); + // Repeated and unknown names keep the command's own errors. + let e = s.execute("view.saved.edit", &json!({"edits": [{"name": "plain", "newName": "c[1].d"}]})).unwrap_err().to_string(); + assert!(e.contains("exists"), "{e}"); + let e = s.execute("view.saved.edit", &json!({"name": "", "delete": true})).unwrap_err().to_string(); + assert!(e.contains("no view named"), "{e}"); + } + + /// A refused call during a drag leaves the drag running and adds no undo step; canceling the + /// drag then leaves the history as it was. + #[test] + fn a_refused_call_leaves_an_interaction_alone() { + let mut s = session_with_views(&["A"]); + let steps = s.doc().unwrap().history.undo.len(); + s.begin_interaction("Move").unwrap(); + assert!(s.execute("view.saved.new", &json!({"name": 5, "center": [0, 0], "zoom": 1})).is_err()); + assert!(s.doc().unwrap().interaction.is_some()); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + s.cancel_interaction().unwrap(); + assert!(s.doc().unwrap().interaction.is_none()); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(names(&mut s), ["A"]); + } + /// Edit Views… is off until the document has a view. #[test] fn edit_views_needs_a_saved_view() { diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 7af7cf1f85..9038598659 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -368,7 +368,7 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { q["ids"] = ids.clone(); } let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; - let result = (spec.run)(s, &q)?; + let result = super::run_checked(s, spec, &q)?; if clear_stroke { s.paint.stroke = Paint::None; } diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 38ce14cab7..77068d125f 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -83,6 +83,7 @@ pub(crate) fn strip_replay_only(id: &str, p: &mut Value) { /// Instances and Lock Guides change the selection, and the proof views, the preferences and added /// fonts give the documents new revisions (they draw again, and type lays out again). const WAIT_FOR_TOOL_EDIT: &[&str] = &[ + "script.run", "command.batch", "document.find", "symbol.selectInstances", diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index a0ae4cd655..d0e4862404 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -112,6 +112,8 @@ pub struct DocState { pub opened_by: Option>, /// What [`DocState::any_empty_artboards`] last measured. Not saved. empty_artboards: std::cell::RefCell, + /// What [`DocState::any_art_to_fit`] last measured. Not saved. + art_to_fit: std::cell::RefCell>, } /// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that @@ -124,10 +126,25 @@ struct EmptyArtboards { any: bool, } +/// Whether an unlocked artboard of those asked about has art that Fit to Artwork Bounds fits it +/// to, with what was measured: the document (held as [`EmptyArtboards::doc`] holds it), the +/// artboards, and the generations of what the measure reads outside the document. One is kept for +/// each open document, and its weak reference keeps the measured document's allocation (not its +/// contents) until the next measure or until the document closes. +#[derive(Clone, Debug)] +struct ArtToFit { + doc: std::sync::Weak, + indices: Vec, + outside: (u64, u64), + any: bool, +} + #[cfg(test)] thread_local! { /// Tests: how many times [`DocState::any_empty_artboards`] measured a document on this thread. pub(crate) static EMPTY_ARTBOARD_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many times [`DocState::any_art_to_fit`] measured a document on this thread. + pub(crate) static ART_TO_FIT_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; } static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -309,6 +326,7 @@ impl DocState { last_perspective: None, opened_by: file_access::current(), empty_artboards: Default::default(), + art_to_fit: Default::default(), } } /// `measure`'s answer for the document now. `measure` runs once for each version of the document, @@ -323,6 +341,38 @@ impl DocState { } last.any } + /// Whether an unlocked artboard of `indices` has art that Fit to Artwork Bounds fits it to. A + /// menu asks on every frame it is open, and measuring builds the solids of 3D effects, so the + /// answer is kept for this version of the document and those artboards, and a change of the + /// selection or the view keeps it. It is measured again when what the measure reads outside the + /// document changes: the installed plug-ins, whose effects draw art, and the installed fonts, + /// which set the bounds of all type. + pub fn any_art_to_fit(&self, indices: &[usize]) -> bool { + self.any_art_to_fit_with(indices, (vectorcraft_plugins::registry::revision(), vectorcraft_text::FontDb::global().generation())) + } + /// [`Self::any_art_to_fit`], with `outside` the generations of the plug-ins and the fonts. + pub(crate) fn any_art_to_fit_with(&self, indices: &[usize], outside: (u64, u64)) -> bool { + // Measuring runs renderer and plug-in code; should it ever ask again while measuring, it + // is measured without being kept rather than borrowed twice. + let Ok(mut last) = self.art_to_fit.try_borrow_mut() else { + let mut r = vectorcraft_render::Renderer::new(); + return indices.iter().filter_map(|i| self.doc.artboards.get(*i)).any(|a| !a.locked && r.art_bounds_on(&self.doc, a.rect).is_some()); + }; + if let Some(k) = last.as_ref() + && std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&self.doc)) + && k.indices == indices + && k.outside == outside + { + return k.any; + } + #[cfg(test)] + ART_TO_FIT_MEASURES.with(|c| c.set(c.get() + 1)); + // One renderer measures every artboard: each object once. + let mut r = vectorcraft_render::Renderer::new(); + let any = indices.iter().filter_map(|i| self.doc.artboards.get(*i)).any(|a| !a.locked && r.art_bounds_on(&self.doc, a.rect).is_some()); + *last = Some(ArtToFit { doc: Arc::downgrade(&self.doc), indices: indices.to_vec(), outside, any }); + any + } /// Unsaved changes: the document differs from the saved one (selection changes and changes that /// are not edits to save don't count, [`DocState::same_content`]). pub fn is_dirty(&self) -> bool { @@ -396,7 +446,7 @@ impl DocState { } let e = HistoryEntry::kept(label, doc, selection, &self.doc); self.history.undo.push(e); - self.history.redo.clear(); + self.history.clear_redo(); self.history.trim(); } /// End the interaction in progress, undoing what it changed. diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 8d939db77b..d32fda613d 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -1,5 +1,8 @@ use super::{NodeId, cancel}; +/// The text of [`EngineError::Busy`], which ends every error a frontend reports for it. +pub const SCRIPT_BUSY: &str = "a script is running: stop it or wait for it to finish"; + #[derive(Debug, thiserror::Error)] pub enum EngineError { #[error("unknown command `{0}`")] @@ -20,6 +23,9 @@ pub enum EngineError { /// The caller asked for the command to stop ([`cancel`]). It changed nothing. #[error("cancelled; nothing was changed")] Cancelled, + /// A running script holds the documents until it ends. Nothing was changed. + #[error("{}", SCRIPT_BUSY)] + Busy, /// A bug: the command panicked. The document was rolled back to its state before the command. #[error("internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug)")] Internal { cmd: String, msg: String }, diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 0565a9115f..c6daff9e41 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -85,6 +85,12 @@ impl AutomationRoots { Ok(Some(Arc::new(Self { read: open(read, Access::Read)?, write: open(write, Access::Write)? }))) } + /// Roots that grant no access of either kind: inside [`confine`] with them, every path a + /// command reads or writes is refused. + pub(crate) fn none() -> Arc { + Arc::new(Self { read: Vec::new(), write: Vec::new() }) + } + /// May the file or folder at `path` be read (or written)? It must lie inside one of the roots /// of that kind. `Err` says why not. pub fn check(&self, path: &str, access: Access) -> Result<(), String> { @@ -208,7 +214,40 @@ pub fn check_read(path: &str) -> Result<(), String> { /// May `path` be written here? Always, without roots in force. pub fn check_write(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Write)) + current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + WRITES.with(|w| { + if let Some(paths) = w.borrow_mut().as_mut() + && !paths.iter().any(|(p, _)| p == path) + { + paths.push((path.to_string(), stamp(path))); + } + }); + Ok(()) +} + +/// A file's modification time and length; `None` when there is no file at `path`. +type Stamp = Option<(Option, u64)>; + +fn stamp(path: &str) -> Stamp { + std::fs::metadata(path).ok().filter(std::fs::Metadata::is_file).map(|m| (m.modified().ok(), m.len())) +} + +thread_local! { + /// The paths [`check_write`] allowed on this thread while they are being recorded, each with + /// its file's stamp at that moment. + static WRITES: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Starts recording the paths [`check_write`] allows on this thread. +pub(crate) fn start_recording_writes() { + WRITES.with(|w| *w.borrow_mut() = Some(Vec::new())); +} + +/// Ends recording → the recorded paths whose file exists now: after a command that `succeeded`, +/// all of them; after one that failed, those made or changed since they were allowed. +pub(crate) fn finish_recording_writes(succeeded: bool) -> Vec { + let recorded = WRITES.with(|w| w.borrow_mut().take()).unwrap_or_default(); + recorded.into_iter().filter(|(path, before)| stamp(path).is_some_and(|now| succeeded || Some(now) != *before)).map(|(path, _)| path).collect() } /// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 8df6060e02..cc545b179f 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -1,7 +1,13 @@ use super::{Arc, Document, Selection}; +#[cfg(test)] +thread_local! { + /// Tests: how many undo steps were copied on this thread. + pub(crate) static ENTRY_CLONES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// One undo step. -#[derive(Clone, Debug)] +#[derive(Debug)] pub struct HistoryEntry { pub label: String, /// The document as it was. It keeps no lookup cache ([`Document::drop_lookup_cache`]): a @@ -27,6 +33,25 @@ pub struct HistoryEntry { color_mode_bytes: usize, } +impl Clone for HistoryEntry { + fn clone(&self) -> Self { + #[cfg(test)] + ENTRY_CLONES.with(|n| n.set(n.get() + 1)); + HistoryEntry { + label: self.label.clone(), + doc: self.doc.clone(), + selection: self.selection.clone(), + bytes: self.bytes, + next_bytes: self.next_bytes, + next: self.next, + named: self.named.clone(), + serial: self.serial, + color_mode_paints: self.color_mode_paints.clone(), + color_mode_bytes: self.color_mode_bytes, + } + } +} + /// The next [`HistoryEntry::serial`]: 1 for the first step made, so 0 never names a step. fn next_serial() -> u64 { static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -146,13 +171,55 @@ pub struct History { /// Maximum undo depth (Illustrator has no hard limit; snapshots are cheap here). pub limit: usize, /// About the most memory the steps may keep ([`HistoryEntry::bytes`]): past it the oldest - /// steps go, but never the last [`History::MIN_STEPS`] undo (and redo) steps. + /// steps go, but never the last [`History::MIN_STEPS`] undo (and redo) steps. The histories of a + /// session's open documents also share [`Session::history_budget`](crate::Session::history_budget). pub byte_budget: usize, + /// Counts the changes made in place to steps below the newest ([`History::put_back`]). + pub(crate) rewrites: u64, + /// Between [`History::mark`] and [`History::release`] or [`History::put_back`]. + pub(crate) held: bool, + /// The redo steps a new step cleared while held ([`History::clear_redo`]). + pub(crate) set_aside: Option>, } impl Default for History { fn default() -> Self { - History { undo: vec![], redo: vec![], limit: 0, byte_budget: default_history_budget() } + History { undo: vec![], redo: vec![], limit: 0, byte_budget: default_history_budget(), rewrites: 0, held: false, set_aside: None } + } +} + +/// What [`History::put_back`] needs to give a history back as it was when [`History::mark`] took +/// it: the newest undo and redo steps, and where each stack stood under them. It holds no other +/// step, so taking one costs the same however many the history holds. +pub(crate) struct HistoryMark { + undo: StackMark, + redo: StackMark, + limit: usize, + byte_budget: usize, + rewrites: u64, +} + +/// One stack of a [`HistoryMark`]. +struct StackMark { + len: usize, + /// [`HistoryEntry::serial`] of the step under the newest one, 0 for none. + below: u64, + newest: Option, +} + +impl StackMark { + fn of(steps: &[HistoryEntry]) -> Self { + let len = steps.len(); + StackMark { len, below: len.checked_sub(2).and_then(|i| steps.get(i)).map_or(0, |e| e.serial), newest: steps.last().cloned() } + } + + /// Puts `steps` back as they were. → `false` when a step under the newest one was removed since. + fn put_back(self, steps: &mut Vec) -> bool { + let kept = self.len.saturating_sub(1); + let intact = steps.len() >= kept && kept.checked_sub(1).is_none_or(|i| steps.get(i).is_some_and(|e| e.serial == self.below)); + steps.truncate(kept); + steps.extend(self.newest); + intact } } @@ -208,6 +275,58 @@ impl History { self.redo.drain(..n); } + /// A [`HistoryMark`] of the history now. Until [`History::release`] or [`History::put_back`], + /// [`History::trim`] lets no step go, so the steps under the newest one stay where they are, and + /// [`History::clear_redo`] sets the redo steps aside. + pub(crate) fn mark(&mut self) -> HistoryMark { + let mark = HistoryMark { + undo: StackMark::of(&self.undo), + redo: StackMark::of(&self.redo), + limit: self.limit, + byte_budget: self.byte_budget, + rewrites: self.rewrites, + }; + self.limit = usize::MAX; + self.byte_budget = usize::MAX; + self.held = true; + self.set_aside = None; + mark + } + + /// Removes the redo steps, as a new step does. While held ([`History::mark`]) the first call + /// keeps them for [`History::put_back`]. + pub(crate) fn clear_redo(&mut self) { + if self.held && self.set_aside.is_none() { + self.set_aside = Some(std::mem::take(&mut self.redo)); + } else { + self.redo.clear(); + } + } + + /// Keeps the history as it is now: the limits `mark` held back apply again. + pub(crate) fn release(&mut self, mark: &HistoryMark) { + self.held = false; + self.set_aside = None; + self.limit = mark.limit; + self.byte_budget = mark.byte_budget; + self.trim(); + } + + /// Gives the history back as it was at `mark`. → `false` when that is not possible: an undo or + /// redo step under the newest one was removed or changed in place since. + pub(crate) fn put_back(&mut self, mark: HistoryMark) -> bool { + if let Some(redo) = self.set_aside.take() { + self.redo = redo; + } + let undo = mark.undo.put_back(&mut self.undo); + let redo = mark.redo.put_back(&mut self.redo); + let intact = self.rewrites == mark.rewrites && undo && redo; + self.held = false; + self.limit = mark.limit; + self.byte_budget = mark.byte_budget; + intact + } + /// Estimate the newest undo step again, its next state now being `now` (the steps after it were /// merged into it, or an undo group extended it). It takes a new number ([`History::step`]). pub(crate) fn recost_last(&mut self, now: &Document) { @@ -221,23 +340,93 @@ impl History { } } -/// The default [`History::byte_budget`]: an eighth of the machine's memory where it is known -/// (Linux), at most 1 GiB (the figure elsewhere); 256 MiB on the web, whose memory is small. +/// Let the oldest steps of `histories` go while together they keep more than `budget` +/// ([`History::bytes`]): undo steps first, the oldest of all the histories first, then redo steps, +/// the furthest ahead first. Each history keeps its last [`History::MIN_STEPS`] undo (and redo) +/// steps, and a held one ([`History::mark`]) keeps all of its steps; their memory still counts. +pub(crate) fn trim_together<'a>(histories: impl IntoIterator, budget: usize) { + let all: Vec<&mut History> = histories.into_iter().collect(); + let mut total = all.iter().fold(0usize, |t, h| t.saturating_add(h.bytes())); + if total <= budget { + return; + } + fn steps(h: &History, redo: bool) -> &[HistoryEntry] { + if redo { &h.redo } else { &h.undo } + } + let mut free: Vec<&mut History> = all.into_iter().filter(|h| !h.held).collect(); + for redo in [false, true] { + // How many of each history's oldest steps go. + let mut gone = vec![0usize; free.len()]; + while total > budget { + // The oldest step any history may still let go. + let next = free + .iter() + .zip(&gone) + .enumerate() + .filter(|(_, (h, n))| steps(h, redo).len().saturating_sub(**n) > History::MIN_STEPS) + .filter_map(|(i, (h, n))| steps(h, redo).get(*n).map(|e| (e.serial, i, e.bytes))) + .min(); + let Some((_, i, bytes)) = next else { break }; + total = total.saturating_sub(bytes); + if let Some(n) = gone.get_mut(i) { + *n += 1; + } + } + for (h, n) in free.iter_mut().zip(gone) { + let steps = if redo { &mut h.redo } else { &mut h.undo }; + steps.drain(..n.min(steps.len())); + } + } +} + +/// What [`Session::trim_histories`](crate::Session::trim_histories) last left: the budget, and for +/// each open document its uid and what a new, undone, redone, merged, recosted, removed or put-back +/// step changes in its history. +pub(crate) type HistoriesSeen = (usize, Vec<(u64, (u64, u64), usize, usize, usize, u64, bool)>); + +impl crate::Session { + /// Let the oldest undo and redo steps of the open documents go while together they keep more + /// than [`Session::history_budget`](crate::Session::history_budget) ([`trim_together`]). While a + /// script runs, its commands leave the histories as they are: the run's end trims them. While an + /// undo group is open in any document, the histories stay as they are too, so a canceled group + /// leaves the other documents' steps in place: closing the groups trims them. When + /// neither the budget nor any history changed since the last call, the steps are not counted + /// again. + pub(crate) fn trim_histories(&mut self) { + if self.script_in_run || self.docs.iter().any(|d| d.undo_group.is_some()) { + return; + } + if self.histories_seen.as_ref() == Some(&self.histories_now()) { + return; + } + trim_together(self.docs.iter_mut().map(|d| &mut d.history), self.history_budget); + self.histories_seen = Some(self.histories_now()); + } + + fn histories_now(&self) -> HistoriesSeen { + let doc = |d: &crate::DocState| { + let h = &d.history; + (d.uid, h.step(), h.undo.len(), h.redo.len(), h.undo.last().map_or(0, |e| e.bytes), h.rewrites, h.held) + }; + (self.history_budget, self.docs.iter().map(doc).collect()) + } +} + +/// The default [`History::byte_budget`] and [`Session::history_budget`](crate::Session::history_budget), +/// which the open documents' histories share: a quarter of the installed memory, or on Linux of the +/// process's cgroup memory limit where that is lower ([`vectorcraft_render::physical_memory`], see +/// [`history_budget_for`]); 1 GiB where the installed memory can't be read, and 256 MiB on the web. pub fn default_history_budget() -> usize { - const MAX: usize = 1 << 30; if cfg!(target_arch = "wasm32") { return 256 << 20; } static BUDGET: std::sync::OnceLock = std::sync::OnceLock::new(); - *BUDGET.get_or_init(|| physical_memory().map_or(MAX, |m| (m / 8).clamp(64 << 20, MAX))) + *BUDGET.get_or_init(|| history_budget_for(vectorcraft_render::physical_memory())) } -/// The machine's memory, where cheap to learn without platform calls. -fn physical_memory() -> Option { - if !cfg!(target_os = "linux") { - return None; - } - let info = std::fs::read_to_string("/proc/meminfo").ok()?; - let kb: usize = info.lines().find_map(|l| l.strip_prefix("MemTotal:"))?.trim().trim_end_matches("kB").trim().parse().ok()?; - kb.checked_mul(1024) +/// The default [`History::byte_budget`] for a reading of `memory` bytes installed: a quarter of it, +/// at least 64 MiB, and at most a quarter of the address space (on 32-bit builds); 1 GiB when the +/// reading is `None` or 0. +pub(crate) fn history_budget_for(memory: Option) -> usize { + memory.filter(|&m| m > 0).map_or(1 << 30, |m| usize::try_from(m / 4).unwrap_or(usize::MAX).clamp(64 << 20, usize::MAX / 4)) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ffcd43019a..043158c582 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -12,6 +12,7 @@ pub mod guard; pub mod inspect; pub mod journal; pub mod link_watch; +pub mod schemas; pub mod steps; pub mod store; mod tooling; @@ -58,6 +59,13 @@ pub struct Session { pub clipboard: Clipboard, /// Executed commands (for actions and debugging), the most recent ones kept ([`Journal`]). pub journal: Journal, + /// About the most memory the undo steps of all the open documents may keep together + /// ([`History::bytes`]): past it the oldest steps of any of them go, but each keeps its last + /// [`History::MIN_STEPS`] undo (and redo) steps. [`default_history_budget`] by default. + pub history_budget: usize, + /// The budget and histories [`Session::trim_histories`] last left, so it does not count the + /// steps again while none of them changed. + pub(crate) histories_seen: Option, pub(crate) tool: Box, /// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes /// back as it was at the release ([`Session::pointer`]). @@ -154,6 +162,9 @@ pub struct Session { /// Where the ICC profiles `color.loadProfile` loads are kept; `None`: only for the process /// ([`Session::attach_profile_store`]). profile_dir: Option, + /// The file Edit › Color Settings are kept in; `None`: only for the process + /// ([`Session::attach_color_settings`]). + color_settings_file: Option, /// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process /// ([`Session::attach_plugin_store`]). plugin_dir: Option, @@ -242,6 +253,21 @@ pub struct Session { pub(crate) screens_hand_off: Option>, /// Where Data Recovery keeps its copies ([`cmd::recovery`]). pub recovery: cmd::recovery::Recovery, + /// The running script's job, while there is one: the mutation lease ([`script`]). + pub(crate) script_key: Option, + /// Stops the running script at its next instruction; the same flag for every run. + pub(crate) script_stop: vectorcraft_js::Interrupt, + /// The report of the run that ended last. + pub(crate) script_report: Option, + /// `script.run` starts the job and returns, and the frontend advances it once per frame + /// ([`Session::script_pump`]). Off, `script.run` advances it to its end. + pub script_frames: bool, + /// Each open document's highest next id a run has seen, by [`DocState::uid`]. + pub(crate) script_high_water: std::collections::HashMap, + /// While a slice of a script runs in this session. + pub(crate) script_in_run: bool, + /// Write recovery copies of the unsaved documents before a run, and don't start without them. + pub script_copy_first: bool, /// While the active tool's actions run: their commands aren't "a command from outside the /// tool" ([`Session::after_command`]). pub(crate) in_tool_actions: bool, @@ -328,6 +354,7 @@ mod history; mod interaction; mod prefs; mod sanity; +pub mod script; mod session; #[cfg(test)] @@ -336,7 +363,9 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS; use command_sets::given_ids; pub use command_sets::{FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit}; pub use doc_state::{DocState, OpenRows, RecalledSelection}; -pub use error::{EngineError, Result}; +pub use error::{EngineError, Result, SCRIPT_BUSY}; +#[cfg(test)] +use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::PreviewCopies; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 6cdf5c3591..747ce91545 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -84,9 +84,9 @@ pub(crate) fn update_changed(s: &mut Session, _: &Value) -> Result { impl Session { /// Start stamping the active document's linked files on a worker thread, unless a look is - /// still running (or the build has no files to look at: the web app). + /// still running, a script is running (or the build has no files to look at: the web app). pub fn start_link_scan(&mut self) { - if self.link_scan.is_some() || cfg!(target_arch = "wasm32") { + if self.link_scan.is_some() || self.script_key.is_some() || cfg!(target_arch = "wasm32") { return; } let Some(st) = self.active() else { return }; @@ -115,10 +115,13 @@ impl Session { } } - /// Apply a finished look (`None` while there is none, or it is still running): see - /// [`Session::apply_link_stamps`]. A look whose worker ended without stamps is cleared, also - /// with `None`, so the next one can start. + /// Apply a finished look (`None` while there is none, it is still running, or a script is + /// running): see [`Session::apply_link_stamps`]. A look whose worker ended without stamps is + /// cleared, also with `None`, so the next one can start. pub fn poll_link_scan(&mut self) -> Option> { + if self.script_key.is_some() { + return None; + } self.link_scan.take_if(|scan| ended_without_stamps(scan, |ended| ended.load(Ordering::SeqCst))); let (uid, stamps) = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?; self.link_scan = None; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index d3b0345264..9ea86a21ea 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -31,6 +31,8 @@ pub struct Prefs { pub disable_auto_add_delete: bool, pub use_precise_cursors: bool, pub show_tool_tips: bool, + /// Other Script… warns before it runs a chosen script. + pub show_external_script_warning: bool, pub anti_aliased_artwork: bool, pub select_same_tint_percent: bool, pub show_home_screen: bool, @@ -41,6 +43,12 @@ pub struct Prefs { /// Align panel menu › Align to Glyph Bounds › Area Text: the same for area type, instead of /// its frame. pub align_glyph_bounds_area: bool, + /// Preferences › Type › Glyph Bounds › Measure Type by Glyph Bounds (also in the Transform + /// panel menu): the bounding box, the Transform panel's, Control bar's and Properties panel's X, + /// Y, W and H, and `object.setBounds` measure each point type object selected as an object (not + /// inside a selected group) by the ink of its glyphs instead of its em box + /// ([`crate::Session::bounds_measure`]). + pub type_glyph_bounds: bool, /// Artboard Options › Fade Region Outside Artboard: while the Artboard tool is active, the /// canvas draws everything outside the artboards darker, the pasteboard and the art on it. pub fade_region_outside_artboard: bool, @@ -114,6 +122,8 @@ pub struct Prefs { // Guides & Grid pub guide_color: String, pub guide_style: String, + /// Lock Guides by Default: the app starts with View › Guides › Lock Guides on. + pub lock_guides_by_default: bool, pub grid_color: String, pub grid_style: String, pub gridline_every: f64, @@ -364,12 +374,14 @@ impl Default for Prefs { disable_auto_add_delete: false, use_precise_cursors: false, show_tool_tips: true, + show_external_script_warning: true, anti_aliased_artwork: true, select_same_tint_percent: false, show_home_screen: true, use_preview_bounds: false, align_glyph_bounds_point: false, align_glyph_bounds_area: false, + type_glyph_bounds: false, fade_region_outside_artboard: true, artboard_update_while_dragging: true, display_print_size: false, @@ -421,6 +433,7 @@ impl Default for Prefs { identify_objects_by: s("objectName"), guide_color: s("#4affff"), guide_style: s("lines"), + lock_guides_by_default: false, grid_color: s("#c8c8c8"), grid_style: s("lines"), gridline_every: 72.0, diff --git a/crates/engine/src/schemas.rs b/crates/engine/src/schemas.rs new file mode 100644 index 0000000000..61ec8f0fd6 --- /dev/null +++ b/crates/engine/src/schemas.rs @@ -0,0 +1,477 @@ +//! The commands' parameter schemas ([`vectorcraft_apischema::ParamSchema`]) and the API level they +//! belong to. +//! +//! A command with a schema (`CommandSpec::schema`) has its params checked against it by +//! [`crate::Session::execute`] before it runs ([`check`]), and by the steps that run a command's +//! implementation directly ([`crate::cmd::run_checked`]): a value of the wrong type, out of range +//! or not in its list, a missing required parameter or an unknown key is refused with a parameter +//! error naming the parameter, and the command does not run, so the document and its undo history +//! stay as they were. An omitted value with a default takes it. The steps of a `command.batch` or +//! an `action.batch` are checked before the first one runs. Saved steps +//! ([`crate::Session::replay`]) keep their keys a schema doesn't name, and their values are checked. +//! The command's `params` text is the text its schema writes, and `engine.commands` lists the schema +//! of each command that has one. +//! +//! [`API_VERSION`] goes up by one whenever a schema of a built-in command changes, and +//! [`SCHEMA_HASHES`] gains a row with the new level and [`schema_hash`]: a test fails while the +//! newest row does not match the schemas. Commands that plug-ins add have no schema. + +use std::sync::OnceLock; + +use serde_json::Value; +use vectorcraft_apischema::{ParamError, Problem}; + +use crate::cmd::params::unknown; +use crate::cmd::{CommandSpec, bad, command_specs}; +use crate::{EngineError, Result}; + +/// The API level of the commands' parameters. +pub const API_VERSION: u32 = 2; + +/// [`schema_hash`] at each API level, oldest first; the last row is [`API_VERSION`]'s. +pub const SCHEMA_HASHES: &[(u32, u64)] = &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653)]; + +/// The hash of every built-in command's schema ([`vectorcraft_apischema::hash`]). +pub fn schema_hash() -> u64 { + vectorcraft_apischema::hash(command_specs().iter().filter_map(|c| Some((c.id, c.schema?)))) +} + +/// Each built-in schema that is wrong in itself, with why ([`vectorcraft_apischema::ParamSchema::definition_problem`]). +/// Worked out once, the first time a command with a schema runs. +fn definition_problems() -> &'static [(&'static str, String)] { + static PROBLEMS: OnceLock> = OnceLock::new(); + PROBLEMS.get_or_init(|| command_specs().iter().filter_map(|c| Some((c.id, c.schema?.definition_problem()?))).collect()) +} + +/// `params` checked against the schema of `spec`: a parameter error under the command's id for the +/// first problem, or the params with the defaults of omitted values filled in (`None` when the +/// command has no schema or nothing was filled in, so `params` is used as it is). A command with no +/// schema costs one branch. `saved`: the params of a saved step, whose keys the schema doesn't name +/// pass. A schema that is wrong in itself is an internal error, and its command does not run. +pub(crate) fn check(spec: &CommandSpec, params: &Value, saved: bool) -> Result> { + let Some(schema) = spec.schema else { return Ok(None) }; + if let Some((_, why)) = definition_problems().iter().find(|(id, _)| *id == spec.id) { + return Err(EngineError::Internal { cmd: spec.id.into(), msg: why.clone() }); + } + let checked = if saved { schema.validate_saved(params) } else { schema.validate(params) }; + checked.map_err(|e| param_error(spec.id, &e)) +} + +/// The parameter error of command `id` for `e`, in the words the message catalogs translate. An +/// unknown top-level key is reported as the commands without a schema report it, with the nearest +/// key. +fn param_error(id: &str, e: &ParamError) -> EngineError { + let path = &e.path; + match &e.problem { + Problem::NotAnObject { got } => bad(id, format!("the params must be an object, not {got}")), + Problem::Unknown { keys } if !path.contains(['.', '[']) => unknown(id, path, keys), + Problem::Unknown { keys } if keys.is_empty() => bad(id, format!("unknown parameter `{path}`; the object takes no keys")), + Problem::Unknown { keys } => bad(id, format!("unknown parameter `{path}`; it takes: {keys}", keys = keys.join(", "))), + Problem::Missing => bad(id, format!("missing `{path}`")), + Problem::WrongType { expected, got } => bad(id, format!("`{path}` must be {expected}, not {got}")), + Problem::TooDeep => EngineError::Internal { cmd: id.into(), msg: e.to_string() }, + } +} + +#[cfg(test)] +#[path = "../../apischema/src/conformance.rs"] +mod conformance; + +#[cfg(test)] +mod tests { + use proptest::prelude::*; + use serde_json::{Map, Value, json}; + use vectorcraft_apischema::{Bound, Omitted, Param, ParamSchema, Type}; + + use super::conformance::{check_schema, instance_valid}; + use super::*; + use crate::Session; + + fn schemas() -> Vec<(&'static str, &'static ParamSchema)> { + command_specs().iter().filter_map(|c| Some((c.id, c.schema?))).collect() + } + + /// The params text of a command with a schema is the text the schema writes. + #[test] + fn params_text_is_the_text_the_schema_writes() { + assert!(!schemas().is_empty()); + for c in command_specs() { + if let Some(schema) = c.schema { + assert_eq!(c.params, schema.params_text(), "{}", c.id); + } + } + } + + /// A schema changed without a new API level (and a new row of hashes) fails here: add the row + /// `(API_VERSION + 1, )` and raise [`API_VERSION`]. + #[test] + fn schema_hash_matches_the_api_version() { + let last = SCHEMA_HASHES.last().copied(); + assert_eq!(last.map(|(level, _)| level), Some(API_VERSION), "the last row of SCHEMA_HASHES is not API_VERSION's"); + assert_eq!(last.map(|(_, hash)| hash), Some(schema_hash()), "the schemas changed: {:#x}", schema_hash()); + assert!(SCHEMA_HASHES.windows(2).all(|w| w[0].0 < w[1].0), "the API levels go up"); + } + + /// Every schema is sound in itself ([`ParamSchema::definition_problem`]), so no command is + /// refused for its schema, and no parameter or command is newer than the API level. + #[test] + fn schemas_are_sound_and_levels_are_known() { + fn walk(id: &str, params: &[Param]) { + for p in params { + assert!(p.since >= 1 && p.since <= API_VERSION, "{id}.{}", p.name); + if let Type::Object(inner) | Type::Array(&Type::Object(inner)) = p.ty { + walk(id, inner); + } + } + } + assert_eq!(definition_problems(), &[]); + for (id, schema) in schemas() { + assert!(schema.since >= 1 && schema.since <= API_VERSION, "{id}"); + walk(id, schema.params); + } + } + + /// Each command's defaults are of its parameter's type (an omitted value takes them), with + /// which ones are filled in. + #[test] + fn declared_defaults_are_filled_in() { + let new_view = command_specs().iter().find(|c| c.id == "view.saved.new").and_then(|c| c.schema).unwrap(); + let filled = new_view.validate(&json!({"center": [1, 2], "zoom": 1})).unwrap().unwrap(); + assert_eq!(filled["rotation"], json!(0)); + assert!(filled.get("name").is_none(), "the command works out the name"); + assert!(new_view.param("rotation").is_some_and(|p| matches!(p.omitted, Omitted::Value("0")))); + } + + /// A refusal from the schema names the parameter, and the command does not run. + #[test] + fn a_refused_value_names_the_parameter_under_the_command() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": -1})).unwrap_err().to_string(); + assert!(e.contains("view.saved.new") && e.contains("`zoom` must be a number > 0, not -1"), "{e}"); + let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": 1, "rotaton": 5})).unwrap_err().to_string(); + assert!(e.contains("unknown parameter `rotaton`; did you mean `rotation`?"), "{e}"); + let e = s.execute("view.saved.new", &Value::Null).unwrap_err().to_string(); + assert!(e.contains("view.saved.new") && e.contains("missing `center`"), "{e}"); + assert!(s.doc().unwrap().doc.views.is_empty()); + assert!(s.doc().unwrap().history.undo.is_empty()); + } + + /// The key check runs before the schema, so a misspelled key is the error even when a value is + /// bad too, and the schema reports the value when the keys are right. + #[test] + fn a_misspelled_key_is_reported_before_a_bad_value() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": -1, "rotaton": 5})).unwrap_err().to_string(); + assert!(e.contains("did you mean `rotation`?"), "{e}"); + let e = s.execute("view.saved.new", &json!({"center": "here", "zoom": -1})).unwrap_err().to_string(); + assert!(e.contains("`center` must be [x, y] (two numbers), not \"here\""), "{e}"); + } + + /// Saved steps keep a retired key, at the top level and inside `edits`, and a bad value is + /// still refused, with no undo step; the journal keeps the params as given. + #[test] + fn saved_steps_keep_retired_keys_and_check_values() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let retired = json!({"name": "A", "center": [1, 2], "zoom": 2, "fitArt": true}); + assert!(s.execute("view.saved.new", &retired).is_err()); + s.replay("view.saved.new", &retired).unwrap(); + assert_eq!(s.doc().unwrap().doc.views[0].name, "A"); + let last = s.journal.last().unwrap(); + assert_eq!(last.1, retired, "the journal has the params as given, with no default filled in"); + s.replay("view.saved.edit", &json!({"edits": [{"name": "A", "newName": "B", "was": 1}]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.views[0].name, "B"); + assert!(s.execute("view.saved.edit", &json!({"edits": [{"name": "B", "newName": "C", "was": 1}]})).is_err()); + let steps = s.doc().unwrap().history.undo.len(); + let e = s.replay("view.saved.new", &json!({"center": [1, 2], "zoom": 0, "fitArt": true})).unwrap_err().to_string(); + assert!(e.contains("`zoom`"), "{e}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + // A frontend that replays through its own path sets the flag, and gets the same rule. + let outer = s.set_replaying(true); + s.execute("view.saved.new", &json!({"name": "C", "center": [1, 2], "zoom": 2, "fitArt": true})).unwrap(); + s.set_replaying(outer); + } + + /// A batch step a schema refuses stops the batch before its first step runs. + #[test] + fn a_batch_is_checked_against_the_schemas_before_its_first_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let step = |p: Value| json!({"command": "view.saved.new", "params": p}); + for (last, named) in [ + (step(json!({"center": [0, 0], "zoom": 0})), "`zoom`"), + (step(json!({"center": [0, 0]})), "`zoom`"), + (json!({"command": "view.saved.new"}), "`center`"), + ] { + let batch = json!({"commands": [step(json!({"name": "First", "center": [0, 0], "zoom": 1})), last]}); + let e = s.execute("command.batch", &batch).unwrap_err().to_string(); + assert!(e.contains("view.saved.new") && e.contains(named), "{e}"); + assert!(s.doc().unwrap().doc.views.is_empty(), "the first step did not run: {e}"); + assert!(s.doc().unwrap().history.undo.is_empty()); + } + } + + /// Values and keys far larger than any a command takes are refused with a short error and no + /// panic. Nested values are leaked because dropping one recurses per level. + #[test] + fn hostile_values_are_refused_with_a_short_error() { + fn deep(levels: usize) -> Value { + (0..levels).fold(json!(1), |inner, _| Value::Array(vec![inner])) + } + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let huge = "z".repeat(2_000_000); + for params in [ + json!({ huge.as_str(): 1, "center": [0, 0], "zoom": 1 }), + json!({"center": [0, 0], "zoom": huge}), + json!({"center": huge, "zoom": 1}), + json!({"center": [0, 0], "zoom": 1, "name": [huge]}), + json!({"center": [0, 0], "zoom": f64::MAX, "rotation": f64::INFINITY}), + ] { + let e = s.execute("view.saved.new", ¶ms).unwrap_err().to_string(); + assert!(e.chars().count() < 400, "{} chars", e.chars().count()); + } + let e = s.execute("view.saved.edit", &json!({"edits": [{"name": "A", huge.as_str(): 1}]})).unwrap_err().to_string(); + assert!(e.chars().count() < 400, "{} chars", e.chars().count()); + let nested = json!({"center": [0, 0]}); + let Value::Object(mut map) = nested else { panic!() }; + map.insert("zoom".into(), deep(500_000)); + let params = Value::Object(map); + let e = s.execute("view.saved.new", ¶ms).unwrap_err().to_string(); + assert!(e.contains("`zoom`") && e.chars().count() < 400, "{e}"); + std::mem::forget(params); + assert!(s.doc().unwrap().doc.views.is_empty()); + assert!(s.doc().unwrap().history.undo.is_empty()); + } + + /// Each command's JSON schema follows the 2020-12 rules, and a validator of those rules, which + /// shares no code with the writer, gives the same answer as the schema check. None of these + /// schemas has a lenient parameter. + #[test] + fn the_listed_schemas_follow_2020_12_and_agree_with_the_check() { + let cases: &[(&str, Value)] = &[ + ("view.capsLock", json!({})), + ("view.capsLock", json!({"on": true})), + ("view.capsLock", json!({"on": "yes"})), + ("view.capsLock", json!({"on": null})), + ("view.capsLock", json!({"of": true})), + ("view.saved.new", json!({"center": [0, 0], "zoom": 1})), + ("view.saved.new", json!({"center": [0.5, -2], "zoom": 0.001, "rotation": -30, "name": "A"})), + ("view.saved.new", json!({"center": [0, 0], "zoom": 1, "name": null})), + ("view.saved.new", json!({"center": [0, 0], "zoom": 1, "rotation": null})), + ("view.saved.new", json!({"center": [0, 0], "zoom": 0})), + ("view.saved.new", json!({"center": [0, 0], "zoom": -1})), + ("view.saved.new", json!({"center": [0], "zoom": 1})), + ("view.saved.new", json!({"center": [0, 0, 0], "zoom": 1})), + ("view.saved.new", json!({"center": [0, "0"], "zoom": 1})), + ("view.saved.new", json!({"zoom": 1})), + ("view.saved.new", json!({"center": [0, 0]})), + ("view.saved.new", json!({"center": [0, 0], "zoom": 1, "name": 5})), + ("view.saved.edit", json!({})), + ("view.saved.edit", json!({"name": "A", "newName": "B"})), + ("view.saved.edit", json!({"name": null, "delete": null})), + ("view.saved.edit", json!({"edits": []})), + ("view.saved.edit", json!({"edits": null})), + ("view.saved.edit", json!({"edits": [{"name": "A", "delete": true}, {"name": "B", "newName": null}]})), + ("view.saved.edit", json!({"edits": [{"newName": "B"}]})), + ("view.saved.edit", json!({"edits": [{"name": "A", "delete": 1}]})), + ("view.saved.edit", json!({"edits": [{"name": "A", "x": 1}]})), + ("view.saved.edit", json!({"edits": {"name": "A"}})), + ("view.saved.list", json!({})), + ("view.saved.list", json!({"all": true})), + ("view.transparencyGrid", json!({})), + ("view.transparencyGrid", json!({"on": null})), + ("view.transparencyGrid", json!({"on": false})), + ("view.transparencyGrid", json!({"on": 1})), + ("view.snapToGlyph.options", json!({"bounds": false, "angular": true})), + ("view.snapToGlyph.options", json!({"bounds": null})), + ("view.capsLock", json!(null)), + ("view.saved.new", json!(null)), + ("view.saved.edit", json!(null)), + ("view.saved.list", json!(null)), + ("view.transparencyGrid", json!(null)), + ("view.snapToGlyph.options", json!(null)), + ("view.capsLock", json!([])), + ("view.saved.new", json!(5)), + ("view.transparencyGrid", json!("on")), + ("engine.apiReference", json!({})), + ("engine.apiReference", json!(null)), + ("engine.apiReference", json!({"prefix": "view."})), + ("engine.apiReference", json!([])), + ]; + assert_eq!(schemas().len(), 7); + for (id, schema) in schemas() { + let written = schema.to_json(); + check_schema(&written, id).unwrap_or_else(|e| panic!("{e}\n{written:#}")); + assert!(cases.iter().any(|(c, _)| *c == id), "{id} has no cases"); + } + for (id, params) in cases { + let schema = schemas().into_iter().find(|(c, _)| c == id).unwrap().1; + assert_eq!(schema.validate(params).is_ok(), instance_valid(&schema.to_json(), params), "{id} {params}"); + } + } + + /// The engine's own listing carries the schema of each command that has one. + #[test] + fn engine_commands_list_the_schemas() { + let s = Session::new(); + let all = s.commands(); + let grid = all.iter().find(|c| c.id == "view.transparencyGrid").and_then(|c| c.schema.clone()).unwrap(); + assert_eq!(grid["$schema"], vectorcraft_apischema::DIALECT); + assert_eq!(grid["properties"]["on"]["x-default"], "toggle"); + let listed = serde_json::to_value(all.iter().find(|c| c.id == "view.saved.new").unwrap()).unwrap(); + assert_eq!(listed["schema"]["required"], json!(["center", "zoom"])); + let without = serde_json::to_value(all.iter().find(|c| c.id == "file.new").unwrap()).unwrap(); + assert!(without.get("schema").is_none()); + } + + /// The listing gives each command with a schema an `inputSchema`, the form an MCP tool's input + /// schema takes: the same schema with the root `type` `"object"`, and every other keyword kept, + /// nested parameters, required names, defaults and VectorCraft's own fields included. A command + /// with no schema lists neither. + #[test] + fn engine_commands_list_an_input_schema_with_an_object_root() { + let s = Session::new(); + let listed: Vec = s.commands().iter().map(|c| serde_json::to_value(c).unwrap()).collect(); + let mut with_schema = 0; + for c in &listed { + let id = c["id"].as_str().unwrap(); + let Some(schema) = c.get("schema") else { + assert!(c.get("inputSchema").is_none(), "{id}"); + continue; + }; + with_schema += 1; + let input = c.get("inputSchema").unwrap_or_else(|| panic!("{id} has no inputSchema")); + assert_eq!(input["type"], "object", "{id}"); + assert_eq!(input["$schema"], vectorcraft_apischema::DIALECT, "{id}"); + check_schema(input, id).unwrap_or_else(|e| panic!("{e}\n{input:#}")); + assert!(!instance_valid(input, &Value::Null), "{id}: the arguments are an object"); + let without_type = |v: &Value| { + let mut v = v.clone(); + v.as_object_mut().map(|o| o.remove("type")); + v + }; + assert_eq!(without_type(schema), without_type(input), "{id}"); + } + assert_eq!(with_schema, schemas().len()); + let get = |id: &str| listed.iter().find(|c| c["id"] == id).unwrap(); + // No required parameter: the schema also takes null, the input schema does not. + let list = get("view.saved.list"); + assert_eq!(list["schema"]["type"], json!(["object", "null"])); + assert_eq!(list["inputSchema"]["type"], "object"); + // Required parameters and their constraints are kept. + let new_view = get("view.saved.new"); + assert_eq!(new_view["inputSchema"]["required"], json!(["center", "zoom"])); + assert_eq!(new_view["inputSchema"]["properties"], new_view["schema"]["properties"]); + // Nested objects in an array keep their keys. + let edit = &get("view.saved.edit")["inputSchema"]["properties"]["edits"]; + assert!(edit.to_string().contains("newName"), "{edit}"); + assert!(get("file.new").get("inputSchema").is_none()); + } + + /// A deprecated command and a deprecated parameter keep their deprecation in the input schema. + #[test] + fn an_input_schema_keeps_deprecation() { + static PARAMS: [Param; 2] = [Param::new("old", Type::Boolean).optional().deprecated(1), Param::new("on", Type::Boolean).optional()]; + let schema = ParamSchema::new(&PARAMS, "Old command.").deprecated(1).to_json(); + let input = crate::cmd::input_schema(&schema); + check_schema(&input, "synthetic").unwrap_or_else(|e| panic!("{e}\n{input:#}")); + assert_eq!(schema["type"], json!(["object", "null"])); + assert_eq!(input["type"], "object"); + assert_eq!(input["deprecated"], true); + assert_eq!(input["x-deprecatedSince"], 1); + assert_eq!(input["properties"]["old"], schema["properties"]["old"]); + assert_eq!(input["properties"]["old"]["deprecated"], true); + assert_eq!(input["description"], "Old command."); + } + + /// The listing says what each View command changes when it runs. Only the commands that make an + /// undo step list `document`. + #[test] + fn each_view_command_lists_what_it_writes() { + let listed: Vec<(&str, Value)> = schemas().into_iter().map(|(id, schema)| (id, schema.to_json()["x-writes"].clone())).collect(); + let expected = [ + ("view.capsLock", "session"), + ("view.saved.new", "document"), + ("view.saved.edit", "document"), + ("view.saved.list", "nothing"), + ("view.transparencyGrid", "session"), + ("view.snapToGlyph.options", "preferences"), + ]; + for (id, writes) in expected { + let got = listed.iter().find(|(c, _)| *c == id).map(|(_, w)| w.clone()); + assert_eq!(got, Some(json!(writes)), "{id}"); + } + } + + /// Values of type `ty` that pass it. + fn valid(ty: Type) -> BoxedStrategy { + fn number(min: Option, max: Option) -> BoxedStrategy { + let low = match min { + Some(Bound::Inclusive(a)) => a, + Some(Bound::Exclusive(a)) => a + 1e-6_f64.max(a.abs() * 1e-9), + None => -1e6, + }; + let high = match max { + Some(Bound::Inclusive(b)) => b, + Some(Bound::Exclusive(b)) => b - 1e-6_f64.max(b.abs() * 1e-9), + None => low.max(0.0) + 1e6, + }; + (low..=high).prop_map(|x| json!(x)).boxed() + } + match ty { + Type::Number { min, max, .. } => number(min, max), + Type::Integer { min, max } => (min.unwrap_or(-1_000_000)..=max.unwrap_or(1_000_000)).prop_map(|x| json!(x)).boxed(), + Type::Boolean => any::().prop_map(Value::from).boxed(), + Type::String => "[ -~]{0,12}".prop_map(Value::from).boxed(), + Type::Enum(names) => prop::sample::select(names.to_vec()).prop_map(Value::from).boxed(), + Type::Id => (0u64..10_000).prop_map(Value::from).boxed(), + Type::Ids => prop::collection::vec(0u64..10_000, 0..4).prop_map(Value::from).boxed(), + Type::Color => Just(json!("#336699")).boxed(), + Type::Point => (-1e6..1e6f64, -1e6..1e6f64).prop_map(|(x, y)| json!([x, y])).boxed(), + Type::Object(params) => valid_object(params), + Type::Array(item) => prop::collection::vec(valid(*item), 0..3).prop_map(Value::from).boxed(), + } + } + + /// Objects that pass `params`: each required parameter, and each optional one or not. + fn valid_object(params: &'static [Param]) -> BoxedStrategy { + let parts: Vec>> = params + .iter() + .map(|p| { + let entry = valid(p.ty).prop_map(move |v| Some((p.name.to_string(), v))); + if p.required { entry.boxed() } else { prop_oneof![Just(None), entry].boxed() } + }) + .collect(); + parts.prop_map(|entries| Value::Object(entries.into_iter().flatten().collect::>())).boxed() + } + + /// Commands with a schema and params for them that pass it. + fn valid_calls() -> BoxedStrategy<(&'static str, Value)> { + let calls: Vec> = + schemas().into_iter().map(|(id, schema)| valid_object(schema.params).prop_map(move |p| (id, p)).boxed()).collect(); + prop::strategy::Union::new(calls).boxed() + } + + proptest! { + /// Params that pass a command's schema never get a parameter error about a value's type or + /// range from the command itself: the schema refuses whatever the command's own checks would. + #[test] + fn schema_valid_params_get_no_type_error_from_the_command((id, params) in valid_calls(), views in 0usize..3) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + for i in 0..views { + s.execute("view.saved.new", &json!({"name": format!("V{i}"), "center": [0, 0], "zoom": 1})).unwrap(); + } + match s.execute(id, ¶ms) { + Err(EngineError::BadParams { msg, .. }) => { + prop_assert!(!msg.contains(" must be ") && !msg.contains("missing") && !msg.contains("unknown parameter"), "{id} {params}: {msg}"); + } + Err(EngineError::Internal { msg, .. }) => prop_assert!(false, "{id} {params} panicked: {msg}"), + _ => {} + } + } + } +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs new file mode 100644 index 0000000000..9d0a47fbff --- /dev/null +++ b/crates/engine/src/script/mod.rs @@ -0,0 +1,1232 @@ +//! Running a script: `script.run`, `script.stop` and the job behind them. +//! +//! A run works on its own copy of the open documents and the session state commands change (the +//! working copy). Between two slices of a run, the session holds the state as it was before the +//! run: what is drawn, what a read-only command returns and what Data Recovery copies never show a +//! script's unfinished work. Each slice swaps the working copy in, advances the interpreter by one +//! measured slice of fuel and swaps it out. A commit makes the working copy the session's state, +//! with one undo step for each document whose art changed. A rollback drops the working copy. +//! +//! While a job exists, [`Session::execute`] refuses any command that can edit, select, save or give +//! a document a new revision, and the tool events are refused the same way (the mutation lease). +//! The script's own commands run through [`Session::execute`] inside a slice, each with its own +//! parameter checks, enabled rule, undo history and journal entry, and a command that fails leaves +//! no trace of itself. Inside a run, `edit.undo` reaches only steps the script made. +//! +//! Files a script's commands saved or exported before it failed stay written, and the failure names +//! them. Ids given out in a run are never given out again for a document, also after an in-run +//! undo or a rollback. +//! +//! The values here are VectorCraft's own limits: [`MAX_SOURCE_BYTES`], [`DEFAULT_FUEL`], +//! [`MAX_FUEL`], [`SLICE_FUEL`], [`HEAP_BYTES`], [`MAX_HOST_CALLS`], [`GROWTH_OBJECTS`], +//! [`GROWTH_BYTES`], [`MAX_CONTINUES`], [`MAX_LOG_LINES`], [`MAX_LOG_BYTES`], [`MAX_ARGS_BYTES`], +//! and the 64 levels, 16 MiB and 1,048,576 entries of [`vectorcraft_js::DataLimits`]'s default. + +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{ + Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind, +}; + +use crate::{ + Clipboard, DocState, DrawMode, EngineError, Journal, NodeId, PaintDefaults, Result, Session, cmd, command_specs, guard, waits_for_tool_edit, +}; + +/// The most bytes of source a run takes, as a file or as `source`. +pub const MAX_SOURCE_BYTES: usize = 8 << 20; +/// The instructions a run may execute when `maxFuel` is left out. +pub const DEFAULT_FUEL: u64 = 1_000_000_000; +/// The largest `maxFuel`. +pub const MAX_FUEL: u64 = 100_000_000_000; +/// The instructions one slice of a run executes before the interface draws again. +pub const SLICE_FUEL: u64 = 500_000; +/// The heap one run may use. +#[cfg(not(target_arch = "wasm32"))] +pub const HEAP_BYTES: usize = 256 << 20; +/// The heap one run may use in a wasm build. +#[cfg(target_arch = "wasm32")] +pub const HEAP_BYTES: usize = 128 << 20; +/// The most `vc.run` calls and getter reads of one run. +pub const MAX_HOST_CALLS: u64 = 2_000_000; +/// The objects a run may make before it is asked to continue or stop. +pub const GROWTH_OBJECTS: u64 = 100_000; +/// The bytes of new document data a run may keep before it is asked to continue or stop. +pub const GROWTH_BYTES: u64 = 512 << 20; +/// How many times a person may let a run go past its growth allowance; each time adds one more. +pub const MAX_CONTINUES: u32 = 8; +/// The most `vc.log` entries of one run. +pub const MAX_LOG_LINES: usize = 10_000; +/// The most bytes of `vc.log` entries of one run. +pub const MAX_LOG_BYTES: usize = 4 << 20; +/// The most bytes of `args` given to one run, as JSON. +pub const MAX_ARGS_BYTES: usize = 1 << 20; +/// The `vc.run` calls one slice makes before the interface draws again. +const SLICE_HOST_CALLS: u32 = 256; +/// The bytes that may cross between a script and the host in one run. +const MAX_BRIDGE_BYTES: u64 = 4 << 30; + +/// The version `vc.api.version` gives. +pub const API_VERSION: &str = "1.0"; +/// The features `vc.api.has` knows. +pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args"]; + +/// What the step of a run's one undo step is called. +pub const STEP_LABEL: &str = "Run Script"; + +/// `id`, as `vc.run` is given it, is one a script may not run: a command that would leave the run's +/// transaction, change something outside the documents that a rollback could not put back, or clear +/// the undo steps from before the run, which the run keeps. +pub fn refused_to_scripts(id: &str) -> bool { + const PREFIXES: &[&str] = &[ + "script.", + "plugin.", + "prefs.", + "actionSet.", + "shortcutSet.", + "help.", + "print.", + "library.", + "importMatches.", + "edit.undoGroup.", + "file.recovery.", + "stroke.widthProfile.", + ]; + const IDS: &[&str] = &[ + "text.addFontFiles", + "text.findFontFiles", + "text.rescanFonts", + "links.findFiles", + "file.place.queue", + "color.loadProfile", + "color.removeProfile", + "file.print", + "view.proofSetup", + "view.proofColors", + "view.overprintPreview", + "view.separationsPreview", + "edit.clearHistory", + ]; + let saved_preset = (id.contains("resets.") || id.contains(".preset.")) && !id.ends_with(".list") && !id.ends_with(".apply"); + id != "script.check" && (saved_preset || PREFIXES.iter().any(|p| id.starts_with(p)) || IDS.contains(&id)) +} + +/// The error for a script's command that [`refused_to_scripts`] names. +pub(crate) fn refused_text(id: &str) -> String { + format!("a script cannot run `{id}`") +} + +/// A request to run a script. +pub(crate) struct Request { + pub name: String, + pub source: String, + pub args: Map, + pub fuel: u64, +} + +thread_local! { + /// The running jobs of this thread's sessions. A job is held here, and not in its session, + /// because it holds the interpreter, which stays on the thread that started it. + static JOBS: RefCell> = RefCell::new(HashMap::new()); +} + +static NEXT_JOB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +/// A session's hold on its running job: while one exists the lease is held. Dropping it ends the job. +#[derive(Debug)] +pub struct JobKey(u64); + +impl Drop for JobKey { + fn drop(&mut self) { + let _ = JOBS.try_with(|jobs| { + if let Ok(mut jobs) = jobs.try_borrow_mut() { + jobs.remove(&self.0); + } + }); + } +} + +fn with_job(key: &JobKey, f: impl FnOnce(&mut Job) -> T) -> Option { + JOBS.with(|jobs| jobs.borrow_mut().get_mut(&key.0).map(f)) +} + +/// The state a script changes that a rollback puts back. +struct World { + docs: Vec, + active: Option, + paint: PaintDefaults, + fill_active: bool, + draw_mode: DrawMode, + draw_inside: Option, + clipboard: Clipboard, + untitled_counter: u32, + menu: cmd::menucmds::MenuState, + last_solid: crate::Color, + last_gradient: crate::GradientPaint, + recent_colors: Vec, + pending_paint: Option, + choices: Choices, + journal: Journal, + /// The preferences when the run started. + start_prefs: crate::Prefs, + /// The Caps Lock state when the run started. + start_caps_lock: bool, +} + +/// The choices outside the documents that a script's commands can change: the preferences, the +/// global edit options, the recent URLs, the chosen gradient stop, freeform point and appearance +/// item, the Eyedropper's sample, the envelope defaults and the Caps Lock state. +#[derive(Clone)] +struct Choices { + prefs: crate::Prefs, + caps_lock: bool, + eyedropper_sample: Option>, + global_edit_options: cmd::globaledit::Options, + recent_urls: Vec, + gradient_stop: Option<(usize, cmd::gradient::StopOwner)>, + freeform_point: Option<(usize, cmd::gradient::StopOwner)>, + active_appearance_item: Option, + envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>, +} + +impl Choices { + fn of(s: &Session) -> Self { + Self { + prefs: s.prefs.clone(), + caps_lock: s.caps_lock, + eyedropper_sample: s.eyedropper_sample.clone(), + global_edit_options: s.global_edit_options.clone(), + recent_urls: s.recent_urls.clone(), + gradient_stop: s.gradient_stop, + freeform_point: s.freeform_point, + active_appearance_item: s.active_appearance_item.clone(), + envelope_defaults: s.envelope_defaults, + } + } + + fn put(self, s: &mut Session) { + s.prefs = self.prefs; + s.caps_lock = self.caps_lock; + s.eyedropper_sample = self.eyedropper_sample; + s.global_edit_options = self.global_edit_options; + s.recent_urls = self.recent_urls; + s.gradient_stop = self.gradient_stop; + s.freeform_point = self.freeform_point; + s.active_appearance_item = self.active_appearance_item; + s.envelope_defaults = self.envelope_defaults; + } + + fn swap(&mut self, s: &mut Session) { + use std::mem::swap; + swap(&mut self.prefs, &mut s.prefs); + swap(&mut self.caps_lock, &mut s.caps_lock); + swap(&mut self.eyedropper_sample, &mut s.eyedropper_sample); + swap(&mut self.global_edit_options, &mut s.global_edit_options); + swap(&mut self.recent_urls, &mut s.recent_urls); + swap(&mut self.gradient_stop, &mut s.gradient_stop); + swap(&mut self.freeform_point, &mut s.freeform_point); + swap(&mut self.active_appearance_item, &mut s.active_appearance_item); + swap(&mut self.envelope_defaults, &mut s.envelope_defaults); + } +} + +/// The preferences after a run: `current`, the session's, which the app may have changed while the +/// run went on, with each preference the run changed from `start` set to the run's value. +fn merged_prefs(start: &crate::Prefs, run: &crate::Prefs, current: &crate::Prefs) -> crate::Prefs { + let (Ok(Value::Object(start)), Ok(Value::Object(run)), Ok(Value::Object(mut out))) = + (serde_json::to_value(start), serde_json::to_value(run), serde_json::to_value(current)) + else { + return current.clone(); + }; + for (key, value) in run { + if start.get(&key) != Some(&value) { + out.insert(key, value); + } + } + serde_json::from_value(Value::Object(out)).unwrap_or_else(|_| current.clone()) +} + +impl World { + /// A working copy of the session's state: its documents, each with an undo history of its own + /// that starts empty, and an empty journal. + fn working(s: &Session) -> Self { + let mut docs = s.docs.clone(); + for st in &mut docs { + st.history.undo.clear(); + st.history.redo.clear(); + } + Self { + docs, + active: s.active, + paint: s.paint.clone(), + fill_active: s.fill_active, + draw_mode: s.draw_mode, + draw_inside: s.draw_inside, + clipboard: s.clipboard.clone(), + untitled_counter: s.untitled_counter, + menu: s.menu.clone(), + last_solid: s.last_solid, + last_gradient: s.last_gradient.clone(), + recent_colors: s.recent_colors.clone(), + pending_paint: s.pending_paint.clone(), + choices: Choices::of(s), + journal: Journal::default(), + start_prefs: s.prefs.clone(), + start_caps_lock: s.caps_lock, + } + } + + /// Exchanges this state with the session's. + fn swap(&mut self, s: &mut Session) { + use std::mem::swap; + swap(&mut self.docs, &mut s.docs); + swap(&mut self.active, &mut s.active); + swap(&mut self.paint, &mut s.paint); + swap(&mut self.fill_active, &mut s.fill_active); + swap(&mut self.draw_mode, &mut s.draw_mode); + swap(&mut self.draw_inside, &mut s.draw_inside); + swap(&mut self.clipboard, &mut s.clipboard); + swap(&mut self.untitled_counter, &mut s.untitled_counter); + swap(&mut self.menu, &mut s.menu); + swap(&mut self.last_solid, &mut s.last_solid); + swap(&mut self.last_gradient, &mut s.last_gradient); + swap(&mut self.recent_colors, &mut s.recent_colors); + swap(&mut self.pending_paint, &mut s.pending_paint); + self.choices.swap(s); + swap(&mut self.journal, &mut s.journal); + } +} + +/// The commands that can change the clipboard and still fail, and that do not put it back +/// themselves. The clipboard can hold a great deal, so a savepoint copies it only for these. +const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "edit.cut"]; + +/// The commands that remove a document's undo history, or the document: a savepoint keeps a whole +/// copy of the histories for these. Any other command that removes or changes a step under the +/// newest undo or redo step and then fails ends the run ([`HISTORY_LOST`]). +const DROP_HISTORY: &[&str] = &["file.close", "file.closeAll", "document.close", "file.revert"]; + +/// A document's state before a command: everything but its undo history, which `mark` gives back, +/// or `whole` for the commands in [`DROP_HISTORY`]. +struct SavedDoc { + state: DocState, + mark: crate::history::HistoryMark, + whole: Option, +} + +/// What one command may need to put back when it fails inside a run: the state of [`World`] the +/// command can reach. +pub(crate) struct Savepoint { + docs: Vec, + active: Option, + paint: PaintDefaults, + fill_active: bool, + draw_mode: DrawMode, + draw_inside: Option, + clipboard: Option, + untitled_counter: u32, + menu: cmd::menucmds::MenuState, + last_solid: crate::Color, + last_gradient: crate::GradientPaint, + recent_colors: Vec, + pending_paint: Option, + choices: Choices, + journal: usize, +} + +impl Savepoint { + /// The state before command `id`. Until [`Savepoint::keep`] or [`Savepoint::restore`], the + /// documents' undo histories let no step go. + pub(crate) fn take(s: &mut Session, id: &str) -> Self { + let whole = DROP_HISTORY.contains(&id); + let docs = s + .docs + .iter_mut() + .map(|st| { + let history = std::mem::take(&mut st.history); + let state = st.clone(); + st.history = history; + let whole = whole.then(|| st.history.clone()); + SavedDoc { state, mark: st.history.mark(), whole } + }) + .collect(); + Self { + docs, + active: s.active, + paint: s.paint.clone(), + fill_active: s.fill_active, + draw_mode: s.draw_mode, + draw_inside: s.draw_inside, + clipboard: CAN_FAIL_AFTER_COPYING.contains(&id).then(|| s.clipboard.clone()), + untitled_counter: s.untitled_counter, + menu: s.menu.clone(), + last_solid: s.last_solid, + last_gradient: s.last_gradient.clone(), + recent_colors: s.recent_colors.clone(), + pending_paint: s.pending_paint.clone(), + choices: Choices::of(s), + journal: s.journal.len(), + } + } + + /// Keeps what the command did: the histories' limits apply again. + pub(crate) fn keep(self, s: &mut Session) { + for saved in &self.docs { + if let Some(st) = s.docs.iter_mut().find(|d| d.uid == saved.state.uid) { + st.history.release(&saved.mark); + } + } + } + + /// Puts back the state before the command. → `false` when an undo history could not be given + /// back as it was (a step under the newest one was removed or changed in place, or its + /// document was closed); the rest is put back all the same. + pub(crate) fn restore(self, s: &mut Session) -> bool { + let mut exact = true; + let mut docs = Vec::with_capacity(self.docs.len()); + for SavedDoc { mut state, mark, whole } in self.docs { + let now = s.docs.iter_mut().find(|d| d.uid == state.uid).map(|d| std::mem::take(&mut d.history)); + state.history = match (whole, now) { + (Some(history), _) => history, + (None, Some(mut history)) => { + exact &= history.put_back(mark); + history + } + (None, None) => { + exact = false; + let mut history = crate::History::default(); + history.put_back(mark); + history + } + }; + docs.push(state); + } + s.docs = docs; + s.active = self.active; + s.paint = self.paint; + s.fill_active = self.fill_active; + s.draw_mode = self.draw_mode; + s.draw_inside = self.draw_inside; + if let Some(clipboard) = self.clipboard { + s.clipboard = clipboard; + } + s.untitled_counter = self.untitled_counter; + s.menu = self.menu; + s.last_solid = self.last_solid; + s.last_gradient = self.last_gradient; + s.recent_colors = self.recent_colors; + s.pending_paint = self.pending_paint; + self.choices.put(s); + s.journal.truncate(self.journal); + exact + } +} + +/// The counters and the session a script's host functions share. Between slices `session` holds a +/// spare session; during a slice it holds the real one, because the interpreter cannot be given a +/// borrow of it. +struct Host { + session: Rc>, + pause: Rc>, + /// The run is sliced by frames, so the person at the computer can be asked to continue. + framed: bool, + calls: Cell, + calls_this_slice: Cell, + objects: Cell, + bytes_kept: Cell, + bridge: Cell, + allowance_objects: Cell, + allowance_bytes: Cell, + continues: Cell, + /// Past the growth allowance, waiting for the person's answer. + waiting: Cell, + log: RefCell>, + log_bytes: Cell, + written: RefCell>, +} + +impl Host { + fn over(&self, limit: &str) -> HostError { + HostError::Abort(limit.to_string()) + } + + fn charge_call(&self, bytes: u64) -> std::result::Result<(), HostError> { + let calls = self.calls.get() + 1; + self.calls.set(calls); + if calls > MAX_HOST_CALLS { + return Err(self.over(OVER_CALLS)); + } + let bridge = self.bridge.get().saturating_add(bytes); + self.bridge.set(bridge); + if bridge > MAX_BRIDGE_BYTES { + return Err(self.over(OVER_BRIDGE)); + } + let n = self.calls_this_slice.get() + 1; + self.calls_this_slice.set(n); + if n >= SLICE_HOST_CALLS { + self.pause.set(true); + } + Ok(()) + } + + /// Counts what a command added to the documents, past which the person is asked or, without + /// anyone to ask, the run ends. A run that goes on past twice its allowance within one slice + /// ends too. + fn charge_growth(&self, objects: u64, bytes: u64) -> std::result::Result<(), HostError> { + self.objects.set(self.objects.get().saturating_add(objects)); + self.bytes_kept.set(self.bytes_kept.get().saturating_add(bytes)); + let (o, b) = (self.objects.get(), self.bytes_kept.get()); + let (limit_o, limit_b) = (self.allowance_objects.get(), self.allowance_bytes.get()); + if o <= limit_o && b <= limit_b { + return Ok(()); + } + let may_ask = self.framed && self.continues.get() < MAX_CONTINUES; + if !may_ask || o > limit_o.saturating_mul(2) || b > limit_b.saturating_mul(2) { + return Err(self.over(OVER_GROWTH)); + } + self.waiting.set(true); + self.pause.set(true); + Ok(()) + } +} + +/// A run in progress. +struct Job { + realm: Realm, + host: Rc, + /// Between slices the working copy; during the last slice's commit the state before the run. + world: World, + /// The documents open when the run began, by [`DocState::uid`]. + start_uids: Vec, + name: String, + /// The file-access scope `script.run` came in, which every slice runs in. + scope: crate::file_access::ScopeHandle, +} + +/// The `Data` for a JSON value, within `limits`. When it does not fit, the error is the place in +/// `v` where it stopped fitting, such as `.layers[2].name`, and empty for `v` itself. +pub(crate) fn to_data(v: &Value, limits: &DataLimits, depth: usize, used: &mut (usize, usize)) -> std::result::Result { + if depth > limits.depth { + return Err(String::new()); + } + used.0 = used.0.saturating_add(16); + used.1 = used.1.saturating_add(1); + if used.0 > limits.bytes || used.1 > limits.entries { + return Err(String::new()); + } + Ok(match v { + Value::Null => Data::Null, + Value::Bool(b) => Data::Bool(*b), + Value::Number(n) => Data::Number(n.as_f64().unwrap_or(f64::NAN)), + Value::String(s) => { + used.0 = used.0.saturating_add(s.len()); + if used.0 > limits.bytes { + return Err(String::new()); + } + Data::String(s.clone()) + } + Value::Array(a) => Data::Array( + a.iter() + .enumerate() + .map(|(i, x)| to_data(x, limits, depth + 1, used).map_err(|place| format!("[{i}]{place}"))) + .collect::>()?, + ), + Value::Object(o) => Data::Object( + o.iter() + .map(|(k, x)| { + used.0 = used.0.saturating_add(k.len()); + to_data(x, limits, depth + 1, used).map(|d| (k.clone(), d)).map_err(|place| format!(".{k}{place}")) + }) + .collect::>()?, + ), + }) +} + +/// The JSON for a value a script gave; a whole number within a double's exact range is an integer, +/// which is how commands read ids and counts. +fn to_json(d: &Data) -> Value { + match d { + Data::Undefined | Data::Null => Value::Null, + Data::Bool(b) => Value::Bool(*b), + Data::Number(n) => + { + #[allow(clippy::cast_possible_truncation)] + if n.fract() == 0.0 && n.abs() <= 9_007_199_254_740_992.0 { + json!(*n as i64) + } else { + serde_json::Number::from_f64(*n).map_or(Value::Null, Value::Number) + } + } + Data::String(s) => Value::String(s.clone()), + Data::Array(a) => Value::Array(a.iter().map(to_json).collect()), + Data::Object(o) => Value::Object(o.iter().map(|(k, v)| (k.clone(), to_json(v))).collect()), + } +} + +/// A step into a JSON value: a key or an index. +enum Step<'a> { + Name(&'a str), + Index(usize), +} + +/// The place in `v` that is more than [`DataLimits`]' depth levels deep, such as `.layers[2].name`, +/// or `None`. It walks `v` with a list of its own, so any depth fits on the stack. +pub(crate) fn too_deep(v: &Value) -> Option { + let limit = DataLimits::default().depth; + // `steps[i - 1]` is the entry that holds entry `i` and the step into it; entry 0 is `v`. + let mut steps: Vec<(usize, Step<'_>)> = Vec::new(); + let mut todo = vec![(v, 0usize, 0usize)]; + while let Some((v, depth, entry)) = todo.pop() { + if depth > limit { + let mut place = Vec::new(); + let mut at = entry; + while let Some((parent, step)) = at.checked_sub(1).and_then(|i| steps.get(i)) { + place.push(match step { + Step::Name(k) => format!(".{k}"), + Step::Index(i) => format!("[{i}]"), + }); + at = *parent; + } + place.reverse(); + return Some(place.concat()); + } + let children: Box, &Value)>> = match v { + Value::Array(a) => Box::new(a.iter().enumerate().map(|(i, x)| (Step::Index(i), x))), + Value::Object(o) => Box::new(o.iter().map(|(k, x)| (Step::Name(k.as_str()), x))), + _ => continue, + }; + for (step, child) in children { + steps.push((entry, step)); + todo.push((child, depth + 1, steps.len())); + } + } + None +} + +/// Estimated bytes of `d`. +fn data_size(d: &Data) -> u64 { + match d { + Data::Undefined | Data::Null | Data::Bool(_) => 4, + Data::Number(_) => 8, + Data::String(s) => s.len() as u64 + 2, + Data::Array(a) => 8 + a.iter().map(data_size).sum::(), + Data::Object(o) => 8 + o.iter().map(|(k, v)| k.len() as u64 + 2 + data_size(v)).sum::(), + } +} + +/// Brings each open document's next id up to the highest one the session has given out for it. +fn raise_ids(s: &mut Session) { + let marks = std::mem::take(&mut s.script_high_water); + for st in &mut s.docs { + if let Some(&mark) = marks.get(&st.uid) + && mark > st.doc.peek_next_id() + { + st.change_unsaved(|d| Arc::make_mut(d).raise_next_id(mark)); + } + } + s.script_high_water = marks; +} + +/// Every object in `d`: all its art ([`crate::Document::art_roots`]), opacity masks included. +fn all_objects(d: &crate::Document) -> u64 { + d.art_roots().map(|n| n.count_with_masks() as u64).sum() +} + +fn note_ids(s: &mut Session) { + for st in &s.docs { + let mark = s.script_high_water.entry(st.uid).or_insert(0); + *mark = (*mark).max(st.doc.peek_next_id()); + } +} + +/// Runs command `id` inside a slice. A command that fails puts everything back it had done. +/// → its result, the objects it added, the bytes of document data it added and the state before +/// it, for a result that cannot cross to the script. +fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { + raise_ids(s); + let mutating = waits_for_tool_edit(id); + let save = mutating.then(|| Savepoint::take(s, id)); + let before: Vec<(u64, Arc, u64)> = + if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; + crate::file_access::start_recording_writes(); + let r = s.execute(id, params); + // A file a command wrote before it failed is on disk all the same. + let mut written = host.written.borrow_mut(); + for path in crate::file_access::finish_recording_writes(r.is_ok()) { + if !written.contains(&path) { + written.push(path); + } + } + drop(written); + match r { + Ok(v) => { + note_ids(s); + let (mut objects, mut bytes) = (0, 0); + for st in &s.docs { + match before.iter().find(|(uid, ..)| *uid == st.uid) { + Some((_, d, ids)) if !Arc::ptr_eq(d, &st.doc) => { + objects += st.doc.peek_next_id().saturating_sub(*ids); + bytes += d.retained_bytes_each(&st.doc).1 as u64; + } + Some(_) => {} + // A document the command opened or made counts whole. + None if mutating => { + objects += all_objects(&st.doc); + bytes += crate::Document::new(1.0, 1.0).retained_bytes_each(&st.doc).1 as u64; + } + None => {} + } + } + Ok((v, objects, bytes, save)) + } + Err(e) => { + if let Some(save) = save + && !save.restore(s) + { + return Err(EngineError::Internal { cmd: id.to_string(), msg: HISTORY_LOST.to_string() }); + } + Err(e) + } + } +} + +fn vc_run(host: &Rc, args: Vec) -> std::result::Result { + let Some(Data::String(id)) = args.first() else { return Err(HostError::Type(NO_COMMAND_ID.to_string())) }; + if args.len() > 2 { + return Err(HostError::Type(TOO_MANY_ARGUMENTS.to_string())); + } + let id = id.clone(); + let params = match args.get(1) { + None | Some(Data::Undefined) => json!({}), + Some(d @ Data::Object(_)) => to_json(d), + Some(_) => return Err(HostError::Type(PARAMS_NOT_OBJECT.to_string())), + }; + let bytes = args.iter().map(data_size).sum(); + host.charge_call(bytes)?; + let session = host.session.clone(); + let r = { + let mut s = session.borrow_mut(); + step(&mut s, host, &id, ¶ms) + }; + let (value, objects, added, save) = match r { + Ok(done) => done, + // A bug is not something a script can handle, and neither is a request to stop. + Err(e @ EngineError::Internal { .. }) => return Err(HostError::Abort(e.to_string())), + Err(EngineError::Cancelled) => return Err(HostError::Abort("canceled".into())), + Err(e) => return Err(HostError::Error(e.to_string())), + }; + let crossed = host.charge_growth(objects, added).and_then(|()| { + let data = to_data(&value, &result_limits(), 0, &mut (0, 0)) + .map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?; + host.charge_call(data_size(&data))?; + Ok(data) + }); + // A command whose result does not reach the script is put back, like one that failed. + if let Some(save) = save { + let mut s = session.borrow_mut(); + if crossed.is_ok() { + save.keep(&mut s); + } else if !save.restore(&mut s) { + return Err(HostError::Abort(HISTORY_LOST.to_string())); + } + } + crossed +} + +/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits +/// of a crossing throws a `RangeError`. +fn vc_document(host: &Host) -> std::result::Result { + let s = host.session.borrow(); + let Some(st) = s.active() else { return Ok(Data::Null) }; + let ids: Vec = st.selection.objects.iter().take(1_000).map(|i| i.0).collect(); + let v = json!({ + "name": st.title(), + "path": st.path, + "modified": st.is_dirty(), + "artboards": st.doc.artboards.len(), + "layers": st.doc.layers.len(), + "selection": ids, + "selectionCount": st.selection.objects.len(), + }); + to_data(&v, &DataLimits::default(), 0, &mut (0, 0)).map_err(|place| HostError::Range(format!("vc.document{place} is too large for a script"))) +} + +/// Every command a script may run: its id, label and parameters. +fn vc_commands() -> Data { + Data::Array( + command_specs() + .iter() + .filter(|c| !refused_to_scripts(c.id)) + .map(|c| { + Data::Object(vec![ + ("id".into(), Data::String(c.id.into())), + ("label".into(), Data::String(c.label.into())), + ("params".into(), Data::String(c.params.into())), + ]) + }) + .collect(), + ) +} + +fn vc_log(host: &Host, args: Vec) -> std::result::Result { + let entry = args.first().unwrap_or(&Data::Undefined); + let bytes = data_size(entry) as usize; + if host.log.borrow().len() >= MAX_LOG_LINES || host.log_bytes.get().saturating_add(bytes) > MAX_LOG_BYTES { + return Err(HostError::Range(LOG_FULL.to_string())); + } + host.log_bytes.set(host.log_bytes.get() + bytes); + host.log.borrow_mut().push(to_json(entry)); + Ok(Data::Undefined) +} + +fn function(f: impl Fn(Vec) -> std::result::Result + 'static) -> HostFunction { + Rc::new(f) +} + +fn vc_object(host: &Rc, args: Data) -> Vec<(String, HostItem)> { + let run = { + let h = host.clone(); + function(move |a| vc_run(&h, a)) + }; + let document = { + let h = host.clone(); + function(move |_| { + h.charge_call(64)?; + vc_document(&h) + }) + }; + let commands = { + let h = host.clone(); + let list = Rc::new(vc_commands()); + let size = data_size(&list); + function(move |_| { + h.charge_call(size)?; + Ok((*list).clone()) + }) + }; + let log = { + let h = host.clone(); + function(move |a| { + h.charge_call(data_size(a.first().unwrap_or(&Data::Undefined)))?; + vc_log(&h, a) + }) + }; + let has = function(|a| Ok(Data::Bool(matches!(a.first(), Some(Data::String(f)) if API_FEATURES.contains(&f.as_str()))))); + vec![ + ("run".into(), HostItem::Function(run)), + ("document".into(), HostItem::Getter(document)), + ("commands".into(), HostItem::Getter(commands)), + ("log".into(), HostItem::Function(log)), + ("args".into(), HostItem::Value(args)), + ( + "api".into(), + HostItem::Object(vec![("version".into(), HostItem::Value(Data::String(API_VERSION.into()))), ("has".into(), HostItem::Function(has))]), + ), + ] +} + +/// A plain-words kind of a run's failure, as the report gives it. +fn kind_id(kind: &RunErrorKind) -> &'static str { + match kind { + RunErrorKind::Syntax => "syntax", + RunErrorKind::Thrown => "thrown", + RunErrorKind::Limit(LimitKind::Interrupted) => "stopped", + RunErrorKind::Limit(_) => "limit", + RunErrorKind::Internal => "internal", + } +} + +/// `message`, with what to do about a failure that comes from a script written for another program. +fn explained(kind: &RunErrorKind, message: &str, source: &str, line: u32) -> String { + const HOST_OBJECTS: &[&str] = + &["app", "$", "alert", "confirm", "prompt", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"]; + let names_host_object = + message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); + let directive = + *kind == RunErrorKind::Syntax && line > 0 && source.lines().nth(line as usize - 1).is_some_and(|l| l.trim_start().starts_with('#')); + if *kind == RunErrorKind::Thrown && names_host_object { + format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") + } else if directive { + format!("{message} (preprocessor lines such as `#target` and `#include` are not read yet)") + } else { + message.to_string() + } +} + +impl Session { + /// Is a script running? While one is, the commands that change anything are refused. + pub fn script_running(&self) -> bool { + self.script_key.is_some() + } + + /// The flag that stops the script running in this session from any thread, at its next + /// instruction. + pub fn script_interrupt(&self) -> Interrupt { + self.script_stop.clone() + } + + /// The report of the run that ended last (`script.run`'s result, or its failure). + pub fn script_report(&self) -> Option<&Value> { + self.script_report.as_ref() + } + + /// The error text of the last run when it failed: its name, place, message and kind, and the + /// files it left written. + pub fn script_failure_text(&self) -> Option { + self.script_report.as_ref().filter(|r| r["ok"] == false).map(failure_text) + } + + /// Has the running script used up its growth allowance, so a person must answer? A run asked + /// to stop no longer waits: the next [`Session::script_pump`] ends it. + pub fn script_waiting(&self) -> bool { + !self.script_stop.is_set() && self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.waiting.get())).unwrap_or(false) + } + + /// The name of the running script. + pub fn script_name(&self) -> Option { + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.name.clone())) + } + + /// Lets the run go past its growth allowance by one more allowance. + pub fn script_continue(&mut self) { + if let Some(k) = &self.script_key { + with_job(k, |j| { + let h = &j.host; + if h.waiting.replace(false) { + h.continues.set(h.continues.get() + 1); + h.allowance_objects.set(h.allowance_objects.get().saturating_add(growth_objects())); + h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(GROWTH_BYTES)); + } + }); + } + } + + /// Asks the running script to stop; it is rolled back at the next slice. False with none running. + pub fn script_request_stop(&mut self) -> bool { + if self.script_key.is_none() { + return false; + } + self.script_stop.set(); + true + } + + /// Stops the running script at once and puts everything back, with the report of a stopped run + /// ([`Self::script_report`]). False with none running. + pub fn script_abandon(&mut self) -> bool { + let Some(key) = self.script_key.take() else { return false }; + let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else { + drop(key); + raise_ids(self); + self.script_stop.clear(); + self.reset_tool(); + cmd::compositefonts::sync(self); + return true; + }; + drop(key); + let kind = LimitKind::Interrupted; + let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; + let _ = self.script_failed(job, &e); + true + } + + /// A script can't start while a document holds a drag in progress or an undo group, which its + /// one undo step could not take in. + fn settle_for_script(&mut self) -> Result<()> { + self.finish_tool_edit_later()?; + if self.active().is_some() { + cmd::settle_interaction(self)?; + } + if self.explicit_undo_group.is_some() || self.docs.iter().any(|d| d.undo_group.is_some() || d.interaction.is_some()) { + return Err(EngineError::Other(OPEN_EDIT.to_string())); + } + Ok(()) + } + + /// Begins a run of `request`. + pub(crate) fn script_start(&mut self, request: Request) -> Result<()> { + self.settle_for_script()?; + // In a build where a fault ends the program, every unsaved document has a copy first. + if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { + return Err(EngineError::Other(NO_RECOVERY_COPY.to_string())); + } + self.reset_tool(); + let open: Vec = self.docs.iter().map(|d| d.uid).collect(); + self.script_high_water.retain(|uid, _| open.contains(uid)); + self.script_stop.clear(); + self.script_report = None; + let limits = Limits { fuel: request.fuel, heap_bytes: HEAP_BYTES, ..Limits::default() }; + let options = Options { max_source_units: MAX_SOURCE_BYTES.saturating_mul(2), ..Options::default() }; + let mut realm = Realm::with_options(options, limits); + realm.share_interrupt(&self.script_stop); + realm.set_data_limits(DataLimits::default()); + let host = Rc::new(Host { + session: Rc::new(RefCell::new(Session::new())), + pause: realm.pause_flag(), + framed: self.script_frames, + calls: Cell::new(0), + calls_this_slice: Cell::new(0), + objects: Cell::new(0), + bytes_kept: Cell::new(0), + bridge: Cell::new(0), + allowance_objects: Cell::new(growth_objects()), + allowance_bytes: Cell::new(GROWTH_BYTES), + continues: Cell::new(0), + waiting: Cell::new(false), + log: RefCell::new(Vec::new()), + log_bytes: Cell::new(0), + written: RefCell::new(Vec::new()), + }); + let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) + .map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?; + let started = realm.define_host_object("vc", vc_object(&host, args)).and_then(|()| realm.start(&request.source)); + if let Err(e) = started { + let report = failure_report(&request.name, &e, &request.source, &host, 0); + let message = failure_text(&report); + self.script_report = Some(report); + return Err(EngineError::Other(message)); + } + let scope = crate::file_access::ScopeHandle::capture(); + let job = Job { realm, host, world: World::working(self), start_uids: open, name: request.name, scope }; + let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + JOBS.with(|jobs| jobs.borrow_mut().insert(id, job)); + self.script_key = Some(JobKey(id)); + Ok(()) + } + + /// Advances the running script by one slice. `None` while it is still running; otherwise the + /// run has ended: its report, or the error that ended it, with the documents put back. + pub fn script_pump(&mut self) -> Option> { + let key = self.script_key.take()?; + let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else { + return Some(Err(EngineError::Other(JOB_GONE.to_string()))); + }; + if job.host.waiting.get() && !self.script_stop.is_set() { + JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job)); + self.script_key = Some(key); + return None; + } + if vectorcraft_doc::cancel::check().is_err() { + self.script_stop.set(); + } + job.host.calls_this_slice.set(0); + let outcome = run_slice(self, &mut job); + match outcome { + Err(panic) => { + let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0 }; + Some(self.script_failed(job, &e)) + } + Ok(Err(e)) => Some(self.script_failed(job, &e)), + Ok(Ok(Progress::Paused)) => { + JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job)); + self.script_key = Some(key); + None + } + Ok(Ok(Progress::Done(_))) => { + let r = self.script_commit(job); + self.trim_histories(); + Some(r) + } + } + } + + fn script_failed(&mut self, job: Job, e: &RunError) -> Result { + let report = failure_report(&job.name, e, "", &job.host, job.realm.fuel_left()); + drop(job); + raise_ids(self); + self.script_stop.clear(); + self.reset_tool(); + cmd::compositefonts::sync(self); + let message = failure_text(&report); + self.script_report = Some(report); + Err(EngineError::Other(message)) + } + + /// Makes the working copy the session's state: one undo step for each document whose art + /// changed, nothing for the others. + fn script_commit(&mut self, mut job: Job) -> Result { + // The working copy goes into the session; `job.world` holds the state before the run. + job.world.swap(self); + self.prefs = merged_prefs(&job.world.start_prefs, &self.prefs, &job.world.choices.prefs); + // The Caps Lock state takes the run's value only when the run changed it. + if self.caps_lock == job.world.start_caps_lock { + self.caps_lock = job.world.choices.caps_lock; + } + note_ids(self); + raise_ids(self); + let mut start = std::mem::take(&mut job.world.docs); + for st in &self.docs { + let changed = start.iter().find(|b| b.uid == st.uid).is_none_or(|b| !st.same_content(&b.doc)); + if changed && (!crate::sanity::doc_sane(&st.doc, &st.selection) || st.doc.too_deep(None)) { + job.world.docs = start; + job.world.swap(self); + let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0 }; + return self.script_failed(job, &e); + } + } + let mut changed_names = Vec::new(); + for st in &mut self.docs { + let Some(b) = start.iter_mut().find(|b| b.uid == st.uid) else { + // A document the script opened or made starts with no undo steps. + st.history = crate::History { limit: st.history.limit, ..crate::History::default() }; + st.revision += 1; + changed_names.push(st.title()); + continue; + }; + let changed = !st.same_content(&b.doc); + st.history = std::mem::take(&mut b.history); + st.recovery.clone_from(&b.recovery); + if changed { + st.push_undo(STEP_LABEL.to_string(), b.doc.clone(), Arc::new(b.selection.clone())); + changed_names.push(st.title()); + } + if changed || st.revision != b.revision { + st.revision = st.revision.max(b.revision) + 1; + } + st.sync_new_art(); + } + // A document a frontend opened while the run went on stays open. + for st in start.iter().filter(|b| !job.start_uids.contains(&b.uid)) { + self.docs.push(st.clone()); + } + // A document the script closed is gone now, with its recovery copy. + for b in start.iter().filter(|b| job.start_uids.contains(&b.uid) && !self.docs.iter().any(|d| d.uid == b.uid)) { + cmd::recovery::forget_closed(self, b); + } + // A document the script saved has nothing left to recover. + cmd::recovery::forget_clean(self); + let entries: Vec<_> = self.journal.iter().cloned().collect(); + self.journal = std::mem::take(&mut job.world.journal); + for (id, p) in entries { + self.journal.push((id, p)); + } + self.script_stop.clear(); + self.reset_tool(); + cmd::compositefonts::sync(self); + let host = &job.host; + let report = json!({ + "ok": true, + "name": job.name, + "changed": changed_names, + "written": *host.written.borrow(), + "log": *host.log.borrow(), + "fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(), + "hostCalls": host.calls.get(), + }); + self.script_report = Some(report.clone()); + Ok(report) + } + + /// Runs the running script until it ends. + pub(crate) fn script_run_to_end(&mut self) -> Result { + loop { + if let Some(result) = self.script_pump() { + return result; + } + if self.script_waiting() { + self.script_stop.set(); + } + } + } +} + +const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; +const INVALID_RESULT: &str = "the script left a document that cannot be kept"; +const JOB_GONE: &str = "the script's run is no longer available"; +const HISTORY_LOST: &str = "a failed command changed undo steps that could not be put back, so the script was stopped"; +// Text a script reads from the errors it catches, or that ends its run with its name and place. +const OVER_CALLS: &str = "the script made more host calls than one run may make"; +const OVER_BRIDGE: &str = "the script passed more data to and from commands than one run may pass"; +const OVER_GROWTH: &str = "the script added more objects and data to the documents than one run may add"; +const NO_COMMAND_ID: &str = "vc.run: give a command id, as a string"; +const TOO_MANY_ARGUMENTS: &str = "vc.run: takes a command id and an object of parameters"; +const PARAMS_NOT_OBJECT: &str = "vc.run: the parameters must be an object"; +const LOG_FULL: &str = "vc.log: the log of this run is full"; +const NO_RECOVERY_COPY: &str = "a recovery copy could not be written, so the script was not run"; + +/// The report of a run that failed. +fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left: u64) -> Value { + json!({ + "ok": false, + "kind": kind_id(&e.kind), + "message": explained(&e.kind, &e.message, source, e.line), + "name": name, + "line": e.line, + "column": e.column, + "written": *host.written.borrow(), + "log": *host.log.borrow(), + "fuelLeft": fuel_left, + }) +} + +/// The text of a failed run's error. +fn failure_text(report: &Value) -> String { + let s = |k: &str| report[k].as_str().unwrap_or_default(); + let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); + let at = if line > 0 { format!(" line {line}, column {column}") } else { String::new() }; + let written = report["written"].as_array().map_or(0, Vec::len); + let kept = if written > 0 { + let paths: Vec<&str> = report["written"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + format!(" (these files stay written: {})", paths.join(", ")) + } else { + String::new() + }; + format!("{}:{at}: {} ({}){kept}", s("name"), s("message"), s("kind")) +} + +/// A run's slice: the working copy in, the real session lent to the host functions, one measured +/// slice run in the file-access scope the run began in, and everything back. A panic in the +/// interpreter is the outer `Err`. +fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result, String> { + let depth = std::mem::replace(&mut s.depth, 0); + job.world.swap(s); + s.script_in_run = true; + let cell = job.host.session.clone(); + std::mem::swap(s, &mut *cell.borrow_mut()); + let scope = job.scope.clone(); + let realm = &mut job.realm; + let r = scope.run(|| { + guard::catch_panic(|| { + #[cfg(test)] + if PANIC_IN_SLICE.with(Cell::get) { + panic!("a slice failed"); + } + realm.advance(SLICE_FUEL) + }) + }); + std::mem::swap(s, &mut *cell.borrow_mut()); + s.script_in_run = false; + job.world.swap(s); + s.depth = depth; + r +} + +/// The objects a run may add before it is asked to continue or stop. +fn growth_objects() -> u64 { + #[cfg(test)] + if let Some(n) = TEST_GROWTH.with(Cell::get) { + return n; + } + GROWTH_OBJECTS +} + +/// The limits of a command's result on its way to the script. +fn result_limits() -> DataLimits { + #[cfg(test)] + if let Some(bytes) = TEST_RESULT_BYTES.with(Cell::get) { + return DataLimits { bytes, ..DataLimits::default() }; + } + DataLimits::default() +} + +#[cfg(test)] +thread_local! { + /// Tests: the bytes a command's result may hold on its way to the script. + pub(crate) static TEST_RESULT_BYTES: Cell> = const { Cell::new(None) }; + /// Tests: makes the next slice panic. + pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; + /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. + pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 208088a4cd..54d84507c5 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -44,6 +44,8 @@ impl Session { fill_active: true, clipboard: Clipboard::default(), journal: Journal::default(), + history_budget: crate::default_history_budget(), + histories_seen: None, tool: vectorcraft_tools::create("selection"), lender: None, held_input: Default::default(), @@ -82,6 +84,7 @@ impl Session { pdf_preset_dir: None, dictionary_file: None, profile_dir: None, + color_settings_file: None, plugin_dir: None, ignored_plugin_grants: Default::default(), plugin_output: None, @@ -129,6 +132,13 @@ impl Session { link_scan: None, global_edit_options: Default::default(), keyboard_text: false, + script_key: None, + script_stop: vectorcraft_js::Interrupt::new(), + script_report: None, + script_frames: false, + script_high_water: Default::default(), + script_in_run: false, + script_copy_first: cfg!(target_arch = "wasm32"), } } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 7c72da22db..1762c96765 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -7,6 +7,9 @@ impl Session { /// Run `f` on a mutable copy of the active document. Outside an interaction this records one /// undo step labelled `label`; inside one it just mutates (the interaction commits later). pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result) -> Result { + if self.script_running() { + return Err(EngineError::Busy); + } // An edit made while typing (the Transform panel) is a step of its own: inside the typing // session, the next keystroke's preview would start again from before it (#1881). if !self.previewing && cmd::typing_in_progress(self) { @@ -109,7 +112,7 @@ impl Session { }, Err(e) => Err(e), }; - match result { + let r = match result { Ok(v) => { st.selection.prune(&st.doc); // An edit that selects what it unlocks, shows or pastes leaves locked guides out, @@ -150,7 +153,12 @@ impl Session { cmd::globaledit::follow_history(st); Err(e) } + }; + // An edit a frontend makes itself, outside a command, keeps to the shared budget too. + if r.is_ok() && self.depth == 0 && !self.in_tool_actions { + self.trim_histories(); } + r } /// [`Session::edit`] with the step named `template`, its `{name}` placeholder filled with `name` @@ -225,6 +233,9 @@ impl Session { } pub fn begin_interaction(&mut self, label: &str) -> Result<()> { + if self.script_running() { + return Err(EngineError::Busy); + } // Typing in progress is kept first: a drag or a dialog's preview would otherwise start // from the snapshot taken before the typing, and drop it (#1881). if label != "Typing" && cmd::typing_in_progress(self) { @@ -262,6 +273,9 @@ impl Session { /// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview). pub fn preview(&mut self, cmd: &str, params: &Value) -> Result { + if self.script_running() { + return Err(EngineError::Busy); + } let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; @@ -385,6 +399,9 @@ impl Session { let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs()); self.journal.push(preview); self.journal_in_undo_groups(doc, &grouped, journal); + if self.depth == 0 { + self.trim_histories(); + } Ok(()) } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 1a60c21019..34c4eed727 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -39,6 +39,14 @@ impl Session { /// Execute a command by id. This is THE entry point for every frontend. pub fn execute(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?; + // A clipboard import is a query that replaces the clipboard, which the end of a run sets too. + if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { + return Err(EngineError::Busy); + } + // A step of a batch a script runs is held to the same rule as the script's own commands. + if self.script_in_run && crate::script::refused_to_scripts(id) { + return Err(EngineError::Other(crate::script::refused_text(id))); + } // An edit the active tool is computing on another thread (a Shape Builder merge) is // applied before a command that may edit, select, save or give a document a new revision, // as the click came first. Queries that only read do not wait for it. @@ -60,6 +68,11 @@ impl Session { if !self.replaying { self.check_params(id, params)?; } + // A command with a parameter schema runs only with params that pass it, and with the + // defaults of omitted values filled in; the journal keeps the params as given. Saved steps + // keep their keys the schema doesn't name, as above. + let checked = crate::schemas::check(spec, params, self.replaying)?; + let run_params = checked.as_ref().unwrap_or(params); // Objects given as `id` (where it stands for `ids` of one) or as `ids` beside it are checked // before anything else: a malformed one, or one naming no object, is an error under this // command's id, never the selection in its place. `effect.apply {id: "stylize.dropShadow"}` @@ -126,7 +139,7 @@ impl Session { if let Some(ids) = &select_first { s.execute("select.set", &serde_json::json!({ "ids": ids }))?; } - let r = cmd::run_spec(s, spec, params); + let r = cmd::run_spec(s, spec, run_params); if r.is_err() && let Some((uid, selection, layer)) = selected_before && let Some(st) = s.docs.iter_mut().find(|d| d.uid == uid) @@ -187,6 +200,7 @@ impl Session { } if self.depth == 0 { self.journal_in_undo_groups(doc, &grouped, journal); + self.trim_histories(); self.after_command(Some(id)); } else if matches!(id, "edit.undo" | "edit.redo") { // A step of `command.batch`: the tool hears of it as it does of the command alone. @@ -297,8 +311,13 @@ impl Session { /// document goes back to how it was before the command (its art, selection, interaction and /// undo history), and the same document stays active, instead of crashing the frontend. pub(crate) fn run_guarded(&mut self, id: &str, f: impl FnOnce(&mut Self) -> Result) -> Result { - let snapshot: Vec<_> = - self.docs.iter().map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.interaction.clone(), d.history.clone())).collect(); + // In a script's run a panic ends the run, and the run's rollback puts the histories back. + let in_run = self.script_in_run; + let snapshot: Vec<_> = self + .docs + .iter() + .map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.interaction.clone(), (!in_run).then(|| d.history.clone()))) + .collect(); let active = self.active().map(|d| d.uid); let r = match guard::catch_panic(|| self.run_nested(f)) { Ok(r) => r, @@ -311,7 +330,9 @@ impl Session { st.doc = doc; st.selection = selection; st.interaction = interaction; - st.history = history; + if let Some(history) = history { + st.history = history; + } cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); st.revision += 1; diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index 58fd90579b..d06934926c 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -160,6 +160,10 @@ impl Session { *n -= below(*n); } } + // The shared budget, which waits while an undo group is open, applies again once none is. + if self.depth == 0 { + self.trim_histories(); + } } /// When journal entry `n` is a `command.batch` with `steps` noted in canceled undo groups and diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index ae98bdf4fa..f6fe8ff5bc 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -11,6 +11,9 @@ //! * **ICC profiles**: the bytes of each profile `color.loadProfile` registered, as `.icc` files //! named after the profile, never the path they came from (a profile in a system folder may //! move or go away). Attaching the folder registers them again. +//! * **Color Settings**: the working spaces, intent and black point compensation +//! `edit.colorSettings` sets, as one JSON file (#6335). Attaching it, after the profiles, makes +//! them the active settings again. //! * **Plug-ins**: the module of each plug-in `plugin.install` installs, as a `.wasm` file named //! after its id (as Illustrator keeps plug-ins in its Plug-ins folder); `plugin.remove` deletes it. //! Attaching the folder installs them again, except in Safe Mode and except the ones the user @@ -293,6 +296,31 @@ impl Session { } } + /// Keep Edit › Color Settings (the working spaces, intent and black point compensation) in the + /// file `path`, and make the settings saved there the active ones (#6335). After + /// [`Session::attach_profile_store`]: they may name a profile it registers. Settings that can't be + /// read, or that name a profile that is gone, leave the defaults with a log record, and the file + /// as it is until the settings change. + pub fn attach_color_settings(&mut self, path: PathBuf) { + if path.exists() { + let restored = read_capped(&path, MAX_PRESET_FILE) + .and_then(|bytes| serde_json::from_slice::(&bytes).map_err(|e| e.to_string())) + .and_then(|settings| vectorcraft_color::cms::set_active(&settings).map_err(|e| e.to_string())); + if let Err(e) = restored { + log::warn!("not using the saved color settings {}: {e}", path.display()); + } + } + self.color_settings_file = Some(path); + } + + /// Write `settings` to the file [`Session::attach_color_settings`] named; `false` when they + /// didn't go there. + pub(crate) fn store_color_settings(&self, settings: &vectorcraft_color::cms::ColorSettings) -> bool { + let Some(path) = &self.color_settings_file else { return false }; + let (Some(dir), Some(file)) = (path.parent(), path.file_name().and_then(|f| f.to_str())) else { return false }; + serde_json::to_vec_pretty(settings).is_ok_and(|bytes| put(dir, file, &bytes)) + } + /// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there /// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). pub fn attach_plugin_store(&mut self, dir: PathBuf) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 000741d5d2..f6e32d719e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -149,6 +149,7 @@ mod repeat_edit; mod save; mod saveoptions; mod scalestrokes; +mod script_run; mod scripts; mod select_ids_first; mod shaper; @@ -186,6 +187,7 @@ mod transformfx; mod transparencygrid; mod trap; mod typearea; +mod typeglyphbounds; mod typescale; mod typeundo; mod units; diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index f5ac96d509..e98593bfc8 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -104,7 +104,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { let list = run(&mut s, "brush.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); let ids: Vec<&str> = libs.iter().map(|l| l["id"].as_str().unwrap()).collect(); - assert_eq!(ids, ["art-ribbons", "calligraphic-nibs", "pattern-borders", "scatter-shapes"]); + assert_eq!(ids, ["art-ribbons", "calligraphic-nibs", "pattern-borders", "scatter-shapes", "game-trails"]); assert!(libs.iter().all(|l| l["category"] == "builtIn")); let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"})); assert_eq!( @@ -112,8 +112,20 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ["Notched Ribbon", "Double Line", "Wave", "Teardrop", "Striped Ribbon"] ); assert_eq!(libs[0]["count"].as_u64(), Some(5)); + let trails = run(&mut s, "brush.library", json!({"library": "game-trails"})); + assert_eq!( + trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), + ["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"] + ); + assert_eq!(libs[4]["count"].as_u64(), Some(4)); // One kind of brush per library, every brush drawing something. - for (id, kind) in [("art-ribbons", "art"), ("calligraphic-nibs", "calligraphic"), ("pattern-borders", "pattern"), ("scatter-shapes", "scatter")] { + for (id, kind) in [ + ("art-ribbons", "art"), + ("calligraphic-nibs", "calligraphic"), + ("pattern-borders", "pattern"), + ("scatter-shapes", "scatter"), + ("game-trails", "art"), + ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); for b in &lib.brushes { diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 467dd40524..3ed51e3c38 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -823,6 +823,13 @@ fn shape_builder_applies_a_merge_before_what_comes_next() { // No files: the command fails after the merge. assert!(s.execute("text.addFontFiles", &json!({"files": []})).is_err()); }), + ("a call its schema refuses", |s, _, _| { + // The refused call adds no undo step of its own: the merge's is the last one. + let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": 0})).unwrap_err().to_string(); + assert!(e.contains("`zoom`"), "{e}"); + assert!(s.doc().unwrap().doc.views.is_empty()); + assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Shape Builder")); + }), ]; let _proof = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let dir = vectorcraft_testkit::temp_dir("shape-builder-merge-first"); @@ -3577,6 +3584,37 @@ fn a_trace_run_hands_its_trace_to_the_command() { assert!((bb.center().x - 160.0).abs() < 1.5, "traced where the image is now: {bb:?}"); } +/// A plug-in run that calls Image Trace and then fails leaves a trace handed in for the command in +/// place, as it leaves the document. +#[test] +fn a_failed_plugin_run_keeps_a_handed_in_trace() { + use vectorcraft_plugins::wat as tpl; + let (id, cmd, args) = ("test.engine.calltrace", "imageTrace.make", r#"{"params":{"ignoreWhite":true}}"#); + let mut s = session(); + s.allow_plugin_grants_from_requests(); + image_doc(&mut s); + let p: Value = serde_json::from_str(args).unwrap(); + let run = cmd::TraceRun::prepare(&s, cmd, &p).unwrap(); + run.run(&|_, _| true).unwrap().hand_in(&mut s); + let grant = json!(["doc.read", "doc.write", "commands"]); + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["{cmd}"]}}"#); + let imports = format!( + r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (data (i32.const 0x2000) "{}") (data (i32.const 0x2100) "{}")"#, + tpl::string(cmd), + tpl::string(args) + ); + let first = + format!("(drop (call $vc_call (i32.const 0x2000) (i32.const {}) (i32.const 0x2100) (i32.const {}))) unreachable", cmd.len(), args.len()); + let wasm = wat::parse_str(tpl::with_imports(&manifest, &imports, &first, "{}")).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + assert!(s.execute("plugin.run", &json!({"id": id, "ids": []})).is_err()); + assert!(s.trace_hand_off.is_some(), "the trace is still handed in"); + assert!(s.execute(cmd, &p).is_ok()); + assert!(s.trace_hand_off.is_none(), "taken"); + s.execute("plugin.remove", &json!({"id": id})).unwrap(); +} + #[test] fn image_trace_ignore_background_keeps_the_color_inside_the_art() { // A black field, a light panel on it and a black ring on the panel. diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 205c7ea71b..3b8ba92db8 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2706,19 +2706,15 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() { assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1), (0, 2)].into()); s.execute("edit.copy", &json!({})).unwrap(); assert_eq!(pasted(&mut s), [2]); - // Cut takes the segment between them. The two surviving runs of an ordinary path - // become independent objects, and this path keeps the first run (#3380). + // Cut takes the two anchors out of the path, as Clear does (#6361): each side keeps one + // anchor, which makes no path, so nothing is left. s.execute("edit.undo", &json!({})).unwrap(); let original = path(&s, id); let picked = s.doc().unwrap().selection.clone(); s.execute("edit.cut", &json!({})).unwrap(); let left = paths(&s); - assert_eq!(left.len(), 2); - assert_eq!(left[0].0, id); - assert!(left.iter().all(|(_, p)| p.subpaths.len() == 1 && !p.subpaths[0].closed)); - assert_eq!(left[0].1.subpaths[0].anchors, original.subpaths[0].anchors[..2]); - assert_eq!(left[1].1.subpaths[0].anchors, original.subpaths[0].anchors[2..]); - assert_eq!(s.doc().unwrap().selection.objects, left.iter().map(|(id, _)| *id).collect::>()); + assert!(left.is_empty()); + assert!(s.doc().unwrap().selection.objects.is_empty()); assert_eq!(s.clipboard.nodes.len(), 1); assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors[1..3]); s.execute("edit.undo", &json!({})).unwrap(); diff --git a/crates/engine/src/tests/editcolors.rs b/crates/engine/src/tests/editcolors.rs index bfd57a7aac..49307845fd 100644 --- a/crates/engine/src/tests/editcolors.rs +++ b/crates/engine/src/tests/editcolors.rs @@ -342,7 +342,12 @@ fn pixels(s: &Session, id: NodeId) -> Vec<[u8; 4]> { /// A selected embedded 2×2 image. fn image_node(s: &mut Session) -> NodeId { - let bytes = png([[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 128]]); + image_of(s, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 128]]) +} + +/// A selected embedded 2×2 image of the pixels `px`. +fn image_of(s: &mut Session, px: [[u8; 4]; 4]) -> NodeId { + let bytes = png(px); s.edit("Place", |d, sel| { d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(bytes)); let id = d.alloc_id(); @@ -383,6 +388,85 @@ fn invert_recolours_an_embedded_image() { assert_eq!(pixels(&s, id)[..2], [[0, 0, 0, 255], [0, 255, 0, 255]]); } +/// The key of image object `id`'s blob. +fn image_key(s: &Session, id: NodeId) -> String { + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not an image") }; + im.key.clone() +} + +/// Convert to Grayscale stores an image with one color channel, alpha kept (#5632). +#[test] +fn convert_to_grayscale_stores_an_image_as_grayscale() { + let mut s = session(); + let id = image_node(&mut s); + let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap(); + assert_eq!(r["changed"], 1); + let key = image_key(&s, id); + let source = s.doc().unwrap().doc.images[&key].gray_source(); + assert!(source.is_some_and(|g| g.alpha && !g.one_bit), "a grayscale file with alpha: {source:?}"); + let gray = |hex: &str| Color::from_hex(hex).unwrap().in_model(vectorcraft_color::cms::Model::Gray).to_rgba8(1.0)[0]; + let (r_, g_, b_, w) = (gray("#ff0000"), gray("#00ff00"), gray("#0000ff"), gray("#ffffff")); + assert_eq!(pixels(&s, id), [[r_, r_, r_, 255], [g_, g_, g_, 255], [b_, b_, b_, 255], [w, w, w, 128]]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(pixels(&s, id)[0], [255, 0, 0, 255], "one undo step restores the color image"); + s.execute("edit.redo", &json!({})).unwrap(); + // An image that is already grayscale has nothing to convert. + let again = s.execute("edit.colors.toGrayscale", &json!({})).unwrap(); + assert_eq!(again["changed"], 0); + assert_eq!(image_key(&s, id), key); +} + +/// An RGB image whose pixels are all neutral still becomes a one-channel image (#5632). +#[test] +fn convert_to_grayscale_stores_a_neutral_rgb_image_as_grayscale() { + let mut s = session(); + let id = image_of(&mut s, [[255, 255, 255, 255], [0, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]]); + let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap(); + assert_eq!(r["changed"], 1); + let source = s.doc().unwrap().doc.images[&image_key(&s, id)].gray_source(); + assert!(source.is_some_and(|g| !g.alpha), "an opaque image has no alpha channel: {source:?}"); +} + +/// Select All leaves a hidden neutral RGB image out of Convert to Grayscale, which would change it. +#[test] +fn a_hidden_neutral_rgb_image_counts_as_not_converted() { + let mut s = session(); + let hidden = image_of(&mut s, [[255, 255, 255, 255], [0, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]]); + s.execute("layer.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap(); + rect(&mut s, json!("#ff0000")); + s.execute("select.all", &json!({})).unwrap(); + let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap(); + assert_eq!(r["notChanged"], json!({"locked": 0, "hidden": 1}), "{r}"); +} + +/// Adjust Colors converting to gray stores an image with one channel; without Convert it keeps +/// the image's RGB (#5632). +#[test] +fn adjust_colors_converting_to_gray_stores_an_image_as_grayscale() { + let source = |convert: bool| { + let mut s = session(); + let id = image_node(&mut s); + s.execute("edit.colors.adjustBalance", &json!({"mode": "gray", "gray": 10, "convert": convert})).unwrap(); + s.doc().unwrap().doc.images[&image_key(&s, id)].gray_source() + }; + assert!(source(true).is_some(), "converted to gray"); + assert!(source(false).is_none(), "the colors keep their model"); +} + +/// A PDF of a CMYK document writes an image Convert to Grayscale made with one channel (#5632). +#[test] +fn a_converted_image_is_written_to_pdf_as_gray_in_a_cmyk_document() { + let mut s = session(); + s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap(); + image_of(&mut s, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [10, 200, 30, 255]]); + s.execute("edit.colors.toGrayscale", &json!({})).unwrap(); + let opts = vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() }; + let pdf = String::from_utf8_lossy(&vectorcraft_pdf::export(&s.doc().unwrap().doc, &opts).unwrap()).into_owned(); + let image = pdf.split("/Subtype/Image").nth(1).or_else(|| pdf.split("/Subtype /Image").nth(1)).expect("an image in the PDF"); + let image = &image[..image.find("stream").unwrap_or(image.len())]; + assert!(image.contains("/DeviceGray") && !image.contains("/DeviceRGB"), "one color channel: {image}"); +} + /// "Dots": a red square tile; a selected rectangle filled with it. fn pattern_fill(s: &mut Session) -> NodeId { rect(s, json!("#ff0000")); diff --git a/crates/engine/src/tests/file.rs b/crates/engine/src/tests/file.rs index 1e3a4b9238..6467fe0912 100644 --- a/crates/engine/src/tests/file.rs +++ b/crates/engine/src/tests/file.rs @@ -447,6 +447,27 @@ fn export_selection_keeps_the_effects_in_the_crop() { } } +/// An Outer Glow at its default Screen mode on the bare page is in a PNG on white and in a JPEG, +/// and in a transparent PNG (#6125). +#[test] +fn a_screen_outer_glow_is_in_raster_exports() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.outerGlow"})).unwrap(); + let mut pixel = |p: serde_json::Value| { + let v = s.execute("document.export", &p).unwrap(); + let img = image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8(); + // 2 pt past the square's stroke, on the right. + *img.get_pixel(122, 110) + }; + for p in [json!({"format": "png", "background": "white"}), json!({"format": "jpg"})] { + let px = pixel(p.clone()); + assert!(px[0] > 235 && px[1] > 235 && px[2] < 235, "{p}: yellow on white: {px:?}"); + } + let px = pixel(json!({"format": "png", "background": "transparent"})); + assert!(px[3] > 0 && px[0] > 235 && px[1] > 235 && px[2] < 40, "the glow is yellow in the transparent image: {px:?}"); +} + /// A group's own drop shadow is inside the crop of the group's selection export too. #[test] fn export_selection_keeps_a_groups_shadow_in_the_crop() { diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index d21d9ec971..279020432d 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -10,6 +10,12 @@ use crate::*; /// A session with one document holding `n` rectangles, all selected. fn session_with_rects(n: usize) -> Session { let mut s = Session::new(); + open_with_rects(&mut s, n); + s +} + +/// Open a new document in `s` holding `n` rectangles, all selected. +fn open_with_rects(s: &mut Session, n: usize) { s.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap(); s.edit("Add", |d, _| { let layer = d.layers[0].id; @@ -22,7 +28,6 @@ fn session_with_rects(n: usize) -> Session { }) .unwrap(); s.execute("select.all", &json!({})).unwrap(); - s } fn first_x(s: &Session) -> f64 { @@ -75,6 +80,203 @@ fn within_the_budget_the_step_limit_still_counts() { assert!(st.history.bytes() < st.history.byte_budget); } +fn moves(s: &mut Session, n: usize) { + for _ in 0..n { + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + } +} + +fn undo_lens(s: &Session) -> Vec { + s.docs.iter().map(|d| d.history.undo.len()).collect() +} + +fn history_bytes(s: &Session) -> usize { + s.docs.iter().map(|d| d.history.bytes()).sum() +} + +#[test] +fn one_document_keeps_its_steps_within_the_session_budget() { + let mut s = session_with_rects(500); + moves(&mut s, 1); + let step = s.doc().unwrap().history.undo.last().unwrap().bytes; + s.history_budget = 3 * step; + moves(&mut s, 20); + let st = s.doc().unwrap(); + assert_eq!(st.history.undo.len(), History::MIN_STEPS, "only the last few steps are kept"); + assert_eq!(st.history.byte_budget, default_history_budget(), "the document's own budget is unchanged"); + // A lower budget applies at the next command, even one that adds no step. + s.history_budget = usize::MAX; + moves(&mut s, 4); + assert_eq!(s.doc().unwrap().history.undo.len(), History::MIN_STEPS + 4); + s.history_budget = 3 * step; + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), History::MIN_STEPS); +} + +#[test] +fn open_documents_share_one_budget_and_the_oldest_steps_go_first() { + let n = 300; + let mut s = session_with_rects(n); + moves(&mut s, 1); + let step = s.doc().unwrap().history.undo.last().unwrap().bytes; + // Room for about 22 moves in all the open documents together. + s.history_budget = 22 * step; + moves(&mut s, 11); + assert_eq!(undo_lens(&s), [13], "Add and 12 moves fit in the budget"); + open_with_rects(&mut s, n); + moves(&mut s, 12); + let lens = undo_lens(&s); + assert_eq!(lens[1], 13, "the newer document keeps all of its steps: {lens:?}"); + assert!((History::MIN_STEPS..13).contains(&lens[0]), "the older document's oldest steps went: {lens:?}"); + assert!(history_bytes(&s) <= s.history_budget, "{} bytes kept, budget {}", history_bytes(&s), s.history_budget); + // Closing the older document frees its share: the other keeps more steps than before. + assert!(s.close_document(0)); + assert!(s.set_active(0)); + moves(&mut s, 6); + assert_eq!(undo_lens(&s), [19], "Add and 18 moves fit in the budget alone"); +} + +#[test] +fn an_undo_group_lets_no_other_documents_steps_go_until_it_ends() { + let mut s = session_with_rects(50); + moves(&mut s, 12); + open_with_rects(&mut s, 50); + // The steps kept now fill the budget exactly. + s.history_budget = history_bytes(&s); + s.execute("select.all", &json!({})).unwrap(); + assert_eq!(undo_lens(&s), [13, 1]); + // A scrubbed field's edits in the second document, then canceled. + s.begin_undo_group(); + moves(&mut s, 3); + assert_eq!(undo_lens(&s), [13, 2], "the group's step waits for the group to end"); + s.end_undo_group(true); + assert_eq!(undo_lens(&s), [13, 1], "a canceled group leaves the other document's steps"); + // The same edits kept: the other document's oldest steps go. + s.begin_undo_group(); + moves(&mut s, 3); + s.end_undo_group(false); + let lens = undo_lens(&s); + assert_eq!(lens[1], 2); + assert!((History::MIN_STEPS..13).contains(&lens[0]), "the older document's oldest steps went: {lens:?}"); + assert!(history_bytes(&s) <= s.history_budget); + // A scrub through an undo scope: its step counts once the scope ends. + s.history_budget = usize::MAX; + assert!(s.set_active(0)); + moves(&mut s, 6); + assert!(s.set_active(1)); + s.history_budget = history_bytes(&s); + let before = undo_lens(&s)[0]; + let scope = s.begin_undo_scope().unwrap(); + moves(&mut s, 3); + assert_eq!(undo_lens(&s), [before, 3], "the scope's step waits for the scope to end"); + s.end_undo_scope(scope, false); + let lens = undo_lens(&s); + assert!(lens[0] < before, "the older document's oldest steps went once the scope ended: {lens:?}"); + assert!(history_bytes(&s) <= s.history_budget); +} + +#[test] +fn steps_kept_outside_a_command_keep_to_the_shared_budget() { + let mut s = session_with_rects(50); + moves(&mut s, 12); + open_with_rects(&mut s, 50); + assert_eq!(undo_lens(&s), [13, 1]); + // A drag the frontend commits itself. + s.begin_interaction("Move").unwrap(); + s.preview("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.history_budget = 1; + assert_eq!(undo_lens(&s), [13, 1]); + s.commit_interaction().unwrap(); + assert_eq!(undo_lens(&s), [History::MIN_STEPS, 2], "the drag's step counts against the other document's"); + // A script run across frames, whose step is kept after `script.run` returns. + s.history_budget = usize::MAX; + assert!(s.set_active(0)); + moves(&mut s, 4); + assert!(s.set_active(1)); + s.script_frames = true; + let source = "for (var i = 0; i < 3000000; i++) {} vc.run('object.move', {dx: 1, dy: 0});"; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap()["running"], true); + s.history_budget = 1; + let mut slices = 0; + let r = loop { + slices += 1; + assert!(slices < 100_000, "the script ends"); + if let Some(r) = s.script_pump() { + break r; + } + }; + assert_eq!(r.unwrap()["ok"], true); + assert_eq!(undo_lens(&s), [History::MIN_STEPS, 3], "the run's step counts against the other document's"); + // An edit a frontend makes itself, outside a command. + s.history_budget = usize::MAX; + assert!(s.set_active(0)); + moves(&mut s, 4); + assert!(s.set_active(1)); + s.history_budget = 1; + s.edit("Add", |d, _| { + let id = d.alloc_id(); + let r = shapes::rectangle(kurbo::Rect::new(0.0, 20.0, 10.0, 30.0)); + d.insert(Some(d.layers[0].id), usize::MAX, Node::path(id, r, Appearance::default_art()))?; + Ok(()) + }) + .unwrap(); + assert_eq!(undo_lens(&s), [History::MIN_STEPS, 4], "the edit's step counts against the other document's"); +} + +#[test] +fn each_document_keeps_its_last_steps_however_small_the_budget() { + let mut s = Session::new(); + // Smaller than any one step. + s.history_budget = 1; + for _ in 0..4 { + open_with_rects(&mut s, 50); + moves(&mut s, 12); + } + assert_eq!(undo_lens(&s), [History::MIN_STEPS; 4]); + // The kept steps undo and redo, and the document now is as it was. + let x = first_x(&s); + assert_eq!(x, 12.0); + for _ in 0..History::MIN_STEPS { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(first_x(&s), x - History::MIN_STEPS as f64); + assert!(s.execute("edit.undo", &json!({})).is_err(), "the older steps went"); + assert_eq!(s.doc().unwrap().history.redo.len(), History::MIN_STEPS); + // A held history keeps all of its steps until it is released. + assert!(s.set_active(0)); + s.docs[0].history.held = true; + moves(&mut s, 3); + assert_eq!(undo_lens(&s)[0], History::MIN_STEPS + 3, "a held history keeps its steps"); + s.docs[0].history.held = false; + s.trim_histories(); + assert_eq!(undo_lens(&s), [History::MIN_STEPS, History::MIN_STEPS, History::MIN_STEPS, 0]); +} + +#[test] +#[cfg(target_pointer_width = "64")] +fn the_default_budget_is_a_quarter_of_installed_memory() { + assert_eq!(history_budget_for(Some(16 << 30)), 4 << 30); + assert_eq!(history_budget_for(Some(64 << 30)), 16 << 30, "no fixed ceiling"); + // On Linux `physical_memory` returns a cgroup memory limit lower than the installed memory in + // its place (the `cgroup_limit_*` tests in vectorcraft-render), so a 2 GiB limit on a 64 GiB + // machine gives the budget of 2 GiB installed. + assert_eq!(history_budget_for(Some(2 << 30)), 512 << 20, "2 GiB, or a 2 GiB cgroup limit"); + assert_eq!(history_budget_for(Some(128 << 20)), 64 << 20, "at least 64 MiB"); + assert_eq!(history_budget_for(Some(1)), 64 << 20, "at least 64 MiB"); + assert_eq!(history_budget_for(Some(0)), 1 << 30, "a reading of 0 is the 1 GiB fallback"); + assert_eq!(history_budget_for(None), 1 << 30, "no reading is the 1 GiB fallback"); +} + +#[test] +#[cfg(any(target_os = "linux", windows, target_os = "macos", target_os = "freebsd"))] +fn the_default_budget_follows_the_installed_memory_read() { + // Where the memory can't be read (a sandbox that hides it), the budget is the 1 GiB fallback. + let memory = vectorcraft_render::physical_memory(); + assert_eq!(default_history_budget(), history_budget_for(memory), "{memory:?}"); + assert_eq!(History::default().byte_budget, default_history_budget()); + assert_eq!(Session::new().history_budget, default_history_budget(), "the open documents share it"); +} + #[test] fn undo_steps_keep_no_lookup_tables() { let mut s = session_with_rects(200); diff --git a/crates/engine/src/tests/linkwatch.rs b/crates/engine/src/tests/linkwatch.rs index 37aac5df5c..7fc8f0a4ba 100644 --- a/crates/engine/src/tests/linkwatch.rs +++ b/crates/engine/src/tests/linkwatch.rs @@ -147,6 +147,26 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() { assert!(s.link_scan.is_none()); } +#[test] +fn a_change_during_a_script_waits_for_the_script_to_end() { + let dir = Folder::new("watch-script"); + let path = dir.file("art.png"); + std::fs::write(&path, png(40, 40, RED)).unwrap(); + let mut s = session(); + s.prefs.update_links = "automatically".into(); + let id = place(&mut s, &path); + look(&mut s); + save(&path, &png(40, 40, BLUE)); + s.start_link_scan(); + s.wait_link_scan(); + s.script_frames = true; + s.execute("script.run", &json!({"source": "while (true) {}"})).unwrap(); + assert!(s.poll_link_scan().is_none(), "the finished look waits"); + assert!(s.script_abandon()); + assert_eq!(s.poll_link_scan().expect("the stamps are applied").unwrap()["updated"], json!([id.0])); + assert_eq!(colour(&s), BLUE); +} + #[test] fn a_change_during_a_drag_waits_for_the_drag_to_end() { let dir = Folder::new("watch-drag"); diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index 08fc120e0d..9fc790efa2 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -945,6 +945,34 @@ fn mesh_point_colour_move_and_undo() { assert!(s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": 99, "color": "#000000"})).is_err()); } +/// #2752: a Mesh tool click on a star, solid or gradient filled, gives a mesh with every point of +/// the star on its border, in one undo step that gives the star back. +#[test] +fn a_mesh_tool_click_keeps_a_stars_points() { + for gradient in [false, true] { + let mut s = session(); + let a = id_of(&s.execute("shape.star", &json!({"cx": 300, "cy": 300, "radius1": 200, "radius2": 80, "points": 5})).unwrap()); + if gradient { + s.execute("paint.setFill", &json!({"ids": [a.0], "gradient": {"kind": "linear"}})).unwrap(); + } else { + fill(&mut s, a, "#0000ff"); + } + let star = node(&s, a).path_data().unwrap().clone(); + sel(&mut s, &[a]); + let undos = undo_len(&s); + s.execute("object.mesh.create", &json!({"at": [300, 300]})).unwrap(); + assert_eq!(undo_len(&s), undos + 1); + let m = mesh_of(&s, a); + let border = m.outline().to_bezpath(); + for anchor in &star.subpaths[0].anchors { + assert!(m.points.iter().any(|q| q.p.distance(anchor.p) < 1e-6), "{:?} is not a mesh point", anchor.p); + assert!(vectorcraft_geom::Shape::bounding_box(&border).inflate(1e-6, 1e-6).contains(anchor.p)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, a).path_data(), Some(&star)); + } +} + /// A mesh point's `color` with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes /// nothing, also when `opacity` is given and when Add Mesh Line takes it; `#rrggbb` still sets it. #[test] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 1bc75a82a4..763cf22edb 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1514,6 +1514,44 @@ fn crop_image_to_rect() { assert!(s.execute("object.cropImage", &json!({})).is_err()); } +/// 100 × 80 px of a busy pattern, opened as an image and scaled to 2 pt a pixel; returns the session, the image and its pixels. +fn busy_image_at_two_points_a_pixel() -> (Session, NodeId, image::RgbaImage) { + let mut px = image::RgbaImage::new(100, 80); + for (x, y, p) in px.enumerate_pixels_mut() { + *p = image::Rgba([(x * 37 % 256) as u8, (y * 91 % 256) as u8, ((x ^ y) * 13 % 256) as u8, 255]); + } + let mut png = Vec::new(); + px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let img = selected(&s)[0]; + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + (s, img, px) +} + +#[test] +fn crop_image_to_rect_copies_the_pixels_without_resampling() { + let (mut s, img, px) = busy_image_at_two_points_a_pixel(); + // Pixels (10, 5) to (40, 25), as points: on the pixel grid, so the cut copies them as they are. + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40]})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 20), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 20.0) && close(b.y0, 10.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + assert_eq!(out, image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image()); +} + +#[test] +fn crop_image_to_a_rect_between_pixels_keeps_the_rect() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + // Pixels (10.5, 5.5) to (40.5, 25.5): off the pixel grid, so the cut is drawn and lands on the rect, not on whole pixels. + s.execute("object.cropImage", &json!({"rect": [21, 11, 60, 40]})).unwrap(); + let b = bounds(&s, img); + assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); +} + /// Crop Image refuses a `rect` that is not an array, such as text, and the image stays as it was; a /// null `rect` crops to the artboard as a missing one does. #[test] @@ -3687,6 +3725,40 @@ fn ruler_guides_and_lock() { assert!(s.execute("guide.remove", &json!({"index": 0})).is_err()); } +/// While guides are locked, a guide dragged out of a ruler and `guide.add` still make new guides, +/// each in one undo step and not selected. The ruler guides and guide paths in the document, the +/// new guides included, can't be selected, moved or deleted. +#[test] +fn new_guides_can_be_made_while_guides_are_locked() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let path = guide_path(&mut s, 300.0); + s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + let n = undo_len(&s); + s.ruler_guide(true, &PointerEvent::new(PointerKind::Drag, 153.0, 30.0), true, v).unwrap(); + s.ruler_guide(true, &PointerEvent::new(PointerKind::Up, 153.0, 30.0), true, v).unwrap(); + assert_eq!(guides(&s), [(false, 50.0), (true, 153.0)]); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "New Guide"); + assert_eq!(s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap()["index"], 2); + assert_eq!(guides(&s).len(), 3); + assert_eq!(selected_guides(&s), Vec::::new()); + for (id, params) in [ + ("guide.select", json!({"indexes": [1]})), + ("guide.move", json!({"index": 1, "pos": 170})), + ("guide.remove", json!({"index": 1})), + ("guide.setLayer", json!({"index": 1, "layer": s.doc().unwrap().current_layer().unwrap().0})), + ] { + assert!(matches!(s.execute(id, ¶ms), Err(EngineError::Disabled(..))), "{id}"); + } + assert_eq!(guides(&s).len(), 3); + sel(&mut s, &[path]); + assert!(selected(&s).is_empty(), "a guide path can't be selected"); +} + #[test] fn invalid_guide_lock_parameters_keep_guides_selected() { let mut s = session(); diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index b9ccac12d5..2930bf1721 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -1086,6 +1086,43 @@ fn defaults_match_the_dialog_and_info_tells_what_applies() { assert!(matches!(selected(&s).kind, NodeKind::Path { live: Some(_), .. })); } +/// Expand refuses an option of the wrong type with an error naming it, and leaves the art, the +/// selection and the undo history as they were. Null counts as an option left out, which keeps its +/// default. +#[test] +fn expand_refuses_an_option_of_the_wrong_type() { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(20.0, 20.0, 180.0, 120.0), white_black(), true); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.revision, st.history.undo.len(), st.history.redo.len(), st.selection.objects.clone()) + }; + let before = (state(&s), node(&s, id)); + let switch = |k: &str| format!("`{k}` must be true or false"); + for (p, want) in [ + (json!({"object": "yes"}), switch("object")), + (json!({"object": 0}), switch("object")), + (json!({"fill": "false"}), switch("fill")), + (json!({"stroke": 1}), switch("stroke")), + (json!({"gradient": 3}), "`gradient` must be a string".to_string()), + (json!({"gradient": true}), "`gradient` must be a string".to_string()), + (json!({"steps": "16"}), "`steps` must be a number, not \"16\"".to_string()), + (json!({"steps": [16]}), "`steps` must be a number, not [16]".to_string()), + ] { + let r = s.execute("object.expand", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{p}: {r:?}"); + assert_eq!((state(&s), node(&s, id)), before, "{p}"); + } + // Null options take their defaults: Object, Fill and Stroke on, 255 solid strips. + run(&mut s, "object.expand", json!({"object": null, "fill": null, "stroke": null, "gradient": null, "steps": null})); + let g = selected(&s); + let NodeKind::Group { children, .. } = &g.kind else { panic!("{:?}", g.kind) }; + let (clip, strips) = clip_parts(&children[0]); + assert!(matches!(clip.kind, NodeKind::Path { live: None, .. })); + assert_eq!(strips.len(), 255); + assert!(children[1].appearance.stroke_paint().is_none(), "outlined stroke"); +} + /// A selected open line with a 2 pt black stroke, no fill and a Zig Zag effect (#3089). fn zig_zag_line(s: &mut Session) -> NodeId { let id = NodeId(run(s, "path.create", json!({"d": "M 20 100 L 180 100"}))["id"].as_u64().unwrap()); diff --git a/crates/engine/src/tests/opacitymask.rs b/crates/engine/src/tests/opacitymask.rs index 206ef7e66d..9327bdc02b 100644 --- a/crates/engine/src/tests/opacitymask.rs +++ b/crates/engine/src/tests/opacitymask.rs @@ -151,6 +151,59 @@ fn mask_options_already_set_record_no_undo_step() { assert!(s.execute("transparency.setOpacityMask", &json!({"id": a.0})).is_err(), "no flag given"); } +/// Make Opacity Mask, Opacity Mask Options and the New Opacity Masks and page toggles refuse a +/// param of the wrong type with an error naming it, and leave the document, the selection, the +/// undo history and the defaults for new masks as they were. Null counts as a param left out, +/// which keeps its default. +#[test] +fn mask_commands_refuse_a_param_of_the_wrong_type() { + let mut s = session(); + let (a, m) = (rect(&mut s, 0.0, 100.0), rect(&mut s, 0.0, 50.0)); + s.execute("select.set", &json!({"ids": [a.0, m.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let (b, c) = (rect(&mut s, 150.0, 100.0), rect(&mut s, 150.0, 50.0)); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.revision, history(s), st.selection.objects.clone(), s.new_mask_defaults()) + }; + let before = state(&s); + let switch = |k: &str| format!("`{k}` must be true or false"); + for (cmd, p, want) in [ + ("transparency.makeOpacityMask", json!({"clip": "false"}), switch("clip")), + ("transparency.makeOpacityMask", json!({"clip": 0}), switch("clip")), + ("transparency.makeOpacityMask", json!({"invert": "true"}), switch("invert")), + ("transparency.makeOpacityMask", json!({"invert": [true]}), switch("invert")), + ("transparency.setOpacityMask", json!({"id": a.0, "clip": "no"}), switch("clip")), + ("transparency.setOpacityMask", json!({"id": a.0, "clip": false, "invert": "yes"}), switch("invert")), + ("transparency.setOpacityMask", json!({"id": a.0, "disabled": 1}), switch("disabled")), + ("transparency.setOpacityMask", json!({"id": a.0, "linked": "false"}), switch("linked")), + ("transparency.toggleNewMasksClipping", json!({"value": "true"}), switch("value")), + ("transparency.toggleNewMasksInverted", json!({"value": 1}), switch("value")), + ("transparency.togglePageKnockoutGroup", json!({"value": "on"}), switch("value")), + ("transparency.togglePageIsolatedBlending", json!({"value": 0}), switch("value")), + ] { + let r = s.execute(cmd, &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{cmd} {p}: {r:?}"); + assert!(state(&s) == before, "{cmd} {p}: nothing changes"); + } + // Null params take their defaults: a new mask clips and is not inverted, a null flag stays as + // it is, and a null value toggles. + let id = s.execute("transparency.makeOpacityMask", &json!({"clip": null, "invert": null})).unwrap()["id"].as_u64().unwrap(); + let made = mask(&s, NodeId(id)).unwrap(); + assert!(made.clip && !made.invert); + s.execute("transparency.setOpacityMask", &json!({"id": a.0, "clip": null, "invert": true, "disabled": null, "linked": null})).unwrap(); + let set = mask(&s, a).unwrap(); + assert!(set.clip && set.invert && !set.disabled && set.linked); + assert!(s.execute("transparency.setOpacityMask", &json!({"id": a.0, "clip": null})).is_err(), "no flag given"); + assert_eq!(s.execute("transparency.toggleNewMasksClipping", &json!({"value": null})).unwrap(), json!({"value": false})); + assert_eq!(s.execute("transparency.toggleNewMasksInverted", &json!({"value": null})).unwrap(), json!({"value": true})); + assert_eq!(s.new_mask_defaults(), (false, true)); + assert_eq!(s.execute("transparency.togglePageKnockoutGroup", &json!({"value": null})).unwrap(), json!({"value": true})); + assert_eq!(s.execute("transparency.togglePageIsolatedBlending", &json!({"value": null})).unwrap(), json!({"value": true})); + assert!(doc(&s).page_knockout && doc(&s).page_isolate); +} + /// #4538: while a mask is edited the Layers panel lists only the mask, so New Layer and New /// Sublayer are refused instead of adding layers no row shows; they work again afterwards. #[test] diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 0870ffb87d..239d6bee7b 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -1786,6 +1786,54 @@ fn delete_empty_artboards_check_measures_a_document_once() { assert_eq!(delete_empty_enabled_counted(&s), (true, 0), "after another change of the selection"); } +/// Whether Fit to Artwork Bounds has art to fit on `indices`, as a menu asks for it, with the +/// plug-ins' and fonts' generations `outside`, and how many times asking measured a document on +/// this thread. +fn art_to_fit_counted(s: &Session, indices: &[usize], outside: (u64, u64)) -> (bool, usize) { + let measures = || crate::doc_state::ART_TO_FIT_MEASURES.with(std::cell::Cell::get); + let before = measures(); + let any = s.doc().unwrap().any_art_to_fit_with(indices, outside); + (any, measures() - before) +} + +/// A menu asks whether Fit to Artwork Bounds has art on every frame while it is open: the answer is +/// measured once for a version of the document and the artboards asked about, kept through a change +/// of the selection or the view, and measured again after an edit, for other artboards, and when +/// the plug-ins or the fonts change. +#[test] +fn art_to_fit_is_measured_once_for_a_version_of_the_document() { + let mut s = row_of_artboards(2); + let both = [0, 1]; + assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (false, 1), "the first frame"); + assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (false, 0), "a later frame"); + let art = box_at(&mut s, 10.0, 20.0); + assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 1), "an edit puts art on artboard 1"); + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 0), "after a change of the selection"); + s.execute("view.transparencyGrid", &json!({})).unwrap(); + assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 0), "after a change of the view"); + assert_eq!(art_to_fit_counted(&s, &[1], (0, 0)), (false, 1), "other artboards"); + assert_eq!(art_to_fit_counted(&s, &[1], (1, 0)), (false, 1), "a plug-in installed or removed"); + assert_eq!(art_to_fit_counted(&s, &[1], (1, 1)), (false, 1), "fonts installed"); + assert_eq!(art_to_fit_counted(&s, &[1], (1, 1)), (false, 0)); +} + +/// A change made to the document in place (`Arc::make_mut`, with no other holder and no change +/// of revision) is measured again: the kept answer holds the document it measured weakly, so a +/// changed document is a new allocation, not the old address. +#[test] +fn art_to_fit_follows_a_change_in_place() { + let mut s = row_of_artboards(2); + box_at(&mut s, 10.0, 20.0); + assert_eq!(art_to_fit_counted(&s, &[0], (0, 0)), (true, 1), "art on artboard 1"); + let st = s.doc_mut().unwrap(); + assert_eq!(Arc::strong_count(&st.doc), 1, "the undo history holds the document before the edit"); + let (revision, empty_spot) = (st.revision, st.doc.artboards[1].rect); + Arc::make_mut(&mut st.doc).artboards[0].rect = empty_spot; + assert_eq!(st.revision, revision); + assert_eq!(art_to_fit_counted(&s, &[0], (0, 0)), (false, 1), "artboard 1 moved off the art"); +} + /// The enabled state follows an edit, an undo, a redo, an added and a removed artboard, a locked /// artboard, and each change measures the document once. #[test] diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index a5bd60490b..57094355c0 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -844,6 +844,69 @@ fn clean_up_removes_junk() { assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none()); } +/// Offset Path, Simplify, Split Into Grid and Clean Up refuse a param of the wrong type with an +/// error naming the param, and leave the document, the selection and the undo history as they were. +/// Null keeps a param's default, and a distance still takes a string with a unit. +#[test] +fn path_commands_refuse_a_param_of_the_wrong_type() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.selection.objects.clone(), st.history.undo.len()) + }; + let before = state(&s); + let number = |k: &str, v: &str| format!("`{k}` must be a number, not {v}"); + let switch = |k: &str| format!("`{k}` must be true or false"); + for (cmd, p, want) in [ + ("object.path.offsetPath", json!({"offset": true}), number("offset", "true")), + ("object.path.offsetPath", json!({"offset": "wide"}), number("offset", "\"wide\"")), + ("object.path.offsetPath", json!({"offset": 5, "joins": 3}), "`joins` must be a string".to_string()), + ("object.path.offsetPath", json!({"offset": 5, "joins": "pointy"}), "`joins` must be one of miter, round, bevel".to_string()), + ("object.path.offsetPath", json!({"offset": 5, "miterLimit": [4]}), number("miterLimit", "[4]")), + ("object.path.simplify", json!({"auto": "true"}), switch("auto")), + ("object.path.simplify", json!({"level": false}), number("level", "false")), + ("object.path.simplify", json!({"level": 50, "tolerance": {}}), number("tolerance", "{}")), + ("object.path.simplify", json!({"cornerAngle": "sharp"}), number("cornerAngle", "\"sharp\"")), + ("object.path.simplify", json!({"straightLines": 1}), switch("straightLines")), + ("object.path.simplify", json!({"wholePaths": "no"}), switch("wholePaths")), + ("object.path.splitIntoGrid", json!({"rows": "many"}), number("rows", "\"many\"")), + ("object.path.splitIntoGrid", json!({"columns": true}), number("columns", "true")), + ("object.path.splitIntoGrid", json!({"gutter": false}), number("gutter", "false")), + ("object.path.splitIntoGrid", json!({"rowGutter": 2, "gutter": "x"}), number("gutter", "\"x\"")), + ("object.path.splitIntoGrid", json!({"height": 5, "totalHeight": [1]}), number("totalHeight", "[1]")), + ("object.path.splitIntoGrid", json!({"width": "wide"}), number("width", "\"wide\"")), + ("object.path.splitIntoGrid", json!({"columnGutter": true}), number("columnGutter", "true")), + ("object.path.splitIntoGrid", json!({"totalWidth": {}}), number("totalWidth", "{}")), + ("object.path.splitIntoGrid", json!({"rowGutter": "a"}), number("rowGutter", "\"a\"")), + ("object.path.splitIntoGrid", json!({"addGuides": "yes"}), switch("addGuides")), + ("object.path.cleanUp", json!({"strayPoints": "false"}), switch("strayPoints")), + ("object.path.cleanUp", json!({"unpaintedObjects": 0}), switch("unpaintedObjects")), + ("object.path.cleanUp", json!({"emptyTextPaths": "no"}), switch("emptyTextPaths")), + ] { + let r = s.execute(cmd, &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{cmd} {p}: {r:?}"); + assert!(state(&s) == before, "{cmd} {p} changed the document, the selection or the undo history"); + } + // Null takes the default: a 10 pt offset with mitered joins. + let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": null, "joins": null, "miterLimit": null})).unwrap()); + assert!(close(bounds(&s, r[0]), Rect::new(90.0, 90.0, 160.0, 150.0), 1e-2), "{:?}", bounds(&s, r[0])); + // A distance with a unit, and a join named in capitals. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.1 in", "joins": "Bevel"})).unwrap()); + assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0])); + // Null switches keep Clean Up's defaults, which remove the stray point. + let r = s.execute("object.path.cleanUp", &json!({"strayPoints": null, "unpaintedObjects": null, "emptyTextPaths": null})).unwrap(); + assert_eq!(r["removed"], 1); + // Split Into Grid with null counts and a gutter with a unit: two by two, 0.5 in apart. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = ids(&s.execute("object.path.splitIntoGrid", &json!({"rows": null, "columns": null, "gutter": "0.5 in", "addGuides": null})).unwrap()); + assert_eq!(r.len(), 4); + assert!(close(bounds(&s, r[0]), Rect::new(100.0, 100.0, 107.0, 102.0), 1e-9), "{:?}", bounds(&s, r[0])); +} + #[test] fn divide_objects_below_cuts() { let mut s = session(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index a705f05b9b..aca18dee1e 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -3407,3 +3407,29 @@ fn another_module_under_an_id_with_settings_needs_replace() { install(&mut s, json!({})).unwrap(); run(&mut s, "plugin.remove", json!({"id": id})); } + +/// A filter that calls commands runs on the document with the edit in progress kept first: a move +/// still being previewed is its own undo step, and the filter is given the moved rectangle, which +/// its empty output then removes. +#[test] +fn a_filter_that_calls_commands_is_given_the_edit_in_progress() { + let id = "test.engine.callsettle"; + let mut s = session(); + let grant = json!(["doc.read", "doc.write", "commands"]); + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["select.all"]}}"#); + let wasm = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); + let paths = |s: &Session| s.doc().unwrap().doc.layers.first().and_then(|l| l.children()).map_or(0, |c| c.len()); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})); + s.begin_interaction("Move").unwrap(); + s.preview("object.move", &json!({"dx": 7, "dy": 0})).unwrap(); + run(&mut s, "plugin.run", json!({"id": id})); + assert!(!s.in_interaction()); + assert_eq!(paths(&s), 0, "the filter was given the moved rectangle and removed it"); + let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); + assert_eq!(labels, [format!("Test {id}").as_str(), "Move"]); + run(&mut s, "edit.undo", json!({})); + let x = run(&mut s, "document.inspect", json!({}))["layers"][0]["children"][0]["bounds"]["x"].clone(); + assert_eq!(x, json!(17.0), "undoing the filter brings back the moved rectangle"); + run(&mut s, "plugin.remove", json!({"id": id})); +} diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 52755f2cbc..8e3c043e4e 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -199,6 +199,110 @@ fn reset_category_and_all() { assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err()); } +/// A rectangle made into a guide path; nothing is selected after. +fn guide_path(s: &mut Session, x: f64) -> NodeId { + let id = square(s, x, 0.0); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + id +} + +/// Lock Guides by Default is off, and preferences saved before it existed leave guides unlocked. +#[test] +fn lock_guides_by_default_is_off_and_older_preferences_leave_guides_unlocked() { + assert!(!Prefs::default().lock_guides_by_default); + let older: Prefs = serde_json::from_value(json!({"keyboardIncrement": 4})).unwrap(); + assert!(!older.lock_guides_by_default); + let mut s = Session::new(); + s.apply_prefs(older); + assert!(!s.guides_locked()); + assert!(s.execute("prefs.set", &json!({"key": "lockGuidesByDefault", "value": "yes"})).is_err()); + assert!(!s.guides_locked() && !s.prefs.lock_guides_by_default); +} + +/// Preferences saved with the option on start a session with guides locked. A document opened in +/// it has its ruler guides and guide paths locked, and new guides can still be made. View › Guides +/// › Lock Guides then unlocks them for the session and leaves the preference on. +#[test] +fn saved_lock_guides_by_default_locks_a_new_session_and_the_documents_it_opens() { + let file = std::env::temp_dir().join(format!("vc-lock-guides-{}.vectorcraft", std::process::id())); + let file = file.to_string_lossy().to_string(); + let mut unlocked = new_doc(); + assert!(!unlocked.guides_locked(), "a session without the preference"); + let path = guide_path(&mut unlocked, 100.0); + unlocked.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap(); + unlocked.execute("document.save", &json!({"path": file})).unwrap(); + + // The preference is set with no document open, as a headless session can. + let mut first = Session::new(); + first.execute("prefs.set", &json!({"key": "lockGuidesByDefault", "value": true})).unwrap(); + let saved = first.prefs.to_json(); + assert_eq!(saved["lockGuidesByDefault"], json!(true)); + + let mut s = Session::new(); + s.apply_prefs(serde_json::from_value(saved).unwrap()); + assert!(s.guides_locked()); + s.execute("document.open", &json!({"path": file})).unwrap(); + let _ = std::fs::remove_file(&file); + assert!(s.guides_locked(), "opening a document keeps the lock"); + assert!(matches!(s.execute("guide.select", &json!({"indexes": [0]})), Err(EngineError::Disabled(..)))); + s.execute("select.set", &json!({"ids": [path.0]})).unwrap(); + assert!(s.doc().unwrap().selection.objects.is_empty(), "a guide path can't be selected"); + assert_eq!(s.execute("guide.add", &json!({"vertical": false, "pos": 20})).unwrap()["index"], 1); + + assert_eq!(s.execute("view.guides.lock", &json!({})).unwrap(), json!({"locked": false})); + assert!(s.prefs.lock_guides_by_default, "the menu leaves the preference as it is"); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("select.set", &json!({"ids": [path.0]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [path]); +} + +/// Changing the preference sets the lock at once and deselects guides in every open document. +/// A change to any other preference, or setting it to the value it has, keeps the session's lock. +#[test] +fn changing_lock_guides_by_default_sets_the_lock_and_other_changes_keep_it() { + let mut s = new_doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let path = guide_path(&mut s, 100.0); + s.execute("select.set", &json!({"ids": [path.0]})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + + set_pref(&mut s, "lockGuidesByDefault", json!(true)); + assert!(s.guides_locked()); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the guide path in the active document"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert!(s.doc().unwrap().selection.guides.is_empty(), "the ruler guide in the other document"); + + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + set_pref(&mut s, "keyboardIncrement", json!(4)); + set_pref(&mut s, "lockGuidesByDefault", json!(true)); + assert!(!s.guides_locked(), "the session's unlock stays"); + + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + set_pref(&mut s, "lockGuidesByDefault", json!(false)); + assert!(!s.guides_locked(), "turning the preference off unlocks guides"); +} + +/// Reset turns the option off and unlocks guides. With the option already off, a reset keeps a +/// lock set from the View menu. +#[test] +fn resetting_lock_guides_by_default_unlocks_guides_only_when_it_was_on() { + let mut s = new_doc(); + for params in [json!({"category": "Guides & Grid"}), json!({})] { + set_pref(&mut s, "lockGuidesByDefault", json!(true)); + assert!(s.guides_locked()); + s.execute("prefs.reset", ¶ms).unwrap(); + assert!(!s.prefs.lock_guides_by_default, "{params}"); + assert!(!s.guides_locked(), "{params}"); + } + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + s.execute("prefs.reset", &json!({})).unwrap(); + assert!(s.guides_locked()); +} + /// `prefs.set` refuses a recovery or plug-ins folder that is missing or is a file. Nothing changes, /// other values in the same call included, and the document gets no undo step. #[test] diff --git a/crates/engine/src/tests/previewbounds.rs b/crates/engine/src/tests/previewbounds.rs index c9bad6e60d..773b2b7842 100644 --- a/crates/engine/src/tests/previewbounds.rs +++ b/crates/engine/src/tests/previewbounds.rs @@ -618,6 +618,77 @@ fn set_bounds_leaves_the_height_of_lines_with_no_height() { assert!(close(geometric(&s, ids[1]), Rect::new(8.3, 100.0, 30.0, 100.0)), "{:?}", geometric(&s, ids[1])); } +/// A line with a 2 pt stroke and butt caps, selected, with Use Preview Bounds on. +fn butt_line(s: &mut Session, from: (f64, f64), to: (f64, f64)) -> NodeId { + let id = NodeId(run(s, "shape.line", json!({"x1": from.0, "y1": from.1, "x2": to.0, "y2": to.1}))["id"].as_u64().unwrap()); + run(s, "stroke.set", json!({"weight": 2, "cap": "butt"})); + preview(s, true); + run(s, "select.set", json!({"ids": [id.0]})); + id +} + +#[test] +fn set_bounds_gives_a_butt_line_the_whole_height() { + // A butt cap ends at the anchor, so 10 mm (28.3465 pt) is the length of the line itself. + let mut s = session(); + let id = butt_line(&mut s, (100.0, 100.0), (100.0, 140.0)); + assert!(close(s.transform_bounds(&[id]).unwrap(), Rect::new(99.0, 100.0, 101.0, 140.0)), "{:?}", s.transform_bounds(&[id])); + run(&mut s, "object.setBounds", json!({"height": 28.3465, "reference": 0, "strokes": false})); + assert!(close(geometric(&s, id), Rect::new(100.0, 100.0, 100.0, 128.3465)), "{:?}", geometric(&s, id)); + assert!(close(s.transform_bounds(&[id]).unwrap(), Rect::new(99.0, 100.0, 101.0, 128.3465)), "{:?}", s.transform_bounds(&[id])); +} + +#[test] +fn set_bounds_gives_a_diagonal_butt_line_the_size_out_of_proportion() { + // The stroke's corners follow the line's slope, which a scale out of proportion changes. + let mut s = session(); + let id = butt_line(&mut s, (100.0, 100.0), (130.0, 140.0)); + let before = s.transform_bounds(&[id]).unwrap(); + // The stroke's corners reach 0.8 pt across x and 0.6 pt across y at this 3-4-5 slope. + assert!(close(before, Rect::new(99.2, 99.4, 130.8, 140.6)), "{before:?}"); + run(&mut s, "object.setBounds", json!({"height": 100, "reference": 0, "strokes": false})); + let v = s.transform_bounds(&[id]).unwrap(); + assert!((v.height() - 100.0).abs() < 1e-6, "{v:?}"); +} + +#[test] +fn set_bounds_gives_a_butt_path_with_slanted_corners_the_size_out_of_proportion() { + // Square ends, but the bevel join at the apex sets the top edge by the slanted segments' + // corners, which a scale out of proportion moves. + let mut s = session(); + let anchors = json!([{"x": 100, "y": 150}, {"x": 100, "y": 140}, {"x": 110, "y": 100}, {"x": 120, "y": 140}, {"x": 120, "y": 150}]); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": anchors}))["id"].as_u64().unwrap()); + run(&mut s, "stroke.set", json!({"weight": 2, "cap": "butt", "join": "bevel"})); + preview(&mut s, true); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "object.setBounds", json!({"width": 60, "height": 20, "reference": 0, "strokes": false})); + let v = s.transform_bounds(&[id]).unwrap(); + assert!((v.width() - 60.0).abs() < 1e-6 && (v.height() - 20.0).abs() < 1e-6, "{v:?}"); +} + +#[test] +fn set_bounds_gives_a_symbol_instance_of_a_diagonal_butt_line_the_size_out_of_proportion() { + let mut s = session(); + butt_line(&mut s, (100.0, 100.0), (130.0, 140.0)); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Line"}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "object.setBounds", json!({"width": 20, "height": 100, "reference": 0, "strokes": false})); + let v = s.transform_bounds(&[id]).unwrap(); + assert!((v.width() - 20.0).abs() < 1e-6 && (v.height() - 100.0).abs() < 1e-6, "{v:?}"); +} + +#[test] +fn align_places_a_vertical_butt_line_by_its_end_points() { + // With Use Preview Bounds on, a butt line's ends line up with the top of a rectangle without + // a stroke. + let mut s = session(); + rect(&mut s, 20.0, 50.0, 0.0); + let id = butt_line(&mut s, (200.0, 160.0), (200.0, 190.0)); + run(&mut s, "select.all", json!({})); + run(&mut s, "object.align", json!({"vertical": "top"})); + assert!(close(geometric(&s, id), Rect::new(200.0, 100.0, 200.0, 130.0)), "{:?}", geometric(&s, id)); +} + /// The rectangles of [`thin_and_thick`] in a group, the thick one in a group of its own inside it /// when `nested`, selected with an unstroked rectangle from x 100 to 110 when `plain`. Returns the /// selected objects. diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs new file mode 100644 index 0000000000..eba254116a --- /dev/null +++ b/crates/engine/src/tests/script_run.rs @@ -0,0 +1,1037 @@ +//! `script.run` and `script.stop`: one transaction per run, the rollback after a throw, a limit, a +//! stop or a panic, the mutation lease between slices, ids, growth and what a run reports. + +use std::cell::Cell; + +use serde_json::{Value, json}; + +use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_RESULT_BYTES}; +use crate::*; + +fn rect(x: i64) -> Value { + json!({"x": x, "y": 0, "width": 10, "height": 10}) +} + +/// Two open documents, each with one rectangle, the second one active. +fn two_docs() -> Session { + let mut s = Session::new(); + for x in [0, 50] { + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &rect(x)).unwrap(); + } + s +} + +/// What a rollback has to put back. +fn state(s: &Session) -> Value { + let docs: Vec = s + .documents() + .iter() + .map(|d| { + json!({ + "uid": d.uid, + "art": format!("{:?}", d.doc.layers), + "selection": d.selection.objects.iter().map(|i| i.0).collect::>(), + "undo": d.history.undo.iter().map(|e| e.label.clone()).collect::>(), + "redo": d.history.redo.len(), + "path": d.path, + "dirty": d.is_dirty(), + }) + }) + .collect(); + json!({"docs": docs, "active": s.active().map(|d| d.uid), "journal": s.journal.len(), "paint": format!("{:?}", s.paint)}) +} + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +fn objects(s: &Session, doc: usize) -> usize { + s.documents()[doc].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +/// A framed run of `source`, one slice in. +fn paused(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(run(s, source).unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert!(s.script_running()); +} + +fn two_rect_script() -> String { + "vc.run('shape.rectangle', {x:100,y:0,width:5,height:5});\ + vc.run('shape.rectangle', {x:110,y:0,width:5,height:5});\ + vc.run('document.activate', {index:0});\ + vc.run('shape.rectangle', {x:120,y:0,width:5,height:5});\ + vc.run('document.activate', {index:1});" + .to_string() +} + +#[test] +fn a_run_is_one_undo_step_in_each_document_it_changed() { + let mut s = two_docs(); + let before = state(&s); + let r = run(&mut s, &two_rect_script()).unwrap(); + assert_eq!(r["ok"], true); + assert_eq!((objects(&s, 0), objects(&s, 1)), (2, 3)); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script"); + assert_eq!(s.documents()[1].history.undo.last().unwrap().label, "Run Script"); + assert_eq!(s.documents()[1].history.undo.len(), before["docs"][1]["undo"].as_array().unwrap().len() + 1); + let after = format!("{:?}", s.documents()[1].doc.layers); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s, 1), 1); + assert_eq!(format!("{:?}", s.documents()[1].doc.layers), before["docs"][1]["art"].as_str().unwrap()); + assert_eq!(s.documents()[1].selection.objects.len(), before["docs"][1]["selection"].as_array().unwrap().len()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(format!("{:?}", s.documents()[1].doc.layers), after); +} + +#[test] +fn a_run_that_changes_nothing_leaves_no_step_no_mark_and_no_journal_entry() { + for source in ["", "var a = 1 + 2;", "vc.log(vc.document); vc.commands.length;"] { + let mut s = two_docs(); + s.execute("document.save", &json!({"path": std::env::temp_dir().join(format!("vc-noop-{}.svg", std::process::id())).to_string_lossy()})) + .unwrap(); + let before = state(&s); + let revisions = |s: &Session| s.documents().iter().map(|d| d.revision).collect::>(); + let revisions_before = revisions(&s); + let r = run(&mut s, source).unwrap(); + assert_eq!(r["changed"], json!([]), "{source}"); + assert_eq!(state(&s), before, "{source}"); + assert_eq!(revisions(&s), revisions_before, "{source}"); + } +} + +#[test] +fn a_caught_command_failure_leaves_nothing_behind_and_the_script_goes_on() { + let mut s = two_docs(); + let source = "var m = '';\ + try { vc.run('command.batch', {commands: [\ + {command:'shape.rectangle', params:{x:1,y:1,width:1,height:1}},\ + {command:'no.such', params:{}}]}); } catch (e) { m = e.message; }\ + try { vc.run('shape.rectangle', {x:'bad'}); } catch (e) { m += '|' + e.name; }\ + vc.log(m); vc.run('shape.rectangle', {x:200,y:0,width:5,height:5});"; + let r = run(&mut s, source).unwrap(); + assert_eq!(objects(&s, 1), 2, "{r}"); + assert!(r["log"][0].as_str().unwrap().contains("|Error"), "{r}"); +} + +#[test] +fn a_failure_puts_back_every_document_and_the_session() { + enum How { + Throw, + Fuel, + Stop, + Panic, + } + for how in [How::Throw, How::Fuel, How::Stop, How::Panic] { + let mut s = two_docs(); + let before = state(&s); + let edits = two_rect_script(); + let r = match how { + How::Throw => run(&mut s, &format!("{edits} throw new Error('boom');")), + How::Fuel => s.execute("script.run", &json!({"source": format!("{edits} while (true) {{}}"), "maxFuel": 2_000_000})), + How::Stop => { + paused(&mut s, &format!("{edits} while (true) {{}}")); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + s.script_pump().unwrap() + } + How::Panic => { + paused(&mut s, &format!("{edits} while (true) {{}}")); + PANIC_IN_SLICE.with(|p| p.set(true)); + let r = s.script_pump().unwrap(); + PANIC_IN_SLICE.with(|p| p.set(false)); + r + } + }; + assert!(r.is_err()); + assert_eq!(state(&s), before); + assert!(!s.script_running()); + s.script_frames = false; + assert_eq!(run(&mut s, "1").unwrap()["ok"], true, "a later run starts"); + } +} + +#[test] +fn a_stop_with_no_run_reports_it() { + assert_eq!(Session::new().execute("script.stop", &json!({})).unwrap()["stopped"], false); +} + +#[test] +fn an_error_names_the_script_its_place_and_kind() { + let mut s = two_docs(); + let e = run(&mut s, "var a;\n throw new TypeError('no');").unwrap_err().to_string(); + assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); + let e = run(&mut s, "var = 1;").unwrap_err().to_string(); + assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); + assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "#target x\n1").unwrap_err().to_string().contains("#target")); + assert_eq!(s.script_report().unwrap()["line"], 1); +} + +#[test] +fn bad_parameters_are_refused_before_anything_runs() { + let mut s = two_docs(); + let before = state(&s); + let mut deep = json!(1); + for _ in 0..100 { + deep = json!([deep]); + } + for p in [ + json!({}), + json!({"source": "1", "args": {"a": deep}}), + json!({"path": "a", "source": "b"}), + json!({"path": ""}), + json!({"path": 1}), + json!({"source": "1", "nope": 1}), + json!({"source": "1", "args": []}), + json!({"source": "1", "args": {"a": "x".repeat(1 << 20)}}), + json!({"source": "1", "answers": {"a": 1}}), + json!({"source": "1", "answers": 1}), + json!({"source": "1", "maxFuel": 0}), + json!({"source": "1", "maxFuel": -1}), + json!({"source": "1", "maxFuel": 1.5}), + json!({"source": "1", "maxFuel": "9"}), + json!({"source": "1", "maxFuel": 100_000_000_001u64}), + ] { + assert!(matches!(s.execute("script.run", &p), Err(EngineError::BadParams { .. })), "{p}"); + } + assert_eq!(state(&s), before); +} + +#[test] +fn files_are_checked_before_they_are_read() { + let dir = std::env::temp_dir().join(format!("vc-script-run-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let write = |name: &str, bytes: &[u8]| { + let p = dir.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let ok = write("Bézier (1) & co.js", b"\xef\xbb\xbfvc.log(1);\r\nvc.log(2);\r\n"); + let r = s.execute("script.run", &path(&ok)).unwrap(); + assert_eq!((r["log"].clone(), r["name"].as_str()), (json!([1, 2]), Some("Bézier (1) & co.js"))); + let invalid = write("a.js", b"var a = '\xff';"); + assert!(s.execute("script.run", &path(&invalid)).unwrap_err().to_string().contains("UTF-8")); + let huge = write("huge.js", &vec![b' '; script::MAX_SOURCE_BYTES + 1]); + assert!(s.execute("script.run", &path(&huge)).unwrap_err().to_string().contains("too large")); + let compiled = write("b.jsxbin", b"@JSXBIN@ES@2.0@"); + assert!(s.execute("script.run", &path(&compiled)).unwrap_err().to_string().contains("compiled")); + let renamed = write("c.js", b"@JSXBIN@ES@2.0@"); + assert!(s.execute("script.run", &path(&renamed)).unwrap_err().to_string().contains("compiled")); + assert!(s.execute("script.run", &path(&dir.to_string_lossy())).is_err()); + let huge_source = " ".repeat(script::MAX_SOURCE_BYTES + 1); + assert!(run(&mut s, &huge_source).unwrap_err().to_string().contains("too large")); + let other = write("notes.txt", b"vc.log(1);"); + assert!(matches!(s.execute("script.run", &path(&other)), Err(EngineError::BadParams { .. })), "a text file that is not a script"); + let upper = write("UP.JSX", b"vc.log(3);"); + assert_eq!(s.execute("script.run", &path(&upper)).unwrap()["log"], json!([3])); + std::fs::create_dir_all(dir.join("folder.js")).unwrap(); + assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() { + let path = std::env::temp_dir().join(format!("vc-script-batch-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let p = path.to_string_lossy().into_owned(); + let mut s = two_docs(); + let source = format!( + "try {{ vc.run('command.batch', {{commands: [\ + {{command: 'view.guides.lock', params: {{locked: true}}}},\ + {{command: 'document.export', params: {{path: {p:?}, format: 'svg'}}}},\ + {{command: 'no.such', params: {{}}}}]}}); }} catch (e) {{ vc.log(e.name); }}" + ); + let r = run(&mut s, &source).unwrap(); + assert_eq!(r["log"], json!(["Error"]), "{r}"); + assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay"); + assert!(path.exists()); + assert_eq!(r["written"], json!([p]), "{r}"); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn an_export_that_fails_names_no_file() { + let path = std::env::temp_dir().join(format!("vc-script-no-folder-{}", std::process::id())).join("out.svg"); + let p = path.to_string_lossy().into_owned(); + let mut s = two_docs(); + let source = format!("try {{ vc.run('document.export', {{path: {p:?}, format: 'svg'}}); }} catch (e) {{ vc.log(e.name); }}"); + let r = run(&mut s, &source).unwrap(); + assert_eq!(r["log"], json!(["Error"]), "{r}"); + assert!(!path.exists()); + assert_eq!(r["written"], json!([]), "{r}"); +} + +#[test] +fn a_failed_run_puts_back_the_choices_its_commands_made() { + let mut s = two_docs(); + let before = s.global_edit_options.clone(); + let source = "vc.run('select.globalEditOptions', {appearance: !vc.run('select.globalEditOptions', {}).appearance}); throw new Error('x');"; + assert!(run(&mut s, source).is_err()); + assert_eq!(s.global_edit_options, before); + let source = "try { vc.run('command.batch', {commands: [\ + {command: 'select.globalEditOptions', params: {size: true}},\ + {command: 'no.such', params: {}}]}); } catch (e) {}"; + run(&mut s, source).unwrap(); + assert_eq!(s.global_edit_options, before, "the failed command's choice went back"); + + assert!(!s.caps_lock); + assert!(run(&mut s, "vc.run('view.capsLock', {on: true}); throw new Error('x');").is_err()); + assert!(!s.caps_lock, "the Caps Lock state went back"); + run(&mut s, "vc.run('view.capsLock', {on: true});").unwrap(); + assert!(s.caps_lock, "a finished run keeps it"); +} + +#[test] +fn a_failed_run_puts_back_the_preferences_its_commands_changed() { + let mut s = two_docs(); + let basic = s.prefs.new_art_basic; + assert!(run(&mut s, &format!("vc.run('appearance.setNewArtBasic', {{on: {}}}); throw new Error('x');", !basic)).is_err()); + assert_eq!(s.prefs.new_art_basic, basic); +} + +#[test] +fn a_finished_run_keeps_its_preferences_and_the_ones_the_app_changed_meanwhile() { + let mut s = two_docs(); + let (basic, increment) = (s.prefs.new_art_basic, s.prefs.keyboard_increment); + paused(&mut s, &format!("vc.run('appearance.setNewArtBasic', {{on: {}}}); for (var i = 0; i < 2000000; i++) {{}}", !basic)); + assert_eq!(s.prefs.new_art_basic, basic, "between slices the app sees the preferences before the run"); + s.prefs.keyboard_increment = increment + 1.0; + s.execute("view.capsLock", &json!({"on": true})).unwrap(); + while s.script_pump().is_none() {} + assert_eq!((s.prefs.new_art_basic, s.prefs.keyboard_increment), (!basic, increment + 1.0)); + assert!(s.caps_lock, "the Caps Lock state the app reported during the run stays"); +} + +#[test] +fn a_script_cannot_load_the_place_cursor() { + let mut s = two_docs(); + let e = run(&mut s, "vc.run('file.place.queue', {paths: []});").unwrap_err().to_string(); + assert!(e.contains("a script cannot run `file.place.queue`"), "{e}"); + let listed = run(&mut s, "vc.log(vc.commands.some(function (c) { return c.id === 'file.place.queue'; }));").unwrap(); + assert_eq!(listed["log"], json!([false]), "{listed}"); +} + +#[test] +fn a_command_whose_result_cannot_cross_is_put_back() { + TEST_RESULT_BYTES.with(|b| b.set(Some(1))); + let mut s = two_docs(); + let r = run(&mut s, "try { vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); } catch (e) { vc.log(e.name); }"); + TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["RangeError"]), "{r}"); + assert_eq!(r["changed"], json!([]), "{r}"); + assert_eq!((objects(&s, 0), objects(&s, 1)), (1, 1)); +} + +#[test] +fn an_abandoned_run_reports_the_files_it_wrote() { + let path = std::env::temp_dir().join(format!("vc-script-abandon-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let p = path.to_string_lossy().into_owned(); + let mut s = two_docs(); + paused(&mut s, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}")); + assert!(path.exists(), "the first slice exported"); + assert!(s.script_abandon()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}"); + assert!(s.script_failure_text().unwrap().contains(&p)); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn a_run_that_only_closes_a_document_keeps_its_journal_entry() { + let mut s = two_docs(); + let journal = s.journal.len(); + let r = run(&mut s, "vc.run('file.close', {index: 1});").unwrap(); + assert_eq!(r["changed"], json!([]), "{r}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.journal.len(), journal + 1); + assert_eq!(s.journal.iter().last().unwrap().0, "file.close"); +} + +#[test] +fn a_command_that_can_fail_after_copying_has_the_clipboard_put_back() { + let mut s = two_docs(); + let keep_clipboard = |s: &mut Session, id: &str| { + let save = script::Savepoint::take(s, id); + s.clipboard.source_artboard = Some(Default::default()); + save.restore(s); + }; + keep_clipboard(&mut s, "edit.cut"); + assert_eq!(s.clipboard.source_artboard, None, "put back"); + s.clipboard.source_artboard = Some(Default::default()); + keep_clipboard(&mut s, "shape.rectangle"); + assert!(s.clipboard.source_artboard.is_some(), "only those commands pay for a copy of the clipboard"); +} + +#[test] +fn a_commands_savepoint_copies_the_same_number_of_undo_steps_however_long_the_runs_history() { + let copied = |n: usize| { + let mut s = two_docs(); + crate::history::ENTRY_CLONES.with(|c| c.set(0)); + let r = run(&mut s, &format!("for (var i = 0; i < {n}; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});")).unwrap(); + assert_eq!(r["ok"], true); + assert_eq!(objects(&s, 1), n + 1); + crate::history::ENTRY_CLONES.with(Cell::get) + }; + let (few, many) = (copied(20), copied(200)); + // Each command copies at most its document's newest step, whatever the history holds. + assert!(many <= 200 + few, "{few} steps copied for 20 commands, {many} for 200"); +} + +#[test] +fn undo_redo_and_a_long_redo_stack_copy_the_same_number_of_steps_per_command() { + let copied = |n: usize| { + let mut s = two_docs(); + crate::history::ENTRY_CLONES.with(|c| c.set(0)); + let source = format!( + "for (var i = 0; i < {n}; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});\ + for (var i = 0; i < {n}; i++) vc.run('edit.undo');\ + for (var i = 0; i < {n}; i++) vc.run('select.none');\ + for (var i = 0; i < {n}; i++) vc.run('edit.redo');" + ); + let r = run(&mut s, &source).unwrap(); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(objects(&s, 1), n + 1); + crate::history::ENTRY_CLONES.with(Cell::get) + }; + let (few, many) = (copied(20), copied(200)); + // Ten times the commands copy about ten times the steps: each command copies its document's + // newest undo and redo steps, whatever the stacks hold. + assert!(many <= 12 * few, "{few} steps copied for 80 commands, {many} for 800"); +} + +#[test] +fn a_failed_command_gives_back_the_redo_steps_and_an_undo_it_made() { + let mut s = two_docs(); + for x in 1..=3 { + s.execute("shape.rectangle", &rect(x)).unwrap(); + } + for _ in 0..2 { + s.execute("edit.undo", &json!({})).unwrap(); + } + let before = state(&s); + let save = script::Savepoint::take(&mut s, "shape.rectangle"); + s.execute("shape.rectangle", &rect(9)).unwrap(); + assert_eq!(s.documents()[1].history.redo.len(), 0); + assert!(save.restore(&mut s), "the redo steps the new step cleared are put back"); + assert_eq!(state(&s), before); + let save = script::Savepoint::take(&mut s, "edit.undo"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(save.restore(&mut s)); + assert_eq!(state(&s), before); + for _ in 0..2 { + s.execute("edit.redo", &json!({})).unwrap(); + } + assert_eq!(objects(&s, 1), 4); +} + +#[test] +fn a_failed_command_at_the_history_limit_keeps_the_oldest_step() { + let mut s = two_docs(); + s.docs[1].history.limit = 5; + let before = state(&s); + for x in 1..=5 { + s.execute("shape.rectangle", &rect(x)).unwrap(); + } + let save = script::Savepoint::take(&mut s, "shape.rectangle"); + s.execute("shape.rectangle", &rect(9)).unwrap(); + assert!(save.restore(&mut s), "the step the limit would have let go is put back"); + assert_eq!(objects(&s, 1), 6); + for _ in 0..5 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(state(&s)["docs"][1]["art"], before["docs"][1]["art"]); +} + +#[test] +fn a_snapshot_too_large_to_cross_throws_instead_of_reading_as_no_document() { + let mut s = two_docs(); + s.docs[1].path = Some("x".repeat(17 << 20)); + let r = run(&mut s, "var m = ''; try { vc.document; m = 'read'; } catch (e) { m = e.name + ': ' + e.message; } vc.log(m);").unwrap(); + let m = r["log"][0].as_str().unwrap(); + assert!(m.starts_with("RangeError: vc.document.") && m.ends_with("is too large for a script"), "{m}"); +} + +#[test] +fn recovery_copies_made_between_slices_hold_the_art_before_the_run() { + let store = std::sync::Arc::new(cmd::recovery::MemoryStore::default()); + let mut s = two_docs(); + s.recovery.set_store(store.clone()); + paused(&mut s, &format!("{} while (true) {{}}", two_rect_script())); + cmd::recovery::save_copies(&mut s).unwrap(); + s.script_abandon(); + drop(s); + let mut s = Session::new(); + s.recovery.set_store(store); + let r = s.execute("file.recovery.restore", &json!({})).unwrap(); + assert_eq!(r["restored"].as_array().map(Vec::len), Some(2), "{r}"); + assert_eq!((objects(&s, 0), objects(&s, 1)), (1, 1), "the copies hold the art from before the run"); +} + +#[test] +fn values_that_cannot_cross_are_named_and_shared_ones_can() { + let mut s = two_docs(); + let cases = [ + ("var a = {}; a.a = a; vc.run('shape.rectangle', a);", "RangeError|TypeError"), + ("var a = {}, c = a; for (var i = 0; i < 100; i++) { c.n = {}; c = c.n; } vc.run('shape.rectangle', a);", "RangeError|TypeError"), + ("vc.run('shape.rectangle', {x: 1/0});", "RangeError|TypeError"), + ("vc.run('shape.rectangle', {x: function () {}});", "RangeError|TypeError"), + ("vc.run('shape.rectangle', 7);", "TypeError"), + ("vc.run(7);", "TypeError"), + ]; + for (source, kinds) in cases { + let e = run(&mut s, source).unwrap_err().to_string(); + assert!(kinds.split('|').any(|k| e.contains(k)), "{source}: {e}"); + } + let r = run(&mut s, "var p = {w: 5}; vc.log({a: p, b: p}); var l = ''; for (var i = 0; i < 20; i++) l += 'xxxxxxxxxx'; vc.log(l);").unwrap(); + assert_eq!(r["log"][0], json!({"a": {"w": 5}, "b": {"w": 5}})); + assert_eq!(r["log"][1].as_str().unwrap().len(), 200); +} + +#[test] +fn commands_outside_the_documents_are_refused_in_a_batch_too() { + let mut s = two_docs(); + for source in [ + "vc.run('prefs.set', {key: 'a', value: 1});", + "vc.run('script.run', {source: '1'});", + "vc.run('script.stop');", + "vc.run('edit.undoGroup.begin', {});", + "vc.run('view.proofColors', {on: true});", + "vc.run('view.proofSetup', {});", + "vc.run('view.overprintPreview', {on: true});", + "vc.run('view.separationsPreview', {});", + "vc.run('command.batch', {commands: [{command: 'prefs.reset', params: {}}]});", + ] { + let e = run(&mut s, source).unwrap_err().to_string(); + assert!(e.contains("cannot run"), "{source}: {e}"); + } + let r = run(&mut s, "var c = vc.commands; var n = 0; for (var i = 0; i < c.length; i++) if (c[i].id.indexOf('prefs.') === 0) n++; vc.log(n); vc.log(c.length > 100);").unwrap(); + assert_eq!(r["log"], json!([0, true])); +} + +#[test] +fn a_script_cannot_clear_the_undo_steps_from_before_its_run() { + let mut s = two_docs(); + let steps = s.documents()[1].history.undo.len(); + let source = "vc.run('shape.rectangle', {x:9,y:9,width:1,height:1});\ + var m = ''; try { vc.run('edit.clearHistory'); } catch (e) { m = e.message; } vc.log(m);"; + let r = run(&mut s, source).unwrap(); + assert_eq!(r["log"], json!(["a script cannot run `edit.clearHistory`"]), "{r}"); + assert_eq!(s.documents()[1].history.undo.len(), steps + 1); +} + +#[test] +fn the_vc_object_reads_the_active_document_and_cannot_be_changed() { + let mut s = two_docs(); + let r = s + .execute( + "script.run", + &json!({"name": "x", "args": {"n": 2}, "source": "vc.args.n = 9; vc.api.version = 'x'; vc.log(vc.args.n); vc.log(vc.api.version); vc.log(vc.api.has('run')); vc.log(vc.api.has('nope')); vc.log(vc.document.artboards); vc.log(typeof vc.document.path);"}), + ) + .unwrap(); + assert_eq!(r["log"], json!([2, "1.0", true, false, 1, "object"])); + let mut empty = Session::new(); + assert_eq!(run(&mut empty, "vc.log(vc.document === null);").unwrap()["log"], json!([true])); + assert!(run(&mut empty, "vc.run('shape.rectangle', {x:0,y:0,width:1,height:1});").unwrap_err().to_string().contains("Error")); +} + +#[test] +fn the_log_is_bounded_and_a_script_can_catch_that() { + let mut s = two_docs(); + let r = run( + &mut s, + "var n = 0; try { while (true) { vc.log(n); n++; } } catch (e) { vc.run('document.inspect', {}); throw new Error(e.name + ' at ' + n); }", + ); + let e = r.unwrap_err().to_string(); + assert!(e.contains(&format!("RangeError at {}", script::MAX_LOG_LINES)), "{e}"); +} + +#[test] +fn between_slices_every_change_is_refused_and_readers_see_the_committed_art() { + let mut s = two_docs(); + let before = state(&s); + paused(&mut s, &format!("{} while (true) {{}}", two_rect_script())); + assert_eq!(state(&s), before); + for (id, p) in [ + ("shape.rectangle", rect(1)), + ("clipboard.importSvg", json!({})), + ("clipboard.importImage", json!({})), + ("clipboard.importText", json!({})), + ("clipboard.importPdf", json!({})), + ("clipboard.importEmf", json!({})), + ("clipboard.importEps", json!({})), + ("edit.undo", json!({})), + ("file.new", json!({})), + ("file.close", json!({})), + ("file.revert", json!({})), + ("file.recovery.restore", json!({})), + ("action.batch", json!({})), + ("command.batch", json!({"commands": []})), + ("effect.apply", json!({})), + ("script.run", json!({"source": "1"})), + ] { + assert!(matches!(s.execute(id, &p), Err(EngineError::Busy)), "{id}"); + } + assert!(matches!(s.begin_interaction("x"), Err(EngineError::Busy))); + assert!(matches!(s.edit("x", |_, _| Ok(())), Err(EngineError::Busy))); + assert!(matches!(s.preview("shape.rectangle", &rect(1)), Err(EngineError::Busy))); + let press = tools::PointerEvent { + kind: tools::PointerKind::Down, + ..serde_json::from_value(json!({"kind": "move", "pos": {"x": 0.0, "y": 0.0}})).unwrap() + }; + assert!(matches!(s.pointer(&press, ViewInfo::default()), Err(EngineError::Busy))); + let inspected = s.execute("document.inspect", &json!({})).unwrap(); + assert_eq!(inspected["layers"][0]["children"].as_array().map(Vec::len), Some(1), "{inspected}"); + assert_eq!(state(&s), before, "the refused commands changed nothing"); + s.script_abandon(); + assert_eq!(state(&s), before); + assert!(s.execute("shape.rectangle", &rect(1)).unwrap()["id"].is_u64()); +} + +#[test] +fn a_document_closed_or_opened_in_a_run_follows_the_run() { + let closing = "vc.run('file.close', {index: 0}); vc.run('file.new', {}); vc.run('shape.rectangle', {x:1,y:1,width:1,height:1});"; + let mut s = two_docs(); + let before = state(&s); + assert!(run(&mut s, &format!("{closing} throw new Error('x');")).is_err()); + assert_eq!(state(&s), before); + let first = s.documents()[0].uid; + run(&mut s, closing).unwrap(); + assert_eq!(s.documents().len(), 2); + assert!(s.documents().iter().all(|d| d.uid != first)); + assert_eq!(s.documents()[1].history.undo.len(), 0, "a document the script made starts with no undo steps"); +} + +#[test] +fn undo_in_a_run_reaches_only_the_runs_own_steps_and_old_ids_stay_dead() { + let mut s = two_docs(); + let history = s.documents()[1].history.undo.len(); + let source = "var p = vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}).id;\ + vc.run('edit.undo');\ + var q = vc.run('shape.rectangle', {x:2,y:2,width:1,height:1}).id;\ + var why = '';\ + try { vc.run('edit.clear', {ids: [p]}); } catch (e) { why = e.message; }\ + vc.run('edit.undo');\ + try { vc.run('edit.undo'); why += '|undid a step from before the run'; } catch (e) { why += '|stopped'; }\ + vc.log({same: p === q, why: why});\ + vc.run('shape.rectangle', {x:3,y:3,width:1,height:1});"; + let r = run(&mut s, source).unwrap(); + assert_eq!(r["log"][0]["same"], false, "{r}"); + let why = r["log"][0]["why"].as_str().unwrap(); + assert!(why.ends_with("|stopped") && why.len() > "|stopped".len(), "{why}"); + assert_eq!(objects(&s, 1), 2); + assert_eq!(s.documents()[1].history.undo.len(), history + 1); +} + +#[test] +fn a_string_over_the_crossing_limit_does_not_cross() { + let limits = vectorcraft_js::DataLimits { bytes: 20, ..vectorcraft_js::DataLimits::default() }; + assert!(script::to_data(&json!("four"), &limits, 0, &mut (0, 0)).is_ok()); + assert_eq!(script::to_data(&json!("fives"), &limits, 0, &mut (0, 0)), Err(String::new())); +} + +#[test] +fn a_result_too_large_to_cross_names_its_place() { + let limits = vectorcraft_js::DataLimits { bytes: 90, ..vectorcraft_js::DataLimits::default() }; + let v = json!({"a": [1, {"name": "x".repeat(40)}]}); + assert_eq!(script::to_data(&v, &limits, 0, &mut (0, 0)), Err(".a[1].name".to_string())); +} + +#[test] +fn ids_given_out_in_an_abandoned_run_are_not_given_out_again() { + let mut s = two_docs(); + let before = s.active().unwrap().doc.peek_next_id(); + paused(&mut s, &format!("{} while (true) {{}}", two_rect_script())); + assert!(s.script_abandon()); + assert!(s.active().unwrap().doc.peek_next_id() > before); +} + +#[test] +fn ids_given_out_in_a_failed_run_are_not_given_out_again() { + let mut s = two_docs(); + let e = + run(&mut s, "var p = vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}).id; throw new Error('id=' + p + ';');").unwrap_err().to_string(); + let used: u64 = e.split("id=").nth(1).unwrap().split(';').next().unwrap().parse().unwrap(); + let dirty = s.documents()[1].is_dirty(); + let id = s.execute("shape.rectangle", &rect(3)).unwrap()["id"].as_u64().unwrap(); + assert!(id > used, "{id} after {used}"); + assert!(dirty); +} + +#[test] +fn a_rollback_keeps_the_history_after_an_undo_in_the_run() { + let mut s = two_docs(); + let before = state(&s); + let source = "vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); vc.run('edit.undo'); throw new Error('x');"; + assert!(run(&mut s, source).is_err()); + assert_eq!(state(&s), before); +} + +#[test] +fn a_batch_joins_the_runs_one_step() { + let mut s = two_docs(); + let undo = s.documents()[1].history.undo.len(); + let source = "vc.run('command.batch', {commands: [\ + {command:'shape.rectangle', params:{x:1,y:1,width:1,height:1}},\ + {command:'shape.rectangle', params:{x:2,y:2,width:1,height:1}}]});"; + run(&mut s, source).unwrap(); + assert_eq!(s.documents()[1].history.undo.len(), undo + 1); + assert_eq!(objects(&s, 1), 3); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s, 1), 1); +} + +#[test] +fn a_run_with_nobody_to_ask_ends_at_its_growth_allowance() { + TEST_GROWTH.with(|g| g.set(Some(20))); + let mut s = two_docs(); + let before = state(&s); + let source = "try { while (true) vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); } catch (e) { vc.run('shape.rectangle', {x:2,y:1,width:1,height:1}); }"; + let e = run(&mut s, source).unwrap_err().to_string(); + TEST_GROWTH.with(|g| g.set(None)); + assert!(e.contains("objects and data"), "{e}"); + assert_eq!(state(&s), before); +} + +#[test] +fn a_document_a_run_opens_counts_toward_its_growth_allowance() { + TEST_GROWTH.with(|g| g.set(Some(20))); + let rects: String = (0..30).map(|i| format!(r#""#)).collect(); + let svg = format!(r#"{rects}"#); + let data = vectorcraft_format::base64_encode(svg.as_bytes()); + let mut s = two_docs(); + let before = state(&s); + let source = format!("try {{ vc.run('document.open', {{name: 'a.svg', dataBase64: '{data}'}}); }} catch (e) {{}}"); + let e = run(&mut s, &source).unwrap_err().to_string(); + assert!(e.contains("objects and data"), "{e}"); + assert_eq!(state(&s), before); + + // A document whose art is all in a symbol counts it too. + let mut maker = Session::new(); + maker.execute("file.new", &json!({})).unwrap(); + for x in 0..30 { + maker.execute("shape.rectangle", &rect(x)).unwrap(); + } + maker.execute("select.all", &json!({})).unwrap(); + let instance = maker.execute("symbol.new", &json!({"name": "Many"})).unwrap()["id"].as_u64().unwrap(); + maker.execute("edit.clear", &json!({"ids": [instance]})).unwrap(); + assert_eq!(objects(&maker, 0), 0); + let data = maker.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let source = format!("vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}});"); + let e = run(&mut s, &source).unwrap_err().to_string(); + TEST_GROWTH.with(|g| g.set(None)); + assert!(e.contains("objects and data"), "{e}"); + assert_eq!(state(&s), before); +} + +#[test] +fn graph_design_art_counts_toward_the_growth_allowance() { + TEST_GROWTH.with(|g| g.set(Some(20))); + let mut s = two_docs(); + for x in 0..30 { + s.execute("shape.rectangle", &rect(x)).unwrap(); + } + let before = state(&s); + let designs = |s: &Session| s.documents().iter().map(|d| d.doc.graph_designs.len()).collect::>(); + let designs_before = designs(&s); + // A design saved from the selection in an open document. + let e = run(&mut s, "vc.run('select.all'); vc.run('graph.design', {new: 'Many'});").unwrap_err().to_string(); + assert!(e.contains("objects and data"), "{e}"); + assert_eq!(state(&s), before); + assert_eq!(designs(&s), designs_before); + + // A document a run opens whose art is all in a graph design. + let mut maker = Session::new(); + maker.execute("file.new", &json!({})).unwrap(); + let ids: Vec = (0..30).map(|x| maker.execute("shape.rectangle", &rect(x)).unwrap()["id"].as_u64().unwrap()).collect(); + maker.execute("select.all", &json!({})).unwrap(); + maker.execute("graph.design", &json!({"new": "Many"})).unwrap(); + maker.execute("edit.clear", &json!({"ids": ids})).unwrap(); + assert_eq!(objects(&maker, 0), 0); + assert_eq!(maker.documents()[0].doc.graph_designs[0].art.count_with_masks(), 31); + let data = maker.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let source = format!("vc.run('document.open', {{name: 'g.vectorcraft', dataBase64: '{data}'}});"); + let e = run(&mut s, &source).unwrap_err().to_string(); + TEST_GROWTH.with(|g| g.set(None)); + assert!(e.contains("objects and data"), "{e}"); + assert_eq!(state(&s), before); +} + +/// Drops `v` one level at a time. +fn drop_flat(v: Value) { + let mut stack = vec![v]; + while let Some(mut v) = stack.pop() { + match &mut v { + Value::Object(o) => stack.extend(std::mem::take(o).into_iter().map(|(_, x)| x)), + Value::Array(a) => stack.append(a), + _ => {} + } + } +} + +#[test] +fn args_nested_ten_thousand_deep_in_a_script_throw_a_range_error_with_their_place() { + let mut s = two_docs(); + let before = state(&s); + let source = "var v = 1; for (var i = 0; i < 10000; i++) v = {a: v}; var m = 'none'; \ + try { vc.run('script.run', {source: '', args: v}); } catch (e) { m = e.name + '|' + e.message; } vc.log(m);"; + let r = run(&mut s, source).unwrap(); + let m = r["log"][0].as_str().unwrap_or_default(); + assert!(m.starts_with("RangeError|") && m.contains(".args.a.a.a") && m.contains("nested too deep"), "{r}"); + assert_eq!(state(&s), before); +} + +#[test] +fn args_nested_ten_thousand_deep_from_a_caller_are_refused_with_their_place() { + let mut s = two_docs(); + let before = state(&s); + // Built by moving each level in: `json!` would copy the value through `to_value`, one call per level. + let wrap = |key: &str, v: Value| Value::Object(std::iter::once((key.to_string(), v)).collect()); + let mut deep = json!(1); + for _ in 0..10_000 { + deep = wrap("a", deep); + } + let mut params = wrap("args", wrap("b", deep)); + params["source"] = json!(""); + let e = s.execute("script.run", ¶ms).unwrap_err().to_string(); + drop_flat(params); + assert!(e.contains("`args.b.a.a.a") && e.contains("nested more than 64 levels deep"), "{e}"); + assert_eq!(state(&s), before); +} + +#[test] +fn a_person_can_let_a_growing_run_go_on_or_stop_it() { + TEST_GROWTH.with(|g| g.set(Some(20))); + let run_to_the_question = |s: &mut Session| { + s.script_frames = true; + run(s, "for (var i = 0; i < 25; i++) vc.run('shape.rectangle', {x:i,y:1,width:1,height:1});").unwrap(); + let slices = Cell::new(0); + while !s.script_waiting() { + assert!(s.script_pump().is_none()); + slices.set(slices.get() + 1); + assert!(slices.get() < 1_000); + } + // Waiting takes no fuel, however often the frame comes round. + assert!(s.script_pump().is_none()); + }; + let mut s = two_docs(); + run_to_the_question(&mut s); + s.script_continue(); + assert!(!s.script_waiting()); + let done = loop { + if let Some(r) = s.script_pump() { + break r; + } + }; + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(objects(&s, 1), 26); + + let mut s = two_docs(); + let before = state(&s); + run_to_the_question(&mut s); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert!(!s.script_waiting()); + assert!(s.script_pump().unwrap().is_err()); + TEST_GROWTH.with(|g| g.set(None)); + assert_eq!(state(&s), before); +} + +#[test] +fn a_file_saved_before_a_failure_stays_written_and_is_named() { + let path = std::env::temp_dir().join(format!("vc-script-save-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let p = path.to_string_lossy().into_owned(); + let mut s = two_docs(); + let before = state(&s); + let source = + format!("vc.run('file.saveAs', {{path: {p:?}}}); vc.run('shape.rectangle', {{x:1,y:1,width:1,height:1}}); throw new Error('later');"); + let e = run(&mut s, &source).unwrap_err().to_string(); + assert!(path.exists()); + assert!(e.contains(&p), "{e}"); + assert_eq!(s.script_report().unwrap()["written"], json!([p])); + assert_eq!(state(&s), before, "the document does not keep the new path"); + let _ = std::fs::remove_file(&path); +} + +/// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope +/// the frames that advance it run in. +#[test] +fn a_framed_run_keeps_the_file_access_scope_it_started_in() { + let dir = std::env::temp_dir().join(format!("vc-script-scope-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (allowed, outside) = (dir.join("allowed"), dir.join("outside")); + std::fs::create_dir_all(&allowed).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&allowed], &[&allowed]).unwrap().unwrap(); + let export = |target: &std::path::Path| { + let p = target.to_string_lossy().into_owned(); + format!("try {{ vc.run('document.export', {{path: {p:?}, format: 'svg'}}); vc.log('ok'); }} catch (e) {{ vc.log(e.name); }}") + }; + let finish = |s: &mut Session| { + loop { + if let Some(r) = s.script_pump() { + return r; + } + } + }; + let mut s = two_docs(); + s.script_frames = true; + let confined_target = outside.join("confined.svg"); + let started = crate::file_access::confine(Some(&roots), || run(&mut s, &export(&confined_target))).unwrap(); + assert_eq!(started["running"], true); + let r = crate::file_access::unconfined(|| finish(&mut s)).unwrap(); + assert_eq!(r["log"], json!(["Error"]), "a confined caller's run stays confined: {r}"); + assert!(!confined_target.exists()); + let user_target = outside.join("user.svg"); + let started = crate::file_access::unconfined(|| run(&mut s, &export(&user_target))).unwrap(); + assert_eq!(started["running"], true); + let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap(); + assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}"); + assert!(user_target.exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_committed_run_exports_what_it_drew() { + let path = std::env::temp_dir().join(format!("vc-script-export-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let p = path.to_string_lossy().into_owned(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let source = "for (var i = 0; i < 7; i++) vc.run('shape.rectangle', {x:i*20,y:5,width:10,height:10});"; + run(&mut s, source).unwrap(); + s.execute("document.save", &json!({"path": p})).unwrap(); + let svg = std::fs::read_to_string(&path).unwrap(); + assert_eq!(svg.matches(" impl proptest::strategy::Strategy { + use proptest::prelude::*; + let piece = prop_oneof![ + Just("vc.run('shape.rectangle', {x:1,y:1,width:5,height:5});".to_string()), + Just("vc.run('select.all'); vc.run('edit.clear');".to_string()), + Just("vc.run('file.new', {});".to_string()), + Just("vc.run('document.activate', {index:0});".to_string()), + Just("vc.run('no.such');".to_string()), + Just("vc.log(vc.document);".to_string()), + Just("throw new Error('x');".to_string()), + Just("vc.run('shape.rectangle', {x:2,y:2,width:5,height:5}); throw new Error('y');".to_string()), + Just("while (true) {}".to_string()), + Just("var o = {}; o.o = o; vc.run('shape.rectangle', o);".to_string()), + Just("{".to_string()), + Just("try {".to_string()), + Just("} catch (e) {}".to_string()), + "[ -~]{0,30}", + "\\PC{0,10}", + ]; + proptest::collection::vec(piece, 0..12).prop_map(|p| p.concat()) +} + +/// Every field of each open document but its next id, and the rest of what a rollback puts back. +/// A failed run raises the next id past the ids it gave out, which [`next_ids`] reads. +fn saved(s: &Session) -> (Value, Vec) { + let docs = s + .documents() + .iter() + .map(|d| { + let mut doc = (*d.doc).clone(); + doc.raise_next_id(1 << 50); + format!("{doc:?}") + }) + .collect(); + (state(s), docs) +} + +fn next_ids(s: &Session) -> Vec { + s.documents().iter().map(|d| d.doc.peek_next_id()).collect() +} + +proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(48))] + + /// Any script text ends with a report or a script error, and a run that fails leaves every + /// document as it was. + #[test] + fn any_source_ends_with_a_report_or_a_script_error(source in source_text()) { + let mut s = two_docs(); + let (before, ids) = (saved(&s), next_ids(&s)); + match s.execute("script.run", &json!({"source": source, "maxFuel": 200_000})) { + Ok(r) => proptest::prop_assert_eq!(&r["ok"], &json!(true), "{}", r), + Err(e) => { + proptest::prop_assert!(matches!(e, EngineError::Other(_)), "{:?}", e); + let kind = s.script_report.as_ref().map(|r| r["kind"].clone()); + proptest::prop_assert!(kind.as_ref().is_some_and(|k| k != "internal"), "{:?}: {}", kind, e); + proptest::prop_assert_eq!(saved(&s), before); + proptest::prop_assert!(next_ids(&s).iter().zip(&ids).all(|(after, was)| after >= was), "{:?} after {:?}", next_ids(&s), ids); + } + } + } +} diff --git a/crates/engine/src/tests/spelling.rs b/crates/engine/src/tests/spelling.rs index 0dfc9fab5a..16d7f01993 100644 --- a/crates/engine/src/tests/spelling.rs +++ b/crates/engine/src/tests/spelling.rs @@ -6,6 +6,14 @@ use serde_json::{Value, json}; use crate::cmd::spelling::MAX_DICTIONARY_FILE_BYTES; use crate::*; +/// Held by each test that changes the custom dictionary, which the whole process shares: a save +/// writes every word in it to the test's file and a reload takes the file's words back, so another +/// test's word could come back after that test deleted it. +fn dictionary_lock() -> std::sync::MutexGuard<'static, ()> { + static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// A session with a new 400 × 400 document. fn session() -> Session { let mut s = Session::new(); @@ -115,6 +123,7 @@ fn marked(s: &mut Session) -> Vec { #[test] fn added_words_are_right_in_every_check_until_deleted() { + let _one_at_a_time = dictionary_lock(); let mut s = session(); text(&mut s, 50.0, "drawing Zqvwkx tools"); assert_eq!(marked(&mut s), ["Zqvwkx"]); @@ -137,6 +146,7 @@ fn added_words_are_right_in_every_check_until_deleted() { #[test] fn a_changed_word_replaces_the_old_one() { + let _one_at_a_time = dictionary_lock(); let mut s = session(); text(&mut s, 50.0, "xkvzqa xkvzqb"); run(&mut s, "text.spelling.addWord", json!({"word": "xkvzqa"})); @@ -150,6 +160,7 @@ fn a_changed_word_replaces_the_old_one() { #[test] fn the_custom_dictionary_file_is_read_and_kept_up_to_date() { + let _one_at_a_time = dictionary_lock(); let dir = vectorcraft_testkit::temp_dir("spelling-dictionary"); let file = dir.join("Custom Dictionary.txt"); std::fs::write(&file, "kqzvwx\nnot one word\n\n").unwrap(); @@ -170,6 +181,7 @@ fn the_custom_dictionary_file_is_read_and_kept_up_to_date() { #[test] fn ignore_all_skips_a_word_in_the_active_document_only() { + let _one_at_a_time = dictionary_lock(); let mut s = session(); text(&mut s, 50.0, "Wqzxkv drawing wqzxkv vqzxkw"); run(&mut s, "text.spelling.ignoreAll", json!({"word": "WQZXKV"})); @@ -183,6 +195,7 @@ fn ignore_all_skips_a_word_in_the_active_document_only() { #[test] fn custom_dictionary_commands_refuse_what_isnt_one_word() { + let _one_at_a_time = dictionary_lock(); let mut s = session(); let long = "q".repeat(65); for (id, p) in [ @@ -210,6 +223,7 @@ fn in_dictionary(s: &mut Session, word: &str) -> bool { #[test] fn a_dictionary_file_that_cant_be_read_whole_is_never_written_over() { + let _one_at_a_time = dictionary_lock(); let dir = vectorcraft_testkit::temp_dir("spelling-unreadable"); // A folder where the file should be can't be read as one; a file past what craft-proof reads // would lose its other words if written back. @@ -231,6 +245,7 @@ fn a_dictionary_file_that_cant_be_read_whole_is_never_written_over() { #[test] fn a_change_that_cant_be_saved_is_taken_back() { + let _one_at_a_time = dictionary_lock(); let mut s = session(); run(&mut s, "text.spelling.addWord", json!({"word": "wkqzvx"})); let dir = vectorcraft_testkit::temp_dir("spelling-rollback"); @@ -245,9 +260,47 @@ fn a_change_that_cant_be_saved_is_taken_back() { run(&mut s, "text.spelling.removeWord", json!({"word": "wkqzvx"})); } +/// Edit Custom Dictionary's Done: its deletes and adds are saved together, or, when the save +/// fails, none of them is kept (a delete saved before an add that failed would stay otherwise). +#[test] +fn a_dictionary_edit_is_saved_whole_or_not_at_all() { + let _one_at_a_time = dictionary_lock(); + const EDIT: &str = "text.spelling.editDictionary"; + let dir = vectorcraft_testkit::temp_dir("spelling-edit"); + let file = dir.join("Custom Dictionary.txt"); + std::fs::write(&file, "pqzvka\npqzvkb\n").unwrap(); + let mut s = session(); + s.attach_custom_dictionary(file.clone()); + // A word already gone and a word already there are skipped; added words are kept in lower case. + let r = run(&mut s, EDIT, json!({"remove": ["pqzvka", "pqzvkz"], "add": ["PqzvkC", "pqzvkb"]})); + assert_eq!(r, json!({"removed": ["pqzvka"], "added": ["pqzvkc"]})); + let saved = std::fs::read_to_string(&file).unwrap(); + let lines: Vec<&str> = saved.lines().collect(); + assert!(lines.contains(&"pqzvkb") && lines.contains(&"pqzvkc") && !lines.contains(&"pqzvka"), "{saved}"); + // A save that fails takes back every delete and add. + let folder = dir.join("folder"); + std::fs::create_dir_all(&folder).unwrap(); + let mut failing = session(); + failing.attach_custom_dictionary(folder); + assert!(failing.execute(EDIT, &json!({"remove": ["pqzvkb", "pqzvkc"], "add": ["pqzvkd"]})).is_err()); + assert!(in_dictionary(&mut s, "pqzvkb") && in_dictionary(&mut s, "pqzvkc"), "the deletes are taken back"); + assert!(!in_dictionary(&mut s, "pqzvkd"), "the add is taken back"); + // A list that isn't one of words is refused before anything changes. + let many: Vec = (0..10_001).map(|i| format!("pqzv{i}")).collect(); + for p in [json!({"remove": "pqzvkb"}), json!({"add": ["a b"]}), json!({"add": [5]}), json!({"remove": ["pqzvkb"], "add": many})] { + assert!(s.execute(EDIT, &p).is_err(), "{EDIT} refuses a bad list"); + assert!(in_dictionary(&mut s, "pqzvkb"), "{EDIT} changed nothing"); + } + let e = s.execute(EDIT, &json!({"add": ["a b"]})).unwrap_err().to_string(); + assert!(e.contains("must hold single words of at most 64 characters"), "{e}"); + run(&mut s, EDIT, json!({"remove": ["pqzvkb", "pqzvkc"]})); + assert!(!in_dictionary(&mut s, "pqzvkb") && !in_dictionary(&mut s, "pqzvkc")); +} + #[cfg(unix)] #[test] fn a_word_another_window_saved_stays_when_this_save_fails() { + let _one_at_a_time = dictionary_lock(); use std::os::unix::fs::PermissionsExt; let dir = vectorcraft_testkit::temp_dir("spelling-readonly"); let file = dir.join("Custom Dictionary.txt"); @@ -296,6 +349,7 @@ fn misspellings_of_one_object_are_what_the_check_lists() { /// what Auto Spell Check found before is checked again. #[test] fn custom_dictionary_changes_move_its_generation_on() { + let _one_at_a_time = dictionary_lock(); use crate::cmd::spelling::dictionary_generation; let mut s = session(); let mut last = dictionary_generation(); diff --git a/crates/engine/src/tests/stylelib.rs b/crates/engine/src/tests/stylelib.rs index 6a93b80a3d..43838ff8e0 100644 --- a/crates/engine/src/tests/stylelib.rs +++ b/crates/engine/src/tests/stylelib.rs @@ -38,10 +38,11 @@ fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { #[test] fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() { - let mut s = Session::new(); + let mut s = session(); let list = run(&mut s, "graphicStyle.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); - assert!(libs.len() >= 6 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}"); + assert!(libs.len() >= 7 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}"); + assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}"); for l in libs { let id = l["id"].as_str().unwrap(); let g = run(&mut s, "graphicStyle.library", json!({"library": id})); @@ -56,6 +57,16 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() } } } + let game = run(&mut s, "graphicStyle.library", json!({"library": "game-hud"})); + let game_names: Vec<&str> = game["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(game_names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]); + let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "game-hud", "name": "Mana Glow", "apply": true, "ids": [id.0]})); + assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec!["Mana Glow"], Some("Mana Glow"))); + let node = doc(&s).node(id).unwrap(); + assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#3498db").unwrap())); + assert_eq!(node.appearance.stroke_paint(), Paint::None); + assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.outerGlow"]); // By name in any case. assert_eq!(run(&mut s, "graphicStyle.library", json!({"library": "shadows and glows"}))["id"], "shadows-glows"); assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err()); @@ -251,11 +262,16 @@ fn every_builtin_style_paints_visibly_on_a_rectangle() { let (_, lib) = cmd::stylelib::library(&s, b.id).unwrap(); for g in &lib.styles { run(&mut s, "file.new", json!({"width": 100, "height": 100})); + // Art under the rectangle: a blend mode shows only against art, not the bare page. + let under = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + run(&mut s, "paint.setFill", json!({"color": "#336699", "ids": [under.0]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [under.0]})); let id = rect(&mut s, 25.0, 30.0, 50.0, 40.0); run(&mut s, "graphicStyle.addFromLibrary", json!({"library": b.id, "name": g.name, "apply": true})); assert_eq!(doc(&s).node(id).unwrap().extras().graphic_style, doc(&s).graphic_style(&g.name).map(|x| x.id), "{}", g.name); let img = renderer.render_region(doc(&s), Rect::new(0.0, 0.0, 100.0, 100.0), 0.5, true); - let painted = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[..3] != [255, 255, 255]).count(); + let bare = img.pixel(0, 0); + let painted = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.pixel(x, y) != bare).count(); assert!(painted > 40, "{} / {} paints {painted} pixels", b.id, g.name); } } diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index 42909da1c7..410bd473da 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -84,12 +84,16 @@ fn the_builtin_library_is_original_art_generated_in_code() { let mut s = Session::new(); let list = run(&mut s, "symbol.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); - assert_eq!(libs.len(), 2, "{libs:?}"); + assert_eq!(libs.len(), 3, "{libs:?}"); assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn"))); assert_eq!( (libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()), (Some("ui-frames"), Some("UI Frames"), Some("builtIn")) ); + assert_eq!( + (libs[2]["id"].as_str(), libs[2]["name"].as_str(), libs[2]["category"].as_str()), + (Some("map-markers"), Some("Map Markers"), Some("builtIn")) + ); let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"})); let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); assert_eq!(names, ["Circle", "Square", "Rounded Square", "Triangle", "Diamond", "Hexagon", "Star", "Burst", "Arrow"]); @@ -125,6 +129,32 @@ fn ui_frames_symbols_carry_default_nine_slice_when_added() { )); } +#[test] +fn map_markers_symbols_add_without_nine_slice() { + let mut s = session(); + let lib = run(&mut s, "symbol.library", json!({"library": "map-markers"})); + let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Pin", "Flag", "Crosshair", "Checkpoint"]); + let mut placed = Vec::new(); + for (i, name) in names.iter().enumerate() { + let r = run( + &mut s, + "symbol.addFromLibrary", + json!({"library": "map-markers", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}), + ); + assert_eq!(r["added"], json!([name])); + placed.push(r["placed"].as_u64().unwrap()); + } + let d = doc(&s); + for name in &names { + assert_eq!(d.symbol_nine_slice(name), None, "{name} should not carry 9-slice guides"); + } + assert!(matches!( + d.node(NodeId(placed[0])).map(|n| &n.kind), + Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == "Pin" + )); +} + #[test] fn a_saved_library_reopens_and_its_symbols_join_another_document_in_one_step() { let dir = folder("user"); diff --git a/crates/engine/src/tests/trap.rs b/crates/engine/src/tests/trap.rs index b2ae099083..aa0a1a75d5 100644 --- a/crates/engine/src/tests/trap.rs +++ b/crates/engine/src/tests/trap.rs @@ -138,15 +138,35 @@ fn no_adjoining_edges_is_a_clear_error_that_changes_nothing() { } #[test] -fn out_of_range_and_unreadable_numbers_are_refused_or_defaulted() { +fn out_of_range_and_unreadable_numbers_are_refused() { let (mut s, _, _) = abutting(); + let before = s.doc().unwrap().doc.clone(); + let undo_len = s.doc().unwrap().history.undo.len(); for p in [json!({"thickness": 1e300}), json!({"thickness": 0}), json!({"heightWidth": 0}), json!({"tintReduction": 101})] { assert!(s.execute("object.pathfinder.trap", &p).is_err(), "{p}"); } - // A thickness that isn't a number falls back to the default. - let r = s.execute("object.pathfinder.trap", &json!({"thickness": "NaN", "tintReduction": 100})).unwrap(); + // A value of the wrong type is refused with an error naming the param, and changes nothing. + for (p, want) in [ + (json!({"thickness": "NaN"}), "`thickness` must be a number, not \"NaN\""), + (json!({"thickness": true}), "`thickness` must be a number, not true"), + (json!({"heightWidth": [100]}), "`heightWidth` must be a number, not [100]"), + (json!({"tintReduction": false}), "`tintReduction` must be a number, not false"), + (json!({"trapsWithProcessColor": "yes"}), "`trapsWithProcessColor` must be true or false"), + (json!({"reverseTraps": 1}), "`reverseTraps` must be true or false"), + ] { + let r = s.execute("object.pathfinder.trap", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}"); + } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); + // Null keeps the default thickness, 0.25 pt; a thickness with a unit is read as a distance. + let r = s.execute("object.pathfinder.trap", &json!({"thickness": null, "reverseTraps": null, "tintReduction": 100})).unwrap(); let bb = traps(&s, &r)[0].geometric_bounds().unwrap(); assert!(near(bb.x1, 50.25), "{bb:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("object.pathfinder.trap", &json!({"thickness": "0.1 in", "tintReduction": 100})).unwrap(); + let bb = traps(&s, &r)[0].geometric_bounds().unwrap(); + assert!(near(bb.x1, 57.2), "{bb:?}"); } #[test] diff --git a/crates/engine/src/tests/typeglyphbounds.rs b/crates/engine/src/tests/typeglyphbounds.rs new file mode 100644 index 0000000000..0ebd61738f --- /dev/null +++ b/crates/engine/src/tests/typeglyphbounds.rs @@ -0,0 +1,349 @@ +//! Preferences › Type › Measure Type by Glyph Bounds (`typeGlyphBounds`): the bounding box, the +//! Transform panel's values and `object.setBounds` measure each point type object selected as an +//! object (not inside a selected group) by the ink of its glyphs instead of its em box. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind, OrientedBox, TextObject}; +use vectorcraft_geom::Rect; + +use crate::*; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn id(v: Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +/// A new document holding point type made by `text.create` with `params`, selected. +fn with_type(params: Value) -> (Session, NodeId) { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 800, "height": 800})); + let t = id(run(&mut s, "text.create", params)); + run(&mut s, "select.set", json!({"ids": [t.0]})); + (s, t) +} + +fn glyphs(s: &mut Session, on: bool) { + run(s, "prefs.set", json!({"values": {"typeGlyphBounds": on}})); +} + +fn text(s: &Session, id: NodeId) -> TextObject { + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("{id:?} is not type") }; + (**t).clone() +} + +/// The ink of the type's glyphs on the page, laid out afresh (not from the cache). +fn ink(s: &Session, id: NodeId) -> Rect { + let t = text(s, id); + t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap()) +} + +/// The em box (the line box) of point type: what the bounding box measures by default. +fn em(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap() +} + +fn near(a: Rect, b: Rect, tol: f64) -> bool { + (a.x0 - b.x0).abs() <= tol && (a.y0 - b.y0).abs() <= tol && (a.x1 - b.x1).abs() <= tol && (a.y1 - b.y1).abs() <= tol +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The glyph box of `c` in Inter Regular, in font units (x min, y min, x max, y max), and the +/// font's units per em, read from the font file's own `head`, `cmap`, `loca` and `glyf` tables. +fn inter_glyph_box(c: char) -> ([f64; 4], f64) { + use skrifa::MetadataProvider; + use skrifa::raw::TableProvider; + let font = skrifa::FontRef::new(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")).unwrap(); + let upem = f64::from(font.head().unwrap().units_per_em()); + let gid = font.charmap().map(c).unwrap(); + let glyph = font.loca(None).unwrap().get_glyf(gid, &font.glyf().unwrap()).unwrap().unwrap(); + ([glyph.x_min(), glyph.y_min(), glyph.x_max(), glyph.y_max()].map(f64::from), upem) +} + +/// "H" in Inter at 100 pt is drawn with straight lines only, so the box of its outline is the glyph +/// box the font file stores: the bounding box takes its size and place from the font itself. +#[test] +fn point_type_measures_the_glyph_box_the_font_file_stores() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "font": "Inter", "text": "H"})); + glyphs(&mut s, true); + let ([x0, y0, x1, y1], upem) = inter_glyph_box('H'); + let k = 100.0 / upem; + let b = s.transform_box(&[t]).unwrap(); + assert_eq!(b.angle, 0.0); + // Text space runs down the page from the baseline at y = 300. + let want = Rect::new(100.0 + x0 * k, 300.0 - y1 * k, 100.0 + x1 * k, 300.0 - y0 * k); + assert!(near(b.rect, want, 1e-6), "{:?} != {want:?}", b.rect); + assert!(near(s.transform_bounds(&[t]).unwrap(), want, 1e-6)); + // The em box is taller than the cap height. + assert!(em(&s, t).height() > b.rect.height() + 10.0, "em box {:?}", em(&s, t)); +} + +#[test] +fn off_by_default_the_box_is_the_em_box() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + assert!(!s.prefs.type_glyph_bounds); + assert_eq!(s.transform_box(&[t]).unwrap().rect, em(&s, t)); + glyphs(&mut s, true); + assert!(near(s.transform_box(&[t]).unwrap().rect, ink(&s, t), 1e-9)); + glyphs(&mut s, false); + assert_eq!(s.transform_box(&[t]).unwrap().rect, em(&s, t)); +} + +/// A typed height scales the type so its ink takes that height, in one undo step, and the type +/// stays type. +#[test] +fn set_bounds_gives_the_ink_the_typed_size() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + glyphs(&mut s, true); + let xf = text(&s, t).xf; + let n = undo_len(&s); + run(&mut s, "object.setBounds", json!({"height": 50})); + assert_eq!(undo_len(&s), n + 1); + assert!((ink(&s, t).height() - 50.0).abs() < 1e-6, "{:?}", ink(&s, t)); + assert!(near(s.transform_box(&[t]).unwrap().rect, ink(&s, t), 1e-6)); + assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_))); + run(&mut s, "edit.undo", json!({})); + assert_eq!(text(&s, t).xf, xf); +} + +/// A typed X moves the ink box's reference point there and keeps its size; a typed width gives +/// the ink that width. +#[test] +fn set_bounds_moves_and_sizes_the_ink_box() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + glyphs(&mut s, true); + let before = ink(&s, t); + run(&mut s, "object.setBounds", json!({"x": 400, "reference": 0})); + let moved = ink(&s, t); + assert!((moved.x0 - 400.0).abs() < 1e-6 && (moved.y0 - before.y0).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - before.width()).abs() < 1e-6 && (moved.height() - before.height()).abs() < 1e-6, "{moved:?}"); + run(&mut s, "object.setBounds", json!({"width": 123})); + assert!((ink(&s, t).width() - 123.0).abs() < 1e-6, "{:?}", ink(&s, t)); + assert!((ink(&s, t).height() - before.height()).abs() < 1e-6, "{:?}", ink(&s, t)); +} + +/// The font size the panels show follows the vertical scale: a typed width alone changes the +/// horizontal scale and keeps the font size, and a typed height alone changes the font size and +/// keeps the width, so the horizontal scale changes the other way. +#[test] +fn a_typed_width_changes_the_horizontal_scale_and_a_typed_height_the_font_size() { + let shown = |s: &Session, t: NodeId| { + let o = text(s, t); + let st = o.effective_char_style(&o.runs[0].style).unwrap(); + (st.size, st.h_scale) + }; + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + glyphs(&mut s, true); + let before = ink(&s, t); + run(&mut s, "object.setBounds", json!({"width": before.width() * 2.0})); + let (size, h_scale) = shown(&s, t); + assert!((size - 100.0).abs() < 1e-6 && (h_scale - 200.0).abs() < 1e-6, "{size} pt at {h_scale}%"); + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + glyphs(&mut s, true); + run(&mut s, "object.setBounds", json!({"height": before.height() * 2.0})); + let (size, h_scale) = shown(&s, t); + assert!((size - 200.0).abs() < 1e-6 && (h_scale - 50.0).abs() < 1e-6, "{size} pt at {h_scale}%"); + assert!((ink(&s, t).width() - before.width()).abs() < 1e-6, "{:?}", ink(&s, t)); +} + +#[test] +fn set_bounds_with_the_current_values_records_no_undo_step() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + glyphs(&mut s, true); + let b = s.transform_box(&[t]).unwrap().rect; + let n = undo_len(&s); + run(&mut s, "object.setBounds", json!({"x": b.center().x, "y": b.center().y, "width": b.width(), "height": b.height()})); + assert_eq!(undo_len(&s), n); + assert_eq!(s.transform_box(&[t]).unwrap().rect, b); +} + +/// A proportional width scales both sides of the ink by the same factor, about the reference +/// point of the ink box (here its top-left corner). +#[test] +fn proportional_width_keeps_the_ink_in_proportion_about_the_reference_point() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + glyphs(&mut s, true); + let before = ink(&s, t); + run(&mut s, "object.setBounds", json!({"width": before.width() * 2.0, "proportional": true, "reference": 0})); + let after = ink(&s, t); + assert!((after.width() - before.width() * 2.0).abs() < 1e-6, "{after:?}"); + assert!((after.height() - before.height() * 2.0).abs() < 1e-6, "{after:?}"); + assert!((after.x0 - before.x0).abs() < 1e-6 && (after.y0 - before.y0).abs() < 1e-6, "{before:?} -> {after:?}"); +} + +/// Rotated type keeps its own angle, and the box is the size of the ink before the rotation. A +/// skewed object's box is the box of its glyph outlines, not of its mapped ink rectangle. +#[test] +fn rotated_and_skewed_type_measure_their_outlines() { + let (mut s, flat) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + glyphs(&mut s, true); + let size = s.transform_box(&[flat]).unwrap().rect.size(); + let t = id(run(&mut s, "text.create", json!({"x": 300, "y": 300, "size": 100, "text": "Hg", "rotation": 30}))); + let b = s.transform_box(&[t]).unwrap(); + assert_eq!(b.angle, s.doc().unwrap().doc.oriented_bounds(&[t], false).unwrap().angle); + assert!(b.angle != 0.0); + assert!((b.rect.width() - size.width).abs() < 1e-6 && (b.rect.height() - size.height).abs() < 1e-6, "{b:?} vs {size:?}"); + + let o = id(run(&mut s, "text.create", json!({"x": 100, "y": 600, "size": 100, "text": "o"}))); + run(&mut s, "select.set", json!({"ids": [o.0]})); + run(&mut s, "object.transform", json!({"matrix": [1, 0, 0.6, 1, -360, 0]})); + let b = s.transform_box(&[o]).unwrap(); + let tx = text(&s, o); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx); + let to_local = OrientedBox { angle: b.angle, rect: Rect::ZERO }.to_doc().inverse(); + let want = lay.ink_bounds_in(to_local * tx.xf).unwrap(); + assert!(near(b.rect, want, 1e-9), "{:?} != {want:?}", b.rect); + let mapped = (to_local * tx.xf).transform_rect_bbox(lay.ink_bounds().unwrap()); + assert!(mapped.width() > b.rect.width() + 1.0, "a round letter's outline is narrower than its slanted box"); +} + +/// Type that draws nothing is measured by its em box. +#[test] +fn empty_and_space_only_type_keep_the_em_box() { + for text in ["", " "] { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 40, "text": text})); + glyphs(&mut s, true); + assert_eq!(s.transform_box(&[t]).unwrap().rect, em(&s, t), "{text:?}"); + } +} + +/// Area type keeps its frame, and type on a path its path. +#[test] +fn area_type_and_type_on_a_path_are_measured_as_before() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 800, "height": 800})); + let area = id(run(&mut s, "text.create", json!({"x": 100, "y": 100, "size": 24, "text": "ace", "area": {"width": 200, "height": 100}}))); + let line = id(run(&mut s, "shape.line", json!({"x1": 100, "y1": 400, "x2": 500, "y2": 400}))); + let path = id(run(&mut s, "text.createInPath", json!({"path": line.0, "mode": "onPath", "text": "ace", "size": 24}))); + for t in [area, path] { + let off = s.transform_box(&[t]).unwrap(); + glyphs(&mut s, true); + assert_eq!(s.transform_box(&[t]).unwrap(), off, "{t:?}"); + glyphs(&mut s, false); + } +} + +#[test] +fn vertical_point_type_measures_its_ink() { + let (mut s, t) = with_type(json!({"x": 100, "y": 100, "size": 60, "text": "ace", "vertical": true})); + glyphs(&mut s, true); + let b = s.transform_box(&[t]).unwrap().rect; + assert!(near(b, ink(&s, t), 1e-9), "{b:?} != {:?}", ink(&s, t)); + assert!(em(&s, t).width() > b.width() + 1.0, "em box {:?}", em(&s, t)); +} + +/// With Use Preview Bounds, the characters' strokes paint around the glyphs. +#[test] +fn preview_bounds_add_the_character_strokes_to_the_ink() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + run(&mut s, "text.setStyle", json!({"ids": [t.0], "stroke": "#000000", "strokeWidth": 6})); + run(&mut s, "prefs.set", json!({"values": {"typeGlyphBounds": true, "usePreviewBounds": true}})); + let o = text(&s, t).char_stroke_outset(); + assert!(o > 0.0); + let b = s.transform_box(&[t]).unwrap().rect; + assert!(near(b, ink(&s, t).inflate(o, o), 1e-9), "{b:?}"); + // A typed height is the height with the strokes. + run(&mut s, "object.setBounds", json!({"height": 80})); + assert!((s.transform_box(&[t]).unwrap().rect.height() - 80.0).abs() < 1e-6, "{:?}", s.transform_box(&[t])); +} + +/// Type inside a selected group is measured as before: the group's box does not change. +#[test] +fn a_group_holding_type_keeps_its_box() { + let (mut s, _) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + let g = id(run(&mut s, "object.group", json!({}))); + let off = s.transform_box(&[g]).unwrap(); + glyphs(&mut s, true); + assert_eq!(s.transform_box(&[g]).unwrap(), off); +} + +/// Runs in two fonts: the box covers the ink of both, and follows an edit of the type. +#[test] +fn mixed_fonts_measure_the_ink_of_every_run() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hgxo"})); + glyphs(&mut s, true); + run(&mut s, "text.setRangeStyle", json!({"id": t.0, "font": "Source Serif 4", "start": 2, "end": 4})); + let tx = text(&s, t); + assert!(tx.runs.iter().any(|r| r.style.font_family == "Source Serif 4") && tx.runs.len() > 1, "{:?}", tx.runs); + assert!(tx.ink().is_some(), "the edit refreshed the cached ink"); + assert!(near(s.transform_box(&[t]).unwrap().rect, ink(&s, t), 1e-9)); +} + +/// A selection of type and a shape is measured by the type's ink and the shape's bounds. +#[test] +fn a_mixed_selection_takes_the_ink_and_the_shapes_bounds() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + let r = id(run(&mut s, "shape.rectangle", json!({"x": 500, "y": 500, "width": 50, "height": 50}))); + glyphs(&mut s, true); + assert!(near(s.transform_bounds(&[t, r]).unwrap(), ink(&s, t).union(Rect::new(500.0, 500.0, 550.0, 550.0)), 1e-9)); +} + +#[test] +fn the_preference_is_checked_and_saved() { + let mut s = Session::new(); + assert!(s.execute("prefs.set", &json!({"values": {"typeGlyphBounds": "yes"}})).is_err()); + assert!(!s.prefs.type_glyph_bounds); + assert!(!serde_json::from_value::(json!({})).unwrap().type_glyph_bounds); + run(&mut s, "prefs.set", json!({"key": "typeGlyphBounds", "value": true})); + let saved = serde_json::to_value(&s.prefs).unwrap(); + assert_eq!(saved["typeGlyphBounds"], json!(true)); + assert!(serde_json::from_value::(saved).unwrap().type_glyph_bounds); + assert_eq!(run(&mut s, "prefs.get", json!({"key": "typeGlyphBounds"})), json!(true)); +} + +/// The preference is not part of the document: a saved document is the same with it on or off. +#[test] +fn saved_documents_do_not_depend_on_the_preference() { + let (mut s, _) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + let off = serde_json::to_string(&s.doc().unwrap().doc).unwrap(); + assert!(!off.contains("cached_ink") && !off.contains("cachedInk"), "the cached ink is not saved"); + glyphs(&mut s, true); + assert_eq!(serde_json::to_string(&s.doc().unwrap().doc).unwrap(), off); +} + +/// What the type draws on the page: its glyphs and its underline and strikethrough bars. +fn drawn(s: &Session, id: NodeId) -> Rect { + let t = text(s, id); + vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap() +} + +/// Underline and strikethrough bars are drawn with the type, so the box takes them in and a typed +/// height gives what is drawn that height. Underlined spaces are measured by their bar. +#[test] +fn underline_and_strikethrough_bars_count_as_ink() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "H"})); + run(&mut s, "text.setRangeStyle", json!({"id": t.0, "start": 0, "end": 1, "underline": true})); + glyphs(&mut s, true); + let b = s.transform_box(&[t]).unwrap().rect; + assert!(near(b, drawn(&s, t), 1e-9), "{b:?} != {:?}", drawn(&s, t)); + assert!(b.y1 > ink(&s, t).y1 + 1.0, "the underline hangs below the glyph"); + run(&mut s, "object.setBounds", json!({"height": 50})); + assert!((drawn(&s, t).height() - 50.0).abs() < 1e-6, "{:?}", drawn(&s, t)); + assert!(near(s.transform_box(&[t]).unwrap().rect, drawn(&s, t), 1e-6)); + + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 40, "text": " "})); + run(&mut s, "text.setRangeStyle", json!({"id": t.0, "start": 0, "end": 3, "strikethrough": true})); + glyphs(&mut s, true); + let b = s.transform_box(&[t]).unwrap().rect; + assert!(near(b, drawn(&s, t), 1e-9), "{b:?} != {:?}", drawn(&s, t)); + assert!(em(&s, t).height() > b.height() + 10.0, "em box {:?}", em(&s, t)); +} + +/// A transform of type keeps its cached ink, which is in text space. +#[test] +fn the_cached_ink_is_the_laid_out_ink() { + let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"})); + let tx = text(&s, t); + assert_eq!(tx.ink(), Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx).ink_bounds())); + run(&mut s, "object.transform", json!({"matrix": [2, 0, 0, 3, 0, 0]})); + assert_eq!(text(&s, t).ink(), tx.ink()); + // A cache measured with other bounds is not read. + let mut stale = text(&s, t); + stale.cached_bounds = Some(Rect::new(0.0, 0.0, 1.0, 1.0)); + assert_eq!(stale.ink(), None); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index d8b32eab72..3f364c2ce6 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -365,6 +365,7 @@ impl Session { freeform_point: self.selected_freeform_point(), raster_sample: self.prefs.eyedropper.sample_size, preview_bounds: self.prefs.use_preview_bounds, + glyph_bounds: self.prefs.type_glyph_bounds, preview_memo: Some(&self.preview_memo), unit, stroke_unit, @@ -455,6 +456,9 @@ impl Session { /// applied, in order ([`Session::tool_poll`]); moves of the pointer with no button held go to /// the tool at once. pub fn pointer(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result> { + if self.script_running() { + return if ev.kind == PointerKind::Move { Ok(vec![]) } else { Err(EngineError::Busy) }; + } let n = self.next_input(); if ev.kind != PointerKind::Move && (!self.held_input.is_empty() || self.tool_edit_pending()) { self.held_input.push_back((n, HeldInput::Pointer(*ev), view)); @@ -877,6 +881,9 @@ impl Session { /// A key for the active tool. While the tool computes an edit on another thread, the key is held /// and made once the edit is applied, after the input held before it. pub fn tool_key(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> Result> { + if self.script_running() { + return Err(EngineError::Busy); + } let n = self.next_input(); if self.tool_editing() { self.held_input.push_back((n, HeldInput::Key(key, mods), view)); @@ -910,6 +917,9 @@ impl Session { /// Typed text for the active tool (Type tool). pub fn tool_text(&mut self, text: &str, view: ViewInfo) -> Result> { + if self.script_running() { + return Err(EngineError::Busy); + } let acts = self.with_tool_cx(view, |t, cx| t.text_input(cx, text)); self.take_tool_panic()?; self.apply_actions(acts) @@ -1059,6 +1069,12 @@ impl Session { self.plane_key(key).is_some() || self.with_tool_cx(view, |t, cx| t.claims_key(cx, key)) } + /// Has the active tool started something that Escape ends while no button is pressed (see + /// `Tool::ends_on_escape`)? + pub fn tool_ends_on_escape(&mut self, view: ViewInfo) -> bool { + self.with_tool_cx(view, |t, cx| t.ends_on_escape(cx)) + } + pub fn overlays(&mut self, view: ViewInfo) -> Vec { // The Blend tool's first pick is not marked after an edit that dropped it. self.tell_tool_history_moved(); @@ -1282,6 +1298,9 @@ impl Session { let outer = std::mem::replace(&mut self.in_tool_actions, true); let r = self.apply_tool_actions(acts); self.in_tool_actions = outer; + if !outer && self.depth == 0 { + self.trim_histories(); + } r } diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index d97560af30..0cc0edc4d4 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -9,6 +9,7 @@ use serde_json::json; use vectorcraft_color::cms; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::colormgmt::{PROFILES_KEY, doc_profiles}; +use vectorcraft_engine::store::MAX_PRESET_FILE; use vectorcraft_geom::Affine; use vectorcraft_render::{RenderOptions, Renderer}; use vectorcraft_testkit::fixtures::{exec, id_of, rect, select, session}; @@ -426,3 +427,108 @@ fn loading_the_working_rgb_profile_again_takes_effect_at_once() { assert!(after.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), "after the reload {after:?}, want {want:?}"); assert!(redrawn, "the canvas redraws"); } + +/// A folder of its own for the test `tag`, empty. +fn fresh_dir(tag: &str) -> std::path::PathBuf { + let dir = vectorcraft_testkit::temp_dir(&format!("color-settings-{tag}")); + let _ = std::fs::remove_dir_all(&dir); + dir +} + +/// An ICC file of an RGB profile named `name` (a built-in one with its description replaced by a +/// name of the same length). +#[allow(clippy::unwrap_used, reason = "a test helper: a missing built-in profile fails the test")] +fn icc_named(name: &str) -> Vec { + let builtin = cms::DISPLAY_P3; + assert_eq!(builtin.len(), name.len()); + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + let mut bytes = cms::icc_bytes(builtin).unwrap().to_vec(); + let (from, to) = (utf16(builtin), utf16(name)); + let at = bytes.windows(from.len()).position(|w| w == from).unwrap(); + bytes[at..at + to.len()].copy_from_slice(&to); + bytes +} + +/// Puts the default Color Settings back, unregisters `profile` and deletes `paths` when dropped, +/// also after a failed assertion, so the next test starts from the defaults. +struct ColorSettingsReset { + profile: Option<&'static str>, + paths: Vec, +} + +impl Drop for ColorSettingsReset { + /// The defaults back, the profile unregistered and the paths deleted. + fn drop(&mut self) { + let _ = cms::set_active(&cms::ColorSettings::default()); + if let Some(name) = self.profile { + cms::unregister_icc(name); + } + for path in &self.paths { + let _ = std::fs::remove_dir_all(path).or_else(|_| std::fs::remove_file(path)); + } + } +} + +/// #6335: Edit › Color Settings come back in the next session: the working spaces (a loaded +/// profile among them, registered again by the profile store first), the intent and black point +/// compensation. A session nobody attached a file to keeps nothing, and nothing is written before +/// the settings change. +#[test] +fn color_settings_come_back_in_the_next_session() { + let _g = settings(); + let root = fresh_dir("color-settings"); + let (profiles, file) = (root.join("Color Profiles"), root.join("Color Settings.json")); + let loaded = "StoreRGB-6"; + let icc = vectorcraft_testkit::temp_dir("store-color-settings").join("loaded.icc"); + let _reset = ColorSettingsReset { profile: Some(loaded), paths: vec![root.clone(), icc.clone()] }; + std::fs::write(&icc, icc_named(loaded)).unwrap(); + + let mut a = Session::new(); + a.attach_profile_store(profiles.clone()); + a.attach_color_settings(file.clone()); + a.execute("color.loadProfile", &json!({"path": icc.to_str().unwrap()})).unwrap(); + a.execute("edit.colorSettings", &json!({})).unwrap(); + assert!(!file.exists(), "nothing to keep before the settings change"); + a.execute("edit.colorSettings", &json!({"rgb": loaded, "cmyk": cms::DEVICE_CMYK, "intent": "perceptual", "bpc": false})).unwrap(); + let chosen = cms::ColorSettings { rgb: loaded.into(), cmyk: cms::DEVICE_CMYK.into(), intent: cms::Intent::Perceptual, bpc: false }; + assert_eq!(cms::active_settings(), chosen); + + // The next start begins with the defaults and without the loaded profile, which the profile + // store registers again before the settings name it. + cms::set_active(&cms::ColorSettings::default()).unwrap(); + assert!(cms::unregister_icc(loaded)); + let mut b = Session::new(); + b.attach_profile_store(profiles); + b.attach_color_settings(file.clone()); + assert_eq!(cms::active_settings(), chosen, "the saved settings are the active ones again"); + + // Without a file, a change is kept only for the process. + let mut c = Session::new(); + c.execute("edit.colorSettings", &json!({"bpc": true})).unwrap(); + let saved: cms::ColorSettings = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert_eq!(saved, chosen, "the file is left alone"); +} + +/// #6335: saved Color Settings that can't be used (a profile that is gone, a damaged or oversized +/// file) leave the defaults and the file as it is; the next change writes over it. +#[test] +fn saved_color_settings_that_cannot_be_used_leave_the_defaults() { + let _g = settings(); + let dir = fresh_dir("color-settings-bad"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + let file = dir.join("Color Settings.json"); + std::fs::create_dir_all(&dir).unwrap(); + let gone = json!({"rgb": cms::SRGB, "cmyk": "A Profile That Is Gone", "intent": "perceptual", "bpc": false}).to_string().into_bytes(); + let oversized = vec![b' '; MAX_PRESET_FILE as usize + 1]; + for bytes in [gone, b"not json".to_vec(), oversized] { + cms::set_active(&cms::ColorSettings::default()).unwrap(); + std::fs::write(&file, &bytes).unwrap(); + let mut s = Session::new(); + s.attach_color_settings(file.clone()); + assert_eq!(cms::active_settings(), cms::ColorSettings::default()); + assert_eq!(std::fs::read(&file).unwrap(), bytes, "left as it is"); + s.execute("edit.colorSettings", &json!({"bpc": false})).unwrap(); + let saved: cms::ColorSettings = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert!(!saved.bpc && saved.cmyk == cms::GENERIC_CMYK, "written over by the next change: {saved:?}"); + } +} diff --git a/crates/engine/tests/it/clear_commands.rs b/crates/engine/tests/it/clear_commands.rs index 3b7fb79e94..655c719965 100644 --- a/crates/engine/tests/it/clear_commands.rs +++ b/crates/engine/tests/it/clear_commands.rs @@ -144,12 +144,14 @@ fn cut_compound_member_keeps_copy_and_delete_targets_consistent() { let (mut s, a, b, c) = compound(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.execute("edit.cut", &json!({})).unwrap(); + // Cut takes the member it copies, and the other member stays in the compound. assert_eq!(s.clipboard.nodes.len(), 1); - assert_eq!(s.clipboard.nodes[0].id, c); - assert!(s.active().unwrap().doc.node(c).is_none()); + assert_eq!(s.clipboard.nodes[0].id, a); + assert!(s.active().unwrap().doc.node(a).is_none()); + assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c)); s.execute("edit.pasteInPlace", &json!({})).unwrap(); let pasted = s.active().unwrap().selection.objects[0]; - assert_eq!(s.active().unwrap().doc.node(pasted).unwrap().children().unwrap().len(), 2); + assert!(s.active().unwrap().doc.node(pasted).unwrap().path_data().is_some(), "an ordinary path is pasted"); s.execute("edit.undo", &json!({})).unwrap(); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.active().unwrap().doc.parent_of(a), Some(c)); diff --git a/crates/engine/tests/it/copy_direct_selection.rs b/crates/engine/tests/it/copy_direct_selection.rs index 957d778299..14c2a45b18 100644 --- a/crates/engine/tests/it/copy_direct_selection.rs +++ b/crates/engine/tests/it/copy_direct_selection.rs @@ -192,7 +192,7 @@ fn pen_tool_drawing_copies_whole_path_not_single_anchor() { } #[test] -fn cut_adjacent_anchors_clipboard_plus_remaining_equals_original() { +fn cut_adjacent_anchors_takes_them_out_of_the_source() { let mut s = Session::new(); run(&mut s, "file.new", json!({"width": 200, "height": 200})); let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); @@ -207,15 +207,93 @@ fn cut_adjacent_anchors_clipboard_plus_remaining_equals_original() { assert_eq!(clip_path.subpaths[0].segment_count(), 1); assert_eq!(clip_path.subpaths[0].anchors.len(), 2); - // Remaining source path must have the remaining 3 segments (segments 0, 2, 3), not 1. + // The source keeps anchors 3 and 0 and the one segment between them. let src_node = s.doc().unwrap().doc.node(r).unwrap(); let src_path = src_node.path_data().unwrap(); - assert_eq!(src_path.subpaths[0].segment_count(), 3); - assert_eq!(src_path.subpaths[0].anchors.len(), 4); + assert_eq!(src_path.subpaths[0].segment_count(), 1); + assert_eq!(src_path.subpaths[0].anchors.len(), 2); assert!(!src_path.subpaths[0].closed); +} - // Sum of segments in clipboard + remaining = 1 + 3 = 4 (the original 4 segments). - assert_eq!(clip_path.subpaths[0].segment_count() + src_path.subpaths[0].segment_count(), 4); +/// Every contour left in the document after `command` runs on anchors `picked` of a four-anchor +/// open path, as `[x, y]` lists. With `compound`, the path is a member of a compound path. +fn contours_after(command: &str, picked: Value, compound: bool) -> Vec> { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 20}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 60, "y": 20})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 100, "y": 80})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 150, "y": 80})); + if compound { + let other = rect(&mut s, 10.0, 100.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [id.0, other.0]})); + run(&mut s, "object.compoundPath.make", json!({})); + } + run(&mut s, "select.anchors", json!({"id": id.0, "anchors": picked, "mode": "set"})); + run(&mut s, command, json!({})); + check_session(&s).unwrap(); + contours(&s) +} + +/// Every contour in the document, as `[x, y]` lists. +fn contours(s: &Session) -> Vec> { + let mut left = vec![]; + for layer in &s.doc().unwrap().doc.layers { + layer.walk(&mut |n| { + if let Some(path) = n.path_data() { + left.extend(path.subpaths.iter().map(|sp| sp.anchors.iter().map(|a| [a.p.x, a.p.y]).collect::>())); + } + }); + } + left +} + +#[test] +fn cut_end_anchors_leaves_the_source_as_clear_does() { + for compound in [false, true] { + let picked = || json!([[0, 0], [0, 1]]); + let left = contours_after("edit.cut", picked(), compound); + assert_eq!(left, contours_after("edit.clear", picked(), compound), "compound: {compound}"); + assert_eq!(left[0], [[100.0, 80.0], [150.0, 80.0]], "compound: {compound}"); + } +} + +#[test] +fn cut_interior_anchors_leaves_the_source_as_clear_does() { + let picked = || json!([[0, 1], [0, 2]]); + let left = contours_after("edit.cut", picked(), true); + assert_eq!(left, contours_after("edit.clear", picked(), true)); + assert!(left.iter().flatten().all(|p| p[0] != 60.0 && p[0] != 100.0), "the picked anchors are gone: {left:?}"); +} + +#[test] +fn cut_one_end_anchor_of_a_compound_member_shortens_it() { + let left = contours_after("edit.cut", json!([[0, 3]]), true); + assert_eq!(left[0], [[10.0, 20.0], [60.0, 20.0], [100.0, 80.0]]); +} + +#[test] +fn cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does() { + let after = |command: &str| { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 400})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 20}]}))["id"].as_u64().unwrap()); + let contour = |y: i32| json!({"anchors": [{"x": 10, "y": y}, {"x": 60, "y": y}, {"x": 110, "y": y}], "closed": false}); + run(&mut s, "path.setAnchors", json!({"id": id.0, "subpaths": [contour(20), contour(120)]})); + run(&mut s, "select.anchors", json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "select.segments", json!({"id": id.0, "segments": [[1, 1]], "mode": "add"})); + run(&mut s, command, json!({})); + check_session(&s).unwrap(); + s + }; + let cut = after("edit.cut"); + assert_eq!(contours(&cut), contours(&after("edit.clear"))); + assert!(contours(&cut).contains(&vec![[10.0, 20.0], [60.0, 20.0], [110.0, 20.0]]), "the picked anchor stays: {:?}", contours(&cut)); + // The clipboard holds what left the source: the picked segment alone. + assert_eq!(cut.clipboard.nodes.len(), 1); + let clip = cut.clipboard.nodes[0].path_data().unwrap(); + assert_eq!(clip.subpaths.len(), 1); + assert_eq!(clip.subpaths[0].anchors.iter().map(|a| [a.p.x, a.p.y]).collect::>(), [[60.0, 120.0], [110.0, 120.0]]); } #[test] @@ -289,13 +367,14 @@ fn copy_when_all_segments_selected_preserves_live_shape() { } #[test] -fn compound_member_selected_whole_with_direct_selection_promotes_member() { +fn compound_member_selected_whole_with_direct_selection_copies_only_the_member() { let mut s = Session::new(); run(&mut s, "file.new", json!({"width": 200, "height": 200})); let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); let standalone = rect(&mut s, 120.0, 10.0, 50.0, 50.0); @@ -316,17 +395,24 @@ fn compound_member_selected_whole_with_direct_selection_promotes_member() { assert!(s.active().unwrap().selection.partial(outer).is_none()); assert!(s.active().unwrap().selection.partial(standalone).is_some()); + let undo_before = s.doc().unwrap().history.undo.len(); run(&mut s, "edit.copy", json!({})); - // Clipboard should have: - // 1. The compound path (outer promoted to compound #786) - // 2. The extracted segment piece from standalone + // The clipboard holds the member as an ordinary path with the compound's paint, and the + // piece extracted from the standalone path. let clip_ids: Vec = s.clipboard.nodes.iter().map(|n| n.id).collect(); - assert_eq!(clip_ids.len(), 2, "promoted compound plus the extracted standalone piece"); - assert!(clip_ids.contains(&compound), "whole compound member must be promoted to compound parent"); + assert_eq!(clip_ids.len(), 2, "the member plus the extracted standalone piece"); + assert!(clip_ids.contains(&outer), "the member is copied itself: {clip_ids:?}"); + assert!(!clip_ids.contains(&compound), "the compound is not copied"); + let member = s.clipboard.nodes.iter().find(|n| n.id == outer).unwrap(); + assert!(matches!(member.kind, NodeKind::Path { .. })); + assert_eq!(member.appearance, s.doc().unwrap().doc.node(compound).unwrap().appearance); + // Copy leaves the document and its history as they were. + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before); + assert_eq!(s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().len(), 2); } #[test] -fn cut_whole_compound_member_with_direct_selection_cuts_compound_and_extracted_piece() { +fn cut_whole_compound_member_with_direct_selection_cuts_member_and_extracted_piece() { let mut s = Session::new(); run(&mut s, "file.new", json!({"width": 200, "height": 200})); let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); @@ -348,16 +434,411 @@ fn cut_whole_compound_member_with_direct_selection_cuts_compound_and_extracted_p }), ); + let undo_before = s.doc().unwrap().history.undo.len(); run(&mut s, "edit.cut", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "Cut is one undo step"); let clip_ids: Vec = s.clipboard.nodes.iter().map(|n| n.id).collect(); - assert_eq!(clip_ids.len(), 2, "promoted compound plus the extracted standalone piece"); - assert!(clip_ids.contains(&compound), "whole compound member must be promoted to compound parent"); + assert_eq!(clip_ids.len(), 2, "the member plus the extracted standalone piece"); + assert!(clip_ids.contains(&outer) && !clip_ids.contains(&compound), "{clip_ids:?}"); - // Compound was removed because member was selected whole + // The member left; the other member stays in the compound. let doc = &s.doc().unwrap().doc; - assert!(doc.node(compound).is_none(), "compound path must be removed on cut"); + assert!(doc.node(outer).is_none(), "the cut member is removed"); + assert_eq!(doc.node(compound).and_then(|n| n.children()).map(|c| c.iter().map(|m| m.id).collect::>()), Some(vec![inner])); // Standalone has cut pieces remaining assert!(doc.node(standalone).is_some(), "partially cut standalone path remains"); + check_session(&s).unwrap(); + + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().len(), 2, "Undo puts the member back"); + run(&mut s, "edit.redo", json!({})); + assert!(s.doc().unwrap().doc.node(outer).is_none()); + check_session(&s).unwrap(); +} + +/// A compound path of `n` rectangles side by side (x = 10, 60, 110, …), filled red, with its id +/// and its members' ids. +fn compound_of(s: &mut Session, n: usize) -> (NodeId, Vec) { + let members: Vec = (0..n).map(|i| rect(s, 10.0 + 50.0 * i as f64, 10.0, 40.0, 40.0)).collect(); + run(s, "select.set", json!({"ids": members.iter().map(|m| m.0).collect::>()})); + let compound = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + run(s, "paint.setFill", json!({"color": "#ff0000"})); + (compound, members) +} + +/// Every anchor of the four-anchor rectangle `id` picked with Direct Selection, which selects it +/// whole. +fn pick_all_anchors(s: &mut Session, id: NodeId) { + run(s, "select.anchorsMany", json!({"items": [{"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2], [0, 3]]}]})); + assert!(s.doc().unwrap().selection.contains(id) && s.doc().unwrap().selection.partial(id).is_none(), "the member is selected whole"); +} + +fn members_of(s: &Session, compound: NodeId) -> Option> { + s.doc().unwrap().doc.node(compound).and_then(|n| n.children()).map(|c| c.iter().map(|m| m.id).collect()) +} + +#[test] +fn cut_of_one_member_of_two_leaves_a_compound_of_one() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + pick_all_anchors(&mut s, m[0]); + let undo_before = s.doc().unwrap().history.undo.len(); + run(&mut s, "edit.cut", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "Cut is one undo step"); + assert_eq!(members_of(&s, compound), Some(vec![m[1]]), "the other member stays a compound of one, as after Clear"); + assert_eq!(s.clipboard.nodes.len(), 1); + assert_eq!(s.clipboard.nodes[0].id, m[0]); + assert!(matches!(s.clipboard.nodes[0].kind, NodeKind::Path { .. }), "the clipboard holds an ordinary path"); + check_session(&s).unwrap(); + + run(&mut s, "edit.undo", json!({})); + assert_eq!(members_of(&s, compound), Some(m.clone()), "Undo puts the member back in its place"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(members_of(&s, compound), Some(vec![m[1]])); + check_session(&s).unwrap(); +} + +#[test] +fn cut_of_the_middle_member_of_three_leaves_the_other_two() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 3); + pick_all_anchors(&mut s, m[1]); + run(&mut s, "edit.cut", json!({})); + assert_eq!(members_of(&s, compound), Some(vec![m[0], m[2]])); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), [m[1]]); + check_session(&s).unwrap(); +} + +#[test] +fn clear_of_a_whole_member_removes_only_the_member_and_keeps_the_clipboard() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + let standalone = rect(&mut s, 10.0, 120.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [standalone.0]})); + run(&mut s, "edit.copy", json!({})); + pick_all_anchors(&mut s, m[0]); + run(&mut s, "edit.clear", json!({})); + assert_eq!(members_of(&s, compound), Some(vec![m[1]])); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), [standalone]); +} + +#[test] +fn group_selection_of_one_member_copies_and_cuts_only_that_member() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + s.select_tool("groupSelection", vectorcraft_engine::ViewInfo::default()).unwrap(); + run(&mut s, "select.set", json!({"ids": [m[1].0]})); + run(&mut s, "edit.copy", json!({})); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), [m[1]]); + assert!(matches!(s.clipboard.nodes[0].kind, NodeKind::Path { .. })); + assert_eq!(members_of(&s, compound), Some(m.clone()), "Copy leaves both members"); + + run(&mut s, "edit.cut", json!({})); + assert_eq!(members_of(&s, compound), Some(vec![m[0]])); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), [m[1]]); + check_session(&s).unwrap(); +} + +#[test] +fn every_member_selected_whole_copies_and_cuts_the_compound() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + s.select_tool("groupSelection", vectorcraft_engine::ViewInfo::default()).unwrap(); + run(&mut s, "select.set", json!({"ids": [m[0].0, m[1].0]})); + run(&mut s, "edit.copy", json!({})); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), [compound]); + run(&mut s, "edit.cut", json!({})); + assert!(s.doc().unwrap().doc.node(compound).is_none(), "the compound leaves whole"); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), [compound]); + check_session(&s).unwrap(); +} + +#[test] +fn a_copied_member_keeps_the_compounds_transparency_mask_and_fill_rule() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + let mask = rect(&mut s, 0.0, 0.0, 120.0, 60.0); + run(&mut s, "select.set", json!({"ids": [compound.0, mask.0]})); + run(&mut s, "transparency.makeOpacityMask", json!({})); + let mask_art = s.doc().unwrap().doc.node(compound).unwrap().extras().mask.clone(); + assert!(mask_art.is_some(), "the compound has an opacity mask"); + run(&mut s, "select.set", json!({"ids": [compound.0]})); + run(&mut s, "transparency.set", json!({"opacity": 50, "blend": "Multiply", "isolate": true})); + run(&mut s, "path.setFillRule", json!({"rule": "evenOdd"})); + assert!(matches!(s.doc().unwrap().doc.node(m[0]).unwrap().kind, NodeKind::Path { rule: FillRule::NonZero, .. }), "the member keeps its own rule"); + let (opacity, blend) = { + let c = s.doc().unwrap().doc.node(compound).unwrap(); + (c.opacity, c.blend) + }; + assert_eq!(opacity, 0.5); + pick_all_anchors(&mut s, m[0]); + run(&mut s, "edit.copy", json!({})); + assert_eq!(s.clipboard.nodes.iter().map(|n| (n.id, n.opacity, n.blend)).collect::>(), [(m[0], opacity, blend)]); + assert!(matches!(s.clipboard.nodes[0].kind, NodeKind::Path { rule: FillRule::EvenOdd, .. })); + assert!(s.clipboard.nodes[0].isolate, "the member keeps the compound's isolated blending"); + assert_eq!(s.clipboard.nodes[0].extras().mask, mask_art, "the member keeps the compound's opacity mask"); +} + +#[test] +fn a_copied_member_with_its_own_appearance_takes_the_compounds() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + // The member carries an appearance of its own, as an imported member can; the compound's + // appearance is the one drawn. + run(&mut s, "paint.setFill", json!({"ids": [compound.0], "color": "#00ff00"})); + let own_look = s.doc().unwrap().doc.node(compound).unwrap().appearance.clone(); + run(&mut s, "paint.setFill", json!({"ids": [compound.0], "color": "#0000ff"})); + let compound_look = s.doc().unwrap().doc.node(compound).unwrap().appearance.clone(); + assert_ne!(own_look, compound_look); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(m[0]).unwrap().appearance = own_look.clone(); + assert!(!s.doc().unwrap().doc.node(m[0]).unwrap().appearance.items.is_empty(), "the member has its own appearance"); + pick_all_anchors(&mut s, m[0]); + run(&mut s, "edit.copy", json!({})); + assert_eq!(s.clipboard.nodes[0].appearance, compound_look); +} + +/// A member copied or cut on its own, whole or in part, takes the compound's graphic style link +/// with its look, or no link when the compound has none or the member no longer has the style's +/// look (a gradient pinned to the compound's bounds); the style the member had before Make Compound +/// Path does not go with it. +#[test] +fn a_copied_member_takes_the_compounds_graphic_style() { + let style_of = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().extras().graphic_style; + let clipboard_styles = |s: &Session| s.clipboard.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + for (compound_styled, gradient) in [(false, false), (true, false), (true, true)] { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let m0 = rect(&mut s, 10.0, 10.0, 40.0, 40.0); + run(&mut s, "paint.setFill", json!({"ids": [m0.0], "color": "#00ff00"})); + run(&mut s, "select.set", json!({"ids": [m0.0]})); + run(&mut s, "graphicStyle.new", json!({"name": "Member"})); + let member_style = style_of(&s, m0); + assert!(member_style.is_some(), "the path is linked to the style made from it"); + let m1 = rect(&mut s, 60.0, 10.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [m0.0, m1.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + let fill = + if gradient { json!({"ids": [compound.0], "gradient": {"kind": "linear"}}) } else { json!({"ids": [compound.0], "color": "#ff0000"}) }; + run(&mut s, "paint.setFill", fill); + assert_eq!(style_of(&s, m0), member_style, "the member keeps its old link inside the compound"); + let compound_style = if compound_styled { + run(&mut s, "select.set", json!({"ids": [compound.0]})); + run(&mut s, "graphicStyle.new", json!({"name": "Compound"})); + style_of(&s, compound) + } else { + None + }; + assert_eq!(compound_style.is_some(), compound_styled); + // A gradient fitted to the compound is pinned to its bounds on the copy, which is no longer + // the style's look. + let link = compound_style.filter(|_| !gradient); + let expected: Vec = if link.is_some() { vec!["Compound".into()] } else { vec![] }; + let case = format!("compound styled: {compound_styled}, gradient: {gradient}"); + + s.select_tool("groupSelection", vectorcraft_engine::ViewInfo::default()).unwrap(); + run(&mut s, "select.set", json!({"ids": [m0.0]})); + run(&mut s, "edit.copy", json!({})); + assert_eq!(s.clipboard.nodes[0].id, m0); + assert_eq!(s.clipboard.nodes[0].extras().graphic_style, link, "whole member, {case}"); + assert_eq!(clipboard_styles(&s), expected, "whole member, {case}"); + + run(&mut s, "select.segments", json!({"id": m0.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + assert_eq!(s.clipboard.nodes.len(), 1); + assert_eq!(s.clipboard.nodes[0].extras().graphic_style, link, "one segment, {case}"); + assert_eq!(clipboard_styles(&s), expected, "one segment, {case}"); + + run(&mut s, "select.set", json!({"ids": [m0.0]})); + run(&mut s, "edit.cut", json!({})); + assert_eq!(members_of(&s, compound), Some(vec![m1])); + let pasted = NodeId(run(&mut s, "edit.pasteInPlace", json!({}))["ids"][0].as_u64().unwrap()); + assert_eq!(style_of(&s, pasted), link, "Cut and Paste in Place, {case}"); + check_session(&s).unwrap(); + } +} + +#[test] +fn every_segment_of_every_member_picked_copies_and_cuts_the_compound() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + let all: Vec> = (0..4).map(|i| vec![0, i]).collect(); + run(&mut s, "select.segments", json!({"id": m[0].0, "segments": all})); + run(&mut s, "select.segments", json!({"id": m[1].0, "segments": all, "mode": "add"})); + let sel = &s.doc().unwrap().selection; + assert!(sel.segments.contains_key(&m[0]) && sel.segments.contains_key(&m[1]), "both members keep their picked segments"); + run(&mut s, "edit.copy", json!({})); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), [compound]); + run(&mut s, "edit.cut", json!({})); + assert!(s.doc().unwrap().doc.node(compound).is_none(), "the compound leaves whole"); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), [compound]); + check_session(&s).unwrap(); +} + +#[test] +fn clear_of_every_segment_or_anchor_of_every_member_leaves_no_empty_compound() { + let all: Vec> = (0..4).map(|i| vec![0, i]).collect(); + let picks: [(&str, Value, Value); 3] = [ + ("every segment", json!({"segments": all}), json!({"segments": all, "mode": "add"})), + ("every anchor", json!({"anchors": all}), json!({"anchors": all})), + ("one member whole, every segment of the other", json!({"anchors": all}), json!({"segments": all, "mode": "add"})), + ]; + for (label, first, second) in picks { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + let layer = s.doc().unwrap().doc.parent_of(compound).unwrap(); + if first.get("segments").is_some() { + run(&mut s, "select.segments", json!({"id": m[0].0, "segments": first["segments"]})); + } else { + run(&mut s, "select.anchorsMany", json!({"items": [{"id": m[0].0, "anchors": first["anchors"]}]})); + } + if second.get("segments").is_some() { + run(&mut s, "select.segments", json!({"id": m[1].0, "segments": second["segments"], "mode": "add"})); + } else { + run(&mut s, "select.anchorsMany", json!({"items": [{"id": m[0].0, "anchors": all}, {"id": m[1].0, "anchors": all}]})); + } + let undo_before = s.doc().unwrap().history.undo.len(); + run(&mut s, "edit.clear", json!({})); + let doc = &s.doc().unwrap().doc; + assert!(doc.node(compound).is_none(), "{label}: Clear removes the compound with its members, as Cut does"); + assert!(doc.node(layer).and_then(|l| l.children()).is_some_and(|c| c.is_empty()), "{label}: nothing is left in the layer"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "{label}: Clear is one undo step"); + check_session(&s).unwrap(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(members_of(&s, compound), Some(m.clone()), "{label}: Undo puts the compound back"); + } +} + +#[test] +fn a_copied_member_keeps_the_compounds_gradient_where_it_was() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + // Members at x 10..50 and 60..100: the compound's gradient spans x 10..100. + let (compound, m) = compound_of(&mut s, 2); + run(&mut s, "paint.setFill", json!({"ids": [compound.0], "gradient": {"kind": "linear"}})); + let (mut expected, bounds) = { + let c = s.doc().unwrap().doc.node(compound).unwrap(); + (c.appearance.clone(), c.geometric_bounds().unwrap()) + }; + assert!(expected.has_unplaced_gradient(), "the compound's gradient is fitted to its bounds"); + assert_eq!((bounds.x0, bounds.x1), (10.0, 100.0)); + expected.pin_gradients(bounds); + s.select_tool("groupSelection", vectorcraft_engine::ViewInfo::default()).unwrap(); + run(&mut s, "select.set", json!({"ids": [m[0].0]})); + run(&mut s, "edit.copy", json!({})); + let member = &s.clipboard.nodes[0]; + assert_eq!(member.id, m[0]); + assert!(!member.appearance.has_unplaced_gradient(), "the member's gradient is not refitted to its own bounds"); + assert_eq!(member.appearance, expected, "the gradient keeps the compound's fit"); + + // The member cut and pasted in place draws the gradient over the compound's stretch. + run(&mut s, "edit.cut", json!({})); + let pasted = NodeId(run(&mut s, "edit.pasteInPlace", json!({}))["ids"][0].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(pasted).unwrap().appearance, expected); +} + +#[test] +fn the_only_member_of_a_compound_of_one_copies_the_compound() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + pick_all_anchors(&mut s, m[0]); + run(&mut s, "edit.cut", json!({})); + assert_eq!(members_of(&s, compound), Some(vec![m[1]]), "Cut leaves a compound of one"); + // Its one member selected whole is every member selected whole. + s.select_tool("groupSelection", vectorcraft_engine::ViewInfo::default()).unwrap(); + run(&mut s, "select.set", json!({"ids": [m[1].0]})); + run(&mut s, "edit.copy", json!({})); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), [compound]); + assert!(matches!(s.clipboard.nodes[0].kind, NodeKind::Compound { .. })); +} + +#[test] +fn copy_of_a_member_then_paste_in_front_adds_a_member_to_the_compound() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + pick_all_anchors(&mut s, m[0]); + run(&mut s, "edit.copy", json!({})); + // The member is still selected: a path pasted in front of it goes into its compound. + let pasted = NodeId(run(&mut s, "edit.pasteInFront", json!({}))["ids"][0].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + assert!(matches!(doc.node(pasted).unwrap().kind, NodeKind::Path { .. })); + assert_eq!(members_of(&s, compound), Some(vec![m[0], pasted, m[1]]), "the pasted path sits just above the member"); + check_session(&s).unwrap(); +} + +#[test] +fn cut_of_a_whole_member_with_anchors_of_another_member_takes_each_by_its_own_rule() { + let after = |command: &str| { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + let whole: Vec> = (0..4).map(|i| vec![0, i]).collect(); + run(&mut s, "select.anchorsMany", json!({"items": [{"id": m[0].0, "anchors": whole}, {"id": m[1].0, "anchors": [[0, 1], [0, 2]]}]})); + run(&mut s, command, json!({})); + check_session(&s).unwrap(); + (s, compound, m) + }; + let (s, compound, m) = after("edit.cut"); + // The whole member and the segment between the two picked anchors went to the clipboard. + assert_eq!(s.clipboard.nodes.len(), 2); + assert!(s.clipboard.nodes.iter().any(|n| n.id == m[0])); + assert!(s.clipboard.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); + // The partly picked member stays in the compound, with what Clear leaves of its outline. + assert_eq!(members_of(&s, compound).map(|c| c.len()), Some(1)); + assert_eq!(contours(&s), contours(&after("edit.clear").0)); + assert_eq!(contours(&s).len(), 1); +} + +#[test] +fn cut_of_a_member_of_a_compound_inside_a_group_leaves_the_group_and_compound() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + let other = rect(&mut s, 10.0, 120.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [compound.0, other.0]})); + let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + pick_all_anchors(&mut s, m[0]); + run(&mut s, "edit.cut", json!({})); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(compound), Some(group)); + assert_eq!(members_of(&s, compound), Some(vec![m[1]])); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), [m[0]]); + check_session(&s).unwrap(); +} + +#[test] +fn paste_in_place_and_in_front_of_a_cut_member_paste_an_ordinary_path() { + for command in ["edit.pasteInPlace", "edit.pasteInFront"] { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let (compound, m) = compound_of(&mut s, 2); + let fill = s.doc().unwrap().doc.node(compound).unwrap().appearance.clone(); + pick_all_anchors(&mut s, m[0]); + run(&mut s, "edit.cut", json!({})); + let pasted = run(&mut s, command, json!({})); + let ids = pasted["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1, "{command}"); + let id = NodeId(ids[0].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let node = doc.node(id).unwrap(); + assert!(matches!(node.kind, NodeKind::Path { .. }), "{command}"); + assert_eq!(node.appearance, fill, "{command}: the path keeps the compound's paint"); + assert!(doc.parent_of(id).and_then(|p| doc.node(p)).is_some_and(|p| p.is_layer()), "{command}: pasted into the layer"); + let anchors: Vec<[f64; 2]> = node.path_data().unwrap().subpaths[0].anchors.iter().map(|a| [a.p.x, a.p.y]).collect(); + assert!(anchors.contains(&[10.0, 10.0]) && anchors.contains(&[50.0, 50.0]), "{command}: where it was: {anchors:?}"); + assert_eq!(members_of(&s, compound), Some(vec![m[1]]), "{command}"); + check_session(&s).unwrap(); + } } #[test] diff --git a/crates/engine/tests/plugin_call.rs b/crates/engine/tests/plugin_call.rs new file mode 100644 index 0000000000..71f2619a30 --- /dev/null +++ b/crates/engine/tests/plugin_call.rs @@ -0,0 +1,239 @@ +//! A filter plug-in whose manifest's `commandAllowlist` names commands calls them with `vc_call`: +//! each call sees what the calls before it left, the calls and the filter's output are one undo +//! step, and a run that fails leaves the document as it was. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_plugins::wat as tpl; + +/// The command imports and the strings the plug-ins pass: the ids "select.all" (0x2000, 10 bytes), +/// "object.move" (0x2010, 11), "no.such.cmd" (0x2020, 11), "effect.apply" (0x2030, 12) and +/// "select.globalEditOptions" (0x2040, 24), and the arguments `{"dx":5,"dy":0}` (0x2100, 15), +/// `{"dx":"x"}` (0x2200, 10), `{"effect":"plugin.test.call.fx"}` (0x2300, 32) and `{"size":true}` +/// (0x2400, 13). +const CALLS: &str = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (import "env" "vc_call_result" (func $vc_call_result (param i32 i32) (result i32))) + (data (i32.const 0x2000) "select.all") + (data (i32.const 0x2010) "object.move") + (data (i32.const 0x2020) "no.such.cmd") + (data (i32.const 0x2030) "effect.apply") + (data (i32.const 0x2040) "select.globalEditOptions") + (data (i32.const 0x2100) "{\22dx\22:5,\22dy\22:0}") + (data (i32.const 0x2200) "{\22dx\22:\22x\22}") + (data (i32.const 0x2300) "{\22effect\22:\22plugin.test.call.fx\22}") + (data (i32.const 0x2400) "{\22size\22:true}")"#; + +/// Selects everything. +const SELECT_ALL: &str = "(drop (call $vc_call (i32.const 0x2000) (i32.const 10) (i32.const 0) (i32.const 0)))"; +/// Moves the selection 5 to the right. +const MOVE: &str = "(drop (call $vc_call (i32.const 0x2010) (i32.const 11) (i32.const 0x2100) (i32.const 15)))"; + +const EMPTY: &str = r#"{"objects":[]}"#; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// Installs filter `id` with `permissions` (a JSON list) and `allowlist` (a JSON list), whose +/// `vc_run` runs `first`, then returns `output` → what `plugin.install` returned, or why it refused. +fn install(s: &mut Session, id: &str, permissions: &str, allowlist: &str, first: &str, output: &str) -> Result { + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{permissions},"commandAllowlist":{allowlist}}}"#); + let wasm = wat::parse_str(tpl::with_imports(&manifest, CALLS, first, output)).unwrap(); + let grant: Value = serde_json::from_str(permissions).unwrap(); + let data = vectorcraft_format::base64_encode(&wasm); + s.execute("plugin.install", &json!({"dataBase64": data, "grant": grant, "replace": true})).map_err(|e| e.to_string()) +} + +/// A filter `id` that may read and change the document and call `select.all` and `object.move`. +fn install_mover(s: &mut Session, id: &str, first: &str, output: &str) { + install(s, id, r#"["doc.read","doc.write","commands"]"#, r#"["select.all","object.move"]"#, first, output).unwrap(); +} + +/// A document with two rectangles and nothing selected. +fn document() -> Session { + let mut s = Session::new(); + s.allow_plugin_grants_from_requests(); + run(&mut s, "file.new", json!({"width": 400, "height": 200})); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})); + run(&mut s, "shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 50})); + run(&mut s, "select.none", json!({})); + s +} + +/// The active document's layers, its undo and redo steps and how many objects are selected. +fn state(s: &mut Session) -> (Value, usize, usize, usize) { + let content = run(s, "document.inspect", json!({}))["layers"].take(); + let d = s.doc().unwrap(); + (content, d.history.undo.len(), d.history.redo.len(), d.selection.len()) +} + +/// Runs filter `id` on nothing, so only its calls change the document. +fn run_plugin(s: &mut Session, id: &str) -> Result { + s.execute("plugin.run", &json!({"id": id, "ids": []})).map_err(|e| e.to_string()) +} + +#[test] +fn calls_see_each_others_changes_and_make_one_undo_step() { + let mut s = document(); + let before = state(&mut s); + install_mover(&mut s, "test.call.mover", &[SELECT_ALL, MOVE].concat(), EMPTY); + run_plugin(&mut s, "test.call.mover").unwrap(); + let after = state(&mut s); + // `object.move` moved what `select.all` selected: both rectangles. + let xs: Vec<&Value> = after.0[0]["children"].as_array().unwrap().iter().map(|c| &c["bounds"]["x"]).collect(); + assert_eq!(xs, [&json!(105.0), &json!(15.0)]); + assert_eq!(after.1, before.1 + 1, "one undo step"); + assert_eq!(s.doc().unwrap().history.undo.last().map(|u| u.label.as_str()), Some("Test test.call.mover")); + run(&mut s, "edit.undo", json!({})); + assert_eq!(state(&mut s).0, before.0); + run(&mut s, "edit.redo", json!({})); + assert_eq!(state(&mut s).0, after.0); + // Without `select.all` nothing is selected, so `object.move` has nothing to move. + run(&mut s, "select.none", json!({})); + install_mover(&mut s, "test.call.mover", MOVE, EMPTY); + assert!(run_plugin(&mut s, "test.call.mover").is_err()); + run(&mut s, "plugin.remove", json!({"id": "test.call.mover"})); +} + +#[test] +fn a_run_that_fails_after_its_calls_changes_nothing() { + let mut s = document(); + let before = state(&mut s); + // A trap, an output that isn't JSON, and a command that fails, each after the move. + let bad_move = "(drop (call $vc_call (i32.const 0x2010) (i32.const 11) (i32.const 0x2200) (i32.const 10)))"; + for (first, output) in + [([SELECT_ALL, MOVE, "unreachable"].concat(), EMPTY), ([SELECT_ALL, MOVE].concat(), "nope"), ([SELECT_ALL, MOVE, bad_move].concat(), EMPTY)] + { + install_mover(&mut s, "test.call.fails", &first, output); + assert!(run_plugin(&mut s, "test.call.fails").is_err(), "{first} {output}"); + assert_eq!(state(&mut s), before, "{first} {output}"); + } + run(&mut s, "plugin.remove", json!({"id": "test.call.fails"})); + // Session state a call changed outside the document goes back too: Global Edit's options. + let options = "(drop (call $vc_call (i32.const 0x2040) (i32.const 24) (i32.const 0x2400) (i32.const 13))) unreachable"; + let allowlist = r#"["select.globalEditOptions"]"#; + install(&mut s, "test.call.options", r#"["doc.read","commands"]"#, allowlist, options, EMPTY).unwrap(); + assert!(run_plugin(&mut s, "test.call.options").is_err()); + assert_eq!(run(&mut s, "select.globalEditOptions", json!({}))["size"], json!(false)); + run(&mut s, "plugin.remove", json!({"id": "test.call.options"})); +} + +/// A command that changes state a failed run can't put back (the preferences, a tool's options, a +/// drag's state) is refused at install, by name. +#[test] +fn install_refuses_reviewed_denials() { + let mut s = document(); + for refused in ["object.liquify", "object.pathfinder.options", "addon.pen.nextSegment"] { + let allowlist = format!(r#"["select.all","{refused}"]"#); + let e = install(&mut s, "test.call.reviewed", r#"["doc.read","commands"]"#, &allowlist, "", EMPTY).unwrap_err(); + assert!(e.contains(refused) && e.contains("may not call"), "{e}"); + } +} + +#[test] +fn install_refuses_a_command_a_plugin_may_not_call_and_reports_unknown_ones() { + let mut s = document(); + let first = "(drop (call $vc_call (i32.const 0x2020) (i32.const 11) (i32.const 0) (i32.const 0)))"; + for refused in ["document.save", "edit.undo", "plugin.run", "script.run"] { + let allowlist = format!(r#"["select.all","{refused}"]"#); + let e = install(&mut s, "test.call.refused", r#"["doc.read","commands"]"#, &allowlist, "", EMPTY).unwrap_err(); + assert!(e.contains(refused) && e.contains("may not call"), "{e}"); + } + let r = install(&mut s, "test.call.unknown", r#"["doc.read","commands"]"#, r#"["select.all","no.such.cmd"]"#, first, EMPTY).unwrap(); + assert_eq!(r["unknownCommands"], json!(["no.such.cmd"])); + let e = run_plugin(&mut s, "test.call.unknown").unwrap_err(); + assert!(e.contains("no.such.cmd"), "{e}"); + run(&mut s, "plugin.remove", json!({"id": "test.call.unknown"})); +} + +#[test] +fn a_call_that_names_a_plugin_is_refused() { + let mut s = document(); + let before = state(&mut s); + let first = format!("{SELECT_ALL} (drop (call $vc_call (i32.const 0x2030) (i32.const 12) (i32.const 0x2300) (i32.const 32)))"); + install(&mut s, "test.call.fx", r#"["doc.read","doc.write","commands"]"#, r#"["select.all","effect.apply"]"#, &first, EMPTY).unwrap(); + let e = run_plugin(&mut s, "test.call.fx").unwrap_err(); + assert!(e.contains("may not call"), "{e}"); + assert_eq!(state(&mut s), before); + run(&mut s, "plugin.remove", json!({"id": "test.call.fx"})); +} + +#[test] +fn without_doc_write_a_call_that_edits_is_refused() { + let mut s = document(); + let before = state(&mut s); + let allowlist = r#"["select.all","object.move"]"#; + install(&mut s, "test.call.reader", r#"["doc.read","commands"]"#, allowlist, &[SELECT_ALL, MOVE].concat(), EMPTY).unwrap(); + let e = run_plugin(&mut s, "test.call.reader").unwrap_err(); + assert!(e.contains("may not call"), "{e}"); + assert_eq!(state(&mut s), before); + // Selecting changes no art, so it runs. + install(&mut s, "test.call.reader", r#"["doc.read","commands"]"#, allowlist, SELECT_ALL, EMPTY).unwrap(); + run_plugin(&mut s, "test.call.reader").unwrap(); + run(&mut s, "plugin.remove", json!({"id": "test.call.reader"})); +} + +/// Installs filter `id` that may read and change the document and call `allowlist`, whose `vc_run` +/// makes `calls` (command id and arguments) in order, dropping their codes, then returns nothing. +fn install_calls(s: &mut Session, id: &str, allowlist: &str, calls: &[(&str, &str)]) { + let mut imports = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32)))"#.to_string(); + let mut first = String::new(); + for (i, (cmd, args)) in calls.iter().enumerate() { + let at = 0x3000 + i * 0x400; + imports += &format!(r#" (data (i32.const {at}) "{}") (data (i32.const {}) "{}")"#, tpl::string(cmd), at + 0x100, tpl::string(args)); + first += &format!("(drop (call $vc_call (i32.const {at}) (i32.const {}) (i32.const {}) (i32.const {})))", cmd.len(), at + 0x100, args.len()); + } + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["doc.read","doc.write","commands"],"commandAllowlist":{allowlist}}}"# + ); + let wasm = wat::parse_str(tpl::with_imports(&manifest, &imports, &first, EMPTY)).unwrap(); + let data = vectorcraft_format::base64_encode(&wasm); + let grant = json!(["doc.read", "doc.write", "commands"]); + run(s, "plugin.install", json!({"dataBase64": data, "grant": grant, "replace": true})); +} + +/// Arguments that carry a file or folder key at any depth, such as an effect's +/// `textureImage.path`, are refused before the command runs, so no file is read; arguments nested +/// without one run. +#[test] +fn a_call_whose_arguments_name_a_file_is_refused() { + let mut s = document(); + let before = state(&mut s); + let allowlist = r#"["select.all","effect.apply","effect.setParams"]"#; + let select = ("select.all", ""); + for (cmd, args) in [ + ("effect.apply", r#"{"effect":"distort.glass","params":{"textureImage":{"path":"missing-texture.png"}}}"#), + ("effect.setParams", r#"{"index":0,"params":{"textureImage":{"path":"missing-texture.png"}}}"#), + ("effect.apply", r#"{"effect":"distort.glass","params":{"layers":[{"name":"a"},{"file":"missing-texture.png"}]}}"#), + ] { + install_calls(&mut s, "test.call.files", allowlist, &[select, (cmd, args)]); + let e = run_plugin(&mut s, "test.call.files").unwrap_err(); + assert!(e.contains("may not call") && e.contains(cmd), "{args}: {e}"); + assert_eq!(state(&mut s), before, "{args}"); + } + // The same effect with ordinary nested params runs. + install_calls(&mut s, "test.call.files", allowlist, &[select, ("effect.apply", r#"{"effect":"distort.glass","params":{"distortion":5}}"#)]); + run_plugin(&mut s, "test.call.files").unwrap(); + assert_eq!(state(&mut s).1, before.1 + 1, "one undo step"); + run(&mut s, "plugin.remove", json!({"id": "test.call.files"})); +} + +/// A command's result describes the document, so a plug-in without `doc.read` may call nothing. +#[test] +fn without_doc_read_every_call_is_refused() { + let mut s = document(); + let before = state(&mut s); + install(&mut s, "test.call.blind", r#"["commands"]"#, r#"["select.all"]"#, SELECT_ALL, EMPTY).unwrap(); + let e = run_plugin(&mut s, "test.call.blind").unwrap_err(); + assert!(e.contains("may not call") && e.contains("select.all"), "{e}"); + assert_eq!(state(&mut s), before); + // The same for an id no command has: without `doc.read` the answer never depends on the command. + let unknown = "(drop (call $vc_call (i32.const 0x2020) (i32.const 11) (i32.const 0) (i32.const 0)))"; + install(&mut s, "test.call.blind", r#"["commands"]"#, r#"["no.such.cmd"]"#, unknown, EMPTY).unwrap(); + let e = run_plugin(&mut s, "test.call.blind").unwrap_err(); + assert!(e.contains("may not call") && e.contains("no.such.cmd"), "{e}"); + run(&mut s, "plugin.remove", json!({"id": "test.call.blind"})); +} diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index 71f21e10d2..b780c115c3 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -145,7 +145,7 @@ fn a_file_an_importer_reads_opens_as_editable_art() { let stroked = r#"{"objects":[{"type":"path","path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,-4000000]},{"p":[50,-4000000]}]}]},"strokes":[{"paint":{"type":"solid","color":{"model":"rgb","r":0,"g":0,"b":0}},"width":10}]}]}"#; open(&mut s, "Stroked.tso", stroked.as_bytes(), json!({})).unwrap(); let (x0, y0, x1, y1) = artboard(&s); - assert!(x0 < 0.0 && x1 > 50.0 && y0 == -4_000_000.0 && y1 > y0 + 1.0, "{:?}", artboard(&s)); + assert!(x0 == 0.0 && x1 == 50.0 && y0 == -4_000_000.0 && y1 > y0 + 1.0, "{:?}", artboard(&s)); s.execute("select.all", &json!({})).unwrap(); s.execute("object.move", &json!({"dx": 0, "dy": 5})).unwrap(); diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 78058a7f9a..28f67f2152 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -7377,3 +7377,65 @@ fn bindings_and_values_the_reader_cant_take_are_left_out() { assert_eq!(back.variables.datasets[1].values.get("picture"), None); assert_eq!(bound_objects(&back).len(), 4); } + +/// Type in a variable font's named instance names the instance's place in the font's design space +/// (`/4`, each axis as 16.16 fixed) and the font's version (`/5`) in its font record, so the app that opens the file doesn't take +/// the font's default instance (#6388); a run's own Variable Font setting is a font of its own, and +/// a static font's record has no design vector. Each comes back as the style it was set in. +#[test] +fn variable_font_instances_name_their_design_space() { + use vectorcraft_doc::{CharStyle, TextObject}; + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let set = |doc: &mut Document, y: f64, style: &str, axes: &[(&str, f64)]| { + let st = CharStyle { + font_family: VARIABLE_FAMILY.into(), + font_style: style.into(), + font_axes: axes.iter().map(|(t, v)| (t.to_string(), *v)).collect(), + ..style_of(12.0) + }; + let n = text_node(doc, TextObject::point(vectorcraft_geom::Point::new(10.0, y), style, st)); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + }; + let mut doc = Document::new(300.0, 200.0); + set(&mut doc, 20.0, "Regular", &[]); + set(&mut doc, 40.0, "Bold", &[]); + set(&mut doc, 60.0, "Bold", &[("wght", 650.0)]); + let static_text = TextObject::point(vectorcraft_geom::Point::new(10.0, 80.0), "Static", style_of(12.0)); + let n = text_node(&mut doc, static_text); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + + let td = text_document(&program(&doc)); + // 400 × 65536, 700 × 65536 and 650 × 65536. + assert!(td.contains("VaritestSans-Regular) /2 1 /4 [ 26214400 ]"), "{td}"); + assert!(td.contains("VaritestSans-Bold) /2 1 /4 [ 45875200 ]"), "{td}"); + assert!(td.contains("VaritestSans-Bold) /2 1 /4 [ 42598400 ]"), "a setting of its own is a font of its own: {td}"); + let static_name = vectorcraft_text::FontDb::global().face(&style_of(12.0).font_family, "Regular").unwrap().postscript_name(); + assert!(td.contains(&format!("{static_name}) /2 1 >>")), "a static font has no design vector: {td}"); + // Each variable font's record names the font's version (name ID 5) after its design vector. + // (The string is UTF-16 after a byte order mark, so the match starts after it.) + assert_eq!(td.matches("] /5 (").count(), 3, "{td}"); + assert_eq!(td.matches("Version 1.000) >>").count(), 3, "{td}"); + assert_eq!(td.matches("/CoolTypeFont").count(), 5, "four fonts and the hidden characters' font"); + + let back = read_back(&doc); + let styles: Vec<(String, String)> = back.layers[0] + .children() + .unwrap() + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((t.runs[0].style.font_family.clone(), t.runs[0].style.font_style.clone())), + _ => None, + }) + .collect(); + assert_eq!( + styles[..3], + [(VARIABLE_FAMILY.into(), "Regular".into()), (VARIABLE_FAMILY.into(), "Bold".into()), (VARIABLE_FAMILY.into(), "Bold".into())] + ); +} + +fn style_of(size: f64) -> vectorcraft_doc::CharStyle { + style(size, Color::BLACK) +} diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index a84fc57200..1e02941c31 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -417,26 +417,61 @@ fn baseline_direction(st: &CharStyle) -> i64 { } } -/// The name the font of style `st` is written under, and whether it's TrueType: an installed -/// face's PostScript name; else its family and style as `family-style` (the family alone for -/// Regular), the form the reader's `family_style` splits. -fn font_name(st: &CharStyle) -> (String, bool) { +/// A font of the font set, as its `CoolTypeFont` record names it. +#[derive(Clone, Debug, PartialEq)] +struct FontRecord { + /// The PostScript name (`/0`). + name: String, + /// Whether its outlines are TrueType (`/2`). + truetype: bool, + /// For a variable font, where in its design space the type is set (`/4`): each `fvar` axis in + /// the font's order, in the axis's own units. Empty for a static font, which has none: without + /// it, an app that opens the file takes a variable font's default instance (#6388). + design: Vec, + /// For a variable font, its version string (`/5`, name ID 5); empty for a static font. + version: String, +} + +/// The font the font set names for style `st`: an installed face's PostScript name, and for a +/// variable font the setting of each of its axes (the named instance's, or the style's own +/// Variable Font setting, clamped to the axis as layout clamps it) and its version; else its family +/// and style as `family-style` (the family alone for Regular), the form the reader's +/// `family_style` splits. +fn font_name(st: &CharStyle) -> FontRecord { let db = vectorcraft_text::FontDb::global(); // The face of that family and style (the font database gives a fallback face for others). + let record = |name: String| FontRecord { name, truetype: false, design: vec![], version: String::new() }; match db .face_version(&st.font_family, &st.font_style, st.font_version.as_deref()) .filter(|f| f.family == st.font_family && f.style == st.font_style) { - Some(face) => (face.postscript_name(), face.is_truetype()), - None if st.font_style.is_empty() || st.font_style == "Regular" => (st.font_family.clone(), false), - None => (format!("{}-{}", st.font_family, st.font_style.replace(' ', "")), false), + Some(face) => { + let axes = face.axes(); + let design: Vec = axes + .iter() + .map(|a| { + let own = face.axis_value(a.tag).unwrap_or(a.default); + let set = st.font_axes.get(String::from_utf8_lossy(&a.tag).as_ref()).copied().filter(|v| v.is_finite()); + set.map_or(own, |v| (v as f32).clamp(a.min.min(a.max), a.max.max(a.min))) + }) + .collect(); + let version = if design.is_empty() { String::new() } else { face.version.clone() }; + FontRecord { name: face.postscript_name(), truetype: face.is_truetype(), design, version } + } + None if st.font_style.is_empty() || st.font_style == "Regular" => record(st.font_family.clone()), + None => record(format!("{}-{}", st.font_family, st.font_style.replace(' ', ""))), } } +/// `v` as the 16.16 fixed-point number a design vector holds (`wght` 700 is 45875200). +fn fixed(v: f32) -> i64 { + if v.is_finite() { (f64::from(v) * 65536.0).round() as i64 } else { 0 } +} + /// Does the font of style `st` come back as itself: the family and style the reader makes of the /// name it is written under (as its `char_style` does)? fn font_kept(st: &CharStyle) -> bool { - let (family, style) = crate::family_style(&font_name(st).0); + let (family, style) = crate::family_style(&font_name(st).name); let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); family == st.font_family && style == st.font_style } @@ -507,8 +542,8 @@ fn place_on(segments: &[[f64; 8]], f: f64) -> f64 { /// The text document being written. #[derive(Default)] pub(in crate::ai_editing) struct TextDoc { - /// Each font's PostScript name and whether it's TrueType. - fonts: Vec<(String, bool)>, + /// The fonts the runs name, each once: two settings of one variable font are two fonts. + fonts: Vec, frames: Vec, stories: Vec, /// The story and frame each text object of a thread is written as. @@ -533,11 +568,15 @@ impl TextDoc { /// The index of the font of `st` in the font set. fn font(&mut self, st: &CharStyle) -> i64 { - let (name, truetype) = font_name(st); - let i = match self.fonts.iter().position(|(n, _)| *n == name) { + let font = font_name(st); + // Two installed versions of one font are two fonts, so each keeps its own `/5`. + let same = |f: &FontRecord| { + f.name == font.name && f.version == font.version && f.design.iter().map(|v| fixed(*v)).eq(font.design.iter().map(|v| fixed(*v))) + }; + let i = match self.fonts.iter().position(same) { Some(i) => i, None => { - self.fonts.push((name, truetype)); + self.fonts.push(font); self.fonts.len() - 1 } }; @@ -806,7 +845,9 @@ impl TextDoc { let total = bytes.saturating_add(added); let total_values = self.doc_values.saturating_add(values); // The font set: each name in UTF-16 with its dictionary round it. - let fonts: usize = self.fonts.iter().map(|(n, _)| n.encode_utf16().count() * 2 + 64).sum(); + // A design vector's numbers and a version string add to it. + let fonts: usize = + self.fonts.iter().map(|f| f.name.encode_utf16().count() * 2 + 64 + f.design.len() * 12 + f.version.encode_utf16().count() * 2).sum(); // ASCII85 writes five characters for every four bytes. if total.saturating_add(RESERVE).saturating_add(fonts).saturating_mul(5) / 4 <= crate::import::MAX_TEXT_DOCUMENT / 4 && total_values.saturating_add(RESERVE_VALUES) <= crate::import::MAX_TEXT_VALUES @@ -924,8 +965,17 @@ impl TextDoc { let mut fonts: Vec = self .fonts .iter() - .map(|(name, truetype)| { - dict(vec![(99, V::Name("CoolTypeFont")), (0, dict(vec![(0, V::Str(name.clone())), (2, V::Int(i64::from(*truetype)))]))]) + .map(|f| { + let mut font = vec![(0, V::Str(f.name.clone())), (2, V::Int(i64::from(f.truetype)))]; + // A variable font's place in its design space and its version (#6388); a static + // font has neither. + if !f.design.is_empty() { + font.push((4, V::List(f.design.iter().map(|v| V::Int(fixed(*v))).collect()))); + if !f.version.is_empty() { + font.push((5, V::Str(f.version.clone()))); + } + } + dict(vec![(99, V::Name("CoolTypeFont")), (0, dict(font))]) }) .collect(); fonts.push(dict(vec![(99, V::Name("CoolTypeFont")), (0, dict(vec![(0, V::Str(HIDDEN_GLYPH_FONT.into())), (2, V::Int(0))]))])); diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index b353a00887..be2d679a78 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -37,6 +37,7 @@ use crate::ps; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; #[cfg(test)] pub(crate) use envelope::MAX_CHECKED; +pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN; pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType}; pub(crate) use frames::text_frames; pub use obj::{NameEncoding, Names}; diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index a421bbd6a3..c0da27f2a9 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -23,7 +23,7 @@ //! one-patch mesh. An envelope whose parts don't read, or that doesn't come out as drawn, keeps its //! drawn art. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; use kurbo::{Affine, BezPath, Point, Rect, Vec2}; @@ -35,14 +35,23 @@ use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, LayerColor, Node, use vectorcraft_geom::PathData; use super::obj::Obj; -use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour}; +use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour, differ_on_black}; /// The plugin that writes envelopes. pub(super) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use /// The note for an envelope that keeps its drawn art. pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live envelope comes in as its drawn art"; +/// The note for an envelope of type, which keeps its drawn art with its type hidden (unless the +/// text document gives the type nothing, which a note of its own then says). +pub(crate) const TYPE_DRAWN: &str = "type in an envelope comes in as the envelope's drawn art, not as editable type"; /// The note for warped type that keeps its drawn art, before how many. pub(crate) const WARPED_TYPE_DRAWN: &str = "warped text objects that came in as drawn art, not as editable type"; + +/// The note for an envelope that keeps its drawn art: [`TYPE_DRAWN`] for an envelope of type +/// (`typed`), else [`DRAWN`]. +pub(crate) fn drawn_note(typed: bool) -> &'static str { + if typed { TYPE_DRAWN } else { DRAWN } +} /// The most envelopes waiting for their drawn art at once. pub(super) const MAX_PENDING: usize = 64; /// The most envelopes and warped text objects one import draws to check; more keep their drawn art. @@ -325,9 +334,9 @@ fn alone(node: &Node, layer: NodeId, shared: &Shared<'_>) -> Document { } /// How `live` and `drawn`, drawn over `region` at `scale`, differ: the pixels that differ in -/// lightness or colour, those whose neighbours all differ too (where one draws something the other -/// doesn't, not an edge drawn a little apart), and the pixels either inks. `None` when they can't -/// be drawn. +/// lightness or colour, seen on white or on black (each is drawn on its own: white art shows only on +/// black), those whose neighbours all differ too (where one draws something the other doesn't, not +/// an edge drawn a little apart), and the pixels either inks. `None` when they can't be drawn. fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Option<(usize, usize, usize)> { let x = vectorcraft_render::Renderer::new().render_region(live, region, scale, false); let y = vectorcraft_render::Renderer::new().render_region(drawn, region, scale, false); @@ -336,7 +345,7 @@ fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Opt } let (w, h) = (x.width as usize, x.height as usize); let (xs, ys) = (x.pixels.as_chunks::<4>().0, y.pixels.as_chunks::<4>().0); - let differs: Vec = xs.iter().zip(ys).map(|(p, q)| differ(p, q) || differ_in_colour(p, q)).collect(); + let differs: Vec = xs.iter().zip(ys).map(|(p, q)| differ(p, q) || differ_in_colour(p, q) || differ_on_black(p, q)).collect(); let inked = xs.iter().zip(ys).filter(|(p, q)| p[3] > 8 || q[3] > 8).count(); let at = |i: usize, j: usize| differs.get(j * w + i).copied().unwrap_or(false); let any = differs.iter().filter(|d| **d).count(); @@ -368,18 +377,160 @@ pub(super) struct WarpedLook { pub(super) left_out: Option, } -/// The text objects read with a Warp, and what the import has left of the budget for checks -/// ([`drawn_alike`]). Type is laid out after the layers are read, so these wait for that -/// ([`Self::settle`]). +/// An envelope of type read with its drawn art: its dictionary, the group on `%_` lines before it +/// and the art in its `AIDeformArtKey` block, as [`live`] takes them (their text slots still +/// empty), and the id of its drawn art in the document. Type is laid out after the layers are read, +/// so it waits for that ([`WarpedType::settle_envelopes`]). +#[derive(Debug)] +pub(crate) struct TypedEnvelope { + pub(super) obj: Obj, + pub(super) before: Option, + pub(super) inner: Vec, + pub(super) drawn: NodeId, +} + +/// Why an envelope of type kept its drawn art. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum TypeKept { + /// Its type is set in a font that isn't available: the fallback font doesn't draw as the file. + Font, + /// A text slot of it has no type of its own (none made, or type a look draws, threaded type, + /// type bound to a variable or a wrap object). + Type, + /// Its parts don't make a live envelope, or its drawn art is gone. + Read, + /// The import has no check left. + Budget, + /// Its live envelope doesn't draw as its drawn art. + Differs, +} + +/// What [`WarpedType::settle_envelopes`] did. +#[derive(Debug, Default)] +pub(crate) struct TypedSettled { + /// How many envelopes of type opened live. + pub(crate) live: usize, + /// Why each of the others kept its drawn art. + pub(crate) kept: Vec, + /// Each live envelope's id, with what takes its place again when the layers with it don't draw + /// as the page: its hidden type, then its drawn art. + pub(crate) put_back: Vec<(NodeId, Vec)>, +} + +/// The text objects read with a Warp and the envelopes of type, and what the import has left of the +/// budget for checks ([`drawn_alike`]). Type is laid out after the layers are read, so these wait +/// for that ([`Self::settle`], [`Self::settle_envelopes`]). #[derive(Debug, Default)] pub struct WarpedType { pub(super) looks: Vec, + pub(super) envelopes: Vec, pub(super) checks: usize, pub(super) spent: Spent, pub(super) page: Option, } impl WarpedType { + /// Are envelopes of type waiting for their type? + pub(crate) fn has_envelopes(&self) -> bool { + !self.envelopes.is_empty() + } + + /// These, for layers `compared` with a page. Layers that aren't leave the envelopes of type + /// their drawn art and their hidden type, with the note ([`TYPE_DRAWN`]) added to `notes`: a + /// live envelope opens only where the page chooses it. + pub(crate) fn compared(mut self, compared: bool, notes: &mut Vec) -> Self { + if !compared && !std::mem::take(&mut self.envelopes).is_empty() && !notes.iter().any(|n| n == TYPE_DRAWN) { + notes.push(TYPE_DRAWN.into()); + } + self + } + + /// Make each envelope of type live where it draws as its drawn art, its contents' text slots + /// holding their type: `type_of` gives, for a slot's id, the hidden text object it became in + /// `doc` and the type the contents take in its place (the slot's visibility and lock are the + /// type's). The live envelope takes its drawn art's place and the hidden type goes. Each check + /// uses one of the import's checks and, for an envelope that shows, adds to what the page check + /// allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't + /// available, the drawn art and the hidden type stay. + pub(crate) fn settle_envelopes(&mut self, doc: &mut Document, type_of: impl Fn(&Document, NodeId) -> Option<(NodeId, Node)>) -> TypedSettled { + let mut settled = TypedSettled::default(); + if self.envelopes.is_empty() { + return settled; + } + let mut shown = BTreeSet::new(); + doc.layers.iter().for_each(|l| collect_shown(l, &mut shown)); + for envelope in std::mem::take(&mut self.envelopes) { + match self.typed_live(doc, envelope, &type_of, &shown) { + Ok(put_back) => { + settled.live += 1; + settled.put_back.push(put_back); + } + Err(why) => settled.kept.push(why), + } + } + settled + } + + /// [`Self::settle_envelopes`] for `envelope`, the shown objects of `doc` being `shown`: the live + /// envelope's id and what takes its place again, or why its drawn art stays. + fn typed_live( + &mut self, + doc: &mut Document, + envelope: TypedEnvelope, + type_of: &impl Fn(&Document, NodeId) -> Option<(NodeId, Node)>, + shown: &BTreeSet, + ) -> Result<(NodeId, Vec), TypeKept> { + let TypedEnvelope { obj, mut before, mut inner, drawn } = envelope; + let art = doc.node(drawn).cloned().ok_or(TypeKept::Read)?; + // The text slots in the contents, in the order the reader put their hidden copies in. + let mut slots = vec![]; + before.iter().chain(&inner).for_each(|n| text_slots_in(n, &mut slots)); + if slots.is_empty() { + return Err(TypeKept::Type); + } + let db = vectorcraft_text::FontDb::global(); + let (mut texts, mut hidden) = (HashMap::new(), vec![]); + for (slot, look) in slots { + let (id, mut text) = type_of(doc, slot).filter(|_| !look).ok_or(TypeKept::Type)?; + let NodeKind::Text(t) = &text.kind else { return Err(TypeKept::Type) }; + if t.runs.iter().any(|r| r.style.font_family.is_empty() || !db.has_family(&r.style.font_family)) { + return Err(TypeKept::Font); + } + text.id = doc.alloc_id(); + texts.insert(slot, text); + hidden.push(id); + } + for n in before.iter_mut().chain(inner.iter_mut()) { + put_type(n, &texts); + } + let kind = live(&obj, before, inner).ok_or(TypeKept::Read)?; + if self.checks == 0 { + return Err(TypeKept::Budget); + } + self.checks -= 1; + let mut envelope = art.clone(); + (envelope.id, envelope.kind) = (doc.alloc_id(), kind); + let layer = doc.alloc_id(); + let shared = Shared { patterns: &doc.patterns, images: &doc.images }; + let (mut live_one, mut plain) = (envelope.clone(), art.clone()); + (live_one.visible, live_one.opacity) = (true, 1.0); + (plain.visible, plain.opacity) = (true, 1.0); + let page = self.page.filter(|_| shown.contains(&drawn)); + if !drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) { + return Err(TypeKept::Differs); + } + if doc.node(drawn).is_none() { + return Err(TypeKept::Read); + } + // The type is the envelope's now: its hidden copy goes, kept for when the drawn art comes back. + let mut put_back: Vec = hidden.into_iter().filter_map(|id| doc.remove(id).ok()).map(Arc::unwrap_or_clone).collect(); + let id = envelope.id; + let Some(slot) = doc.node_mut(drawn) else { return Err(TypeKept::Read) }; + *slot = envelope; + put_back.push(art); + Ok((id, put_back)) + } + /// Replace each warped text object of `doc` that doesn't draw as its saved look (or that the /// budget has no check left for) with that look: `made` gives the text object a slot became. A /// frame in `threaded` stays type, since the frames of a thread share one story. A replaced @@ -392,7 +543,7 @@ impl WarpedType { threaded: &BTreeSet, restyled: &mut Vec, ) -> usize { - let Self { looks, mut checks, mut spent, page } = self; + let Self { looks, mut checks, mut spent, page, .. } = self; let mut shown_ids = BTreeSet::new(); doc.layers.iter().for_each(|l| collect_shown(l, &mut shown_ids)); let mut replaced = 0; @@ -436,6 +587,29 @@ impl WarpedType { } } +/// The ids of the text slots in `n` and its groups, in order, each with whether it is a slot of type +/// that a look draws ([`super::is_look_slot`]). +fn text_slots_in(n: &Node, out: &mut Vec<(NodeId, bool)>) { + let look = super::is_look_slot(n.name.as_deref()); + if look || super::slot_of(n.name.as_deref()).is_some() { + out.push((n.id, look)); + } else if !matches!(n.kind, NodeKind::Compound { .. }) { + n.children().into_iter().flatten().for_each(|c| text_slots_in(c, out)); + } +} + +/// `n` with each text slot in it or its groups replaced by its type in `texts`, by the slot's id, +/// shown and locked as the slot is. +fn put_type(n: &mut Node, texts: &HashMap) { + if let Some(text) = texts.get(&n.id) { + let (visible, locked) = (n.visible, n.locked); + *n = text.clone(); + (n.visible, n.locked) = (visible, locked); + } else if !matches!(n.kind, NodeKind::Compound { .. }) { + n.children_mut().into_iter().flatten().for_each(|c| put_type(Arc::make_mut(c), texts)); + } +} + /// Add to `out` the ids of `n` and what is in it, unless hidden. fn collect_shown(n: &Node, out: &mut BTreeSet) { if n.visible { diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index 3937045dbe..4f667fbe45 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -133,7 +133,7 @@ impl Space { } /// A named colour or ink's full colour: `[c m y k /DeviceCMYK (name) /kind]` or `[r g b /DeviceRGB …]`. -fn ink(a: &[V]) -> Option { +pub(super) fn ink(a: &[V]) -> Option { let at = a.iter().position(|v| matches!(v, V::Name(_)))?; let nums: Vec = a.get(..at)?.iter().map(|v| v.num().filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0) as f32)).collect::>()?; match (a.get(at).and_then(V::text).as_deref(), nums.as_slice()) { diff --git a/crates/eps/src/import/ai/paint.rs b/crates/eps/src/import/ai/paint.rs index a25f2b82af..5f39c3b977 100644 --- a/crates/eps/src/import/ai/paint.rs +++ b/crates/eps/src/import/ai/paint.rs @@ -72,6 +72,37 @@ pub(super) fn color_op_in(op: &str, vals: &[V], names: &mut Names) -> Option<(Pa } } +/// `n [c m y k /DeviceCMYK (name) /Separation] XC` (or `[r g b /DeviceRGB …]`) before an image: its +/// samples are one ink's tints. The ink at 100 % as a paint, with the named colour that makes its +/// spot swatch (none for Registration). `None` for a device space (`/DeviceGray XC`), the ink +/// `None`, which paints nothing, or another form. +pub(super) fn separation_ink(vals: &[V], names: &mut Names) -> Option<(Paint, Option)> { + let a = vals.iter().rev().find_map(|v| if let V::Arr(a) = v { Some(a) } else { None })?; + let [.., name @ V::Str(_), V::Name(kind)] = a.as_slice() else { return None }; + if kind.trim_start_matches('/') != "Separation" { + return None; + } + let color = super::mesh::ink(a)?; + let name = names.text(name)?; + if name == "None" { + return None; + } + if is_registration(&name) { + let paint = Paint::Solid { color: Color::cmyk(1.0, 1.0, 1.0, 1.0), swatch: Some(vectorcraft_color::swatch::REGISTRATION.into()), tint: 1.0 }; + return Some((paint, None)); + } + // A process plate is its CMYK colour, not a spot ink: no swatch of its name. + if let Some(plate) = ["Cyan", "Magenta", "Yellow", "Black"].iter().position(|p| *p == name) { + let mut cmyk = [0.0; 4]; + if let Some(v) = cmyk.get_mut(plate) { + *v = 1.0; + } + return Some((Paint::solid(Color::cmyk(cmyk[0], cmyk[1], cmyk[2], cmyk[3])), None)); + } + let paint = Paint::Solid { color, swatch: Some(name.clone()), tint: 1.0 }; + Some((paint, Some(Named { name, color, tint: 1.0, spot: true }))) +} + fn is_registration(name: &str) -> bool { matches!(name, vectorcraft_color::swatch::REGISTRATION | "Registration" | "/All" | "All" | "/[Registration]") } diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index cb0bc19090..5a253f21a3 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -557,6 +557,9 @@ struct Reader<'a> { envelope_spent: super::envelope::Spent, /// The text objects read with a Warp ([`super::envelope::WarpedType`]). warped_type: Vec, + /// The envelopes of type read with their drawn art, settled once the type is laid out + /// ([`super::envelope::TypedEnvelope`]). + typed_envelopes: Vec, /// The live envelopes made so far and the drawn art each took the place of /// ([`Structure::envelopes_drawn`]). envelopes_drawn: Vec<(NodeId, Node)>, @@ -769,6 +772,7 @@ impl<'a> Reader<'a> { envelope_checks: super::envelope::MAX_CHECKED, envelope_spent: super::envelope::Spent::default(), warped_type: Vec::new(), + typed_envelopes: Vec::new(), envelopes_drawn: Vec::new(), clip_fills: HashSet::new(), looks: HashSet::new(), diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 7d2565172d..3d859bf74e 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -472,10 +472,34 @@ impl<'a> Reader<'a> { return Ok(()); }; let opacity = opacity.filter(|_| alpha_len > 0); + // An image in one ink's Separation space (`XC`): its samples are the ink's tints, the most + // at 100 % (255, or a set bit). It comes in as a grayscale image of them, black at 100 %, + // that the ink colorizes, as a Separation image opens from a PDF; its alpha channel + // becomes its opacity mask. + let ink = if channels == 1 && !image_mask { self.raster.as_mut().and_then(|r| r.ink.take()) } else { None }; + let inverted; + let samples = if ink.is_some() { + inverted = samples.iter().map(|b| !b).collect::>(); + inverted.as_slice() + } else { + samples + }; + let ink = ink.map(|(paint, named)| { + // Its colour counts toward the document's colour model, as a fill's does (Registration + // says nothing of it). + let registration = matches!(&paint, Paint::Solid { swatch: Some(s), .. } if s == vectorcraft_color::swatch::REGISTRATION); + match paint.color().filter(|_| !registration) { + Some(vectorcraft_color::Color::Rgb { .. }) => self.rgb_colors += 1, + Some(vectorcraft_color::Color::Cmyk { .. }) => self.cmyk_colors += 1, + _ => {} + } + self.spots.extend(named); + paint + }); let gray1 = *bits == 1.0 && channels == 1 && opacity.is_none(); if k > 1 || w * h > raster::SMALL || (gray1 && !image_mask) { - // An image mask keeps the color that colorizes it. - let colorize = (image_mask && channels == 1 && *bits == 1.0).then(|| self.mask_paint()); + // An image mask keeps the color that colorizes it, an ink image its ink. + let colorize = if image_mask && channels == 1 && *bits == 1.0 { Some(self.mask_paint()) } else { ink }; return self.large_image(samples, opacity, shape, k, &m, colorize); } // CMYK samples keep their ink amounts as a CMYK TIFF, as the PDF importer keeps a CMYK @@ -487,7 +511,11 @@ impl<'a> Reader<'a> { return self.add_raster(blob, opacity, &m, (w as u32, h as u32), None); } if image_mask && channels == 1 && *bits == 1.0 { - return self.colorized_raster(samples, row, opacity, &m, (w as u32, h as u32)); + let paint = self.mask_paint(); + return self.colorized_raster(samples, (row, 1), opacity, &m, (w as u32, h as u32), paint); + } + if let Some(paint) = ink { + return self.colorized_raster(samples, (row, *bits as u8), opacity, &m, (w as u32, h as u32), paint); } let mut rgba = Vec::with_capacity((w * h * 4) as usize); for y in 0..h as usize { @@ -526,15 +554,24 @@ impl<'a> Reader<'a> { self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32), None) } - /// A 1-bit gray image whose ImageMask is 1 (`samples`, `row` bytes a row): a grayscale image - /// colorized with the fill color. Its 0 bits, which open black with ImageMask 0, take that color, - /// and its 1 bits are transparent. A fill that isn't a solid color colorizes it black. - fn colorized_raster(&mut self, samples: &[u8], row: usize, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32)) -> Result<(), String> { + /// A one-channel image (`samples` of `bits` bits, `row` bytes a row) as a grayscale image + /// colorized with `paint`: a 1-bit gray image whose ImageMask is 1, with the fill color (its 0 + /// bits, which open black with ImageMask 0, take that color, and its 1 bits are transparent; a + /// fill that isn't a solid color colorizes it black), or an ink's tints, inverted, with the ink. + fn colorized_raster( + &mut self, + samples: &[u8], + (row, bits): (usize, u8), + alpha: Option<&[u8]>, + m: &[f64], + (w, h): (u32, u32), + paint: Paint, + ) -> Result<(), String> { let mut gray = Vec::with_capacity(w as usize * h as usize); for y in 0..h as usize { let line = samples.get(y * row..(y + 1) * row).unwrap_or_default(); for x in 0..w as usize { - let v = line.get(x / 8).map_or(0, |b| ((b >> (7 - x % 8)) & 1) * 255); + let v = if bits == 1 { line.get(x / 8).map_or(0, |b| ((b >> (7 - x % 8)) & 1) * 255) } else { line.get(x).copied().unwrap_or(0) }; gray.push(v); } } @@ -544,7 +581,6 @@ impl<'a> Reader<'a> { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); } - let paint = self.mask_paint(); self.add_raster(ImageBlob::new("image/png", png), alpha, m, (w, h), Some(paint)) } @@ -625,12 +661,15 @@ impl<'a> Reader<'a> { return self.add_raster(ImageBlob::new("image/png", png), None, m, (ow, oh), colorize); } let cmyk = s.channels == 4; - let (pixels, mask) = raster::reduce(samples, opacity, s, k, !cmyk); + // A colorized image's alpha channel becomes its opacity mask, as at its full size: a + // grayscale image whose pixels have alpha takes only a spot color, black or white. + let inline = !cmyk && colorize.is_none(); + let (pixels, mask) = raster::reduce(samples, opacity, s, k, inline); let blob = if cmyk { Inks::new(ow, oh, pixels).and_then(|i| ImageBlob::cmyk_tiff(&i)) } else { use image::ImageEncoder as _; - let colour = match (s.channels, opacity.is_some()) { + let colour = match (s.channels, inline && opacity.is_some()) { (1, false) => image::ExtendedColorType::L8, (1, true) => image::ExtendedColorType::La8, (_, false) => image::ExtendedColorType::Rgb8, diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 35c0f46ae6..02f6f8097c 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -516,16 +516,17 @@ impl<'a> Reader<'a> { slot.visible = false; self.add(slot, false)?; } - // An envelope of type keeps its drawn art and its type, hidden, as above: the - // type is filled in after reading, which the envelope can't wait for. - if typed { - return Ok(()); - } - if self.envelopes.len() >= crate::import::ai::envelope::MAX_PENDING { - self.warn(crate::import::ai::envelope::DRAWN); + // An envelope of type keeps its drawn art and its type, hidden, as above, until + // the type is filled in after reading: then it opens live where it draws as its + // drawn art ([`crate::import::ai::envelope::TypedEnvelope`]). In a symbol's or a + // pattern's art it keeps them. + let waits = !typed || (self.symbol.is_none() && self.pattern.is_none()); + if !waits || self.envelopes.len() >= crate::import::ai::envelope::MAX_PENDING { + self.warn(crate::import::ai::envelope::drawn_note(typed)); } else { let siblings = self.frames.last().map_or(0, |f| f.children.len()); - self.envelopes.push(PendingEnvelope { obj: *o, before, inner: children, depth: self.frames.len(), siblings }); + let depth = self.frames.len(); + self.envelopes.push(PendingEnvelope { obj: *o, before, inner: children, depth, siblings, typed }); } } } @@ -862,9 +863,8 @@ impl<'a> Reader<'a> { /// in containers that closed keep their drawn art. pub(super) fn end_envelope(&mut self) { let depth = self.frames.len(); - while self.envelopes.last().is_some_and(|p| p.depth > depth) { - self.envelopes.pop(); - self.warn(crate::import::ai::envelope::DRAWN); + while let Some(p) = self.envelopes.pop_if(|p| p.depth > depth) { + self.warn(crate::import::ai::envelope::drawn_note(p.typed)); } if self.envelopes.last().is_none_or(|p| p.depth != depth) { return; @@ -872,9 +872,13 @@ impl<'a> Reader<'a> { let Some(p) = self.envelopes.pop() else { return }; let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last()); let Some(drawn) = drawn else { - self.warn(crate::import::ai::envelope::DRAWN); + self.warn(crate::import::ai::envelope::drawn_note(p.typed)); return; }; + if p.typed { + self.wait_for_type(p); + return; + } let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner)).flatten(); let Some(kind) = live else { self.warn(crate::import::ai::envelope::DRAWN); @@ -931,6 +935,32 @@ impl<'a> Reader<'a> { } } +impl Reader<'_> { + /// An envelope of type `p` whose drawn art was just read (the last object of this container): + /// it waits for its type to be laid out ([`crate::import::ai::envelope::TypedEnvelope`]), unless + /// objects the reader couldn't read are in it, or too many already wait. Then it keeps its + /// drawn art and its type, hidden. + fn wait_for_type(&mut self, p: PendingEnvelope) { + let Some(drawn) = self.frames.last().and_then(|f| f.children.last()) else { return }; + let mut ids = HashSet::new(); + fn collect(n: &Node, ids: &mut HashSet) { + ids.insert(n.id); + for c in n.children().into_iter().flatten() { + collect(c, ids); + } + } + collect(drawn, &mut ids); + p.before.iter().chain(&p.inner).for_each(|n| collect(n, &mut ids)); + let unread = self.unread.iter().any(|(id, _)| ids.contains(id)); + if unread || self.typed_envelopes.len() >= crate::import::ai::envelope::MAX_CHECKED { + self.warn(crate::import::ai::envelope::TYPE_DRAWN); + return; + } + let drawn = drawn.id; + self.typed_envelopes.push(crate::import::ai::envelope::TypedEnvelope { obj: p.obj, before: p.before, inner: p.inner, drawn }); + } +} + /// Does `node` hold a text slot? fn has_text_slot(node: &Node) -> bool { let mut slots = vec![]; diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index e1fbe0d4d5..f7df4f35d6 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -181,9 +181,13 @@ impl<'a> Reader<'a> { } else if line.starts_with("AI5_EndRaster") { // A file `XG` named in this raster object is no later one's. self.image_link = None; - if let Some(Raster { operands: Some(vals), mut samples, half, max, .. }) = self.raster.take() { + if let Some(Raster { operands: Some(vals), mut samples, half, max, ink, .. }) = self.raster.take() { end_hex(&mut samples, half, max); - return self.image_from(vals, &samples, true); + // The image's ink (`XC`) stays for `image_from` to read. + self.raster = Some(Raster { ink, ..Raster::default() }); + let read = self.image_from(vals, &samples, true); + self.raster = None; + return read; } } else if line.starts_with("AI5_BeginPlace") { // One that is still open (no `~` ended it) isn't read. diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 1b962064c8..63e9f3df77 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1165,9 +1165,8 @@ impl<'a> Reader<'a> { self.warn(super::types::GRAPH_UNENDED); } // Envelopes whose plugin never closed them keep their drawn art. - if !self.envelopes.is_empty() { - self.envelopes.clear(); - self.warn(crate::import::ai::envelope::DRAWN); + for p in std::mem::take(&mut self.envelopes) { + self.warn(crate::import::ai::envelope::drawn_note(p.typed)); } if !self.unknown.is_empty() { let ops: Vec = self.unknown.iter().map(|o| format!("`{o}`")).collect(); @@ -1297,6 +1296,11 @@ impl<'a> Reader<'a> { for w in &mut self.warped_type { vectorcraft_doc::swatches::map_node_solid_paints(&mut w.look, &mut follow); } + for e in &mut self.typed_envelopes { + for n in e.before.iter_mut().chain(e.inner.iter_mut()) { + vectorcraft_doc::swatches::map_node_solid_paints(n, &mut follow); + } + } } let mut warnings = self.warnings; if let Some((lib, unread)) = brushes { @@ -1341,6 +1345,7 @@ impl<'a> Reader<'a> { envelopes_drawn: self.envelopes_drawn, warped_type: super::super::envelope::WarpedType { looks: self.warped_type, + envelopes: self.typed_envelopes, checks: self.envelope_checks, spent: self.envelope_spent, page, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index f584f26c27..6c84eff236 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -361,6 +361,14 @@ impl<'a> Reader<'a> { r.space = vals.iter().rev().find_map(V::text); } } + // `n [… (name) /Separation] XC`: the image's samples are that ink's tints. A device + // space (`/DeviceGray XC` after a linked image's file name) changes nothing read here. + "XC" => { + let ink = paint::separation_ink(&vals, &mut self.names); + if let Some(r) = self.raster.as_mut() { + r.ink = ink; + } + } // Placed files. // `[a b c d tx ty] llx lly urx ury (path) `` ` ``, three more numbers before the path in // newer files: the version 7 form has no `%AI5_BeginPlace` before it. Before the art, diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index b07270ef82..6457c1cde1 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -224,6 +224,9 @@ pub(super) struct PendingEnvelope { /// had: its drawn art is the one child after them. pub(super) depth: usize, pub(super) siblings: usize, + /// Its contents hold type: it is settled once the type is laid out + /// ([`super::super::envelope::TypedEnvelope`]). + pub(super) typed: bool, } /// What a reader of a pattern's definition has of its head, `(name) llx lly urx ury`: the operands @@ -279,6 +282,9 @@ impl BrushArtColors { #[derive(Debug, Default)] pub(super) struct Raster { pub(super) space: Option, + /// The ink of an image in a Separation space (`XC`): its paint at 100 % and the named colour + /// for its swatch (`paint::separation_ink`). + pub(super) ink: Option<(Paint, Option)>, /// `XI`'s operands when its samples follow as hex in comment lines (`%FF00…`) up to /// `%AI5_EndRaster`, the form the version 7 specification documents (§8). pub(super) operands: Option>, @@ -370,8 +376,6 @@ pub(super) const IGNORED: &[&str] = &[ "As", "Xd", "Xr", - // `/DeviceGray XC` after a linked image's file name (`XG`): its colour space. - "XC", "Xh", "XH", "Bc", diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 2d6aa99678..2b127e275b 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2755,6 +2755,108 @@ fn image_masks_are_colorized_with_the_fill() { assert_eq!(pixels(&doc).0.get_pixel(0, 0).0, [255, 0, 0, 255]); } +/// A gray image `w` × 1 (`bits` bits a pixel, `alpha` channels, data `data`) whose colour space is +/// set by `xc` (the operands of `XC`) instead of `/DeviceGray XN`. +fn ink_image(xc: &str, bits: u32, alpha: u32, w: u32, data: &[u8]) -> Vec { + let mut out = image("[ 1 0 0 1 0 100 ]", (w, 1), ("DeviceGray", 1, alpha), data, data.len() + 3); + // In place, as bytes: the samples aren't text. + let mut swap = |from: &[u8], to: &[u8]| { + let at = out.windows(from.len()).position(|s| s == from).unwrap(); + out.splice(at..at + from.len(), to.iter().copied()); + }; + swap(b"/DeviceGray XN\n", format!("{xc} XC\n").as_bytes()); + swap(format!(" 8 1 {alpha} 0 1 0 ").as_bytes(), format!(" {bits} 1 {alpha} 0 1 0 ").as_bytes()); + out +} + +/// An image in one ink's Separation space (`n [… (name) /Separation] XC`): its samples are the +/// ink's tints (255 at 100 %), so it opens as a grayscale image of them, black at 100 %, colorized +/// by the ink's spot swatch; its alpha channel becomes its opacity mask. +#[test] +fn separation_images_are_colorized_with_their_ink() { + let black = "1 [0 0 0 1 /DeviceCMYK (Black Ink) /Separation]"; + let r = read(&ink_image(black, 8, 0, 3, &[0, 128, 255])).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let a = art(&r.doc); + let Some(Paint::Solid { color, swatch: Some(swatch), tint }) = a[0].extras().colorize.as_deref() else { panic!("{:?}", a[0].extras().colorize) }; + assert_eq!((swatch.as_str(), *tint), ("Black Ink", 1.0)); + assert_eq!(color.to_rgba8(1.0), Color::cmyk(0.0, 0.0, 0.0, 1.0).to_rgba8(1.0)); + assert!(r.doc.swatch("Black Ink").is_some_and(|s| s.spot), "a spot swatch for the ink"); + let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(r.doc.images[&im.key].gray_source().is_some_and(|g| !g.alpha)); + let img = pixels(&r.doc).0; + assert_eq!((0..3).map(|x| img.get_pixel(x, 0).0[0]).collect::>(), [255, 127, 0], "no ink is white, 100 % black"); + + // An RGB alternate gives the ink's colour; an alpha channel becomes the opacity mask. + let white = "1 [1 1 1 /DeviceRGB (White Ink) /Separation]"; + let r = read(&ink_image(white, 8, 1, 2, &[255, 255, 255, 0])).unwrap(); + let a = art(&r.doc); + let Some(Paint::Solid { color, swatch: Some(swatch), .. }) = a[0].extras().colorize.as_deref() else { panic!("{:?}", a[0].extras().colorize) }; + assert_eq!((swatch.as_str(), color.to_rgba8(1.0)), ("White Ink", Color::rgb(1.0, 1.0, 1.0).to_rgba8(1.0))); + assert!(a[0].extras().mask.is_some(), "the alpha channel as an opacity mask"); + + // 1 bit a pixel: a set bit is the ink at 100 % (101). + let r = read(&ink_image(black, 1, 0, 3, b"\xa0")).unwrap(); + let a = art(&r.doc); + assert!(a[0].extras().colorize.is_some()); + let img = pixels(&r.doc).0; + assert_eq!((0..3).map(|x| img.get_pixel(x, 0).0[0]).collect::>(), [0, 255, 0]); + + // A device space, and the ink None (which paints nothing), leave the image as it was. + for xc in ["/DeviceGray", "1 [0 0 0 1 /DeviceCMYK (None) /Separation]"] { + let doc = read(&ink_image(xc, 8, 0, 2, &[0, 200])).unwrap().doc; + assert!(art(&doc)[0].extras().colorize.is_none(), "{xc}"); + assert_eq!(pixels(&doc).0.get_pixel(1, 0).0, [200, 200, 200, 255], "{xc}"); + } +} + +/// A process plate's Separation colorizes in the plate's CMYK colour, with no swatch of its name; +/// Registration in the Registration colour. +#[test] +fn separation_images_of_process_plates_and_registration() { + let r = read(&ink_image("1 [0 0 0 1 /DeviceCMYK (Black) /Separation]", 8, 0, 2, &[0, 255])).unwrap(); + assert_eq!(art(&r.doc)[0].extras().colorize.as_deref(), Some(&Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)))); + assert!(r.doc.swatches.iter().all(|s| !s.spot), "no spot swatch for a process plate"); + let r = read(&ink_image("1 [1 1 1 1 /DeviceCMYK (All) /Separation]", 8, 0, 2, &[0, 255])).unwrap(); + let swatch = art(&r.doc)[0].extras().colorize.as_deref().and_then(|p| if let Paint::Solid { swatch, .. } = p { swatch.clone() } else { None }); + assert_eq!(swatch.as_deref(), Some(vectorcraft_color::swatch::REGISTRATION)); +} + +/// The version 7 form, with samples in hex comment lines after `XI`, keeps the image's ink. +#[test] +fn a_separation_image_with_hex_comment_lines_keeps_its_ink() { + let s = "%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n\ + 1 [0 0 0 1 /DeviceCMYK (Black Ink) /Separation] XC\n[ 1 0 0 1 0 100 ] 3 1 0 Xh\n\ + [ 1 0 0 1 0 100 ] 0 0 3 1 3 1 8 1 0 0 0 0 XI\n%0080FF\n%AI5_EndRaster\nN\nLB\n%AI5_EndLayer--\n"; + let mut data = stream("").into_bytes(); + let at = data.windows(14).position(|w| w == b"%%PageTrailer\n").unwrap(); + data.splice(at..at, s.bytes()); + let r = read(&data).unwrap(); + let a = art(&r.doc); + assert!( + matches!(a[0].extras().colorize.as_deref(), Some(Paint::Solid { swatch: Some(s), .. }) if s == "Black Ink"), + "{:?}", + a[0].extras().colorize + ); + let img = pixels(&r.doc).0; + assert_eq!((0..3).map(|x| img.get_pixel(x, 0).0[0]).collect::>(), [255, 127, 0]); +} + +/// A Separation image reduced to fit the limits keeps its ink, and its alpha channel becomes its +/// opacity mask, as at its full size. +#[test] +fn a_reduced_separation_image_keeps_its_ink_and_its_alpha_as_a_mask() { + let samples = [255u8; 16].iter().chain([0u8; 16].iter()).copied().collect::>(); + let data = ink_image("1 [0 0 0 1 /DeviceCMYK (Black Ink) /Separation]", 8, 1, 16, &samples); + let r = super::with_image_limits(4, 1 << 31, 512 << 20, || read(&data).unwrap()); + assert!(r.warnings.iter().any(|w| w.contains("was reduced")), "{:?}", r.warnings); + let a = art(&r.doc); + assert!(a[0].extras().colorize.is_some()); + assert!(a[0].extras().mask.is_some(), "the alpha channel as an opacity mask"); + let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(r.doc.images[&im.key].gray_source().is_some_and(|g| !g.alpha), "no alpha in the pixels"); +} + #[test] fn images_with_alpha_channels() { // RGB samples, then the alpha channel (not counted in the data's size). @@ -7724,6 +7826,23 @@ fn an_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { assert_eq!(r.warnings, [super::envelope::DRAWN]); } +/// The same, in white: white art seen on white looks like nothing, so the check sees it on black +/// too, and a white envelope that draws elsewhere keeps its drawn art. +#[test] +fn a_white_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { + use vectorcraft_doc::live::EnvelopeKind; + const WHITE: &str = "0 0 0 0 1 1 1 Xa\n"; + let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true }; + let content = envelope_content().replace(RED, WHITE); + let drawn = drawn_content(&other).replace(RED, WHITE); + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &content, 1, &drawn); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); +} + /// A document of `n` warped text objects, with the art the live warp makes of each, in its look. fn warped_type_doc(n: usize) -> (Document, Vec) { use vectorcraft_doc::{Appearance, Effect, TextObject}; @@ -7769,6 +7888,36 @@ fn warped_type_past_the_budget_comes_in_as_its_look() { assert_eq!(kept.extras().wrap, Some(wrap)); } +/// White warped type is checked as other type is: seen on white it looks like nothing, so the check +/// sees it on black too. Type whose live warp draws as its look stays type; type whose look is +/// warped the other way comes in as its look. +#[test] +fn white_warped_type_that_draws_elsewhere_comes_in_as_its_look() { + use vectorcraft_doc::{Appearance, CharStyle, Effect, TextObject}; + let warp = |bend: f64| { + let mut appearance = Appearance::default(); + appearance.effects.push(Effect { id: "warp.arc".into(), params: serde_json::json!({"bend": bend}), visible: true }); + appearance + }; + for (look_bend, replaced) in [(40.0, 0), (-40.0, 1)] { + let mut doc = Document::new(400.0, 200.0); + let mut layer = Node::layer(doc.alloc_id(), "Art", vectorcraft_doc::LayerColor::Preset(0)); + let white = CharStyle { fill: Paint::solid(Color::WHITE), ..Default::default() }; + let t = TextObject::point(kurbo::Point::new(20.0, 60.0), "TILT", white); + let mut text = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + text.appearance = warp(40.0).into(); + let mut other = text.clone(); + other.appearance = warp(look_bend).into(); + let mut look = vectorcraft_effects::expand_outlined(None, &other, None).unwrap(); + look.id = doc.alloc_id(); + let looks = vec![super::envelope::WarpedLook { slot: text.id, look, left_out: None }]; + layer.children_mut().unwrap().push(Arc::new(text)); + doc.layers = vec![Arc::new(layer)]; + let warped = super::envelope::WarpedType { looks, checks: 1, ..Default::default() }; + assert_eq!(warped.settle(&mut doc, Some, &Default::default(), &mut vec![]), replaced, "look bent {look_bend}"); + } +} + /// The budget for warped type is what the envelopes left: their checks and the page's share they /// spent, with the page they are held to. #[test] @@ -7843,7 +7992,7 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() { let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None }; let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0)); let settle = |w: &super::envelope::WarpedLook, spent| { - let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, page }; + let warped = super::envelope::WarpedType { looks: vec![copy(w)], envelopes: vec![], checks: 1, spent, page }; warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) }; let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 }; diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index e0d00ac827..31cd90d79b 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -104,8 +104,7 @@ pub(super) type Built = Result<(Document, Vec), String>; /// units ([`page_scale_alone`]). The document is drawn at that scale. Else `Err(structure)`, for /// [`build_from`] with the page. pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Result> { - let Some(scale) = page_scale_alone(&structure, pages, unit).filter(|_| nothing_waits_on_page(&structure) && type_all_made(&structure, data)) - else { + let Some(scale) = alone_scale(&structure, data, pages, unit) else { return Err(Box::new(structure)); }; let styles = structure.styles_read; @@ -120,6 +119,12 @@ pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f6 Ok(built) } +/// The scale [`build_without_page`] draws `structure` (the editing copy `data` read) at on `pages` +/// in units of `unit` points, when it builds it without the page. +pub(super) fn alone_scale(structure: &Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Option { + page_scale_alone(structure, pages, unit).filter(|_| nothing_waits_on_page(structure) && type_all_made(structure, data)) +} + /// Is nothing in `structure` waiting on the page: no object unread (the page's art takes its /// place), no placed file with another placement, no live envelope with the drawn art it replaced /// (the comparison with the page chooses between them), no linked image showing a placeholder @@ -424,8 +429,20 @@ pub(super) fn build_from( } // Area type flows around the wrap objects above it before it is compared with the page. resolve_text_wrap(&mut doc)?; - let bound_text = text_bound_slots(&doc, &bindings, &xml_ids); - settle_warped_type(warped_type, &mut doc, &filled, &threaded_frames, &bound_text, &mut restyled, &mut notes)?; + let bound_text = bound_slots(&doc, &bindings, &xml_ids, VariableKind::Text); + let bound_visible = bound_slots(&doc, &bindings, &xml_ids, VariableKind::Visibility); + // Without a page to compare the layers with, envelopes of type keep their drawn art: like the + // other live envelopes, one opens live only where the layers with it draw as the page. + let warped_type = warped_type.compared(frame.is_some(), &mut notes); + let bound = [&bound_text, &bound_visible]; + let typed = settle_warped_type(warped_type, &mut doc, &filled, &threaded_frames, bound, &mut restyled, &mut notes)?; + // The live envelopes and what takes the place of each again, when the layers with them don't + // draw as the page, with the note that says so. + let envelopes_drawn: Vec<(NodeId, Vec, &str)> = envelopes_drawn + .into_iter() + .map(|(id, art)| (id, vec![art], ai::ENVELOPE_DRAWN)) + .chain(typed.into_iter().map(|(id, nodes)| (id, nodes, ai::ENVELOPE_TYPE_DRAWN))) + .collect(); if empty > 0 { notes.push(format!("{empty} {}", if frame.is_some() { TEXT_LEFT_OUT } else { TYPE_LEFT_OUT })); } @@ -478,9 +495,14 @@ pub(super) fn build_from( other => match drawn_or_trusted(&frame, &mut view, &mut doc, &envelopes_drawn, ¬es, unseen, trust, why, reflow) { Ok(more) => notes.extend(more), // The objects that draw differently from the page come in as its art, from - // the placement that draws closer to it. + // the placement that draws closer to it. The layers don't draw as the page: + // envelopes of type keep their drawn art and their type, hidden. Err(why) => { - let other = other.map(|(_, other, unseen)| (other, unseen)); + let typed = type_drawn(&mut doc, &envelopes_drawn); + let other = other.map(|(_, mut other, unseen)| { + type_drawn(&mut other, &envelopes_drawn); + (other, unseen) + }); let placements = closer_first(&frame, &mut view, (doc, unseen), other, reflow); let Some((kept, unseen, kept_notes)) = placements.into_iter().find_map(|(base, unseen)| { keep_differing(&base, &frame, &mut view, &threaded_frames, &shown, reflow).map(|(kept, n)| (kept, unseen, n)) @@ -488,7 +510,8 @@ pub(super) fn build_from( return Err(why); }; doc = kept; - notes.extend(unseen_note(unseen).into_iter().chain(kept_notes)); + let typed = typed.then(|| ai::ENVELOPE_TYPE_DRAWN.to_string()).filter(|n| !notes.contains(n)); + notes.extend(typed.into_iter().chain(unseen_note(unseen)).chain(kept_notes)); } }, }, @@ -616,40 +639,69 @@ fn bind_variables( notes.extend(ai::bindings_note(skipped)); } -/// The text object slots of `doc` that `bindings` binds to a text variable, each named by its XML id -/// (`ids`). -fn text_bound_slots(doc: &Document, bindings: &[ai::BindingRef], ids: &std::collections::HashMap>) -> BTreeSet { +/// The objects of `doc`, text object slots among them, that `bindings` binds to a variable of +/// `kind`, each named by its XML id (`ids`). +fn bound_slots( + doc: &Document, + bindings: &[ai::BindingRef], + ids: &std::collections::HashMap>, + kind: VariableKind, +) -> BTreeSet { bindings .iter() - .filter(|b| doc.variables.variable(&b.variable).is_some_and(|v| v.kind == VariableKind::Text)) + .filter(|b| doc.variables.variable(&b.variable).is_some_and(|v| v.kind == kind)) .filter_map(|b| b.target.as_ref().and_then(|t| ids.get(t).copied().flatten())) .collect() } /// Warped type stays type where its live warp draws as its look, and where a text variable binds it -/// (`bound_text`, by slot). Elsewhere the look takes its place, and one note says how many did. +/// (`bound`'s first set, by slot). Elsewhere the look takes its place, and one note says how many did. /// `filled` says what each slot became, and the comparisons with the page leave out the boxes in /// `restyled`. Fails as [`resolve_text_wrap`] does when the looks give the wrap shapes too many -/// anchors. +/// anchors. Before that, the envelopes of type open live where they draw as their drawn art, with +/// the type of their text slots (made type, one text object for the slot, not threaded, bound to +/// no text variable and no visibility variable, `bound`'s second set, and no wrap object); the +/// others keep their drawn art, with a note. Returns each live envelope of type's id with what +/// takes its place again (its hidden type, then its drawn art). fn settle_warped_type( - warped: ai::WarpedType, + mut warped: ai::WarpedType, doc: &mut Document, filled: &std::collections::HashMap, threaded: &BTreeSet, - bound_text: &BTreeSet, + bound: [&BTreeSet; 2], restyled: &mut Vec, notes: &mut Vec, -) -> Result<(), String> { +) -> Result)>, String> { + let [bound_text, bound_visible] = bound; let made = |slot| match filled.get(&slot).map(|f| f.text.as_slice()).filter(|_| !bound_text.contains(&slot)) { Some(&[one]) => Some(one), _ => None, }; + // An envelope's type: the one text object a slot became (hidden, with nothing else), named as + // the slot (made type is no longer weighed against the page: the envelope draws it). A variable + // binds the hidden text object a slot became, which the live envelope's type takes the place of + // with an id of its own: a slot bound to one keeps its type hidden, and the drawn art stays. + let type_of = |doc: &Document, slot: NodeId| { + if bound_visible.contains(&slot) { + return None; + } + let id = made(slot).filter(|id| !threaded.contains(id) && filled.get(&slot).is_some_and(|f| f.objects == [*id]))?; + let mut text = doc.node(id).filter(|n| matches!(n.kind, NodeKind::Text(_)) && n.extras().wrap.is_none())?.clone(); + if let Some(name) = text.name.as_deref().and_then(|n| n.strip_prefix(MADE)) { + text.name = (!name.is_empty()).then(|| name.to_string()); + } + Some((id, text)) + }; + let typed = warped.settle_envelopes(doc, type_of); + if !typed.kept.is_empty() && !notes.iter().any(|n| n == ai::ENVELOPE_TYPE_DRAWN) { + notes.push(ai::ENVELOPE_TYPE_DRAWN.into()); + } let replaced = warped.settle(doc, made, threaded, restyled); if replaced > 0 { notes.push(format!("{}: {replaced}", ai::WARPED_TYPE_DRAWN)); resolve_text_wrap(doc)?; } - Ok(()) + Ok(typed.put_back) } /// Most anchors copied into the wrap shapes of a file's area type ([`vectorcraft_doc::text::wrap_work`]). @@ -1254,14 +1306,15 @@ fn slot_content( /// The layers `doc` don't draw as the page (`why`), `unseen` text objects of them taken out: the /// notes to add when `doc` with each live envelope `drawn` lists replaced by the drawn art it took /// the place of (see [`ai::Structure::envelopes_drawn`]) draws as the page, `doc` then being that; -/// else, with `trust`, the notes for `doc` as it is. An error, `why`, otherwise. The envelope note -/// is added unless `notes` has it. +/// else, with `trust`, the notes for `doc` as it is but for its envelopes of type, which keep their +/// drawn art ([`type_drawn`]). An error, `why`, otherwise. The envelope note is added unless +/// `notes` has it. #[allow(clippy::too_many_arguments)] fn drawn_or_trusted( frame: &Frame<'_>, view: &mut PageView, doc: &mut Document, - drawn: &[(NodeId, Node)], + drawn: &[(NodeId, Vec, &str)], notes: &[String], unseen: usize, trust: bool, @@ -1270,27 +1323,61 @@ fn drawn_or_trusted( ) -> Result, String> { let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}")); let mut put_back = doc.clone(); - let mut any = false; - for (id, art) in drawn { - if let Some(n) = put_back.node_mut(*id) { - *n = art.clone(); - any = true; - } + // Each envelope still there, in place of the art it took the place of. + let there: Vec<&(NodeId, Vec, &str)> = drawn.iter().filter(|(id, ..)| put_back.node(*id).is_some()).collect(); + // One inside another's art goes with it: only the outermost are put back (a place inside + // another place fails the whole put-back). + let mut inside = std::collections::HashSet::new(); + for n in there.iter().filter_map(|(id, ..)| put_back.node(*id)) { + n.walk(&mut |c| { + if c.id != n.id { + inside.insert(c.id); + } + }); } + let outermost = there.iter().filter(|(id, ..)| !inside.contains(id)).map(|(id, art, _)| (*id, art.clone())).collect(); + let any = !there.is_empty() && put_back.insert_beside(outermost, true).is_ok(); if any { let more = prune_unseen(frame, view, &mut put_back, reflow); if let Ok(note) = compare(frame, view, &put_back, reflow) { *doc = put_back; - let envelope = (!notes.iter().any(|n| n == ai::ENVELOPE_DRAWN)).then(|| ai::ENVELOPE_DRAWN.to_string()); + let mut envelope: Vec = vec![]; + for (.., say) in there { + if !notes.iter().chain(&envelope).any(|n| n == say) { + envelope.push(say.to_string()); + } + } return Ok(envelope.into_iter().chain(unseen_note(unseen + more)).chain(note).collect()); } } if trust { - return Ok(unseen_note(unseen).into_iter().chain([format!("{why}: they come from its editing data all the same")]).collect()); + let typed = type_drawn(doc, drawn).then(|| ai::ENVELOPE_TYPE_DRAWN.to_string()).filter(|n| !notes.contains(n)); + let trusted = format!("{why}: they come from its editing data all the same"); + return Ok(typed.into_iter().chain(unseen_note(unseen)).chain([trusted]).collect()); } Err(why) } +/// Put each live envelope of type in `drawn` (as [`drawn_or_trusted`] takes them) that `doc` still +/// has back as its hidden type and its drawn art: whether one was. An envelope of type opens live +/// only where the layers with it draw as the page, so where they don't, though they are used all +/// the same (the editing data trusted, or the objects that differ come in as the page's art), it +/// keeps its drawn art. +fn type_drawn(doc: &mut Document, drawn: &[(NodeId, Vec, &str)]) -> bool { + let typed: Vec<(NodeId, Vec)> = drawn + .iter() + .filter(|(id, _, say)| *say == ai::ENVELOPE_TYPE_DRAWN && doc.node(*id).is_some()) + .map(|(id, art, _)| (*id, art.clone())) + .collect(); + if typed.is_empty() || doc.insert_beside(typed, true).is_err() { + return false; + } + // The type put back is still marked as made from the text document, which the rest no longer + // is once the page has weighed it ([`prune_unseen`]). + unmark(&mut doc.layers, true, true, &mut vec![]); + true +} + /// `doc` with the placed files `placed` lists at their other placement (see /// [`ai::Structure::placed_elsewhere`]): each image's transform followed by its move. `None` when /// no listed image survives replacement. @@ -2000,7 +2087,7 @@ mod candidate_tests { let warped = ai::WarpedType::unchecked(vec![(id, (*look).clone())]); let filled = std::collections::HashMap::from([(id, Filled { text: vec![id], objects: vec![id] })]); let mut notes = vec![]; - let settled = settle_warped_type(warped, &mut doc, &filled, &BTreeSet::new(), &BTreeSet::new(), &mut vec![], &mut notes); + let settled = settle_warped_type(warped, &mut doc, &filled, &BTreeSet::new(), [&BTreeSet::new(); 2], &mut vec![], &mut notes); assert_eq!(settled.is_ok(), ok, "{texts} text objects"); assert_eq!(notes, ["warped text objects that came in as drawn art, not as editable type: 1"]); } diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index 044dbd2401..5b87a03c7d 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -56,6 +56,15 @@ pub(in crate::import) fn differ(p: &[u8; 4], q: &[u8; 4]) -> bool { lightness(p).abs_diff(lightness(q)) > SAME_PIXEL || (a.min(b) <= WHITE && a.abs_diff(b) > SAME_PIXEL) } +/// Do two pixels look different seen on black: in lightness? An object drawn on its own and seen +/// only on white hides what it draws in white (white type over nothing looks like nothing): seen +/// on black too, that shows. +pub(in crate::import) fn differ_on_black(p: &[u8; 4], q: &[u8; 4]) -> bool { + // Premultiplied, a pixel is what it shows on black. + let on_black = |p: &[u8; 4]| [0, 1, 2].map(|i| u32::from(p[i])); + p != q && lightness(on_black(p)).abs_diff(lightness(on_black(q))) > SAME_PIXEL +} + /// How far apart two pixels' red, green or blue may be for them to be the same colour (a colour /// and its CMYK equivalent stay within it; a red and a dark red don't). const SAME_COLOUR: u32 = 64; @@ -705,7 +714,8 @@ fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render: } /// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin -/// for the strokes round it). +/// for the strokes round it). The type in a live envelope isn't: the envelope draws it bent, away +/// from its text object's box, and is weighed as the art it draws, as its drawn art would be. fn type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec) { for n in nodes.iter().filter(|n| n.visible) { if let NodeKind::Text(_) = n.kind @@ -714,7 +724,9 @@ fn type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec let px = |r: Rect| Rect::new((r.x0 - region.x0) * scale, (r.y0 - region.y0) * scale, (r.x1 - region.x0) * scale, (r.y1 - region.y0) * scale); out.push(px(b.inflate(OUTLINE_REACH, OUTLINE_REACH))); - } else if let Some(c) = n.children() { + } else if !matches!(n.kind, NodeKind::Envelope { .. }) + && let Some(c) = n.children() + { type_areas(c, region, scale, out); } } diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index c0331574cc..ee39aec1f1 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -1,4 +1,4 @@ -use super::build::{PAGE_MOVE, Page, build, build_from, build_on_page, build_without_page, reid_page_art}; +use super::build::{PAGE_MOVE, Page, alone_scale, build, build_from, build_on_page, build_without_page, reid_page_art}; use super::slots::LAYERS_UNREAD; use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai}; @@ -137,7 +137,7 @@ pub fn layered_ai_from( all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part")); all }; - let AiLayers { data, structure } = layers; + let AiLayers { data, structure, alone } = layers; let data = match data { Ok(data) => data, Err(why) => return (visible, unread(warnings, &why), false), @@ -180,6 +180,18 @@ pub fn layered_ai_from( let built = structure .unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)) .and_then(|structure| build_from(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit)); + // Layers that waited on the page only for their envelopes of type open alone, as they would + // have without them, each envelope keeping its drawn art, unless one opened live with the page. + let live = matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers)); + if !live + && let Some((mut done, notes)) = alone.and_then(|(pages, unit)| { + let structure = ai::read_over_page(&data, false, names).ok()?; + build_without_page(structure, &data, &pages, unit).ok()?.ok() + }) + { + done.setup.bleed = visible.setup.bleed; + return (done, notes, true); + } match built { Ok((mut done, notes)) => { done.setup.bleed = visible.setup.bleed; @@ -191,6 +203,17 @@ pub fn layered_ai_from( } } +/// Is there an envelope of type (one whose contents hold type) in `nodes` or what they hold? +fn holds_type_envelope(nodes: &[Arc]) -> bool { + fn holds_type(n: &Node) -> bool { + matches!(n.kind, NodeKind::Text(_)) || n.children().is_some_and(|c| c.iter().any(|c| holds_type(c))) + } + nodes.iter().any(|n| match &n.kind { + NodeKind::Envelope { content, .. } => content.iter().any(|c| holds_type(c)), + _ => n.children().is_some_and(|c| holds_type_envelope(c)), + }) +} + /// The `.ai` whose editing copy is `private` (as [`layered_ai`] takes it) from its layers alone, /// without its PDF part, whose pages (each its trim box in points, width and height) are `pages` /// and are in units of `unit` points (its first page's `UserUnit`): the document and the notes of @@ -201,20 +224,27 @@ pub fn layered_ai_from( pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec), AiLayers> { let data = match ai::decode_private(private) { Ok(data) => data, - Err(why) => return Err(AiLayers { data: Err(why), structure: None }), + Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None }), }; if !has_layers(&data) { - return Err(AiLayers { data: Ok(data), structure: None }); + return Err(AiLayers { data: Ok(data), structure: None, alone: None }); } // An image past the hard limits is read as an unread box, which the PDF part's art replaces. let structure = match ai::read_over_page(&data, false, names) { Ok(structure) => structure, - Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)) }), + Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None }), }; + // An envelope of type opens live only where the layers with it draw as the page, as the other + // live envelopes do: the PDF part is imported to compare them with. Should none open live, the + // layers open alone as they would have, the envelopes keeping their drawn art ([`layered_ai_from`]). + if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit).is_some() { + let alone = Some((pages.to_vec(), unit)); + return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone }); + } match build_without_page(structure, &data, pages, unit) { Ok(Ok((doc, notes))) => Ok((doc, notes)), - Ok(_) => Err(AiLayers { data: Ok(data), structure: None }), - Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)) }), + Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None }), + Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None }), } } @@ -226,12 +256,15 @@ pub struct AiLayers { /// Its layers read with [`ai::read`] as [`layered_ai`] reads them, or why they can't be; `None` /// when they are still to be read. structure: Option, String>>, + /// The pages and their unit the layers open on without the PDF part, when they wait on it only + /// for their envelopes of type ([`ai_layers_alone`]). + alone: Option<(Vec<(f64, f64)>, f64)>, } impl AiLayers { /// The editing copy `private` (as [`layered_ai`] takes it), decoded. pub fn decode(private: &[u8]) -> Self { - Self { data: ai::decode_private(private), structure: None } + Self { data: ai::decode_private(private), structure: None, alone: None } } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 13f979f9f8..f71c037c96 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5222,9 +5222,400 @@ fn envelope_options_keep_the_source_text_hidden_under_its_outlined_appearance() } }); assert_eq!(texts, [("CHONKYCATS".to_string(), false)], "{:?}", r.warnings); + // The notes say the type isn't editable. + assert_eq!(super::tests::program_warnings(&r.warnings), [crate::import::ai::ENVELOPE_TYPE_DRAWN], "{:?}", r.warnings); +} + +/// A family that is installed, for type that must draw as itself; `None` (the test is skipped) +/// when no font is available. +fn installed_family() -> Option { + let db = vectorcraft_text::FontDb::global(); + let plain = |f: &String| !f.is_empty() && f.chars().all(|c| c.is_ascii_alphanumeric() || c == ' '); + ["DejaVu Sans", "Liberation Sans", "Noto Sans", "Source Sans 3", "Arial", "Helvetica"] + .iter() + .map(|f| f.to_string()) + .find(|f| db.has_family(f)) + .or_else(|| db.families().into_iter().find(|f| plain(f) && db.has_family(f))) +} + +/// The art space of the 100 × 100 page of [`native_with_text`] has y up. +fn to_art(p: kurbo::Point) -> (f64, f64) { + (p.x, 100.0 - p.y) +} + +/// What the live envelope `envelope` (on the page axes) draws, as VectorCraft draws it: the +/// format's paths (each subpath filled on its own, in the color its type is drawn in) and the +/// page's PostScript for them. +fn drawn_envelope(envelope: &Node) -> (String, String) { + fn walk(n: &Node, color: [f32; 3], art: &mut String, page: &mut String) { + let [r, g, b] = n.appearance.fill().and_then(|f| f.paint.color()).map_or(color, |c| c.to_rgb()); + let NodeKind::Path { path, .. } = &n.kind else { + n.children().into_iter().flatten().for_each(|c| walk(c, [r, g, b], art, page)); + return; + }; + let pt = |p: kurbo::Point| { + let (x, y) = to_art(p); + format!("{x} {y}") + }; + for el in path.to_bezpath().elements() { + match *el { + kurbo::PathEl::MoveTo(p) => { + *art += &format!("0 0 0 0 {r} {g} {b} Xa\n{} m\n", pt(p)); + *page += &format!("{r} {g} {b} setrgbcolor newpath {} moveto ", pt(p)); + } + kurbo::PathEl::LineTo(p) => { + *art += &format!("{} L\n", pt(p)); + *page += &format!("{} lineto ", pt(p)); + } + kurbo::PathEl::CurveTo(a, c, p) => { + *art += &format!("{} {} {} C\n", pt(a), pt(c), pt(p)); + *page += &format!("{} {} {} curveto ", pt(a), pt(c), pt(p)); + } + kurbo::PathEl::QuadTo(..) => {} + kurbo::PathEl::ClosePath => { + *art += "f\n"; + *page += "closepath fill\n"; + } + } + } + } + let (mut art, mut page) = (String::new(), String::new()); + walk(&vectorcraft_effects::expand_live_deep(None, envelope), [0.0; 3], &mut art, &mut page); + (art, page) +} + +/// An arc warp of `bend` (a fraction) in the editing data's keys, with the Envelope Options new +/// envelopes have and Fidelity 50. +fn arc_keys(bend: f64) -> String { + format!( + "131073 /Int (AIDeformOptionsKey) ,\n50 /Int (AIDeformFidelityKey) ,\n0 /Bool (AIDeformEditModeKey) ,\n1 /Int (DeformStyle) ,\n0 /Real (DeformHoriz) ,\n{bend} /Real (DeformValue) ,\n0 /Real (DeformVert) ,\n0 /Bool (Rotate) ,\n" + ) +} + +/// An envelope made with a warp (`keys`) around the type of story 0, as the editing data writes +/// it: on `%_` lines the group with its mesh, its dictionary with the text object in its contents, +/// then its drawn art `drawn` on plain lines and the plugin's `XP`. +fn type_envelope(keys: &str, drawn: &str) -> String { + type_envelope_with(keys, drawn, "") +} + +/// [`type_envelope`], with `after` (on plain lines, written on `%_` ones) after the text object in +/// its contents, such as the text object's XML id. +fn type_envelope_with(keys: &str, drawn: &str, after: &str) -> String { + let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; + let corner = |x: f64, y: f64, nx: f64, ny: f64, px: f64, py: f64| format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); + let mesh = format!( + "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[1 1] /Size X#\n/Data X#\n/DeviceGray /CS X#\n[0 0] /P X#\n{}{}{}{}/E X#\n/End X!\n", + corner(20.0, 40.0, 20.0, 50.0, 30.0, 40.0), + corner(20.0, 70.0, 30.0, 70.0, 20.0, 60.0), + corner(80.0, 70.0, 80.0, 60.0, 70.0, 70.0), + corner(80.0, 40.0, 70.0, 40.0, 80.0, 50.0), + ); + format!( + "{}{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_1 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", + hidden(&format!("u\n{mesh}U\n")), + hidden(&format!("/ArtDictionary :\n{keys}")), + hidden(&format!("u\n{}{after}U\n9 () XW\n", text_object(0))), + ) +} + +/// The text document of the type in [`type_envelope`]: "FLUX" set in `family`, drawn in `paint` (a +/// text paint, the default's when `None`). +fn type_envelope_text(family: &str, paint: Option<&str>) -> String { + let doc = text_document(&[("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0)]).replace("(Helvetica)", &format!("({family})")); + let mut doc = match paint { + Some(p) => doc.replace("/0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >>", p), + None => doc, + }; + // [`native_with_text`] writes 60 characters a line: the end of the data, `~>`, isn't split. + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + doc +} + +/// The live envelope an arc warp of `bend` (in percent) makes of `text`, as the reader makes it. +fn arc_envelope(text: &Node, bend: f64) -> Node { + let mut text = text.clone(); + text.visible = true; + let kind = vectorcraft_doc::live::EnvelopeKind::Warp { style: "arc".into(), bend, h: 0.0, v: 0.0, horizontal: true }; + Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { + content: vec![std::sync::Arc::new(text)], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: vectorcraft_doc::live::EnvelopeOptions::NEW, + frame: Box::default(), + }, + ) +} + +/// The type of the file with an envelope of type whose drawn art is `drawn`, read with its text +/// document `doc`: the hidden text object it keeps, as the reader makes it. +fn made_envelope_type(doc: &str) -> Node { + let art = native_with_text(&layer("Art", true, &type_envelope(&arc_keys(0.3), &format!("{}\n", square(10, 10)))), doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let mut text = None; + r.document.walk(|n| { + if matches!(n.kind, NodeKind::Text(_)) { + text = Some(n.clone()); + } + }); + text.unwrap_or_else(|| panic!("no type: {:?}", r.warnings)) +} + +/// The envelopes and the type, shown or not, in the layers of `d`: each envelope's contents, and +/// the plain text of the type outside envelopes with whether it shows. +fn envelopes_and_type(d: &Document) -> (Vec>, Vec<(String, bool)>) { + let (mut envelopes, mut loose) = (vec![], vec![]); + fn walk(n: &Node, envelopes: &mut Vec>, loose: &mut Vec<(String, bool)>) { + match &n.kind { + NodeKind::Envelope { content, .. } => envelopes.push( + content + .iter() + .map(|c| { + if let NodeKind::Text(t) = &c.kind { + format!("{}{}", t.plain_text(), if c.visible { "" } else { " (hidden)" }) + } else { + "art".into() + } + }) + .collect(), + ), + NodeKind::Text(t) => loose.push((t.plain_text(), n.visible)), + _ => n.children().into_iter().flatten().for_each(|c| walk(c, envelopes, loose)), + } + } + d.layers.iter().for_each(|l| walk(l, &mut envelopes, &mut loose)); + (envelopes, loose) +} + +/// An envelope of type whose live envelope, its type laid out from the text document, draws as its +/// drawn art opens live: the type is its contents, shown and editable, and the hidden copy of the +/// type goes (#3179). +#[test] +fn an_envelope_of_type_that_draws_as_its_drawn_art_opens_live() { + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let (drawn, page) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); + let art = native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope(&arc_keys(0.3), &drawn))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); } +/// An envelope of type whose live envelope draws apart from its drawn art (the file's art bends the +/// other way) keeps its drawn art and its type, hidden, with a note. +#[test] +fn an_envelope_of_type_that_draws_apart_from_its_drawn_art_keeps_it() { + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let (drawn, page) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), -30.0)); + let art = native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope(&arc_keys(0.3), &drawn))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert!(envelopes.is_empty(), "{envelopes:?}"); + assert_eq!(loose, [("FLUX".to_string(), false)], "{:?}", r.warnings); + assert_eq!(super::tests::program_warnings(&r.warnings), [crate::import::ai::ENVELOPE_TYPE_DRAWN], "{:?}", r.warnings); +} + +/// White type in an envelope that draws apart from its drawn art keeps the drawn art too: the +/// envelope and its drawn art are each drawn on their own, where white shows only on black. +#[test] +fn an_envelope_of_white_type_that_draws_apart_from_its_drawn_art_keeps_it() { + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, Some("/0 << /0 1 /1 [ 1.0 1.0 1.0 1.0 ] >>")); + let text = made_envelope_type(&doc); + assert_eq!(text_fill(&text), Some(vectorcraft_color::Color::rgb(1.0, 1.0, 1.0))); + let (drawn, page) = drawn_envelope(&arc_envelope(&text, -30.0)); + // A dark square under it, so the page shows the white type. + let ground = "0 0 0 1 k\n0 0 m\n100 0 L\n100 100 L\n0 100 L\nf\n"; + let art = native_with_text(&layer("Art", true, &format!("{ground}{}", type_envelope(&arc_keys(0.3), &drawn))), &doc); + let r = import(&eps(&format!("0 0 0 1 setcmykcolor 0 0 moveto 100 0 lineto 100 100 lineto 0 100 lineto closepath fill\n{page}"), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert!(envelopes.is_empty(), "{envelopes:?}"); + assert_eq!(loose, [("FLUX".to_string(), false)], "{:?}", r.warnings); +} + +/// A `.ai` whose layers would open alone, without its PDF part, waits on the PDF part when an +/// envelope of type is in them, as for the other live envelopes: one opens live only where the +/// layers with it draw as the page. Where they don't, they open alone as before, the envelope +/// keeping its drawn art and its type, hidden, with the note, even though it would draw as that +/// drawn art; where they do, it opens live (#3179). +#[test] +fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { + let Some(family) = installed_family() else { return }; + let stories = [("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8170.0, 8220.0), (0.0, 0.0), 0.0)]; + let mut doc = text_document(&stories).replace("(Helvetica)", &format!("({family})")); + // [`native_with_text`] writes 60 characters a line: the end of the data, `~>`, isn't split. + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let (drawn, _) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); + let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); + let file = private(&native_with_text(&layer("Art", true, &art), &doc)); + let names = crate::NameEncoding::default(); + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + // A PDF part the layers don't draw as. + let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, false, 1.0, names); + assert!(read, "{notes:?}"); + let (envelopes, loose) = envelopes_and_type(&d); + assert!(envelopes.is_empty(), "{envelopes:?}"); + assert_eq!(loose, [("Note".to_string(), true), ("FLUX".to_string(), false)], "{notes:?}"); + assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}"); + // A PDF part that draws as those layers, with the drawn art: the envelope opens live. + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let (d, notes, read) = crate::layered_ai_from(layers, d, vec![], false, false, 1.0, names); + assert!(read, "{notes:?}"); + let (envelopes, loose) = envelopes_and_type(&d); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{notes:?}"); + assert_eq!(loose, [("Note".to_string(), true)], "{notes:?}"); +} + +/// The hidden type outside envelopes in the layers of `d`: each text object's name. +fn loose_type_names(d: &Document) -> Vec> { + let mut out = vec![]; + fn walk(n: &Node, out: &mut Vec>) { + match &n.kind { + NodeKind::Envelope { .. } => {} + NodeKind::Text(_) => out.push(n.name.clone()), + _ => n.children().into_iter().flatten().for_each(|c| walk(c, out)), + } + } + d.layers.iter().for_each(|l| walk(l, &mut out)); + out +} + +/// An envelope of type that draws as its drawn art doesn't open live where the page draws other art +/// there (the warp bent the other way): the page check weighs the live envelope as the art it draws, +/// not as type laid out again, so it sees the two differ. The file comes in as its page, as it does +/// with the drawn art (#3179). +#[test] +fn an_envelope_of_type_that_draws_apart_from_the_page_does_not_open_live() { + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let text = made_envelope_type(&doc); + let (drawn, _) = drawn_envelope(&arc_envelope(&text, 30.0)); + let (_, page) = drawn_envelope(&arc_envelope(&text, -30.0)); + let art = native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope(&arc_keys(0.3), &drawn))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + let (envelopes, _) = envelopes_and_type(&r.document); + assert!(envelopes.is_empty(), "{envelopes:?} {:?}", r.warnings); + assert!(r.warnings.iter().any(|n| n.contains("layers weren't read") && n.contains("differs from the page's")), "{:?}", r.warnings); +} + +/// Layers used though they draw differently from the page (the editing data trusted) leave an +/// envelope of type its drawn art and its type, hidden, with the note, even where it draws as that +/// drawn art: one opens live only where the layers with it draw as the page. A `.ai` whose layers +/// would open alone then opens alone, as it would without the envelope (#3179). +#[test] +fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_drawn_art() { + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let (drawn, _) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); + let art = native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope(&arc_keys(0.3), &drawn))), &doc); + // The page has the square only. + let r = crate::import_trusting(&eps(&page_square(10, 10), &art), true, true).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert!(envelopes.is_empty(), "{envelopes:?}"); + assert_eq!(loose, [("FLUX".to_string(), false)], "{:?}", r.warnings); + // The type put back is named as the file names it. + assert_eq!(loose_type_names(&r.document), [None]); + assert!(r.warnings.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|n| n.ends_with("they come from its editing data all the same")), "{:?}", r.warnings); + // A `.ai` whose layers would open alone, its PDF part drawn apart from them. + let stories = [("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8170.0, 8220.0), (0.0, 0.0), 0.0)]; + let mut doc = text_document(&stories).replace("(Helvetica)", &format!("({family})")); + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); + let file = private(&native_with_text(&layer("Art", true, &art), &doc)); + let names = crate::NameEncoding::default(); + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, true, 1.0, names); + assert!(read, "{notes:?}"); + let (envelopes, loose) = envelopes_and_type(&d); + assert!(envelopes.is_empty(), "{envelopes:?}"); + assert_eq!(loose, [("Note".to_string(), true), ("FLUX".to_string(), false)], "{notes:?}"); + assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}"); + assert!(!notes.iter().any(|n| n.ends_with("they come from its editing data all the same")), "{notes:?}"); +} + +/// Layers whose objects that draw differently from the page come in as its art leave an envelope +/// of type its drawn art and its type, hidden, with the note, even where the envelope draws as the +/// page: the layers with it don't (#3179). +#[test] +fn layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_its_drawn_art() { + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let (drawn, page) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); + // A square black in the layers and cyan on the page, away from the envelope. + let body = format!("{}\n{}\n{}", square(10, 10), square_16(76, BLACK), type_envelope(&arc_keys(0.3), &drawn)); + let art = native_with_text(&layer("Art", true, &body), &doc); + let cyan = "1 0 0 0 setcmykcolor 76 10 moveto 92 10 lineto 92 26 lineto 76 26 lineto closepath fill"; + let r = import(&eps(&format!("{}\n{cyan}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!( + r.warnings.iter().any(|n| n.starts_with("objects that drew differently from the file's own page came in as its art")), + "{:?}", + r.warnings + ); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert!(envelopes.is_empty(), "{envelopes:?}"); + assert_eq!(loose, [("FLUX".to_string(), false)], "{:?}", r.warnings); + assert_eq!(loose_type_names(&r.document), [None]); + assert!(r.warnings.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{:?}", r.warnings); +} + +/// An envelope of type whose type a visibility variable binds keeps its drawn art, as one whose type +/// a text variable binds does: the binding stays the hidden type's, which the live envelope would +/// take the place of (#3179). +#[test] +fn an_envelope_of_type_bound_to_a_visibility_variable_keeps_its_drawn_art() { + use vectorcraft_testkit::ai::{XmlValue, named, variable_library_data, xml_element, xml_node}; + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let (drawn, page) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); + let reference = "/XMLUIDREF : (type_x5F_1) ;"; + let attributes = [("trait", XmlValue::Str("visibility")), ("varName", XmlValue::Unicode("v_shown")), ("docRef", XmlValue::Raw(reference))]; + let declared = [xml_node(1, "variable", XmlValue::Str(""), &attributes, &[])]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + // The text object's XML id, on plain lines as `type_envelope_with` takes it. + let id = named("type_x5F_1").replace("%_", ""); + let envelope = type_envelope_with(&arc_keys(0.3), &drawn, &id); + let art = native_with_text(&(library + &layer("Art", true, &format!("{}\n{envelope}", square(10, 10)))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert!(envelopes.is_empty(), "{envelopes:?}"); + assert_eq!(loose, [("FLUX".to_string(), false)], "{:?}", r.warnings); + let mut text = vec![]; + r.document.walk(|n| { + if matches!(n.kind, NodeKind::Text(_)) { + text.push(n.id); + } + }); + assert_eq!(r.document.variables.objects_of("v_shown"), text, "{:?}", r.warnings); + assert!(r.warnings.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|n| n.contains("variable bindings")), "{:?}", r.warnings); +} + +/// The fill of the first run of type `n`. +fn text_fill(n: &Node) -> Option { + let NodeKind::Text(t) = &n.kind else { return None }; + t.runs.first().and_then(|r| r.style.fill.color()) +} + /// A live envelope that draws a little apart from its drawn art, in layers that already differ /// from the page almost as much as the page check takes, would make them differ too much: its /// drawn art is put back, so the file still opens from its layers. diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index c208f1b524..863c6fdd34 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -10,7 +10,8 @@ //! is left as it was and the save fails. //! //! On macOS `File::sync_all` is a full flush (`F_FULLFSYNC`), which SMB shares refuse with -//! `ENOTSUP` while a plain `fsync` works: [`sync_file`] falls back to the plain one there (#1620). +//! `ENOTSUP` and virtiofs shares (folders shared into a macOS VM) with `ENOTTY`, while a plain +//! `fsync` works: [`sync_file`] falls back to the plain one there (#1620). use std::fs::{File, OpenOptions}; use std::io::{self, Write as _}; @@ -180,8 +181,9 @@ fn copy_new(from: &Path, path: &Path) -> io::Result<()> { } /// Flush `file` to stable storage (`sync_all`). On Apple platforms that is a full flush -/// (`F_FULLFSYNC`); where the volume refuses it with `ENOTSUP` (SMB shares, #1620) this falls back -/// to a plain `fsync`. Any other error, and a failed `fsync`, is returned as it is. +/// (`F_FULLFSYNC`); where the volume refuses it with `ENOTSUP` (SMB shares) or `ENOTTY` (virtiofs +/// shares, #1620) this falls back to a plain `fsync`. Any other error, and a failed `fsync`, is +/// returned as it is. pub fn sync_file(file: &File) -> io::Result<()> { match full_sync(file) { Err(e) if full_flush_unsupported(&e) => plain_fsync(file), @@ -190,9 +192,10 @@ pub fn sync_file(file: &File) -> io::Result<()> { } /// Whether `e` is a volume refusing a full flush. Never off Apple platforms: there `sync_all` is -/// already a plain `fsync`. Checked by its code because std maps `ENOTSUP` to `Uncategorized`. +/// already a plain `fsync`. Checked by its code because std maps `ENOTSUP` and `ENOTTY` to +/// `Uncategorized`. fn full_flush_unsupported(e: &io::Error) -> bool { - cfg!(target_vendor = "apple") && e.raw_os_error() == Some(ENOTSUP) + cfg!(target_vendor = "apple") && matches!(e.raw_os_error(), Some(ENOTSUP | ENOTTY)) } #[cfg(target_vendor = "apple")] @@ -232,6 +235,9 @@ fn full_sync(file: &File) -> io::Result<()> { const ENOTSUP: i32 = 45; #[cfg(not(target_vendor = "apple"))] const ENOTSUP: i32 = 95; +/// What macOS answers when a virtiofs share (a folder shared into a VM) is asked for a full flush. +/// The same number on every Unix. +const ENOTTY: i32 = 25; #[cfg(test)] thread_local! { @@ -414,6 +420,17 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A save to a virtiofs share (#1620: a folder shared into a macOS VM): macOS refuses the full + /// flush there with `ENOTTY` (os error 25), which falls back to a plain `fsync` as `ENOTSUP` does. + /// Elsewhere neither is a refused full flush, and other errors never are. + #[test] + fn a_full_flush_refused_with_enotty_falls_back_like_enotsup() { + let apple = cfg!(target_vendor = "apple"); + assert_eq!(full_flush_unsupported(&io::Error::from_raw_os_error(25)), apple, "ENOTTY"); + assert_eq!(full_flush_unsupported(&io::Error::from_raw_os_error(ENOTSUP)), apple, "ENOTSUP"); + assert!(!full_flush_unsupported(&io::Error::other("the connection was lost"))); + } + fn denied() -> io::Result { Err(io::Error::new(io::ErrorKind::PermissionDenied, "refused by the share")) } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 984d3a1236..d420b94b31 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -501,7 +501,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> return Ok(Value::String(Str::from_units(units.to_vec()))); } Some(Func::Native { name, .. }) => format!("function {name}() {{ [native code] }}"), - Some(Func::Host { name, .. }) => format!("function {name}() {{ [native code] }}"), + Some(Func::Host { name, .. } | Func::Data { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Bound { .. }) => "function () { [native code] }".to_string(), None => return Err(interp.type_error("Function.prototype.toString was called on a value that is not a function")), }; diff --git a/crates/js/src/chars.rs b/crates/js/src/chars.rs index eb61fe763d..a7b2c1374c 100644 --- a/crates/js/src/chars.rs +++ b/crates/js/src/chars.rs @@ -1,5 +1,8 @@ //! Character classes of ECMA-262 5.1 section 7: white space, line terminators and the characters -//! identifiers are made of. +//! identifiers are made of. Identifiers follow the Unicode `ID_Start` and `ID_Continue` rule of +//! later editions. + +use std::cmp::Ordering; use unicode_general_category::{GeneralCategory as G, get_general_category}; @@ -14,35 +17,97 @@ pub fn is_whitespace(c: u32) -> bool { matches!(c, 0x09 | 0x0B | 0x0C | 0x20 | 0xA0 | 0xFEFF | 0x1680 | 0x2000..=0x200A | 0x202F | 0x205F | 0x3000) } -/// A character an identifier may start with: a letter (categories Lu, Ll, Lt, Lm, Lo and Nl), -/// `$` or `_` (section 7.6). `\u` escapes are decoded before this check. +/// A character an identifier may start with: a Unicode `ID_Start` character, `$` or `_` +/// (the Names and Keywords clause of current ECMA-262 editions). `ID_Start` is the letters (categories Lu, Ll, Lt, Lm, Lo and Nl) +/// and `Other_ID_Start`, less `Pattern_Syntax` and `Pattern_White_Space` (Unicode Standard Annex +/// #31). The categories come from Unicode 16.0. `\u` escapes are decoded before this check. pub fn is_id_start(c: u32) -> bool { match c { 0x24 | 0x5F => true, 0x41..=0x5A | 0x61..=0x7A => true, 0..=0x7F => false, - // U+2E2F VERTICAL TILDE is a letter (Lm) that Unicode leaves out of identifiers. - 0x2E2F => false, - _ => category(c).is_some_and(|g| { - matches!(g, G::UppercaseLetter | G::LowercaseLetter | G::TitlecaseLetter | G::ModifierLetter | G::OtherLetter | G::LetterNumber) - }), + _ if is_other_id_start(c) => true, + _ => { + category(c).is_some_and(|g| { + matches!(g, G::UppercaseLetter | G::LowercaseLetter | G::TitlecaseLetter | G::ModifierLetter | G::OtherLetter | G::LetterNumber) + }) && !is_pattern_syntax(c) + } } } -/// A character an identifier may hold after its first: those it may start with, decimal digits -/// (Nd), combining marks (Mn, Mc), connector punctuation (Pc), and the zero width non-joiner and -/// joiner. +/// A character an identifier may hold after its first: a Unicode `ID_Continue` character or `$`. +/// `ID_Continue` adds to `ID_Start` the decimal digits (Nd), combining marks (Mn, Mc), connector +/// punctuation (Pc, which holds `_`) and `Other_ID_Continue` (which holds the zero width +/// non-joiner and joiner), less `Pattern_Syntax` and `Pattern_White_Space`. pub fn is_id_part(c: u32) -> bool { match c { 0x30..=0x39 => true, - 0x200C | 0x200D => true, - 0x2E2F => false, _ if is_id_start(c) => true, 0..=0x7F => false, - _ => category(c).is_some_and(|g| matches!(g, G::NonspacingMark | G::SpacingMark | G::DecimalNumber | G::ConnectorPunctuation)), + _ if is_other_id_continue(c) => true, + _ => { + category(c).is_some_and(|g| matches!(g, G::NonspacingMark | G::SpacingMark | G::DecimalNumber | G::ConnectorPunctuation)) + && !is_pattern_syntax(c) + } } } +/// `Other_ID_Start` (Unicode PropList): characters kept in `ID_Start` though their category is +/// not a letter. +fn is_other_id_start(c: u32) -> bool { + matches!(c, 0x1885 | 0x1886 | 0x2118 | 0x212E | 0x309B | 0x309C) +} + +/// `Other_ID_Continue` (Unicode PropList 16.0): characters kept in `ID_Continue` though their +/// category is not a letter, mark, digit or connector. +fn is_other_id_continue(c: u32) -> bool { + matches!(c, 0xB7 | 0x387 | 0x1369..=0x1371 | 0x19DA | 0x200C | 0x200D | 0x30FB | 0xFF65) +} + +/// Non-ASCII `Pattern_Syntax` ranges (Unicode PropList). Unicode does not change this set, and no +/// identifier character belongs to it. `Pattern_White_Space` outside ASCII (U+0085, U+200E, U+200F, +/// U+2028 and U+2029) holds no letter, mark, digit or connector, so the category checks leave it out. +const PATTERN_SYNTAX: [(u32, u32); 23] = [ + (0x00A1, 0x00A7), + (0x00A9, 0x00A9), + (0x00AB, 0x00AC), + (0x00AE, 0x00AE), + (0x00B0, 0x00B1), + (0x00B6, 0x00B6), + (0x00BB, 0x00BB), + (0x00BF, 0x00BF), + (0x00D7, 0x00D7), + (0x00F7, 0x00F7), + (0x2010, 0x2027), + (0x2030, 0x203E), + (0x2041, 0x2053), + (0x2055, 0x205E), + (0x2190, 0x245F), + (0x2500, 0x2775), + (0x2794, 0x2BFF), + (0x2E00, 0x2E7F), + (0x3001, 0x3003), + (0x3008, 0x3020), + (0x3030, 0x3030), + (0xFD3E, 0xFD3F), + (0xFE45, 0xFE46), +]; + +/// Whether a non-ASCII code point is `Pattern_Syntax`. +fn is_pattern_syntax(c: u32) -> bool { + PATTERN_SYNTAX + .binary_search_by(|&(lo, hi)| { + if hi < c { + Ordering::Less + } else if lo > c { + Ordering::Greater + } else { + Ordering::Equal + } + }) + .is_ok() +} + /// The Unicode general category of a code point; `None` for a lone surrogate. fn category(c: u32) -> Option { char::from_u32(c).map(get_general_category) diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 1b2099fe16..a53721fc71 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -158,6 +158,9 @@ pub(crate) type NativeFn = fn(&mut crate::interp::Interp, Value, &[Value], bool) /// A function the embedding defines. pub(crate) type HostFn = dyn Fn(&[crate::JsValue]) -> Result; +/// A function the embedding defines that takes and gives structured values. +pub(crate) type DataFn = crate::host::HostFunction; + /// The built-ins the interpreter treats specially when it calls them. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum NativeKind { @@ -177,6 +180,7 @@ pub(crate) enum Func { Closure { code: Rc, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, Host { f: Rc, name: Rc }, + Data { f: DataFn, name: Rc }, Bound { target: ObjId, this: Value, args: Rc<[Value]> }, } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs new file mode 100644 index 0000000000..457b2ce2e1 --- /dev/null +++ b/crates/js/src/host.rs @@ -0,0 +1,351 @@ +//! Structured values between a script and its host: [`Data`] (JSON's shapes and `undefined`), the +//! checks a value passes on its way across, and the frozen objects a host adds to the global +//! environment. +//! +//! A value read from a script may hold plain objects, arrays, strings, finite numbers, booleans, +//! `null` and `undefined`. A cycle, a value too deep or too large, a function, a getter, a date, a +//! regular expression, a boxed primitive, a hole in an array and a number that is not finite are +//! refused with a `TypeError` or `RangeError` naming where the value is. The same object may appear +//! more than once when it is not its own ancestor; each appearance counts against the size limit, +//! so sharing cannot multiply the work without limit. + +use std::rc::Rc; + +use crate::LimitKind; +use crate::heap::{Class, ENUMERABLE, Func, Key, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::{Value, index_key}; + +/// A value that crosses between a script and the host. +#[derive(Clone, Debug, PartialEq)] +pub enum Data { + Undefined, + Null, + Bool(bool), + Number(f64), + String(String), + Array(Vec), + /// An object's own enumerable properties, in the order the object lists them. + Object(Vec<(String, Data)>), +} + +/// How much one crossing may carry. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DataLimits { + /// How deeply arrays and objects may nest. + pub depth: usize, + /// Estimated bytes of the strings, names and numbers. + pub bytes: usize, + /// Array elements and object properties, all of them counted together. + pub entries: usize, +} + +impl Default for DataLimits { + fn default() -> Self { + Self { depth: 64, bytes: 16 << 20, entries: 1 << 20 } + } +} + +/// How a host function fails. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum HostError { + /// Thrown to the script as an `Error`; the script can catch it. + Error(String), + /// Thrown to the script as a `TypeError`. + Type(String), + /// Thrown to the script as a `RangeError`. + Range(String), + /// Ends the run with [`LimitKind::Host`] and this message. The script cannot catch it. + Abort(String), +} + +/// A function the host gives a script, with its arguments converted. +pub type HostFunction = Rc) -> Result>; + +/// A member of an object the host adds to the global environment. +#[derive(Clone)] +pub enum HostItem { + /// A read-only copy of a value. + Value(Data), + Function(HostFunction), + /// A property whose value the function gives each time it is read. + Getter(HostFunction), + /// A frozen object with these members. + Object(Vec<(String, HostItem)>), +} + +enum Step { + Name(Key), + Index(u32), +} + +/// A value being read: what it has used so far, and where the reader is. +struct Reading { + limits: DataLimits, + bytes: usize, + entries: usize, + ancestors: Vec, + path: Vec, + function: Rc, +} + +impl Reading { + fn place(&self) -> String { + let mut s = String::new(); + for step in &self.path { + match step { + Step::Index(i) => s.push_str(&format!("[{i}]")), + Step::Name(k) => { + s.push('.'); + s.push_str(&String::from_utf16_lossy(k)); + } + } + } + s + } +} + +enum Shape { + Array(u32), + Plain(Vec<(Key, Prop)>), +} + +impl Interp { + fn data_error(&mut self, r: &Reading, t: ErrorType, what: &str) -> Abrupt { + let message = format!("{}: argument{} {what}", r.function, r.place()); + self.throw(t, &message) + } + + fn charge_reading(&mut self, r: &mut Reading, bytes: usize) -> JsResult<()> { + r.bytes = r.bytes.saturating_add(bytes); + if r.bytes > r.limits.bytes { + return Err(self.data_error(r, ErrorType::Range, "is too large")); + } + Ok(()) + } + + fn charge_entries(&mut self, r: &mut Reading, n: usize) -> JsResult<()> { + r.entries = r.entries.saturating_add(n); + if r.entries > r.limits.entries { + return Err(self.data_error(r, ErrorType::Range, "has too many entries")); + } + Ok(()) + } + + fn read_data(&mut self, v: &Value, r: &mut Reading) -> JsResult { + match v { + Value::Undefined => Ok(Data::Undefined), + Value::Null => Ok(Data::Null), + Value::Bool(b) => Ok(Data::Bool(*b)), + Value::Number(n) if n.is_finite() => Ok(Data::Number(*n)), + Value::Number(_) => Err(self.data_error(r, ErrorType::Type, "is not a finite number")), + Value::String(s) => { + self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?; + Ok(Data::String(s.to_rust_string())) + } + Value::Object(id) => self.read_object(*id, r), + } + } + + fn read_object(&mut self, id: ObjId, r: &mut Reading) -> JsResult { + self.use_fuel()?; + if r.ancestors.contains(&id) { + return Err(self.data_error(r, ErrorType::Type, "refers to itself")); + } + if r.ancestors.len() >= r.limits.depth { + return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); + } + let shape = match &self.object(id)?.class { + Class::Array { length, .. } => Shape::Array(*length), + Class::Ordinary => { + let o = self.object(id)?; + if o.props.len() > r.limits.entries { + return Err(self.data_error(r, ErrorType::Range, "has too many entries")); + } + Shape::Plain(o.props.iter().filter(|(_, p)| p.enumerable()).map(|(k, p)| (k.clone(), p.clone())).collect()) + } + other => { + let what = format!("is a {}, not plain data", other.name()); + return Err(self.data_error(r, ErrorType::Type, &what)); + } + }; + r.ancestors.push(id); + let out = match shape { + Shape::Array(length) => self.read_array(id, length, r), + Shape::Plain(props) => self.read_plain(props, r), + }; + r.ancestors.pop(); + out + } + + fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult { + self.charge_entries(r, length as usize)?; + let mut items = Vec::with_capacity(length as usize); + for i in 0..length { + self.use_fuel()?; + r.path.push(Step::Index(i)); + let prop = self.object(id)?.props.get(&index_key(i)).cloned(); + let item = match prop { + Some(Prop::Data { value: Value::Undefined, .. }) | None => Err(self.data_error(r, ErrorType::Type, "is undefined")), + Some(Prop::Data { value, .. }) => self.read_data(&value, r), + Some(Prop::Accessor { .. }) => Err(self.data_error(r, ErrorType::Type, "is a getter, not plain data")), + }?; + r.path.pop(); + items.push(item); + } + Ok(Data::Array(items)) + } + + fn read_plain(&mut self, props: Vec<(Key, Prop)>, r: &mut Reading) -> JsResult { + self.charge_entries(r, props.len())?; + let mut out = Vec::with_capacity(props.len()); + for (k, prop) in props { + self.use_fuel()?; + self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; + let name = String::from_utf16_lossy(&k); + r.path.push(Step::Name(k)); + let item = match prop { + // A property holding `undefined` reads as one left out. + Prop::Data { value: Value::Undefined, .. } => None, + Prop::Data { value, .. } => Some(self.read_data(&value, r)?), + Prop::Accessor { .. } => return Err(self.data_error(r, ErrorType::Type, "is a getter, not plain data")), + }; + r.path.pop(); + if let Some(item) = item { + out.push((name, item)); + } + } + Ok(Data::Object(out)) + } + + /// A host value as a JavaScript value, `frozen` when a script may not change it. A value + /// deeper or longer than the limits throws a `RangeError`. + pub(crate) fn write_data(&mut self, d: Data, depth: usize, frozen: bool) -> JsResult { + if depth > self.data_limits.depth { + return Err(self.throw(ErrorType::Range, "a host value is nested too deep")); + } + Ok(match d { + Data::Undefined => Value::Undefined, + Data::Null => Value::Null, + Data::Bool(b) => Value::Bool(b), + Data::Number(n) => Value::Number(n), + Data::String(s) => { + let bytes = string_bytes(s.encode_utf16().count()); + self.reserve_heap(bytes)?; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + Value::str(&s) + } + Data::Array(items) => { + self.write_container(items.into_iter().enumerate().map(|(i, d)| (Slot::Index(i), d)).collect(), true, depth, frozen)? + } + Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?, + }) + } + + fn write_container(&mut self, items: Vec<(Slot, Data)>, array: bool, depth: usize, frozen: bool) -> JsResult { + if items.len() > self.data_limits.entries { + return Err(self.throw(ErrorType::Range, "a host value has too many entries")); + } + let flags = if frozen { ENUMERABLE } else { crate::heap::OPEN }; + self.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(items.len())))?; + let id = if array { + let proto = self.intrinsics.array_proto; + self.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: !frozen }, Some(proto))) + } else { + self.new_object() + }; + let mark = self.temp_roots.len(); + self.temp_roots.push(Value::Object(id)); + let mut result = Ok(()); + for (slot, d) in items { + let name = match slot { + Slot::Index(i) => index_key(u32::try_from(i).unwrap_or(u32::MAX)), + Slot::Name(n) => key(&n), + }; + result = self.write_data(d, depth + 1, frozen).and_then(|value| self.define(id, name, Prop::Data { value, flags })); + if result.is_err() { + break; + } + } + self.temp_roots.truncate(mark); + result?; + if frozen { + self.object_mut(id)?.extensible = false; + } + Ok(Value::Object(id)) + } + + /// Calls host function `f`: reads its arguments, runs it, and gives its result to the script. + pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value]) -> JsResult { + let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() }; + let mut data = Vec::with_capacity(args.len()); + for (i, a) in args.iter().enumerate() { + reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); + data.push(self.read_data(a, &mut reading)?); + reading.path.pop(); + } + match f(data) { + Ok(d) => self.write_data(d, 0, false), + Err(HostError::Abort(message)) => { + self.host_abort = Some(message); + Err(Abrupt::Limit(LimitKind::Host)) + } + Err(HostError::Error(message)) => Err(self.throw_host(ErrorType::Error, &message)?), + Err(HostError::Type(message)) => Err(self.throw_host(ErrorType::Type, &message)?), + Err(HostError::Range(message)) => Err(self.throw_host(ErrorType::Range, &message)?), + } + } + + /// The exception for a host error, charged to the heap. + fn throw_host(&mut self, t: ErrorType, message: &str) -> JsResult { + let bytes = string_bytes(message.encode_utf16().count()); + self.reserve_heap(bytes)?; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + Ok(self.throw(t, message)) + } + + /// Adds the frozen object `name` with `items` to the global environment. + pub(crate) fn install_host_object(&mut self, name: &str, items: Vec<(String, HostItem)>) -> JsResult<()> { + let o = self.host_object(name, items)?; + let global = self.global; + self.define(global, key(name), Prop::Data { value: Value::Object(o), flags: 0 }) + } + + fn host_object(&mut self, path: &str, items: Vec<(String, HostItem)>) -> JsResult { + let o = self.new_object(); + let mark = self.temp_roots.len(); + self.temp_roots.push(Value::Object(o)); + let mut result = Ok(()); + for (name, item) in items { + result = self.install_item(o, path, name, item); + if result.is_err() { + break; + } + } + self.temp_roots.truncate(mark); + result?; + self.object_mut(o)?.extensible = false; + Ok(o) + } + + fn install_item(&mut self, o: ObjId, path: &str, name: String, item: HostItem) -> JsResult<()> { + let full = format!("{path}.{name}"); + let prop = match item { + HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE }, + HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full)), flags: ENUMERABLE }, + HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full)), set: None, flags: ENUMERABLE }, + HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE }, + }; + self.define(o, key(&name), prop) + } + + fn host_function(&mut self, f: HostFunction, name: &str) -> ObjId { + let proto = self.intrinsics.function_proto; + self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into() }), Some(proto))) + } +} + +enum Slot { + Index(usize), + Name(String), +} diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs new file mode 100644 index 0000000000..85e178d879 --- /dev/null +++ b/crates/js/src/host_tests.rs @@ -0,0 +1,288 @@ +//! Resumable runs and the structured values host functions take and give. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +use super::*; + +fn realm(fuel: u64) -> Realm { + let mut r = Realm::new(); + r.set_limits(Limits { fuel, ..Limits::default() }); + r +} + +/// A realm with `host.take(value)`, which records what it was given and returns it. +fn with_take(r: &mut Realm) -> Rc>> { + let seen: Rc>> = Rc::default(); + let log = seen.clone(); + let f: HostFunction = Rc::new(move |mut args| { + let v = if args.is_empty() { Data::Undefined } else { args.remove(0) }; + log.borrow_mut().push(v.clone()); + Ok(v) + }); + r.define_host_object("host", vec![("take".into(), HostItem::Function(f))]).unwrap(); + seen +} + +fn finish(r: &mut Realm, slice: u64) -> (Result, u32) { + let mut slices = 0; + loop { + slices += 1; + match r.advance(slice) { + Ok(Progress::Paused) => {} + Ok(Progress::Done(v)) => return (Ok(v), slices), + Err(e) => return (Err(e), slices), + } + } +} + +#[test] +fn a_resumed_run_gives_the_result_of_one_run() { + let source = "var t = 0; for (var i = 0; i < 2000; i++) { t += i; } t"; + let whole = realm(10_000_000).run(source).unwrap(); + let mut r = realm(10_000_000); + r.start(source).unwrap(); + assert!(r.is_running()); + let (v, slices) = finish(&mut r, 100); + assert_eq!(v.unwrap(), whole); + assert!(slices > 10, "the run paused: {slices} slices"); + assert!(!r.is_running()); +} + +#[test] +fn state_survives_a_pause_and_a_collection_between_slices() { + let mut r = realm(10_000_000); + r.start("var o = {a: [1, 2, 3]}; var n = 0; for (var i = 0; i < 500; i++) { n += o.a.length; } n").unwrap(); + assert_eq!(r.advance(50).unwrap(), Progress::Paused); + r.collect_garbage(); + assert_eq!(finish(&mut r, 50).0.unwrap(), JsValue::Number(1500.0)); +} + +#[test] +fn the_fuel_limit_covers_every_slice_together() { + let mut r = realm(5_000); + r.start("while (true) {}").unwrap(); + let (v, slices) = finish(&mut r, 100); + assert!(matches!(v, Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }))); + assert!((40..=60).contains(&slices), "{slices}"); +} + +#[test] +fn a_set_flag_stops_a_loop_in_a_getter() { + let mut r = realm(u64::MAX); + r.start("var o = {}; Object.defineProperty(o, 'x', {get: function () { while (true) {} }}); o.x").unwrap(); + r.interrupt().set(); + let e = r.advance(10).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Interrupted)); +} + +#[test] +fn a_nested_run_past_the_slice_allowance_is_the_unbroken_limit_and_a_run_with_little_fuel_is_the_fuel_limit() { + for (total, kind) in [(u64::MAX, LimitKind::Unbroken), (1_000, LimitKind::Fuel)] { + for source in [ + "var o = {}; Object.defineProperty(o, 'x', {get: function () { while (true) {} }}); o.x", + "[1].forEach(function () { while (true) {} });", + ] { + let mut r = realm(total); + r.set_unbroken_fuel(5_000); + r.start(source).unwrap(); + let e = finish(&mut r, 1).0.unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(kind), "{source}"); + } + } +} + +#[test] +fn neither_a_limit_nor_a_stop_can_be_caught() { + let mut r = realm(1_000); + r.start("try { while (true) {} } catch (e) { 'caught' } finally { 'ran' }").unwrap(); + assert_eq!(finish(&mut r, 50).0.unwrap_err().kind, RunErrorKind::Limit(LimitKind::Fuel)); + + let shared = Interrupt::new(); + let mut r = realm(1_000_000); + r.share_interrupt(&shared); + r.start("try { while (true) {} } catch (e) { 'caught' }").unwrap(); + assert_eq!(r.advance(10).unwrap(), Progress::Paused); + shared.set(); + assert_eq!(r.advance(10).unwrap_err().kind, RunErrorKind::Limit(LimitKind::Interrupted)); +} + +#[test] +fn a_host_function_can_end_the_slice() { + let mut r = realm(1_000_000); + let pause = r.pause_flag(); + let f: HostFunction = Rc::new(move |_| { + pause.set(true); + Ok(Data::Null) + }); + r.define_host_object("host", vec![("yield".into(), HostItem::Function(f))]).unwrap(); + r.start("host.yield(); host.yield(); 7").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert_eq!(r.advance(1_000).unwrap(), Progress::Done(JsValue::Number(7.0))); +} + +#[test] +fn plain_values_cross_in_both_directions() { + let mut r = realm(1_000_000); + let seen = with_take(&mut r); + let out = r.run("var v = host.take({a: 1, b: 'x', c: [true, null], d: undefined}); v.c[0] === true && v.b === 'x' && v.d === undefined"); + assert_eq!(out.unwrap(), JsValue::Bool(true)); + let want = Data::Object(vec![ + ("a".into(), Data::Number(1.0)), + ("b".into(), Data::String("x".into())), + ("c".into(), Data::Array(vec![Data::Bool(true), Data::Null])), + ]); + assert_eq!(seen.borrow().as_slice(), [want]); +} + +#[test] +fn a_callback_of_a_built_in_can_call_the_host() { + let mut r = realm(1_000_000); + let seen = with_take(&mut r); + r.start("[1, 2, 3].forEach(function (n) { host.take(n); });").unwrap(); + finish(&mut r, 2).0.unwrap(); + assert_eq!(seen.borrow().len(), 3); +} + +/// `value` passed to the host throws an error of type `name` whose message holds `part`. +fn refused(setup: &str, name: &str, part: &str) { + let mut r = realm(10_000_000); + r.set_data_limits(DataLimits { depth: 8, bytes: 1_000, entries: 100 }); + let seen = with_take(&mut r); + let probe = format!("var e; {setup} try {{ host.take(value); }} catch (x) {{ e = x; }} e ? e.name + '|' + e.message : 'none'"); + let JsValue::String(out) = r.run(&probe).unwrap() else { panic!("{setup}") }; + assert!(out.starts_with(name) && out.contains(part), "{setup}: {out}"); + assert!(seen.borrow().is_empty(), "{setup}: the function ran"); +} + +#[test] +fn values_that_are_not_plain_data_are_refused_with_their_place() { + refused("var value = {}; value.self = value;", "TypeError", ".self refers to itself"); + refused("var value = [[1]]; value[0][0] = value;", "TypeError", "[0][0][0] refers to itself"); + refused("var value = {f: function () {}};", "TypeError", ".f is a Function"); + refused("var value = {n: 1 / 0};", "TypeError", ".n is not a finite number"); + refused("var value = {n: 0 / 0};", "TypeError", ".n is not a finite number"); + refused("var value = {d: new Date(0)};", "TypeError", ".d is a Date"); + refused("var value = {}; Object.defineProperty(value, 'g', {enumerable: true, get: function () { return 1; }});", "TypeError", ".g is a getter"); + refused("var value = [1, , 3];", "TypeError", "[0][1] is undefined"); + refused("var value = 1; for (var i = 0; i < 20; i++) value = [value];", "RangeError", "nested too deep"); + refused("var value = new Array(5000);", "RangeError", "too many entries"); + refused("var value = 'x'; for (var i = 0; i < 12; i++) value += value;", "RangeError", "too large"); +} + +#[test] +fn a_value_nested_ten_thousand_deep_is_refused_with_its_place() { + let mut r = realm(100_000_000); + let seen = with_take(&mut r); + let probe = "var v = 1; for (var i = 0; i < 10000; i++) v = {a: v}; var m = 'none'; \ + try { host.take({args: v}); } catch (e) { m = e.name + '|' + e.message; } m"; + let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") }; + assert!(out.starts_with("RangeError|") && out.contains(".args.a.a.a") && out.contains("nested too deep"), "{out}"); + assert!(seen.borrow().is_empty(), "the function ran"); +} + +#[test] +fn a_shared_object_is_allowed_and_sharing_cannot_multiply_the_work() { + let mut r = realm(10_000_000); + r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 1_000 }); + let seen = with_take(&mut r); + r.run("var s = {a: 1}; host.take({x: s, y: s, z: [s, s]});").unwrap(); + assert_eq!(seen.borrow().len(), 1); + // Each level doubles the paths to the bottom: the entry limit ends the walk. + let JsValue::String(out) = + r.run("var v = [1]; for (var i = 0; i < 40; i++) v = [v, v]; var m = 'none'; try { host.take(v); } catch (e) { m = e.name; } m").unwrap() + else { + panic!() + }; + assert_eq!(out, "RangeError"); +} + +#[test] +fn a_host_object_cannot_be_changed_by_a_script() { + let mut r = realm(1_000_000); + let args = Data::Object(vec![("list".into(), Data::Array(vec![Data::Number(1.0)]))]); + r.define_host_object("vc", vec![("args".into(), HostItem::Value(args))]).unwrap(); + let out = r.run( + "vc.args.list[0] = 2; vc.args.list.push; vc.args.more = 1; vc.extra = 1; var was = vc; vc = 3; \ + [was.args.list[0], was.args.more === undefined, was.extra === undefined, Object.isFrozen(was.args.list)].join()", + ); + assert_eq!(out.unwrap(), JsValue::String("1,true,true,true".into())); +} + +#[test] +fn a_getter_is_read_each_time() { + let mut r = realm(1_000_000); + let count = Rc::new(Cell::new(0.0)); + let c = count.clone(); + let f: HostFunction = Rc::new(move |_| { + c.set(c.get() + 1.0); + Ok(Data::Number(c.get())) + }); + r.define_host_object("host", vec![("n".into(), HostItem::Getter(f))]).unwrap(); + assert_eq!(r.run("host.n + host.n").unwrap(), JsValue::Number(3.0)); +} + +#[test] +fn errors_from_the_host_can_be_caught_and_an_abort_cannot() { + let mut r = realm(1_000_000); + let f: HostFunction = Rc::new(|a| match a.first() { + Some(Data::String(k)) if k == "type" => Err(HostError::Type("bad type".into())), + Some(Data::String(k)) if k == "range" => Err(HostError::Range("bad range".into())), + Some(Data::String(k)) if k == "abort" => Err(HostError::Abort("stopped by the host".into())), + _ => Err(HostError::Error("bad".into())), + }); + r.define_host_object("host", vec![("f".into(), HostItem::Function(f))]).unwrap(); + let out = r.run( + "var a = []; ['type', 'range', 'x'].forEach(function (k) { try { host.f(k); } catch (e) { a.push(e.name + ':' + e.message); } }); a.join()", + ); + assert_eq!(out.unwrap(), JsValue::String("TypeError:bad type,RangeError:bad range,Error:bad".into())); + let e = r.run("try { host.f('abort'); } catch (e) { 'caught' }").unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Limit(LimitKind::Host), "stopped by the host")); +} + +#[test] +fn an_error_says_where_in_the_source_it_was_raised() { + let mut r = realm(1_000_000); + r.start("var a = 1;\n throw new TypeError('no');").unwrap(); + let e = finish(&mut r, 1).0.unwrap_err(); + assert_eq!((e.kind, e.line), (RunErrorKind::Thrown, 2)); + assert!(e.column >= 3, "{}", e.column); + assert_eq!(e.message, "TypeError: no"); +} + +#[test] +fn advancing_without_a_run_is_an_error() { + let mut r = realm(1_000); + let e = r.advance(10).unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Internal, "no run to advance")); +} + +proptest::proptest! { + /// A slice size does not change what a script computes. + #[test] + fn any_slice_size_gives_the_same_result(slice in 1u64..500, n in 0u32..300) { + let source = format!("var a = []; for (var i = 0; i < {n}; i++) a.push(i * 2); a.join().length"); + let whole = realm(50_000_000).run(&source).unwrap(); + let mut r = realm(50_000_000); + r.start(&source).unwrap(); + proptest::prop_assert_eq!(finish(&mut r, slice).0.unwrap(), whole); + } + + /// Hostile text for a value never makes the bridge panic. + #[test] + fn hostile_values_end_with_a_value_or_a_script_error(depth in 0usize..120, width in 0usize..6, cycle in proptest::bool::ANY) { + let mut r = realm(5_000_000); + with_take(&mut r); + let mut s = String::from("var v = [];"); + for _ in 0..depth { + s.push_str(&format!("v = [v{}];", ",v".repeat(width.min(2)))); + } + if cycle { + s.push_str("var c = {}; c.c = c; v = [v, c];"); + } + s.push_str("var ok = 'ok'; try { host.take(v); } catch (e) { ok = e.name; } ok"); + let JsValue::String(out) = r.run(&s).unwrap() else { panic!() }; + proptest::prop_assert!(matches!(out.as_str(), "ok" | "RangeError" | "TypeError"), "{}", out); + } +} diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index b110a955b4..f868149492 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -179,6 +179,12 @@ pub(crate) struct Interp { pub(crate) date_host: crate::date_builtins::DateHost, /// The bytes native code holds outside the heap's cells through [`HeldBytes`]. pub(crate) held: Rc, + /// Set by the host to end the current slice of a resumable run at the next safe point. + pub(crate) pause: Rc>, + /// The message of the uncatchable error a host function ended the run with. + pub(crate) host_abort: Option, + /// How much a value passed to or from a host function may carry. + pub(crate) data_limits: crate::DataLimits, } /// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's @@ -367,6 +373,9 @@ impl Interp { install_error: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), + pause: Rc::default(), + host_abort: None, + data_limits: crate::DataLimits::default(), }; crate::builtins::install(&mut interp); interp.fuel = limits.fuel; @@ -558,6 +567,28 @@ impl Interp { } } + /// Runs the boundary frame on top until it returns (`Some` with its value) or the remaining + /// fuel falls to `pause_at`, or the host asks for a pause (`None`, with the frames left in + /// place for the next call). Only this outermost loop pauses: a nested run has native frames + /// under it and goes on until it returns. + pub(crate) fn execute_slice(&mut self, pause_at: u64) -> JsResult> { + loop { + match self.step() { + Ok(Some(v)) => return Ok(Some(v)), + Ok(None) => {} + Err(Abrupt::Throw(v)) => self.unwind(v)?, + Err(other) => { + self.note_site(); + self.abort_to_boundary(); + return Err(other); + } + } + if self.fuel <= pause_at || self.pause.replace(false) { + return Ok(None); + } + } + } + fn step(&mut self) -> JsResult> { self.tick()?; let frame = self.frame_mut()?; @@ -966,11 +997,11 @@ impl Interp { // ---- properties ---- - fn object(&self, id: ObjId) -> JsResult<&Object> { + pub(crate) fn object(&self, id: ObjId) -> JsResult<&Object> { self.heap.object(id).ok_or_else(|| Abrupt::Internal("object out of range".into())) } - fn object_mut(&mut self, id: ObjId) -> JsResult<&mut Object> { + pub(crate) fn object_mut(&mut self, id: ObjId) -> JsResult<&mut Object> { self.heap.object_mut(id).ok_or_else(|| Abrupt::Internal("object out of range".into())) } @@ -1815,6 +1846,11 @@ impl Interp { self.temp_roots.truncate(mark); return Ok(Prepared::Done(r?)); } + Func::Data { f, name } => { + // The arguments are read before the function runs, and a result being built + // keeps itself reachable. + return Ok(Prepared::Done(self.call_data(&f, &name, &args)?)); + } Func::Host { f: host, .. } => { let js_args: Vec = args.iter().map(|v| self.to_js_value(v)).collect(); return match host(&js_args) { @@ -2135,6 +2171,15 @@ impl Interp { if is_eval && self.reentry >= self.limits.reentry { return Err(Abrupt::Limit(LimitKind::Reentry)); } + self.enter_global(code, is_eval)?; + self.reentry += nested; + let r = self.execute(); + self.reentry -= nested; + r + } + + /// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. + pub(crate) fn enter_global(&mut self, code: Rc, is_eval: bool) -> JsResult<()> { self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let (env, global) = (self.global_env, self.global); let (env, var_env) = if code.strict && is_eval { @@ -2144,11 +2189,7 @@ impl Interp { (env, env) }; self.instantiate_global(&code, var_env, is_eval)?; - self.push_code_frame(code, env, var_env, Value::Object(global), true)?; - self.reentry += nested; - let r = self.execute(); - self.reentry -= nested; - r + self.push_code_frame(code, env, var_env, Value::Object(global), true) } fn push_code_frame(&mut self, code: Rc, env: EnvId, var_env: EnvId, this: Value, boundary: bool) -> JsResult<()> { diff --git a/crates/js/src/lexer.rs b/crates/js/src/lexer.rs index 8b82570a77..9a6ce8766d 100644 --- a/crates/js/src/lexer.rs +++ b/crates/js/src/lexer.rs @@ -341,7 +341,7 @@ impl<'s> Lexer<'s> { } else { self.decimal() }; - if self.peek().is_some_and(|c| c == BACKSLASH || is_id_start(c) || is_decimal_digit(c)) { + if self.code_point(self.pos).is_some_and(|(c, _)| c == BACKSLASH || is_id_start(c) || is_decimal_digit(c)) { return Err(self.error_at(self.pos, "identifier starts immediately after numeric literal")); } let mut token = self.token(TokenKind::Number(value), start, line, column, false); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index b883be432d..a95a4b8847 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -47,6 +47,7 @@ mod compiler; mod date_builtins; mod error; mod heap; +mod host; mod interp; mod lexer; mod number; @@ -65,9 +66,10 @@ pub use ast::{ PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl, }; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; +pub use host::{Data, DataLimits, HostError, HostFunction, HostItem}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; -pub use realm::{Interrupt, JsValue, LimitKind, Limits, Realm, RunError, RunErrorKind}; +pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. @@ -185,6 +187,8 @@ impl LineTable { #[cfg(test)] mod builtins_tests; #[cfg(test)] +mod host_tests; +#[cfg(test)] mod interp_tests; #[cfg(test)] mod tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 45d7c08bd8..a28b150a52 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -51,14 +51,36 @@ pub enum LimitKind { Reentry, /// The host set the interrupt flag. Interrupted, + /// A getter, a callback of a built-in or another nested run spent [`MAX_UNBROKEN_FUEL`] + /// without returning to the point where a resumable run can pause. + Unbroken, + /// A host function ended the run ([`crate::HostError::Abort`]). + Host, +} + +/// The fuel [`Realm::advance`] lets a slice spend, past the slice it was asked for, in a nested run +/// it cannot pause. +pub const MAX_UNBROKEN_FUEL: u64 = 200_000_000; + +/// How far a resumable run got. +#[derive(Clone, Debug, PartialEq)] +pub enum Progress { + /// The slice ended; call [`Realm::advance`] again. + Paused, + /// The script ended, with its completion value. + Done(JsValue), } /// A flag the host sets, from any thread, to stop the running script at its next instruction. /// It stays set until [`Interrupt::clear`]. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] pub struct Interrupt(Arc); impl Interrupt { + pub fn new() -> Self { + Self::default() + } + pub fn set(&self) { self.0.store(true, Ordering::Relaxed); } @@ -121,6 +143,7 @@ impl From for RunError { /// A global environment with the built-ins, in which scripts run one after another. pub struct Realm { interp: Interp, + unbroken_fuel: u64, } impl Default for Realm { @@ -138,7 +161,13 @@ impl Realm { /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. pub fn with_options(options: Options, limits: Limits) -> Self { - Self { interp: Interp::new(options, limits) } + Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL } + } + + /// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default + /// [`MAX_UNBROKEN_FUEL`]). + pub fn set_unbroken_fuel(&mut self, fuel: u64) { + self.unbroken_fuel = fuel; } pub fn limits(&self) -> &Limits { @@ -173,6 +202,13 @@ impl Realm { /// value of the last expression statement that ran). A realm whose built-ins could not be /// installed runs nothing and gives an internal error. pub fn run(&mut self, source: &str) -> Result { + let code = self.compile(source)?; + let result = self.interp.run_global(code, false); + self.outcome(result) + } + + /// Compiles `source` and readies the realm for a run. + fn compile(&mut self, source: &str) -> Result, RunError> { let interp = &mut self.interp; if let Some(message) = &interp.install_error { return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 }); @@ -181,13 +217,18 @@ impl Realm { interp.source_units = 0; interp.throw_site = None; interp.last_thrown = Value::Undefined; + interp.host_abort = None; let strict = interp.options.strict; - let code = match interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)) { - Ok(code) => code, - Err(CompileError::Syntax(e)) => return Err(e.into()), - Err(CompileError::Internal(m)) => return Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), - }; - let result = interp.run_global(code, false); + match interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)) { + Ok(code) => Ok(code), + Err(CompileError::Syntax(e)) => Err(e.into()), + Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), + } + } + + /// The end of a run: its completion value or error, with the interpreter's stacks emptied. + fn outcome(&mut self, result: Result) -> Result { + let interp = &mut self.interp; let (line, column) = interp.throw_site.take().map_or((0, 0), |(code, pc)| code.line_column(pc)); interp.stack.clear(); interp.frames.clear(); @@ -200,11 +241,84 @@ impl Realm { interp.last_thrown = v; Err(RunError { kind: RunErrorKind::Thrown, message, line, column }) } + Err(Abrupt::Limit(LimitKind::Host)) => { + let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host)); + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column }) + } Err(Abrupt::Limit(kind)) => Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column }), Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column }), } } + /// Begins a run that [`Realm::advance`] carries on: compiles `source` and enters it. + pub fn start(&mut self, source: &str) -> Result<(), RunError> { + let code = self.compile(source)?; + match self.interp.enter_global(code, false) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + + /// Runs the script begun with [`Realm::start`] for about `slice` units of fuel (at least one + /// instruction), and pauses where it can resume: between two instructions of the script's own + /// code. A getter, a built-in's callback or another nested run has native frames under it, so + /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. Once this has returned + /// [`Progress::Done`] or an error, the run is over. + pub fn advance(&mut self, slice: u64) -> Result { + let interp = &mut self.interp; + if interp.frames.is_empty() { + return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0 }); + } + let total = interp.fuel; + let cap = slice.saturating_add(self.unbroken_fuel).min(total); + interp.fuel = cap; + let r = interp.execute_slice(cap - slice.min(cap)); + let used = cap - interp.fuel; + interp.fuel = total - used; + match r { + Ok(None) => Ok(Progress::Paused), + Ok(Some(v)) => self.outcome(Ok(v)).map(Progress::Done), + // The run's own fuel is not used up, so it was the allowance of this slice. + Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(Progress::Done), + Err(e) => self.outcome(Err(e)).map(Progress::Done), + } + } + + /// Is a run begun with [`Realm::start`] still going? + pub fn is_running(&self) -> bool { + !self.interp.frames.is_empty() + } + + /// The flag a host function sets to end the current slice at the next point it can pause. + pub fn pause_flag(&self) -> std::rc::Rc> { + self.interp.pause.clone() + } + + /// Has this realm stop when `interrupt` is set, in place of its own flag. + pub fn share_interrupt(&mut self, interrupt: &Interrupt) { + self.interp.interrupt = interrupt.0.clone(); + } + + /// Fuel the run has left. + pub fn fuel_left(&self) -> u64 { + self.interp.fuel + } + + /// Sets how much a value passed to or from a host function may carry. + pub fn set_data_limits(&mut self, limits: crate::DataLimits) { + self.interp.data_limits = limits; + } + + /// Adds the frozen object `name`, with `items`, to the global environment. Scripts cannot add + /// to it, change it or replace it. A heap too small for it ends with the error the realm's + /// next run would give. + pub fn define_host_object(&mut self, name: &str, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { + match self.interp.install_host_object(name, items) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Defines the global variable `name` holding the exception the last run did not catch /// (`undefined` if there was none). pub fn bind_last_thrown(&mut self, name: &str) { diff --git a/crates/js/src/tests.rs b/crates/js/src/tests.rs index c1cd095475..8c24b5d0bb 100644 --- a/crates/js/src/tests.rs +++ b/crates/js/src/tests.rs @@ -401,6 +401,118 @@ fn identifier_characters_follow_their_unicode_categories() { assert!(parse("var a\\u00B2 = 1;", &Options::default()).is_err()); } +#[test] +fn identifiers_take_the_other_id_start_and_continue_characters() { + // Other_ID_Start: not letters by category, but ID_Start, so they start and continue a name. + for c in [0x1885, 0x1886, 0x2118, 0x212E, 0x309B, 0x309C] { + let ch = char::from_u32(c).unwrap_or_default(); + for src in [format!("var {ch} = 1;"), format!("var a{ch} = 1;"), format!("var \\u{c:04X}\\u{{{c:X}}} = 1;")] { + let p = ok(&src); + let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!("{src:?}") }; + assert!(decls[0].name.name.contains(ch), "{src:?}"); + } + } + // Other_ID_Continue: may follow the first character, but cannot start a name. + for c in [0xB7, 0x387].into_iter().chain(0x1369..=0x1371).chain([0x19DA, 0x200C, 0x200D, 0x30FB, 0xFF65]) { + let ch = char::from_u32(c).unwrap_or_default(); + for src in [format!("var a{ch} = 1;"), format!("var a\\u{c:04X} = 1;"), format!("var a\\u{{{c:X}}} = 1;")] { + ok(&src); + } + assert!(err(&format!("var {ch} = 1;")).message.contains("unexpected character"), "{c:X}"); + assert!(err(&format!("var \\u{c:04X} = 1;")).message.contains("identifier escape"), "{c:X}"); + assert!(err(&format!("var \\u{{{c:X}}} = 1;")).message.contains("identifier escape"), "{c:X}"); + } +} + +#[test] +fn identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes() { + // U+2E2F is a letter by category but Pattern_Syntax; U+2010, U+00B6 and U+2190 are + // punctuation and symbols in Pattern_Syntax. + for c in [0x2E2F, 0x2010, 0xB6, 0x2190, 0x3001] { + let ch = char::from_u32(c).unwrap_or_default(); + assert!(err(&format!("var {ch} = 1;")).message.contains("unexpected character"), "{c:X}"); + assert!(err(&format!("var a{ch} = 1;")).message.contains("unexpected character"), "{c:X}"); + assert!(err(&format!("var a\\u{c:04X} = 1;")).message.contains("identifier escape"), "{c:X}"); + assert!(err(&format!("var \\u{{{c:X}}} = 1;")).message.contains("identifier escape"), "{c:X}"); + } + for bad in [r"var \uD800 = 1;", r"var a\uDC00 = 1;", r"var a\u{D800} = 1;", r"var a\u{110000} = 1;", r"var a\u{} = 1;"] { + assert!(parse(bad, &Options::default()).is_err(), "{bad}"); + } + // A supplementary letter is one identifier character, at the start and after a number. + let p = ok("var \u{10000}\u{1D7CE} = 1;"); + let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!() }; + assert_eq!(decls[0].name.name, "\u{10000}\u{1D7CE}"); + assert!(err("1\u{10000};").message.contains("immediately after numeric literal")); +} + +/// The code point ranges of `Pattern_Syntax` and `Pattern_White_Space` as Unicode's PropList lists +/// them; Unicode does not change either set. +fn pattern_syntax_and_white_space() -> Vec> { + let pattern = "0009..000D 0020 0021..002F 003A..0040 005B..005E 0060 007B..007E 0085 00A1..00A7 00A9 00AB..00AC 00AE \ + 00B0..00B1 00B6 00BB 00BF 00D7 00F7 200E..200F 2010..2027 2028..2029 2030..203E 2041..2053 2055..205E \ + 2190..245F 2500..2775 2794..2BFF 2E00..2E7F 3001..3003 3008..3020 3030 FD3E..FD3F FE45..FE46"; + pattern + .split_whitespace() + .map(|range| { + let (lo, hi) = range.split_once("..").unwrap_or((range, range)); + let (Ok(lo), Ok(hi)) = (u32::from_str_radix(lo, 16), u32::from_str_radix(hi, 16)) else { panic!("{range}") }; + lo..=hi + }) + .collect() +} + +#[test] +fn no_pattern_syntax_or_white_space_character_is_an_identifier_character() { + use crate::chars::{is_id_part, is_id_start}; + // `$` is Pattern_Syntax but an identifier character in scripts. + let mut checked = 0; + for range in pattern_syntax_and_white_space() { + for c in range.filter(|&c| c != 0x24) { + assert!(!is_id_start(c) && !is_id_part(c), "U+{c:04X}"); + checked += 1; + } + } + assert_eq!(checked, 2760 + 11 - 1); + for c in 0xD800..=0xDFFF { + assert!(!is_id_start(c) && !is_id_part(c), "U+{c:04X}"); + } + assert!(!is_id_start(0x110000) && !is_id_part(0x110000)); +} + +#[test] +fn identifier_characters_are_unicode_16_id_start_and_id_continue() { + use crate::chars::{is_id_part, is_id_start}; + use unicode_general_category::{GeneralCategory as G, get_general_category}; + // Unicode Standard Annex #31: ID_Start is the categories Lu, Ll, Lt, Lm, Lo and Nl plus + // Other_ID_Start; ID_Continue adds Mn, Mc, Nd, Pc and Other_ID_Continue; both leave out + // Pattern_Syntax and Pattern_White_Space. Other_ID_Start and Other_ID_Continue as PropList 16.0 + // lists them. + let other_start = [0x1885..=0x1886, 0x2118..=0x2118, 0x212E..=0x212E, 0x309B..=0x309C]; + let other_continue = [0xB7..=0xB7, 0x387..=0x387, 0x1369..=0x1371, 0x19DA..=0x19DA, 0x200C..=0x200D, 0x30FB..=0x30FB, 0xFF65..=0xFF65]; + let mut excluded = vec![false; 0x11_0000]; + for range in pattern_syntax_and_white_space() { + for c in range { + excluded[c as usize] = true; + } + } + let (mut id_starts, mut id_continues) = (0, 0); + for c in (0..=0x10_FFFF_u32).filter(|c| !(0xD800..=0xDFFF).contains(c)) { + let Some(ch) = char::from_u32(c) else { panic!("U+{c:04X}") }; + let g = get_general_category(ch); + let letter = matches!(g, G::UppercaseLetter | G::LowercaseLetter | G::TitlecaseLetter | G::ModifierLetter | G::OtherLetter | G::LetterNumber); + let id_start = (letter || other_start.iter().any(|r| r.contains(&c))) && !excluded[c as usize]; + let continuing = matches!(g, G::NonspacingMark | G::SpacingMark | G::DecimalNumber | G::ConnectorPunctuation); + let id_continue = (id_start || continuing || other_continue.iter().any(|r| r.contains(&c))) && !excluded[c as usize]; + id_starts += usize::from(id_start); + id_continues += usize::from(id_continue); + // Scripts add `$` and `_` at the start and `$` later (ECMA-262, Names and Keywords). + assert_eq!(is_id_start(c), id_start || c == 0x24 || c == 0x5F, "start U+{c:04X}"); + assert_eq!(is_id_part(c), id_continue || c == 0x24, "part U+{c:04X}"); + } + // The totals of ID_Start and ID_Continue in DerivedCoreProperties 16.0. + assert_eq!((id_starts, id_continues), (141_269, 144_541)); +} + #[test] fn comments_and_line_terminators() { let p = ok("a /* one\ntwo */ b"); diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index a6e16ea4c4..bf32bcfcd6 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -14,8 +14,8 @@ //! //! A second test runs the same ES5 tests through the interpreter, each in a new realm after the //! suite's `assert.js`, `sta.js` and the files its `includes:` names: every test that must parse -//! and uses only the built-ins the interpreter has (those that name a missing global or method, -//! in their own source or an included file, are counted as skipped, as are `async` tests). A test +//! and uses only the built-ins the interpreter has (those whose code, or an included file's, uses a +//! missing global or method are counted as skipped, as are `async` tests). A test //! passes when it completes, or, for `negative: phase: runtime`, when it throws an object whose //! `constructor` is the global its `type:` names. Its counts are printed apart from the parse //! counts, and its failures go to `run-failures.txt`. @@ -31,7 +31,7 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; -use vectorcraft_js::{JsValue, Limits, Options, Realm, RunErrorKind, TokenKind, parse, tokenize}; +use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize}; /// A test file's metadata, from its `/*--- … ---*/` block. #[derive(Default)] @@ -248,15 +248,41 @@ fn missing_builtins<'a>(provided: &[&str]) -> HashSet<&'a str> { MISSING_BUILTINS.split_whitespace().filter(|name| !provided.contains(name)).collect() } -/// The source names a missing built-in, as an identifier, a property name or a word inside a -/// string literal (code passed to `eval` or `Function`), or does not parse as ES5 (the tests that -/// use `let` and `const`). -fn needs_missing_builtin(source: &str, missing: &HashSet<&str>) -> bool { - let Ok(tokens) = tokenize(source, &Options::default()) else { return true }; - tokens.iter().any(|t| match &t.kind { +/// The code of `sources` (a test and the harness files it includes) uses a missing built-in, or +/// one of them does not parse as ES5 (the tests that use `let` and `const`). A name counts as an +/// identifier or a property name, as a string literal that is the name alone (a property key, as +/// in `this["Map"]`), and as a word in any string literal when one of the sources can run a string +/// as code. Comments, and strings that only mention the name in a message, do not count. +fn needs_missing_builtin(sources: &[&str], missing: &HashSet<&str>) -> bool { + let mut lists = Vec::with_capacity(sources.len()); + for source in sources { + let Ok(tokens) = tokenize(source, &Options::default()) else { return true }; + lists.push(tokens); + } + let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens)); + lists.iter().flatten().any(|t| match &t.kind { TokenKind::Ident(name) => missing.contains(name.as_str()), TokenKind::String(units) => { - String::from_utf16_lossy(units).split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')).any(|word| missing.contains(word)) + let text = String::from_utf16_lossy(units); + missing.contains(text.as_str()) + || (strings_are_code && text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')).any(|word| missing.contains(word))) + } + _ => false, + }) +} + +/// The tokens can run a string as code: they name `eval`, `Function` or a `constructor` property, +/// as an identifier or as a string key (`this["eval"]`), called directly or through an alias. +/// `Function.prototype` alone does not count. +fn runs_strings_as_code(tokens: &[Token]) -> bool { + const RUNNERS: [&str; 3] = ["eval", "Function", "constructor"]; + tokens.iter().enumerate().any(|(i, t)| match &t.kind { + TokenKind::String(units) => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())), + TokenKind::Ident(name) if name == "eval" || name == "constructor" => true, + TokenKind::Ident(name) if name == "Function" => { + let prototype = tokens.get(i + 1).is_some_and(|d| d.is_punct(Punct::Dot)) + && tokens.get(i + 2).is_some_and(|p| matches!(&p.kind, TokenKind::Ident(p) if p == "prototype")); + !prototype } _ => false, }) @@ -428,7 +454,7 @@ fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> ( } let counts = if meta.es5 { &mut es5_counts } else { &mut later_counts }; let includes: String = meta.includes.iter().map(|i| read(&harness_dir.join(i)) + "\n").collect(); - if meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&source, missing) || needs_missing_builtin(&includes, missing) { + if meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&[&source, &includes], missing) { counts.skipped += 1; continue; } @@ -467,3 +493,68 @@ fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> ( } (es5_counts, later_counts) } + +/// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. +fn skips(sources: &[&str]) -> bool { + let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); + needs_missing_builtin(sources, &missing) +} + +#[test] +fn a_missing_name_in_a_message_string_does_not_skip() { + assert!(!skips(&[r##"if (x !== 1) { $ERROR("#1: new Map() should not be needed"); }"##])); + assert!(!skips(&[r#"assert.sameValue(f(), 1, 'Set the value: ' + "a Symbol");"#])); + // Quotes escaped inside the string, and a regular expression literal holding quotes. + assert!(!skips(&[r#"var r = /"Map'/; var s = "say \"Map\" and \'Set\'";"#])); + // A string in an included harness file is a message too. + assert!(!skips(&["var x = 1;", r#"function check(v) { if (!v) throw new Test262Error("no Symbol"); }"#])); +} + +#[test] +fn a_missing_name_in_code_skips() { + assert!(skips(&["var m = new Map();"])); + assert!(skips(&["var s = this.Symbol;"])); + assert!(skips(&["", "function helper() { return typeof Set; }"])); + // A name both in a message and in code. + assert!(skips(&[r#"var m = new Map(); assert(m, "Map");"#])); +} + +#[test] +fn a_missing_name_in_a_string_that_can_run_as_code_skips() { + assert!(skips(&[r#"eval("new Map()");"#])); + assert!(skips(&[r#"var e = eval; var s = "Symbol()"; e(s);"#])); + assert!(skips(&[r#"var f = Function("return Set");"#])); + assert!(skips(&[r#"var f = new Function("a", "return new Map(a)");"#])); + assert!(skips(&[r#"var f = Function.apply(null, ["return Symbol"]);"#])); + assert!(skips(&[r#"var f = (function () {}).constructor("return Set");"#])); + assert!(skips(&[r#"var F = Function; F("return new Map()")();"#])); + assert!(skips(&[r#"var C = Function.prototype.constructor; C("return new Map()")();"#])); + assert!(skips(&[r#"this["eval"]("new Map()");"#])); + assert!(skips(&[r#"var F = this['Function']; F("return new Map()")();"#])); + // The string is in the test and the eval in an included file. + assert!(skips(&[r#"run("new Map()");"#, "function run(code) { return eval(code); }"])); +} + +#[test] +fn a_string_that_is_only_a_missing_name_skips() { + // A property key reads the global by name, with or without `eval` in the source. + assert!(skips(&[r#"var M = this["Map"];"#])); + assert!(skips(&[r#"for (var k in this) { if (k === 'Set') { throw 1; } }"#])); + assert!(skips(&[r#"var names = ["Object", "Symbol"];"#])); +} + +#[test] +fn comments_and_longer_names_do_not_skip() { + assert!(!skips(&["// new Map()\n/* Symbol() */ var x = 1;"])); + assert!(!skips(&["var Mapping = 1, Settings = 2; Symbolic = 3;"])); + assert!(!skips(&[r#"eval("var Mapping = 1, Settings = 2;");"#])); + // `Function.prototype` alone does not make strings code. + assert!(!skips(&[r#"assert(Function.prototype, "a Map");"#])); +} + +#[test] +fn a_source_that_does_not_parse_as_es5_skips() { + assert!(skips(&["let x = 1;"])); + assert!(skips(&["var x = 1;", "const y = 2;"])); + assert!(skips(&["var s = `${x}`;"])); +} diff --git a/crates/mcp/src/resources.rs b/crates/mcp/src/resources.rs index 50792de6d9..9f2f3b99e6 100644 --- a/crates/mcp/src/resources.rs +++ b/crates/mcp/src/resources.rs @@ -18,6 +18,20 @@ pub const DOC_JSON_URI: &str = "vectorcraft://document/json"; /// The live command catalog, including enabled state. pub const COMMANDS_URI: &str = "vectorcraft://commands"; +/// The command API reference in Markdown (`engine.apiReference`). +pub const REFERENCE_URI: &str = "vectorcraft://commands/reference"; + +/// The media type of the JSON resources. +pub const JSON: &str = "application/json"; +/// The media type of the command API reference. +pub const MARKDOWN: &str = "text/markdown; charset=utf-8"; + +/// What `resources/read` returns for a URI: the text and its media type. +#[derive(Debug, PartialEq)] +pub struct Contents { + pub mime: &'static str, + pub text: String, +} /// Why a resource could not be read. The distinction matters: the server turns it into `-32002` /// (no such resource) or `-32602` (bad URI), and guessing from the message text would not hold. @@ -83,9 +97,24 @@ pub fn list() -> Value { {"uri": DOC_URI, "name": "document", "title": "Active document (summary)", "description": "Layer tree, artboards, selection and history of the active document (document.inspect)", "mimeType": "application/json"}, {"uri": DOC_JSON_URI, "name": "document-json", "title": "Active document (full model)", "description": "The complete document model as JSON (document.json)", "mimeType": "application/json"}, {"uri": COMMANDS_URI, "name": "commands", "title": "Command catalog", "description": "Command ids, labels, parameter descriptions and current enabled state", "mimeType": "application/json"}, + {"uri": REFERENCE_URI, "name": "command-reference", "title": "Command API reference", "description": "Markdown reference of the commands that have a parameter schema: types, ranges, units, defaults, API levels, what each writes and returns (engine.apiReference)", "mimeType": MARKDOWN}, ]}) } +/// `resources/read`: the text behind a resource URI, the command API reference as Markdown and +/// every other resource as indented JSON ([`read`]). +pub fn read_contents(b: &mut dyn Backend, uri: &str) -> Result { + if uri == REFERENCE_URI { + let mut reply = exec(b, "engine.apiReference").map_err(ReadError::Backend)?; + return match reply.get_mut("markdown").map(Value::take) { + Some(Value::String(text)) => Ok(Contents { mime: MARKDOWN, text }), + _ => Err(ReadError::Backend("engine.apiReference returned no `markdown` text".into())), + }; + } + let v = read(b, uri)?; + Ok(Contents { mime: JSON, text: serde_json::to_string_pretty(&v).unwrap_or_default() }) +} + /// `resources/templates/list`. pub fn templates() -> Value { let list: Vec = TEMPLATES @@ -246,7 +275,7 @@ mod tests { #[test] fn lists_are_well_formed() { let l = list(); - assert_eq!(l["resources"].as_array().map(Vec::len), Some(3)); + assert_eq!(l["resources"].as_array().map(Vec::len), Some(4)); let t = templates(); let items = t["resourceTemplates"].as_array().expect("templates"); assert_eq!(items.len(), TEMPLATES.len()); @@ -257,6 +286,51 @@ mod tests { } } + /// A backend that gives every call the same reply. + struct Fixed(Result); + + impl Backend for Fixed { + fn call(&mut self, _: &str, _: Value) -> Result { + self.0.clone() + } + fn has_ui(&self) -> bool { + false + } + fn describe(&self) -> String { + "fixed".into() + } + } + + /// The command reference is listed and read as Markdown, with the text `engine.apiReference` + /// returns, and with no document open; the other fixed resources still read as JSON. + #[test] + fn the_command_reference_reads_as_markdown() { + let listed = list(); + let entry = listed["resources"].as_array().and_then(|r| r.iter().find(|r| r["uri"] == REFERENCE_URI)).expect("listed"); + assert_eq!(entry["mimeType"], MARKDOWN); + assert_eq!(entry["name"], "command-reference"); + let mut b = Box::new(crate::Headless::new()); + let read = read_contents(b.as_mut(), REFERENCE_URI).unwrap(); + assert_eq!(read.mime, MARKDOWN); + let direct = b.call("engine.execute", json!({"command": "engine.apiReference", "params": {}})).unwrap(); + assert_eq!(read.text, direct["markdown"].as_str().unwrap()); + assert!(read.text.starts_with("# VectorCraft command API reference\n"), "{}", read.text); + assert_eq!(read_contents(b.as_mut(), REFERENCE_URI).unwrap(), read); + let commands = read_contents(b.as_mut(), COMMANDS_URI).unwrap(); + assert_eq!(commands.mime, JSON); + assert!(serde_json::from_str::(&commands.text).unwrap().is_array()); + assert!(matches!(read_contents(b.as_mut(), "vectorcraft://commands/nope"), Err(ReadError::NotFound(_)))); + } + + /// A reply without the Markdown text, and an app that cannot be reached, are backend errors. + #[test] + fn a_bad_or_failed_reference_reply_is_a_backend_error() { + for reply in [Ok(json!({})), Ok(json!({"markdown": 5})), Ok(json!("text")), Err("the app is not running".to_string())] { + let mut b = Fixed(reply.clone()); + assert!(matches!(read_contents(&mut b, REFERENCE_URI), Err(ReadError::Backend(_))), "{reply:?}"); + } + } + #[test] fn missing_and_unknown_uris_are_errors() { let mut b = Box::new(crate::Headless::with_document()); diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index c0139bccc6..a445c7146d 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -28,7 +28,8 @@ const METHOD_NOT_FOUND: i64 = -32601; const INVALID_PARAMS: i64 = -32602; const INTERNAL_ERROR: i64 = -32603; const RESOURCE_NOT_FOUND: i64 = -32002; -/// The engine is running a long call and this request was not run (implementation-defined range). +/// The engine is running a long call or a script and this request was not run +/// (implementation-defined range). pub(crate) const SERVER_BUSY: i64 = -32003; /// How long a call runs before a request that would have to wait behind it is refused as busy @@ -435,16 +436,20 @@ impl Server { if let Some(arguments) = args.as_object() { crate::tools::check_tool_arguments(name, arguments).map_err(|e| (INVALID_PARAMS, e))?; } - Ok(call_tool(self.backend.as_mut(), name, &args).to_value()) + let result = call_tool(self.backend.as_mut(), name, &args); + match result.script_busy() { + Some(message) => Err((SERVER_BUSY, message)), + None => Ok(result.to_value()), + } } "resources/read" => { let uri = params.get("uri").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing `uri`".to_string()))?; - let v = resources::read(self.backend.as_mut(), uri).map_err(|e| match e { + let read = resources::read_contents(self.backend.as_mut(), uri).map_err(|e| match e { resources::ReadError::NotFound(uri) => (RESOURCE_NOT_FOUND, format!("resource not found: {uri}")), resources::ReadError::Invalid(why) => (INVALID_PARAMS, why), resources::ReadError::Backend(why) => (INTERNAL_ERROR, why), })?; - Ok(json!({"contents": [{"uri": uri, "mimeType": "application/json", "text": serde_json::to_string_pretty(&v).unwrap_or_default()}]})) + Ok(json!({"contents": [{"uri": uri, "mimeType": read.mime, "text": read.text}]})) } "completion/complete" => Ok(prompts::complete(self.backend.as_mut(), params)), "logging/setLevel" => { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index e986deda04..02e5624b3e 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -304,7 +304,7 @@ fn headless_end_to_end() { // Resources. let v = rpc(&mut s, 10, "resources/list", json!({})); - assert_eq!(v["result"]["resources"].as_array().unwrap().len(), 3); + assert_eq!(v["result"]["resources"].as_array().unwrap().len(), 4); let v = rpc(&mut s, 11, "resources/read", json!({"uri": "vectorcraft://document"})); let text = v["result"]["contents"][0]["text"].as_str().unwrap(); assert!(serde_json::from_str::(text).unwrap()["layers"].is_array()); @@ -1463,6 +1463,60 @@ fn pointer_gesture_forwards_backquote_on_each_event() { assert_eq!(rect["bounds"]["x"], 100.0, "{doc}"); } +/// The documented Rotate View calls reach the desktop control methods, preserving document +/// coordinates and modifiers, and a successful null reset remains a successful MCP response. +#[test] +fn rotate_view_calls_forward_to_desktop_control() { + use std::cell::RefCell; + use std::rc::Rc; + + struct Recording(Rc>>); + impl Backend for Recording { + fn call(&mut self, method: &str, params: Value) -> Result { + self.0.borrow_mut().push((method.into(), params)); + Ok(Value::Null) + } + fn has_ui(&self) -> bool { + true + } + fn describe(&self) -> String { + "desktop control contract".into() + } + } + + let seen = Rc::new(RefCell::new(Vec::new())); + let mut s = Server::new(Box::new(Recording(seen.clone()))); + let selected = call(&mut s, 1, "select_tool", json!({"tool": "rotateView"})); + let turned = call( + &mut s, + 2, + "pointer_gesture", + json!({"events": [ + {"kind": "down", "x": 300, "y": 150}, {"kind": "drag", "x": 200, "y": 250}, {"kind": "up", "x": 200, "y": 250} + ], "mods": {"shift": true}}), + ); + let reset = call(&mut s, 3, "command_run", json!({"id": "view.rotateReset", "params": {}})); + for reply in [&selected, &turned, &reset] { + assert_eq!(reply["isError"], false, "{reply}"); + } + assert_eq!(text_of(&reset), "null"); + assert_eq!( + *seen.borrow(), + vec![ + ("ui.tool.select".into(), json!({"tool": "rotateView"})), + ( + "ui.pointer".into(), + json!({"events": [ + {"kind": "down", "x": 300, "y": 150, "space": "doc"}, + {"kind": "drag", "x": 200, "y": 250, "space": "doc"}, + {"kind": "up", "x": 200, "y": 250, "space": "doc"} + ], "mods": {"shift": true}}) + ), + ("engine.execute".into(), json!({"command": "view.rotateReset", "params": {}})) + ] + ); +} + /// A `backquote` that is not a boolean is an error, and none of the gesture's events runs. #[test] fn pointer_gesture_rejects_a_backquote_that_is_not_a_boolean() { diff --git a/crates/mcp/src/tests/concurrency.rs b/crates/mcp/src/tests/concurrency.rs index 7b9352e526..d291d1e9fe 100644 --- a/crates/mcp/src/tests/concurrency.rs +++ b/crates/mcp/src/tests/concurrency.rs @@ -344,6 +344,23 @@ fn a_cancelled_export_through_the_real_engine_writes_nothing_and_leaves_the_sess thread.join().unwrap(); } +#[test] +fn a_change_while_a_script_runs_is_refused_as_busy() { + let mut backend = crate::Headless::with_document(); + backend.session.script_frames = true; + backend.session.execute("script.run", &json!({"source": "while (true) {}"})).unwrap(); + let mut s = Server::new(Box::new(backend)); + let call = |id: &str, params: Value| json!({"name": "command_run", "arguments": {"id": id, "params": params}}); + let reply = super::rpc(&mut s, 1, "tools/call", call("shape.rectangle", json!({"x": 0, "y": 0, "width": 1, "height": 1}))); + assert_eq!(reply["error"]["code"], -32003, "{reply}"); + assert!(reply["error"]["message"].as_str().unwrap().contains("a script is running"), "{reply}"); + let reply = super::rpc(&mut s, 2, "tools/call", json!({"name": "doc_inspect", "arguments": {}})); + assert_eq!(reply["result"]["isError"], false, "reading the document is not refused: {reply}"); + let reply = super::rpc(&mut s, 3, "tools/call", call("no.such", json!({}))); + assert_eq!(reply["result"]["isError"], true, "any other failure stays a tool error: {reply}"); + assert!(reply.get("error").is_none(), "{reply}"); +} + #[test] fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { use std::io::BufRead; diff --git a/crates/mcp/src/tests/conventions.rs b/crates/mcp/src/tests/conventions.rs index 929851917a..0b7352bf4a 100644 --- a/crates/mcp/src/tests/conventions.rs +++ b/crates/mcp/src/tests/conventions.rs @@ -57,18 +57,63 @@ fn command_listings_take_query_menu_and_brief() { let menu: Vec<&str> = c["menu"].as_array().unwrap().iter().map(|m| m.as_str().unwrap()).collect(); assert_eq!(menu.get(..2), Some(&["Object", "Path"][..]), "{c}"); } - // `brief` drops the params text and nothing else. + // `brief` drops the params text and the schemas, and nothing else. let full = payload(&call(&mut s, "command_list", json!({}))); let brief = payload(&call(&mut s, "command_list", json!({"brief":true}))); assert_eq!(ids(&full), ids(&brief)); assert!(full.as_array().unwrap().iter().any(|c| c.get("params").is_some())); - assert!(brief.as_array().unwrap().iter().all(|c| c.get("params").is_none() && c.get("label").is_some())); + assert!(full.as_array().unwrap().iter().any(|c| c.get("inputSchema").is_some())); + assert!( + brief + .as_array() + .unwrap() + .iter() + .all(|c| c.get("params").is_none() && c.get("schema").is_none() && c.get("inputSchema").is_none() && c.get("label").is_some()) + ); assert!(brief.to_string().len() * 2 < full.to_string().len(), "brief is much shorter"); // The other listing takes them too. let r = payload(&call(&mut s, "list_commands", json!({"query":"rectangle","brief":true,"menu":""}))); assert_eq!(ids(&r["commands"]), ids(&by_filter)); } +#[path = "../../../apischema/src/conformance.rs"] +mod conformance; + +/// Both listings give a command with a parameter schema an `inputSchema` with an object root, +/// which follows the 2020-12 rules, and the filters select the same commands as before. +#[test] +fn command_listings_carry_input_schemas() { + let mut s = Server::new(Box::new(Headless::with_document())); + let list = payload(&call(&mut s, "list_commands", json!({"filter":"view.saved"}))); + let bare = payload(&call(&mut s, "command_list", json!({"filter":"view.saved"}))); + assert_eq!(list["commands"], bare); + assert_eq!(list["count"], bare.as_array().unwrap().len()); + let commands = bare.as_array().unwrap(); + let with_input: Vec<&Value> = commands.iter().filter(|c| c.get("inputSchema").is_some()).collect(); + assert!(with_input.len() >= 3, "{bare}"); + for c in with_input { + let input = &c["inputSchema"]; + assert_eq!(input["type"], "object", "{c}"); + conformance::check_schema(input, c["id"].as_str().unwrap()).unwrap_or_else(|e| panic!("{e}\n{input:#}")); + assert!(!conformance::instance_valid(input, &Value::Null)); + assert_eq!(conformance::instance_valid(&c["schema"], &Value::Null), c["schema"]["type"] != "object", "{c}"); + } + let saved_list = commands.iter().find(|c| c["id"] == "view.saved.list").unwrap(); + assert_eq!(saved_list["schema"]["type"], json!(["object", "null"])); + assert_eq!(saved_list["inputSchema"]["type"], "object"); + // A command without a schema lists neither. + let new = payload(&call(&mut s, "command_list", json!({"filter":"file.new","enabled_only":true}))); + let new = new.as_array().unwrap().iter().find(|c| c["id"] == "file.new").unwrap().clone(); + assert!(new.get("schema").is_none() && new.get("inputSchema").is_none(), "{new}"); + // `brief`, `menu` and the enabled filter select the same ids with and without the schemas. + let ids = |v: &Value| v.as_array().unwrap().iter().map(|c| c["id"].clone()).collect::>(); + let view = payload(&call(&mut s, "list_commands", json!({"menu":"view","enabledOnly":true}))); + let view_brief = payload(&call(&mut s, "list_commands", json!({"menu":"view","enabledOnly":true,"brief":true}))); + assert_eq!(ids(&view["commands"]), ids(&view_brief["commands"])); + assert_eq!(view["count"], view_brief["count"]); + assert!(view_brief["commands"].as_array().unwrap().iter().all(|c| c.get("inputSchema").is_none() && c.get("schema").is_none())); +} + #[test] fn conventions_commands_batch_and_bounded_preview() { let mut s = Server::new(Box::new(Headless::with_document())); diff --git a/crates/mcp/src/tests/protocol.rs b/crates/mcp/src/tests/protocol.rs index 1fe41c3e51..a3c79aae74 100644 --- a/crates/mcp/src/tests/protocol.rs +++ b/crates/mcp/src/tests/protocol.rs @@ -261,3 +261,20 @@ fn log_records_go_out_as_notifications_once_asked_for() { assert!(lines[last_reply + 1..].iter().all(|l| l.get("id").is_none()), "{lines:?}"); result(&mut s, 4, "logging/setLevel", json!({"level": null})); } + +/// `list_commands` gives each command's input schema over stdin and stdout, as a client reads it. +#[test] +fn list_commands_over_stdio_carries_input_schemas() { + let mut s = server(); + let call = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "list_commands", "arguments": {"filter": "view.saved"}}}); + let mut out = Vec::new(); + s.serve((call.to_string() + "\n").as_bytes(), &mut out).unwrap(); + let lines: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + let reply = lines.iter().find(|l| l["id"] == 1).cloned().unwrap_or(Value::Null); + assert_eq!(reply["result"]["isError"], false, "{reply}"); + let listed: Value = serde_json::from_str(reply["result"]["content"][0]["text"].as_str().unwrap_or("null")).unwrap_or(Value::Null); + let commands = listed["commands"].as_array().cloned().unwrap_or_default(); + assert!(commands.iter().filter(|c| c.get("inputSchema").is_some()).count() >= 3, "{listed}"); + let saved_list = commands.iter().find(|c| c["id"] == "view.saved.list").cloned().unwrap_or(Value::Null); + assert_eq!(saved_list["inputSchema"]["type"], "object", "{listed}"); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 66080b6fa4..93ef5749af 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -36,4 +36,9 @@ impl ToolResult { pub fn to_value(&self) -> Value { json!({"content": self.content, "isError": self.is_error}) } + /// The error's text, when the engine refused the call because a script is running. + pub(crate) fn script_busy(&self) -> Option { + let text = self.content.first()?.get("text")?.as_str()?; + (self.is_error && text.ends_with(vectorcraft_engine::SCRIPT_BUSY)).then(|| text.to_string()) + } } diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 616e32aaef..8fe45b83eb 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -98,7 +98,7 @@ pub fn tool_definitions() -> Vec { tool( "command_list", "List commands", - "Discover command ids, labels, parameter descriptions and enabled state. Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}.", + "Discover command ids, labels, parameter descriptions and enabled state. A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}.", obj( json!({"filter": string("Case-insensitive id, label or menu substring"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabled_only": {"type":"boolean"}, "brief": {"type":"boolean", "description": BRIEF}}), &[], @@ -156,7 +156,7 @@ pub fn tool_definitions() -> Vec { tool( "list_commands", "List commands", - "List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state). Every editing action is a command; run any of them with run_command. Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only.", + "List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Every editing action is a command; run any of them with run_command. Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only.", obj( json!({"filter": string("Case-insensitive substring matched against id, label and menu path (e.g. \"align\", \"Object\")"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabledOnly": {"type": "boolean", "description": "Only commands that can run right now"}, "brief": {"type": "boolean", "description": BRIEF}}), &[], diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index eabd73e3ec..b1c5af70bb 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -10,8 +10,7 @@ pub(super) const MENU_FILTER: &str = "Case-insensitive substring of the menu path, its levels joined with \" > \" (e.g. \"Object\", \"Object > Path\")"; /// The `brief` argument of the command listings. -pub(super) const BRIEF: &str = - "Leave out each command's params description (the bulk of the catalogue); run command_list with the id as filter to read it"; +pub(super) const BRIEF: &str = "Leave out each command's params description and its schema and inputSchema (the bulk of the catalogue); run command_list with the id as filter to read them"; /// The `max_side` argument of the window captures. pub(super) const MAX_SIDE_WINDOW: &str = @@ -30,7 +29,7 @@ pub(super) fn trace_views(a: &Args) -> Result { /// The command catalogue narrowed by the listing tools' arguments: `filter` (or `query`) on the /// id, label and menu path, `menu` on the menu path, `enabledOnly`, and `brief` (no `params` -/// text: the full catalogue is too large for many clients, #2173). +/// text, `schema` or `inputSchema`: the full catalogue is too large for many clients, #2173). fn filter_commands(all: Value, a: &Args) -> Value { let text = |k: &str| a.get(k).and_then(Value::as_str).map(str::to_lowercase).filter(|s| !s.is_empty()); let needle = text("filter").or_else(|| text("query")); @@ -63,7 +62,9 @@ fn filter_commands(all: Value, a: &Args) -> Value { .filter(hit) .map(|mut c| { if brief && let Some(o) = c.as_object_mut() { - o.remove("params"); + for key in ["params", "schema", "inputSchema"] { + o.remove(key); + } } c }) diff --git a/crates/mcp/tests/protocol_props.rs b/crates/mcp/tests/protocol_props.rs index 2eb3db6472..f9dc065ff1 100644 --- a/crates/mcp/tests/protocol_props.rs +++ b/crates/mcp/tests/protocol_props.rs @@ -290,8 +290,16 @@ fn resources_are_json() { let list = rpc(&mut s, 2, "resources/list", json!({})); for r in list["result"]["resources"].as_array().unwrap() { let v = rpc(&mut s, 3, "resources/read", json!({"uri": r["uri"]})); - let text = v["result"]["contents"][0]["text"].as_str().unwrap(); - serde_json::from_str::(text).unwrap(); + let content = &v["result"]["contents"][0]; + assert_eq!(content["mimeType"], r["mimeType"], "{}", r["uri"]); + assert_eq!(content["uri"], r["uri"]); + let text = content["text"].as_str().unwrap(); + if r["mimeType"] == "application/json" { + serde_json::from_str::(text).unwrap(); + } else { + assert_eq!(r["mimeType"], "text/markdown; charset=utf-8", "{}", r["uri"]); + assert!(text.starts_with("# ") && text.ends_with('\n'), "{}", r["uri"]); + } } } diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index 7321626cd1..e12c9fb395 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -20,6 +20,8 @@ use crate::fit::{end_tangent, fit_single, is_straight, sample, start_tangent}; thread_local! { /// The contour passes made over an arrangement on this thread, each of which walks all of it. pub(crate) static CONTOUR_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The sweeps [`normalize_bez`] made on this thread. + static NORMALIZE_SWEEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Default curve-refit tolerance (document points) used to merge split curve pieces back together. @@ -822,6 +824,8 @@ pub fn try_normalize(path: &PathData, rule: FillRule) -> Result Result { + #[cfg(test)] + NORMALIZE_SWEEPS.with(|n| n.set(n.get() + 1)); let eps = eps_for([bp])?; let mut bp = bp.clone(); snap_horizontals(&mut [&mut bp], eps); @@ -983,25 +987,21 @@ pub fn try_unite_all_with(paths: &[(&PathData, FillRule)], precision: f64) -> Re /// [`try_unite_all_with`] with the sweeps run on `paths` as they are. pub(crate) fn try_unite_all_upright(paths: &[(&PathData, FillRule)], precision: f64) -> Result { - let mut all = BezPath::new(); - for (p, r) in paths { - let bp = fill_bezpath(p); + let bps: Vec = paths.iter().map(|(p, _)| fill_bezpath(p)).collect(); + let mut parts = Vec::new(); + for (bp, (_, r)) in bps.iter().zip(paths) { if bp.elements().is_empty() { continue; } - for ct in normalize_bez(&bp, *r)?.contours() { - all.extend(ct.path.iter()); - } + parts.push((normalize_bez(bp, *r)?, bp.segments().count())); } - if all.elements().is_empty() { - return Ok(PathData::default()); - } - let tidy = Tidy::keeping(precision, paths.iter().map(|(p, _)| fill_bezpath(p)).collect::>().iter()); - Ok(all_contours_to_path(&normalize_bez(&all, FillRule::NonZero)?, &tidy)) + unite_parts(parts, bps, precision) } /// Union of many filled paths. Each input is first normalised on its own, then all are swept /// together with a single integer winding number, which keeps this fast for thousands of shapes. +/// A single input whose own sweep split none of its segments, with no two of them within twice the +/// sweep tolerance, is not swept a second time. pub fn unite_all(paths: &[(&PathData, FillRule)]) -> PathData { unite_all_with(paths, DEFAULT_PRECISION) } @@ -1019,25 +1019,180 @@ pub fn unite_all_with(paths: &[(&PathData, FillRule)], precision: f64) -> PathDa /// [`unite_all_with`] with the sweeps run on `paths` as they are. pub(crate) fn unite_all_upright(paths: &[(&PathData, FillRule)], precision: f64) -> PathData { - let mut all = BezPath::new(); - for (p, r) in paths { - let bp = fill_bezpath(p); + let bps: Vec = paths.iter().map(|(p, _)| fill_bezpath(p)).collect(); + let mut parts = Vec::new(); + for (bp, (_, r)) in bps.iter().zip(paths) { if bp.elements().is_empty() { continue; } - let Ok(c) = normalize_bez(&bp, *r) else { continue }; + let Ok(c) = normalize_bez(bp, *r) else { continue }; + parts.push((c, bp.segments().count())); + } + unite_parts(parts, bps, precision).unwrap_or_default() +} + +/// The union of `parts`, each the contours [`normalize_bez`] made of one input with that input's +/// segment count, refit to `precision` keeping the anchors of `inputs`. +/// +/// When there is one part, its sweep split none of the input's segments and none of them lies +/// within twice the sweep tolerance of another, its contours are the union and are refit as they +/// are. Otherwise all the contours are swept again together under NonZero, which also merges the +/// short pieces the first sweeps leave where a path crosses itself, and contours that lie within +/// that distance of each other. +fn unite_parts(parts: Vec<(Contours, usize)>, inputs: Vec, precision: f64) -> Result { + if parts.is_empty() { + return Ok(PathData::default()); + } + let tidy = Tidy::keeping(precision, inputs.iter()); + if let [(c, input_segments)] = parts.as_slice() + && splits_nothing(c, *input_segments, &tidy) + && eps_for(inputs.iter()).is_ok_and(|eps| !comes_close(c, 2.0 * eps)) + { + return Ok(all_contours_to_path(c, &tidy)); + } + drop(inputs); + let mut all = BezPath::new(); + for (c, _) in parts { for ct in c.contours() { all.extend(ct.path.iter()); } } if all.elements().is_empty() { - return PathData::default(); + return Ok(PathData::default()); } - let tidy = Tidy::keeping(precision, paths.iter().map(|(p, _)| fill_bezpath(p)).collect::>().iter()); - match normalize_bez(&all, FillRule::NonZero) { - Ok(c) => all_contours_to_path(&c, &tidy), - Err(_) => PathData::default(), + Ok(all_contours_to_path(&normalize_bez(&all, FillRule::NonZero)?, &tidy)) +} + +/// Are the contours `c` the input's own segments: as many as `input_segments`, each starting at an +/// anchor `tidy` keeps? A segment split where paths cross gives a piece that starts away from the +/// anchors, and a piece dropped inside another path leaves fewer segments than the input. +fn splits_nothing(c: &Contours, input_segments: usize, tidy: &Tidy) -> bool { + let mut n = 0; + for ct in c.contours() { + for s in ct.path.segments() { + if !tidy.is_kept(to_seg(s).c.p0) { + return false; + } + n += 1; + } } + n == input_segments +} + +/// The pairs of segments [`comes_close`] compares for each segment. Past it the answer is yes. +const MAX_CLOSE_PAIRS: usize = 512; + +/// One segment of a contour for [`comes_close`]: its control points' extents along and across the +/// side the segments are sorted on, and its place in its contour. +struct CloseSeg { + c: CubicBez, + line: bool, + lo: f64, + hi: f64, + across_lo: f64, + across_hi: f64, + contour: usize, + index: usize, + len: usize, +} + +impl CloseSeg { + fn new(seg: Seg, contour: usize, index: usize, len: usize) -> Self { + let pts = [seg.c.p0, seg.c.p1, seg.c.p2, seg.c.p3]; + let (lo, hi) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), p| (l.min(p.x), h.max(p.x))); + let (across_lo, across_hi) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), p| (l.min(p.y), h.max(p.y))); + Self { c: seg.c, line: seg.line, lo, hi, across_lo, across_hi, contour, index, len } + } +} + +/// Does a segment of the contours `c` lie within `touch` of another? A sweep can join such +/// segments or leave them apart depending on the order it meets them in, so a second sweep can +/// answer differently from the first. Segments whose control points can't be told apart from +/// `touch` count as close, which costs only that second sweep. +fn comes_close(c: &Contours, touch: f64) -> bool { + let mut segs = Vec::new(); + for (contour, ct) in c.contours().enumerate() { + let len = ct.path.segments().count(); + for (index, s) in ct.path.segments().enumerate() { + segs.push(CloseSeg::new(to_seg(s), contour, index, len)); + } + } + // Sort along the longer side of the whole, where fewer segments overlap. + let extent = |lo: fn(&CloseSeg) -> f64, hi: fn(&CloseSeg) -> f64| { + segs.iter().map(hi).fold(f64::NEG_INFINITY, f64::max) - segs.iter().map(lo).fold(f64::INFINITY, f64::min) + }; + if extent(|s| s.across_lo, |s| s.across_hi) > extent(|s| s.lo, |s| s.hi) { + for s in &mut segs { + std::mem::swap(&mut s.lo, &mut s.across_lo); + std::mem::swap(&mut s.hi, &mut s.across_hi); + } + } + segs.sort_by(|a, b| a.lo.total_cmp(&b.lo)); + let (mut pairs, budget) = (0usize, segs.len().saturating_mul(MAX_CLOSE_PAIRS)); + for (i, a) in segs.iter().enumerate() { + for b in segs.iter().skip(i + 1) { + if b.lo > a.hi + touch { + break; + } + pairs += 1; + if pairs > budget { + return true; + } + if a.across_lo > b.across_hi + touch || b.across_lo > a.across_hi + touch { + continue; + } + let neighbors = a.contour == b.contour && ((a.index + 1) % a.len == b.index || (b.index + 1) % b.len == a.index); + let close = if neighbors { neighbors_run_together(a, b, touch) } else { !hulls_apart(&a.c, &b.c, touch) }; + if close { + return true; + } + } + } + false +} + +/// The sine of the angle below which two segments leaving a shared end count as parallel. +const PARALLEL_SINE: f64 = 1e-3; + +/// Do segments `a` and `b`, which share an end, run along each other within `touch`? Straight +/// segments do when the far end of either lies within `touch` of the other. A curve does when the +/// two leave their shared end in the same direction, or when their extents overlap by more than +/// `touch` both ways. +fn neighbors_run_together(a: &CloseSeg, b: &CloseSeg, touch: f64) -> bool { + use kurbo::ParamCurveNearest; + if a.line && b.line { + let (shared, p, q) = if a.c.p3 == b.c.p0 { (a.c.p3, a.c.p0, b.c.p3) } else { (a.c.p0, a.c.p3, b.c.p0) }; + let near = |p: Point, q: Point| kurbo::Line::new(shared, q).nearest(p, 0.0).distance_sq.sqrt() <= touch; + return near(q, p) || near(p, q); + } + let (from_a, from_b) = if a.c.p3 == b.c.p0 { + ([a.c.p3, a.c.p2, a.c.p1, a.c.p0], [b.c.p0, b.c.p1, b.c.p2, b.c.p3]) + } else { + ([a.c.p0, a.c.p1, a.c.p2, a.c.p3], [b.c.p3, b.c.p2, b.c.p1, b.c.p0]) + }; + let away = |pts: [Point; 4]| pts.iter().skip(1).map(|p| *p - pts[0]).find(|v| v.hypot2() > 0.0); + if let (Some(u), Some(v)) = (away(from_a), away(from_b)) + && u.dot(v) > 0.0 + && u.cross(v).abs() <= PARALLEL_SINE * u.hypot() * v.hypot() + { + return true; + } + a.hi.min(b.hi) - a.lo.max(b.lo) > touch && a.across_hi.min(b.across_hi) - a.across_lo.max(b.across_lo) > touch +} + +/// Is there a direction, along or across a side of either segment's control polygon or chord, in +/// which the control points of `a` and `b` lie more than `touch` apart? +fn hulls_apart(a: &CubicBez, b: &CubicBez, touch: f64) -> bool { + let (pa, pb) = ([a.p0, a.p1, a.p2, a.p3], [b.p0, b.p1, b.p2, b.p3]); + let apart = |d: kurbo::Vec2| { + let span = + |pts: &[Point; 4]| pts.iter().map(|p| p.to_vec2().dot(d)).fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), v| (l.min(v), h.max(v))); + let ((la, ha), (lb, hb)) = (span(&pa), span(&pb)); + let gap = touch * d.hypot(); + gap > 0.0 && (lb - ha > gap || la - hb > gap) + }; + let sides = |p: [Point; 4]| [p[3] - p[0], p[1] - p[0], p[2] - p[1], p[3] - p[2]]; + sides(pa).into_iter().chain(sides(pb)).any(|d| apart(d) || apart(kurbo::Vec2::new(-d.y, d.x))) } /// [`area`] that reports a refused input instead of an area of zero. @@ -1316,6 +1471,185 @@ mod tests { assert!(arrangement_adds_up(&arr, [&s, &t])); } + /// The union with every input swept on its own and then all their contours swept together. + fn unite_swept_twice(paths: &[(&PathData, FillRule)], precision: f64) -> PathData { + let bps: Vec = paths.iter().map(|(p, _)| fill_bezpath(p)).collect(); + let mut all = BezPath::new(); + for (bp, (_, r)) in bps.iter().zip(paths) { + for ct in normalize_bez(bp, *r).unwrap().contours() { + all.extend(ct.path.iter()); + } + } + all_contours_to_path(&normalize_bez(&all, FillRule::NonZero).unwrap(), &Tidy::keeping(precision, bps.iter())) + } + + /// The unions of `paths` by [`unite_all_with`] and [`try_unite_all_with`], each with the sweeps it made. + fn unite_counting_sweeps(paths: &[(&PathData, FillRule)]) -> [(PathData, usize); 2] { + let counted = |f: &dyn Fn() -> PathData| { + NORMALIZE_SWEEPS.with(|n| n.set(0)); + let out = f(); + (out, NORMALIZE_SWEEPS.with(std::cell::Cell::get)) + }; + [counted(&|| unite_all_with(paths, DEFAULT_PRECISION)), counted(&|| try_unite_all_with(paths, DEFAULT_PRECISION).unwrap())] + } + + /// Disjoint rings, each a circle with a circular hole, as one even-odd compound path. + fn rings(n: usize) -> PathData { + let mut bp = BezPath::new(); + for i in 0..n { + let c = Point::new((i % 10) as f64 * 30.0, (i / 10) as f64 * 30.0); + bp.extend(kurbo::Circle::new(c, 12.0).path_elements(0.1)); + bp.extend(kurbo::Circle::new(c, 5.0).path_elements(0.1)); + } + PathData::from_bezpath(&bp) + } + + /// A polygon with `n` teeth of different heights along its top. + fn zigzag(n: usize) -> PathData { + let mut pts: Vec = (0..=n).map(|i| Point::new(i as f64 * 4.0, if i % 2 == 0 { 0.0 } else { -10.0 - (i * 37 % 11) as f64 })).collect(); + pts.push(Point::new(n as f64 * 4.0, 20.0)); + pts.push(Point::new(0.0, 20.0)); + PathData::single(vectorcraft_geom::SubPath::polyline(&pts, true)) + } + + /// A sweep can leave segments within its tolerance apart where a second sweep joins them. + #[test] + fn a_lone_input_with_segments_within_the_tolerance_is_swept_again() { + use vectorcraft_geom::SubPath; + let triangles = |gap: f64, lift: f64| { + PathData::new(vec![ + SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(0.0, 10.0)], true), + SubPath::polyline(&[Point::new(10.0 + gap, lift), Point::new(10.0 + gap, 10.0 + lift), Point::new(gap, 10.0 + lift)], true), + ]) + }; + let mut bp = BezPath::new(); + bp.extend(kurbo::Circle::new((0.0, 0.0), 10.0).path_elements(0.1)); + bp.extend(kurbo::Circle::new((20.000001, 0.0), 10.0).path_elements(0.1)); + let circles = PathData::from_bezpath(&bp); + for (name, path, joined) in + [("snapped", triangles(0.99e-6, 0.99e-6), Some(1)), ("same heights", triangles(0.9e-6, 0.0), Some(1)), ("circles", circles, None)] + { + let want = unite_swept_twice(&[(&path, FillRule::NonZero)], DEFAULT_PRECISION); + if let Some(n) = joined { + assert_eq!(want.subpaths.len(), n, "{name}"); + } + for (got, sweeps) in unite_counting_sweeps(&[(&path, FillRule::NonZero)]) { + assert_eq!(sweeps, 2, "{name}"); + assert_eq!(got, want, "{name}"); + } + } + // Farther apart than that, the sweep's own contours stand. + let apart = triangles(1e-5, 0.0); + let want = unite_swept_twice(&[(&apart, FillRule::NonZero)], DEFAULT_PRECISION); + assert_eq!(want.subpaths.len(), 2); + for (got, sweeps) in unite_counting_sweeps(&[(&apart, FillRule::NonZero)]) { + assert_eq!(sweeps, 1); + assert_eq!(got, want); + } + } + + #[test] + fn a_lone_part_beside_a_refused_input_keeps_its_union() { + use vectorcraft_geom::SubPath; + let polygon = |pts: &[(f64, f64)]| PathData::single(SubPath::polyline(&pts.iter().map(|p| Point::new(p.0, p.1)).collect::>(), true)); + let square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let refused = polygon(&[(f64::NAN, 0.0), (1.0, 1.0), (0.0, 1.0)]); + let want = unite_swept_twice(&[(&square, FillRule::NonZero)], DEFAULT_PRECISION); + assert_eq!(unite_all(&[(&square, FillRule::NonZero), (&refused, FillRule::NonZero)]), want); + } + + #[test] + fn neighboring_segments_run_together_when_one_lies_along_the_other() { + let line = |a: (f64, f64), b: (f64, f64)| CloseSeg::new(Seg::line(a.into(), b.into()), 0, 0, 2); + let curve = |p: [(f64, f64); 4]| CloseSeg::new(Seg { c: CubicBez::new(p[0], p[1], p[2], p[3]), line: false }, 0, 0, 2); + let touch = 2e-6; + // The two sides of a needle's tip, and an ordinary corner. + assert!(neighbors_run_together(&line((10.0, 10.0), (30.0, 30.0)), &line((30.0, 30.0), (10.0, 10.000001)), touch)); + assert!(!neighbors_run_together(&line((0.0, 0.0), (10.0, 0.0)), &line((10.0, 0.0), (10.0, 10.0)), touch)); + // Curves that fold back over each other, and two quarters of a circle. + let out = curve([(0.0, 0.0), (5.0, 8.0), (10.0, 8.0), (20.0, 0.0)]); + assert!(neighbors_run_together(&out, &curve([(20.0, 0.0), (10.0, 6.0), (5.0, 6.0), (0.0, 1.0)]), touch)); + // A curved hairpin that lies within the tolerance along its length. + let there = curve([(0.0, 0.0), (5.0, 1e-7), (15.0, 1e-7), (20.0, 0.0)]); + assert!(neighbors_run_together(&there, &curve([(20.0, 0.0), (15.0, 2e-7), (5.0, 2e-7), (0.0, 1e-6)]), touch)); + let quarter = curve([(10.0, 0.0), (10.0, 5.5), (5.5, 10.0), (0.0, 10.0)]); + assert!(!neighbors_run_together(&quarter, &curve([(0.0, 10.0), (-5.5, 10.0), (-10.0, 5.5), (-10.0, 0.0)]), touch)); + } + + #[test] + fn a_lone_input_its_own_sweep_does_not_split_is_swept_once() { + for (name, path, rule) in [("rings", rings(40), FillRule::EvenOdd), ("zigzag", zigzag(301), FillRule::NonZero)] { + let want = unite_swept_twice(&[(&path, rule)], DEFAULT_PRECISION); + assert!(!want.is_empty(), "{name}"); + for (got, sweeps) in unite_counting_sweeps(&[(&path, rule)]) { + assert_eq!(sweeps, 1, "{name}"); + assert_eq!(got, want, "{name}"); + } + } + } + + #[test] + fn inputs_that_cross_or_are_several_are_swept_again_together() { + // Overlapping circles in one compound path: the first sweep splits them where they cross. + let mut bp = BezPath::new(); + for i in 0..12 { + bp.extend(kurbo::Circle::new(((i % 4) as f64 * 15.0, (i / 4) as f64 * 15.0), 10.0).path_elements(0.1)); + } + let overlapping = PathData::from_bezpath(&bp); + let want = unite_swept_twice(&[(&overlapping, FillRule::NonZero)], DEFAULT_PRECISION); + for (got, sweeps) in unite_counting_sweeps(&[(&overlapping, FillRule::NonZero)]) { + assert_eq!(sweeps, 2); + assert_eq!(got, want); + } + // Two overlapping squares in one compound path, each with an anchor where the other crosses it: the first sweep + // splits no segment and starts every piece at an anchor, but drops the pieces inside the other square. + let mut bp = BezPath::new(); + for pts in [ + [(0.0, 0.0), (10.0, 0.0), (10.0, 5.0), (10.0, 10.0), (5.0, 10.0), (0.0, 10.0)], + [(5.0, 5.0), (10.0, 5.0), (15.0, 5.0), (15.0, 15.0), (5.0, 15.0), (5.0, 10.0)], + ] { + bp.move_to(pts[0]); + for p in &pts[1..] { + bp.line_to(*p); + } + bp.close_path(); + } + let anchored = PathData::from_bezpath(&bp); + let want = unite_swept_twice(&[(&anchored, FillRule::NonZero)], DEFAULT_PRECISION); + for (got, sweeps) in unite_counting_sweeps(&[(&anchored, FillRule::NonZero)]) { + assert_eq!(sweeps, 2); + assert_eq!(got, want); + } + // Two plain overlapping squares in one compound path: as many segments come out as go in, because the sweep drops + // the two pieces inside the other square and adds two where the outlines cross. + let mut bp = BezPath::new(); + for (x, y) in [(0.0, 0.0), (5.0, 5.0)] { + bp.move_to((x, y)); + bp.line_to((x + 10.0, y)); + bp.line_to((x + 10.0, y + 10.0)); + bp.line_to((x, y + 10.0)); + bp.close_path(); + } + let balanced = PathData::from_bezpath(&bp); + assert_eq!( + normalize_bez(&fill_bezpath(&balanced), FillRule::NonZero).unwrap().contours().map(|c| c.path.segments().count()).sum::(), + 8 + ); + let want = unite_swept_twice(&[(&balanced, FillRule::NonZero)], DEFAULT_PRECISION); + for (got, sweeps) in unite_counting_sweeps(&[(&balanced, FillRule::NonZero)]) { + assert_eq!(sweeps, 2); + assert_eq!(got, want); + } + // Two inputs that do not cross each other or themselves are still swept together. + let (a, b) = (square(0.0, 0.0, 10.0), square(20.0, 0.0, 10.0)); + let both = [(&a, FillRule::NonZero), (&b, FillRule::NonZero)]; + let want = unite_swept_twice(&both, DEFAULT_PRECISION); + for (got, sweeps) in unite_counting_sweeps(&both) { + assert_eq!(sweeps, 3); + assert_eq!(got, want); + } + } + #[test] #[cfg(panic = "unwind")] fn a_panic_in_the_contour_pass_becomes_an_error() { diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 66ff8b6e39..a5a3b83863 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -52,3 +52,9 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } serde_json = { workspace = true } # `draw_text`, to write test files with live text as other writers do. krilla = { workspace = true, features = ["simple-text"] } + +# An independent raster oracle for gradient placement in PDF forms. These are test-only macOS +# bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer. +[target.'cfg(target_os = "macos")'.dev-dependencies] +objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFData"] } +objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGBitmapContext", "CGColorSpace", "CGContext", "CGDataProvider", "CGImage", "CGPDFDocument", "CGPDFPage"] } diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 47184d5202..d8316e94e3 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -9,12 +9,11 @@ use craft_pdf::write::{self, Metadata}; use krilla::color::separation::{Color as SepColor, SeparationColorant, SeparationSpace}; use krilla::color::{cmyk, luma, rgb}; use krilla::configure::{Archival, PdfVersion}; -use krilla::geom::{Path, PathBuilder, Size, Transform}; +use krilla::geom::{Path, PathBuilder, Size}; use krilla::image::Image; use krilla::num::NormalizedF32; use krilla::page::PageSettings; use krilla::paint::{Fill, LinearGradient, RadialGradient, SpreadMethod, Stop, Stroke, StrokeDash}; -use krilla::surface::Surface; use krilla::text::{Glyph, GlyphId, KrillaGlyph}; use kurbo::{PathEl, Shape, Vec2}; use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; @@ -28,6 +27,7 @@ use crate::forms::Mark; use crate::lab_spot::{find, rfind}; use crate::marks::PageBoxes; use crate::output::ColorOut; +use crate::surface::Surface; use crate::{Compatibility, ExportReport, PdfError, PdfOptions, Standard}; mod entry; @@ -40,7 +40,7 @@ mod text; mod writer; pub(crate) use entry::{RgbInCmyk, leaving_out_undecodable}; -pub use entry::{export, export_with_report, page_areas}; +pub use entry::{check_page_sizes, export, export_with_report, page_areas}; #[cfg(test)] use exporter::{MAX_COORD, writable, xf}; #[cfg(test)] @@ -131,7 +131,7 @@ mod tests { fn writable_bounds_values_the_transform_and_values_through_it() { let mut pdf = krilla::Document::new(); let mut page = pdf.start_page_with(PageSettings::new(Size::from_wh(100.0, 100.0).unwrap())); - let mut s = page.surface(); + let mut s = Surface::page(page.surface(), 100.0); let r = Rect::new(0.0, 0.0, 10.0, 10.0); assert!(writable(&s, Affine::IDENTITY, r)); assert!(!writable(&s, Affine::IDENTITY, Rect::new(-2_147_483_649.0, 0.0, 10.0, 10.0))); diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index d131ece8fd..75b87209c5 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -1,5 +1,6 @@ use super::writer::{Sheet, Writer, date_time}; -use super::{Affine, Document, ExportReport, Exporter, HashSet, PageBoxes, PdfError, PdfOptions, Rect, write}; +use super::{Affine, Document, ExportReport, Exporter, HashSet, PageBoxes, PdfError, PdfOptions, Rect, krilla, write}; +use crate::{Compatibility, PdfSettings, Standard}; /// Export `doc` as PDF bytes: one page per artboard (or the artboards chosen in `opts`). pub fn export(doc: &Document, opts: &PdfOptions) -> Result, PdfError> { @@ -49,6 +50,8 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; let doc = baked.as_ref().unwrap_or(doc); let pages = pages(doc, opts)?; + let raised = for_long_pages(set, &pages)?; + let set = raised.as_ref().unwrap_or(set); let title = crate::pdfx::title(set.standard, opts.title.clone().unwrap_or_else(|| doc.title.clone())); // The time of writing (none on the web) dates the editing data and the page information. @@ -59,6 +62,11 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let mut w = Writer::new(doc, set, &title, created_at, doc.color_mode == vectorcraft_doc::ColorMode::Cmyk)?; // Preserve Editing: the native document as an embedded file (`check` refused PDF/A with it). let mut warnings = set.warnings(); + if raised.is_some() { + warnings.push( + "PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6".into(), + ); + } let native = opts.native.as_deref().filter(|_| set.preserve_editing); if let Some(native) = native { w.pdf.document_mut().embed_file(crate::editing::embedded_file(native, set.compression.compress_text, now.map(date_time))); @@ -78,9 +86,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha ex.overprint = set.advanced.overprint == crate::Overprint::Preserve; let bleed = set.bleed_of(doc); let marks = set.marks.printer_marks(); - // In PDF 1.6 and later files that aren't PDF/X files, a page with a side longer than - // [`MAX_PAGE_SIDE`] is written in larger units; other files have every page in points. - let scales = set.compatibility.has_user_unit() && !set.standard.is_pdfx(); + let scales = writes_user_units(set); // PDF/X files have no annotations over the art (ISO 15930: only printer's mark and trap // network annotations, outside the bleed box): objects' URLs aren't written as links there. let links = !set.standard.is_pdfx(); @@ -93,6 +99,8 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha } let mut units = Vec::with_capacity(pages.len()); let total = pages.len() as u64; + let long: Vec<(usize, f64)> = + pages.iter().map(|(i, b)| (*i, b.media.width().max(b.media.height()))).filter(|(_, side)| *side > MAX_PDF14_REAL).collect(); for (written, (i, boxes)) in pages.into_iter().enumerate() { // The page count and the page being written, for a client that asked for progress. vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; @@ -104,6 +112,9 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha // `unit` points. let unit = if scales { user_unit(m.width(), m.height()) } else { 1.0 }; units.push(unit); + if m.width().max(m.height()) > MAX_PAGE_SIDE { + warnings.push(long_page_warning(set, i, m.width(), m.height(), unit, scales)); + } let shift = Affine::translate((-m.x0, -m.y0)); let view = if unit > 1.0 { Affine::scale(1.0 / unit) * shift } else { shift }; let sheet = Sheet { @@ -127,7 +138,10 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; let (layers, overprinted, invisible) = (ex.layers, ex.overprinted, ex.invisible); w.absorb(ex); - let (bytes, more) = w.finish(left_out, display_doc_title)?; + let (bytes, more) = match w.finish(left_out, display_doc_title) { + Ok(done) => done, + Err(e) => return Err(writer_error(doc, opts, left_out, &long, e)), + }; let bytes = crate::forms::finish(bytes, doc, set, layers, overprinted, invisible)?; // The writer gives the file its creation date as its modification date too. let bytes = match opts.modified.filter(|m| Some(*m) != created_at) { @@ -138,6 +152,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let bytes = crate::post::rights(bytes, &doc.metadata)?; warnings.extend(more); let bytes = crate::post::user_units(bytes, &units)?; + // A PDF 1.5 file written as PDF 1.6 keeps the encryption PDF 1.5 has (128-bit RC4). let bytes = crate::post::finish(bytes, opts, native.is_some(), &mut warnings)?; warnings.dedup(); Ok(ExportReport { bytes, warnings }) @@ -168,12 +183,153 @@ pub fn page_areas(doc: &Document, opts: &PdfOptions) -> Result, PdfErr /// gives: 14,400 (200 inches in units of 1/72 inch). pub(crate) const MAX_PAGE_SIDE: f64 = 14_400.0; +/// The smallest side of a page in units of its default user space that ISO 32000-1 (Annex C.2) +/// gives: 3. +const MIN_PAGE_SIDE: f64 = 3.0; + +/// The largest real number the writer puts in a PDF 1.3 or 1.4 file: past it, krilla fails the +/// file with `Limit(TooLargeFloat)`. +const MAX_PDF14_REAL: f64 = 32_767.0; + +/// Pages with a side longer than [`MAX_PAGE_SIDE`] are written with a `UserUnit`: in PDF 1.6 and +/// later files that aren't PDF/X files. Other files have every page in points. +fn writes_user_units(set: &PdfSettings) -> bool { + set.compatibility.has_user_unit() && !set.standard.is_pdfx() +} + /// The `UserUnit` (PDF 1.6) of a page `w` × `h` points large: 1 when both sides are at most /// [`MAX_PAGE_SIDE`], else the longer side divided by it, rounded up to the next thousandth, so -/// that both sides are at most [`MAX_PAGE_SIDE`] units. +/// that both sides are at most [`MAX_PAGE_SIDE`] units. A short side of [`MIN_PAGE_SIDE`] points +/// or more stays at least [`MIN_PAGE_SIDE`] units: the unit is at most the short side divided by +/// it, rounded down to the next thousandth, and the long side is then longer than +/// [`MAX_PAGE_SIDE`] units. fn user_unit(w: f64, h: f64) -> f64 { - let side = w.abs().max(h.abs()); - if side.is_finite() && side > MAX_PAGE_SIDE { (side / MAX_PAGE_SIDE * 1000.0).ceil() / 1000.0 } else { 1.0 } + let (side, short) = (w.abs().max(h.abs()), w.abs().min(h.abs())); + if !(side.is_finite() && side > MAX_PAGE_SIDE) { + return 1.0; + } + let unit = (side / MAX_PAGE_SIDE * 1000.0).ceil() / 1000.0; + if short >= MIN_PAGE_SIDE { unit.min((short / MIN_PAGE_SIDE * 1000.0).floor() / 1000.0).max(1.0) } else { unit } +} + +/// Check the page sizes of `doc` exported with `opts` before anything is drawn: the error +/// [`export`] gives for a page that the file's PDF version or standard can't hold. +pub fn check_page_sizes(doc: &Document, opts: &PdfOptions) -> Result<(), PdfError> { + for_long_pages(&opts.settings, &pages(doc, opts)?).map(|_| ()) +} + +/// The settings `set` is written with when one of `pages` has a side longer than +/// [`MAX_PAGE_SIDE`]: a PDF 1.5 file that isn't a PDF/X file is written as PDF 1.6, which has a +/// page's `UserUnit` (`None`: `set` as it is). Other files without a `UserUnit` have the page in +/// points. The writer puts a whole number as an integer and fails a PDF 1.3 or 1.4 file that has +/// a real number past [`MAX_PDF14_REAL`]: a page whose side is past it and not a whole number of +/// points is refused here, before anything is drawn ([`page_too_long`]). +fn for_long_pages(set: &PdfSettings, pages: &[(usize, PageBoxes)]) -> Result, PdfError> { + if !pages.iter().any(|(_, b)| b.media.width().max(b.media.height()) > MAX_PAGE_SIDE) { + return Ok(None); + } + let raised = (set.compatibility == Compatibility::Pdf15 && !set.standard.is_pdfx()) + .then(|| PdfSettings { compatibility: Compatibility::Pdf16, ..set.clone() }); + // The writer's test for a whole number, on the `f32` it writes. + let real = |side: f64| side > MAX_PDF14_REAL && (side as f32) as i32 as f32 != side as f32; + if let Some((i, b)) = pages.iter().find(|(_, b)| real(b.media.width()) || real(b.media.height())) { + page_too_long(set, *i, b.media.width().max(b.media.height()))?; + } + Ok(raised) +} + +/// The error for the page of artboard `artboard` (0-based), `side` points long, whose size or art +/// needs a real number past [`MAX_PDF14_REAL`], in a PDF 1.3 or 1.4 file written with `set`; `Ok` +/// in other files. +fn page_too_long(set: &PdfSettings, artboard: usize, side: f64) -> Result<(), PdfError> { + if !matches!(set.compatibility, Compatibility::Pdf13 | Compatibility::Pdf14) { + return Ok(()); + } + // PDF/X-1a and PDF/X-3 files are always PDF 1.3. + let label = if matches!(set.standard, Standard::PdfX1a | Standard::PdfX3) { set.standard.label() } else { set.compatibility.label() }; + let (max, n, side) = (thousands(MAX_PDF14_REAL), artboard + 1, format!("{:.0}", side.ceil())); + Err(PdfError::BadSetting(format!( + "{label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard" + ))) +} + +/// The writer's `error` for `doc` exported with `opts`, or, when it failed on a real number past +/// [`MAX_PDF14_REAL`] in a PDF 1.3 or 1.4 file, the error for the page of `long` (artboards and +/// sides past it) that needs one. With several such pages, the first [`MAX_PROBES`] are each +/// written alone, without the editing data and the thumbnails, to find it; past them, the first +/// page is named. +fn writer_error(doc: &Document, opts: &PdfOptions, left_out: &mut HashSet, long: &[(usize, f64)], error: PdfError) -> PdfError { + const MAX_PROBES: usize = 8; + let too_large = format!("{:?}", krilla::error::KrillaError::Limit(krilla::error::LimitError::TooLargeFloat)); + if !matches!(&error, PdfError::Write(e) if *e == too_large) { + return error; + } + let failing = match long { + [] => return error, + [one] => *one, + [first, ..] => long + .iter() + .take(MAX_PROBES) + .copied() + .find(|(i, _)| { + let alone = PdfOptions { + settings: opts.settings.clone(), + artboards: Some(vec![*i]), + title: opts.title.clone(), + display_doc_title: opts.display_doc_title, + created: opts.created, + modified: opts.modified, + native: None, + private_data: None, + thumbnails: vec![], + }; + matches!(export_with_report_inner(doc, &alone, left_out), Err(PdfError::BadSetting(_))) + }) + .unwrap_or(*first), + }; + page_too_long(&opts.settings, failing.0, failing.1).err().unwrap_or(error) +} + +/// `v` (a whole number) with commas between groups of three digits: 32,767. +fn thousands(v: f64) -> String { + let digits = format!("{v:.0}"); + let mut out = String::with_capacity(digits.len() + digits.len() / 3); + for (k, c) in digits.chars().enumerate() { + if k > 0 && (digits.len() - k) % 3 == 0 { + out.push(','); + } + out.push(c); + } + out +} + +/// A page `w` × `h` points large in points, rounded up, and in meters: 56693 × 2835 pt (20.00 × +/// 1.00 m). +fn page_size(w: f64, h: f64) -> String { + const METERS_PER_POINT: f64 = 0.0254 / 72.0; + format!("{:.0} × {:.0} pt ({:.2} × {:.2} m)", w.ceil(), h.ceil(), w * METERS_PER_POINT, h * METERS_PER_POINT) +} + +/// The warning for the page of artboard `artboard` (0-based), `w` × `h` points large with a side +/// longer than [`MAX_PAGE_SIDE`], written in units of `unit` points; `scales`: the file has +/// `UserUnit`s. +fn long_page_warning(set: &PdfSettings, artboard: usize, w: f64, h: f64, unit: f64, scales: bool) -> String { + let n = artboard + 1; + let size = page_size(w, h); + if scales && w.max(h) / unit > MAX_PAGE_SIDE { + format!( + "the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units" + ) + } else if unit > 1.0 { + format!( + "the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller" + ) + } else { + let label = if set.standard.is_pdfx() || set.standard == Standard::PdfA2b { set.standard.label() } else { set.compatibility.label() }; + format!( + "the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in" + ) + } } /// The RGB colours and non-CMYK images a CMYK document carries, which the export separates into diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index 2fea9a5686..d3d5f8e7fe 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -3,9 +3,11 @@ use vectorcraft_geom::Point; use super::entry::RgbInCmyk; use super::{ Affine, Arc, BezPath, BlendMode, Color, Compatibility, Document, Exporter, Fill, FillRule, HashMap, HashSet, Node, NormalizedF32, Path, - PathBuilder, PathEl, Rect, Shape, Standard, Surface, Transform, cmyk, krilla, luma, rgb, + PathBuilder, PathEl, Rect, Shape, Standard, Surface, cmyk, krilla, luma, rgb, }; +pub(super) use crate::surface::xf; + /// How deep inline graphics nest before they are left out. pub(super) const MAX_INLINE_DEPTH: u32 = 4; @@ -96,11 +98,6 @@ pub(super) const MAX_GRADIENT_PX: f64 = 4096.0; /// with overflow checks it panics on -2,147,483,648. pub(super) const MAX_COORD: f64 = 1e9; -pub(super) fn xf(a: Affine) -> Transform { - let c = a.as_coeffs(); - Transform::from_row(c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32, c[4] as f32, c[5] as f32) -} - /// The current transform of surface `s` in the content stream it draws into, without that stream's /// root transform (a page's y flip). pub(super) fn ctm(s: &Surface) -> Affine { @@ -203,9 +200,12 @@ pub(super) fn cover(s: &mut Surface, page: Rect, level: u8, opacity: f32) { /// group of that opacity that, unlike the writer's opacity groups, is not isolated. /// The cover is white, so a reader that takes every soft mask as a luminosity mask shows the same. pub(super) fn constant_mask(s: &mut Surface, page: Rect, alpha: f32) -> krilla::mask::Mask { + let transform = s.group_transform(); let mut sb = s.stream_builder(); - let mut ms = sb.surface(); + let mut ms = Surface::stream(sb.surface()); + ms.push_transform(&transform); cover(&mut ms, page, 255, alpha); + ms.pop(); ms.finish(); krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Alpha) } diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index dbf4b0d874..2d9a9cc175 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -22,8 +22,10 @@ impl Exporter<'_> { /// Opacity mask → luminosity soft mask. Outside the art the backdrop is black (clip) or white; /// invert is a white Difference rect on top (luminance is linear, so luma(1 − c) = 1 − luma(c)). fn soft_mask(&mut self, s: &mut Surface, m: &vectorcraft_doc::OpacityMask, page: Rect) -> Option { + let transform = s.group_transform(); let mut sb = s.stream_builder(); - let mut ms = sb.surface(); + let mut ms = Surface::stream(sb.surface()); + ms.push_transform(&transform); // An opaque backdrop when it matters: white outside the art (no clip), or black for the // inverting Difference pass below to turn white. if !m.clip || m.invert { @@ -39,6 +41,8 @@ impl Exporter<'_> { self.image_left_out = image_left_out.map(|outer| outer || incomplete); (self.knockout, self.overprint) = (knockout, overprint); if incomplete { + ms.pop(); + ms.finish(); return None; } if m.invert { @@ -46,6 +50,7 @@ impl Exporter<'_> { cover(&mut ms, page, 255, 1.0); ms.pop(); } + ms.pop(); ms.finish(); Some(krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity)) } @@ -96,21 +101,27 @@ impl Exporter<'_> { s.opacity = 1.0; s }; + let transform = s.group_transform(); let mut sb = s.stream_builder(); - let mut ms = sb.surface(); + let mut ms = Surface::stream(sb.surface()); + ms.push_transform(&transform); cover(&mut ms, page, 255, 1.0); let alpha = { + let transform = ms.group_transform(); let mut ab = ms.stream_builder(); - let mut als = ab.surface(); + let mut als = Surface::stream(ab.surface()); + als.push_transform(&transform); let overprint = std::mem::take(&mut self.overprint); self.measured_node(&mut als, &shape, page, false, Some(measured)); self.overprint = overprint; + als.pop(); als.finish(); krilla::mask::Mask::new(ab.finish(), krilla::mask::MaskType::Alpha) }; ms.push_mask(alpha); cover(&mut ms, page, 0, 1.0); ms.pop(); + ms.pop(); ms.finish(); krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity) } diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 4750bef85c..9e4578bdca 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -351,7 +351,7 @@ impl Exporter<'_> { let cell = Rect::new(0.0, 0.0, pw, ph); let tiles = def.instances_in(Affine::IDENTITY, cell); let mut sb = s.stream_builder(); - let mut cs = sb.surface(); + let mut cs = Surface::stream(sb.surface()); let reaches_out = tiles.iter().any(|t| t.visual_bounds().is_some_and(|b| cell.intersect(b) != b)); let clip = reaches_out.then(|| to_path(&cs, &cell.to_path(0.1))).flatten(); if let Some(c) = &clip { diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index d7e652f2e5..027025ad2c 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -2,7 +2,7 @@ use super::entry::RgbInCmyk; use super::exporter::{constant_mask, cover, to_path, writable, xf}; use super::{ Affine, Arc, Archival, ColorOut, Compatibility, Document, Exporter, HashSet, Image, Metadata, Node, PageSettings, PdfError, PdfVersion, Rect, - Shape, Size, Standard, Vec2, find, krilla, rfind, write, + Shape, Size, Standard, Surface, Vec2, find, krilla, rfind, write, }; /// A PDF being written, shared by export and print: the file's configuration and metadata, then @@ -125,7 +125,7 @@ impl Writer { let size = Size::from_wh(w.max(least) as f32, h.max(least) as f32).ok_or_else(|| PdfError::BadSetting(format!("page size {w} × {h}")))?; let at = |b: Rect| krilla::geom::Rect::from_ltrb(b.x0 as f32, b.y0 as f32, b.x1 as f32, b.y1 as f32); let mut page = self.pdf.document_mut().start_page_with(PageSettings::new(size).with_trim_box(at(sheet.trim)).with_bleed_box(at(sheet.bleed))); - let mut s = page.surface(); + let mut s = Surface::page(page.surface(), size.height()); let paper = Rect::new(0.0, 0.0, w, h); if sheet.negative { cover(&mut s, paper, 255, 1.0); diff --git a/crates/pdf/src/forms.rs b/crates/pdf/src/forms.rs index 4a1d061473..b771e88b7b 100644 --- a/crates/pdf/src/forms.rs +++ b/crates/pdf/src/forms.rs @@ -13,7 +13,6 @@ use std::io::Read; use craft_pdf::write::backend as krilla; use krilla::geom::PathBuilder; use krilla::graphic::Graphic; -use krilla::surface::Surface; use std::sync::Arc; use vectorcraft_doc::{Document, Node, NodeKind}; @@ -21,6 +20,7 @@ use vectorcraft_doc::{Document, Node, NodeKind}; use crate::encrypt::{Lexer, Obj, StreamSpans, Tok, int, stream_spans}; use crate::output::{deflate, text_string}; use crate::patch::{Patch, Xref}; +use crate::surface::{Surface, affine}; use crate::{PdfError, PdfSettings, Standard}; /// What a marked form is. @@ -87,6 +87,9 @@ pub(crate) fn form(s: &mut Surface, mark: Mark, draw: impl FnOnce(&mut Surface)) /// form's drawing space), rounded outwards to whole units: [`finish`] gives the form a box that /// covers the paper and the art. pub(crate) fn layer_form(s: &mut Surface, i: usize, paper: vectorcraft_geom::Rect, draw: impl FnOnce(&mut Surface)) { + // The art and its box move into page space together; keeping the old local paper here + // would clip layers on translated artboards or give the importer a spurious clipping group. + let paper = affine(s.group_transform()).transform_rect_bbox(paper); let corner = |x: f64, y: f64| (x as f32, y as f32); marked(s, Mark::Layer(i), [corner(paper.x0.floor(), paper.y0.floor()), corner(paper.x1.ceil(), paper.y1.ceil())], draw); } @@ -94,8 +97,9 @@ pub(crate) fn layer_form(s: &mut Surface, i: usize, paper: vectorcraft_geom::Rec /// Draw `draw` as a form of its own, marked `mark`: an empty clip from the mark's first point /// through `rest`. fn marked(s: &mut Surface, mark: Mark, rest: [(f32, f32); 2], draw: impl FnOnce(&mut Surface)) { + let transform = s.group_transform(); let mut sb = s.stream_builder(); - let mut fs = sb.surface(); + let mut fs = Surface::stream(sb.surface()); let (x, y) = mark.at(); let mut pb = PathBuilder::new(); pb.move_to(x, y); @@ -108,10 +112,14 @@ fn marked(s: &mut Surface, mark: Mark, rest: [(f32, f32); 2], draw: impl FnOnce( fs.push_clip_path(&p, &krilla::paint::FillRule::NonZero); fs.pop(); } + fs.push_transform(&transform); draw(&mut fs); + fs.pop(); fs.finish(); let stream = sb.finish(); + s.push_transform(&transform.invert().unwrap_or_default()); s.draw_graphic(Graphic::new(stream, false)); + s.pop(); } // ---------- finishing the written file ---------- diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index 6423578af1..ffc185a575 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -30,6 +30,7 @@ use crate::import_shading::{ use crate::import_text::{Families, LineFacts, Look, Placement, TextLine, Upright}; use crate::{CropTo, ImportOptions, ImportReport, PdfError, TextAs}; +mod actual_text; mod builder; mod cid; mod device; diff --git a/crates/pdf/src/import/actual_text.rs b/crates/pdf/src/import/actual_text.rs new file mode 100644 index 0000000000..d6d18a7566 --- /dev/null +++ b/crates/pdf/src/import/actual_text.rs @@ -0,0 +1,95 @@ +//! Bounded ownership of authored replacement text (ISO 32000-1, 14.9.4). + +use super::state::Builder; +use super::{Affine, Look, Placement, Shape, TextLine, Upright}; +use crate::import_text::TextContent; + +/// Only one replacement is retained: the outermost owner, even after it is consumed. +/// Depth is counted separately so ignored deep tags still unwind to the right owner. +#[derive(Default)] +pub(super) struct ActualText { + depth: usize, + owner: Option, + pending: Option, +} + +impl ActualText { + pub(super) fn begin(&mut self) { + self.depth = self.depth.saturating_add(1); + } + + pub(super) fn end(&mut self) { + if self.owner == Some(self.depth) { + self.owner = None; + self.pending = None; + } + self.depth = self.depth.saturating_sub(1); + } + + pub(super) fn active(&self) -> bool { + self.owner.is_some() + } + + pub(super) fn set(&mut self, bytes: &[u8]) -> bool { + if self.active() { + return true; + } + // Bound before decoding: at most 64 KiB encoded / 192 KiB UTF-8, and no + // allocation per nested tag. Oversized/deep replacements use ordinary mappings. + if self.depth == 0 || self.depth > 128 || bytes.len() > 64 * 1024 { + return false; + } + self.owner = Some(self.depth); + self.pending = Some(crate::import_scan::text_string(bytes)); + true + } +} + +impl Builder<'_> { + /// The authored path never enters ordinary visual glyph reordering. The font was matched + /// against the glyph's original Unicode, not against this replacement's characters. + pub(super) fn actual_glyph(&mut self, o: &craft_pdf::interpret::font::OutlineGlyph, m: Affine, at: Placement, look: Look, opacity: f32) -> bool { + let key = o.font_cache_key(); + self.flush_glyphs(); + // A fill and stroke callback for the same glyph consumes its text only once. + if let (Some(stroke), Some(line)) = (&look.stroke, &mut self.text) + && look.fill.is_none() + && line.stroke_actual(key, at, stroke.clone(), look.overprint_stroke) + { + return true; + } + let width = o.advance_width().filter(|w| w.is_finite()); + let advance = width.map_or(at.size * 0.5, |w| w as f64 / 1000.0 * at.size * at.h_scale / 100.0); + let top = width.filter(|w| w.abs() <= 1.0).map(|_| { + let vx = self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(o.glyph_id().to_u32())); + Upright { top: m * kurbo::Point::new(vx, 880.0) } + }); + // Keep pending until placement succeeds, including across a line flush. + let pending = self.actual.pending.take(); + let content = match pending.as_deref() { + Some(text) if !text.is_empty() => TextContent::Actual(text), + _ => TextContent::Pen, + }; + let place = |line: &mut TextLine| match top { + Some(top) => line.push_upright_content(&look, at, opacity, top, content), + None => line.push_content(&look, at, opacity, advance, content), + }; + if !self.text.as_mut().is_some_and(place) { + self.flush_text(); + let mut line = TextLine::new(at, opacity); + if !place(&mut line) { + self.actual.pending = pending; + return false; + } + self.text = Some(line); + } + let mut ink = o.outline(); + if let Some(line) = &mut self.text + && !ink.elements().is_empty() + { + ink.apply_affine(m); + line.ink.push(ink.bounding_box()); + } + true + } +} diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index b16b49b035..61acbfc8ea 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -23,6 +23,7 @@ impl<'p> Builder<'p> { glyphs: None, text: None, text_as, + actual: Default::default(), images: HashMap::new(), image_keys: HashMap::new(), cmyk_keys: HashSet::new(), @@ -102,6 +103,7 @@ impl<'p> Builder<'p> { self.mask = None; self.masked.clear(); self.marked.clear(); + self.actual = Default::default(); (self.scan, self.tag_at, self.aligned, self.paint_at) = (scan, 0, true, 0); if self.scan.overprints && self.scan.zero_mode { self.warn(OVERPRINT_ZERO_MODE); @@ -583,13 +585,13 @@ impl<'p> Builder<'p> { Some(Paint::Pattern { pattern: name, xf }) } - /// Separation image `st` (`w` × `h` pixels) as the paint of its ink at 100 % (a spot swatch, a + /// Image `st` of one ink (`w` × `h` pixels) as the paint of its ink at 100 % (a spot swatch, a /// process plate or Registration, found by its colour space) and its tints as gray pixels /// ([`crate::import_image::tint_gray`]). `None` for another image, an ink whose colour can't /// be told, or tints that can't be read (with a warning): the image opens in RGB. The ink is /// only marked used once the tints are read. pub(super) fn separation_image(&mut self, st: &craft_pdf::syntax::object::Stream<'_>, w: u32, h: u32) -> Option<(Paint, Vec)> { - let space = self.colors.array_space(&crate::import_image::separation_space(st)?)?; + let space = self.colors.array_space(&crate::import_image::one_ink_space(st)?)?; let gray = crate::import_image::tint_gray(st, w, h).map_err(|why| self.warn(why)).ok()?; Some((self.colors.native(space, &[1.0])?.paint(), gray)) } @@ -749,6 +751,7 @@ impl<'p> Builder<'p> { if self.text_as != TextAs::Text || self.nested > 0 { return false; } + let authored = self.actual.active(); let key = o.font_cache_key(); let glyph = o.glyph_id().to_u32(); let (unicode, from_cid) = match o.as_unicode().filter(|u| !replacement(u)) { @@ -773,6 +776,7 @@ impl<'p> Builder<'p> { let text: String = match unicode { Some(BfString::Char(c)) => c.to_string(), Some(BfString::String(s)) => s, + None if authored => String::new(), None => { // Invisible text isn't kept as outlines: the caller says it was left out. if paint.is_some() && o.as_unicode().is_some_and(|u| replacement(&u)) { @@ -785,7 +789,7 @@ impl<'p> Builder<'p> { // Adobe's CID tables map some ideographs to their look-alike Kangxi radicals. let text: String = if from_cid { text.chars().map(unify_radical).collect() } else { text }; let Some(at) = Placement::of(m) else { return false }; - if text.is_empty() || text.chars().any(|c| c.is_control()) { + if !authored && (text.is_empty() || text.chars().any(|c| c.is_control())) { return false; } let width = o.advance_width().filter(|w| w.is_finite()); @@ -849,6 +853,9 @@ impl<'p> Builder<'p> { fill: if stroke.is_none() { paint } else { None }, stroke, }; + if authored { + return self.actual_glyph(o, m, at, look, opacity); + } let advance = width.map_or(at.size * 0.5, |w| w as f64 / 1000.0 * at.size * at.h_scale / 100.0); // A glyph set vertically is drawn from its origin, which the file puts the position // vector's vx (from the font's `W2`, else half its width from `W` or `DW`) to the left of @@ -858,6 +865,9 @@ impl<'p> Builder<'p> { let vx = self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(glyph)); m * kurbo::Point::new(vx, 880.0) }); + // A horizontal line is gathered in visual order and put back in logical order as a whole: + // a ligature's characters (lam-alef, lam-lam-heh) go in visual order too (#6072). + let text = if top.is_none() { visual_glyph_text(text) } else { text }; let place = |line: &mut TextLine| match top { Some(top) => line.push_upright(&look, at, opacity, Upright { top }, &text), None => line.push(&look, at, opacity, advance, &text), @@ -887,3 +897,16 @@ impl<'p> Builder<'p> { true } } + +/// The characters of one glyph in the order they are drawn: a PDF names a ligature's characters +/// in logical order (lam then alef for لا), while a horizontal line of type is gathered glyph by +/// glyph in visual order and only then put back in logical order. Right-to-left characters are +/// turned round here so that putting the line back restores them. +fn visual_glyph_text(text: String) -> String { + if text.chars().nth(1).is_none() { + return text; + } + let Some((order, _)) = vectorcraft_text::logical_order(&text) else { return text }; + let chars: Vec = text.chars().collect(); + order.iter().filter_map(|&i| chars.get(i)).collect() +} diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 53da5a5218..2fb6bb9c80 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -250,7 +250,7 @@ impl<'a> Device<'a> for Builder<'_> { let mask = if crate::import_image::has_mask(st) { self.alpha_mask(key, &r, w, h, transform) } else { None }; return self.add_image_masked(key, || cmyk.map(|blob| (blob, w, h)), transform, mask, None); } - // A Separation image keeps its ink: its tints as a grayscale image that the ink at + // An image of one ink keeps it: its tints as a grayscale image that the ink at // 100 % colorizes, as a mask painted in the ink comes in. Its mask becomes an // opacity mask, as a CMYK image's does. Read once per image: the decision is kept, // so one that opens in RGB stays RGB, and the gray pixels have their own key. @@ -378,6 +378,7 @@ impl<'a> Device<'a> for Builder<'_> { if self.nested > 0 { return; } + self.actual.begin(); let at = self.tag_at; self.tag_at += 1; let group = match self.scan.tags.get(at) { @@ -416,5 +417,12 @@ impl<'a> Device<'a> for Builder<'_> { self.flush(); } self.marked.pop(); + self.actual.end(); + } + + fn actual_text(&mut self, text: &[u8]) { + if self.nested == 0 && self.text_as == crate::TextAs::Text && !self.actual.set(text) { + self.warn("ActualText beyond the import size or nesting limit was left to glyph mappings"); + } } } diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 0eb100b362..93a84ae688 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -82,6 +82,7 @@ pub(super) struct Builder<'p> { pub(super) glyphs: Option, pub(super) text: Option, pub(super) text_as: TextAs, + pub(super) actual: super::actual_text::ActualText, pub(super) images: HashMap, pub(super) image_keys: HashMap, /// The images kept with their CMYK samples ([`crate::import_image`]). diff --git a/crates/pdf/src/import_image.rs b/crates/pdf/src/import_image.rs index b5875e9bd3..d376c2b31e 100644 --- a/crates/pdf/src/import_image.rs +++ b/crates/pdf/src/import_image.rs @@ -3,9 +3,10 @@ //! convention JPEG readers and the PDF writer take a CMYK JPEG to follow) is kept as it is; any //! other is decoded, its Decode array applied, and stored as a CMYK TIFF //! ([`ImageBlob::cmyk_tiff`]). A mask (`/SMask`, `/Mask`) doesn't change that: the importer -//! carries it as the image's opacity mask ([`has_mask`]). A Separation image keeps its ink: its -//! tints are read as a grayscale image ([`tint_gray`]) that the ink colorizes. Every other image is -//! read as RGB by the interpreter. +//! carries it as the image's opacity mask ([`has_mask`]). A DeviceN image of process plates only +//! keeps them the same way, as a CMYK image ([`process_devicen`]). An image of one ink (a +//! Separation, or a DeviceN of one colorant) keeps it: its tints are read as a grayscale image +//! ([`tint_gray`]) that the ink colorizes. Every other image is read as RGB by the interpreter. use craft_pdf::syntax::Filter; use craft_pdf::syntax::object::stream::{ImageColorSpace, ImageDecodeParams}; @@ -13,6 +14,8 @@ use craft_pdf::syntax::object::{Array, Dict, Name, Stream}; use vectorcraft_doc::ImageBlob; use vectorcraft_doc::cmyk::{Inks, MAX_CMYK_PIXELS, jpeg_components}; +use crate::import_color::ink_names; + /// A CMYK image read as RGB: why. pub(crate) const UNREAD: &str = "CMYK images whose samples couldn't be read in CMYK were imported in RGB"; @@ -57,7 +60,7 @@ fn decode_ranges(d: &Dict<'_>) -> [(f32, f32); 4] { pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result, &'static str> { let d = st.dict(); if !cmyk_space(d) { - return Ok(None); + return process_devicen(st, width, height); } let ranges = decode_ranges(d); let filters = st.filters(); @@ -94,19 +97,86 @@ pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result(st: &Stream<'a>) -> Option> { +/// The image's colour space when it lays one ink: a Separation (`[/Separation name alt tint]`), or +/// a DeviceN of one colorant (`[/DeviceN [name] alt tint …]`). `None` for the ink `None`, which +/// paints nothing (ISO 32000-1 §8.6.6.4): the interpreter draws it. +pub(crate) fn one_ink_space<'a>(st: &Stream<'a>) -> Option> { let d = st.dict(); let a = d.get::>(key(d, b"ColorSpace", b"CS"))?; - let one_ink = { - let mut it = a.flex_iter(); - it.next::>()?.as_ref() == b"Separation" && it.next::>()?.as_ref() != b"None" - }; + let one_ink = matches!(ink_names(&mut a.flex_iter()).as_ref().map(|(_, names)| names.as_slice()), Some([name]) if name != "None"); one_ink.then_some(a) } -/// The tints of the one-component image `st` (`width` × `height` pixels, a Separation image's) +/// The CMYK channel of each colorant of the image's DeviceN space (`None` for the ink `None`) when +/// it has two or more colorants and all are process plates, or `None`. One colorant is an image of +/// one ink ([`one_ink_space`]). +fn process_plates(d: &Dict<'_>) -> Option>> { + let a = d.get::>(key(d, b"ColorSpace", b"CS"))?; + let (device_n, names) = ink_names(&mut a.flex_iter())?; + // PDF's own limit is 32 colorants. + if !device_n || names.len() < 2 || names.len() > 32 { + return None; + } + let plates = names + .iter() + .map(|n| match n.as_str() { + "None" => Some(None), + n => ["Cyan", "Magenta", "Yellow", "Black"].iter().position(|p| *p == n).map(Some), + }) + .collect::>>()?; + plates.iter().any(Option::is_some).then_some(plates) +} + +/// A DeviceN image of process plates only ([`process_plates`]) in CMYK: each colorant's tint in +/// its plate, its Decode array applied, as a CMYK TIFF. `Ok(None)` for any other image, `Err` (a +/// warning) when its samples can't be read. +fn process_devicen(st: &Stream<'_>, width: u32, height: u32) -> Result, &'static str> { + let d = st.dict(); + let Some(plates) = process_plates(d) else { return Ok(None) }; + let bpc = d.get::(key(d, b"BitsPerComponent", b"BPC")).unwrap_or(8); + if !matches!(bpc, 8 | 16) { + return Err(UNREAD); + } + let n = u64::from(width) * u64::from(height); + if n == 0 || n > MAX_CMYK_PIXELS { + return Err(UNREAD); + } + let comps = plates.len(); + let ranges: Vec<(f32, f32)> = match d.get::>(key(d, b"Decode", b"D")).map(|a| a.iter::().collect::>()) { + Some(v) if v.len() == 2 * comps && v.iter().all(|x| x.is_finite()) => v.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect(), + _ => vec![(0.0, 1.0); comps], + }; + let size = usize::from(bpc / 8); + let params = + ImageDecodeParams { is_indexed: false, bpc: Some(bpc), num_components: u8::try_from(comps).ok(), target_dimension: None, width, height }; + let decoded = st.decoded_image(¶ms).map_err(|_| UNREAD)?; + // An image codec lays its samples out its own way. + if decoded.image_data.is_some() { + return Err(UNREAD); + } + // Within `MAX_CMYK_PIXELS` and 32 colorants of 2 bytes this fits a 64-bit `usize`, not always a + // 32-bit one (the web build): checked. + let len = usize::try_from(n).ok().and_then(|n| n.checked_mul(comps)?.checked_mul(size)).ok_or(UNREAD)?; + let raw = decoded.data.get(..len).ok_or(UNREAD)?; + let value = |s: &[u8]| match *s { + [hi, lo] => u16::from_be_bytes([hi, lo]) as f32 / 65535.0, + [v] => v as f32 / 255.0, + _ => 0.0, + }; + let mut inks = Vec::with_capacity(n as usize * 4); + for px in raw.chunks_exact(size * comps) { + let mut cmyk = [0.0f32; 4]; + for ((s, plate), (lo, hi)) in px.chunks_exact(size).zip(&plates).zip(&ranges) { + if let Some(c) = plate.and_then(|p| cmyk.get_mut(p)) { + *c = c.max((lo + value(s) * (hi - lo)).clamp(0.0, 1.0)); + } + } + inks.extend(cmyk.map(|v| (v * 255.0).round() as u8)); + } + Inks::new(width, height, inks).and_then(|i| ImageBlob::cmyk_tiff(&i)).map(Some).ok_or(UNREAD) +} + +/// The tints of the one-component image `st` (`width` × `height` pixels, an image of one ink) /// as a grayscale image: white where it lays no ink, black at 100 %, its Decode array applied. /// `Err` (a warning) when its samples can't be read. pub(crate) fn tint_gray(st: &Stream<'_>, width: u32, height: u32) -> Result, &'static str> { diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index 8157759e7d..a90d6a33be 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -146,6 +146,27 @@ fn common_gap(gaps: &[Gap]) -> f64 { if *common > 0.5 { 0.0 } else { common.max(0.0) } } +/// A mapped glyph, authored logical text, or a glyph whose replacement was already placed. +#[derive(Clone, Copy)] +pub(crate) enum TextContent<'a> { + Mapped(&'a str), + Actual(&'a str), + Pen, +} + +impl<'a> TextContent<'a> { + fn text(self) -> &'a str { + match self { + Self::Mapped(text) | Self::Actual(text) => text, + Self::Pen => "", + } + } + + fn authored(self) -> bool { + !matches!(self, Self::Mapped(_)) + } +} + /// A line of type being gathered: runs of glyphs on one baseline. pub(crate) struct TextLine { /// The first glyph's placement. @@ -173,6 +194,10 @@ pub(crate) struct TextLine { /// glyph has its glyph's [`Slot`]; a space read from a gap and the other characters of a /// glyph of several have none. slots: Vec>, + /// Per character: authored logical order must survive visual-to-logical reconstruction. + authored: Vec, + /// Fill callbacks in an authored span, for the reader's later stroke pass. + actual_fills: HashMap<(u128, u64, u64), Option>, /// The first glyph was set vertically ([`Upright`]). upright: Option, /// The glyphs make a column (vertical type), each below the last. @@ -232,6 +257,8 @@ impl TextLine { runs: vec![], text_bytes: 0, slots: vec![], + authored: vec![], + actual_fills: HashMap::new(), upright: None, column: false, ink: vec![], @@ -251,10 +278,24 @@ impl TextLine { /// line's single glyph a column): below the last one, in the same column. `false`: it starts /// another line. pub fn push_upright(&mut self, look: &Look, at: Placement, opacity: f32, upright: Upright, text: &str) -> bool { + self.push_upright_content(look, at, opacity, upright, TextContent::Mapped(text)) + } + + pub fn push_upright_content(&mut self, look: &Look, at: Placement, opacity: f32, upright: Upright, content: TextContent<'_>) -> bool { + let text = content.text(); + if !text.is_empty() && self.authored.is_empty() && self.upright.is_some() { + // Suppressed vertical glyphs likewise provide no text anchor. + self.at = at; + self.opacity = opacity; + self.runs.clear(); + self.column = false; + } let down = -self.at.up(); let size = self.at.size.max(at.size); let Some((last, _, run)) = self.runs.last_mut() else { self.runs.push((look.clone(), 0.0, text.to_string())); + self.record_actual_fill(look, at, content); + self.authored.extend(text.chars().map(|_| content.authored())); (self.upright, self.next, self.last) = (Some(upright), at.origin + down * at.size, at.origin); return true; }; @@ -276,14 +317,20 @@ impl TextLine { self.column = true; // Letter-spaced Japanese is common: a gap reads as a space only when a whole em is left // out (the tracking set in `finish` keeps narrower gaps). - if step > size * 0.9 && !run.ends_with(is_space) && !text.starts_with(is_space) { + if !matches!(content, TextContent::Pen) && step > size * 0.9 && !run.is_empty() && !run.ends_with(is_space) && !text.starts_with(is_space) { run.push(' '); + self.authored.push(false); } - if last.takes(look) { + if last.takes(look) + && (matches!(content, TextContent::Pen) + || (!matches!(content, TextContent::Actual(_)) && !self.authored.last().copied().unwrap_or(false))) + { run.push_str(text); } else { self.runs.push((look.clone(), 0.0, text.to_string())); } + self.record_actual_fill(look, at, content); + self.authored.extend(text.chars().map(|_| content.authored())); self.next = at.origin + down * at.size; self.last = at.origin; true @@ -292,10 +339,28 @@ impl TextLine { /// Add glyph `text` drawn with `look` at `at` (advancing `advance` points) at `opacity` if /// it continues this line; `false`: it starts another. pub fn push(&mut self, look: &Look, at: Placement, opacity: f32, advance: f64, text: &str) -> bool { + self.push_content(look, at, opacity, advance, TextContent::Mapped(text)) + } + + pub fn push_content(&mut self, look: &Look, at: Placement, opacity: f32, advance: f64, content: TextContent<'_>) -> bool { + let text = content.text(); + let pen = matches!(content, TextContent::Pen); // A vertical line (even a single upright glyph) takes no horizontal glyphs. if self.column || self.upright.is_some() { return false; } + if !pen && self.text_bytes == 0 && !self.baseline.is_empty() { + // A line containing only suppressed glyphs has no text anchor yet. Its first + // real character starts at its own origin, including after a line flush. + self.at = at; + self.opacity = opacity; + self.next = at.origin; + self.last = at.origin; + self.last_dir = at.dir; + self.last_size = at.size; + self.baseline.clear(); + self.runs.clear(); + } let bytes = self.text_bytes; let glyph = self.baseline.len(); let curved = self.curved(); @@ -334,12 +399,12 @@ impl TextLine { if !on_line && !on_curve { return false; } - if !run.ends_with(is_space) && !text.starts_with(is_space) { + if !pen && !run.is_empty() && !run.ends_with(is_space) && !text.starts_with(is_space) { self.gaps.push(Gap { at: bytes, width: gap, em: self.last_size.min(at.size), on_line }); } // A space the file draws between two glyphs spans the gaps on both sides of it. - let drawn = self.drawn_space.take(); - if on_line { + let drawn = if pen { None } else { self.drawn_space.take() }; + if on_line && !pen { let mut chars = text.chars(); if chars.next().is_some_and(is_space) && chars.next().is_none() && !run.ends_with(is_space) { self.drawn_space = Some((bytes, gap + advance)); @@ -347,7 +412,10 @@ impl TextLine { self.drawn_spaces.push((b, before + gap)); } } - if last.takes(look) && (*last_shift - shift).abs() < 1e-3 { + if last.takes(look) + && (*last_shift - shift).abs() < 1e-3 + && (pen || (!matches!(content, TextContent::Actual(_)) && !self.authored.last().copied().unwrap_or(false))) + { run.push_str(text); } else { self.runs.push((look.clone(), shift, text.to_string())); @@ -355,12 +423,18 @@ impl TextLine { } else { self.runs.push((look.clone(), 0.0, text.to_string())); } + self.record_actual_fill(look, at, content); self.text_bytes = self.text_bytes.saturating_add(text.len()); - let one = text.chars().count() == 1; - self.slots.push(Some(Slot { glyph, advance: one.then_some(advance) })); - self.slots.extend(text.chars().skip(1).map(|_| None)); + if !pen { + let one = text.chars().count() == 1 && !content.authored(); + self.slots.push(Some(Slot { glyph, advance: one.then_some(advance) })); + self.slots.extend(text.chars().skip(1).map(|_| None)); + self.authored.extend(text.chars().map(|_| content.authored())); + } + // Pen-only glyphs retain a baseline but no character slot: later text still points + // to its own glyph, even after several suppressed glyphs or a style change. self.next = at.origin + at.dir * advance; - if !text.trim().is_empty() { + if pen || !text.trim().is_empty() { self.visible = self.next; } self.last = at.origin; @@ -370,6 +444,25 @@ impl TextLine { true } + fn record_actual_fill(&mut self, look: &Look, at: Placement, content: TextContent<'_>) { + if content.authored() && look.fill.is_some() { + let run = matches!(content, TextContent::Actual(_)).then(|| self.runs.len().saturating_sub(1)); + self.actual_fills.insert((look.font, at.origin.x.to_bits(), at.origin.y.to_bits()), run); + } + } + + /// The reader fills a whole Tj/TJ before replaying its glyphs as strokes. A replay + /// must neither consume the replacement nor rewind the pen. Only the first glyph's + /// style belongs to the replacement; suppressed glyphs have no text to restyle. + pub fn stroke_actual(&mut self, font: u128, at: Placement, stroke: (Paint, f64), overprint: bool) -> bool { + let key = (font, at.origin.x.to_bits(), at.origin.y.to_bits()); + let Some(run) = self.actual_fills.remove(&key) else { return false }; + if let Some((look, ..)) = run.and_then(|i| self.runs.get_mut(i)) { + (look.stroke, look.overprint_stroke) = (Some(stroke), overprint); + } + true + } + /// Has the baseline turned (more than about 3° from the first glyph to the last)? fn curved(&self) -> bool { self.last_dir.dot(self.at.dir) < 0.9986 @@ -416,16 +509,27 @@ impl TextLine { // Turned along a curve: type on a path through the glyphs. let path = if self.curved() { self.baseline_path() } else { None }; facts.wraps = path.is_none() && self.upright.is_none() && self.runs.last().is_some_and(|(.., t)| t.ends_with(' ')); - if let Some((.., last)) = self.runs.last_mut() { - last.truncate(last.trim_end().len()); + if !self.authored.last().copied().unwrap_or(false) + && let Some((.., last)) = self.runs.last_mut() + { + // Trim only ordinary trailing spaces, never authored replacement characters. + let trim = last + .chars() + .rev() + .zip(self.authored.iter().rev()) + .take_while(|(c, authored)| c.is_whitespace() && !**authored) + .map(|(c, _)| c.len_utf8()) + .sum::(); + last.truncate(last.len().saturating_sub(trim)); } self.runs.retain(|(.., t)| !t.is_empty()); - if self.runs.iter().all(|(.., t)| t.trim().is_empty()) { + if self.runs.iter().all(|(.., t)| t.is_empty()) || (!self.authored.contains(&true) && self.runs.iter().all(|(.., t)| t.trim().is_empty())) { return None; } // The spaces trimmed off the end have no place either. let chars: usize = self.runs.iter().map(|(.., t)| t.chars().count()).sum(); self.slots.truncate(chars); + self.authored.truncate(chars); // The baseline most of the characters sit on is the line's: the others are shifted off it // (a line starting with a raised footnote mark keeps the baseline of its text). let mut on: Vec<(f64, usize)> = vec![]; @@ -493,6 +597,7 @@ impl TextLine { let char_at = earlier + head.chars().count(); if char_at <= self.slots.len() { self.slots.insert(char_at, None); + self.authored.insert(char_at, false); } run.text.insert(at, ' '); spaces.push((gap.at, gap.width, gap.on_line)); @@ -502,7 +607,7 @@ impl TextLine { gaps.extend(self.drawn_spaces.iter().map(|&(b, width)| (b + spaces.iter().filter(|s| s.0 < b).count(), width))); gaps.sort_by_key(|&(b, _)| b); if self.upright.is_none() { - to_logical(&mut t); + to_logical(&mut t, &self.authored); } let angle = self.at.dir.atan2(); // The glyphs' tops lean along the baseline (+x), up being -y in the type's own space. @@ -1055,9 +1160,26 @@ fn is_style(s: &str) -> bool { /// Hebrew or Arabic comes from a PDF in visual order (each glyph where it is drawn): put `t`'s text /// back in logical order, with the paragraph direction that shows it as drawn. -fn to_logical(t: &mut TextObject) { - let Some((order, rtl)) = vectorcraft_text::logical_order(&t.plain_text()) else { return }; +fn to_logical(t: &mut TextObject, authored: &[bool]) { + let Some((mut order, rtl)) = vectorcraft_text::logical_order(&t.plain_text()) else { return }; let chars: Vec<(char, usize)> = t.runs.iter().enumerate().flat_map(|(i, r)| r.text.chars().map(move |c| (c, i))).collect(); + if authored.contains(&true) { + // Explicit spans are logical-order islands. Reconstruct each ordinary stretch on + // either side independently; never reverse authored Arabic or its joiners again. + order.clear(); + let mut start = 0; + while start < chars.len() { + let actual = authored.get(start).copied().unwrap_or(false); + let end = (start + 1..chars.len()).find(|&i| authored.get(i).copied().unwrap_or(false) != actual).unwrap_or(chars.len()); + let text: String = chars.get(start..end).unwrap_or_default().iter().map(|(c, _)| c).collect(); + if !actual && let Some((local, _)) = vectorcraft_text::logical_order(&text) { + order.extend(local.into_iter().map(|i| start + i)); + } else { + order.extend(start..end); + } + start = end; + } + } let mut runs: Vec<(usize, String)> = Vec::with_capacity(t.runs.len()); for &(c, i) in order.iter().filter_map(|&k| chars.get(k)) { match runs.last_mut() { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index ca7e44ae7a..234f4b8a8d 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -70,11 +70,12 @@ mod presets; mod print; mod settings; mod streams; +mod surface; mod syntax; pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with}; pub use encrypt::Encryption; -pub use export::{export, export_with_report, page_areas}; +pub use export::{check_page_sizes, export, export_with_report, page_areas}; pub use file_info::{FileInfo, file_info}; #[cfg(any(test, feature = "read-count"))] pub use import::imports_of; diff --git a/crates/pdf/src/surface.rs b/crates/pdf/src/surface.rs new file mode 100644 index 0000000000..4229781cdd --- /dev/null +++ b/crates/pdf/src/surface.rs @@ -0,0 +1,140 @@ +//! Keep form XObjects in page space. Quartz resolves shading patterns inside a form against the +//! page's initial space, whereas other readers also apply the transform at the form's invocation. +//! Moving that transform inside the form makes both interpretations agree (including gradients +//! in opacity groups, masks, layers and overprinting art), without rasterizing the art. +//! +//! krilla's page surface has an implicit y flip which `ctm()` does not include. Remember that +//! root separately; a form's surface has an identity root. A group still counts as one push/pop +//! for the drawing code, even though moving its transform takes three krilla pushes. + +use std::ops::{Deref, DerefMut}; + +use craft_pdf::write::backend as krilla; +use krilla::blend::BlendMode; +use krilla::geom::{Path, Transform}; +use krilla::mask::Mask; +use krilla::num::NormalizedF32; +use krilla::paint::FillRule; +use vectorcraft_geom::Affine; + +pub(crate) fn xf(a: Affine) -> Transform { + let c = a.as_coeffs(); + Transform::from_row(c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32, c[4] as f32, c[5] as f32) +} + +pub(crate) fn affine(t: Transform) -> Affine { + Affine::new([t.sx(), t.ky(), t.kx(), t.sy(), t.tx(), t.ty()].map(f64::from)) +} + +struct Push { + count: usize, + root: Affine, +} + +/// A drawing surface whose form groups keep gradients and masks in the same page space. +pub(crate) struct Surface<'a> { + inner: krilla::surface::Surface<'a>, + root: Affine, + pushes: Vec, +} + +impl<'a> Surface<'a> { + /// Wrap a page while recording the writer's implicit Y flip outside its reported CTM. + pub fn page(inner: krilla::surface::Surface<'a>, height: f32) -> Self { + Self { inner, root: Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, height.into()]), pushes: vec![] } + } + + /// Wrap a form or pattern stream, which starts without a page's implicit Y flip. + pub fn stream(inner: krilla::surface::Surface<'a>) -> Self { + Self { inner, root: Affine::IDENTITY, pushes: vec![] } + } + + /// Current drawing space → page space, for both a form's art and its mask. A singular + /// enclosing transform draws no area: keep that form local rather than trying to invert it. + pub fn group_transform(&self) -> Transform { + let t = xf(self.root * affine(self.inner.ctm())); + if t.invert().is_some() { t } else { Transform::identity() } + } + + /// Move the enclosing transform inside a form and record its three pushes as one group. + fn group(&mut self, push: impl FnOnce(&mut krilla::surface::Surface)) { + let t = self.group_transform(); + self.inner.push_transform(&t.invert().unwrap_or_default()); + push(&mut self.inner); + self.inner.push_transform(&t); + self.pushes.push(Push { count: 3, root: self.root }); + self.root = Affine::IDENTITY; + } + + /// Apply opacity in page space when it creates a form; full opacity is a plain push. + pub fn push_opacity(&mut self, opacity: NormalizedF32) { + if opacity == NormalizedF32::ONE { + // krilla does not create a form for full opacity. + self.inner.push_opacity(opacity); + self.plain_push(); + } else { + self.group(|s| s.push_opacity(opacity)); + } + } + + pub fn push_isolated(&mut self) { + self.group(|s| s.push_isolated()); + } + + /// The mask's stream is already in [`Self::group_transform`]'s space, like the group's art. + pub fn push_mask(&mut self, mask: Mask) { + self.group(|s| s.push_mask(mask)); + } + + fn plain_push(&mut self) { + self.pushes.push(Push { count: 1, root: self.root }); + } + + pub fn push_transform(&mut self, transform: &Transform) { + self.inner.push_transform(transform); + self.plain_push(); + } + + pub fn push_clip_path(&mut self, path: &Path, rule: &FillRule) { + self.inner.push_clip_path(path, rule); + self.plain_push(); + } + + pub fn push_blend_mode(&mut self, mode: BlendMode) { + self.inner.push_blend_mode(mode); + self.plain_push(); + } + + /// Restore the enclosing coordinate space, undoing every writer push for the last group. + /// An unmatched pop is logged rather than forwarded to the writer's stack. + pub fn pop(&mut self) { + let Some(push) = self.pushes.pop() else { + log::error!("PDF surface pop without a matching push"); + return; + }; + for _ in 0..push.count { + self.inner.pop(); + } + self.root = push.root; + } + + pub fn finish(self) { + self.inner.finish(); + } +} + +// Drawing operations use krilla directly; every push/pop above keeps our coordinate state in +// step. Stream builders are wrapped with `Surface::stream` when their surfaces are created. +impl<'a> Deref for Surface<'a> { + type Target = krilla::surface::Surface<'a>; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl DerefMut for Surface<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } +} diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index eb9a4d2846..365b653890 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -8,6 +8,7 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, shapes}; use crate::*; +mod actual_text; mod blend; mod charstroke; mod cmykblend; @@ -748,7 +749,7 @@ fn an_image_whose_pixels_cant_be_decoded_is_left_out_with_one_note() { } /// #2023: a group's Transform effect copies an image among its members as it does the paths: the -/// PDF draws the image three times, where the effect put it. +/// PDF draws the image three times, where the effect put it, the original on top. #[test] fn a_group_transform_effect_exports_its_image_copies() { let mut d = doc(200.0, 100.0); @@ -775,7 +776,7 @@ fn a_group_transform_effect_exports_its_image_copies() { let out = roundtrip(&d); let lefts: Vec = leaves(&out).iter().filter(|n| matches!(n.kind, NodeKind::Image(_))).filter_map(|n| n.geometric_bounds()).map(|b| b.x0.round()).collect(); - assert_eq!(lefts, [20.0, 70.0, 120.0]); + assert_eq!(lefts, [120.0, 70.0, 20.0]); } /// Build a PDF with a correct xref table from object bodies. diff --git a/crates/pdf/src/tests/actual_text.rs b/crates/pdf/src/tests/actual_text.rs new file mode 100644 index 0000000000..8e6bd4810b --- /dev/null +++ b/crates/pdf/src/tests/actual_text.rs @@ -0,0 +1,309 @@ +//! Original, synthetic PDF content; no external fonts needed for semantic coverage. + +use crate::{ImportOptions, ImportReport, TextAs, import_with_report}; +use vectorcraft_doc::{NodeKind, TextObject}; + +fn stream(entries: &str, content: &[u8]) -> Vec { + let mut bytes = format!("<< /Length {} {entries} >>\nstream\n", content.len()).into_bytes(); + bytes.extend_from_slice(content); + bytes.extend_from_slice(b"\nendstream"); + bytes +} + +fn document(objects: &[Vec]) -> Vec { + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = vec![0]; + for (i, object) in objects.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend(format!("{} 0 obj\n", i + 1).bytes()); + bytes.extend_from_slice(object); + bytes.extend_from_slice(b"\nendobj\n"); + } + let xref = bytes.len(); + bytes.extend(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len()).bytes()); + for offset in offsets.iter().skip(1) { + bytes.extend(format!("{offset:010} 00000 n \n").bytes()); + } + bytes.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len()).bytes()); + bytes +} + +fn pdf(pages: &[&str]) -> Vec { + let kids = (0..pages.len()).map(|i| format!("{} 0 R", 4 + i * 2)).collect::>().join(" "); + let mut objects = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + format!("<< /Type /Pages /Kids [{kids}] /Count {} >>", pages.len()).into_bytes(), + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), + ]; + for (i, content) in pages.iter().enumerate() { + objects.push(format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Resources << /Font << /F 3 0 R >> /Properties << /Named << /ActualText (Named) >> >> >> /Contents {} 0 R >>", 5 + i * 2).into_bytes()); + objects.push(stream("", format!("BT /F 20 Tf 1 0 0 1 20 700 Tm {content} ET").as_bytes())); + } + document(&objects) +} + +fn open(content: &str) -> ImportReport { + import_with_report(&pdf(&[content]), &ImportOptions::default()).unwrap() +} + +// Geometry assertions need the PDF and layout to use the same widths. Unembedded +// Helvetica is not installed on every platform; missing-font layout fits the overall +// line length, so removing characters changes even an ordinary suffix's position. +fn open_positioned(content: &str) -> ImportReport { + let data = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); + let face = vectorcraft_text::FontDb::global().find_postscript("SourceSans3-Regular").unwrap(); + assert_eq!(face.file_data(), data); + let widths = (32u8..=126) + .map(|c| { + let glyph = face.glyph_for(char::from(c)); + assert_ne!(glyph, 0); + (face.advance(glyph) * 1000.0 / face.units_per_em()).to_string() + }) + .collect::>() + .join(" "); + let font = format!( + "<< /Type /Font /Subtype /TrueType /BaseFont /SourceSans3-Regular /Encoding /WinAnsiEncoding /FontDescriptor 6 0 R /FirstChar 32 /LastChar 126 /Widths [{widths}] >>" + ); + let descriptor = b"<< /Type /FontDescriptor /FontName /SourceSans3-Regular /Flags 32 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 1000 /Descent -300 /CapHeight 700 /StemV 80 /FontFile2 7 0 R >>".to_vec(); + let bytes = custom_pdf(content, font.as_bytes(), "", &[descriptor, stream("", data)]); + import_with_report(&bytes, &ImportOptions::default()).unwrap() +} + +fn texts(report: &ImportReport) -> Vec { + let mut result = vec![]; + report.document.walk(|node| { + if let NodeKind::Text(text) = &node.kind { + result.push((**text).clone()); + } + }); + result +} + +fn plain(report: &ImportReport) -> String { + texts(report).iter().map(TextObject::plain_text).collect() +} + +fn utf16(text: &str) -> String { + format!("", text.encode_utf16().map(|u| format!("{u:04X}")).collect::()) +} + +fn character_origin(report: &ImportReport, character: char) -> kurbo::Point { + for text in texts(report) { + let plain = text.plain_text(); + if let Some(byte) = plain.find(character) { + let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text); + let glyph = layout.glyphs.iter().find(|g| g.byte == byte).unwrap(); + return text.xf * glyph.origin; + } + } + panic!("missing {character}"); +} + +#[test] +fn actual_text_replaces_once_and_keeps_suffix_position() { + let replaced = open_positioned("/Span << /ActualText (AB) >> BDC (xy) Tj EMC (C) Tj"); + let ordinary = open_positioned("(xyC) Tj"); + assert_eq!(plain(&replaced), "ABC"); + let delta = character_origin(&replaced, 'C') - character_origin(&ordinary, 'C'); + assert!(delta.hypot() < 0.05, "suffix moved: {delta:?}"); +} + +#[test] +fn actual_text_empty_and_nested_owners() { + for (content, expected) in [ + ("(P) Tj /Span << /ActualText () >> BDC (xy) Tj EMC (C) Tj", "PC"), + ("/Span << /ActualText (AB) >> BDC /Span << /ActualText (INNER) >> BDC (x) Tj EMC (y) Tj EMC (C) Tj", "ABC"), + ("/Span << /ActualText () >> BDC /Span << /ActualText (INNER) >> BDC (xy) Tj EMC EMC (C) Tj", "C"), + ("/Span BMC /Span << /ActualText (AB) >> BDC (xy) Tj EMC EMC (C) Tj", "ABC"), + ("/Span << /ActualText (A) >> BDC (x) Tj EMC /Span << /ActualText (B) >> BDC (y) Tj EMC (C) Tj", "ABC"), + ] { + assert_eq!(plain(&open(content)), expected, "{content}"); + } +} + +#[test] +fn actual_text_decodes_pdf_strings_and_preserves_authored_order() { + for (encoded, expected) in [ + (utf16("ل\u{200d}ا\u{200c}ب"), "ل\u{200d}ا\u{200c}ب"), + ("<8093A0>".into(), "•fi€"), + ("".into(), "Ab"), + ("( A )".into(), " A "), + ("( )".into(), " "), + (utf16("A\nB"), "A\nB"), + ] { + assert_eq!(plain(&open(&format!("/Span << /ActualText {encoded} >> BDC (xy) Tj EMC"))), expected); + } + assert_eq!(plain(&open("/Span /Named BDC (xy) Tj EMC")), "Named"); +} + +#[test] +fn actual_text_across_operations_styles_and_line_flushes() { + let report = open_positioned("/Span << /ActualText (AB) >> BDC (x) Tj [(y) -400 (z)] TJ 1 0 0 rg /F 24 Tf (w) Tj EMC (C) Tj"); + assert_eq!(plain(&report), "ABC"); + let report = open_positioned("/Span << /ActualText (AB) >> BDC (x) Tj 0 -40 Td (y) Tj EMC (C) Tj"); + assert_eq!(plain(&report), "ABC"); + let ordinary = open_positioned("(x) Tj 0 -40 Td (yC) Tj"); + assert!((character_origin(&report, 'C') - character_origin(&ordinary, 'C')).hypot() < 0.05); + // The replacement belongs to the first placed glyph's style and line. + assert_eq!(texts(&report)[0].plain_text(), "AB"); +} + +#[test] +fn actual_text_fill_and_stroke_is_not_duplicated() { + let report = open("2 Tr /Span << /ActualText (AB) >> BDC [(xy) 0 (zw)] TJ EMC (C) Tj"); + assert_eq!(plain(&report), "ABC"); + assert!(texts(&report).iter().flat_map(|t| &t.runs).all(|r| r.style.has_stroke())); +} + +#[test] +fn actual_text_page_reset_and_unbalanced_end() { + let bytes = pdf(&["/Span << /ActualText (AB) >> BDC (xy) Tj", "EMC (C) Tj"]); + let report = import_with_report(&bytes, &ImportOptions::default()).unwrap(); + assert_eq!(plain(&report), "ABC"); +} + +#[test] +fn actual_text_outlines_are_unchanged() { + let outline = |content| { + let report = import_with_report(&pdf(&[content]), &ImportOptions { text_as: TextAs::Outlines, ..Default::default() }).unwrap(); + assert!(texts(&report).is_empty()); + let mut paths = vec![]; + report.document.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + paths.push(path.to_bezpath()); + } + }); + paths + }; + assert_eq!(outline("/Span << /ActualText (AB) >> BDC (xy) Tj EMC"), outline("(xy) Tj")); +} + +#[test] +fn actual_text_bounded_replacements_recover_siblings() { + let oversized = "A".repeat(64 * 1024 + 1); + let report = open(&format!("/Span << /ActualText ({oversized}) >> BDC (x) Tj EMC /Span << /ActualText (B) >> BDC (y) Tj EMC")); + assert_eq!(plain(&report), "xB"); + assert!(report.warnings.iter().any(|w| w.contains("ActualText beyond"))); + let deep = format!( + "{} /Span << /ActualText (ignored) >> BDC (x) Tj EMC {} /Span << /ActualText (B) >> BDC (y) Tj EMC", + "/Span BMC ".repeat(128), + "EMC ".repeat(128) + ); + assert_eq!(plain(&open(&deep)), "xB"); +} + +#[test] +fn actual_text_survives_reader_windows() { + let content = format!("/Span << /ActualText (AB) >> BDC (x) Tj {} (y) Tj EMC (C) Tj", "q Q ".repeat(20_000)); + assert_eq!(plain(&open(&content)), "ABC"); +} + +fn custom_pdf(content: &str, font: &[u8], resources: &str, extra: &[Vec]) -> Vec { + let mut objects = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_vec(), + font.to_vec(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Resources << /Font << /F 3 0 R >> {resources} >> /Contents 5 0 R >>") + .into_bytes(), + stream("", format!("BT /F 20 Tf 1 0 0 1 20 700 Tm {content} ET").as_bytes()), + ]; + objects.extend_from_slice(extra); + document(&objects) +} + +#[test] +fn actual_text_mixed_line_still_reconstructs_ordinary_rtl() { + let map = stream("", b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapType 2 def 1 begincodespacerange <00> endcodespacerange 4 beginbfchar <78> <05DD> <79> <05D5> <7A> <05DC> <77> <05E9> endbfchar endcmap end end"); + let content = format!("(xyzw) Tj /Span << /ActualText {} >> BDC (xy) Tj EMC (xyzw) Tj", utf16("ل\u{200d}ا")); + let bytes = custom_pdf(&content, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /ToUnicode 6 0 R >>", "", &[map]); + let report = import_with_report(&bytes, &ImportOptions::default()).unwrap(); + assert_eq!(texts(&report).len(), 1); + assert_eq!(plain(&report), "שלוםل\u{200d}اשלום"); +} + +#[test] +fn actual_text_rescues_a_glyph_without_unicode() { + // Identity-H with no ToUnicode or embedded font: CID 65535 has no character mapping. + let font = b"<< /Type /Font /Subtype /Type0 /BaseFont /Unmapped /Encoding /Identity-H /DescendantFonts [6 0 R] >>"; + let descendant = b"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /Unmapped /CIDSystemInfo << /Registry (Unknown) /Ordering (Identity) /Supplement 0 >> /FontDescriptor 7 0 R /DW 500 >>".to_vec(); + let descriptor = b"<< /Type /FontDescriptor /FontName /Unmapped /Flags 4 /FontBBox [0 0 1000 1000] /ItalicAngle 0 /Ascent 800 /Descent -200 /CapHeight 700 /StemV 80 >>".to_vec(); + let extra = [descendant, descriptor]; + let import = |content| import_with_report(&custom_pdf(content, font, "", &extra), &ImportOptions::default()).unwrap(); + assert!(plain(&import("3 Tr Tj")).is_empty(), "the fixture really has no usable mapping"); + assert_eq!(plain(&import("3 Tr /Span << /ActualText (AB) >> BDC Tj EMC")), "AB"); +} + +#[test] +fn actual_text_matches_embedded_glyph_identity_not_replacement() { + let font = b"<< /Type /Font /Subtype /TrueType /BaseFont /SourceSans3-Regular /Encoding /WinAnsiEncoding /FontDescriptor 6 0 R /FirstChar 120 /LastChar 121 /Widths [500 500] >>"; + let descriptor = b"<< /Type /FontDescriptor /FontName /SourceSans3-Regular /Flags 32 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 1000 /Descent -300 /CapHeight 700 /StemV 80 /FontFile2 7 0 R >>".to_vec(); + let data = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); + let bytes = custom_pdf("/Span << /ActualText (AB) >> BDC (xy) Tj EMC", font, "", &[descriptor, stream("", data)]); + let report = import_with_report(&bytes, &ImportOptions::default()).unwrap(); + assert_eq!(plain(&report), "AB"); + assert!(!report.warnings.iter().any(|w| w.contains("differ from the installed font")), "{:?}", report.warnings); +} + +#[test] +fn actual_text_nested_mask_interpretation_does_not_consume_page_owner() { + let mask = stream( + "/Type /XObject /Subtype /Form /BBox [0 0 600 800] /Group << /S /Transparency /CS /DeviceGray >> /Resources << /Font << /F 3 0 R >> >>", + b"/Span << /ActualText (MASK) >> BDC BT /F 20 Tf 1 0 0 1 20 700 Tm (mask) Tj ET EMC 1 g 0 0 600 800 re f", + ); + let bytes = custom_pdf( + "/Span << /ActualText (AB) >> BDC /Mask gs (xy) Tj EMC", + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + "/ExtGState << /Mask << /SMask << /S /Luminosity /G 6 0 R >> >> >>", + &[mask], + ); + let report = import_with_report(&bytes, &ImportOptions::default()).unwrap(); + assert_eq!(plain(&report), "AB"); +} + +#[test] +fn actual_text_empty_span_keeps_following_position_without_slots() { + for (content, baseline) in [ + ("(P) Tj /Span << /ActualText () >> BDC (xy) Tj EMC (CD) Tj", "(PxyCD) Tj"), + ("/Span << /ActualText () >> BDC (xy) Tj EMC (CD) Tj", "(xyCD) Tj"), + ] { + let report = open_positioned(content); + let ordinary = open_positioned(baseline); + assert_eq!(plain(&report), if content.starts_with("(P)") { "PCD" } else { "CD" }); + for c in ['C', 'D'] { + assert!((character_origin(&report, c) - character_origin(&ordinary, c)).hypot() < 0.05, "{content}: {c}"); + } + } +} + +#[test] +fn actual_text_waits_for_a_placeable_glyph() { + let report = open("/Span << /ActualText (AB) >> BDC -1 0 0 1 20 700 Tm (x) Tj 1 0 0 1 20 660 Tm (y) Tj EMC (C) Tj"); + assert_eq!(plain(&report), "ABC"); +} + +#[test] +fn actual_text_stroke_does_not_restyle_ordinary_prefix() { + let report = open("(P) Tj 2 Tr /Span << /ActualText (AB) >> BDC (xyzw) Tj EMC"); + assert_eq!(plain(&report), "PAB"); + for text in texts(&report) { + for run in text.runs { + assert_eq!(run.style.has_stroke(), !run.text.contains('P'), "{:?}", run.text); + } + } +} + +#[test] +fn actual_text_vertical_column_keeps_replacement_once() { + let font = b"<< /Type /Font /Subtype /Type0 /BaseFont /Vertical /Encoding /Identity-V /DescendantFonts [6 0 R] /ToUnicode 8 0 R >>"; + let descendant = b"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /Vertical /CIDSystemInfo << /Registry (Unknown) /Ordering (Identity) /Supplement 0 >> /FontDescriptor 7 0 R /DW 500 /DW2 [880 -1000] >>".to_vec(); + let descriptor = b"<< /Type /FontDescriptor /FontName /Vertical /Flags 4 /FontBBox [0 0 1000 1000] /ItalicAngle 0 /Ascent 800 /Descent -200 /CapHeight 700 /StemV 80 >>".to_vec(); + let map = stream("", b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange 3 beginbfchar <0001> <0078> <0002> <0079> <0003> <0043> endbfchar endcmap end end"); + let extra = [descendant, descriptor, map]; + for (replacement, expected) in [("AB", "ABC"), ("", "C")] { + let content = format!("/Span << /ActualText ({replacement}) >> BDC <00010002> Tj EMC <0003> Tj"); + let bytes = custom_pdf(&content, font, "", &extra); + let report = import_with_report(&bytes, &ImportOptions::default()).unwrap(); + assert_eq!(plain(&report), expected); + assert!(texts(&report).iter().all(|text| text.vertical)); + } +} diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 2e4469dbb0..97388ea313 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -432,3 +432,64 @@ fn a_separation_image_that_cant_be_read_stays_rgb() { assert!(r.document.swatches.iter().all(|s| !s.spot), "no swatch for an ink nothing uses"); assert_eq!(r.warnings.iter().filter(|w| w.contains("spot ink")).count(), 1, "{:?}", r.warnings); } + +/// A Type 4 tint transform as an object, `code` its program. +fn type4(code: &str, inputs: usize) -> String { + let domain = "0 1 ".repeat(inputs); + format!("<< /FunctionType 4 /Domain [{}] /Range [0 1 0 1 0 1 0 1] /Length {} >>\nstream\n{code}\nendstream", domain.trim_end(), code.len()) +} + +/// The imported images' blobs, in paint order. +fn image_blobs(d: &Document) -> Vec<(ImageBlob, bool)> { + let mut out = vec![]; + for l in &d.layers { + l.walk(&mut |n| { + if let NodeKind::Image(im) = &n.kind { + out.push((d.images[&im.key].clone(), n.extras().colorize.is_some())); + } + }); + } + out +} + +/// A DeviceN image of one colorant opens as a Separation image does: its tints, colorized by the ink. +#[test] +fn a_devicen_image_of_one_ink_opens_colorized_by_it() { + let space = "[/DeviceN [/SpotRed] /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 1 0] /N 1 >>]"; + let d = separation_page(space, 4, 8, "", "0055AAFF", &[]); + let images = imported_images(&d); + assert_eq!(images.len(), 1); + assert_eq!(images[0].1, [255, 170, 85, 0]); + assert!(matches!(&images[0].0, Some(Paint::Solid { swatch: Some(s), .. }) if s == "SpotRed"), "{:?}", images[0].0); +} + +/// A DeviceN image of process plates only opens in CMYK, each colorant's tint in its plate. +#[test] +fn a_devicen_image_of_process_plates_opens_in_cmyk() { + let space = format!("[/DeviceN [/Cyan /Magenta] /DeviceCMYK {} 0 R]", first_extra(1) + 1); + // Cyan and Magenta → (c, m, 0, 0); pixels: none, cyan, magenta, both. + let d = separation_page(&space, 4, 8, "", "0000FF0000FFFFFF", &[&type4("{ 0 0 }", 2)]); + let blobs = image_blobs(&d); + assert_eq!(blobs.len(), 1); + let (blob, colorized) = &blobs[0]; + assert!(blob.is_cmyk() && !colorized, "a CMYK image"); + let inks = blob.cmyk().unwrap().data; + assert_eq!(inks, [0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255, 255, 0, 0]); + + // 16 bits a sample, the ink None among the plates, and a Decode array that inverts Cyan. + let space = format!("[/DeviceN [/Cyan /None /Black] /DeviceCMYK {} 0 R]", first_extra(1) + 1); + let d = separation_page(&space, 2, 16, "/Decode [1 0 0 1 0 1]", "FFFF0000000000000000FFFF", &[&type4("{ exch pop 0 0 3 -1 roll }", 3)]); + let blobs = image_blobs(&d); + assert_eq!(blobs[0].0.cmyk().unwrap().data, [0, 0, 0, 0, 255, 0, 0, 255]); +} + +/// A DeviceN image of a spot ink and a process plate (a duotone) still opens as RGB: an image can +/// hold one ink or the process plates, not both. +#[test] +fn a_duotone_devicen_image_still_opens_as_rgb() { + let space = format!("[/DeviceN [/Black /SpotRed] /DeviceCMYK {} 0 R]", first_extra(1) + 1); + let d = separation_page(&space, 2, 8, "", "FF0000FF", &[&type4("{ dup 3 -1 roll 0 4 1 roll }", 2)]); + let blobs = image_blobs(&d); + assert_eq!(blobs.len(), 1); + assert!(!blobs[0].0.is_cmyk() && !blobs[0].1, "RGB, not colorized"); +} diff --git a/crates/pdf/src/tests/live_text.rs b/crates/pdf/src/tests/live_text.rs index 4cb4417bc0..bddeb758d2 100644 --- a/crates/pdf/src/tests/live_text.rs +++ b/crates/pdf/src/tests/live_text.rs @@ -477,3 +477,43 @@ fn hebrew_comes_back_in_logical_order() { assert_eq!(shown(&t[0]), shown(&original), "{text}"); } } + +/// The text objects a PDF of `text` set in `face` imports as. +fn imported_texts(face: &vectorcraft_text::FontFace, text: &str) -> Vec { + let mut pdf = krilla::Document::new(); + let mut page = pdf.start_page_with(PageSettings::from_wh(300.0, 200.0).unwrap()); + let mut s = page.surface(); + let font = Font::new(face.file_data().to_vec().into(), face.face_index()).unwrap(); + s.draw_text(KPoint::from_xy(20.0, 50.0), font, 24.0, text, false, TextDirection::Auto); + s.finish(); + page.finish(); + let r = import_with_report(&pdf.finish().unwrap(), &ImportOptions::default()).unwrap(); + texts(&r.document).iter().map(|t| t.plain_text()).collect() +} + +#[test] +fn arabic_ligatures_keep_their_letters_in_order() { + // A lam-alef ligature is one glyph whose text is lam then alef: it must not be turned round + // with the line it sits in (#6072). + let db = vectorcraft_text::FontDb::global(); + let preferred = ["DejaVu Sans", "Arial", "Times New Roman", "Noto Sans Arabic", "Noto Naskh Arabic"].map(String::from); + // Whether `face` draws lam-alef as one glyph, the ligature the fix is about. + let ligates = |face: &vectorcraft_text::FontFace| { + let style = vectorcraft_doc::CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), ..Default::default() }; + let t = TextObject::point(kurbo::Point::ORIGIN, "لا", style); + vectorcraft_text::layout(db, &t).glyphs.len() == 1 + }; + // An installed Arabic font with a lam-alef ligature whose glyphs come back as live type. + let Some(face) = preferred + .iter() + .chain(&db.families()) + .filter_map(|f| db.face(f, "Regular")) + .filter(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f)) + .find(|f| !imported_texts(f, "بب").is_empty()) + else { + return; // No such font on this host. + }; + for text in ["لا", "بلال", "السلام عليكم", "لا إله إلا الله"] { + assert_eq!(imported_texts(&face, text), [text], "in {}", face.family); + } +} diff --git a/crates/pdf/src/tests/marks.rs b/crates/pdf/src/tests/marks.rs index e4df914a14..19031505d3 100644 --- a/crates/pdf/src/tests/marks.rs +++ b/crates/pdf/src/tests/marks.rs @@ -133,13 +133,291 @@ fn a_page_past_14400_pt_is_written_with_a_user_unit_and_reads_back_at_its_size() assert!(near(back.artboards[0].rect, Rect::new(0.0, 0.0, 20_000.0, 10_000.0)), "{:?}", back.artboards[0].rect); let red = painted(&back, |p| rgb(p, [255, 0, 0])); assert!(red.len() == 1 && near(red[0], Rect::new(-5.0, 10.0, 40.0, 50.0)), "{red:?}"); - // PDF 1.5 and PDF/X-4 files have the page in points, past 14,400. - for v in [json!({"compatibility": "1.5"}), json!({"standard": "pdfX4", "compatibility": "1.6"})] { + // PDF/X-4 files have the page in points, past 14,400. + for v in [json!({"standard": "pdfX4", "compatibility": "1.5"}), json!({"standard": "pdfX4", "compatibility": "1.6"})] { let pages = units_and_media(&pdf(&d, v.clone())); assert_eq!(pages[0], (1.0, Rect::new(0.0, 0.0, 20_000.0, 10_000.0)), "{v}"); } } +/// 20 m in points. +const TWENTY_M: f64 = 20.0 / 0.0254 * 72.0; + +/// [`doc`] with its artboard `w` × `h` points large. +fn sized(w: f64, h: f64) -> Document { + let mut d = doc(); + d.artboards[0].rect = Rect::new(0.0, 0.0, w, h); + d +} + +/// The export of `d` with `set`. +fn report(d: &Document, set: PdfSettings) -> Result { + export_with_report(d, &PdfOptions { settings: set, created: Some(1_791_200_000), ..PdfOptions::uncompressed() }) +} + +/// The numbers that follow `key` in the file's bytes (`/MediaBox [0 0 w h]`, `/UserUnit u`), read +/// as text, without the PDF reader: none when the file has no `key`. +fn raw_numbers(bytes: &[u8], key: &str, count: usize) -> Vec { + let text = String::from_utf8_lossy(bytes); + let Some(at) = text.find(key) else { return vec![] }; + let words = text[at + key.len()..].split(|c: char| c.is_whitespace() || matches!(c, '[' | ']' | '/' | '>')).filter(|w| !w.is_empty()); + words.take(count).map(|w| w.parse().unwrap_or(f64::NAN)).collect() +} + +/// The page's width and height in meters as the file's bytes give them: its media box times its +/// `UserUnit` (1 without one). +fn raw_meters(bytes: &[u8]) -> (f64, f64) { + let media = raw_numbers(bytes, "/MediaBox", 4); + let unit = raw_numbers(bytes, "/UserUnit", 1).first().copied().unwrap_or(1.0); + let m = |v: f64| v * unit / 72.0 * 0.0254; + (m(media[2] - media[0]), m(media[3] - media[1])) +} + +/// The warnings about pages longer than 14,400 pt. +fn long_page_warnings(r: &ExportReport) -> Vec<&String> { + r.warnings.iter().filter(|w| w.contains("page limit of 14,400 pt")).collect() +} + +/// A 20 m page at PDF 1.7 (the default) is written with a `UserUnit` of 3.938, reads back at 20 m +/// from the file's bytes, through the PDF reader and through the import, and the export says how +/// it is written. +#[test] +fn a_20_m_page_keeps_its_size_with_a_user_unit_and_the_export_says_so() { + let d = sized(TWENTY_M, TWENTY_M / 20.0); + let r = report(&d, PdfSettings::default()).unwrap(); + assert!(r.bytes.starts_with(b"%PDF-1.7")); + assert_eq!( + long_page_warnings(&r), + [ + "the page of artboard 1 is 56693 × 2835 pt (20.00 × 1.00 m), longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of 3.938, so apps that ignore UserUnit show it that many times smaller" + ], + "{:?}", + r.warnings + ); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.938]); + let (w, h) = raw_meters(&r.bytes); + assert!((w - 20.0).abs() < 0.001 && (h - 1.0).abs() < 0.001, "{w} × {h} m"); + let pages = units_and_media(&r.bytes); + assert_eq!(pages[0].0, 3.938); + assert!(pages[0].1.width() <= 14_400.0, "{pages:?}"); + let page = &info(&r.bytes, None).unwrap().pages[0]; + assert!((page.width - TWENTY_M).abs() < 0.01, "{page:?}"); + let back = import(&r.bytes).unwrap(); + assert!((back.artboards[0].rect.width() - TWENTY_M).abs() < 0.01, "{:?}", back.artboards[0].rect); +} + +/// Every built-in preset and every PDF version keeps a 20 m page at its size, or refuses it with +/// the reason: PDF 1.3 and 1.4 files (PDF/X-1a and PDF/X-3 among them) have no `UserUnit` and +/// hold no real number past 32,767, PDF 1.5 is written as PDF 1.6 to have one, and PDF/X-4 pages +/// at PDF 1.5 or 1.6 stay in points with a warning. +#[test] +fn every_preset_and_version_keeps_a_20_m_page_or_says_why_not() { + let d = sized(TWENTY_M, TWENTY_M / 20.0); + let refused = |e: PdfError, label: &str| { + assert_eq!( + e.to_string(), + format!( + "invalid PDF setting: {label} files hold real numbers up to 32,767, and the page of artboard 1, 56693 pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard" + ) + ); + }; + for preset in crate::builtin_presets() { + let name = preset.name.as_str(); + match report(&d, preset.settings.clone()) { + Err(e) if matches!(name, "PDF/X-1a:2001" | "PDF/X-3:2002") => refused(e, name), + Err(e) => panic!("{name}: {e}"), + Ok(r) if name == "PDF/X-4:2010" => { + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new(), "{name}"); + assert!((raw_meters(&r.bytes).0 - 20.0).abs() < 0.001, "{name}"); + let w = long_page_warnings(&r); + let points = "PDF/X-4:2010 pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in"; + assert!(w.len() == 1 && w[0].ends_with(points), "{w:?}"); + } + Ok(r) => { + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.938], "{name}"); + assert!((raw_meters(&r.bytes).0 - 20.0).abs() < 0.001, "{name}"); + assert_eq!(long_page_warnings(&r).len(), 1, "{name}: {:?}", r.warnings); + } + } + } + for c in Compatibility::ALL.iter().copied() { + let set = PdfSettings { compatibility: c, ..PdfSettings::default() }; + match (c, report(&d, set)) { + (Compatibility::Pdf13 | Compatibility::Pdf14, Err(e)) => refused(e, c.label()), + (Compatibility::Pdf13 | Compatibility::Pdf14, Ok(_)) => panic!("{} is refused", c.label()), + (_, Err(e)) => panic!("{}: {e}", c.label()), + (_, Ok(r)) => { + let header = if c == Compatibility::Pdf15 { "1.6" } else { c.id() }; + assert!(r.bytes.starts_with(format!("%PDF-{header}").as_bytes()), "{}", c.label()); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.938], "{}", c.label()); + assert!((raw_meters(&r.bytes).0 - 20.0).abs() < 0.001, "{}", c.label()); + let raised = r.warnings.iter().any(|w| w.starts_with("PDF 1.5 has no UserUnit") && w.ends_with("the file is written as PDF 1.6")); + assert_eq!(raised, c == Compatibility::Pdf15, "{}: {:?}", c.label(), r.warnings); + } + } + } + // PDF/X-4 and PDF/A-2b files at PDF 1.4 have no `UserUnit` either. + let at_14 = |standard| report(&d, PdfSettings { standard, compatibility: Compatibility::Pdf14, ..PdfSettings::default() }); + refused(at_14(Standard::PdfX4).err().unwrap(), "PDF 1.4"); + refused(at_14(Standard::PdfA2b).err().unwrap(), "PDF 1.4"); +} + +/// A page from 14,400 to 32,767 pt long is written in points, with the warning, in PDF 1.3 and 1.4 +/// files, PDF/X-1a, PDF/X-3, PDF/X-4 and PDF/A-2b files among them, as before the warning. Past +/// 32,767 pt a page of whole points is written too, as the writer puts whole numbers as integers; +/// a side that isn't a whole number, or art that needs a real number past 32,767, gets the error. +#[test] +fn pdf_1_4_writes_a_page_up_to_32767_pt_in_points() { + let presets = crate::builtin_presets(); + let preset = |name: &str| presets.iter().find(|p| p.name == name).unwrap().settings.clone(); + let sets = [ + ("PDF 1.3", PdfSettings { compatibility: Compatibility::Pdf13, ..PdfSettings::default() }), + ("PDF 1.4", PdfSettings { compatibility: Compatibility::Pdf14, ..PdfSettings::default() }), + ("PDF/X-1a:2001", preset("PDF/X-1a:2001")), + ("PDF/X-3:2002", preset("PDF/X-3:2002")), + ("PDF/X-4:2010", PdfSettings { standard: Standard::PdfX4, compatibility: Compatibility::Pdf14, ..PdfSettings::default() }), + ("PDF/A-2b", PdfSettings { standard: Standard::PdfA2b, compatibility: Compatibility::Pdf14, ..PdfSettings::default() }), + ]; + for (label, set) in &sets { + for side in [17_000.0, 32_767.0, 40_000.0] { + let r = report(&sized(side, 300.0), set.clone()).unwrap_or_else(|e| panic!("{label} at {side}: {e}")); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new(), "{label}"); + assert_eq!(raw_numbers(&r.bytes, "/MediaBox", 4), [0.0, 0.0, side, 300.0], "{label}"); + let w = long_page_warnings(&r); + let points = format!("{label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in"); + assert!(w.len() == 1 && w[0].ends_with(&points), "{label}: {w:?}"); + } + // For PDF/X-4 and PDF/A-2b files the error names the PDF version. + let label = if matches!(*label, "PDF/X-4:2010" | "PDF/A-2b") { "PDF 1.4" } else { label }; + let refused = |e: PdfError, side: &str| { + let refusal = format!("{label} files hold real numbers up to 32,767, and the page of artboard 1, {side} pt long, needs larger ones"); + assert!(e.to_string().contains(&refusal), "{e}"); + }; + refused(report(&sized(32_767.5, 300.0), set.clone()).err().unwrap(), "32768"); + // Art at a coordinate that isn't a whole number past 32,767. + let mut d = sized(40_000.0, 300.0); + let layer = d.default_layer().unwrap(); + let id = d.alloc_id(); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.insert(Some(layer), 0, Node::path(id, shapes::rectangle(Rect::new(35_000.5, 10.0, 35_100.25, 50.0)), red)).unwrap(); + refused(report(&d, set.clone()).err().unwrap(), "40000"); + } +} + +/// With several pages past 32,767 pt in a PDF 1.4 file, the error names the page whose art needs a +/// real number past 32,767, not the first long page. +#[test] +fn the_error_names_the_long_page_whose_art_needs_a_larger_real() { + let mut d = sized(40_000.0, 300.0); + let mut second = d.artboards[0].clone(); + second.rect = Rect::new(0.0, 10_000.0, 40_000.0, 10_300.0); + d.artboards.push(second); + let layer = d.default_layer().unwrap(); + let id = d.alloc_id(); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.insert(Some(layer), 0, Node::path(id, shapes::rectangle(Rect::new(35_000.5, 10_010.0, 35_100.25, 10_050.0)), red)).unwrap(); + let set = PdfSettings { compatibility: Compatibility::Pdf14, ..PdfSettings::default() }; + let e = report(&d, set).err().unwrap(); + assert!(e.to_string().contains("the page of artboard 2, 40000 pt long, needs larger ones"), "{e}"); +} + +/// A long page whose short side would be under 3 units at the `UserUnit` its long side needs +/// (ISO 32000-1, Annex C.2; PDF/A-2b's 6.1.13) is written with a smaller unit that keeps the +/// short side at 3 units, and a warning; 100 m × 4 mm is one. A short side under 3 pt is under 3 +/// units at any unit, and keeps the unit its long side needs. +#[test] +fn a_page_too_narrow_for_its_user_unit_keeps_3_units_on_its_short_side() { + const MM: f64 = 72.0 / 25.4; + for set in [PdfSettings::default(), PdfSettings { standard: Standard::PdfA2b, ..PdfSettings::default() }] { + let r = report(&sized(TWENTY_M * 5.0, 4.0 * MM), set).unwrap(); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.779]); + let media = raw_numbers(&r.bytes, "/MediaBox", 4); + assert!(media[3] - media[1] >= 3.0, "{media:?}"); + assert!((media[2] - media[0] - TWENTY_M * 5.0 / 3.779).abs() < 0.01, "{media:?}"); + assert_eq!( + r.warnings.iter().filter(|w| w.contains("too long and narrow")).collect::>(), + [ + "the page of artboard 1 is 283465 × 12 pt (100.00 × 0.00 m), too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of 3.779, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units" + ] + ); + assert!(long_page_warnings(&r).is_empty(), "{:?}", r.warnings); + } + // A short side of 3 units or more at the long side's unit keeps that unit. + let r = report(&sized(TWENTY_M * 5.0, 60.0), PdfSettings::default()).unwrap(); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [19.686]); + let media = raw_numbers(&r.bytes, "/MediaBox", 4); + assert!(media[3] - media[1] >= 3.0, "{media:?}"); + let r = report(&sized(TWENTY_M * 5.0, 2.0), PdfSettings::default()).unwrap(); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [19.686]); +} + +/// A PDF 1.5 file written as PDF 1.6 for a long page keeps PDF 1.5's encryption, 128-bit RC4, as +/// the Save PDF dialog shows it. +#[test] +fn a_pdf_1_5_file_written_as_1_6_keeps_rc4_encryption() { + let mut set = PdfSettings { compatibility: Compatibility::Pdf15, ..PdfSettings::default() }; + set.security.open_password = "secret".into(); + let has = |bytes: &[u8], s: &[u8]| bytes.windows(s.len()).any(|w| w == s); + let r = report(&sized(TWENTY_M, 300.0), set).unwrap(); + assert!(r.bytes.starts_with(b"%PDF-1.6")); + assert!(has(&r.bytes, b"/CFM/V2") && !has(&r.bytes, b"AESV2"), "the file is encrypted with RC4"); +} + +/// The warning gives a page's size rounded up, as the error does: a side of 14,400.4 pt is 14401. +#[test] +fn the_long_page_warning_rounds_the_size_up() { + let r = report(&sized(14_400.4, 300.0), PdfSettings::default()).unwrap(); + assert!(long_page_warnings(&r)[0].contains("is 14401 × 300 pt"), "{:?}", r.warnings); +} + +/// A page of exactly 14,400 pt is written in points with no warning, at any PDF version; one +/// point longer gets a `UserUnit` of 1.001 and the warning, and stays in points at PDF 1.4. +#[test] +fn a_page_of_14400_pt_stays_in_points_and_one_point_more_does_not() { + let at = |side: f64, c: Compatibility| report(&sized(side, 300.0), PdfSettings { compatibility: c, ..PdfSettings::default() }); + for c in [Compatibility::Pdf14, Compatibility::Pdf15, Compatibility::Pdf17] { + let r = at(14_400.0, c).unwrap(); + assert!(long_page_warnings(&r).is_empty() && !r.warnings.iter().any(|w| w.contains("UserUnit")), "{}: {:?}", c.label(), r.warnings); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new(), "{}", c.label()); + assert_eq!(raw_numbers(&r.bytes, "/MediaBox", 4), [0.0, 0.0, 14_400.0, 300.0], "{}", c.label()); + } + let r = at(14_401.0, Compatibility::Pdf17).unwrap(); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [1.001]); + assert_eq!(long_page_warnings(&r).len(), 1, "{:?}", r.warnings); + assert!(long_page_warnings(&r)[0].contains("14401 × 300 pt (5.08 × 0.11 m)"), "{:?}", r.warnings); + let r = at(14_401.0, Compatibility::Pdf14).unwrap(); + assert_eq!(raw_numbers(&r.bytes, "/MediaBox", 4), [0.0, 0.0, 14_401.0, 300.0]); + assert_eq!(long_page_warnings(&r).len(), 1, "{:?}", r.warnings); +} + +/// A page of 14,400 pt or less is written as before in every built-in preset and every PDF +/// version: the header names the version asked for, the media box is in points, and there is no +/// `UserUnit` and no page-size warning. A PDF 1.5 file with a password keeps 128-bit RC4. +#[test] +fn a_page_within_14400_pt_is_written_as_before_at_every_version() { + let d = sized(14_400.0, 14_400.0); + let mut sets: Vec = crate::builtin_presets().into_iter().map(|p| p.settings).collect(); + for c in [Compatibility::Pdf13, Compatibility::Pdf14, Compatibility::Pdf15, Compatibility::Pdf16, Compatibility::Pdf17, Compatibility::Pdf20] { + sets.push(PdfSettings { compatibility: c, ..PdfSettings::default() }); + } + for set in sets { + let label = format!("{} {}", set.standard.label(), set.compatibility.label()); + let r = report(&d, set.clone()).unwrap_or_else(|e| panic!("{label}: {e}")); + // PDF/X-1a and PDF/X-3 files are always PDF 1.3. + let pdf13 = set.compatibility == Compatibility::Pdf13 || matches!(set.standard, Standard::PdfX1a | Standard::PdfX3); + let header = if pdf13 { "%PDF-1.3".to_string() } else { format!("%{}", set.compatibility.label().replace(' ', "-")) }; + assert!(r.bytes.starts_with(header.as_bytes()), "{label}: {:?}", String::from_utf8_lossy(&r.bytes[..8])); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new(), "{label}"); + assert_eq!(raw_numbers(&r.bytes, "/MediaBox", 4), [0.0, 0.0, 14_400.0, 14_400.0], "{label}"); + assert!(!r.warnings.iter().any(|w| w.contains("14,400") || w.contains("UserUnit")), "{label}: {:?}", r.warnings); + } + let mut set = PdfSettings { compatibility: Compatibility::Pdf15, ..PdfSettings::default() }; + set.security.open_password = "secret".into(); + let r = report(&d, set).unwrap(); + let has = |s: &[u8]| r.bytes.windows(s.len()).any(|w| w == s); + assert!(r.bytes.starts_with(b"%PDF-1.5") && has(b"/CFM/V2") && !has(b"AESV2")); +} + #[test] fn art_in_the_bleed_is_kept_and_clipped_to_the_bleed_box() { let d = doc(); diff --git a/crates/pdf/tests/gradient_forms.rs b/crates/pdf/tests/gradient_forms.rs new file mode 100644 index 0000000000..9f06c9b844 --- /dev/null +++ b/crates/pdf/tests/gradient_forms.rs @@ -0,0 +1,215 @@ +//! Gradients in forms must follow the art, including on pages with a nonzero origin. Quartz +//! exposed a failure the import/render round trip did not: it resolved a form's shading pattern +//! in page space, leaving off-centre gradients painted entirely in their last stop's colour. +//! These fixtures are original, generated geometry; no user artwork or external files are used. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{Appearance, ColorMode, Document, Knockout, Node, OpacityMask}; +use vectorcraft_geom::{Affine, Point, Rect, shapes}; +use vectorcraft_pdf::{PdfOptions, export, import}; +use vectorcraft_testkit::raster::{assert_similar, render_artboard}; + +#[derive(Clone, Copy, Debug)] +enum Form { + Page, + Opacity, + Isolated, + Nested, + PassThrough, + Mask, + Knockout, + Layer, + Overprint, +} + +const FORMS: [Form; 9] = + [Form::Page, Form::Opacity, Form::Isolated, Form::Nested, Form::PassThrough, Form::Mask, Form::Knockout, Form::Layer, Form::Overprint]; + +fn rect(d: &mut Document, bounds: Rect, paint: Paint) -> Node { + Node::path(d.alloc_id(), shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0)) +} + +fn group(d: &mut Document, n: Node) -> Node { + Node::group(d.alloc_id(), vec![Arc::new(n)]) +} + +/// Generate off-centre gradient art in each form type, moving the art and artboard together. +fn fixture(form: Form, kind: GradientKind, mode: ColorMode, origin: Point) -> (Document, PdfOptions) { + let mut d = Document::new_with_mode(120.0, 180.0, mode); + let color = |k| if mode == ColorMode::Cmyk { Color::cmyk(0.0, 0.0, 0.0, k) } else { Color::gray(k) }; + let mut gradient = GradientPaint::new(Gradient { + kind, + stops: vec![GradientStop::new(0.0, color(1.0)), GradientStop::new(0.6, color(0.4)), GradientStop::new(1.0, color(0.0))], + ..Default::default() + }); + let (start, end) = match kind { + GradientKind::Radial => (Point::new(32.0, 35.0), Point::new(60.0, 35.0)), + _ => (Point::new(10.0, 10.0), Point::new(70.0, 70.0)), + }; + gradient.geom = Some(GradientGeom { start, end, aspect: 0.8, focal: None }); + let mut n = rect(&mut d, Rect::new(10.0, 10.0, 70.0, 70.0), Paint::Gradient(Box::new(gradient))); + let mut opts = PdfOptions::default(); + match form { + Form::Page => d.page_isolate = true, + Form::Opacity => n.opacity = 0.6, + Form::Isolated => { + n = group(&mut d, n); + n.isolate = true; + } + Form::Nested => { + n.opacity = 0.75; + n = group(&mut d, n); + n.opacity = 0.8; + } + Form::PassThrough => { + n.blend = BlendMode::Multiply; + n = group(&mut d, n); + n.opacity = 0.6; + } + Form::Mask => { + let mask = rect(&mut d, Rect::new(10.0, 10.0, 44.0, 70.0), Paint::solid(Color::WHITE)); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(mask, true))); + } + Form::Knockout => { + let top = rect(&mut d, Rect::new(50.0, 50.0, 80.0, 80.0), Paint::solid(Color::WHITE)); + n = Node::group(d.alloc_id(), vec![Arc::new(n), Arc::new(top)]); + n.knockout = Knockout::On; + } + Form::Layer => opts.settings.create_layers = true, + Form::Overprint => n.appearance.fill_mut().unwrap().overprint = true, + } + n.transform(Affine::translate(origin.to_vec2()), false); + d.artboards[0].rect = d.artboards[0].rect + origin.to_vec2(); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, n).unwrap(); + (d, opts) +} + +/// Round trips preserve gradient placement for the form types the importer supports. +#[test] +fn gradients_in_forms_keep_their_position_when_read_back() { + // The importer has a pre-existing mismatch on the knockout's synthesized nested masks; + // Quartz below checks its actual PDF output, along with the other forms. + for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Knockout)) { + for kind in [GradientKind::Linear, GradientKind::Radial] { + for origin in [Point::ORIGIN, Point::new(125.0, -80.0)] { + let (d, opts) = fixture(form, kind, ColorMode::Rgb, origin); + let back = import(&export(&d, &opts).unwrap()).unwrap(); + assert_similar(&render_artboard(&back), &render_artboard(&d), 5.0, 0.01); + } + } + } +} + +/// Layer form bounds stay page-sized after translation, without extra imported clipping groups. +#[test] +fn translated_layer_forms_cover_the_paper_in_their_new_space() { + // The layer-box repair added upstream must move with the gradient fix's form transform. + // A local-space paper box would otherwise introduce a clipping group on import. + for origin in [Point::ORIGIN, Point::new(125.0, -80.0), Point::new(-250.0, 450.0)] { + let (d, mut opts) = fixture(Form::Layer, GradientKind::Radial, ColorMode::Rgb, origin); + opts.settings.compression.compress_text = false; + let bytes = export(&d, &opts).unwrap(); + let text = String::from_utf8_lossy(&bytes); + let boxes: Vec> = text + .split("/Subtype/Form") + .skip(1) + .map(|form| { + form.split("/BBox[").nth(1).unwrap().split(']').next().unwrap().split_ascii_whitespace().map(|v| v.parse().unwrap()).collect() + }) + .collect(); + assert_eq!(boxes, [vec![0.0, 0.0, 120.0, 180.0]], "{origin:?}: the layer covers exactly the page"); + let back = import(&bytes).unwrap(); + let children = back.layers[0].children().unwrap(); + assert_eq!(children.len(), 1); + assert!(children[0].path_data().is_some(), "{origin:?}: no clipping group wraps the layer's art"); + } +} + +// Test the renderer that exhibited the fault, not just our own importer (which accepted the +// old files). OS bindings are confined to this integration-test module. +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod quartz { + use objc2_core_foundation::CFData; + use objc2_core_graphics::{CGBitmapContextCreate, CGColorSpace, CGContext, CGDataProvider, CGImageAlphaInfo, CGPDFDocument}; + use vectorcraft_testkit::raster::Image; + + use super::*; + + /// Render the first PDF page through Quartz as an oracle independent of our importer. + fn render(bytes: &[u8]) -> Image { + let data = CFData::from_bytes(bytes); + let provider = CGDataProvider::with_cf_data(Some(&data)).unwrap(); + let doc = CGPDFDocument::with_provider(Some(&provider)).unwrap(); + let page = CGPDFDocument::page(Some(&doc), 1).unwrap(); + let space = CGColorSpace::new_device_rgb().unwrap(); + let (width, height) = (120, 180); + let mut rgba = vec![255u8; width * height * 4]; + // SAFETY: the buffer holds every RGBA row, stays allocated and is not accessed until the + // context is dropped. All inputs are the small, generated fixtures above. + let context = unsafe { + CGBitmapContextCreate(rgba.as_mut_ptr().cast(), width, height, 8, width * 4, Some(&space), CGImageAlphaInfo::PremultipliedLast.0) + } + .unwrap(); + CGContext::draw_pdf_page(Some(&context), Some(&page)); + drop(context); + Image { width: width as u32, height: height as u32, rgba } + } + + /// Quartz places RGB and CMYK radial centres, edges and masks with their translated art. + #[test] + fn quartz_keeps_off_centre_radials_in_transparency_and_layer_forms() { + for mode in [ColorMode::Rgb, ColorMode::Cmyk] { + for form in FORMS { + for origin in [Point::ORIGIN, Point::new(125.0, -80.0)] { + let (d, opts) = fixture(form, GradientKind::Radial, mode, origin); + let img = render(&export(&d, &opts).unwrap()); + let centre = img.over_white(32, 35)[0]; + let edge = img.over_white(32, 55)[0]; + assert!(centre < 150 && edge.saturating_sub(centre) > 40, "{mode:?} {form:?} {origin:?}: centre {centre}, edge {edge}"); + assert_eq!(img.over_white(90, 100), [255; 3], "art stays in its bounds"); + if matches!(form, Form::Mask) { + assert_eq!(img.over_white(46, 35), [255; 3], "the mask moves with the gradient"); + } + } + } + } + } + + /// Quartz retains the linear ramp's direction inside forms on a translated artboard. + #[test] + fn quartz_keeps_linear_gradient_directions_in_forms() { + for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Mask | Form::Knockout)) { + let (d, opts) = fixture(form, GradientKind::Linear, ColorMode::Rgb, Point::new(-30.0, 45.0)); + let img = render(&export(&d, &opts).unwrap()); + let (start, end) = (img.over_white(20, 20)[0], img.over_white(60, 60)[0]); + assert!(end.saturating_sub(start) > 60, "{form:?}: start {start}, end {end}"); + } + } + + /// A gradient's stop-opacity mask remains aligned with its colour through nested forms. + #[test] + fn quartz_keeps_gradient_stop_opacity_aligned_inside_nested_forms() { + let (mut d, opts) = fixture(Form::Nested, GradientKind::Radial, ColorMode::Rgb, Point::ORIGIN); + let mut leaves = vec![]; + d.walk(|n| { + if n.path_data().is_some() { + leaves.push(n.id); + } + }); + for id in leaves { + let fill = d.node_mut(id).unwrap().appearance.fill_mut().unwrap(); + let Paint::Gradient(g) = &mut fill.paint else { panic!("gradient fixture") }; + for stop in &mut g.gradient.stops { + stop.opacity = 0.6 * (1.0 - stop.offset); + } + } + let img = render(&export(&d, &opts).unwrap()); + let (centre, edge) = (img.over_white(32, 35)[0], img.over_white(32, 55)[0]); + assert!(centre > 145 && centre < 205 && edge > 240, "centre {centre}, edge {edge}"); + } +} diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index f8235a4fbb..182456aa71 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -1,9 +1,10 @@ //! What a plug-in may import from the host ([`IMPORTS`]), from plug-in API level 2 on: //! `vc_progress` reports how far a run has got, `vc_cancelled` tells it the user or a host limit //! asked it to stop, and `vc_log` writes a log line (the `progress` permission); `vc_settings_*` -//! read and write its settings (`settings`) and `vc_cache_*` its cache (`cache`, [`crate::storage`]). -//! A module may import one only when its manifest gives `api` 2 and lists the import's permission, -//! and the host checks each import when the module is loaded ([`check_imports`], [`check_granted`]): +//! read and write its settings (`settings`) and `vc_cache_*` its cache (`cache`, [`crate::storage`]); +//! `vc_call` runs a command its manifest's `commandAllowlist` names and `vc_call_result` reads that +//! command's result (`commands`, through the [`Bridge`] the run is given). A module may import one +//! only when its manifest gives `api` 2 and lists the import's permission, and the host checks each import when the module is loaded ([`check_imports`], [`check_granted`]): //! one it doesn't offer, one with another signature and one the manifest doesn't allow are refused //! by name. //! @@ -13,8 +14,9 @@ //! each line ([`MAX_LOG_LINE`]) and each run ([`MAX_LOG_LINES`], [`MAX_LOG_BYTES`], //! [`MAX_LOG_READ`]) are capped. Keys and values must lie inside the module's memory, keys must be //! [`crate::storage::valid_name`]s, values are capped, and so are each run's storage calls -//! ([`MAX_STORAGE_CALLS`]) and the bytes they move ([`MAX_STORAGE_BYTES`]). Nothing a module passes -//! can panic the host. +//! ([`MAX_STORAGE_CALLS`]) and the bytes they move ([`MAX_STORAGE_BYTES`]). Command calls are capped +//! per call ([`MAX_CALL_DATA`]) and per run ([`MAX_CALLS`], [`MAX_CALL_BYTES`]). Nothing a module +//! passes can panic the host. use std::sync::Arc; @@ -95,6 +97,72 @@ pub const MAX_STORAGE_CALLS: usize = 10_000; /// pass it returns [`STORAGE_BUDGET`]. pub const MAX_STORAGE_BYTES: usize = 1 << 30; +/// What `vc_call` returns: the command ran, and `vc_call_result` reads its result. +pub const CALL_OK: i32 = 0; +/// What `vc_call` or `vc_call_result` returns: the id, the arguments or the buffer doesn't lie +/// inside the module's memory. +pub const CALL_OUTSIDE_MEMORY: i32 = -1; +/// What `vc_call` returns: the id or the arguments are not UTF-8. +pub const CALL_BAD_UTF8: i32 = -2; +/// What `vc_call` returns: the arguments are not a JSON object. +pub const CALL_BAD_JSON: i32 = -3; +/// What `vc_call` returns: the manifest's `commandAllowlist` doesn't list the command. +pub const CALL_NOT_ALLOWED: i32 = -4; +/// What `vc_call` returns: no command has the id. +pub const CALL_UNKNOWN_COMMAND: i32 = -5; +/// What `vc_call` returns: a plug-in may not call the command, whatever its manifest lists. +pub const CALL_DENIED_COMMAND: i32 = -6; +/// What `vc_call` returns: the command can't run now (no document, nothing selected). +pub const CALL_DISABLED: i32 = -7; +/// What `vc_call` returns: the command ran and failed. +pub const CALL_COMMAND_FAILED: i32 = -8; +/// What `vc_call` returns: the arguments or the result are larger than [`MAX_CALL_DATA`], or the +/// run made [`MAX_CALLS`] calls or moved [`MAX_CALL_BYTES`] with them. +pub const CALL_LIMIT: i32 = -9; +/// What `vc_call_result` returns: no call has a result yet. +pub const CALL_NO_RESULT: i32 = -10; +/// What `vc_call` returns: nothing can be called now (while the module is being loaded, in a run +/// that isn't a filter's run on a document, or after a call in the run failed). In a run, this +/// fails it too. +pub const CALL_NO_CONTEXT: i32 = -11; + +/// Most `vc_call` calls one run makes. +pub const MAX_CALLS: usize = 1_000; + +/// Largest arguments or result of one `vc_call`, in bytes. +pub const MAX_CALL_DATA: usize = 8 << 20; + +/// Most bytes of arguments and results one run's `vc_call` calls move, all together. +pub const MAX_CALL_BYTES: usize = 64 << 20; + +/// Instructions each `vc_call` costs the run, besides one for every 64 bytes of its arguments and +/// result: [`MAX_CALLS`] calls cost a fifth of a filter's usual budget. +pub const CALL_FUEL: u64 = 10_000; + +/// Why a command a plug-in called with `vc_call` didn't run, or failed: the code `vc_call` returns +/// and the reason, which the run's error gives. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CallFailure { + pub code: i32, + pub why: String, +} + +/// What runs the commands a plug-in calls: a command id and its arguments (a JSON object) → the +/// command's result, or why it didn't run. +pub type Bridge<'a> = dyn FnMut(&str, &serde_json::Value) -> std::result::Result + 'a; + +/// What `vc_call` pauses the run with, for the host to make the call ([`Run::pending`]). +#[derive(Debug)] +pub(crate) struct CallPending; + +impl std::fmt::Display for CallPending { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("vc_call") + } +} + +impl wasmi::errors::HostError for CallPending {} + /// One host import: its name, its type and the permission it needs. pub struct Import { pub name: &'static str, @@ -134,7 +202,17 @@ const fn storage_import(name: &'static str, params: &'static [ValType], signatur /// A storage call that fails returns [`STORAGE_NOT_FOUND`], [`STORAGE_OUTSIDE_MEMORY`], /// [`STORAGE_BAD_NAME`], [`STORAGE_FULL`], [`STORAGE_UNAVAILABLE`], [`STORAGE_FAILED`] or /// [`STORAGE_BUDGET`]. -pub const IMPORTS: [Import; 9] = [ +/// +/// With `commands`, for a filter whose manifest's `commandAllowlist` names the command: +/// +/// - `vc_call(id, id_len, args, args_len) -> i32`: runs the command with the UTF-8 id of `id_len` +/// bytes at `id` and the arguments at `args` (a UTF-8 JSON object; no bytes: `{}`) on the document +/// the run is for → [`CALL_OK`] or why it didn't run or failed. A failed call fails the run, and +/// nothing the run did stays; +/// - `vc_call_result(out, out_cap) -> i32`: the length of the last successful call's result (JSON), +/// copied to `out` when it fits in `out_cap` (nothing is copied otherwise), or +/// [`CALL_NO_RESULT`]. +pub const IMPORTS: [Import; 11] = [ Import { name: "vc_progress", params: &[ValType::I64, ValType::I64], @@ -156,6 +234,8 @@ pub const IMPORTS: [Import; 9] = [ storage_import("vc_cache_read", &[I32, I32, I32, I32], "(param i32 i32 i32 i32) (result i32)", Permission::Cache), storage_import("vc_cache_write", &[I32, I32, I32, I32], "(param i32 i32 i32 i32) (result i32)", Permission::Cache), storage_import("vc_cache_clear", &[I32, I32], "(param i32 i32) (result i32)", Permission::Cache), + storage_import("vc_call", &[I32, I32, I32, I32], "(param i32 i32 i32 i32) (result i32)", Permission::Commands), + storage_import("vc_call_result", &[I32, I32], "(param i32 i32) (result i32)", Permission::Commands), ]; /// Which of a plug-in's stores a storage import reads or writes. @@ -291,6 +371,18 @@ pub(crate) struct Run { storage: Option>, storage_calls: usize, storage_bytes: usize, + /// The commands `vc_call` may run (the manifest's `commandAllowlist`), once the module has + /// loaded and when the run has something to run them ([`Run::allow_calls`]); `None` otherwise. + allowed: Option>, + /// How many `vc_call` calls the run made, and the bytes of arguments and results they moved. + calls: usize, + call_bytes: usize, + /// The call `vc_call` paused the run for: its command id, its arguments and their size in bytes. + pub(crate) pending: Option<(String, serde_json::Value, usize)>, + /// The last successful call's result, as JSON text. + pub(crate) call_result: Option>, + /// The run's first failed call, which fails the run. + pub(crate) call_failure: Option, pub(crate) report: Report, } @@ -309,6 +401,12 @@ impl Run { storage: None, storage_calls: 0, storage_bytes: 0, + allowed: None, + calls: 0, + call_bytes: 0, + pending: None, + call_result: None, + call_failure: None, report: Report::default(), } } @@ -319,6 +417,119 @@ impl Run { self } + /// From now on, `vc_call` runs the commands in `allowed`. + pub(crate) fn allow_calls(&mut self, allowed: Vec) { + self.allowed = Some(allowed); + } + + /// Records the run's first failed call, `e`, and returns `code`. + fn fail(&mut self, code: i32, e: Error) -> i32 { + self.call_failure.get_or_insert(e); + code + } + + /// `vc_call`: checks the call to the command at `id` with the arguments at `args` in `memory` + /// and leaves it in [`Run::pending`] for the host to make, or → the code for why it can't be + /// made, which fails the run. The size of the arguments is checked before they are read. After + /// the run's first failed call, every call returns [`CALL_NO_CONTEXT`] and none is made. + fn call_request(&mut self, memory: &[u8], id: (usize, usize), args: (usize, usize)) -> std::result::Result<(), i32> { + self.call_result = None; + // No call is made after the run's first failed call. + if self.call_failure.is_some() { + return Err(CALL_NO_CONTEXT); + } + if self.allowed.is_none() { + let why = "vc_call: no command can be called here (while the module loads, or in a run that can't make calls)"; + return Err(self.fail(CALL_NO_CONTEXT, Error::Abi(why.into()))); + } + let shown = || { + id.0.checked_add(id.1) + .filter(|_| id.1 <= crate::manifest::MAX_ALLOWED_ID) + .and_then(|end| memory.get(id.0..end)) + .map_or_else(|| "?".to_string(), |b| permissions::display_text(&String::from_utf8_lossy(b), permissions::MAX_SHOWN_FIELD)) + }; + if args.1 > MAX_CALL_DATA { + let (shown, len) = (shown(), args.1); + return Err(self.fail(CALL_LIMIT, Error::Limit(format!("command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA})")))); + } + if self.calls >= MAX_CALLS || self.call_bytes.saturating_add(args.1) > MAX_CALL_BYTES { + return Err(self.fail(CALL_LIMIT, Error::Limit(format!("command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run)")))); + } + self.calls += 1; + self.call_bytes += args.1; + let slice = |(at, len): (usize, usize)| at.checked_add(len).and_then(|end| memory.get(at..end)); + let (Some(id_bytes), Some(arg_bytes)) = (slice(id).filter(|_| id.1 <= crate::manifest::MAX_ALLOWED_ID), slice(args)) else { + if id.1 > crate::manifest::MAX_ALLOWED_ID { + let shown = shown(); + return Err(self.fail(CALL_NOT_ALLOWED, Error::Abi(format!("vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it")))); + } + let shown = shown(); + return Err( + self.fail(CALL_OUTSIDE_MEMORY, Error::Abi(format!("vc_call `{shown}`: the id or the arguments lie outside the module's memory"))) + ); + }; + let (Ok(name), Ok(text)) = (std::str::from_utf8(id_bytes), std::str::from_utf8(arg_bytes)) else { + let shown = shown(); + return Err(self.fail(CALL_BAD_UTF8, Error::Abi(format!("vc_call `{shown}`: the id or the arguments are not UTF-8")))); + }; + if !self.allowed.as_ref().is_some_and(|allowed| allowed.iter().any(|a| a == name)) { + let shown = shown(); + return Err(self.fail(CALL_NOT_ALLOWED, Error::Abi(format!("vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it")))); + } + let parsed = if text.is_empty() { Ok(serde_json::Value::Object(serde_json::Map::new())) } else { serde_json::from_str(text) }; + match parsed { + Ok(v @ serde_json::Value::Object(_)) => { + self.pending = Some((name.to_string(), v, args.1)); + Ok(()) + } + _ => { + let shown = shown(); + Err(self.fail(CALL_BAD_JSON, Error::Abi(format!("vc_call `{shown}`: the arguments are not a JSON object")))) + } + } + } + + /// Takes the host's answer to the call in [`Run::pending`], to command `id`: keeps its result for + /// `vc_call_result`, or records the failure → what `vc_call` returns. + pub(crate) fn call_answered(&mut self, id: &str, answer: std::result::Result) -> i32 { + let shown = permissions::display_text(id, permissions::MAX_SHOWN_FIELD); + let value = match answer { + Ok(value) => value, + Err(f) => { + let why = f.why; + return self.fail(f.code, Error::Failed(format!("vc_call `{shown}`: {why}"))); + } + }; + let text = serde_json::to_vec(&value).unwrap_or_default(); + let len = text.len(); + if len > MAX_CALL_DATA { + return self.fail(CALL_LIMIT, Error::Limit(format!("command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA})"))); + } + if self.call_bytes.saturating_add(len) > MAX_CALL_BYTES { + return self.fail(CALL_LIMIT, Error::Limit(format!("command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run)"))); + } + self.call_bytes += len; + self.call_result = Some(text); + CALL_OK + } + + /// `vc_call_result`: copies the last successful call's result into the `out_cap` bytes at `out` + /// when it fits → its length, or [`CALL_NO_RESULT`] or [`CALL_OUTSIDE_MEMORY`]. Neither fails + /// the run: a plug-in asks again with a larger buffer. + fn call_result(&self, memory: &mut [u8], out: (usize, usize)) -> i32 { + let Some(result) = &self.call_result else { return CALL_NO_RESULT }; + if out.1 > 0 && out.0.checked_add(out.1).is_none_or(|end| end > memory.len()) { + return CALL_OUTSIDE_MEMORY; + } + if result.len() <= out.1 + && let Some(dest) = memory.get_mut(out.0..out.0 + result.len()) + { + dest.copy_from_slice(result); + } + // At most MAX_CALL_DATA, which an i32 holds. + i32::try_from(result.len()).unwrap_or(CALL_LIMIT) + } + /// Makes one storage call with `call`, on the plug-in's storage and a [`Meter`] holding the /// run's storage bytes left, and counts the call and the bytes it read and wrote → the code for /// a run that has used up its calls or has no storage, else what `call` returns. @@ -534,6 +745,25 @@ pub(crate) fn linker(engine: &Engine, granted: &[Permission]) -> Linker { host.run.storage_remove(area, data, (offset(key), offset(key_len))) }); } + if granted.contains(&Permission::Commands) { + // A call that can be made pauses the run: the host makes it with what the run was given to + // make calls with ([`crate::Plugin::run_calling`]), and resumes the run with the code. + let _ = linker.func_wrap( + MODULE, + "vc_call", + |mut caller: Caller<'_, Host>, id: i32, id_len: i32, args: i32, args_len: i32| -> std::result::Result { + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(CALL_OUTSIDE_MEMORY) }; + match host.run.call_request(data, (offset(id), offset(id_len)), (offset(args), offset(args_len))) { + Ok(()) => Err(wasmi::Error::host(CallPending)), + Err(code) => Ok(code), + } + }, + ); + let _ = linker.func_wrap(MODULE, "vc_call_result", |mut caller: Caller<'_, Host>, out: i32, out_cap: i32| -> i32 { + let Some((data, host)) = memory_and_host(&mut caller) else { return CALL_OUTSIDE_MEMORY }; + host.run.call_result(data, (offset(out), offset(out_cap))) + }); + } linker } diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index e3f1f76dea..b4faf543db 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -5,7 +5,8 @@ //! //! - **no host imports but those of API level 2** ([`host`]: progress, Cancel and log lines with //! the `progress` permission, and settings and a cache of its own with the `settings` and `cache` -//! permissions, [`storage`]): no WASI, file system, network, clock or randomness. A module that +//! permissions, [`storage`], and the commands its `commandAllowlist` names with the `commands` +//! permission): no WASI, file system, network, clock or randomness. A module that //! imports anything else is rejected; //! - an **instruction budget** (fuel) per call, metered in slices so a wall-clock deadline is //! also enforced (native builds), so infinite loops end with an error. A filter may ask for a diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index d548e64440..a16bd8a4f9 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -25,6 +25,12 @@ pub const MAX_COMMANDS: usize = 32; /// Longest command id, in characters. pub const MAX_COMMAND_ID: usize = 32; +/// Most commands a manifest's `commandAllowlist` names. +pub const MAX_ALLOWED_COMMANDS: usize = 256; + +/// Longest command id a manifest's `commandAllowlist` names, in bytes. +pub const MAX_ALLOWED_ID: usize = 128; + /// What a plug-in is. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -337,6 +343,11 @@ pub struct Manifest { /// The menu commands it adds, in menu order (a filter or a live effect only). #[serde(default, deserialize_with = "ordered_commands", skip_serializing_if = "Vec::is_empty")] pub commands: Vec, + /// The VectorCraft commands a run may call with `vc_call` (exact command ids, such as + /// `object.transform`): only a filter with the usual budget whose `permissions` list `commands` + /// lists any ([`Manifest::validate`]). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub command_allowlist: Vec, } impl Manifest { @@ -371,6 +382,7 @@ impl Manifest { budget: Budget::Light, paint_output: false, commands: Vec::new(), + command_allowlist: Vec::new(), } } @@ -427,7 +439,40 @@ impl Manifest { } } self.validate_params()?; - self.validate_commands() + self.validate_commands()?; + self.validate_allowlist() + } + + /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids + /// ([`valid_allowed_id`]), and only a filter with the usual budget lists any: a heavy one runs in + /// the background, away from the document its commands would change. A list needs the + /// permission `commands`, and `commands` needs a list. + fn validate_allowlist(&self) -> Result<()> { + let listed = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::Commands.name())); + if self.command_allowlist.is_empty() == listed { + return Err(Error::Manifest("`commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist`".into())); + } + if self.command_allowlist.is_empty() { + return Ok(()); + } + if self.kind != Kind::Filter || self.budget == Budget::Heavy { + return Err(Error::Manifest("only a filter with the usual budget declares `commandAllowlist`".into())); + } + if self.command_allowlist.len() > MAX_ALLOWED_COMMANDS { + return Err(Error::Manifest(format!("at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist`"))); + } + for (i, id) in self.command_allowlist.iter().enumerate() { + if !valid_allowed_id(id) || self.command_allowlist.get(..i).is_some_and(|before| before.contains(id)) { + let shown = permissions::display_text(id, permissions::MAX_SHOWN_FIELD); + return Err(Error::Manifest(format!("`commandAllowlist` names `{shown}`, which is not a command id or is listed twice"))); + } + } + Ok(()) + } + + /// May a run call command `id` ([`Manifest::command_allowlist`])? + pub fn allows_call(&self, id: &str) -> bool { + self.command_allowlist.iter().any(|a| a == id) } /// Checks each parameter and its dialog layout. @@ -810,6 +855,15 @@ fn params_as_object(p: &[(String, Param)], s: S) -> std::r m.end() } +/// A command id as a `commandAllowlist` names it: 1 to [`MAX_ALLOWED_ID`] bytes from +/// `A-Za-z0-9._-`, starting with a letter, with no empty part between dots. +pub fn valid_allowed_id(id: &str) -> bool { + (1..=MAX_ALLOWED_ID).contains(&id.len()) + && id.bytes().next().is_some_and(|b| b.is_ascii_alphabetic()) + && id.split('.').all(|part| !part.is_empty()) + && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) +} + /// `[A-Za-z0-9._-]{1,64}`. pub fn valid_id(id: &str) -> bool { (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index 778b19cee8..7380edd568 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -5,9 +5,9 @@ //! `doc.read`, `doc.write`, `state` and `progress` are the names of the plug-in capability model in //! storytold/photocraft#662; the other names are VectorCraft's own. A manifest without //! `permissions` gets the ones its kind implies ([`Permission::implied`]): what every plug-in of -//! that kind could do before manifests listed them. `progress`, `settings` and `cache`, which let a -//! plug-in use the host imports of API level 2 ([`crate::host`]), are never implied: a manifest -//! lists them. +//! that kind could do before manifests listed them. `progress`, `settings`, `cache` and `commands`, +//! which let a plug-in use the host imports of API level 2 ([`crate::host`]), are never implied: a +//! manifest lists them. use serde::{Deserialize, Serialize}; @@ -19,7 +19,7 @@ use crate::{Error, Kind, Result}; pub const API_LEVEL: u32 = 2; /// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`, -/// `settings` and `cache` permissions they need. +/// `settings`, `cache` and `commands` permissions they need. pub const PROGRESS_API: u32 = 2; /// The API level that adds a filter's `inputs` ([`crate::InputKind`]). @@ -70,10 +70,14 @@ pub enum Permission { /// Keep a cache of its own, which the user can clear ([`crate::storage`]). #[serde(rename = "cache")] Cache, + /// Run the VectorCraft commands its manifest's `commandAllowlist` names, with `vc_call` + /// ([`crate::host::IMPORTS`]): a filter only. + #[serde(rename = "commands")] + Commands, } /// Every permission this host grants, in the order prompts list them. -pub const ALL: [Permission; 9] = [ +pub const ALL: [Permission; 10] = [ Permission::DocRead, Permission::DocWrite, Permission::State, @@ -83,11 +87,13 @@ pub const ALL: [Permission; 9] = [ Permission::Progress, Permission::Settings, Permission::Cache, + Permission::Commands, ]; /// The permissions of the host imports, which any kind may list and none implies; each needs plug-in -/// API level [`PROGRESS_API`]. -pub const HOST: [Permission; 3] = [Permission::Progress, Permission::Settings, Permission::Cache]; +/// API level [`PROGRESS_API`]. Only a filter with a `commandAllowlist` may list `commands` +/// ([`crate::manifest::Manifest::command_allowlist`]). +pub const HOST: [Permission; 4] = [Permission::Progress, Permission::Settings, Permission::Cache, Permission::Commands]; impl Permission { /// Its name in a manifest and in `plugin.install`'s `grant`. @@ -102,6 +108,7 @@ impl Permission { Permission::Progress => "progress", Permission::Settings => "settings", Permission::Cache => "cache", + Permission::Commands => "commands", } } @@ -122,6 +129,7 @@ impl Permission { Permission::Progress => "Show its progress, see Cancel and write log lines", Permission::Settings => "Keep settings of its own", Permission::Cache => "Keep a cache of its own, which you can clear", + Permission::Commands => "Run these commands", } } diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index e6278fc99a..5abaa0bf48 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -1,11 +1,11 @@ //! The wasmi host: loading, instantiating and calling a plug-in under resource limits. use wasmi::{ - Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, WasmParams, - WasmResults, + Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, Val, + WasmParams, WasmResults, }; -use crate::host::{self, Deadline, Host, Report, Run}; +use crate::host::{self, Bridge, Deadline, Host, Report, Run}; use crate::manifest::{MAX_MANIFEST_BYTES, Manifest}; use crate::permissions::Permission; use crate::{Error, Kind, Result}; @@ -132,6 +132,18 @@ impl Live { } } +/// Takes `cost` instructions from a run: from the budget still to hand out (`left`), then from what +/// the store holds. A run that can't pay ends with its instruction budget. +fn charge(live: &mut Live, left: &mut u64, cost: u64) -> Result<()> { + let held = live.store.get_fuel().map_err(wasm_err)?; + if held.saturating_add(*left) < cost { + return Err(Error::Limit("instruction budget".into())); + } + let from_left = cost.min(*left); + *left -= from_left; + live.store.set_fuel(held - (cost - from_left)).map_err(wasm_err) +} + fn wasm_err(e: wasmi::Error) -> Error { if e.as_trap_code() == Some(wasmi::TrapCode::OutOfFuel) { Error::Limit("instruction budget".into()) } else { Error::Trap(e.to_string()) } } @@ -257,6 +269,22 @@ impl Plugin { /// slice size, keeping that fuel, and a run ends with the instruction budget only when the /// store's fuel and the rest of the budget together can't pay for the next instruction. fn call(&self, live: &mut Live, f: &TypedFunc, params: P, fuel: u64, deadline: &Deadline) -> Result { + self.call_with(live, f, params, fuel, deadline, None) + } + + /// [`Plugin::call`], making each command call a `vc_call` pauses it for with `bridge` + /// ([`host::Run::pending`]) and resuming it with the code. Each call costs [`host::CALL_FUEL`] + /// instructions and one for every 64 bytes of its arguments and result; the deadline and the + /// caller's cancellation are checked before and after it. + fn call_with( + &self, + live: &mut Live, + f: &TypedFunc, + params: P, + fuel: u64, + deadline: &Deadline, + mut bridge: Option<&mut Bridge<'_>>, + ) -> Result { let mut left = fuel; let give = left.min(FUEL_SLICE); left -= give; @@ -265,7 +293,22 @@ impl Plugin { loop { match call { TypedResumableCall::Finished(r) => return Ok(r), - TypedResumableCall::HostTrap(_) => return Err(Error::Trap("unexpected host trap".into())), + TypedResumableCall::HostTrap(inv) => { + let pending = live.store.data_mut().run.pending.take(); + let (Some((id, args, size)), Some(bridge)) = (pending, bridge.as_deref_mut()) else { + return Err(Error::Trap("unexpected host trap".into())); + }; + charge(live, &mut left, host::CALL_FUEL.saturating_add(size as u64 / 64))?; + deadline.check()?; + vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; + let answer = bridge(&id, &args); + let code = live.store.data_mut().run.call_answered(&id, answer); + let returned = live.store.data().run.call_result.as_ref().map_or(0, Vec::len); + charge(live, &mut left, returned as u64 / 64)?; + deadline.check()?; + vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; + call = inv.resume(&mut live.store, &[Val::I32(code)]).map_err(wasm_err)?; + } TypedResumableCall::OutOfFuel(inv) => { let need = inv.required_fuel(); let held = live.store.get_fuel().map_err(wasm_err)?; @@ -302,30 +345,61 @@ impl Plugin { /// [`vectorcraft_doc::cancel::scope`] its progress goes to the scope's sink (a live effect's /// doesn't) and `vc_cancelled` sees the scope's Cancel. pub fn run_reporting(&self, input: &[u8], params: &[u8], limits: &Limits) -> (Result>, Report) { + self.run_guarded(input, params, limits, None) + } + + /// [`Plugin::run_reporting`] for a filter whose manifest's `commandAllowlist` names commands: + /// each `vc_call` of one of them is made with `bridge`, on the caller's thread, while the run + /// waits. A failed call fails the run, also when the plug-in goes on and returns an output; the + /// error names the command. + pub fn run_calling(&self, input: &[u8], params: &[u8], limits: &Limits, bridge: &mut Bridge<'_>) -> (Result>, Report) { + self.run_guarded(input, params, limits, Some(bridge)) + } + + fn run_guarded(&self, input: &[u8], params: &[u8], limits: &Limits, bridge: Option<&mut Bridge<'_>>) -> (Result>, Report) { let mut report = Report::default(); if let Err(e) = crate::safe_mode::check() { return (Err(e), report); } // wasmi reports misbehaving modules as errors; a panic would be a bug in it, and must // still not take the document down (native builds; wasm aborts on panic anyway). - let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_inner(input, params, limits, &mut report))); + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_inner(input, params, limits, &mut report, bridge))); (run.map_err(|_| Error::Trap("the runtime panicked".into())).and_then(|r| r), report) } - fn run_inner(&self, input: &[u8], params: &[u8], limits: &Limits, report: &mut Report) -> Result> { + fn run_inner(&self, input: &[u8], params: &[u8], limits: &Limits, report: &mut Report, bridge: Option<&mut Bridge<'_>>) -> Result> { let total = input.len().checked_add(params.len()).filter(|b| *b <= i32::MAX as usize && *b <= self.limits.max_memory_bytes / 2); total.ok_or_else(|| Error::Limit(SELECTION_TOO_LARGE.into()))?; let deadline = Deadline::new(limits.wall_time_ms); let m = &self.manifest; let run = Run::new(&m.id, m.kind != Kind::Effect, true, deadline).with_storage(crate::registry::storage(&m.id)); let mut live = self.instantiate(run, &m.permissions(), report)?; - let out = self.run_live(&mut live, input, params, limits, &deadline); - *report = std::mem::take(&mut live.store.data_mut().run.report); - out + // Calls can be made from `vc_run` on, not from the start function. + if bridge.is_some() { + live.store.data_mut().run.allow_calls(m.command_allowlist.clone()); + } + let out = self.run_live(&mut live, input, params, limits, &deadline, bridge); + let state = &mut live.store.data_mut().run; + *report = std::mem::take(&mut state.report); + // A failed call fails the run, whatever the plug-in did after it, unless the run was + // canceled. + match (state.call_failure.take(), out) { + (_, Err(Error::Cancelled)) => Err(Error::Cancelled), + (Some(e), _) => Err(e), + (None, out) => out, + } } /// Hands `input` and `params` to the instance `live` and runs `vc_run` → the output JSON bytes. - fn run_live(&self, live: &mut Live, input: &[u8], params: &[u8], limits: &Limits, deadline: &Deadline) -> Result> { + fn run_live( + &self, + live: &mut Live, + input: &[u8], + params: &[u8], + limits: &Limits, + deadline: &Deadline, + bridge: Option<&mut Bridge<'_>>, + ) -> Result> { let alloc: TypedFunc = live.func("vc_alloc")?; let run: TypedFunc = live.func("vc_run")?; let place = |live: &mut Live, bytes: &[u8]| -> Result { @@ -341,7 +415,7 @@ impl Plugin { let iptr = place(live, input)?; let pptr = place(live, params)?; let fuel = limits.fuel_base.saturating_add((input.len() as u64).saturating_mul(limits.fuel_per_byte)); - let packed = self.call(live, &run, (iptr as i32, input.len() as i32, pptr as i32, params.len() as i32), fuel, deadline)?; + let packed = self.call_with(live, &run, (iptr as i32, input.len() as i32, pptr as i32, params.len() as i32), fuel, deadline, bridge)?; // A cancelled run, or one past its time budget, changes nothing, also when the plug-in saw // `vc_cancelled` and returned. vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; diff --git a/crates/plugins/tests/call.rs b/crates/plugins/tests/call.rs new file mode 100644 index 0000000000..2dd2c7c5e7 --- /dev/null +++ b/crates/plugins/tests/call.rs @@ -0,0 +1,382 @@ +//! `vc_call` and `vc_call_result`: a filter of API level 2 that lists `commands` calls the commands +//! its manifest's `commandAllowlist` names, through what the host gives the run to make them with. +//! Every misuse is a code the plug-in sees, and fails the run. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_plugins::host::{ + CALL_BAD_JSON, CALL_BAD_UTF8, CALL_COMMAND_FAILED, CALL_LIMIT, CALL_NO_CONTEXT, CALL_NO_RESULT, CALL_NOT_ALLOWED, CALL_OUTSIDE_MEMORY, + CallFailure, MAX_CALL_DATA, MAX_CALLS, +}; +use vectorcraft_plugins::{Error, Limits, Manifest, Plugin, wat as tpl}; + +const INPUT: &str = r#"{"objects":[]}"#; + +/// The command imports, as `$vc_call` and `$vc_call_result`, and the strings the tests pass: the id +/// "select.all" at 0x2000, "object.delete" at 0x2010, the arguments `{"a":1}` at 0x2100, the byte +/// 0xff at 0x2200 and `[1]` at 0x2300. 0x3000 is free for a result. +const CALLS: &str = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (import "env" "vc_call_result" (func $vc_call_result (param i32 i32) (result i32))) + (data (i32.const 0x2000) "select.all") + (data (i32.const 0x2010) "object.delete") + (data (i32.const 0x2100) "{\22a\22:1}") + (data (i32.const 0x2200) "\ff") + (data (i32.const 0x2300) "[1]")"#; + +/// A filter `id` that may call `select.all`. +fn manifest(id: &str) -> String { + format!( + r#"{{"id":"{id}","name":"Caller","kind":"filter","api":2,"permissions":["doc.read","doc.write","commands"],"commandAllowlist":["select.all"]}}"# + ) +} + +/// `vc_call` of the id at `id` (`len` bytes) with the arguments at `args` (`args_len` bytes). +fn call(id: &str, len: &str, args: &str, args_len: &str) -> String { + format!("(call $vc_call (i32.const {id}) (i32.const {len}) (i32.const {args}) (i32.const {args_len}))") +} + +/// `select.all` with `{"a":1}`. +fn select_all() -> String { + call("0x2000", "10", "0x2100", "7") +} + +/// Instructions that trap unless `expr` is `want`. +fn expect(expr: &str, want: i32) -> String { + format!("(if (i32.ne {expr} (i32.const {want})) (then unreachable))") +} + +/// A filter that runs `first`, then returns the input. +fn calling(id: &str, first: &str) -> Plugin { + let src = tpl::with_imports(&manifest(id), CALLS, first, INPUT); + Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap() +} + +/// Runs `p` with a bridge that answers every call with `answer` → the run's result and the calls it +/// got. +fn run_with(p: &Plugin, answer: impl Fn(&str) -> Result) -> (vectorcraft_plugins::Result>, Vec<(String, Value)>) { + let mut seen = Vec::new(); + let mut bridge = |id: &str, args: &Value| { + seen.push((id.to_string(), args.clone())); + answer(id) + }; + let (out, _) = p.run_calling(INPUT.as_bytes(), b"{}", p.limits(), &mut bridge); + (out, seen) +} + +#[test] +fn a_call_runs_its_command_and_the_result_is_read_back() { + // The result `{"n":1}` is 7 bytes: a 2-byte buffer gets its length and nothing copied, then a + // larger one gets it, which the run returns as its output. + let run = format!( + "{} {} (if (i32.ne (i32.load8_u (i32.const 0x3000)) (i32.const 0)) (then unreachable)) {} (i64.or (i64.shl (i64.const 7) (i64.const 32)) (i64.const 0x3000))", + expect(&select_all(), 0), + expect("(call $vc_call_result (i32.const 0x3000) (i32.const 2))", 7), + expect("(call $vc_call_result (i32.const 0x3000) (i32.const 64))", 7), + ); + let src = tpl::module(&manifest("test.call.result"), &run, CALLS, 1); + let p = Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap(); + let (out, seen) = run_with(&p, |_| Ok(json!({"n": 1}))); + assert_eq!(out.unwrap(), br#"{"n":1}"#); + assert_eq!(seen, [("select.all".to_string(), json!({"a": 1}))]); + // No bytes of arguments are `{}`; a result buffer outside memory is a code, not a failure. + let p = calling( + "test.call.empty", + &[ + expect("(call $vc_call_result (i32.const 0x3000) (i32.const 64))", CALL_NO_RESULT), + expect(&call("0x2000", "10", "0", "0"), 0), + expect("(call $vc_call_result (i32.const -16) (i32.const 64))", CALL_OUTSIDE_MEMORY), + ] + .concat(), + ); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + assert_eq!(out.unwrap(), INPUT.as_bytes()); + assert_eq!(seen, [("select.all".to_string(), json!({}))]); +} + +/// Each misuse returns its code, and the run fails with an error that names the call, even when the +/// plug-in goes on and returns an output. The host makes no call for any of them. +#[test] +fn a_call_the_host_refuses_fails_the_run_even_when_the_plugin_goes_on() { + let cases = [ + (call("0x2010", "13", "0", "0"), CALL_NOT_ALLOWED, "vc_call `object.delete`: the manifest's `commandAllowlist` doesn't list it"), + (call("0x2000", "10", "0x2200", "1"), CALL_BAD_UTF8, "vc_call `select.all`: the id or the arguments are not UTF-8"), + (call("0x2000", "10", "0x2300", "3"), CALL_BAD_JSON, "vc_call `select.all`: the arguments are not a JSON object"), + (call("0x2000", "10", "0x2100", "3"), CALL_BAD_JSON, "the arguments are not a JSON object"), + (call("0x2000", "10", "-16", "7"), CALL_OUTSIDE_MEMORY, "vc_call `select.all`: the id or the arguments lie outside the module's memory"), + (call("-4", "10", "0", "0"), CALL_OUTSIDE_MEMORY, "vc_call `?`: the id or the arguments lie outside the module's memory"), + (call("0x2000", "200", "0", "0"), CALL_NOT_ALLOWED, "doesn't list it"), + ]; + for (i, (first, code, says)) in cases.into_iter().enumerate() { + let p = calling(&format!("test.call.refused{i}"), &expect(&first, code)); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + let e = out.expect_err(says).to_string(); + assert!(e.contains(says), "{first}: {e}"); + assert!(seen.is_empty(), "{first}"); + } +} + +/// Arguments longer than [`MAX_CALL_DATA`] are refused from their length alone: these 100 MiB start +/// outside memory, and the code is still the size limit. +#[test] +fn oversized_arguments_are_refused_before_they_are_read() { + let p = calling("test.call.huge", &expect(&call("0x2000", "10", "-16", &(100 << 20).to_string()), CALL_LIMIT)); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + let e = out.unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.contains(&format!("104857600 bytes, limit {MAX_CALL_DATA}"))), "{e}"); + assert!(seen.is_empty()); +} + +#[test] +fn a_failed_command_fails_the_run_with_its_reason() { + let p = calling("test.call.failed", &expect(&select_all(), CALL_COMMAND_FAILED)); + let (out, seen) = run_with(&p, |_| Err(CallFailure { code: CALL_COMMAND_FAILED, why: "nothing is selected".into() })); + assert_eq!(out, Err(Error::Failed("vc_call `select.all`: nothing is selected".into()))); + assert_eq!(seen.len(), 1); + // Also when the plug-in traps after it: the call's failure is the one reported. + let p = calling("test.call.failed.trap", &format!("(drop {}) unreachable", select_all())); + let (out, _) = run_with(&p, |_| Err(CallFailure { code: CALL_COMMAND_FAILED, why: "nothing is selected".into() })); + assert_eq!(out, Err(Error::Failed("vc_call `select.all`: nothing is selected".into()))); +} + +/// After the run's first failed call, a plug-in that goes on calling gets [`CALL_NO_CONTEXT`] for +/// each call and the host makes none of them; the run fails with the first call's reason. +#[test] +fn no_call_is_made_after_a_failed_one() { + let rest = [select_all(), select_all(), select_all()].map(|c| expect(&c, CALL_NO_CONTEXT)).concat(); + let p = calling("test.call.after.failed", &format!("{}{rest}", expect(&select_all(), CALL_COMMAND_FAILED))); + let (out, seen) = run_with(&p, |_| Err(CallFailure { code: CALL_COMMAND_FAILED, why: "nothing is selected".into() })); + assert_eq!(out, Err(Error::Failed("vc_call `select.all`: nothing is selected".into()))); + assert_eq!(seen.len(), 1); + // Also after a call the host refused without making it. + let p = calling( + "test.call.after.refused", + &format!("{}{}", expect(&call("0x2010", "13", "0", "0"), CALL_NOT_ALLOWED), expect(&select_all(), CALL_NO_CONTEXT)), + ); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + assert!(out.unwrap_err().to_string().contains("vc_call `object.delete`: the manifest's `commandAllowlist` doesn't list it")); + assert!(seen.is_empty()); +} + +/// A result larger than [`MAX_CALL_DATA`] fails the run, and so do more than [`MAX_CALLS`] calls. +#[test] +fn results_and_calls_are_capped() { + let p = calling("test.call.big", &expect(&select_all(), CALL_LIMIT)); + let (out, _) = run_with(&p, |_| Ok(Value::String("x".repeat(MAX_CALL_DATA)))); + assert!(matches!(out, Err(Error::Limit(ref why)) if why.starts_with("command call size (vc_call `select.all`")), "{out:?}"); + // A result of exactly MAX_CALL_DATA bytes (the string and its two quotes) is kept. + let p = calling("test.call.edge", &expect(&select_all(), 0)); + let (out, _) = run_with(&p, |_| Ok(Value::String("x".repeat(MAX_CALL_DATA - 2)))); + assert_eq!(out.unwrap(), INPUT.as_bytes()); + let many = format!( + "(local $i i32) (loop $l {} (local.set $i (i32.add (local.get $i) (i32.const 1))) (br_if $l (i32.lt_u (local.get $i) (i32.const {MAX_CALLS})))) {}", + expect(&select_all(), 0), + expect(&select_all(), CALL_LIMIT) + ); + let p = calling("test.call.many", &many); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + assert!(matches!(out, Err(Error::Limit(ref why)) if why.starts_with("command calls (")), "{out:?}"); + assert_eq!(seen.len(), MAX_CALLS); +} + +/// Each call costs instructions, so a budget too small for the calls ends the run: 256,000 (the +/// base and the input's share) pays for 25 calls of 10,000 and the loop around them. +#[test] +fn calls_cost_instructions() { + let many = format!("(loop $l {} (br $l))", expect(&select_all(), 0)); + let src = tpl::with_imports(&manifest("test.call.fuel"), CALLS, &many, INPUT); + let p = Plugin::load(&wat::parse_str(&src).unwrap(), Limits { fuel_base: 200_000, ..Limits::default() }).unwrap(); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + assert_eq!(out, Err(Error::Limit("instruction budget".into()))); + assert_eq!(seen.len(), 25); +} + +/// Cancel stops the run at the next call, and what it did is the caller's to undo. +#[test] +fn cancel_stops_a_run_at_its_next_call() { + let p = calling("test.call.cancel", &[expect(&select_all(), 0), expect(&select_all(), 0)].concat()); + let token = vectorcraft_doc::cancel::CancelToken::new(); + let mut calls = 0; + let mut bridge = |_: &str, _: &Value| { + calls += 1; + token.cancel(); + Ok(Value::Null) + }; + let (out, _) = vectorcraft_doc::cancel::scope(&token, None, || p.run_calling(INPUT.as_bytes(), b"{}", p.limits(), &mut bridge)); + assert_eq!(out, Err(Error::Cancelled)); + assert_eq!(calls, 1); +} + +/// Without a bridge (a run that isn't a filter's run on a document), and while the module is being +/// loaded, `vc_call` returns [`CALL_NO_CONTEXT`]; in a run, that fails the run as any failed call +/// does, also when the plug-in goes on. +#[test] +fn without_a_bridge_a_call_returns_no_context() { + let no_context = |out: vectorcraft_plugins::Result>| { + let e = out.unwrap_err(); + assert!(matches!(e, Error::Abi(_)) && e.to_string().contains("no command can be called here"), "{e}"); + }; + // The start function's call gets the code, and the module loads; a run, with a bridge or + // without one, then fails on it, and the bridge is never asked. + let start = format!("(func $start {}) (start $start)", expect(&select_all(), CALL_NO_CONTEXT)); + let src = tpl::with_imports(&manifest("test.call.none"), &format!("{CALLS} {start}"), "", INPUT); + let p = Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap(); + no_context(p.run(INPUT.as_bytes(), b"{}")); + let (out, seen) = run_with(&p, |_| Ok(json!({}))); + no_context(out); + assert!(seen.is_empty()); + // A call from `vc_run` without a bridge. + no_context(calling("test.call.none", &expect(&select_all(), CALL_NO_CONTEXT)).run(INPUT.as_bytes(), b"{}")); +} + +/// A module that imports `vc_call` or `vc_call_result` needs the permission `commands`, which needs +/// `api` 2 and a `commandAllowlist`; only a filter with the usual budget lists one. +#[test] +fn the_call_imports_need_the_commands_permission() { + let import = r#"(import "env" "vc_call_result" (func (param i32 i32) (result i32)))"#; + let without = r#"{"id":"test.call.perm","name":"C","kind":"filter","api":2,"permissions":["doc.read"]}"#; + let e = Plugin::load(&wat::parse_str(tpl::with_imports(without, import, "", INPUT)).unwrap(), Limits::default()).unwrap_err().to_string(); + assert!( + e.contains("imports `env.vc_call_result`, which a plug-in may use only at plug-in API level 2 (`api` 2) and with the permission `commands`"), + "{e}" + ); + for (manifest, says) in [ + (r#"{"id":"a","name":"x","kind":"filter","permissions":["commands"],"commandAllowlist":["select.all"]}"#, "needs plug-in API level 2"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"]}"#, "`commands` needs a `commandAllowlist`"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"commandAllowlist":["select.all"]}"#, "`commandAllowlist` needs the permission `commands`"), + ( + r#"{"id":"a","name":"x","kind":"effect","api":2,"permissions":["doc.read","effect.render","commands"],"commandAllowlist":["select.all"]}"#, + "only a filter with the usual budget", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"budget":"heavy","permissions":["commands"],"commandAllowlist":["select.all"]}"#, + "only a filter with the usual budget", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["select.all","select.all"]}"#, + "names `select.all`", + ), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["select..all"]}"#, "not a command id"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["1select"]}"#, "not a command id"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":[""]}"#, "not a command id"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["select/all"]}"#, "not a command id"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["select\\all"]}"#, "not a command id"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["../select.all"]}"#, "not a command id"), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":[]}"#, + "`commands` needs a `commandAllowlist`", + ), + ] { + let e = Manifest::parse(manifest.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{manifest}: {e}"); + } + let long = format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["{}"]}}"#, "a".repeat(129)); + assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("not a command id")); + let ids: Vec = (0..257).map(|i| format!("\"c{i}\"")).collect(); + let many = format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":[{}]}}"#, ids.join(",")); + assert!(Manifest::parse(many.as_bytes()).unwrap_err().to_string().contains("at most 256 commands")); + let m = Manifest::parse(manifest("test.call.ok").as_bytes()).unwrap(); + assert!(m.allows_call("select.all") && !m.allows_call("select.none")); + assert_eq!(serde_json::to_value(&m).unwrap()["commandAllowlist"], json!(["select.all"])); +} + +/// A small xorshift generator, so the cases are the same on every run. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + + /// Up to `max` random bytes. + fn bytes(&mut self, max: u64) -> Vec { + (0..self.below(max + 1)).map(|_| self.next() as u8).collect() + } + + /// A random JSON value nested at most `depth` deep. + fn json(&mut self, depth: u32) -> Value { + match self.below(if depth == 0 { 4 } else { 6 }) { + 0 => Value::Null, + 1 => Value::Bool(self.below(2) == 0), + 2 => json!((self.next() as i64) >> self.below(64)), + 3 => Value::String(String::from_utf8_lossy(&self.bytes(12)).into_owned()), + 4 => Value::Array((0..self.below(4)).map(|_| self.json(depth - 1)).collect()), + _ => Value::Object((0..self.below(4)).map(|i| (format!("k{i}"), self.json(depth - 1))).collect()), + } + } +} + +/// Any bytes as a call's id and arguments: random bytes, JSON values of every kind, cut-off and +/// corrupted JSON, ids with path characters or a NUL, and arguments of exactly [`MAX_CALL_DATA`] +/// bytes and one byte more. The host makes the call only for a listed id with a JSON object of at +/// most [`MAX_CALL_DATA`] bytes; every other call gets a code and fails the run with an error, and +/// none panics. The plug-in calls with its parameters as the id and its input as the arguments. +#[test] +fn any_bytes_as_a_call_get_a_code() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let ids: [&[u8]; 7] = [b"select.all", b"select.al", b"select.all\0", b"../select.all", b"select/all", b"\xff\xfe", b""]; + let mut cases: Vec<(Vec, Vec)> = Vec::new(); + for i in 0..600 { + let args = match i % 4 { + 0 => rng.bytes(48), + 1 => serde_json::to_vec(&rng.json(3)).unwrap(), + 2 => { + let mut v = serde_json::to_vec(&rng.json(3)).unwrap(); + v.truncate(rng.below(v.len() as u64 + 1) as usize); + v + } + _ => { + let mut v = serde_json::to_vec(&json!({"a": rng.json(3)})).unwrap(); + let at = rng.below(v.len() as u64) as usize; + v[at] = rng.next() as u8; + v + } + }; + let id = if rng.below(3) == 0 { rng.bytes(16) } else { ids[rng.below(ids.len() as u64) as usize].to_vec() }; + cases.push((args, id)); + } + for len in [MAX_CALL_DATA, MAX_CALL_DATA + 1] { + let mut v = br#"{"a":""#.to_vec(); + v.resize(len - 2, b'x'); + v.extend_from_slice(br#""}"#); + cases.push((v, b"select.all".to_vec())); + } + let p = calling("test.call.fuzz", "(drop (call $vc_call (local.get $pp) (local.get $pl) (local.get $in) (local.get $il)))"); + let mut made = 0; + for (args, id) in &cases { + let mut seen = Vec::new(); + let mut bridge = |_: &str, a: &Value| { + seen.push(a.clone()); + Ok(Value::Null) + }; + let (out, _) = p.run_calling(args, id, p.limits(), &mut bridge); + let object = if args.len() > MAX_CALL_DATA { + None + } else if args.is_empty() { + Some(json!({})) + } else { + serde_json::from_slice::(args).ok().filter(Value::is_object) + }; + let shown = String::from_utf8_lossy(&args[..args.len().min(64)]).into_owned(); + match object.filter(|_| id.as_slice() == b"select.all") { + Some(v) => { + assert_eq!(out.as_deref().ok(), Some(INPUT.as_bytes()), "{shown}"); + assert_eq!(seen, [v], "{shown}"); + made += 1; + } + None => { + assert!(seen.is_empty(), "{shown}"); + let e = out.expect_err(&shown); + assert!(matches!(e, Error::Abi(_) | Error::Limit(_)), "{shown}: {e}"); + } + } + } + // Both kinds of case came up: calls made and calls refused. + assert!(made >= 5 && made < cases.len() - 5, "{made} of {}", cases.len()); +} diff --git a/crates/render/src/bounds.rs b/crates/render/src/bounds.rs index 5cb622e5dc..c3aaf98322 100644 --- a/crates/render/src/bounds.rs +++ b/crates/render/src/bounds.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use super::{BezPath, Document, FillRule, Node, NodeKind, Rect, SymbolBoxes, brush_fx, fx}; /// Bounds of everything `n` paints, as the renderer culls it: its members, strokes, brush art and @@ -13,12 +15,39 @@ pub fn painted_bounds(doc: &Document, n: &Node) -> Option { /// out the transparent source art of a Shaper group as [`Node::visual_bounds_with`] does. Symbol /// instances are measured by their art in `symbols`. pub fn effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { + effect_bounds_with(symbols, n, None, None) +} + +impl crate::Renderer { + /// [`effect_bounds`] of `n`, its 3D art measured as this renderer draws and keeps it + /// (`Renderer::bounds_of`): a pass that measures the same objects again, over each + /// artboard of an export, builds each solid once. What it keeps is measured with the symbol + /// boxes it was first measured with, and found by the objects' addresses: give each document, + /// and each kind of `symbols`, its own renderer. + pub fn effect_bounds(&mut self, symbols: &SymbolBoxes, n: &Arc) -> Option { + effect_bounds_with(symbols, n, Some(n), Some(self)) + } +} + +/// [`effect_bounds`] of `n` (`held`: `n` as held in its document, which `renderer` keeps what it +/// measures by). Through `renderer`, an object is measured once for every artboard it measures: +/// those it measures as [`effect_bounds`] does (`Renderer::bounds_of`), those whose +/// brushed strokes it leaves room for afresh. +pub(crate) fn effect_bounds_with( + symbols: &SymbolBoxes, + n: &Node, + held: Option<&Arc>, + mut renderer: Option<&mut crate::Renderer>, +) -> Option { match &n.kind { NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } if !fx::has_object_fx(n) => children .iter() .skip(usize::from(n.extras().shaper.is_some())) - .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, effect_bounds(symbols, c))), - _ => fx::cull_bounds(symbols, n), + .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, effect_bounds_with(symbols, c, Some(c), renderer.as_deref_mut()))), + _ => match (renderer, held) { + (Some(r), Some(a)) if brush_fx::pad(symbols, a) == 0.0 => r.bounds_of(symbols, a), + _ => fx::cull_bounds(symbols, n), + }, } } diff --git a/crates/render/src/brush_fx.rs b/crates/render/src/brush_fx.rs index f412d7249c..2b724f2805 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -115,6 +115,13 @@ impl BrushCache { self.library(doc, stamp); self.key } + + /// [`Self::library_key`] checked now, between frames: `doc` may be the document of the last + /// frame, edited in place. + pub(crate) fn library_key_now(&mut self, doc: &Document, stamp: u64) -> u64 { + self.checked = (u64::MAX, 0); + self.library_key(doc, stamp) + } } /// Cull bounds that allow for brush art reaching past the stroke (scatter, wide nibs), symbol diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index 01fd6da015..1c15247034 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -4,7 +4,7 @@ use std::collections::HashSet; use std::sync::Arc; -use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, SymbolBoxes}; use vectorcraft_geom::{Affine, Rect}; /// What may draw differently in a document than in its version before an edit ([`changed`]). @@ -82,10 +82,44 @@ fn add_placed(symbols: &SymbolBoxes, n: &Node, files: &HashSet, area: &m /// art also draws in the copies round it). Objects that an edit doesn't touch /// keep their identity, so this costs what changed, not the size of the document. pub fn changed(old: &Document, new: &Document) -> Changed { + changed_with(old, new, None, &crate::RenderOptions::default()) +} + +impl crate::Renderer { + /// [`changed`], measured through this renderer (`Renderer::bounds_of`): what it drew of `old` + /// it measured to draw it, and what it measures of `new`, a 3D effect's art included, it holds + /// to draw that with `opts`; the objects `opts` leaves out (hidden, templates and guides the + /// view hides, the instance a symbol is edited from) draw nothing. The view that drew `old` + /// with this renderer and `opts` asks this. With Overprint Preview or Separations Preview the + /// renderer draws copies of the objects (`proof::prepare`), so they are measured afresh and + /// nothing is held. + pub fn changed(&mut self, old: &Document, new: &Document, opts: &crate::RenderOptions) -> Changed { + let renderer = (!crate::proof::overprints(opts)).then_some(self); + changed_with(old, new, renderer, opts) + } + + /// Let go of the art made to measure objects ([`crate::Renderer::changed`]) and held for this + /// renderer to draw them: another one draws the frame. + pub fn let_go_of_measured(&mut self) { + self.measured.clear(); + self.measured_bytes = 0; + self.pass_bounds.clear(); + self.three_d_bounds.retain(|_, e| e.0.strong_count() > 0); + self.three_d_kept = self.three_d_bounds.len(); + } + + /// The bytes of the art made to measure objects that this renderer holds to draw them + /// ([`crate::Renderer::changed`]). + pub fn measured_bytes(&self) -> usize { + self.measured_bytes + } +} + +fn changed_with(old: &Document, new: &Document, renderer: Option<&mut crate::Renderer>, opts: &crate::RenderOptions) -> Changed { if new.pattern_edit.is_some() || !old.same_outside_layers(new) { return Changed::Everything; } - let mut diff = Diff { old: old.symbol_boxes(), new: new.symbol_boxes(), area: None }; + let mut diff = Diff { old: old.symbol_boxes(), new: new.symbol_boxes(), area: None, renderer, opts, sources: (None, None) }; diff.children(&old.layers, &new.layers); diff.area.map_or(Changed::Nothing, Changed::Area) } @@ -102,14 +136,20 @@ pub fn view_pixels(area: Rect, view: Affine, w: u32, h: u32) -> Option<[u32; 4]> (x1 > x0 && y1 > y0).then_some([x0 as u32, y0 as u32, x1 as u32, y1 as u32]) } -/// [`changed`] in progress: the symbols' boxes of both versions, and the area so far. -struct Diff<'a> { +/// [`changed`] in progress: the symbols' boxes of both versions, the area so far, the renderer +/// that measures, if any (else each object is measured afresh), the options of the frames it +/// measures for, and the hidden source image, in each version, of the Image Trace object whose +/// members it compares. +struct Diff<'a, 'r> { old: SymbolBoxes<'a>, new: SymbolBoxes<'a>, area: Option, + renderer: Option<&'r mut crate::Renderer>, + opts: &'r crate::RenderOptions, + sources: (Option, Option), } -impl Diff<'_> { +impl Diff<'_, '_> { /// Members in the same order compare one by one. Members added, removed or restacked count /// before and after, except those that kept their place unchanged. fn children(&mut self, old: &[Arc], new: &[Arc]) { @@ -123,8 +163,8 @@ impl Diff<'_> { match (old.get(i), new.get(i)) { (Some(a), Some(b)) if Arc::ptr_eq(a, b) => {} (a, b) => { - self.add_old(a.map(|a| &**a)); - self.add_new(b.map(|b| &**b)); + self.add_old(a); + self.add_new(b); } } } @@ -135,20 +175,25 @@ impl Diff<'_> { /// only had anchors moved changed around them ([`moved_anchors`]). Any other object that /// changed counts whole, before and after. fn node(&mut self, old: &Arc, new: &Arc) { - if Arc::ptr_eq(old, new) { + if Arc::ptr_eq(old, new) || self.unseen(Side::Old, old) && self.unseen(Side::New, new) { return; } if let (Some(a), Some(b)) = (members(old), members(new)) && same_but_members(old, new) { + // An Image Trace object draws its hidden source image, its first member, in some views. + // Each version's own: an edit can put another member first (undoing Send to Back). + let first = |n: &Node, m: &[Arc]| n.extras().trace.is_some().then(|| m.first().map(|s| s.id)).flatten(); + let outer = std::mem::replace(&mut self.sources, (first(old, a), first(new, b))); self.children(a, b); + self.sources = outer; } else if let Some((area, moved, anchors)) = moved_anchors(old, new) { if moved <= FEW_MOVED && anchors >= MANY_ANCHORS { self.add(area); } else { // The object's box before and after holds every pixel that changed too, and so // does where the two overlap. - let whole = vectorcraft_geom::union_opt(crate::brush_fx::cull_bounds(&self.old, old), crate::brush_fx::cull_bounds(&self.new, new)); + let whole = vectorcraft_geom::union_opt(self.bounds(Side::Old, old), self.bounds(Side::New, new)); self.add(area.zip(whole).map(|(a, w)| a.intersect(w))); } } else { @@ -157,12 +202,42 @@ impl Diff<'_> { } } - fn add_old(&mut self, n: Option<&Node>) { - self.add(n.and_then(|n| crate::brush_fx::cull_bounds(&self.old, n))); + /// Does `n` of the `side` version draw nothing, as the renderer leaves it out + /// (`node_checks::left_out`)? The source image of an Image Trace object draws in some views. + /// The members of a group or layer left out are never compared ([`Self::node`]). + fn unseen(&self, side: Side, n: &Node) -> bool { + let (doc, source) = match side { + Side::Old => (self.old.document(), self.sources.0), + Side::New => (self.new.document(), self.sources.1), + }; + source != Some(n.id) && crate::node_checks::left_out(self.opts, doc, n) } - fn add_new(&mut self, n: Option<&Node>) { - self.add(n.and_then(|n| crate::brush_fx::cull_bounds(&self.new, n))); + /// The cull bounds of `n` of the `side` version, through the renderer when there is one; + /// `None` when it draws nothing ([`Self::unseen`]), as nothing is measured to draw it. + fn bounds(&mut self, side: Side, n: &Arc) -> Option { + if self.unseen(side, n) { + return None; + } + let Diff { old, new, renderer, .. } = self; + let symbols = match side { + Side::Old => old, + Side::New => new, + }; + match renderer { + Some(r) => r.bounds_of(symbols, n), + None => crate::brush_fx::cull_bounds(symbols, n), + } + } + + fn add_old(&mut self, n: Option<&Arc>) { + let b = n.and_then(|n| self.bounds(Side::Old, n)); + self.add(b); + } + + fn add_new(&mut self, n: Option<&Arc>) { + let b = n.and_then(|n| self.bounds(Side::New, n)); + self.add(b); } fn add(&mut self, r: Option) { @@ -170,6 +245,13 @@ impl Diff<'_> { } } +/// Which version of the document [`Diff`] measures an object of. +#[derive(Clone, Copy)] +enum Side { + Old, + New, +} + /// The members of a group or layer whose members draw each on their own: no clipping mask, and no /// effects of its own. fn members(n: &Node) -> Option<&[Arc]> { diff --git a/crates/render/src/encode.rs b/crates/render/src/encode.rs index db5e3b74ff..201931a8ac 100644 --- a/crates/render/src/encode.rs +++ b/crates/render/src/encode.rs @@ -205,18 +205,32 @@ pub fn art_bounds(doc: &Document) -> Option { /// object of a layer or sublayer whose drawn bounds overlap `rect`, with all of its bounds; a group /// or a clipping layer counts as one object. `None` when no object overlaps `rect`. pub fn art_bounds_on(doc: &Document, rect: Rect) -> Option { + art_bounds_on_with(doc, rect, None) +} + +impl crate::Renderer { + /// [`art_bounds_on`], its 3D art measured as this renderer draws and keeps it + /// (`Renderer::bounds_of`): a pass over each artboard builds each solid once. What it + /// keeps is measured with the document's symbol boxes as it first measured them, and found by + /// the objects' addresses: give each document its own renderer. + pub fn art_bounds_on(&mut self, doc: &Document, rect: Rect) -> Option { + art_bounds_on_with(doc, rect, Some(self)) + } +} + +fn art_bounds_on_with(doc: &Document, rect: Rect, mut renderer: Option<&mut crate::Renderer>) -> Option { // Art flush with an edge from outside can overlap it by a rounding error (#1295). let rect = rect.inflate(-1e-6, -1e-6); - fn on(symbols: &SymbolBoxes, n: &Node, rect: Rect) -> Option { + fn on(symbols: &SymbolBoxes, n: &Arc, rect: Rect, mut renderer: Option<&mut crate::Renderer>) -> Option { match &n.kind { NodeKind::Layer { template: false, clip: false, children, .. } if n.visible => { - children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, on(symbols, c, rect))) + children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, on(symbols, c, rect, renderer.as_deref_mut()))) } - _ => drawn_bounds(symbols, n).filter(|b| b.x0 < rect.x1 && b.x1 > rect.x0 && b.y0 < rect.y1 && b.y1 > rect.y0), + _ => drawn_bounds_with(symbols, n, Some(n), renderer).filter(|b| b.x0 < rect.x1 && b.x1 > rect.x0 && b.y0 < rect.y1 && b.y1 > rect.y0), } } let symbols = doc.symbol_boxes(); - doc.layers.iter().fold(None, |acc, l| vectorcraft_geom::union_opt(acc, on(&symbols, l, rect))) + doc.layers.iter().fold(None, |acc, l| vectorcraft_geom::union_opt(acc, on(&symbols, l, rect, renderer.as_deref_mut()))) } /// Bounds of what an export draws of object `n` ([`art_bounds`]): `None` when `n` is hidden, a @@ -224,6 +238,12 @@ pub fn art_bounds_on(doc: &Document, rect: Rect) -> Option { /// except in a group or layer with effects of its own that keep all its members (`without_undrawn` /// lists them). Symbol instances are measured by their art in `symbols`. pub fn drawn_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { + drawn_bounds_with(symbols, n, None, None) +} + +/// [`drawn_bounds`] of `n` (`held`: `n` as held in its document, which `renderer` keeps what it +/// measures by). +fn drawn_bounds_with(symbols: &SymbolBoxes, n: &Node, held: Option<&Arc>, mut renderer: Option<&mut crate::Renderer>) -> Option { if !n.visible { return None; } @@ -232,8 +252,23 @@ pub fn drawn_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } if !fx::has_object_fx(n) => children .iter() .skip(usize::from(n.extras().shaper.is_some())) - .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, drawn_bounds(symbols, c))), - _ => crate::effect_bounds(symbols, without_undrawn(n).as_ref().unwrap_or(n)), + .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, drawn_bounds_with(symbols, c, Some(c), renderer.as_deref_mut()))), + _ => match (without_undrawn(n), held, renderer) { + // A new object, measured once a pass by the one it was made from. + (Some(kept), Some(a), Some(r)) => { + let key = Arc::as_ptr(a) as usize; + if let Some((node, b)) = r.pass_bounds.get(&key) + && Arc::ptr_eq(node, a) + { + return *b; + } + let b = crate::bounds::effect_bounds_with(symbols, &kept, None, Some(r)); + r.pass_bounds.insert(key, (a.clone(), b)); + b + } + (Some(kept), _, renderer) => crate::bounds::effect_bounds_with(symbols, &kept, None, renderer), + (None, held, renderer) => crate::bounds::effect_bounds_with(symbols, n, held, renderer), + }, } } diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 326a8c18e9..e16f134aca 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -174,6 +174,12 @@ pub struct FrameStats { /// ([`Renderer::draw_type_edges`]). Type drawn from the pixels an earlier frame kept is not /// counted. pub type_edges: usize, + /// The art of 3D effects (Revolve, Extrude & Bevel, Inflate, Rotate) this renderer made for the + /// objects it draws or measures itself (`Renderer::bounds_of`) since its last frame + /// began: none it found kept, and none made by measures without a renderer (the free bounds + /// functions), which this renderer doesn't see. A view that measured what changed through the + /// renderer ([`crate::Renderer::changed`]) made the art then, and draws it with none made. + pub three_d_built: usize, pub micros: u64, } diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index bb944559e5..a337616329 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -70,7 +70,7 @@ mod renderer; #[cfg(test)] pub(crate) use bounds::visual_bounds; -pub(crate) use bounds::{cull_bounds, drawn_outline, drawn_outlines, painted_reach, path_cull_bounds}; +pub(crate) use bounds::{cull_bounds, drawn_outline, drawn_outlines, painted_reach, path_cull_bounds, three_d_art_bounds, with_own_raster_reach}; #[cfg(test)] pub(crate) use entries::Drawn; pub(crate) use entries::{DocInputs, FxGeom, Inputs, Reads, ShadowEntry}; diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 8ad62cf4ce..9d5e9c0d1a 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -57,12 +57,6 @@ pub(super) fn item_effects(item: &AppearanceItem) -> &[Effect] { /// Visual bounds including geometry effects, stroke outsets and shadows/glows (symbol instances /// measured by their art from `symbols`). pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { - if let Some(art) = effects::revolve_art(n).or_else(|| effects::solid_art(n)) { - return cull_bounds(symbols, &art).map(|b| { - let o = outset(symbols, &n.appearance.effects, b); - b.inflate(o, o) - }); - } if let Some(art) = painted_art(symbols, n) { return art.visual_bounds_with(symbols).map(|r| with_raster_reach(symbols, n, r)); } @@ -109,6 +103,10 @@ fn paints(item: &AppearanceItem) -> bool { /// [`Node::visual_bounds_with`] measures them, without the reach of `n`'s own raster effects /// (symbol instances measured by their art from `symbols`): what Rasterize makes its image over. pub(crate) fn drawn_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { + // A 3D effect's art holds its fills' and strokes' raster effects, measured with it. + if let Some(b) = three_d_bounds(symbols, n) { + return b; + } let b = art_bounds(symbols, n)?; let items = n.appearance.items.iter().filter(|i| paints(i) && !effects::raster_effects(item_effects(i)).is_empty()); Some(items.map(|i| spread(symbols, item_effects(i), item_bounds(symbols.document(), n, i).unwrap_or(b))).fold(b, |acc, r| acc.union(r))) @@ -168,13 +166,6 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { members.iter().filter(|c| c.visible).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, painted_reach(symbols, c))) }; match &n.kind { - // A group's or layer's 3D effect: the art of its members' solids. - NodeKind::Layer { .. } | NodeKind::Group { clip: false, .. } - if effects::has_solid(n) - && let Some(art) = effects::solid_art(n) => - { - drawn_bounds(symbols, &art) - } _ if effects::has_container_appearance(n) => { let art = effects::evaluate_container(Some(symbols.document()), n); let art = art.as_ref().unwrap_or(n); @@ -182,10 +173,6 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { } NodeKind::Layer { clip: false, .. } | NodeKind::Group { clip: false, .. } => union(n), _ if has_fx(n) => { - // A 3D effect's art. - if let Some(art) = effects::revolve_art(n).or_else(|| effects::solid_art(n)) { - return drawn_bounds(symbols, &art); - } if let Some(art) = painted_art(symbols, n) { return art.visual_bounds_with(symbols); } @@ -221,7 +208,7 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { Some(r) => r.visual_bounds_with(symbols), None => None, } - .or_else(|| n.visual_bounds_with(symbols))?; + .or_else(|| own_box(symbols, n))?; let a = match &reshaped { Some(r) => reshaped_art_effects_reach(symbols, n, r), None => art_effects_reach(symbols, n), @@ -385,6 +372,13 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool) -> Optio let reach = effects::addons::halftone::reach(n); inner(&effects::addons::halftone::split(n).0).map(|b| b.inflate(reach, reach)) } + // A 3D effect's art, as the renderer draws it, and the raster effects' reach: the solid of + // type or of a group's members reaches past the letters or members the arms below measure. + _ if (effects::has_revolve(n) || effects::has_solid(n)) + && let Some(b) = three_d_bounds(symbols, n) => + { + b.map(|b| with_own_raster_reach(symbols, n, b)) + } // The evaluated art (its fills, strokes and geometry effects) and the raster effects' reach. _ if effects::has_container_appearance(n) => { let art = effects::evaluate_container(Some(symbols.document()), n); @@ -394,8 +388,7 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool) -> Optio } else { art.children()?.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, inner(c))) }?; - let o = outset(symbols, &n.appearance.effects, b); - Some(b.inflate(o, o)) + Some(with_own_raster_reach(symbols, n, b)) } NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, inner(c))) @@ -418,15 +411,14 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool) -> Optio Some(r) => r.visual_bounds_with(symbols), None => None, } - .or_else(|| n.visual_bounds_with(symbols))?; + .or_else(|| own_box(symbols, n))?; let a = match &reshaped { Some(r) if after_reshape => reshaped_art_effects_reach(symbols, n, r), _ => art_effects_reach(symbols, n), }; let a = a.max(live_content_reach(symbols, n)); let b = b.inflate(a, a); - let o = outset(symbols, &n.appearance.effects, b); - Some(b.inflate(o, o)) + Some(with_own_raster_reach(symbols, n, b)) } NodeKind::SymbolInstance { .. } => { let b = n.visual_bounds_with(symbols)?; @@ -445,6 +437,62 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool) -> Optio } } +/// The bounds of the art a 3D effect of `n` draws (Revolve, Extrude & Bevel, Inflate, Rotate), +/// built now, without `n`'s own raster effects ([`three_d_art_bounds`]): `None` when it draws no +/// such art, `Some(None)` when that art paints nothing. The renderer measures the art it keeps +/// instead ([`crate::Renderer::bounds_of`]). +fn three_d_bounds(symbols: &SymbolBoxes, n: &Node) -> Option> { + if !effects::has_revolve(n) && !effects::has_solid(n) { + return None; + } + let doc = Some(symbols.document()); + let art = effects::revolve_art_in(doc, n).or_else(|| effects::solid_art_in(doc, n))?; + Some(three_d_art_bounds(symbols, &art)) +} + +/// The bounds of `art`, the art a 3D effect draws for an object, as the renderer draws it: with +/// its geometry effects, without the raster effects the object paints over it (which +/// [`with_own_raster_reach`] adds), and each object in it with the raster effects of its own fills +/// and strokes and the art of its brushed strokes (a stroke without a 3D effect of its own keeps +/// its brush): the art itself, which Rasterize and exports take, not the room culling leaves. +pub(crate) fn three_d_art_bounds(symbols: &SymbolBoxes, art: &Node) -> Option { + fn pieces(symbols: &SymbolBoxes, n: &Node) -> Option { + match &n.kind { + NodeKind::Group { children, clip: false } if !has_object_fx(n) => { + children.iter().filter(|c| c.visible).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, pieces(symbols, c))) + } + // The art its brushed strokes draw, not the room culling leaves for it. + _ => { + let brushed = vectorcraft_brush::has_brush(n) + .then(|| vectorcraft_brush::expand(symbols.document(), n)) + .flatten() + .and_then(|art| art.visual_bounds_with(symbols)); + vectorcraft_geom::union_opt(cull_bounds(symbols, n), brushed) + } + } + } + let mut art = art.clone(); + art.appearance.effects.retain(|e| effects::is_geometry(&e.id)); + let art = effects::evaluate_container(Some(symbols.document()), &art).unwrap_or(art); + pieces(symbols, &art) +} + +/// `b`, the bounds of what `n` draws, grown by how far `n`'s own raster effects paint past it. +pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) -> Rect { + let o = outset(symbols, &n.appearance.effects, b); + b.inflate(o, o) +} + +/// `n`'s own visual box, type's grown to hold its glyphs ([`glyphs_box`]): what it draws when its +/// object effects leave it as it is (Revolve builds no art from type). +fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { + let b = n.visual_bounds_with(symbols)?; + Some(match &n.kind { + NodeKind::Text(t) => vectorcraft_geom::union_opt(Some(b), glyphs_box(t, n.appearance.outset())).unwrap_or(b), + _ => b, + }) +} + /// The box of type `t`'s glyphs as laid out (its layout bounds, else laid out now), grown by its /// characters' strokes, miter spikes included, and by `outset`: on a path they stand above it and /// run past its ends, in an area they can hang past its frame, where its own box diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index ee09114643..e9aa8486d8 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -6,8 +6,8 @@ use super::raster::{ shade_filter, shadow_filter, silhouette, }; use super::{ - Affine, Arc, BezPath, FillRule, Frame, GeomContext, Ink, Node, NodeKind, RasterFx, Rect, RenderContext, Renderer, Shape, Vec2, blend_mode, - effects, fill_rule, peniko, + Affine, Arc, BezPath, FillRule, Frame, GeomContext, Ink, Node, NodeKind, RasterFx, Rect, RenderContext, Renderer, Shape, SymbolBoxes, Vec2, + blend_mode, effects, fill_rule, peniko, }; #[cfg(test)] @@ -437,7 +437,13 @@ impl Renderer { let region = if clipped { self.clip_of(&art) } else { None }; // A symbol's art can change while the instance doesn't: no cached shadows. let cache = (cache && !matches!(a.kind, NodeKind::SymbolInstance { .. })).then_some(0); - let bounds = rasterize_bounds(f.symbols, a, &rfx); + // A 3D effect's art is in hand: Rasterize takes its bounds, measured once while it is + // kept, without building it again. + let rasterizes = rfx.iter().any(|x| matches!(x, RasterFx::Rasterize(_))); + let bounds = match rasterizes.then(|| self.three_d_art_bounds(f.symbols, &art)).flatten() { + Some(b) => b, + None => rasterize_bounds(f.symbols, a, &rfx), + }; let reach = bounds.map_or(reach, |b| reach.union(b)); let content = Content { node: a, owner: Some(a), cache, reach, outline: region.as_deref().map(|r| (&r.0, r.1)), bounds, kept: None }; self.raster_fx(ctx, f, &content, &rfx, &mut |r, c, fr| r.draw_fx_art(c, fr, a, &art)); @@ -487,6 +493,91 @@ impl Renderer { { return art; } + // Made to measure it ([`Self::measured_fx_art`]): taken out, and kept in `fx_arts` from now + // on if made from what it reads now, else made again. + let measured = self.measured.remove(&key).filter(|m| Arc::ptr_eq(&m.0, a)).map(|m| { + self.measured_bytes = self.measured_bytes.saturating_sub(crate::lru::node_bytes(&m.1)); + (m.1, m.2) + }); + let art = match measured { + Some((art, was)) => { + let now = match &found { + Some(f) => Some(f.0), + None => self.outside_key(doc, a), + }; + if was == now { art } else { self.make_fx_art(doc, a) } + } + None => self.make_fx_art(doc, a), + }; + if cache { + let bytes = crate::lru::node_bytes(&art); + self.fx_arts.insert(key, (a.clone(), art.clone(), found), bytes, self.stamp); + } + art + } + + /// The art [`Self::fx_art`] draws for `a`, to measure it: the art kept for it, else made now and + /// held until the frame ends ([`Renderer::measured`]), for [`Self::fx_art`] to keep if `a` is + /// drawn. What is measured but never drawn (culled, off the view) is let go, and isn't kept in + /// place of what is drawn. + pub(crate) fn measured_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc) -> Arc { + let key = Arc::as_ptr(a) as usize; + if let Some((node, art, found)) = self.fx_arts.get(&key, self.stamp) + && Arc::ptr_eq(node, a) + { + let (art, was) = (art.clone(), found.as_ref().map(|f| f.0)); + if was.is_none_or(|was| self.live_found(doc, a).0 == was) { + return art; + } + } + let now = self.outside_key(doc, a); + if let Some((node, art, was)) = self.measured.get(&key) + && Arc::ptr_eq(node, a) + && *was == now + { + return art.clone(); + } + let art = self.make_fx_art(doc, a); + // Art held for an object before (made from what it read then) gives way. + if let Some(old) = self.measured.remove(&key) { + self.measured_bytes = self.measured_bytes.saturating_sub(crate::lru::node_bytes(&old.1)); + } + let bytes = crate::lru::node_bytes(&art); + // Within a budget: past it, what is measured is made again to draw it. + if self.measured_bytes + bytes <= self.measured_budget { + self.measured_bytes += bytes; + self.measured.insert(key, (a.clone(), art.clone(), now)); + } + art + } + + /// The bounds of `art`, art [`Self::fx_art`] made for an object, when it is a 3D effect's art + /// ([`super::three_d_art_bounds`]), measured once while it is kept; `None` for any other art. + pub(crate) fn three_d_art_bounds(&mut self, symbols: &SymbolBoxes, art: &Arc) -> Option> { + let key = Arc::as_ptr(art) as usize; + // Raster effects in the art spread by the resolution; brushed strokes in it draw from the + // brushes. + let at = (super::raster::doc_raster_ppi(symbols.document()).to_bits(), self.brushes.library_key(symbols.document(), self.stamp)); + let (kept, measured) = + self.three_d_bounds.get(&key).filter(|e| std::ptr::eq(e.0.as_ptr(), Arc::as_ptr(art))).map(|e| (true, e.1.filter(|m| m.0 == at)))?; + if let (true, Some((_, b))) = (kept, measured) { + return Some(b); + } + let b = super::three_d_art_bounds(symbols, art); + self.three_d_bounds.insert(key, (Arc::downgrade(art), Some((at, b)))); + Some(b) + } + + /// The key of what `a`'s art reads from outside it ([`Self::live_found`]), `None` when it reads + /// nothing. + fn outside_key(&mut self, doc: &vectorcraft_doc::Document, a: &Arc) -> Option { + (evaluates_live(a) || reads_outside(a)).then(|| self.live_found(doc, a).0) + } + + /// The art [`Self::fx_art`] draws for `a`, made now. + fn make_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc) -> Arc { + // Whether the art is a 3D effect's ([`Self::three_d_art_bounds`]). + let mut three_d = false; let symbol = match &a.kind { NodeKind::SymbolInstance { symbol, .. } => { doc.symbols.iter().find(|s| s.name == *symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)) @@ -496,8 +587,12 @@ impl Renderer { let container = is_container(a); let art = match effects::crop_marks_art(a) .or_else(|| crate::addons::halftone::art(doc, a)) - .or_else(|| effects::revolve_art(a)) - .or_else(|| effects::solid_art(a)) + .or_else(|| { + let art = effects::revolve_art_in(Some(doc), a).or_else(|| effects::solid_art_in(Some(doc), a)); + self.stats.three_d_built += usize::from(art.is_some()); + three_d |= art.is_some(); + art + }) .or_else(|| effects::reshape(Some(doc), a, symbol.as_ref())) { Some(r) => r, @@ -505,7 +600,16 @@ impl Renderer { None if matches!(a.kind, NodeKind::Text(_) | NodeKind::Image(_) | NodeKind::Path { .. } | NodeKind::Compound { .. }) => (**a).clone(), None => effects::outline_art(Some(doc), a, symbol.as_ref()).unwrap_or_else(|| Node::group(a.id, vec![])), }; - let art = if effects::has_revolve(a) || effects::has_solid(a) { effects::evaluate_container(Some(doc), &art).unwrap_or(art) } else { art }; + let has_three_d = effects::has_revolve(a) || effects::has_solid(a); + let mut art = if has_three_d { effects::evaluate_container(Some(doc), &art).unwrap_or(art) } else { art }; + // A 3D effect on a fill or stroke that built nothing (Revolve after Roughen, a solid too + // complex) draws the item as without it: left in the art, it would draw the art as an + // object with effects again, and that art again, without end. + if has_three_d && !three_d && !container { + for item in &mut art.appearance.items { + item.effects_mut().retain(|e| !effects::is_three_d(&e.id)); + } + } // Vector Halftone samples the object with its colour adjustments: its dots keep their inks. let outer = if effects::addons::halftone::has_halftone(a) { None } else { effects::color_map(&a.appearance.effects) }; let mut art = self.adjusted_art(doc, art, outer.as_ref()); @@ -520,9 +624,18 @@ impl Renderer { // knockout setting says). art.knockout = if container { a.knockout } else { vectorcraft_doc::Knockout::Off }; let art = Arc::new(art); - if cache { - let bytes = crate::lru::node_bytes(&art); - self.fx_arts.insert(key, (a.clone(), art.clone(), found), bytes, self.stamp); + if three_d { + // A renderer that only measures (an export, Fit to Artwork Bounds) ends no frame: what + // it no longer holds is let go here too. + if self.three_d_bounds.len() >= (2 * self.three_d_kept).max(1024) { + self.three_d_bounds.retain(|_, e| e.0.strong_count() > 0); + self.three_d_kept = self.three_d_bounds.len(); + #[cfg(test)] + { + self.three_d_sweeps += 1; + } + } + self.three_d_bounds.insert(Arc::as_ptr(&art) as usize, (Arc::downgrade(&art), None)); } art } diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index a2b8473ac1..c03a6cc0f3 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1,7 +1,9 @@ +use std::sync::Arc; + use serde_json::json; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Effect, Node}; -use vectorcraft_geom::{Affine, Rect, shapes}; +use vectorcraft_geom::{Affine, Point, Rect, shapes}; use super::{DRAG_PIXEL_BUDGET, Drawn, PIXEL_BUDGET, drag_scale, filter_region, filter_region_within, pan_margin}; use crate::tests_fontchange::{fonts_steady, with_fonts_unchanged}; @@ -182,8 +184,8 @@ fn shadow_rasters_keep_their_node_and_a_byte_budget() { /// kept for any pan: its grid starts at the reach's first whole device pixel, which a pan by whole /// pixels moves with the art, so the raster drawn after the pan is the one a fresh renderer makes, /// also for pans that aren't multiples of the raster's scale. A pan by a fraction of a pixel -/// places the raster at the nearest whole pixel, as a full-size raster kept whole is placed, and -/// here draws as a fresh renderer draws too. A 100 pt glow at 500% (scale 2) and a 2 pt glow +/// keeps the raster and places it at the nearest whole pixel, as a full-size raster kept whole is +/// placed. A 100 pt glow at 500% (scale 2) and a 2 pt glow /// round the page at 800% (scale 3, near the narrowest blur made coarser). #[test] fn a_coarser_glow_kept_whole_draws_after_a_pan_as_made_again() { @@ -210,7 +212,22 @@ fn a_coarser_glow_kept_whole_draws_after_a_pan_as_made_again() { assert_eq!(image(&r), kept, "blur {blur}, pan {pan:?}: the raster kept is drawn"); let mut fresh = Renderer::new(); fresh.threads = 2; - assert!(panned.pixels == fresh.render(&d, size.0, size.1, xf, &opts).pixels, "blur {blur}, pan {pan:?}"); + if pan.0.fract() == 0.0 && pan.1.fract() == 0.0 { + assert!(panned.pixels == fresh.render(&d, size.0, size.1, xf, &opts).pixels, "blur {blur}, pan {pan:?}"); + } else { + // Right of the rectangle's soft edge the frame holds only the glow, which the kept raster + // places at the whole pixel nearest the pan, where a fresh render draws it too. A pan of + // half a pixel is as near to the pixels on both sides, so either one is accepted. + let right = (xf * Point::new(rect.x1, rect.y0)).x.ceil() as usize + 3; + let row = size.0 as usize * 4; + let glow = |p: &[u8]| p.chunks(row).flat_map(|r| r[right * 4..].to_vec()).collect::>(); + let nearest = |v: f64| if (v - v.trunc()).abs() == 0.5 { vec![v.floor(), v.ceil()] } else { vec![v.round()] }; + let found = nearest(pan.0).into_iter().flat_map(|x| nearest(pan.1).into_iter().map(move |y| (x, y))).any(|whole| { + let at = Affine::translate(whole) * base; + glow(&panned.pixels) == glow(&fresh.render(&d, size.0, size.1, at, &opts).pixels) + }); + assert!(found, "blur {blur}, pan {pan:?}: the glow is drawn at the whole pixel nearest the pan"); + } } } } @@ -541,6 +558,698 @@ fn visual_bounds_include_shadow() { assert!(b.x1 >= 10.0 + 7.0 + 7.5 - 1e-9); } +/// A shadow after a 3D effect reaches as far past the solid as it says, once: the solid's art keeps +/// the raster effects that follow the 3D effect, and the object paints them over that art. +#[test] +fn a_shadow_after_a_3d_effect_reaches_past_the_solid_once() { + let r = Rect::new(40.0, 40.0, 60.0, 60.0); + let extrude = ("threeD.extrude", json!({"depth": 20.0, "position": "isometricTop"})); + let shadow = ("stylize.dropShadow", json!({"x": 20, "y": 0, "blur": 0})); + let measure = |d: &Document| super::cull_bounds(&d.symbol_boxes(), &d.layers[0].children().unwrap()[0]).unwrap(); + let solid = measure(&doc_with(r, Color::BLACK, vec![extrude.clone()])); + let shadowed = measure(&doc_with(r, Color::BLACK, vec![extrude, shadow])); + assert_eq!(shadowed.union(solid), shadowed); + let grown = [solid.x0 - shadowed.x0, solid.y0 - shadowed.y0, shadowed.x1 - solid.x1, shadowed.y1 - solid.y1]; + assert!(grown.iter().all(|g| *g <= 20.0 + 1e-6) && grown.iter().any(|g| *g >= 20.0 - 1e-6), "{solid:?} {shadowed:?}"); +} + +/// Revolve builds no art from type: the type draws its glyphs, and its bounds hold them. +#[test] +fn revolved_type_is_measured_by_the_glyphs_it_draws() { + use vectorcraft_doc::NodeKind; + use vectorcraft_doc::text::{CharStyle, TextObject}; + let _fonts = fonts_steady(); + let mut d = Document::new(100.0, 100.0); + let style = CharStyle { size: 30.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "KW", style)))); + n.appearance.effects = vec![Effect { id: "threeD.revolve".into(), params: json!({}), visible: true }]; + let l = d.layers[0].id; + let id = d.insert(Some(l), 0, n).unwrap(); + let (img, b) = with_fonts_unchanged(|| (render(&d), super::cull_bounds(&d.symbol_boxes(), d.node(id).unwrap()).unwrap())); + let inked: Vec<(u32, u32)> = (0..100).flat_map(|y| (0..100).map(move |x| (x, y))).filter(|&(x, y)| img.pixel(x, y)[0] < 250).collect(); + assert!(!inked.is_empty()); + assert!(inked.iter().all(|&(x, y)| b.inflate(1.0, 1.0).contains(vectorcraft_geom::Point::new(f64::from(x), f64::from(y)))), "{b:?}"); +} + +/// An export crops to the solid a 3D effect draws on type, not to the letters, and so does +/// Object › Rasterize. +#[test] +fn an_export_and_rasterize_hold_the_solid_of_3d_type() { + use vectorcraft_doc::NodeKind; + use vectorcraft_doc::text::{CharStyle, TextObject}; + let _fonts = fonts_steady(); + let mut d = Document::new(100.0, 100.0); + let style = CharStyle { size: 30.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "K", style)))); + let letters = with_fonts_unchanged(|| crate::encode::art_bounds(&doc_of(&mut d.clone(), n.clone())).unwrap()); + n.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 60.0, "position": "isometricTop"}), visible: true }]; + let solid_doc = doc_of(&mut d, n.clone()); + let (solid, rasterized) = with_fonts_unchanged(|| { + let n = &solid_doc.layers[0].children().unwrap()[0]; + (crate::encode::art_bounds(&solid_doc).unwrap(), crate::drawn_bounds(&solid_doc, n).unwrap()) + }); + assert!(solid.width() > letters.width() + 15.0, "{letters:?} {solid:?}"); + assert!(rasterized.width() > letters.width() + 15.0, "{letters:?} {rasterized:?}"); +} + +/// A symbol instance, a blend and a clipping group with Extrude & Bevel, alone or in a group, draw +/// their solids on the canvas, in an export and in Object › Rasterize, not their flat art. +#[test] +fn a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids() { + use vectorcraft_doc::{BlendSpacing, BlendSpec, NodeId, NodeKind, Symbol}; + let square = |x: f64, y: f64| { + Arc::new(Node::path( + NodeId(0), + shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), + Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0), + )) + }; + let mut d = Document::new(200.0, 200.0); + d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: square(0.0, 0.0) }); + let mut clip = (*square(30.0, 30.0)).clone(); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let spec = Box::new(BlendSpec { spacing: BlendSpacing::Steps(2), ..Default::default() }); + let instance = NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((40.0, 40.0)) }; + let clipped = NodeKind::Group { children: vec![Arc::new(clip), square(20.0, 20.0)], clip: true }; + let in_group = |kind: NodeKind| NodeKind::Group { children: vec![Arc::new(Node::new(NodeId(0), kind)), square(100.0, 100.0)], clip: false }; + let kinds = [ + ("a symbol instance", instance.clone()), + ("a blend", NodeKind::Blend { children: vec![square(30.0, 30.0), square(60.0, 40.0)], spec }), + ("a clipping group", clipped.clone()), + ("a group holding a symbol instance", in_group(instance)), + ("a group holding a clipping group", in_group(clipped)), + ]; + for (what, kind) in kinds { + let mut n = Node::new(d.alloc_id(), kind); + let flat = crate::encode::art_bounds(&doc_of(&mut d.clone(), n.clone())).unwrap(); + n.appearance.effects = + vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 60.0, "position": "isometricTop"}), visible: true }]; + let solid_doc = doc_of(&mut d.clone(), n); + let n = &solid_doc.layers[0].children().unwrap()[0]; + let (solid, rasterized) = (crate::encode::art_bounds(&solid_doc).unwrap(), crate::drawn_bounds(&solid_doc, n).unwrap()); + let size = |r: Rect| r.width() + r.height(); + assert!(size(solid) > size(flat) + 20.0, "{what}: {flat:?} {solid:?}"); + assert!(size(rasterized) > size(flat) + 20.0, "{what}: {flat:?} {rasterized:?}"); + // The renderer builds the solid from the object itself, with the document's symbols, as + // the effect builds it: one solid built, not the object's art drawn again with the effect. + let built = vectorcraft_effects::solid_art_in(Some(&solid_doc), n).and_then(|a| a.visual_bounds()).unwrap(); + assert!((solid.x0 - built.x0).abs() < 1.0 && (solid.x1 - built.x1).abs() < 1.0, "{what}: {built:?} {solid:?}"); + let mut r = Renderer::new(); + r.art_bounds_on(&solid_doc, Rect::new(0.0, 0.0, 200.0, 200.0)); + assert_eq!(r.stats.three_d_built, 1, "{what}"); + } +} + +/// A loaded file can hold a 3D effect on art past the limits commands check: a blend of more +/// than 4,096 objects, art nested more than 64 levels deep in a clipping group. The art then draws +/// as it does without the effect, and drawing it does not fail. +#[test] +fn art_past_the_three_d_limits_draws_as_without_the_effect() { + use vectorcraft_doc::{BlendSpacing, BlendSpec, NodeId, NodeKind}; + let square = |x: f64| { + Arc::new(Node::path( + NodeId(0), + shapes::rectangle(Rect::new(x, 10.0, x + 20.0, 30.0)), + Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0), + )) + }; + let mut clip = (*square(0.0)).clone(); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let mut deep = (*square(0.0)).clone(); + for _ in 0..200 { + deep = Node::group(NodeId(0), vec![Arc::new(deep)]); + } + let spec = Box::new(BlendSpec { spacing: BlendSpacing::Steps(1000), ..Default::default() }); + let kinds = [ + ("a blend of 6,000 objects", NodeKind::Blend { children: (0..6).map(|i| square(30.0 * i as f64)).collect(), spec }), + ("art 200 levels deep in a clip", NodeKind::Group { children: vec![Arc::new(clip), Arc::new(deep)], clip: true }), + ]; + let d = Document::new(200.0, 200.0); + for (what, kind) in kinds { + let mut n = Node::new(NodeId(500), kind); + let flat = crate::encode::art_bounds(&doc_of(&mut d.clone(), n.clone())).unwrap(); + n.appearance.effects = + vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 60.0, "position": "isometricTop"}), visible: true }]; + let loaded = doc_of(&mut d.clone(), n); + let n = &loaded.layers[0].children().unwrap()[0]; + assert!(vectorcraft_effects::validate_three_d_in(Some(&loaded), n, "threeD.extrude", &json!({})).is_err(), "{what}"); + assert_eq!(crate::encode::art_bounds(&loaded), Some(flat), "{what}"); + assert!(crate::drawn_bounds(&loaded, n).is_some(), "{what}"); + } +} + +fn doc_of(d: &mut Document, n: Node) -> Document { + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d.clone() +} + +/// A shadow on a fill after its own 3D effect is drawn on the fill's solid and reaches past it +/// once: Object › Rasterize takes the solid and the shadow, no more. +#[test] +fn a_fills_shadow_after_its_3d_effect_reaches_past_its_solid_once() { + let mut d = doc_with(Rect::new(40.0, 40.0, 60.0, 60.0), Color::BLACK, vec![]); + let id = d.layers[0].children().unwrap()[0].id; + let fill = |shadow: bool| { + let mut fx = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0, "position": "isometricTop"}), visible: true }]; + if shadow { + fx.push(Effect { id: "stylize.dropShadow".into(), params: json!({"x": 20, "y": 0, "blur": 0}), visible: true }); + } + fx + }; + d.node_mut(id).unwrap().appearance.fill_mut().unwrap().effects = fill(false); + let solid = crate::drawn_bounds(&d, d.node(id).unwrap()).unwrap(); + d.node_mut(id).unwrap().appearance.fill_mut().unwrap().effects = fill(true); + let shadowed = crate::drawn_bounds(&d, d.node(id).unwrap()).unwrap(); + let grown = [solid.x0 - shadowed.x0, solid.y0 - shadowed.y0, shadowed.x1 - solid.x1, shadowed.y1 - solid.y1]; + assert!(grown.iter().all(|g| *g <= 20.0 + 1e-6) && grown.iter().any(|g| *g >= 20.0 - 1e-6), "{solid:?} {shadowed:?}"); +} + +/// A fill's own 3D effect leaves the brushed stroke drawn with its brush: Object › Rasterize, exports +/// and culling take the brush's art in, and Rasterize and exports no more than the solid and that +/// art. +#[test] +fn a_brushed_stroke_beside_a_fills_3d_effect_is_measured_with_its_brush() { + let mut d = doc_with(Rect::new(40.0, 40.0, 60.0, 60.0), Color::BLACK, vec![]); + let id = d.layers[0].children().unwrap()[0].id; + { + let n = d.node_mut(id).unwrap(); + n.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 1.0))); + if let Some(vectorcraft_doc::AppearanceItem::Stroke(s)) = n.appearance.items.last_mut() { + s.brush = Some("10 pt. Oval".into()); + } + n.appearance.fill_mut().unwrap().effects = + vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0, "position": "isometricTop"}), visible: true }]; + } + let n = d.node(id).unwrap(); + let brush = vectorcraft_brush::expand(&d, n).and_then(|art| art.visual_bounds()).unwrap(); + let symbols = d.symbol_boxes(); + let rasterized = crate::drawn_bounds(&d, n).unwrap(); + let exported = crate::effect_bounds(&symbols, n).unwrap(); + for (what, b) in [("Rasterize", rasterized), ("exports", exported), ("culling", super::cull_bounds(&symbols, n).unwrap())] { + assert_eq!(b.union(brush), b, "{what}: {b:?} holds the brush's art {brush:?}"); + } + // The solid alone, without the stroke: what else may be measured. + let mut plain = d.clone(); + plain.node_mut(id).unwrap().appearance.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Stroke(_))); + let solid = crate::drawn_bounds(&plain, plain.node(id).unwrap()).unwrap(); + let most = solid.union(brush).inflate(1.0, 1.0); + for (what, b) in [("Rasterize", rasterized), ("exports", exported)] { + assert_eq!(most.union(b), most, "{what}: {b:?} no more than the solid and the brush's art {most:?}"); + } +} + +/// The renderer measures a 3D object with Crop Marks as the free measure does: by the marks and +/// the object, which paints its own shadow inside them, counted once. +#[test] +fn the_renderer_measures_3d_art_with_crop_marks_as_drawn() { + let fx = vec![ + ("threeD.extrude", json!({"depth": 30.0, "position": "isometricTop"})), + ("stylize.dropShadow", json!({"x": 20, "y": 0, "blur": 0})), + (crate::effects::CROP_MARKS, json!({})), + ]; + let d = doc_with(Rect::new(40.0, 40.0, 60.0, 60.0), Color::BLACK, fx); + let n = d.layers[0].children().unwrap()[0].clone(); + let symbols = d.symbol_boxes(); + let free = super::cull_bounds(&symbols, &n).unwrap(); + assert_eq!(Renderer::new().bounds_of(&symbols, &n), Some(free)); +} + +/// Vector Halftone draws dots in place of a 3D effect's solid: the renderer doesn't measure the +/// object by art it holds to draw it with, and measures it as the free measure does. +#[test] +fn the_renderer_measures_3d_art_with_vector_halftone_as_drawn() { + let fx = vec![("threeD.extrude", json!({"depth": 30.0, "position": "isometricTop"})), (crate::effects::addons::halftone::HALFTONE, json!({}))]; + let d = doc_with(Rect::new(40.0, 40.0, 60.0, 60.0), Color::BLACK, fx); + let n = d.layers[0].children().unwrap()[0].clone(); + let symbols = d.symbol_boxes(); + let free = super::cull_bounds(&symbols, &n).unwrap(); + let mut r = Renderer::new(); + // A consistency check: measured from the dots' art, the bounds come out the same. + assert_eq!(r.bounds_of(&symbols, &n), Some(free)); + assert_eq!(r.measured_bytes(), 0, "no art held"); +} + +/// A renderer measures the art over each artboard as [`crate::encode::art_bounds_on`] does, and +/// builds each 3D solid once for every artboard it measures. +#[test] +fn a_renderer_measures_the_art_on_each_artboard_building_each_solid_once() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let boards = 30; + for i in 0..boards { + let x = f64::from(i) * 100.0; + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(x + 30.0, 30.0, x + 60.0, 60.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects = + vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 40.0, "position": "isometricTop"}), visible: true }]; + d.insert(Some(l), 0, n).unwrap(); + } + let mut r = Renderer::new(); + for i in 0..boards { + let rect = Rect::new(f64::from(i) * 100.0, 0.0, f64::from(i) * 100.0 + 100.0, 100.0); + assert_eq!(r.art_bounds_on(&d, rect), crate::encode::art_bounds_on(&d, rect), "artboard {i}"); + } + assert_eq!(r.stats.three_d_built, boards as usize, "each solid built once"); +} + +/// A 3D object measured but not drawn (off the view) doesn't keep its art past the frame: what is +/// kept is what is drawn. +#[test] +fn only_drawn_3d_art_is_kept() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for x in [30.0, 530.0] { + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(x, 30.0, x + 30.0, 60.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0}), visible: true }]; + ids.push(d.insert(Some(l), 0, n).unwrap()); + } + let mut r = Renderer::new(); + r.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + let kept = |r: &Renderer, id| { + let n = d.layers[0].children().unwrap().iter().find(|c| c.id == id).unwrap(); + r.fx_arts.contains_key(&(Arc::as_ptr(n) as usize)) + }; + assert!(kept(&r, ids[0]), "drawn, kept"); + assert!(!kept(&r, ids[1]), "off the view, let go"); + assert!(r.measured.is_empty()); +} + +/// Art made to measure objects is held within a budget: past it, objects are measured and their +/// art is made again if they are drawn. +#[test] +fn measured_art_is_held_within_its_budget() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + for i in 0..20 { + let x = 500.0 + f64::from(i) * 40.0; + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(x, 30.0, x + 30.0, 60.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0}), visible: true }]; + d.insert(Some(l), 0, n).unwrap(); + } + let symbols = d.symbol_boxes(); + let mut r = Renderer::new(); + let one = { + let n = &d.layers[0].children().unwrap()[0]; + r.bounds_of(&symbols, n); + r.measured_bytes + }; + r.let_go_of_measured(); + r.measured_budget = one * 3; + for n in d.layers[0].children().unwrap() { + r.bounds_of(&symbols, n); + } + assert!(r.measured_bytes <= one * 3 && r.measured.len() <= 3, "{} bytes in {} entries", r.measured_bytes, r.measured.len()); + // Every object is measured right, those past the budget too, and draws as a new renderer + // draws it, its art made again. + for n in d.layers[0].children().unwrap() { + assert_eq!(r.bounds_of(&symbols, n), super::cull_bounds(&symbols, n), "{:?}", n.id); + } + let (view, opts) = (Affine::translate((-500.0, 0.0)), RenderOptions::default()); + let drawn = r.render(&d, 800, 100, view, &opts).pixels; + assert!(drawn == Renderer::new().render(&d, 800, 100, view, &opts).pixels); +} + +/// An edit to 3D objects the frame doesn't draw (hidden, in a hidden group, drawn hidden) builds +/// nothing to measure them, and changes nothing. +#[test] +fn an_edit_out_of_sight_builds_nothing() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let extruded = |d: &mut Document, x: f64| { + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(x, 30.0, x + 20.0, 50.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0}), visible: true }]; + n + }; + let mut hidden = extruded(&mut d, 10.0); + hidden.visible = false; + let member = extruded(&mut d, 40.0); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(member)]); + group.visible = false; + let drawn_hidden = extruded(&mut d, 70.0); + let ids = [d.insert(Some(l), 0, hidden).unwrap(), group.children().unwrap()[0].id, d.insert(Some(l), 0, drawn_hidden).unwrap()]; + d.insert(Some(l), 0, group).unwrap(); + let opts = RenderOptions { hidden: vec![ids[2]], ..Default::default() }; + let mut r = Renderer::new(); + r.render(&d, 100, 100, Affine::IDENTITY, &opts); + let mut e = d.clone(); + for id in ids { + e.node_mut(id).unwrap().appearance.effects[0].params = json!({"depth": 5.0}); + } + let built = r.stats.three_d_built; + assert_eq!(r.changed(&d, &e, &opts), crate::Changed::Nothing); + assert_eq!((r.stats.three_d_built - built, r.measured.len()), (0, 0)); +} + +/// The bounds of 3D art kept for a pass that only measures stay as many as the art still held. +#[test] +fn a_measuring_pass_keeps_the_bounds_of_held_art_only() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + for i in 0..3000 { + let x = f64::from(i) * 30.0; + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(x, 30.0, x + 20.0, 50.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 2.0}), visible: true }]; + d.insert(Some(l), 0, n).unwrap(); + } + let symbols = d.symbol_boxes(); + let mut r = Renderer::new(); + // Nothing measured is held: the art is let go once measured. + r.measured_budget = 0; + for n in d.layers[0].children().unwrap() { + r.bounds_of(&symbols, n); + } + assert_eq!(r.stats.three_d_built, 3000); + assert!(r.three_d_bounds.len() <= 1024, "{} kept", r.three_d_bounds.len()); +} + +/// While its 3D art is held, a pass that only measures sweeps the bounds kept for 3D art each time +/// they double, not on every new art past a size. +#[test] +fn a_measuring_pass_sweeps_the_bounds_of_held_art_as_they_double() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + for i in 0..3000 { + let x = f64::from(i) * 30.0; + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(x, 30.0, x + 20.0, 50.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 2.0}), visible: true }]; + d.insert(Some(l), 0, n).unwrap(); + } + let mut r = Renderer::new(); + // Held here, as the art kept to draw is. + let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d, n)).collect(); + assert_eq!((held.len(), r.three_d_bounds.len()), (3000, 3000)); + assert!(r.three_d_sweeps <= 2, "{} sweeps", r.three_d_sweeps); +} + +/// A renderer checks the brush library between frames only once it has measured 3D art, and again +/// only after measuring 3D art since the library last changed. +#[test] +fn the_brush_library_is_checked_only_after_3d_art_is_measured() { + let mut d = doc_with(Rect::new(30.0, 30.0, 60.0, 60.0), Color::BLACK, vec![]); + let mut r = Renderer::new(); + r.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(r.brush_library, None); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0}), visible: true }]; + r.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + assert!(r.brush_library.is_some()); + // A library changed: the bounds measured with the old one go, and so does its key. + let mut lib = vectorcraft_brush::library(&d); + lib.retain(|b| b.name != "3 pt. Round"); + vectorcraft_brush::store(&mut d, &lib); + r.check_symbols(&d); + assert_eq!(r.brush_library, None); +} + +/// An object whose 3D effect builds nothing (Revolve on a group's fill) is measured by the renderer +/// as the free measure does it: as the renderer draws it, by its members. +#[test] +fn a_3d_effect_that_builds_nothing_is_measured_alike() { + let mut d = Document::new(100.0, 100.0); + let mut hidden = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(60.0, 10.0, 90.0, 20.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + hidden.visible = false; + let shown = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + let mut g = Node::group(d.alloc_id(), vec![Arc::new(hidden), Arc::new(shown)]); + g.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + *g.appearance.items[0].effects_mut() = vec![Effect { id: "threeD.revolve".into(), params: json!({}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let n = d.layers[0].children().unwrap()[0].clone(); + assert!(crate::effects::has_revolve(&n) && crate::effects::revolve_art(&n).is_none(), "builds nothing"); + let symbols = d.symbol_boxes(); + assert_eq!(Renderer::new().effect_bounds(&symbols, &n), crate::effect_bounds(&symbols, &n)); + assert_eq!(Renderer::new().bounds_of(&symbols, &n), crate::brush_fx::cull_bounds(&symbols, &n)); +} + +/// A group with effects of its own that holds an extruded path is measured once for every artboard +/// of a pass: its bounds are kept after the first. +#[test] +fn a_group_holding_3d_art_is_measured_once_a_pass() { + let mut d = Document::new(100.0, 100.0); + let mut inner = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(30.0, 30.0, 60.0, 60.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + inner.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0}), visible: true }]; + let mut g = Node::group(d.alloc_id(), vec![Arc::new(inner)]); + g.appearance.effects = vec![Effect { id: "stylize.dropShadow".into(), params: json!({"x": 4, "y": 4, "blur": 2}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let g = d.layers[0].children().unwrap()[0].clone(); + let mut r = Renderer::new(); + let first = Rect::new(0.0, 0.0, 100.0, 100.0); + assert_eq!(r.art_bounds_on(&d, first), crate::encode::art_bounds_on(&d, first)); + let key = Arc::as_ptr(&g) as usize; + assert!(r.geom.contains_key(&key), "kept for the next artboard"); + // The group's bounds, planted over the next artboards: they read the kept bounds, measuring + // nothing again. + let planted = Rect::new(100.0, 0.0, 300.0, 100.0); + r.geom.get_mut(&key).unwrap().bounds = Some(planted); + for i in 1..3 { + let rect = Rect::new(f64::from(i) * 100.0, 0.0, f64::from(i) * 100.0 + 100.0, 100.0); + assert_eq!(r.art_bounds_on(&d, rect), Some(planted), "artboard {i}"); + } +} + +/// A pass that only measures (Fit to Artwork Bounds, an export) holds no 3D art past its budget: +/// what it measured and didn't keep is let go. +#[test] +fn a_measuring_pass_holds_no_art_past_its_budget() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + for i in 0..20 { + let x = f64::from(i) * 40.0; + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(x, 30.0, x + 30.0, 60.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0}), visible: true }]; + d.insert(Some(l), 0, n).unwrap(); + } + let mut r = Renderer::new(); + r.measured_budget = 0; + r.art_bounds_on(&d, Rect::new(0.0, 0.0, 100.0, 100.0)); + assert!(r.measured.is_empty()); + assert!(r.three_d_bounds.values().all(|e| e.0.strong_count() == 0), "no art held"); +} + +/// Drawing an object takes the art made to measure it out of the budget: a frame draws each 3D +/// object with that art, making none again, while what it measured fits the budget. +#[test] +fn drawing_takes_measured_art_out_of_the_budget() { + let mut d = Document::new(800.0, 100.0); + let l = d.layers[0].id; + for i in 0..20 { + let x = f64::from(i) * 40.0; + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(x, 30.0, x + 30.0, 60.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0}), visible: true }]; + d.insert(Some(l), 0, n).unwrap(); + } + let n = d.layers[0].children().unwrap()[0].clone(); + let mut r = Renderer::new(); + r.bounds_of(&d.symbol_boxes(), &n); + assert!(r.measured_bytes > 0); + r.fx_art(&d, &n, true); + assert_eq!((r.measured_bytes, r.measured.len()), (0, 0), "taken out when drawn"); + let mut r = Renderer::new(); + r.render(&d, 800, 100, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(r.stats.three_d_built, 20, "each made once"); +} + +/// An object with a brushed stroke whose 3D effect builds nothing is measured by a pass as without +/// it: not with the room culling leaves for its brush. +#[test] +fn a_pass_measures_brushed_art_as_exports_do() { + let mut d = Document::new(100.0, 100.0); + let mut art = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + art.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 1.0))); + if let Some(vectorcraft_doc::AppearanceItem::Stroke(s)) = art.appearance.items.last_mut() { + s.brush = Some("10 pt. Oval".into()); + } + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Brushed".into(), art: Arc::new(art) }); + let mut n = Node::new(d.alloc_id(), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Brushed".into(), xf: Affine::translate((50.0, 50.0)) }); + n.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let n = d.layers[0].children().unwrap()[0].clone(); + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + assert_eq!(Renderer::new().art_bounds_on(&d, rect), crate::encode::art_bounds_on(&d, rect)); + let symbols = d.symbol_boxes().with_brush_art(); + assert_eq!(Renderer::new().effect_bounds(&symbols, &n), crate::effect_bounds(&symbols, &n)); +} + +/// A 3D object whose brushed stroke's brush gets wider is drawn where the brush now reaches, by a +/// renderer that measured it before: culling leaves room for brush art. +#[test] +fn a_3d_objects_wider_brush_is_drawn_where_it_reaches() { + let mut d = Document::new(100.0, 100.0); + let mut ap = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0); + ap.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let mut n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(104.0, 40.0, 124.0, 60.0)), ap); + n.appearance.fill_mut().unwrap().effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 2.0}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + r.render(&d, 100, 100, Affine::IDENTITY, &opts); + let mut lib = vectorcraft_brush::library(&d); + let round = lib.iter_mut().find(|b| b.name == "3 pt. Round").unwrap(); + if let vectorcraft_brush::BrushKind::Calligraphic(c) = &mut round.kind { + c.size = 30.0; + } + vectorcraft_brush::store(&mut d, &lib); + let drawn = r.render(&d, 100, 100, Affine::IDENTITY, &opts).pixels; + let fresh = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixels; + assert!(fresh.iter().any(|c| *c < 128), "the wider brush reaches into the view"); + assert!(drawn == fresh, "as a new renderer draws it"); +} + +/// A 20 pt square at `x` with a fill-level 3D effect, a brushed stroke and Rasterize, in a 100 pt +/// view: drawn by a renderer that drew it before its brush got wider (`size` pt), and by a new +/// renderer. +fn drawn_after_a_brush_widens(x: f64, size: f64) -> (Vec, Vec) { + let brush = "3 pt. Round"; + let mut d = Document::new(100.0, 100.0); + let mut ap = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0); + ap.stroke_mut().unwrap().brush = Some(brush.into()); + let mut n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 40.0, x + 20.0, 60.0)), ap); + n.appearance.fill_mut().unwrap().effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 2.0}), visible: true }]; + n.appearance.effects = vec![Effect { id: "rasterize".into(), params: json!({"useDocumentResolution": false, "resolution": 72}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + r.render(&d, 100, 100, Affine::IDENTITY, &opts); + let mut lib = vectorcraft_brush::library(&d); + let b = lib.iter_mut().find(|b| b.name == brush).unwrap(); + if let vectorcraft_brush::BrushKind::Calligraphic(c) = &mut b.kind { + c.size = size; + } + vectorcraft_brush::store(&mut d, &lib); + let drawn = r.render(&d, 100, 100, Affine::IDENTITY, &opts).pixels; + (drawn, Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixels) +} + +/// Rasterize on a brushed 3D object outside the view draws its art with the brush as it is now, by +/// a renderer that drew it with the brush before: the object is measured again when the brush +/// library changes, with the brush's art reaching past the room culling leaves for it, and +/// rasterized again. +#[test] +fn a_rasterized_3d_objects_brush_widened_is_drawn() { + let (drawn, fresh) = drawn_after_a_brush_widens(140.0, 120.0); + assert!(fresh.iter().any(|c| *c < 128), "the wider brush reaches into the view"); + assert!(drawn == fresh, "as a new renderer draws it"); +} + +/// A rasterized brushed 3D object in the view is rasterized again when its brush changes. +#[test] +fn a_rasterized_objects_brush_widened_in_view_is_drawn_again() { + let (drawn, fresh) = drawn_after_a_brush_widens(40.0, 12.0); + let (_, before) = drawn_after_a_brush_widens(40.0, 3.0); + assert!(fresh != before, "the wider brush draws otherwise"); + assert!(drawn == fresh, "as a new renderer draws it"); +} + +/// A group with effects of its own that holds a hidden member is measured without it once a pass, +/// as exports measure it. +#[test] +fn a_group_with_a_hidden_member_is_measured_once_a_pass() { + let mut d = Document::new(100.0, 100.0); + let mut solid = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(30.0, 30.0, 60.0, 60.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + solid.appearance.effects = vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 20.0}), visible: true }]; + let mut hidden = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(80.0, 80.0, 95.0, 95.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + hidden.visible = false; + let mut g = Node::group(d.alloc_id(), vec![Arc::new(solid), Arc::new(hidden)]); + g.appearance.effects = vec![Effect { id: "stylize.dropShadow".into(), params: json!({"x": 4, "y": 4, "blur": 2}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let g = d.layers[0].children().unwrap()[0].clone(); + let mut r = Renderer::new(); + let first = Rect::new(0.0, 0.0, 100.0, 100.0); + assert_eq!(r.art_bounds_on(&d, first), crate::encode::art_bounds_on(&d, first)); + let key = Arc::as_ptr(&g) as usize; + assert!(r.pass_bounds.contains_key(&key), "kept for the next artboard"); + // The group's bounds, planted over the next artboards: they read the kept bounds, measuring + // nothing again. + let planted = Rect::new(100.0, 0.0, 300.0, 100.0); + r.pass_bounds.get_mut(&key).unwrap().1 = Some(planted); + for i in 1..3 { + let rect = Rect::new(f64::from(i) * 100.0, 0.0, f64::from(i) * 100.0 + 100.0, 100.0); + assert_eq!(r.art_bounds_on(&d, rect), Some(planted), "artboard {i}"); + } +} + +/// Art made again for an object, after what it read from outside it changed, takes the place of +/// the art held for it, and of its bytes. +#[test] +fn art_measured_again_takes_the_place_of_the_held() { + let d = doc_with(Rect::new(30.0, 30.0, 60.0, 60.0), Color::BLACK, vec![("threeD.extrude", json!({"depth": 20.0}))]); + let n = d.layers[0].children().unwrap()[0].clone(); + let key = Arc::as_ptr(&n) as usize; + let mut r = Renderer::new(); + let art = r.measured_fx_art(&d, &n); + let bytes = r.measured_bytes; + // As if it had read something else then. + r.measured.insert(key, (n.clone(), art, Some(7))); + r.measured_fx_art(&d, &n); + assert_eq!((r.measured_bytes, r.measured.len()), (bytes, 1)); +} + /// Multithreaded rendering filters each effect offscreen; it must match the single-threaded /// reference (blend modes against the real backdrop, objects partly off-screen, all effects). #[test] @@ -1143,3 +1852,76 @@ fn an_image_inner_glow_follows_its_visible_pixels() { assert!(lum(img.pixel(60, 50)) < lum(img.pixel(51, 50)), "threads {threads}: fading inward"); } } + +/// A 3D effect on a path's fill or stroke that builds nothing (Revolve after Roughen, in a paint +/// whose copies on the faces would pass the budget) draws the item as without it: the art made for the object is drawn without it, not as an object with +/// effects again, and that art again, without end. A stroked object draws exactly as without the +/// 3D effect, with a raster effect of its own (Drop Shadow, Gaussian Blur) too. An object with +/// only a fill and a raster effect draws from that art, where without the 3D effect it draws as a +/// path, whose raster effects are clipped to the path's own geometry: there Roughen's spikes are +/// cut off, so the two differ in a few pixels at the edge and match inside the path. That clipping +/// is an older bug on main of drawing without the 3D effect, not the design. Either +/// way the raster effect reaches past what the object draws without it. +#[test] +fn a_3d_effect_that_builds_nothing_draws_the_item_as_without_it() { + let rough = + Effect { id: "distort.roughen".into(), params: json!({"size": 10, "relative": false, "detail": 10, "points": "smooth"}), visible: true }; + let revolve = Effect { id: "threeD.revolve".into(), params: json!({}), visible: true }; + // A gradient of one color with 1,000 stops. + let ramp = |c: Color| { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = (0..1000).map(|i| GradientStop::new(i as f32 / 1000.0, c)).collect(); + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))) + }; + let shadow = Effect { id: "stylize.dropShadow".into(), params: json!({}), visible: true }; + let blur = Effect { id: "blur.gaussian".into(), params: json!({"radius": 2}), visible: true }; + let cases = [ + (vec![], true, true), + (vec![], false, true), + (vec![shadow.clone()], true, true), + (vec![blur.clone()], false, true), + (vec![], true, false), + (vec![shadow], true, false), + (vec![blur], true, false), + ]; + for (object, on_fill, stroked) in cases { + let draw = |object: &[Effect], three: bool| { + let mut d = Document::new(100.0, 100.0); + let stroke = if stroked { ramp(Color::rgb(0.0, 0.0, 1.0)) } else { Paint::None }; + let ap = Appearance::basic(ramp(Color::BLACK), stroke, 2.0); + let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 60.0, 60.0)), ap); + let l = d.layers[0].id; + let id = d.insert(Some(l), 0, n).unwrap(); + let n = d.node_mut(id).unwrap(); + n.appearance.effects = object.to_vec(); + let item = if on_fill { + n.appearance.fill_mut().unwrap().effects = vec![]; + &mut n.appearance.items[0] + } else { + &mut n.appearance.items[1] + }; + *item.effects_mut() = [Some(rough.clone()), three.then(|| revolve.clone())].into_iter().flatten().collect(); + assert!(crate::effects::revolve_art(d.node(id).unwrap()).is_none(), "builds nothing"); + Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()).pixels + }; + let what = format!("{object:?} on the fill {on_fill}, stroked {stroked}"); + let (with, without) = (draw(&object, true), draw(&object, false)); + if stroked || object.is_empty() { + assert!(with == without, "{what}: as without it"); + } else { + // Under 4% of the pixels, all at the edge, where Roughen's spikes are: inside the path + // they match. + let differ: Vec<(usize, usize)> = + (0..100 * 100).filter(|i| with[i * 4..i * 4 + 4] != without[i * 4..i * 4 + 4]).map(|i| (i % 100, i / 100)).collect(); + assert!(differ.len() * 25 < 100 * 100, "{what}: {} pixels differ", differ.len()); + let inside = differ.iter().find(|(x, y)| (33..57).contains(x) && (33..57).contains(y)); + assert!(inside.is_none(), "{what}: differs inside the path at {inside:?}"); + } + if !object.is_empty() { + // Ink where the object without its raster effect draws none. + let plain = draw(&[], true); + let past = (0..100 * 100).filter(|i| plain[i * 4 + 3] == 0 && with[i * 4 + 3] > 0).count(); + assert!(past > 0, "{what}: drawn past the object"); + } + } +} diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 93adbf245f..92246e1cde 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -63,7 +63,7 @@ pub fn installed_memory() -> Option { /// Installed memory in bytes (`MemTotal` in `/proc/meminfo`), or the memory limit of the process's /// cgroups where that is lower. #[cfg(target_os = "linux")] -fn physical_memory() -> Option { +pub fn physical_memory() -> Option { let info = std::fs::read_to_string("/proc/meminfo").ok()?; let line = info.lines().find(|l| l.starts_with("MemTotal:"))?; let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; @@ -174,14 +174,14 @@ fn mountinfo_unescape(field: &str) -> String { /// Installed memory in bytes (`GlobalMemoryStatusEx`). #[cfg(windows)] -fn physical_memory() -> Option { +pub fn physical_memory() -> Option { winsafe::GlobalMemoryStatusEx().ok().map(|m| m.ullTotalPhys) } /// Installed memory in bytes, as `sysctl` prints it (`hw.memsize` on macOS, `hw.physmem` on /// FreeBSD). #[cfg(any(target_os = "macos", target_os = "freebsd"))] -fn physical_memory() -> Option { +pub fn physical_memory() -> Option { let (sysctl, name) = if cfg!(target_os = "macos") { ("/usr/sbin/sysctl", "hw.memsize") } else { ("/sbin/sysctl", "hw.physmem") }; let out = std::process::Command::new(sysctl).args(["-n", name]).output().ok().filter(|o| o.status.success())?; sysctl_bytes(&out.stdout) @@ -193,8 +193,9 @@ fn sysctl_bytes(out: &[u8]) -> Option { std::str::from_utf8(out).ok()?.trim().parse().ok() } -#[cfg(not(any(target_os = "linux", windows, target_os = "macos", target_os = "freebsd", target_arch = "wasm32")))] -fn physical_memory() -> Option { +/// Installed memory in bytes: not read on other targets, the web among them. +#[cfg(not(any(target_os = "linux", windows, target_os = "macos", target_os = "freebsd")))] +pub fn physical_memory() -> Option { None } diff --git a/crates/render/src/ink.rs b/crates/render/src/ink.rs index c8df531a89..2d67db2073 100644 --- a/crates/render/src/ink.rs +++ b/crates/render/src/ink.rs @@ -176,7 +176,7 @@ impl Ink { peniko::Color::from_rgba8(r, g, b, a) } - fn fixed8(self, [r, g, b, a]: [u8; 4]) -> [u8; 4] { + pub(crate) fn fixed8(self, [r, g, b, a]: [u8; 4]) -> [u8; 4] { match self.base() { Ink::Display | Ink::RichBlack => [r, g, b, a], _ => { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 31591e4b71..6c9c7c5541 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -15,7 +15,7 @@ mod freeform; mod fx; mod group; mod images; -pub use images::{image_cached, keep_decoded_image}; +pub use images::{image_cached, keep_decoded_image, physical_memory}; mod ink; mod live; mod lru; @@ -49,6 +49,14 @@ pub use pattern::render_pattern_swatch; pub use vectorcraft_effects as effects; pub use vello_cpu; +/// Art made to measure an object ([`Renderer::measured`]): the object, its art, and the key of +/// what the art read from outside the object (`None`: nothing). +type MeasuredArt = (Arc, Arc, Option); + +/// A 3D effect's art ([`Renderer::three_d_bounds`]), held weakly, and its bounds once measured at a +/// raster effects resolution (its bits) with a brush library (its key). +type ThreeDArt = (std::sync::Weak, Option<((u64, u64), Option)>); + /// Reusable renderer (keeps the render context, geometry and glyph caches between frames; decoded /// images are shared by all renderers, see [`set_image_cache_budget`]). pub struct Renderer { @@ -76,6 +84,11 @@ pub struct Renderer { /// The plug-in revision ([`effects::plugin_revision`]) that `geom`, `fx_geom` and `fx_arts` were /// last checked against (see [`Self::check_plugins`]). plugin_revision: u64, + /// The key of the brush library ([`brush_fx::BrushCache::library_key`]) when `geom`'s bounds of + /// 3D art were measured with it (see [`Self::check_symbols`]): set by the first such measure + /// and kept, whether or not those bounds still are, until the library changes. `None` until + /// then, and nothing is checked. + brush_library: Option, /// Is a live-effect plug-in that paints its pieces installed (found when `plugin_revision` /// changes)? painting_plugins: bool, @@ -148,6 +161,33 @@ pub struct Renderer { shape_of: usize, /// The art drawn for objects with effects that apply through it (see `fx::has_object_fx`). fx_arts: FrameCache, + /// The art of objects with object effects made to measure them ([`Renderer::bounds_of`]) and + /// not drawn yet, by the object's address, with the object and the key of what it read from + /// outside the object when it was made (`None`: nothing): drawing one keeps it in `fx_arts` + /// while that is unchanged; the frame's end lets go of the rest. + measured: PtrMap, + /// The bytes of the art in `measured` ([`lru::node_bytes`]), within `measured_budget` + /// ([`lru::MEASURED_BUDGET`]). + measured_bytes: usize, + measured_budget: usize, + /// The export bounds of the objects measured without their hidden members + /// (`encode::drawn_bounds`), by the object they were made from: kept for a pass over artboards, + /// let go when a frame ends. + pub(crate) pass_bounds: PtrMap, Option)>, + /// The 3D effects' art among the art `fx_art` made, by its address, with the art (weakly: what + /// keeps the art is `fx_arts` and `measured`) and its bounds once measured. An entry is added + /// for every 3D art made, measured or not. Entries whose art is gone are swept when a frame + /// ends (`let_go_of_measured`) and, for a renderer that only measures, when the map reaches + /// twice the size it kept at the last sweep (at least 1024): it holds at most max(twice the + /// entries kept at the last sweep, 1024). Until swept, an entry's weak pointer keeps the art's + /// allocation (not its contents) alive. + three_d_bounds: PtrMap, + /// How many entries `three_d_bounds` kept when it last let go of the art no longer held: it + /// does so again when it holds twice as many. + three_d_kept: usize, + /// How many times `three_d_bounds` was swept for art no longer held between frames. + #[cfg(test)] + three_d_sweeps: usize, /// Symbol art as instances and inline graphics draw it (see [`Self::placed_art`]). placed_arts: FrameCache, /// The bitmap clock of [`placed_document`] when this frame first drew a placed document from diff --git a/crates/render/src/lru.rs b/crates/render/src/lru.rs index 5f5976a097..54ab4e51ed 100644 --- a/crates/render/src/lru.rs +++ b/crates/render/src/lru.rs @@ -33,6 +33,10 @@ pub(crate) const CHAR_STROKE_BUDGET: usize = 128 << 20; pub(crate) const CLIP_BUDGET: usize = 32 << 20; /// The art drawn for objects with effects that apply through it (`Renderer::fx_art`). pub(crate) const FX_ART_BUDGET: usize = 64 << 20; +/// Art made to measure objects and held until the frame ends, for the objects drawn to keep +/// (`Renderer::measured`): as much as the art kept for the objects drawn (`FX_ART_BUDGET`), which +/// a frame measures before it draws them. Past it, an object is made again to draw it. +pub(crate) const MEASURED_BUDGET: usize = FX_ART_BUDGET; /// Symbol art placed for instances and inline graphics (`Renderer::placed_art`). pub(crate) const PLACED_ART_BUDGET: usize = 64 << 20; /// Brush art per brushed stroke (`Renderer::draw_brush`). diff --git a/crates/render/src/node_checks.rs b/crates/render/src/node_checks.rs index 07a1b9dc28..c4c81b3373 100644 --- a/crates/render/src/node_checks.rs +++ b/crates/render/src/node_checks.rs @@ -107,6 +107,33 @@ pub(crate) fn holds_instance(n: &Node) -> bool { holds } +/// Is `a` left out of a frame `doc` draws with `opts`, before any culling: hidden, a template or +/// guide the view hides, drawn hidden, or the instance its symbol is being edited from? +pub(crate) fn left_out(opts: &crate::RenderOptions, doc: &vectorcraft_doc::Document, a: &Node) -> bool { + let view_item = (opts.skip_templates || opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. }) + || (opts.skip_templates || opts.hide_guides) && matches!(a.kind, NodeKind::Path { guide: true, .. }); + !a.visible || view_item || opts.hidden.contains(&a.id) || edited_instance(opts, doc, a.id) +} + +/// Symbol editing mode on screen: is `id` the instance editing was entered from, which is not drawn +/// (with its masks and effects), since the editing layer holds a copy of its art in its place? +fn edited_instance(opts: &crate::RenderOptions, doc: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId) -> bool { + opts.isolated.is_some() && doc.symbol_edit.as_ref().is_some_and(|e| e.instance == Some(id)) +} + +/// Does [`crate::Renderer::bounds_of`] measure `n` by the 3D art the renderer draws and keeps for +/// it: a Revolve, Extrude & Bevel, Inflate or Rotate without Crop Marks or Vector Halftone, which +/// draw other art? +pub(crate) fn measures_three_d(n: &Node) -> bool { + (effects::has_revolve(n) || effects::has_solid(n)) && !effects::has_crop_marks(n) && !effects::addons::halftone::has_halftone(n) +} + +/// Does `n` hold an object that [`crate::Renderer::bounds_of`] measures by its 3D effect's art +/// ([`measures_three_d`])? +pub(crate) fn holds_measured_three_d(n: &Node) -> bool { + measures_three_d(n) || n.children().is_some_and(|c| c.iter().any(|c| holds_measured_three_d(c))) +} + /// Does `n` hold an object with a visible plug-in effect ([`effects::has_plugin_effect`]), in it or /// in the opacity masks of the objects in it? pub(crate) fn holds_plugin_effect(n: &Node) -> bool { diff --git a/crates/render/src/options.rs b/crates/render/src/options.rs index 93d0f07b9a..8a152e11f2 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -35,7 +35,7 @@ pub fn raster_size(region: Rect, scale: f64) -> Result<(u32, u32), String> { pub struct RenderOptions { /// Outline (wireframe) view: 1 px black paths, no paint. pub outline: bool, - /// Pasteboard colour behind everything (premultiplied RGBA8); `None` = transparent. + /// Pasteboard color behind everything (straight-alpha RGBA8); `None` = transparent. pub background: Option<[u8; 4]>, /// Draw artboards as white rectangles (screen view). Export sets this to false. pub artboards: bool, diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index e8df562155..a5bfcbf26e 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -45,6 +45,7 @@ impl Renderer { kept: PtrMap::default(), symbols: vec![], plugin_revision: 0, + brush_library: None, painting_plugins: false, paint_names: 0, strokes: PtrMap::default(), @@ -70,6 +71,14 @@ impl Renderer { knockout: false, shape_of: 0, fx_arts: FrameCache::new(lru::FX_ART_BUDGET, 256), + measured: PtrMap::default(), + measured_bytes: 0, + measured_budget: lru::MEASURED_BUDGET, + pass_bounds: PtrMap::default(), + three_d_bounds: PtrMap::default(), + three_d_kept: 0, + #[cfg(test)] + three_d_sweeps: 0, placed_arts: FrameCache::new(lru::PLACED_ART_BUDGET, 256), placed_frame: None, nested: 0, @@ -227,12 +236,16 @@ impl Renderer { self.clips.sweep(g); self.clip_paints.sweep(g); self.fx_arts.sweep(g); + // Only the 3D art still kept (in `fx_arts`) keeps its bounds. + self.let_go_of_measured(); self.placed_arts.sweep(g); self.brushes.entries.sweep(g); self.live.sweep(g); } - /// Draw frame `f` (`w`×`h` pixels): the background, the artboards and the page's art. + /// Draw frame `f` (`w`×`h` pixels): the artboards and the page's art, then the background + /// under them. The art blends only with itself, as it does on the canvas, where the paper is + /// drawn apart from it: a Screen glow on the bare page stays visible on a white background (#6125). fn draw_frame(&mut self, f: &Frame, w: u16, h: u16) -> Vec { let (threads, opts) = (self.threads, f.opts); let kept = self.contexts.iter().position(|(t, c)| *t == threads && c.width() == w && c.height() == h); @@ -247,11 +260,6 @@ impl Renderer { ctx.set_aliasing_threshold(opts.anti_alias.threshold()); let render_mode = if opts.precise { vello_cpu::RenderMode::OptimizeQuality } else { vello_cpu::RenderMode::OptimizeSpeed }; self.raster = vello_cpu::RasterizerSettings { render_mode, ..Default::default() }; - if let Some(bg) = opts.background { - ctx.set_transform(Affine::IDENTITY); - ctx.set_paint(f.ink.fixed(bg)); - ctx.fill_rect(&kurbo::Rect::new(0.0, 0.0, w as f64, h as f64)); - } if opts.artboards && !opts.outline { // Paper: white on screen, no ink on the ink planes. ctx.set_transform(f.view); @@ -278,7 +286,11 @@ impl Renderer { if self.contexts.len() > 2 { self.contexts.remove(0); } - pm.data_as_u8_slice().to_vec() + let mut pixels = pm.data_as_u8_slice().to_vec(); + if let Some(bg) = opts.background { + over_background(&mut pixels, f.ink.fixed8(bg)); + } + pixels } /// The page's art: the layers (or the pattern being edited), inside the page group when the @@ -363,7 +375,7 @@ impl Renderer { } /// Render any node (also one outside the tree, e.g. opacity-mask art) fitted into - /// `size`×`size` pixels, optionally over a solid premultiplied background. A symbol instance + /// `size`×`size` pixels, optionally over a solid straight-alpha background. A symbol instance /// is fitted by its symbol's art in `doc`. pub fn render_node_thumbnail(&mut self, doc: &Document, n: &Node, size: u32, background: Option<[u8; 4]>) -> Option { self.render_node_thumbnail_with(doc, n, size, background, &RenderOptions::default()) @@ -392,10 +404,6 @@ impl Renderer { let view = Affine::translate((w as f64 / 2.0, w as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2()); let mut ctx = single_threaded_context(w, w); ctx.set_aliasing_threshold(opts.anti_alias.threshold()); - if let Some(bg) = background { - ctx.set_paint(peniko::Color::from_rgba8(bg[0], bg[1], bg[2], bg[3])); - ctx.fill_rect(&kurbo::Rect::new(0.0, 0.0, w as f64, w as f64)); - } let symbols = doc.symbol_boxes().quick(); let frame = Frame { mt: false, @@ -415,6 +423,22 @@ impl Renderer { self.draw_forced_arc(&mut ctx, &frame, &Arc::new(n.clone())); let pm = self.finish(&mut ctx, vello_cpu::RasterizerSettings::default()); self.end_frame(); - Some(Rendered { width: w as u32, height: w as u32, pixels: pm.data_as_u8_slice().to_vec() }) + let mut pixels = pm.data_as_u8_slice().to_vec(); + if let Some(bg) = background { + over_background(&mut pixels, bg); + } + Some(Rendered { width: w as u32, height: w as u32, pixels }) + } +} + +/// Premultiplied RGBA `pixels` drawn over the solid color `background` (`[r, g, b, a]`, straight). +pub(crate) fn over_background(pixels: &mut [u8], [r, g, b, a]: [u8; 4]) { + let alpha = u32::from(a); + let under = [u32::from(r) * alpha / 255, u32::from(g) * alpha / 255, u32::from(b) * alpha / 255, alpha]; + for p in pixels.as_chunks_mut::<4>().0 { + let rest = 255 - u32::from(p[3]); + for (v, bg) in p.iter_mut().zip(under) { + *v = (u32::from(*v) + (bg * rest + 127) / 255).min(255) as u8; + } } } diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index f5c9cfdb0a..9b59367deb 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -5,6 +5,7 @@ use super::{ shape_masked_image, single_plain_fill, text_geom_snapped, white_shape_mask, }; use crate::kept_paths::{self, KeptPath}; +use crate::node_checks::{holds_measured_three_d, measures_three_d}; impl Renderer { /// Cached cull bounds of a node (containers union their cached children), symbol instances @@ -29,6 +30,24 @@ impl Renderer { } acc } + // A 3D effect's art, measured as this renderer draws and keeps it ([`Self::fx_art`]): one + // build for the measure and the draw. Crop Marks and Vector Halftone draw other art, and + // an object whose 3D effect builds nothing (Revolve on a group, a solid too complex) is + // drawn otherwise, measured as below. + _ if measures_three_d(a) + && let Some(b) = { + let art = self.measured_fx_art(symbols.document(), a); + self.three_d_art_bounds(symbols, &art) + } => + { + // Culling leaves room for brush art as for any object ([`brush_fx::cull_bounds`]); + // the measure is made again when the brush library changes ([`Self::check_symbols`]). + if self.brush_library.is_none() { + self.brush_library = Some(self.brushes.library_key_now(symbols.document(), self.stamp)); + } + let pad = brush_fx::pad(symbols, a); + b.map(|b| fx::with_own_raster_reach(symbols, a, b).inflate(pad, pad)) + } _ => self.kept_bounds(symbols, a).unwrap_or_else(|| brush_fx::cull_bounds(symbols, a)), }; self.geom.insert(key, GeomEntry { node: a.clone(), bounds: b, path: None, stamp: self.stamp }); @@ -81,7 +100,8 @@ impl Renderer { /// Drop the cached bounds of symbol instances and of the objects that hold them when `doc`'s /// symbols are not those of the document last drawn (by name and art): those bounds measured - /// the instances by their symbol's art. + /// the instances by their symbol's art. Likewise drop those of objects measured by a 3D + /// effect's art, and of the objects that hold them, when the brush library has changed. pub(crate) fn check_symbols(&mut self, doc: &Document) { let same = self.symbols.len() == doc.symbols.len() && self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| *name == s.name && std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art))); @@ -89,6 +109,14 @@ impl Renderer { self.geom.retain(|_, e| !holds_instance(&e.node)); self.symbols = doc.symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(); } + // That art is measured with the art its brushed strokes draw ([`Self::bounds_of`]). Without + // such bounds, nothing is checked. + if let Some(was) = self.brush_library + && self.brushes.library_key_now(doc, self.stamp) != was + { + self.geom.retain(|_, e| !holds_measured_three_d(&e.node)); + self.brush_library = None; + } } /// When a plug-in has been installed or removed since the last check @@ -188,19 +216,10 @@ impl Renderer { self.path_of(f.symbols, &owner) } - /// Symbol editing mode on screen: `id` is the instance editing was entered from, which is not - /// drawn (with its masks and effects), since the editing layer holds a copy of its art in its - /// place. - fn edited_instance(f: &Frame, id: NodeId) -> bool { - f.opts.isolated.is_some() && f.doc.symbol_edit.as_ref().is_some_and(|e| e.instance == Some(id)) - } - /// Whether `a` is left out of this frame: hidden, a skipped template or guide, the instance a /// symbol is edited from, or culled. fn skipped(&mut self, f: &Frame, a: &Arc) -> bool { - let skipped_view_item = (f.opts.skip_templates || f.opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. }) - || (f.opts.skip_templates || f.opts.hide_guides) && matches!(a.kind, NodeKind::Path { guide: true, .. }); - if !a.visible || skipped_view_item || f.opts.hidden.contains(&a.id) || Self::edited_instance(f, a.id) { + if crate::node_checks::left_out(f.opts, f.doc, a) { return true; } match self.bounds_of(f.symbols, a) { @@ -635,11 +654,8 @@ impl Renderer { /// `fx_owner`, so its path, its live-effect geometry and, through [`Self::draw_kept_node`], a /// live object's evaluation come from the caches. fn draw_outline_member(&mut self, ctx: &mut RenderContext, f: &Frame, c: &Arc) { - if !c.visible - || f.opts.hidden.contains(&c.id) - || f.opts.hide_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) - || Self::edited_instance(f, c.id) - { + // Left out as any object is ([`Self::skipped`]). + if crate::node_checks::left_out(f.opts, f.doc, c) { return; } match self.bounds_of(f.symbols, c) { diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 4593971492..27c299c49c 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -55,20 +55,32 @@ fn document() -> (Document, [NodeId; 5]) { } /// Draws `new` again only where it changed from `old`, over `old` drawn whole, and checks that -/// this is `new` drawn whole; returns what changed. +/// this is `new` drawn whole; returns what changed. Measured afresh ([`changed`]) and by the +/// renderer that drew `old`, which then draws the part ([`Renderer::changed`]): both must hold. fn redraw(old: &Document, new: &Document) -> Changed { - let mut r = Renderer::new(); let opts = RenderOptions::default(); - let before = r.render(old, W, H, view(), &opts); - let after = r.render(new, W, H, view(), &opts); + let after = Renderer::new().render(new, W, H, view(), &opts); let change = changed(old, new); + let mut fresh = Renderer::new(); + let before = fresh.render(old, W, H, view(), &opts); + patched(&mut fresh, &before, new, change, &after, &opts); + let mut r = Renderer::new(); + let before = r.render(old, W, H, view(), &opts); + let measured = r.changed(old, new, &opts); + patched(&mut r, &before, new, measured, &after, &opts); + change +} + +/// `before` with `new` drawn again by `r` with `opts` only where `change` says, checked against +/// `after`. +fn patched(r: &mut Renderer, before: &Rendered, new: &Document, change: Changed, after: &Rendered, opts: &RenderOptions) { let mut patched = Rendered { width: W, height: H, pixels: before.pixels.clone() }; match change { Changed::Everything => patched.pixels = after.pixels.clone(), Changed::Nothing => {} Changed::Area(area) => { if let Some([x0, y0, x1, y1]) = view_pixels(area, view(), W, H) { - let part = r.render(new, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))) * view(), &opts); + let part = r.render(new, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))) * view(), opts); for y in 0..y1 - y0 { let (from, to) = ((y * (x1 - x0) * 4) as usize, (((y0 + y) * W + x0) * 4) as usize); let n = ((x1 - x0) * 4) as usize; @@ -78,7 +90,6 @@ fn redraw(old: &Document, new: &Document) -> Changed { } } assert!(patched.pixels == after.pixels, "{change:?}: drawn again only there, it differs from drawing it all"); - change } fn area(c: Changed) -> Rect { @@ -421,3 +432,307 @@ fn a_path_painted_by_its_whole_shape_changes_whole_when_an_anchor_moves() { let a = area(redraw(&plain, &added)); assert!(a.width() > 80.0 && a.height() > 60.0, "{a:?}"); } + +/// Changing a 3D effect's parameters on `make`'s object, from `before` to `after`. +fn three_d_change(make: impl Fn(&mut Document) -> Node, id: &str, before: serde_json::Value, after: serde_json::Value) -> Changed { + let effect = |params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true }; + let mut old = Document::new(110.0, 80.0); + let l = old.layers[0].id; + let mut n = make(&mut old); + n.appearance.effects.push(effect(before)); + let n = old.insert(Some(l), 0, n).unwrap(); + let mut new = old.clone(); + new.node_mut(n).unwrap().appearance.effects[0] = effect(after); + redraw(&old, &new) +} + +/// Type and a group draw a 3D effect as solids that reach past their letters and members: a +/// shallower or turned solid changes where the deeper one drew too. +#[test] +fn a_3d_effect_changed_on_type_or_a_group_changes_where_its_solid_was() { + use vectorcraft_doc::{CharStyle, TextObject}; + let blue = Color::rgb(0.1, 0.2, 0.6); + let type_k = move |d: &mut Document| { + let style = CharStyle { size: 30.0, fill: Paint::solid(blue), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(40.0, 50.0), "K", style)))) + }; + let group = move |d: &mut Document| { + let (a, b) = (rect(d, Rect::new(40.0, 30.0, 50.0, 50.0), blue), rect(d, Rect::new(52.0, 30.0, 60.0, 50.0), blue)); + Node::group(d.alloc_id(), vec![Arc::new(a), Arc::new(b)]) + }; + let at = |depth: f64| serde_json::json!({"depth": depth, "position": "isometricTop"}); + for make in [&type_k as &dyn Fn(&mut Document) -> Node, &group] { + for (id, before, after) in [ + ("threeD.extrude", at(60.0), at(5.0)), + ("threeD.inflate", at(40.0), at(2.0)), + ("threeD.rotate", serde_json::json!({"rotationX": 0.0}), serde_json::json!({"rotationX": 80.0})), + ] { + // `redraw` holds the pixels drawn again only where it changed to drawing it all, and + // only an area of the document is drawn again. + area(three_d_change(make, id, before, after)); + } + } + // Type on a path, a group with a hidden member, and a group in a group. + let on_path = move |d: &mut Document| { + let style = CharStyle { size: 14.0, fill: Paint::solid(blue), ..Default::default() }; + let mut t = TextObject::point(Point::ZERO, "Along", style); + let line = kurbo::Line::new((30.0, 55.0), (80.0, 35.0)).to_path(0.1); + t.kind = vectorcraft_doc::TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(&line), start: 0.0, end: None }; + t.xf = Affine::IDENTITY; + t.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds); + Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))) + }; + let hiding = move |d: &mut Document| { + let mut hidden = rect(d, Rect::new(10.0, 10.0, 20.0, 20.0), blue); + hidden.visible = false; + let shown = rect(d, Rect::new(40.0, 30.0, 60.0, 50.0), blue); + Node::group(d.alloc_id(), vec![Arc::new(hidden), Arc::new(shown)]) + }; + let nested = move |d: &mut Document| { + let inner = group(d); + Node::group(d.alloc_id(), vec![Arc::new(inner)]) + }; + for make in [&on_path as &dyn Fn(&mut Document) -> Node, &hiding, &nested] { + area(three_d_change(make, "threeD.extrude", at(60.0), at(5.0))); + } + // A revolved path, and revolved type, which Revolve leaves as it is. + let path = move |d: &mut Document| rect(d, Rect::new(40.0, 30.0, 60.0, 50.0), blue); + for make in [&path as &dyn Fn(&mut Document) -> Node, &type_k] { + area(three_d_change(make, "threeD.revolve", serde_json::json!({"offset": 30.0}), serde_json::json!({"offset": 0.0}))); + } +} + +/// A renderer that drew a document measures what an edit changed through what it keeps +/// ([`Renderer::changed`]): the same area as [`changed`], and the 3D art it made to measure the +/// edit it draws the edit with, making none again. [`changed`] makes its own, and the renderer +/// makes the art again to draw it. +#[test] +fn a_renderer_measures_an_edit_with_the_3d_art_it_draws() { + use vectorcraft_doc::{CharStyle, TextObject}; + let mut old = Document::new(110.0, 80.0); + let style = CharStyle { size: 30.0, fill: Paint::solid(Color::rgb(0.1, 0.2, 0.6)), ..Default::default() }; + let mut n = Node::new(old.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(40.0, 50.0), "K", style)))); + let extrude = |depth: f64| vectorcraft_doc::Effect { + id: "threeD.extrude".into(), + params: serde_json::json!({"depth": depth, "position": "isometricTop"}), + visible: true, + }; + n.appearance.effects.push(extrude(60.0)); + let l = old.layers[0].id; + let id = old.insert(Some(l), 0, n).unwrap(); + let mut new = old.clone(); + new.node_mut(id).unwrap().appearance.effects[0] = extrude(5.0); + let opts = RenderOptions::default(); + let _fonts = crate::tests_fontchange::fonts_steady(); + let (measured, built, apart) = crate::tests_fontchange::with_fonts_unchanged(|| { + let mut r = Renderer::new(); + r.render(&old, W, H, view(), &opts); + let measured = area(r.changed(&old, &new, &opts)); + r.render(&new, W, H, view(), &opts); + let mut fresh = Renderer::new(); + fresh.render(&old, W, H, view(), &opts); + let _ = changed(&old, &new); + fresh.render(&new, W, H, view(), &opts); + (measured, r.stats.three_d_built, fresh.stats.three_d_built) + }); + assert_eq!(measured, area(changed(&old, &new)), "as changed measures it"); + assert_eq!(built, 0, "drawn with the art made to measure it"); + assert_eq!(apart, 1, "changed keeps nothing for the renderer"); +} + +/// An Image Trace object shown with its source image (`view`): its hidden source, a red image at +/// the left, and two traced shapes, at the right; the object's id, and the ids of the source and +/// of the second shape. +fn traced(view: &str) -> (Document, NodeId, NodeId, NodeId) { + let mut d = Document::new(W as f64, H as f64); + let mut png = vec![]; + let red = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])); + red.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + d.images.insert("red".into(), vectorcraft_doc::ImageBlob::new("image/png", png)); + let source = red_image(&mut d, 10.0); + let a = rect(&mut d, Rect::new(60.0, 10.0, 70.0, 20.0), Color::rgb(0.0, 0.5, 0.0)); + let b = rect(&mut d, Rect::new(80.0, 10.0, 90.0, 20.0), Color::rgb(1.0, 0.5, 0.0)); + let ids = (source.id, b.id); + let mut g = Node::group(d.alloc_id(), vec![Arc::new(source), Arc::new(a), Arc::new(b)]); + g.extras_mut().trace = Some(Box::new(serde_json::json!({ "view": view }))); + let l = d.layers[0].id; + let g = d.insert(Some(l), 0, g).unwrap(); + (d, g, ids.0, ids.1) +} + +/// A hidden 30 pt square of the red image at (`x`, 10), as an Image Trace object's source. +fn red_image(d: &mut Document, x: f64) -> Node { + let xf = Affine::translate((x, 10.0)) * Affine::scale(30.0); + let im = vectorcraft_doc::ImageObject { key: "red".into(), width: 1, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + let mut source = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + source.visible = false; + source +} + +/// Draws `new` again only where the renderer that drew `old` on screen, its Image Trace objects in +/// their views, measures that it changed, and checks that this is `new` drawn whole. +fn redraw_traced(old: &Document, new: &Document) -> Changed { + let opts = RenderOptions { trace_views: true, ..Default::default() }; + let after = Renderer::new().render(new, W, H, view(), &opts); + let mut r = Renderer::new(); + let before = r.render(old, W, H, view(), &opts); + let red = |r: &Rendered| r.pixels.chunks(4).any(|p| p[0] > 200 && p[1] < 60); + assert!(red(&before) || red(&after), "a source shows"); + let measured = r.changed(old, new, &opts); + patched(&mut r, &before, new, measured, &after, &opts); + measured +} + +#[test] +fn moving_a_trace_objects_source_changes_where_it_shows() { + for view in ["sourceImage", "outlinesWithSourceImage"] { + let (old, _, source, _) = traced(view); + let mut new = old.clone(); + new.node_mut(source).unwrap().transform(Affine::translate((5.0, 30.0)), false); + let a = area(redraw_traced(&old, &new)); + assert!(a.contains(Point::new(12.0, 12.0)) && a.contains(Point::new(44.0, 69.0)), "{view}: before and after: {a:?}"); + } +} + +/// A trace object's source that is first again after an edit (undoing Send to Back on a traced +/// shape), or a new source in its place, draws where it shows. +#[test] +fn a_trace_objects_new_first_member_is_its_source() { + let (back, g, source, shape) = traced("sourceImage"); + // The shape sent to the back, before the source. + let mut sent = back.clone(); + let children = sent.node_mut(g).unwrap().children_mut().unwrap(); + let at = children.iter().position(|c| c.id == shape).unwrap(); + let moved = children.remove(at); + children.insert(0, moved); + redraw_traced(&sent, &back); + // A new source image, with an id of its own. + let mut replaced = back.clone(); + let new_source = red_image(&mut replaced, 55.0); + let children = replaced.node_mut(g).unwrap().children_mut().unwrap(); + assert_eq!(children[0].id, source); + children[0] = Arc::new(new_source); + redraw_traced(&back, &replaced); +} + +/// Recoloring a traced shape changes only the shape, as the free measure and the renderer that drew +/// the trace object in its view measure it. Through the renderer the area is bounded, not drawn +/// again and compared: in this view (outlines with the source image) a partial render of the +/// outlines differs from the whole by one in alpha on a few dozen hairline pixels, either way, +/// which is older than this test and has nothing to do with what changed (the recolor changes no +/// pixel in this view). +#[test] +fn recolouring_a_traced_shape_changes_only_the_shape() { + let (old, _, _, shape) = traced("outlinesWithSourceImage"); + let mut new = old.clone(); + new.node_mut(shape).unwrap().appearance.fill_mut().unwrap().paint = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + // The shape, half its 2 pt stroke and a pixel's anti-aliasing, at most: measured by the + // renderer that drew the trace object in its view, and by the free measure. + let opts = RenderOptions { trace_views: true, ..Default::default() }; + let mut r = Renderer::new(); + r.render(&old, W, H, view(), &opts); + let measured = area(r.changed(&old, &new, &opts)); + let shape = Rect::new(80.0, 10.0, 90.0, 20.0).inflate(2.0, 2.0); + for (what, a) in [("measured", measured), ("free", area(redraw(&old, &new)))] { + assert!(a.union(shape) == shape, "{what}: only the shape: {a:?}"); + } +} + +/// Templates and guides that the view hides draw nothing: an edit to them changes nothing. +#[test] +fn an_edit_to_what_the_view_hides_changes_nothing() { + let mut old = Document::new(W as f64, H as f64); + let template = Node::layer(old.alloc_id(), "Template", vectorcraft_doc::LayerColor::Preset(1)); + let template = old.insert(None, usize::MAX, template).unwrap(); + if let Some(NodeKind::Layer { template: t, .. }) = old.node_mut(template).map(|n| &mut n.kind) { + *t = true; + } + let traced = rect(&mut old, Rect::new(10.0, 10.0, 40.0, 40.0), Color::rgb(0.5, 0.5, 0.5)); + let traced = old.insert(Some(template), 0, traced).unwrap(); + let mut guide = rect(&mut old, Rect::new(60.0, 10.0, 90.0, 40.0), Color::BLACK); + if let NodeKind::Path { guide: g, .. } = &mut guide.kind { + *g = true; + } + let l = old.layers[0].id; + let guide = old.insert(Some(l), 0, guide).unwrap(); + let mut new = old.clone(); + for id in [traced, guide] { + new.node_mut(id).unwrap().transform(Affine::translate((5.0, 5.0)), false); + } + let opts = RenderOptions { hide_templates: true, hide_guides: true, ..Default::default() }; + let mut r = Renderer::new(); + r.render(&old, W, H, view(), &opts); + assert_eq!(r.changed(&old, &new, &opts), Changed::Nothing); + assert!(matches!(changed(&old, &new), Changed::Area(_)), "shown, they change"); +} + +/// Overprint Preview and separations draw objects through the inks they print, not through the +/// art a renderer keeps for them: a renderer measures an edit there holding none of the 3D art it +/// made to measure it, and as [`changed`] does. +#[test] +fn an_edit_measured_under_overprint_holds_no_art() { + use vectorcraft_doc::{CharStyle, TextObject}; + let mut old = Document::new(110.0, 80.0); + let style = CharStyle { size: 30.0, fill: Paint::solid(Color::rgb(0.1, 0.2, 0.6)), ..Default::default() }; + let mut n = Node::new(old.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(40.0, 50.0), "K", style)))); + let extrude = |depth: f64| vectorcraft_doc::Effect { + id: "threeD.extrude".into(), + params: serde_json::json!({"depth": depth, "position": "isometricTop"}), + visible: true, + }; + n.appearance.effects.push(extrude(60.0)); + let l = old.layers[0].id; + let id = old.insert(Some(l), 0, n).unwrap(); + let mut new = old.clone(); + new.node_mut(id).unwrap().appearance.effects[0] = extrude(5.0); + let _fonts = crate::tests_fontchange::fonts_steady(); + let held = |opts: &RenderOptions| { + crate::tests_fontchange::with_fonts_unchanged(|| { + let mut r = Renderer::new(); + r.render(&old, W, H, view(), opts); + (area(r.changed(&old, &new, opts)), r.measured_bytes()) + }) + }; + let (_, on_screen) = held(&RenderOptions::default()); + assert!(on_screen > 0, "the screen view holds the art it measured with"); + let (measured, overprinted) = held(&RenderOptions { overprint_preview: true, ..Default::default() }); + assert_eq!(overprinted, 0); + // A consistency check: the area itself doesn't tell the branch taken. + assert_eq!(measured, area(changed(&old, &new)), "as changed measures it"); +} + +/// Symbol editing mode on screen doesn't draw the instance it was entered from: an edit to that +/// instance changes nothing there, and changes where it draws in an export. +#[test] +fn an_edit_to_the_instance_symbol_editing_came_from_changes_nothing_on_screen() { + use vectorcraft_doc::{Symbol, SymbolEdit}; + let mut old = Document::new(W as f64, H as f64); + let art = rect(&mut old, Rect::new(20.0, 20.0, 50.0, 50.0), Color::rgb(0.0, 0.5, 0.0)); + old.symbols.push(Symbol { dynamic: false, name: "Square".into(), art: Arc::new(art.clone()) }); + let inst = Node::new(old.alloc_id(), NodeKind::SymbolInstance { symbol: "Square".into(), xf: Affine::IDENTITY }); + let l = old.layers[0].id; + let inst = old.insert(Some(l), 0, inst).unwrap(); + let layer = old.add_layer(Some("Square")); + let copy = old.reid(&art); + old.insert(Some(layer), usize::MAX, copy).unwrap(); + old.symbol_edit = Some(SymbolEdit { + symbol: "Square".into(), + layer, + instance: Some(inst), + xf: Affine::IDENTITY, + group: false, + changed: false, + back_isolation: None, + back_layer: None, + }); + let mut new = old.clone(); + new.node_mut(inst).unwrap().transform(Affine::translate((30.0, 30.0)), false); + let screen = RenderOptions { isolated: Some(layer), ..Default::default() }; + let mut r = Renderer::new(); + r.render(&old, W, H, view(), &screen); + assert_eq!(r.changed(&old, &new, &screen), Changed::Nothing); + let export = RenderOptions::default(); + let mut r = Renderer::new(); + r.render(&old, W, H, view(), &export); + assert!(matches!(r.changed(&old, &new, &export), Changed::Area(_)), "an export draws it"); +} diff --git a/crates/render/src/tests/fontchange.rs b/crates/render/src/tests/fontchange.rs index 5b0f60091a..82c5c77ff7 100644 --- a/crates/render/src/tests/fontchange.rs +++ b/crates/render/src/tests/fontchange.rs @@ -371,3 +371,34 @@ fn a_renderer_maps_enveloped_type_from_its_glyphs_in_the_current_font() { assert!(off(before, after) > 0.5, "the type draws in the font that arrived: {before:?} vs {after:?}"); assert!(off(src(), after) < 1e-6, "{:?} vs {after:?}", src()); } + +/// 3D type measured for an edit ([`Renderer::changed`]) and drawn after its font became available +/// is drawn in that font: the art made to measure it, in the font it had, isn't taken. +#[test] +fn three_d_type_measured_before_its_font_arrives_draws_in_it() { + let _adding = adding_fonts(); + const FAMILY: &str = "Solid Serif 44"; + let mut old = Document::new(300.0, 150.0); + let style = CharStyle { size: 60.0, font_family: FAMILY.into(), ..Default::default() }; + let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 100.0), "Hamburg", style)))); + n.id = old.alloc_id(); + let extrude = |depth: f64| vectorcraft_doc::Effect { + id: "threeD.extrude".into(), + params: serde_json::json!({"depth": depth, "position": "isometricTop"}), + visible: true, + }; + n.appearance.effects.push(extrude(40.0)); + let l = old.layers[0].id; + let id = old.insert(Some(l), 0, n).unwrap(); + let mut new = old.clone(); + new.node_mut(id).unwrap().appearance.effects[0] = extrude(10.0); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + r.render(&old, 300, 150, Affine::IDENTITY, &opts); + let _ = r.changed(&old, &new, &opts); + assert!(vectorcraft_text::FontDb::global().add_font(serif_as(FAMILY)) > 0); + let drawn = r.render(&new, 300, 150, Affine::IDENTITY, &opts).pixels; + let fresh = Renderer::new().render(&new, 300, 150, Affine::IDENTITY, &opts).pixels; + let differ = drawn.iter().zip(&fresh).filter(|(a, b)| a != b).count(); + assert_eq!(differ, 0, "as a new renderer draws it"); +} diff --git a/crates/render/src/tests/knockout.rs b/crates/render/src/tests/knockout.rs index 2a7e51e81b..4043173aeb 100644 --- a/crates/render/src/tests/knockout.rs +++ b/crates/render/src/tests/knockout.rs @@ -116,15 +116,63 @@ fn page_knockout_and_isolated_blending() { Arc::make_mut(&mut d.layers[0]).knockout = Knockout::Off; assert!(close(render(&d).pixel(50, 50), BLUE_OVER_RED)); - // Page Isolated Blending: a Difference object no longer blends with the white under the page. + // A Difference object on the bare page keeps its color: the background goes under the + // finished art (#6125), with Page Isolated Blending or without it. let mut d = Document::new(100.0, 100.0); let mut red = half(&mut d, 10.0, (1.0, 0.0, 0.0)); red.opacity = 1.0; red.blend = Blend::Difference; d.insert(Some(d.layers[0].id), 0, red).unwrap(); - assert!(close(render(&d).pixel(30, 50), [0, 255, 255, 255]), "inverts the white: {:?}", render(&d).pixel(30, 50)); + assert!(close(render(&d).pixel(30, 50), [255, 0, 0, 255]), "the bare page: {:?}", render(&d).pixel(30, 50)); d.page_isolate = true; assert!(close(render(&d).pixel(30, 50), [255, 0, 0, 255]), "isolated: {:?}", render(&d).pixel(30, 50)); + // A white object under it is art: the Difference object inverts it. + let id = d.alloc_id(); + let white = Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0)); + d.insert(Some(d.layers[0].id), 0, white).unwrap(); + assert!(close(render(&d).pixel(30, 50), [0, 255, 255, 255]), "inverts the white object: {:?}", render(&d).pixel(30, 50)); +} + +/// On a white or blue background, every blend mode on the bare page gives the transparent +/// render over that color (#6125). +#[test] +fn no_blend_mode_reads_the_background() { + for mode in Blend::ALL { + let mut d = Document::new(100.0, 100.0); + let mut red = half(&mut d, 10.0, (1.0, 0.0, 0.0)); + red.blend = mode; + d.insert(Some(d.layers[0].id), 0, red).unwrap(); + let clear = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()).pixel(30, 50); + for bg in [[255, 255, 255, 255], [0, 0, 255, 255]] { + let got = + Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { background: Some(bg), ..Default::default() }).pixel(30, 50); + let a = i32::from(clear[3]); + let want = [0, 1, 2].map(|c| (i32::from(clear[c]) * a + i32::from(bg[c]) * (255 - a)) / 255); + assert!((0..3).all(|c| (i32::from(got[c]) - want[c]).abs() <= 3) && got[3] == 255, "{mode:?} on {bg:?}: {got:?}, want {want:?}"); + } + } +} + +/// Premultiplied pixels of alpha 0, 128 and 255 over backgrounds of alpha 0, 128 and 255. +#[test] +fn over_background_composites_premultiplied_pixels() { + let over = |p: [u8; 4], a: u8| { + let mut px = p.to_vec(); + crate::renderer::over_background(&mut px, [200, 100, 0, a]); + [px[0], px[1], px[2], px[3]] + }; + const CLEAR: [u8; 4] = [0; 4]; + const HALF: [u8; 4] = [64, 10, 100, 128]; + const SOLID: [u8; 4] = [9, 8, 7, 255]; + assert_eq!(over(CLEAR, 0), CLEAR); + assert_eq!(over(HALF, 0), HALF); + assert_eq!(over(SOLID, 0), SOLID); + assert_eq!(over(CLEAR, 128), [100, 50, 0, 128]); + assert_eq!(over(HALF, 128), [114, 35, 100, 192]); + assert_eq!(over(SOLID, 128), SOLID); + assert_eq!(over(CLEAR, 255), [200, 100, 0, 255]); + assert_eq!(over(HALF, 255), [164, 60, 100, 255]); + assert_eq!(over(SOLID, 255), SOLID); } #[test] diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index ef8972c3a9..fe1e5ee1d1 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -771,6 +771,64 @@ fn rasterize_on_an_image_takes_in_its_strokes_shape() { assert_eq!((lum(img.pixel(8, 35)), lum(img.pixel(12, 35)), img.pixel(35, 35)), (WHITE, 0, [255, 0, 0, 255])); } +/// A 40 pt square filled with `fill` carrying effect `id`, in a 100×100 document. +fn glowing_square(fill: Color, id: &str, params: Value) -> Document { + let mut n = Node::path(NodeId(0), shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)), Appearance::basic(Paint::solid(fill), Paint::None, 0.0)); + n.appearance.effects.push(fx(id, params)); + doc_with(Document::new(100.0, 100.0), n) +} + +/// A glow on the bare page is drawn before the background goes under the art: the pixel is the +/// transparent render's over that color, also for a background other than white (#6125). +#[test] +fn a_screen_outer_glow_on_the_bare_page_shows_on_a_background() { + let d = glowing_square(Color::WHITE, "stylize.outerGlow", json!({})); + let clear = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()).pixel(27, 50); + assert!(clear[0] > 20 && clear[0] == clear[1] && clear[2] == 0, "the glow is yellow: {clear:?}"); + for (bg, name) in [([255, 255, 255, 255], "white"), ([0, 0, 255, 255], "blue")] { + let p = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { background: Some(bg), ..Default::default() }).pixel(27, 50); + let a = u32::from(clear[3]); + let want: Vec = (0..3).map(|c| (u32::from(clear[c]) * a + u32::from(bg[c]) * (255 - a)) / 255).collect(); + assert!(a > 0 && (0..3).all(|c| u32::from(p[c]).abs_diff(want[c]) <= 2), "{name}: {p:?}, want {want:?}"); + assert_eq!(p[3], 255, "{name}: opaque"); + } +} + +/// A thumbnail with a background shows a Screen glow on the bare page, opaque (#6125). +#[test] +fn a_screen_outer_glow_is_in_a_thumbnail_on_a_background() { + let d = glowing_square(Color::WHITE, "stylize.outerGlow", json!({})); + let n = d.layers[0].children().unwrap()[0].clone(); + let img = Renderer::new().render_node_thumbnail(&d, &n, 100, Some([255; 4])).unwrap(); + let pixels = img.pixels.as_chunks::<4>().0; + assert!(pixels.iter().all(|p| p[3] == 255), "every pixel is opaque"); + assert!(pixels.iter().any(|p| p[0] > 235 && p[1] > 235 && p[2] < 235), "the glow shows as yellow on white"); +} + +/// The ink planes put the background under the art too: on a white background a Screen glow on +/// the bare page prints yellow ink, and the bare page around it prints none (#6125). +#[test] +fn a_screen_outer_glow_prints_ink_on_a_background() { + let d = glowing_square(Color::WHITE, "stylize.outerGlow", json!({})); + let opts = RenderOptions { background: Some([255; 4]), ..Default::default() }; + let inks = Renderer::new().render_region_inks(&d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, &opts); + let at = |x: usize, y: usize| &inks[(y * 100 + x) * 4..][..4]; + assert!(at(27, 50)[2] > 10, "yellow ink in the glow: {:?}", at(27, 50)); + assert_eq!(at(5, 50), [0; 4], "no ink on the bare page"); +} + +/// An Inner Glow blends with the object's own fill whatever is under the page: white Screen +/// lightens a black square, red Screen leaves a white one white, and red Normal shows on it. +#[test] +fn an_inner_glow_blends_with_its_own_fill_on_a_background() { + let red = |mode: &str| json!({"color": "#ff0000", "mode": mode, "opacity": 100}); + let dark = render(&glowing_square(Color::BLACK, "stylize.innerGlow", json!({"color": "#ffffff", "opacity": 100}))).pixel(32, 50); + assert!(dark[0] > 20 && dark[0] == dark[1], "the white glow lightens the black edge: {dark:?}"); + assert_eq!(render(&glowing_square(Color::WHITE, "stylize.innerGlow", red("screen"))).pixel(32, 50), [255, 255, 255, 255]); + let normal = render(&glowing_square(Color::WHITE, "stylize.innerGlow", red("normal"))).pixel(32, 50); + assert!(normal[0] == 255 && normal[1] < 245, "red on the white edge: {normal:?}"); +} + #[test] fn a_strokes_own_glow_paints_around_that_stroke_only() { let mut d = Document::new(100.0, 100.0); diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 13c4268472..eed8ecd335 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -98,7 +98,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: brushes: None, knockout: doc.page_knockout, anonymous: false, - knockout_filter: None, + knockout_filters: HashMap::new(), + region_boxes: None, + art_reach: HashMap::new(), warnings: vec![], id_prefix, linked: Vec::new(), @@ -255,8 +257,13 @@ struct Writer<'a> { knockout: bool, /// Writing a copy of an object (a knockout mask): no object ids, so they stay unique. anonymous: bool, - /// The filter that paints art black keeping its alpha (knockout masks), once defined. - knockout_filter: Option, + /// The filters that paint art black keeping its alpha (knockout masks), by the region + /// attributes they were defined with. + knockout_filters: HashMap, + /// The document's symbol boxes, measured once for every mask and filter region. + region_boxes: Option>, + /// How far each symbol's art paints past its box, by name, once measured for a region. + art_reach: HashMap, /// The brush library, parsed when the first brushed stroke is written. brushes: Option>, /// Features written approximately (once each). diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index adcd3fd259..129bd83e28 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -2,8 +2,8 @@ use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_vali use super::paint::{StrokePlan, has_raster, pixel_gradient}; use super::text::OUTLINE_TOLERANCE; use super::{ - Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer, Writer, - Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, + Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, HashMap, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer, + Writer, Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, }; /// A symbol's `` def and the instance transforms that can `` it. @@ -143,9 +143,12 @@ fn pin_to_page(n: &mut Node, m: Affine) { const TINY_MASKS: &str = "SVG Tiny 1.2 has no masks: opacity masks are left out and knockout groups written as plain groups"; pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; -/// A region covering any artwork (mask and filter extents). +/// The region of a mask or filter over art that has no box to measure: one covering any artwork. const BIG: &str = "x=\"-100000\" y=\"-100000\" width=\"200000\" height=\"200000\""; +/// How deep [`Writer::paint_reach`] looks into members and symbol art. +const MAX_REACH_DEPTH: u32 = 64; + /// Attributes of every ``: user-space units, and luminance taken from the sRGB values (as the /// canvas and PDF take it) rather than from linearised ones. pub(super) const MASK: &str = "maskUnits=\"userSpaceOnUse\" color-interpolation=\"sRGB\""; @@ -354,13 +357,18 @@ impl Writer<'_> { return self.node_body(&bare); } let mid = self.fresh_id("mask"); + let mut bare = n.clone(); + bare.extras_mut().mask = None; + // The region covers what the object and the mask art paint: readers draw the mask into an + // image of the region's size. + let region = self.region_attrs(&[&bare, &m.art]); // Mask art is a picture of its own: it takes no part in a knockout group around the object. let knockout = std::mem::take(&mut self.knockout); let art = self.detached(2, |w| w.node(&m.art)); self.knockout = knockout; let inv = m.invert.then(|| { let fid = self.fresh_id("invert"); - self.def(1, &format!("")); + self.def(1, &format!("")); self.def(2, ""); self.def(1, ""); fid @@ -368,13 +376,13 @@ impl Writer<'_> { // The mask's options, so import restores them (and its art without backdrop and filter). let flags: Vec<&str> = [(!m.clip).then_some("noclip"), m.invert.then_some("invert")].into_iter().flatten().collect(); let data = if flags.is_empty() { String::new() } else { format!(" {MASK_FLAGS}=\"{}\"", flags.join(" ")) }; - self.def(1, &format!("")); + self.def(1, &format!("")); if let Some(fid) = &inv { self.def(1, &format!("")); } if !m.clip || m.invert { let c = if m.clip { "black" } else { "white" }; - self.def(1, &format!("")); + self.def(1, &format!("")); } self.defs.push_str(&art); if inv.is_some() { @@ -383,8 +391,6 @@ impl Writer<'_> { self.def(1, ""); self.line(&format!("")); self.depth += 1; - let mut bare = n.clone(); - bare.extras_mut().mask = None; self.node_body(&bare); self.depth -= 1; self.line(""); @@ -399,6 +405,127 @@ impl Writer<'_> { std::mem::replace(&mut self.body, body) } + /// The `x`, `y`, `width` and `height` of a mask or filter region over `nodes`, in the current + /// user space: the box of everything they paint ([`Self::paint_reach`]), 2 larger on each + /// side for antialiasing. [`BIG`] when none of them has a box, when one holds type (a reader + /// sets live type in its own font, which can be wider, and type on a path is measured by its + /// path), or when one nests deeper than [`MAX_REACH_DEPTH`]. The art of a symbol instance + /// written in place keeps its strokes and effects at their own size while the instance scales + /// its geometry, so the region also covers the geometry's box, placed, grown by the strokes' + /// and effects' reach unscaled. + fn region_attrs(&mut self, nodes: &[&Node]) -> String { + let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes()); + let mut art_reach = std::mem::take(&mut self.art_reach); + let region = self.region_of(&symbols, &mut art_reach, nodes); + self.region_boxes = Some(symbols); + self.art_reach = art_reach; + region + } + + /// [`Self::region_attrs`] with the document's symbol boxes and the symbols' art reach so far. + fn region_of(&self, symbols: &vectorcraft_doc::SymbolBoxes, art_reach: &mut HashMap, nodes: &[&Node]) -> String { + let mut painted: Option = None; + for n in nodes { + let Some(v) = n.visual_bounds_with(symbols) else { continue }; + let Some(r) = self.paint_reach(symbols, art_reach, n, v, 0) else { + return BIG.to_string(); + }; + let g = n.geometric_bounds_with(symbols).unwrap_or(v); + let stroke = [g.x0 - v.x0, g.y0 - v.y0, v.x1 - g.x1, v.y1 - g.y1].into_iter().fold(0.0, f64::max); + let scaled = self.xf.transform_rect_bbox(v.inflate(r, r)); + let unscaled = self.xf.transform_rect_bbox(g).inflate(stroke + r, stroke + r); + let both = scaled.union(unscaled); + painted = Some(painted.map_or(both, |p| p.union(both))); + } + let Some(b) = painted.map(|b| b.inflate(2.0, 2.0)).filter(|b| b.is_finite()) else { + return BIG.to_string(); + }; + format!("x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"", self.num(b.x0), self.num(b.y0), self.num(b.width()), self.num(b.height())) + } + + /// How far what `n` paints reaches past its visual box `b`: the reach of its own raster effects + /// and of those of its fills and strokes (measured as [`Self::open_filters`] measures them), + /// how far brush art can paint past its brushed strokes (`16 × w + 8` for the widest brushed + /// stroke `w`, as the canvas allows for it), and the most that one of its members or its + /// symbol's art reaches past its own box, spread by its own effects. `art_reach` keeps each + /// symbol's art reach by name once measured, so art used many times is measured once. A live + /// object is measured as the art it is written as: expanded on its own, as [`Self::node`] + /// expands it, so with the same limits. `None` when `n`, its members or its symbol's art hold + /// type, or nest deeper than [`MAX_REACH_DEPTH`]. + fn paint_reach( + &self, + symbols: &vectorcraft_doc::SymbolBoxes, + art_reach: &mut HashMap, + n: &Node, + b: Rect, + depth: u32, + ) -> Option { + use vectorcraft_effects::RasterFx; + // Type draws past its measured box in a reader's own font. + if matches!(n.kind, NodeKind::Text(_)) { + return None; + } + // An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first. + let grow = 18.0 / self.doc.raster_ppi(); + let reach = |effects: &[vectorcraft_doc::Effect]| -> f64 { + vectorcraft_effects::raster_effects(effects) + .iter() + .map(|f| f.outset(b) + if matches!(f, RasterFx::OuterGlow { .. }) { grow } else { 0.0 }) + .sum() + }; + let items = n.appearance.items.iter().map(|i| reach(i.effects())).fold(0.0, f64::max); + let brush = if vectorcraft_brush::has_brush(n) { + let w = + n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max); + 16.0 * w + 8.0 + } else { + 0.0 + }; + let own = reach(&n.appearance.effects) + items + brush; + if vectorcraft_doc::live::is_live(n) { + if depth >= MAX_REACH_DEPTH { + return None; + } + let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + let Some(gb) = g.visual_bounds_with(symbols) else { return Some(own) }; + let past = [b.x0 - gb.x0, b.y0 - gb.y0, gb.x1 - b.x1, gb.y1 - b.y1].into_iter().fold(0.0, f64::max); + return Some(own + past + self.paint_reach(symbols, art_reach, &g, gb, depth + 1)?); + } + let symbol = match &n.kind { + NodeKind::SymbolInstance { symbol, xf } => self.doc.symbols.iter().find(|s| s.name == *symbol).map(|s| (s, xf)), + _ => None, + }; + if n.children().is_none_or(|c| c.is_empty()) && symbol.is_none() { + return Some(own); + } + if depth >= MAX_REACH_DEPTH { + return None; + } + let mut inner: f64 = 0.0; + for c in n.children().into_iter().flatten() { + if let Some(cb) = c.visual_bounds_with(symbols) { + inner = inner.max(self.paint_reach(symbols, art_reach, c, cb, depth + 1)?); + } + } + if let Some((s, xf)) = symbol { + let art = match art_reach.get(&s.name) { + Some(r) => *r, + None => { + let r = match s.art.visual_bounds_with(symbols) { + Some(ab) => self.paint_reach(symbols, art_reach, &s.art, ab, depth + 1)?, + None => 0.0, + }; + art_reach.insert(s.name.clone(), r); + r + } + }; + // The art's reach, measured in symbol space, as far as the instance can stretch it. + let [xx, xy, yx, yy, _, _] = xf.as_coeffs(); + inner = inner.max(art * xx.hypot(xy).max(yx.hypot(yy)).max(1.0)); + } + Some(own + inner) + } + /// Props of a group (or layer): a knockout group is isolated, a hidden one not displayed. fn group_props(&self, n: &Node) -> Props { let mut p = css::transparency(n); @@ -450,9 +577,12 @@ impl Writer<'_> { written.push((before, self.detached(depth + nest - 1 - i, |w| w.node(c)))); } let after = self.symbol_nodes; + // Each mask covers what the group's elements paint. + let all: Vec<&Node> = elements.iter().map(|c| &***c).collect(); + let region = self.region_attrs(&all); for (c, (before, _)) in rest.iter().zip(&written).rev() { self.symbol_nodes = *before; - let mid = self.knockout_mask(c); + let mid = self.knockout_mask(c, ®ion); self.line(&format!("")); self.depth += 1; } @@ -466,16 +596,18 @@ impl Writer<'_> { } /// A mask that is 1 − the knockout shape of `c`: white, then `c` painted black (at full object - /// opacity without its own mask, unless those define its shape). Returns the mask id. - fn knockout_mask(&mut self, c: &Node) -> String { - let filter = match &self.knockout_filter { + /// opacity without its own mask, unless those define its shape). `region` is the attributes of + /// the mask's region ([`Self::region_attrs`]), which the filter that paints `c` black shares. + /// Returns the mask id. + fn knockout_mask(&mut self, c: &Node, region: &str) -> String { + let filter = match self.knockout_filters.get(region) { Some(f) => f.clone(), None => { let f = self.fresh_id("knockout-shape"); - self.def(1, &format!("")); + self.def(1, &format!("")); self.def(2, ""); self.def(1, ""); - self.knockout_filter = Some(f.clone()); + self.knockout_filters.insert(region.to_string(), f.clone()); f } }; @@ -490,8 +622,8 @@ impl Writer<'_> { let art = self.detached(3, |w| w.node(&shape)); self.anonymous = anonymous; let mid = self.fresh_id("knockout"); - self.def(1, &format!("")); - self.def(2, &format!("")); + self.def(1, &format!("")); + self.def(2, &format!("")); self.def(2, &format!("")); self.defs.push_str(&art); self.def(2, ""); diff --git a/crates/svg/tests/it/blend_export.rs b/crates/svg/tests/it/blend_export.rs index 65fb26799c..3804d30ed2 100644 --- a/crates/svg/tests/it/blend_export.rs +++ b/crates/svg/tests/it/blend_export.rs @@ -1,10 +1,11 @@ //! Blend modes and opacity masks in SVG export look as on the canvas: every mode follows the //! reference formulas when resvg draws the file, and masks take luminance the canvas's way. +use usvg::roxmltree; use vectorcraft_color::blend::blend_rgb; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, OpacityMask}; -use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeKind, OpacityMask, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; use vectorcraft_svg::{ExportOptions, export}; use vectorcraft_testkit::raster::{Image, render_artboard}; @@ -138,3 +139,126 @@ fn a_knockout_group_with_a_brushed_stroke_keeps_its_masks() { let svg = export(&d, &ExportOptions::default()); assert!(svg.contains("` and `` element in `svg`. +fn regions(svg: &str) -> Vec<[f64; 4]> { + let xml = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }).unwrap(); + xml.descendants() + .filter(|n| matches!(n.tag_name().name(), "mask" | "filter")) + .map(|n| ["x", "y", "width", "height"].map(|a| n.attribute(a).and_then(|v| v.parse().ok()).unwrap_or(f64::NAN))) + .collect() +} + +/// Mask and filter regions cover the art they apply to and no more: readers draw a mask into an +/// image of its region's size, and one drawn at 200,000 units square runs out of memory. +#[test] +fn mask_and_filter_regions_cover_their_art() { + let knockout = { + let mut d = Document::new(40.0, 20.0); + let below = rect(&mut d, Rect::new(0.0, 0.0, 40.0, 20.0), [200, 0, 0]); + let mut top = rect(&mut d, Rect::new(5.0, 5.0, 15.0, 15.0), [0, 0, 200]); + top.opacity = 0.5; + let mut group = Node::group(d.alloc_id(), vec![below.into(), top.into()]); + group.knockout = vectorcraft_doc::Knockout::On; + add(&mut d, group); + d + }; + for (what, d) in [("clip", masked(true, false)), ("no clip, inverted", masked(false, true)), ("knockout", knockout)] { + let svg = export(&d, &ExportOptions::default()); + let found = regions(&svg); + assert!(!found.is_empty(), "{what}: {svg}"); + for [x, y, w, h] in found { + // The art is 40 × 20, with 2 to spare on each side. + assert!(x >= -2.5 && y >= -2.5 && w <= 45.0 && h <= 25.0 && w >= 40.0 && h >= 20.0, "{what}: {x} {y} {w} {h} in {svg}"); + } + } +} + +/// A mask's region reaches as far as the masked art paints: a drop shadow of the object, or of an +/// object in the masked group, shows past the object as on the canvas. +#[test] +fn a_mask_region_keeps_the_shadows_of_the_masked_art() { + let shadow = vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 15, "y": 15, "blur": 0, "opacity": 100}), + visible: true, + }; + for in_group in [false, true] { + let mut d = Document::new(60.0, 60.0); + let mut red = rect(&mut d, Rect::new(10.0, 10.0, 30.0, 30.0), [255, 0, 0]); + red.appearance.effects.push(shadow.clone()); + let mut masked = if in_group { Node::group(d.alloc_id(), vec![red.into()]) } else { red }; + // An unclipped mask lets the art show outside the mask art: all of the shadow shows. + let art = rect(&mut d, Rect::new(10.0, 10.0, 20.0, 30.0), [255, 255, 255]); + masked.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + add(&mut d, masked); + let svg = export(&d, &ExportOptions::default()); + let (canvas, written) = (render_artboard(&d), resvg_render(&svg, 60, 60)); + for (x, y) in [(15, 15), (40, 40), (35, 28)] { + let (c, w) = (canvas.over_white(x, y), written.over_white(x, y)); + assert!(within(c, w, 3), "in a group {in_group}, at {x},{y}: canvas {c:?}, svg {w:?}\n{svg}"); + } + assert!(canvas.over_white(40, 40)[0] < 100, "the shadow shows on the canvas: {:?}", canvas.over_white(40, 40)); + } +} + +/// Type is measured by its layout or its path, and a reader sets live type in its own font, so a +/// mask or knockout over type keeps the region that covers any artwork. +#[test] +fn mask_and_filter_regions_over_type_cover_any_artwork() { + let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + let text = |d: &mut Document| Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 30.0), "Wide", style.clone())))); + let masked = { + let mut d = Document::new(80.0, 40.0); + let mut t = text(&mut d); + let art = rect(&mut d, Rect::new(0.0, 0.0, 40.0, 40.0), [255, 255, 255]); + t.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + add(&mut d, t); + d + }; + let knockout = { + let mut d = Document::new(80.0, 40.0); + let below = rect(&mut d, Rect::new(0.0, 0.0, 80.0, 40.0), [200, 0, 0]); + let mut top = text(&mut d); + top.opacity = 0.5; + let mut group = Node::group(d.alloc_id(), vec![below.into(), top.into()]); + group.knockout = vectorcraft_doc::Knockout::On; + add(&mut d, group); + d + }; + for (what, d) in [("masked type", masked), ("type in a knockout group", knockout)] { + let svg = export(&d, &ExportOptions::default()); + let found = regions(&svg); + assert!(!found.is_empty(), "{what}: {svg}"); + for [x, y, w, h] in found { + assert!(x <= -100000.0 && y <= -100000.0 && w >= 200000.0 && h >= 200000.0, "{what}: {x} {y} {w} {h} in {svg}"); + } + } +} + +/// A live object under a mask is measured as it is written, expanded: the mask's region covers +/// the drop shadows of a blend's steps. +#[test] +fn a_mask_region_covers_a_blend_as_written() { + let shadow = vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 15, "y": 15, "blur": 0, "opacity": 100}), + visible: true, + }; + let mut d = Document::new(100.0, 50.0); + let mut a = rect(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), [255, 0, 0]); + let mut b = rect(&mut d, Rect::new(70.0, 10.0, 80.0, 20.0), [0, 0, 255]); + a.appearance.effects.push(shadow.clone()); + b.appearance.effects.push(shadow); + let mut blend = Node::new(d.alloc_id(), NodeKind::Blend { children: vec![a.into(), b.into()], spec: Default::default() }); + let art = rect(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0), [255, 255, 255]); + blend.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + add(&mut d, blend); + let svg = export(&d, &ExportOptions::default()); + // The steps' drop shadows are filters with regions of their own; the mask's covers them all: + // the steps run from 10 to 80 across, and their shadows 15 further. + let xml = roxmltree::Document::parse_with_options(&svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }).unwrap(); + let mask = xml.descendants().find(|n| n.has_tag_name("mask")).unwrap(); + let [x, y, w, h] = ["x", "y", "width", "height"].map(|a| mask.attribute(a).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN)); + assert!(x <= 0.0 && y <= 0.0 && x + w >= 95.0 && y + h >= 35.0 && w < 200.0 && h < 200.0, "{x} {y} {w} {h} in {svg}"); +} diff --git a/crates/svg/tests/it/container_export.rs b/crates/svg/tests/it/container_export.rs index 5f34b6cc3a..9518d31d21 100644 --- a/crates/svg/tests/it/container_export.rs +++ b/crates/svg/tests/it/container_export.rs @@ -92,5 +92,5 @@ fn a_group_transform_copies_its_images() { .filter(|l| l.starts_with("` would expand to about 20 MB from a file of a few KB: the import +/// refuses it before the XML reader expands anything. The namespace entities drawing apps write +/// (`&ns_svg;`) still import. +#[test] +fn entities_repeated_in_element_content_are_refused_and_namespace_entities_import() { + let bomb = format!( + r#"]>{}"#, + "x".repeat(10_000), + "&a;".repeat(250), + "&b;".repeat(8) + ); + assert!(bomb.len() < 20_000, "{} bytes", bomb.len()); + match import_with(&bomb, &ImportOptions::default()) { + Err(SvgError::Parse(e)) => assert!(e.contains("entities"), "{e}"), + other => panic!("refused as a parse error, not {:?}", other.map(|(_, w)| w)), + } + let ns = r#"]>"#; + let (d, _) = import_with(ns, &ImportOptions::default()).unwrap(); + assert_eq!(art(&d).len(), 1, "the rectangle"); +} diff --git a/crates/svg/tests/it/mask_options.rs b/crates/svg/tests/it/mask_options.rs index 541a8f702c..16c021391e 100644 --- a/crates/svg/tests/it/mask_options.rs +++ b/crates/svg/tests/it/mask_options.rs @@ -55,6 +55,27 @@ fn an_inverted_unclipped_mask_round_trips() { } } +/// Mask art that reaches past the masked object comes back whole: the mask's region covers the art +/// as well as the object, so import does not clip the art to the region. +#[test] +fn mask_art_larger_than_its_object_round_trips_unclipped() { + let mut d = Document::new(200.0, 200.0); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let white = Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0); + let mut n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(50.0, 50.0, 100.0, 100.0)), red); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 20.0, 180.0, 170.0)), white); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let s = export(&d, &ExportOptions::default()); + let (back, warnings) = import_with_report(&s).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let [m] = &masks(&back)[..] else { panic!("one masked object: {s}") }; + assert!(m.art.path_data().is_some(), "the art alone, not clipped by the region: {:?}\n{s}", m.art.kind); + let b = m.art.geometric_bounds().unwrap(); + assert!((b.x0 - 10.0).abs() < 1e-6 && (b.y0 - 20.0).abs() < 1e-6 && (b.x1 - 180.0).abs() < 1e-6 && (b.y1 - 170.0).abs() < 1e-6, "{b:?}"); +} + #[test] fn foreign_masks_keep_their_art() { // Without the attribute a white backdrop is part of the mask art (another app's file). diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index 0fad6ff096..3e58b02286 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -296,6 +296,31 @@ fn masks_in_symbols_move_with_the_art_when_linked() { } } +/// A masked object in a symbol's art, drawn by an instance that scales it down: its stroke keeps +/// its weight, and the mask's region still covers all of it. +#[test] +fn a_mask_in_a_scaled_instance_covers_the_strokes_at_their_weight() { + let mut d = Document::new(120.0, 120.0); + let stroked = Appearance::basic(Paint::solid(Color::rgb8(200, 0, 0)), Paint::solid(Color::BLACK), 20.0); + let mut art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), stroked); + let shape = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 100.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + art.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(shape, false))); + d.symbols.push(Symbol { dynamic: false, name: "Framed".into(), art: Arc::new(art) }); + instance(&mut d, "Framed", Affine::translate((50.0, 50.0)) * Affine::scale(0.2)); + let svg = export(&d, &ExportOptions::default()); + let (canvas, written) = (render_artboard(&d), resvg_render(&svg, 120, 120)); + // The stroke runs 10 either side of the 20 × 20 square's edge at (50, 50). + for (x, y) in [(43, 60), (77, 60), (60, 43), (60, 77)] { + let (c, w) = (canvas.over_white(x, y), written.over_white(x, y)); + assert!(c.iter().all(|v| *v < 60), "the stroke shows on the canvas at {x},{y}: {c:?}"); + assert!(c.iter().zip(w).all(|(a, b)| (*a as i32 - b as i32).abs() <= 8), "at {x},{y}: canvas {c:?}, svg {w:?}\n{svg}"); + } +} + #[test] fn symbols_inside_themselves_end() { let mut d = symbol_doc(1.0, &[Affine::translate((50.0, 50.0))]); diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index cbb2c20d2a..aab7f0e1f0 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -59,7 +59,8 @@ pub const VARIABLE_WIDEN: f32 = 0.25; /// axis (400–700, default 400, the face itself being Regular) whose maximum makes the glyphs of /// [`VARIABLE_CHARS`] [`VARIABLE_WIDEN`] wider (outlines and advances, through `gvar`), with the /// named instances Normal (the default, the face Regular), SemiBold (550) and Bold (700), plus an instance without -/// a name and one named like another (`BOLD`), which style lists leave out. `None` when it can't +/// a name and one named like another (`BOLD`), which style lists leave out. Its version (name ID 5) is +/// `Version 1.000`. `None` when it can't /// be built. pub fn variable_font() -> Option> { const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); @@ -106,6 +107,7 @@ pub fn variable_font() -> Option> { (1, VARIABLE_FAMILY), (2, "Regular"), (4, "Varitest Sans Regular"), + (5, "Version 1.000"), (6, "VaritestSans-Regular"), (256, "Weight"), (257, "Normal"), diff --git a/crates/text/src/tests/harakat.rs b/crates/text/src/tests/harakat.rs index c097fc48b9..e590f103c7 100644 --- a/crates/text/src/tests/harakat.rs +++ b/crates/text/src/tests/harakat.rs @@ -512,6 +512,43 @@ fn assert_authored_ownership(t: &TextObject, text: &str, l: &TextLayout, what: & } } +/// Repeated glyphs in one cluster can belong to differently painted runs. Match each authored +/// occurrence in order, without needing an installed font, and still reject a changed owner. +#[test] +fn duplicate_authored_glyphs_keep_occurrence_order() { + let mut text = TextObject::point(Point::ZERO, "\u{0651}", style(FAMILY)); + text.runs.push(vectorcraft_doc::TextRun::new("\u{0651}", CharStyle { fill: red(), ..style(FAMILY) })); + let glyph = |run| PositionedGlyph { + outline: Default::default(), + run, + byte: 0, + origin: Point::ZERO, + advance: 0.0, + len: 4, + angle: 0.0, + line: 0, + font_id: 0, + gid: 7, + xf: Affine::IDENTITY, + rtl: true, + scale: 1.0, + image: None, + colour: None, + bend: None, + unturned: Affine::IDENTITY, + pivot: Point::ZERO, + carets: Vec::new(), + width: 0.0, + width_start: 0.0, + }; + let before = TextLayout { glyphs: vec![glyph(0), glyph(1)], ..TextLayout::default() }; + assert_eq!(assert_kashida_ownership(&text, &before, &before, &red(), "duplicate glyphs", false), 0); + + let mut wrong = before.clone(); + wrong.glyphs[0].run = 1; + assert!(std::panic::catch_unwind(|| assert_kashida_ownership(&text, &before, &wrong, &red(), "changed owner", false)).is_err()); +} + /// Compare authored glyph run indices before/after Insert Kashidas (matched by byte and gid; /// layout order can differ between point and justified area), and assert every inserted tatweel /// uses the base letter's paint at the cluster start—not `mark_fill`. When `require_mark_last`, @@ -525,16 +562,17 @@ fn assert_kashida_ownership( what: &str, require_mark_last: bool, ) -> usize { - let mut before_runs: std::collections::HashMap<(usize, u32), Vec> = std::collections::HashMap::new(); + let mut before_runs: std::collections::HashMap<(usize, u32), std::collections::VecDeque> = std::collections::HashMap::new(); for g in before.glyphs.iter().filter(|g| g.len > 0) { - before_runs.entry((g.byte, g.gid)).or_default().push(g.run); + before_runs.entry((g.byte, g.gid)).or_default().push_back(g.run); } let mut after_n = 0; for g in with_kashida.glyphs.iter().filter(|g| g.len > 0) { after_n += 1; let runs = before_runs.get_mut(&(g.byte, g.gid)).unwrap_or_else(|| panic!("{what}: authored glyph {} at {} missing before kashida", g.gid, g.byte)); - let want_run = runs.pop().unwrap_or_else(|| panic!("{what}: no remaining before-run for {} at {}", g.gid, g.byte)); + // Duplicate glyphs at the same cluster byte retain their occurrence order. + let want_run = runs.pop_front().unwrap_or_else(|| panic!("{what}: no remaining before-run for {} at {}", g.gid, g.byte)); assert_eq!(g.run, want_run, "{what}: authored run at {} gid {}", g.byte, g.gid); let want_fill = coloured.runs.get(want_run).map(|r| &r.style.fill).unwrap_or_else(|| panic!("{what}: missing run {want_run}")); assert_eq!(&run_of(coloured, g).style.fill, want_fill, "{what}: authored fill at {}", g.byte); diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 6ce5f3501e..5606cb884c 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -18,11 +18,18 @@ mod caps; mod mesh; pub use mesh::{Mesh, extrude_mesh, inflate_meshes, plane_mesh, revolve_mesh}; -use vectorcraft_geom::{BezPath, ParamCurve, PathData, Point, Rect, Vec2, kurbo::ParamCurveDeriv}; +use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape, Vec2, kurbo::ParamCurveDeriv}; /// Resource limits shared by desktop, CLI and browser evaluation. -const MAX_PROFILE_POINTS: usize = 1024; +const MAX_PROFILE_POINTS: usize = 16_384; const MAX_FACES: usize = 32768; +/// Most faces Revolve builds for one object, its members together: about 460 MB of drawn art. +const MAX_REVOLVE_FACES: usize = 163_840; +/// Most faces Extrude & Bevel and Inflate build for one solid, as many as Revolve's. +const MAX_SOLID_FACES: usize = MAX_REVOLVE_FACES; +/// Samples a curved profile segment takes, and the fewest it takes on a surface over its budget. +const CURVE_SAMPLES: usize = 16; +const MIN_CURVE_SAMPLES: usize = 4; #[derive(Clone, Copy, Debug, Default, PartialEq)] struct V3(f64, f64, f64); @@ -86,6 +93,9 @@ pub struct Revolve { /// Close circular endpoint rings of open profiles. Partial sweeps get sectors; /// the angular cut sides are left open. Enabled by default. pub cap_ends: bool, + /// Samples for each curved profile segment, from [`revolve_curve_samples`] for the surfaces of + /// one object. `None` plans them from the profile alone. + pub curve_samples: Option, } /// The default light's Rotation and Height: the light of the earlier default direction (45° to the @@ -114,6 +124,7 @@ impl Default for Revolve { shade: true, smooth_shading: true, cap_ends: true, + curve_samples: None, } } } @@ -307,6 +318,11 @@ impl Revolve { ..self } } + /// How many steps a sanitized sweep takes. + fn steps(self) -> usize { + ((self.segments as f64 * self.angle / 360.0).ceil() as usize).max(1) + } + fn rotate(self, v: V3) -> V3 { let (sx, cx) = self.rotation_x.to_radians().sin_cos(); let (sy, cy) = self.rotation_y.to_radians().sin_cos(); @@ -449,16 +465,234 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi /// Evaluate a profile in document space. All subpaths share one axis from `bounds`. /// Invalid or excessively complex inputs return an error, never a partial surface. pub fn revolve(path: &PathData, bounds: Rect, options: Revolve) -> Result, String> { - revolve_faces(path, bounds, options, None) + revolve_faces(path, FillRule::NonZero, bounds, options, None) } -/// [`revolve`], or with `mesh` the surface's faces before projection, kept there instead of drawn. -fn revolve_faces(path: &PathData, bounds: Rect, options: Revolve, mut mesh: Option<&mut Vec>) -> Result, String> { +const TOO_COMPLEX_PROFILE: &str = "Revolve profile is too complex"; +const TOO_COMPLEX_SURFACE: &str = "Revolve surface is too complex; reduce Segments or simplify the profile"; + +/// The samples each curved segment takes when `paths`, the profiles of one object's surfaces, are +/// revolved with `options`: [`CURVE_SAMPLES`] when every surface fits the limits together, else as +/// many as fit, the same number for every curve. An error when [`MIN_CURVE_SAMPLES`] do not fit. +/// The count is made before any face is built. +pub fn revolve_curve_samples<'a>(paths: impl IntoIterator, options: Revolve) -> Result { let o = options.sanitized(); + let steps = o.steps(); + let per_edge = if o.shade && o.smooth_shading { steps.saturating_mul(2) } else { steps }; + let (mut anchors, mut contours, mut lines, mut curves, mut caps) = (0usize, 0usize, 0usize, 0usize, 0usize); + for sp in paths.into_iter().flat_map(|p| &p.subpaths) { + anchors = anchors.saturating_add(sp.anchors.len()); + contours += 1; + if anchors > MAX_PROFILE_POINTS || contours > MAX_PROFILE_POINTS { + return Err(TOO_COMPLEX_PROFILE.into()); + } + let segments = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; + for i in 0..segments { + if sp.segment_is_line(i) { + lines += 1; + } else { + curves += 1; + } + } + if o.cap_ends && !sp.closed && segments > 0 { + caps += 2; + } + } + let points = MAX_PROFILE_POINTS.saturating_sub(contours); + if lines.saturating_add(curves.saturating_mul(MIN_CURVE_SAMPLES)) > points { + return Err(TOO_COMPLEX_PROFILE.into()); + } + let edges = (MAX_REVOLVE_FACES.saturating_sub(caps.saturating_mul(steps)) / per_edge).min(points); + if curves == 0 { + return if lines > edges { Err(TOO_COMPLEX_SURFACE.into()) } else { Ok(CURVE_SAMPLES) }; + } + let samples = (edges.saturating_sub(lines) / curves).min(CURVE_SAMPLES); + if samples < MIN_CURVE_SAMPLES { Err(TOO_COMPLEX_SURFACE.into()) } else { Ok(samples) } +} + +/// Most work the search for holes does: each winding test counts its contour's elements, and each +/// contour placed in a cell of the grid or looked at as a candidate for a point counts one. +const MAX_HOLE_WORK: usize = 16_000_000; + +/// Most cells along each side of the grid the search for holes sorts contours into. +const MAX_HOLE_GRID: usize = 256; + +/// For each segment of each subpath of `path`, whether it walls a hole under `rule`: the fill is +/// outside its closed contour at the segment's middle and not inside. An error past +/// [`MAX_HOLE_WORK`]. +#[cfg(test)] +fn hole_segments(path: &PathData, rule: FillRule) -> Result>, String> { + hole_segments_counted(path, rule).map(|(holes, _)| holes) +} + +/// [`hole_segments`] and the work it did. +#[cfg(test)] +fn hole_segments_counted(path: &PathData, rule: FillRule) -> Result<(Vec>, usize), String> { + let mut search = HoleSearch::new(path, rule)?; + let mut holes = Vec::with_capacity(path.subpaths.len()); + for (i, sp) in path.subpaths.iter().enumerate() { + let segments = if sp.closed { sp.anchors.len() } else { 0 }; + holes.push((0..segments).map(|segment| search.is_hole(i, sp.segment(segment).eval(0.5))).collect::, _>>()?); + } + Ok((holes, search.work)) +} + +/// The closed contours of a profile sorted into a grid over the bounds of them all, each listed in +/// the cells its bounds reach into, to find which parts of the profile's edges wall a hole under +/// its fill rule. A point is tested only against the contours of its cell. Every test counts +/// toward [`MAX_HOLE_WORK`]. +struct HoleSearch { + /// Each subpath's outline, its bounds, and for a closed one which way it winds. + contours: Vec<(BezPath, Rect, Option)>, + rule: FillRule, + area: Option, + side: usize, + grid: Vec>, + work: usize, +} + +impl HoleSearch { + fn new(path: &PathData, rule: FillRule) -> Result { + // Each contour takes a profile point, as in `revolve_curve_samples`. + if path.subpaths.len() > MAX_PROFILE_POINTS { + return Err(TOO_COMPLEX_PROFILE.into()); + } + let contours: Vec<(BezPath, Rect, Option)> = path + .subpaths + .iter() + .map(|sp| { + let contour = PathData::new(vec![sp.clone()]).to_bezpath(); + let bounds = contour.bounding_box(); + let direction = sp.closed.then(|| if contour.area() < 0.0 { -1 } else { 1 }); + (contour, bounds, direction) + }) + .collect(); + let closed = || contours.iter().enumerate().filter(|(_, (_, _, d))| d.is_some()); + let area = closed().map(|(_, (_, b, _))| *b).reduce(|a, b| a.union(b)); + let side = ((closed().count() as f64).sqrt().ceil() as usize).clamp(1, MAX_HOLE_GRID); + let mut search = HoleSearch { contours: vec![], rule, area, side, grid: vec![vec![]; side * side], work: 0 }; + for (j, (_, b, _)) in closed() { + let cells = search.cells(*b); + search.spend(cells.len())?; + for c in cells { + if let Some(c) = search.grid.get_mut(c) { + c.push(j); + } + } + } + search.contours = contours; + Ok(search) + } + + fn spend(&mut self, n: usize) -> Result<(), String> { + self.work = self.work.saturating_add(n); + if self.work > MAX_HOLE_WORK { Err(TOO_COMPLEX_PROFILE.to_string()) } else { Ok(()) } + } + + /// The grid cells `r` reaches into. + fn cells(&self, r: Rect) -> Vec { + let Some(a) = self.area else { return vec![] }; + let side = self.side; + let at = |v: f64, lo: f64, hi: f64| { + let span = hi - lo; + if span > 0.0 { (((v - lo) / span * side as f64).floor().max(0.0) as usize).min(side - 1) } else { 0 } + }; + let (x0, x1) = (at(r.x0, a.x0, a.x1), at(r.x1, a.x0, a.x1)); + let (y0, y1) = (at(r.y0, a.y0, a.y1), at(r.y1, a.y0, a.y1)); + (y0..=y1).flat_map(|y| (x0..=x1).map(move |x| y * side + x)).collect() + } + + /// The closed contours other than `own` whose bounds may meet `r`, each once. + fn candidates(&mut self, own: usize, r: Rect) -> Result, String> { + let mut out = vec![]; + for c in self.cells(r) { + let listed = self.grid.get(c).map_or(&[][..], Vec::as_slice); + out.extend(listed.iter().copied().filter(|j| *j != own)); + } + self.spend(out.len())?; + out.sort_unstable(); + out.dedup(); + Ok(out) + } + + /// Whether the edge of closed subpath `own` at `p` walls a hole: the fill is outside its + /// contour there and not inside. + fn is_hole(&mut self, own: usize, p: Point) -> Result { + let Some(direction) = self.contours.get(own).and_then(|c| c.2) else { return Ok(false) }; + let mut others = 0i32; + for j in self.candidates(own, Rect::from_points(p, p))? { + let Some((contour, bounds, Some(_))) = self.contours.get(j) else { continue }; + if !bounds.contains(p) { + continue; + } + let (elements, winding) = (contour.elements().len(), contour.winding(p)); + self.spend(elements)?; + others += winding; + } + Ok(match self.rule { + FillRule::EvenOdd => others % 2 != 0, + FillRule::NonZero => others != 0 && others + direction == 0, + }) + } + + /// The line from `a` to `b` on subpath `own`, cut where it crosses another closed contour: each + /// part's end, the last one `b`, and whether that part walls a hole at its middle. + fn parts(&mut self, own: usize, a: Point, b: Point) -> Result, String> { + let mut out = vec![]; + let mut from = 0.0; + for t in self.crossings(own, a, b)?.into_iter().chain([1.0]) { + let hole = self.is_hole(own, a.lerp(b, (from + t) * 0.5))?; + out.push((if t < 1.0 { a.lerp(b, t) } else { b }, hole)); + from = t; + } + Ok(out) + } + + /// Where the line from `a` to `b` on closed subpath `own` crosses another closed contour, as + /// sorted fractions of the way from `a` to `b`, strictly between them. + fn crossings(&mut self, own: usize, a: Point, b: Point) -> Result, String> { + if self.contours.get(own).and_then(|c| c.2).is_none() { + return Ok(vec![]); + } + let line = vectorcraft_geom::kurbo::Line::new(a, b); + let reach = Rect::from_points(a, b); + let mut out = vec![]; + for j in self.candidates(own, reach)? { + let Some((contour, bounds, Some(_))) = self.contours.get(j) else { continue }; + if bounds.x0 > reach.x1 || bounds.x1 < reach.x0 || bounds.y0 > reach.y1 || bounds.y1 < reach.y0 { + continue; + } + let found: Vec = contour.segments().flat_map(|s| s.intersect_line(line)).map(|i| i.line_t).collect(); + self.spend(contour.elements().len())?; + out.extend(found.into_iter().filter(|t| *t > 1e-9 && *t < 1.0 - 1e-9)); + } + out.sort_by(f64::total_cmp); + out.dedup_by(|x, y| (*x - *y).abs() < 1e-9); + Ok(out) + } +} + +/// [`revolve`], or with `mesh` the surface's faces before projection, kept there instead of drawn, +/// each turned out of the region `rule` fills. +fn revolve_faces( + path: &PathData, + rule: FillRule, + bounds: Rect, + options: Revolve, + mut mesh: Option<&mut Vec>, +) -> Result, String> { + let o = options.sanitized(); + let curve_samples = match o.curve_samples { + Some(samples) => samples.clamp(1, CURVE_SAMPLES), + None => revolve_curve_samples([path], o)?, + }; + // For a mesh, each piece of a closed contour's edge is cut where it crosses another contour, so + // each part's normal turns toward a hole only where it walls one. + let mut search = if mesh.is_some() { Some(HoleSearch::new(path, rule)?) } else { None }; // A face kept for a mesh: its normal follows from its corners. let keep = |mesh: &mut Vec, face: Vec, normal: V3| { mesh.push((vec![face], normal)); - if mesh.len() > MAX_FACES { Err("Revolve surface is too complex; reduce Segments or simplify the profile".to_string()) } else { Ok(()) } + if mesh.len() > MAX_REVOLVE_FACES { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } }; if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { return Err("Revolve requires finite profile coordinates within 100 million points".into()); @@ -470,7 +704,7 @@ fn revolve_faces(path: &PathData, bounds: Rect, options: Revolve, mut mesh: Opti let center_y = (bounds.y0 + bounds.y1) * 0.5; let radius = (bounds.x0 - axis).abs().max((bounds.x1 - axis).abs()); let eye = eye_distance(o.perspective, radius.max(bounds.height().abs()).max(1.0)); - let steps = ((o.segments as f64 * o.angle / 360.0).ceil() as usize).max(1); + let steps = o.steps(); let sweep = o.angle.to_radians(); let smooth = o.shade && o.smooth_shading; let [lx, ly, lz] = o.light_direction(); @@ -489,32 +723,33 @@ fn revolve_faces(path: &PathData, bounds: Rect, options: Revolve, mut mesh: Opti if let Some(face) = face { faces.push(face); mesh_cost += cost; - if mesh_cost > MAX_FACES { - return Err("Revolve surface is too complex; reduce Segments or simplify the profile".into()); + if mesh_cost > MAX_REVOLVE_FACES { + return Err(TOO_COMPLEX_SURFACE.into()); } } Ok(()) }; let mut count = 0; let mut curve_budget = 0; - for sp in &path.subpaths { + for (contour, sp) in path.subpaths.iter().enumerate() { let mut profile = Vec::new(); let mut tangents = Vec::new(); + let mut hole_edges = Vec::new(); if let Some(first) = sp.anchors.first() { profile.push(first.p); count += 1; if count > MAX_PROFILE_POINTS { - return Err("Revolve profile is too complex".into()); + return Err(TOO_COMPLEX_PROFILE.into()); } } let segments = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; - // Bound work before sampling any data. Curves get sixteen samples, straight edges one. + // Bound work before sampling any data. Straight edges get one sample. if segments > MAX_PROFILE_POINTS { - return Err("Revolve profile is too complex".into()); + return Err(TOO_COMPLEX_PROFILE.into()); } for i in 0..segments { let curve = sp.segment(i); - let samples = if sp.segment_is_line(i) { 1 } else { 16 }; + let samples = if sp.segment_is_line(i) { 1 } else { curve_samples }; for k in 1..=samples { let t0 = (k - 1) as f64 / samples as f64; let t1 = k as f64 / samples as f64; @@ -536,11 +771,19 @@ fn revolve_faces(path: &PathData, bounds: Rect, options: Revolve, mut mesh: Opti let v = d.eval(t.clamp(1e-7, 1.0 - 1e-7)).to_vec2(); if v.hypot2() > 1e-20 { v } else { b - a } }; - tangents.push([tangent(t0), tangent(t1)]); - profile.push(b); - count += 1; - if count > MAX_PROFILE_POINTS { - return Err("Revolve profile is too complex".into()); + let a = profile.last().copied().unwrap_or(b); + let parts = match search.as_mut() { + Some(search) => search.parts(contour, a, b)?, + None => vec![(b, false)], + }; + for (end, hole) in parts { + tangents.push([tangent(t0), tangent(t1)]); + hole_edges.push(hole); + profile.push(end); + count += 1; + if count > MAX_PROFILE_POINTS { + return Err(TOO_COMPLEX_PROFILE.into()); + } } } } @@ -565,8 +808,9 @@ fn revolve_faces(path: &PathData, bounds: Rect, options: Revolve, mut mesh: Opti let area: f64 = ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.0 * q.1 - q.0 * p.1).sum(); if area < 0.0 { -1.0 } else { 1.0 } }; - for (i, (pair, [ta, tb])) in profile.windows(2).zip(tangents).enumerate() { + for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(tangents).zip(hole_edges).enumerate() { let [a, b] = pair else { continue }; + let turn = if hole { -turn } else { turn }; if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { return Err("Revolve profile contains invalid coordinates".into()); } diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index 2f2f698441..d1970c2028 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -76,10 +76,11 @@ pub fn inflate_meshes( } /// Revolve's surface ([`crate::revolve`]) as a mesh. As the effect draws it, a sweep of less than -/// 360° caps its ends with sectors and leaves its two cut sides open ([`Revolve::cap_ends`]). -pub fn revolve_mesh(path: &PathData, bounds: Rect, options: Revolve) -> Result { +/// 360° caps its ends with sectors and leaves its two cut sides open ([`Revolve::cap_ends`]). The +/// walls of holes under `rule`, such as the counter of an O, face into the hole. +pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve) -> Result { let mut faces = vec![]; - crate::revolve_faces(path, bounds, options, Some(&mut faces))?; + crate::revolve_faces(path, rule, bounds, options, Some(&mut faces))?; mesh(&faces) } diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 3251cbb3ee..2011d6689c 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -231,7 +231,7 @@ fn a_revolved_profile_is_a_closed_cylinder() { let p = PathData::from_bezpath(&b); let r = p.bounds().unwrap(); let o = Revolve { offset: 10.0, edge: Edge::Left, segments: 64, ..Revolve::default() }; - let m = revolve_mesh(&p, r, o).unwrap(); + let m = revolve_mesh(&p, FillRule::NonZero, r, o).unwrap(); assert!(closed(&m)); let exact = 2.0 * std::f64::consts::PI * 10.0 * 100.0 + 2.0 * std::f64::consts::PI * 100.0; assert!((area(&m) - exact).abs() / exact < 0.01, "{} vs {exact}", area(&m)); @@ -246,7 +246,7 @@ fn a_partial_revolve_caps_its_ends_with_sectors() { let p = PathData::from_bezpath(&b); let r = p.bounds().unwrap(); let o = Revolve { angle: 90.0, offset: 10.0, segments: 64, ..Revolve::default() }; - let m = revolve_mesh(&p, r, o).unwrap(); + let m = revolve_mesh(&p, FillRule::NonZero, r, o).unwrap(); let exact = 0.25 * (2.0 * std::f64::consts::PI * 10.0 * 100.0 + 2.0 * std::f64::consts::PI * 100.0); assert!((area(&m) - exact).abs() / exact < 0.01, "{} vs {exact}", area(&m)); } @@ -261,7 +261,7 @@ fn a_revolved_surface_has_unit_normals_facing_out_whatever_its_length_and_direct let p = PathData::from_bezpath(&b); let r = p.bounds().unwrap(); let o = Revolve { offset: 10.0, edge: Edge::Left, segments: 64, ..Revolve::default() }; - let m = revolve_mesh(&p, r, o).unwrap(); + let m = revolve_mesh(&p, FillRule::NonZero, r, o).unwrap(); assert!(!m.is_empty(), "{from} to {to}: the revolve made no triangles"); assert!(m.normals.iter().all(|n| (dot(*n, *n) - 1.0).abs() < 1e-9), "{from} to {to}: a normal is not unit length"); assert!(closed(&m), "{from} to {to}"); @@ -269,6 +269,62 @@ fn a_revolved_surface_has_unit_normals_facing_out_whatever_its_length_and_direct } } +/// The radial direction of every triangle's normal at the wall `x` pt from the axis, each as the +/// sign of the normal's part along the way from the axis: 1 away from it, -1 toward it. +fn wall_directions(m: &Mesh, x: f64) -> Vec { + m.triangles + .iter() + .filter_map(|t| { + let [a, b, c] = corners(m, *t); + let centre = [(a[0] + b[0] + c[0]) / 3.0, 0.0, (a[2] + b[2] + c[2]) / 3.0]; + let radius = centre[0].hypot(centre[2]); + let n = m.normals[t[0] as usize]; + ((radius - x).abs() < 1.0 && n[1].abs() < 0.5).then(|| dot(n, centre).signum()) + }) + .collect() +} + +#[test] +fn the_wall_of_a_counter_faces_into_the_hole() { + // A square ring 20 pt thick, its axis at the outer square's left edge minus 10: the outer wall + // reaches 110 pt from the axis, and the hole's far wall 90 pt from it. + let ring = |hole_clockwise: bool, rule: FillRule| { + let mut b = BezPath::new(); + square(&mut b, 0.0, 0.0, 100.0, false); + square(&mut b, 20.0, 20.0, 60.0, hole_clockwise); + let (p, r) = shape(&b); + revolve_mesh(&p, rule, r, Revolve { offset: 10.0, segments: 32, ..Revolve::default() }).unwrap() + }; + for (clockwise, rule) in [(true, FillRule::NonZero), (true, FillRule::EvenOdd), (false, FillRule::EvenOdd)] { + let m = ring(clockwise, rule); + let outer = wall_directions(&m, 110.0); + assert!(!outer.is_empty() && outer.iter().all(|s| *s > 0.0), "outer wall, {clockwise} {rule:?}"); + let hole = wall_directions(&m, 90.0); + assert!(!hole.is_empty() && hole.iter().all(|s| *s < 0.0), "the hole's far wall faces the axis, {clockwise} {rule:?}"); + } + // Wound the same way under the nonzero rule, the inner square is not a hole. + let m = ring(false, FillRule::NonZero); + let inner = wall_directions(&m, 90.0); + assert!(!inner.is_empty() && inner.iter().all(|s| *s > 0.0)); +} + +#[test] +fn an_edge_that_crosses_another_contour_faces_the_hole_only_where_it_walls_it() { + // Two squares overlapping under the even-odd rule leave their overlap empty. The first square's + // right edge (110 pt from the axis) and the second's left edge (50 pt from it) each wall the + // overlap along part of their length and the outside along the rest. + let mut b = BezPath::new(); + square(&mut b, 0.0, 0.0, 100.0, false); + square(&mut b, 40.0, 40.0, 100.0, false); + let (p, r) = shape(&b); + let m = revolve_mesh(&p, FillRule::EvenOdd, r, Revolve { offset: 10.0, segments: 32, ..Revolve::default() }).unwrap(); + for radius in [110.0, 50.0] { + let walls = wall_directions(&m, radius); + assert!(walls.iter().any(|s| *s > 0.0) && walls.iter().any(|s| *s < 0.0), "both ways at {radius}"); + } + assert!(wall_directions(&m, 150.0).iter().all(|s| *s > 0.0), "the second square's far edge faces out"); +} + #[test] fn inflate_puffs_the_front_toward_the_viewer() { let mut b = BezPath::new(); diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 4d6e781882..45d7d310b2 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -11,11 +11,12 @@ use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Vec2}; -use crate::{MAX_FACES, Revolve, V3, eye_distance, perspective_scale}; +use crate::{MAX_FACES, MAX_SOLID_FACES, Revolve, V3, eye_distance, perspective_scale}; mod build; mod inflate; mod membrane; +mod outline; mod rings; #[cfg(test)] @@ -23,11 +24,13 @@ use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, extrude_faces, plane_faces}; pub use build::{extrude, plane}; #[cfg(test)] +use inflate::GRID_WORK; +#[cfg(test)] pub(crate) use inflate::INFLATED; pub(crate) use inflate::inflate_faces; pub use inflate::{inflate, inflate_together}; #[cfg(test)] -use membrane::{Edges, Membrane, cell_triangles}; +use membrane::{Edges, GRID_BUDGET, MAX_EDGE_ENTRIES, MAX_GRID_WORK, Membrane, cell_triangles}; use rings::signed_area; #[cfg(test)] use rings::{MAX_SOLID_POINTS, rings}; @@ -251,6 +254,9 @@ pub struct Facet { pub normal: [f64; 3], /// Smooth lighting on an inflated triangle, before clipping individual RGB channels. pub rgb_gradient: Option, + /// The facet's outline with the profile's curves kept as cubics, for [`Facet::path`]. The + /// contours stay the polygon that visibility and depth use. + pub outline: Option, /// The contours in view space, before projection, for tests that measure depths. #[cfg(test)] view: Vec>, @@ -266,7 +272,11 @@ impl Facet { if perimeter > 0.0 { 2.0 * area / perimeter } else { 0.0 } } + /// The facet's outline: its curved outline when it has one, else its contours. pub fn path(&self) -> PathData { + if let Some(path) = &self.outline { + return path.clone(); + } let mut bp = BezPath::new(); for c in &self.contours { let Some(first) = c.first() else { continue }; @@ -319,3 +329,6 @@ mod tests; #[cfg(test)] mod tests_inflate_shading; + +#[cfg(test)] +mod tests_limits; diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 9948c4796c..66a22f80fa 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -1,5 +1,14 @@ -use super::rings::{MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, inset, left, signed_area, solid_rings}; -use super::{Bevel, Extrude, Facet, FillRule, MAX_FACES, PathData, Point, Rect, Revolve, V3, View, eye_distance, perspective_scale}; +use vectorcraft_geom::kurbo::ParamCurveDeriv; + +use super::outline::{self, Along, Budget, CURVE_TOLERANCE}; +use super::rings::{ + CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, inset, left, signed_area, + solid_rings_traced, +}; +use super::{ + Bevel, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, Point, Rect, Revolve, V3, View, eye_distance, + perspective_scale, +}; /// Turns 3D points into document points and shades faces for one view. pub(super) struct Camera { @@ -87,8 +96,8 @@ impl Builder<'_> { } if let Some(mesh) = &mut self.mesh { mesh.push((contours, n.unit())); - if mesh.len() > MAX_FACES { - return Err("The 3D surface is too complex; simplify the shape".into()); + if mesh.len() > MAX_SOLID_FACES { + return Err(TOO_COMPLEX_SURFACE.into()); } return Ok(()); } @@ -132,11 +141,12 @@ impl Builder<'_> { illumination: crate::illumination(&self.camera.view, n, self.camera.light), normal: [n.0, n.1, n.2], rgb_gradient: None, + outline: None, #[cfg(test)] view, }); - if self.facets.len() > MAX_FACES { - return Err("The 3D surface is too complex; simplify the shape".into()); + if self.facets.len() > MAX_SOLID_FACES { + return Err(TOO_COMPLEX_SURFACE.into()); } Ok(()) } @@ -169,6 +179,19 @@ impl Builder<'_> { /// wall with `cuts` (see [`cuts`]) as `cuts[i]` quads along edge `i`. `outward` is the /// direction (before rotation) the band faces away from the solid, for orienting normals. pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3) -> Result<(), String> { + self.curved_band(a, b, cuts, outward, None) + } + + /// [`Builder::band`], with `curves` the pieces of curve the rings' edges follow and the + /// outlines at `a` and `b`: a quad whose edge is not cut keeps its edges along the profile curved. + pub(super) fn curved_band( + &mut self, + a: &[V3], + b: &[V3], + cuts: &[usize], + outward: impl Fn(usize) -> V3, + mut curves: Option, + ) -> Result<(), String> { let n = a.len().min(b.len()); // At 0 and 1, the corners themselves. let lerp = |p: V3, q: V3, s: f64| { @@ -196,12 +219,29 @@ impl Builder<'_> { if normal.dot(self.camera.rotate(outward(i))) < 0.0 { normal = V3(-normal.0, -normal.1, -normal.2); } + let before = self.facets.len(); self.face(vec![quad], normal, order)?; + if let Some(w) = curves.as_mut().filter(|_| pieces == 1) + && let Some(span) = w.spans.get(i).copied().flatten() + { + self.outline(before, |c| c.first().and_then(|quad| outline::wall(&span, quad, w.near, w.far, w.budget))); + } } } Ok(()) } + /// Give the facet that [`Builder::face`] added, when it added one after `before` facets, the + /// outline `outline` makes from its projected contours. + pub(super) fn outline(&mut self, before: usize, outline: impl FnOnce(&[Vec]) -> Option) { + if self.mesh.is_some() || self.facets.len() <= before { + return; + } + if let Some(f) = self.facets.last_mut() { + f.outline = outline(&f.contours); + } + } + /// How many faces the builder holds: facets, or faces kept for a mesh. pub(super) fn len(&self) -> usize { self.mesh.as_ref().map_or(self.facets.len(), Vec::len) @@ -214,6 +254,62 @@ impl Builder<'_> { } } +/// The curves a band's quads keep: the piece of curve each edge of its rings follows, and the +/// outlines at its two rings (`None` keeps that ring's edges straight). +pub(super) struct WallCurves<'a> { + pub(super) spans: &'a [Option], + pub(super) near: Option<&'a Along<'a>>, + pub(super) far: Option<&'a Along<'a>>, + pub(super) budget: &'a mut Budget, +} + +/// Where a point of the art goes in view space at one step: [`Camera::place`] after a [`Turn`], +/// at depth `z`, as one affine map worked out once for the step. +pub(super) struct Placing { + centre: Point, + at_centre: V3, + x: V3, + y: V3, +} + +impl Placing { + pub(super) fn new(camera: &Camera, centre: Point, turn: Turn, z: f64) -> Self { + let at = |p: Point| camera.place(turn.apply(p), z); + let at_centre = at(centre); + let x = at(Point::new(centre.x + 1.0, centre.y)).sub(at_centre); + let y = at(Point::new(centre.x, centre.y + 1.0)).sub(at_centre); + Self { centre, at_centre, x, y } + } + pub(super) fn place(&self, p: Point) -> V3 { + let (dx, dy) = (p.x - self.centre.x, p.y - self.centre.y); + V3( + self.at_centre.0 + self.x.0 * dx + self.y.0 * dy, + self.at_centre.1 + self.x.1 * dx + self.y.1 * dy, + self.at_centre.2 + self.x.2 * dx + self.y.2 * dy, + ) + } +} + +/// The point `w` points to the left of `span`'s curve at `t`, as the ring runs along it (toward +/// the filled side): where [`inset`] moves the ring's points, without its miters. +fn offset(span: &Span, t: f64, w: f64) -> Point { + let p = span.curve.eval(t); + if w == 0.0 { + return p; + } + let mut d = span.curve.deriv().eval(t).to_vec2(); + // A handle of zero length leaves no tangent at its end: the curve leaves toward its next point. + if d.hypot() < 1e-12 { + d = span.curve.p2 - span.curve.p0; + if t > 0.5 { + d = span.curve.p3 - span.curve.p1; + } + } + let d = if span.t1 < span.t0 { -d } else { d }; + let l = d.hypot(); + if l < 1e-12 { p } else { Point::new(p.x - d.y / l * w, p.y + d.x / l * w) } +} + /// How many pieces each edge of a twisted wall is drawn in, from two neighboring slices of the /// wall, `a` and `b` (partner rings): as many as make each piece about as long along the edge as /// the band between the slices is wide there, 1 to [`MAX_PIECES`]. Twisted walls pass in front of @@ -407,15 +503,26 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio if o.depth <= 0.0 { return plane_faces(path, rule, bounds, view, mesh); } - let rings = solid_rings(path, rule, bounds.width().max(bounds.height()), MAX_SOLID_POINTS)?; + let steps = steps(&o); + // One face for each edge of the outline in each band between two steps, and the two caps: + // counted before any point is sampled, and again on the rings, which can have more points + // once contours that meet are merged. + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); + let size = bounds.width().max(bounds.height()); + let most = curve_pieces(path, size, bands, caps)?; + let traced = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?; + let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); + let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); + if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { + return Err(TOO_COMPLEX_SURFACE.into()); + } let camera = Camera::new(view, bounds, o.depth); let mut b = Builder { camera: &camera, closed: o.cap, hidden: o.hidden, facets: vec![], mesh: mesh.then(Vec::new) }; - let steps = steps(&o); let z = |t: f64| o.depth / 2.0 - o.depth * t; let ring_at = |ring: &[Point], s: &Step| -> Vec { section(&inset(ring, s.inset), bounds, &o, s.t).iter().map(|p| camera.place(*p, z(s.t))).collect() }; // Every band of a twisted outline, bevels included, is cut as its walls' first slice is (with - // bevels and no walls, as its shallowest band is), within the facet limit. + // bevels and no walls, as its shallowest band is), within [`MAX_FACES`] facets. let depth_of = |s: &[Step]| s.get(1).zip(s.first()).map_or(0.0, |(b, a)| (b.t - a.t).abs()); let wall = steps .windows(2) @@ -429,7 +536,33 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio }) .collect(); fit(&mut pieces, steps.len().saturating_sub(1), MAX_FACES); - for (ring, pieces) in rings.iter().zip(&pieces) { + // The outline at each step, through the profile's curves: exact where the step is not inset, + // and within the sampling tolerance (which the inset rings themselves keep to) where it is. + let sampled = (size / 2000.0).max(0.05); + let maps: Vec = steps.iter().map(|s| Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, s.t), z(s.t))).collect(); + let at: Vec<_> = steps + .iter() + .zip(&maps) + .map(|(s, m)| { + let (w, camera) = (s.inset, &camera); + move |span: &Span, t: f64| camera.project(m.place(offset(span, t, w))) + }) + .collect(); + // A step that is not inset moves the art point by point, affinely without perspective. + let point_maps: Vec<_> = maps.iter().map(|m| |p: Point| camera.project(m.place(p))).collect(); + let along: Vec = steps + .iter() + .zip(&at) + .zip(&point_maps) + .map(|((s, at), map)| Along { + at, + map: (s.inset == 0.0).then_some(map as &dyn Fn(Point) -> Point), + affine: camera.eye.is_none(), + tolerance: if s.inset == 0.0 { CURVE_TOLERANCE } else { sampled }, + }) + .collect(); + let mut budget = Budget::default(); + for ((ring, traced), pieces) in rings.iter().zip(&traced).zip(&pieces) { let placed: Vec> = steps.iter().map(|s| ring_at(ring, s)).collect(); for (k, pair) in placed.windows(2).enumerate() { let ([a, c], Some(s0), Some(s1)) = (pair, steps.get(k), steps.get(k + 1)) else { continue }; @@ -442,15 +575,25 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio } else { 0.0 }; - b.band(a, c, pieces, |i| outward(ring, i, face))?; + // The edges a band shares with a cap follow the cap's curves; the edges between two bands + // stay straight, within the sampling tolerance. + let (near, far) = (along.get(k).filter(|_| k == 0), along.get(k + 1).filter(|_| k + 2 == steps.len())); + let curves = (near.is_some() || far.is_some()).then(|| WallCurves { spans: &traced.spans, near, far, budget: &mut budget }); + b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves)?; } } if o.cap { // A cap turned toward the viewer covers the walls it overlaps, even those nearer than its // center: twisted walls, and the walls of a fill inside the solid of its stroke. - for (s, n) in [(steps.first(), 1.0), (steps.last(), -1.0)] { + let caps = [(steps.first(), along.first(), 1.0), (steps.last(), along.last(), -1.0)]; + for (s, along, n) in caps { let Some(s) = s else { continue }; + let before = b.len(); b.face(rings.iter().map(|r| ring_at(r, s)).collect(), camera.rotate(V3(0.0, 0.0, n)), Order::Last)?; + if let Some(along) = along { + let traced: Vec<&Ring> = traced.iter().collect(); + b.outline(before, |c| outline::face(&traced, c, along, &mut budget)); + } } } Ok(b.finish()) @@ -465,15 +608,21 @@ pub fn plane(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Resul /// [`plane`], or with `mesh` its face before projection instead of its facet. pub(crate) fn plane_faces(path: &PathData, rule: FillRule, bounds: Rect, view: View, mesh: bool) -> Result { check_bounds(bounds)?; - let rings = solid_rings(path, rule, bounds.width().max(bounds.height()), MAX_PLANE_POINTS)?; + let rings = solid_rings_traced(path, rule, bounds.width().max(bounds.height()), MAX_PLANE_POINTS, CURVE_PIECES)?; let camera = Camera::new(view, bounds, 0.0); let mut b = Builder { camera: &camera, closed: false, hidden: false, facets: vec![], mesh: mesh.then(Vec::new) }; - let contours: Vec> = rings.iter().map(|r| r.iter().map(|p| camera.place(*p, 0.0)).collect()).collect(); + let contours: Vec> = rings.iter().map(|r| r.points.iter().map(|p| camera.place(*p, 0.0)).collect()).collect(); // A plane is one flat face, seen from either side. Its normal is turned toward the viewer, so // it is drawn last, as a cap is, and planes drawn in one order keep the order they are given in. let up = camera.rotate(V3(0.0, 0.0, 1.0)); let n = if camera.facing(V3::default(), up) < 0.0 { V3(-up.0, -up.1, -up.2) } else { up }; b.face(contours, n, Order::Last)?; + let m = Placing::new(&camera, bounds.center(), Turn::new(bounds, 0.0, 1.0, 0.0), 0.0); + let at = |span: &Span, t: f64| camera.project(m.place(span.curve.eval(t))); + let map = |p: Point| camera.project(m.place(p)); + let along = Along { at: &at, map: Some(&map), affine: camera.eye.is_none(), tolerance: CURVE_TOLERANCE }; + let rings: Vec<&Ring> = rings.iter().collect(); + b.outline(0, |c| outline::face(&rings, c, &along, &mut Budget::default())); Ok(b.finish()) } diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index 51f9af9111..20242697f1 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -1,7 +1,12 @@ use super::build::{Builder, Built, Camera, Order, Turn, check_bounds, cuts, fit, newell, outward}; -use super::membrane::{Edges, MAX_MATERIAL_SEGMENTS, Membrane, cell_triangles, clip, filled, material}; -use super::rings::{MAX_SOLID_POINTS, signed_area, solid_rings}; -use super::{Facet, FillRule, Inflate, MAX_FACES, PathData, Point, Rect, V3, Vec2, View}; +use super::membrane::{Edges, MAX_MATERIAL_SEGMENTS, Membrane, cell_triangles, clip, crossings, filled, material}; +use super::rings::{MAX_SOLID_POINTS, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings}; +use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, Point, Rect, V3, Vec2, View}; + +/// The slices the sides are cut into: more to follow a twist or taper. +fn slices(o: &Inflate) -> usize { + if o.twist != 0.0 || o.taper != 1.0 { ((o.twist.abs() / 6.0).ceil() as usize).clamp(8, 64) } else { 1 } +} /// A shape to inflate: its rings and the membrane under them on the grid of the bounds. struct Puff { @@ -18,11 +23,14 @@ struct Puff { /// The rings of `path` and its membrane on the grid of `bounds`; `None` for a shape with no area. fn puff(path: &PathData, rule: FillRule, bounds: Rect, o: &Inflate) -> Result, String> { - let rings = solid_rings(path, rule, bounds.width().max(bounds.height()), MAX_SOLID_POINTS)?; + // The sides take one face for each edge of the outline in each slice; the grid's faces are + // counted as they are built. + let size = bounds.width().max(bounds.height()); + let most = curve_pieces(path, size, if o.depth > 0.0 { slices(o) } else { 0 }, 0)?; + let rings = solid_rings(path, rule, size, MAX_SOLID_POINTS, most)?; if rings.is_empty() { return Ok(None); } - let size = bounds.width().max(bounds.height()); if size <= 0.0 { return Ok(None); } @@ -35,8 +43,11 @@ fn puff(path: &PathData, rule: FillRule, bounds: Rect, o: &Inflate) -> Result = const { std::cell::Cell::new(0) }; + /// The grid work of the last solid this thread inflated in full, for the tests. + pub(super) static GRID_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The facets of one inflated shape, for a camera that allows for a puff `reach` high (or the @@ -143,14 +156,41 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, mesh: boo // builds the topology of every outline ring near its cell, so a self-crossing outline cost its // crossings again in every cell it spans. Past it, cells take their clipped pieces. let material_left = std::cell::Cell::new(MAX_MATERIAL_SEGMENTS); - // The shape's part of a rectangle, as rings. + // Every ring's bounds, and the crossings of the last few rows the cells' centres lie on (a + // row of cells has at most seven, at its three levels). + let ring_bounds: Vec> = + rings.iter().map(|r| Some(r.iter().skip(1).fold(Rect::from_points(*r.first()?, *r.first()?), |b, p| b.union_pt(*p)))).collect(); + let points = rings.iter().map(Vec::len).fold(0usize, usize::saturating_add); + let rows: std::cell::RefCell)>> = std::cell::RefCell::new(vec![]); + let filled_at = |p: Point| -> bool { + let mut rows = rows.borrow_mut(); + if let Some((_, xs)) = rows.iter().find(|(y, _)| *y == p.y.to_bits()) { + return filled(xs, p.x); + } + let xs = if edges.charge(points) { crossings(&rings, p.y) } else { vec![] }; + let inside = filled(&xs, p.x); + if rows.len() >= 8 { + rows.remove(0); + } + rows.push((p.y.to_bits(), xs)); + inside + }; + // The shape's part of a rectangle, as rings: only the rings whose bounds meet it are clipped, + // each point counted as work. let cut = |r: Rect| -> Vec> { // A cell no edge crosses is wholly inside the shape or wholly outside it. if !edges.touch(r) { let corners = vec![Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; - return if filled(&rings, r.center()) { vec![corners] } else { vec![] }; + return if filled_at(r.center()) { vec![corners] } else { vec![] }; } - let pieces: Vec> = rings.iter().map(|ring| clip(ring, r)).filter(|c| !c.is_empty()).collect(); + let pieces: Vec> = rings + .iter() + .zip(&ring_bounds) + .filter(|(_, b)| b.is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1)) + .filter(|(ring, _)| edges.charge(ring.len())) + .map(|(ring, _)| clip(ring, r)) + .filter(|c| !c.is_empty()) + .collect(); if pieces.iter().map(|p| signed_area(p)).sum::() <= 1e-9 * r.area() { return vec![]; } @@ -185,6 +225,9 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, mesh: boo } }) .collect(); + if edges.spent() { + return Err(TOO_COMPLEX_SURFACE.into()); + } let level = |i: isize, j: isize| -> u32 { if i < 0 || j < 0 || i as usize >= nx || j as usize >= ny { 0 } else { levels[j as usize * nx + i as usize] } }; for j in 0..ny { @@ -201,6 +244,9 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, mesh: boo for sx in (bx0..bx1).step_by(step) { let r = Rect::from_points(at(sx, sy), at(sx + step, sy + step)); let pieces = cut(r); + if edges.spent() { + return Err(TOO_COMPLEX_SURFACE.into()); + } if pieces.is_empty() { continue; } @@ -312,7 +358,7 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, mesh: boo } if o.depth > 0.0 { // The sides, cut into slices that follow a twist or taper. - let slices = if o.twist != 0.0 || o.taper != 1.0 { ((o.twist.abs() / 6.0).ceil() as usize).clamp(8, 64) } else { 1 }; + let slices = slices(&o); let at = |ring: &[Point], k: usize| -> Vec { let t = k as f64 / slices as f64; let turn = Turn::new(bounds, o.twist, o.taper, t); @@ -320,11 +366,20 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, mesh: boo }; let mut pieces: Vec> = rings.iter().map(|r| if o.twist != 0.0 { cuts(&at(r, 0), &at(r, 1)) } else { vec![] }).collect(); fit(&mut pieces, slices, MAX_FACES.saturating_sub(b.len())); + let edges = rings.iter().map(Vec::len).fold(0usize, usize::saturating_add); + if b.len().saturating_add(edges.saturating_mul(slices)) > MAX_SOLID_FACES { + return Err(TOO_COMPLEX_SURFACE.into()); + } for (ring, pieces) in rings.iter().zip(&pieces) { for k in 0..slices { b.band(&at(ring, k), &at(ring, k + 1), pieces, |i| outward(ring, i, 0.0))?; } } } + #[cfg(test)] + GRID_WORK.with(|w| w.set(edges.work())); + if edges.spent() { + return Err(TOO_COMPLEX_SURFACE.into()); + } Ok(b.finish()) } diff --git a/crates/three-d/src/solid/membrane.rs b/crates/three-d/src/solid/membrane.rs index 02d2585318..e8a855e29a 100644 --- a/crates/three-d/src/solid/membrane.rs +++ b/crates/three-d/src/solid/membrane.rs @@ -1,9 +1,35 @@ +use std::cell::Cell; + use super::build::segment_distance; -use super::rings::{MAX_PLANE_POINTS, contains, left, rings, signed_area}; +use super::rings::{MAX_PLANE_POINTS, TOO_COMPLEX_SURFACE, left, rings, signed_area}; use super::{FillRule, PathData, Point, Rect, Vec2}; +/// Most entries the edge index of one inflated shape holds: one for each bucket an edge's bounds +/// cover (64 MiB). +pub(super) const MAX_EDGE_ENTRIES: usize = 1 << 24; + +/// Most work the grid of one inflated shape takes: the index's entries, the edges its queries +/// look at, the crossings of the rows it fills and the ring points its cells clip, together. +pub(super) const MAX_GRID_WORK: usize = 1 << 28; + +#[cfg(test)] +thread_local! { + /// The grid work the next edge indexes of this thread may take, for the tests. + pub(super) static GRID_BUDGET: Cell = const { Cell::new(MAX_GRID_WORK) }; +} + +/// The grid work a new edge index may take. +fn grid_budget() -> usize { + #[cfg(test)] + return GRID_BUDGET.with(Cell::get); + #[cfg(not(test))] + MAX_GRID_WORK +} + /// The edges of `rings` filed in a grid of square buckets, so the nearest edge to a point is -/// found among the buckets around it rather than among all the edges. +/// found among the buckets around it rather than among all the edges. It also counts the work +/// done with it (see [`MAX_GRID_WORK`]): once that is spent, its buckets read as empty, and the +/// caller refuses the shape. pub(super) struct Edges { edges: Vec<(Point, Point)>, normals: Vec<(Vec2, Vec2)>, @@ -11,10 +37,14 @@ pub(super) struct Edges { size: f64, n: usize, buckets: Vec>, + work: Cell, + budget: usize, } impl Edges { - pub(super) fn new(rings: &[Vec]) -> Self { + /// The index of `rings`' edges; an error when it would hold more than [`MAX_EDGE_ENTRIES`] + /// entries, counted before any is filed. + pub(super) fn new(rings: &[Vec]) -> Result { const N: usize = 64; let edges: Vec<(Point, Point)> = rings.iter().flat_map(|r| r.iter().zip(r.iter().cycle().skip(1)).take(r.len()).map(|(a, b)| (*a, *b))).collect(); @@ -37,16 +67,48 @@ impl Edges { let size = (bounds.width().max(bounds.height()) / N as f64).max(1e-9); let mut buckets = vec![vec![]; N * N]; let index = |v: f64, o: f64| (((v - o) / size).floor().max(0.0) as usize).min(N - 1); - for (k, (a, b)) in edges.iter().enumerate() { - let (i0, i1) = (index(a.x.min(b.x), bounds.x0), index(a.x.max(b.x), bounds.x0)); - let (j0, j1) = (index(a.y.min(b.y), bounds.y0), index(a.y.max(b.y), bounds.y0)); + let spans = |(a, b): &(Point, Point)| { + ((index(a.x.min(b.x), bounds.x0), index(a.x.max(b.x), bounds.x0)), (index(a.y.min(b.y), bounds.y0), index(a.y.max(b.y), bounds.y0))) + }; + let entries = edges.iter().map(spans).fold(0usize, |sum, ((i0, i1), (j0, j1))| sum.saturating_add((i1 - i0 + 1) * (j1 - j0 + 1))); + if entries > MAX_EDGE_ENTRIES { + return Err(TOO_COMPLEX_SURFACE.into()); + } + for (k, e) in edges.iter().enumerate() { + let ((i0, i1), (j0, j1)) = spans(e); for j in j0..=j1 { for i in i0..=i1 { buckets[j * N + i].push(k as u32); } } } - Self { edges, normals, origin: bounds.origin(), size, n: N, buckets } + Ok(Self { edges, normals, origin: bounds.origin(), size, n: N, buckets, work: Cell::new(entries), budget: grid_budget() }) + } + + /// Has the work done with the index gone past its budget? + pub(super) fn spent(&self) -> bool { + self.work.get() > self.budget + } + + /// The work done with the index so far. + #[cfg(test)] + pub(super) fn work(&self) -> usize { + self.work.get() + } + + /// Count `amount` more work; `false` once the budget is spent, when the work is not to be done. + pub(super) fn charge(&self, amount: usize) -> bool { + if self.spent() { + return false; + } + self.work.set(self.work.get().saturating_add(amount)); + !self.spent() + } + + /// The edges filed in bucket (`i`, `j`), counted as work; none once the budget is spent. + fn bucket(&self, i: isize, j: isize) -> &[u32] { + let bucket = self.buckets.get((j * self.n as isize + i) as usize).map_or(&[][..], Vec::as_slice); + if self.charge(bucket.len()) { bucket } else { &[] } } /// The bucket row or column of coordinate `v`, from the grid's origin `o` on that axis. @@ -58,15 +120,11 @@ impl Edges { /// looked at. pub(super) fn near(&self, p: Point, tolerance: f64) -> bool { self.touch(Rect::new(p.x - tolerance, p.y - tolerance, p.x + tolerance, p.y + tolerance)) && { - let n = self.n as isize; let (i0, i1) = (self.cell(p.x - tolerance, self.origin.x), self.cell(p.x + tolerance, self.origin.x)); let (j0, j1) = (self.cell(p.y - tolerance, self.origin.y), self.cell(p.y + tolerance, self.origin.y)); (j0..=j1).any(|j| { (i0..=i1).any(|i| { - self.buckets[(j * n + i) as usize] - .iter() - .filter_map(|k| self.edges.get(*k as usize)) - .any(|(a, b)| segment_distance(p, *a, *b) <= tolerance) + self.bucket(i, j).iter().filter_map(|k| self.edges.get(*k as usize)).any(|(a, b)| segment_distance(p, *a, *b) <= tolerance) }) }) } @@ -75,10 +133,9 @@ impl Edges { /// Call `f` with each edge whose bounding box overlaps `r` (an edge in several of the /// buckets `r` covers comes more than once). fn each(&self, r: Rect, mut f: impl FnMut(Point, Point)) { - let n = self.n as isize; for j in self.cell(r.y0, self.origin.y)..=self.cell(r.y1, self.origin.y) { for i in self.cell(r.x0, self.origin.x)..=self.cell(r.x1, self.origin.x) { - for (a, b) in self.buckets[(j * n + i) as usize].iter().filter_map(|k| self.edges.get(*k as usize)) { + for (a, b) in self.bucket(i, j).iter().filter_map(|k| self.edges.get(*k as usize)) { if a.x.min(b.x) <= r.x1 && a.x.max(b.x) >= r.x0 && a.y.min(b.y) <= r.y1 && a.y.max(b.y) >= r.y0 { f(*a, *b); } @@ -89,12 +146,11 @@ impl Edges { /// Does any edge pass through `r` (its bounding box, at least, overlapping it)? pub(super) fn touch(&self, r: Rect) -> bool { - let n = self.n as isize; let (i0, i1) = (self.cell(r.x0, self.origin.x), self.cell(r.x1, self.origin.x)); let (j0, j1) = (self.cell(r.y0, self.origin.y), self.cell(r.y1, self.origin.y)); (j0..=j1).any(|j| { (i0..=i1).any(|i| { - self.buckets[(j * n + i) as usize] + self.bucket(i, j) .iter() .filter_map(|k| self.edges.get(*k as usize)) .any(|(a, b)| a.x.min(b.x) <= r.x1 && a.x.max(b.x) >= r.x0 && a.y.min(b.y) <= r.y1 && a.y.max(b.y) >= r.y0) @@ -122,12 +178,15 @@ impl Edges { let mut best = f64::INFINITY; let mut nearest = (p, Vec2::ZERO); for r in 0..n { + if self.spent() { + break; + } for j in (cj - r)..=(cj + r) { for i in (ci - r)..=(ci + r) { if (j - cj).abs() != r && (i - ci).abs() != r || i < 0 || j < 0 || i >= n || j >= n { continue; } - for k in &self.buckets[(j * n + i) as usize] { + for k in self.bucket(i, j) { if let Some((a, b)) = self.edges.get(*k as usize) { let d = *b - *a; let t = if d.hypot2() < 1e-18 { 0.0 } else { ((p - *a).dot(d) / d.hypot2()).clamp(0.0, 1.0) }; @@ -152,9 +211,24 @@ impl Edges { } } -/// Is `p` filled by `rings` (nonzero winding, as they are oriented)? -pub(super) fn filled(rings: &[Vec], p: Point) -> bool { - rings.iter().filter(|r| contains(r, p)).count() % 2 == 1 +/// Where the edges of `rings` cross the line through `y`, in order: the points of the line +/// filled by `rings` (nonzero winding, as they are oriented) are those with an odd number of +/// crossings to their right ([`filled`]). An edge crosses where one end is above the line and +/// the other is not, as [`super::rings::contains`] counts it. +pub(super) fn crossings(rings: &[Vec], y: f64) -> Vec { + let mut xs: Vec = rings + .iter() + .flat_map(|r| r.iter().zip(r.iter().cycle().skip(1)).take(r.len())) + .filter(|(a, b)| (a.y > y) != (b.y > y)) + .map(|(a, b)| a.x + (y - a.y) / (b.y - a.y) * (b.x - a.x)) + .collect(); + xs.sort_by(f64::total_cmp); + xs +} + +/// Is `x` filled on the line whose [`crossings`] are `xs`? +pub(super) fn filled(xs: &[f64], x: f64) -> bool { + (xs.len() - xs.partition_point(|v| *v <= x)) % 2 == 1 } /// `ring` cut to the rectangle `cell` (Sutherland–Hodgman: the rectangle is convex, the ring @@ -203,13 +277,17 @@ impl Membrane { pub(super) fn solve(rings: &[Vec], edges: &Edges, origin: Point, step: f64, nx: usize, ny: usize) -> Self { let node = |i: usize, j: usize| Point::new(origin.x + i as f64 * step, origin.y + j as f64 * step); let idx = |i: usize, j: usize| j * nx + i; - // A node on the outline itself is held at zero with the outside. - let inside: Vec = (0..nx * ny) - .map(|k| { - let p = node(k % nx, k / nx); - filled(rings, p) && !edges.near(p, 1e-6 * step) - }) - .collect(); + // A node on the outline itself is held at zero with the outside. Each row of nodes is + // tested against the crossings of its line. + let points = rings.iter().map(Vec::len).fold(0usize, usize::saturating_add); + let mut inside = Vec::with_capacity(nx * ny); + for j in 0..ny { + let xs = if edges.charge(points) { crossings(rings, node(0, j).y) } else { vec![] }; + inside.extend((0..nx).map(|i| { + let p = node(i, j); + filled(&xs, p.x) && !edges.near(p, 1e-6 * step) + })); + } // The nearest crossing of the outline from `p` along (dx, dy), within one step. let crossing = |p: Point, dx: f64, dy: f64| -> f64 { let mut best = step; diff --git a/crates/three-d/src/solid/outline.rs b/crates/three-d/src/solid/outline.rs new file mode 100644 index 0000000000..07fb0ce58b --- /dev/null +++ b/crates/three-d/src/solid/outline.rs @@ -0,0 +1,196 @@ +//! Curved outlines for the facets of a solid: a cap, the flat plane of Rotate and the edges of a +//! wall along the profile follow the profile's curves as cubics, while each facet's polygon stays +//! the shape that visibility and depth are worked out on. + +use vectorcraft_geom::{BezPath, CubicBez, ParamCurve, PathData, Point}; + +use super::rings::{Ring, Span}; + +/// How far a fitted cubic may lie from the outline it follows, in points. +pub(super) const CURVE_TOLERANCE: f64 = 0.001; + +/// How many times one piece of curve is halved at most to fit it. A piece that still misses the +/// tolerance keeps its sampled straight edges. +const MAX_DEPTH: u32 = 8; + +/// Fitted cubics one solid's outlines hold at most. Past it, the remaining edges stay straight. +pub(super) const MAX_OUTLINE_CURVES: usize = 1 << 20; + +/// The fitted cubics of one solid: how many it holds so far, against [`MAX_OUTLINE_CURVES`]. +#[derive(Default)] +pub(super) struct Budget(usize); + +/// The outline of a solid at one step, as a point of the document for a point of a profile's +/// curve: `at(span, t)` is where the outline lies at `t` on `span`'s curve. `tolerance` is how far +/// a fitted cubic may lie from it. With `map`, the outline is the curve moved point by point by +/// that map, and a piece of curve is tried first as its control points moved by it: exact when +/// `affine`, otherwise kept when it lies within the tolerance. +pub(super) struct Along<'a> { + pub(super) at: &'a dyn Fn(&Span, f64) -> Point, + pub(super) map: Option<&'a dyn Fn(Point) -> Point>, + pub(super) affine: bool, + pub(super) tolerance: f64, +} + +/// `g` from `p` at `a` to `q` at `b` as cubics within `tolerance`, appended to `out`. False when it +/// does not fit within [`MAX_DEPTH`] halvings, or reaches a point that is not finite. +#[allow(clippy::too_many_arguments)] +fn fit(g: &dyn Fn(f64) -> Point, p: Point, q: Point, a: f64, b: f64, tolerance: f64, depth: u32, out: &mut Vec) -> bool { + // Second-order one-sided differences, taken inside the piece: a handle of zero length at an end + // of the source curve turns its normal, and so an inset outline's tangent, at that end. + let h = (b - a) * 1e-5; + if h == 0.0 || !h.is_finite() { + return false; + } + let (g0, g1, g2) = (g(a), g(a + h), g(a + 2.0 * h)); + let start = (g1 - g0) * 2.0 - (g2 - g0) * 0.5; + let (g0, g1, g2) = (g(b), g(b - h), g(b - 2.0 * h)); + let end = (g0 - g1) * 2.0 - (g0 - g2) * 0.5; + let (start, end) = (start / h, end / h); + let curve = CubicBez::new(p, p + start * ((b - a) / 3.0), q - end * ((b - a) / 3.0), q); + let points = [curve.p1, curve.p2]; + if points.iter().any(|c| !c.x.is_finite() || !c.y.is_finite()) { + return false; + } + let mut error = 0.0f64; + for u in [0.25, 0.5, 0.75] { + let want = g(a + (b - a) * u); + if !want.x.is_finite() || !want.y.is_finite() { + return false; + } + error = error.max(curve.eval(u).distance(want)); + } + if error <= tolerance { + out.push(curve); + return true; + } + if depth >= MAX_DEPTH { + return false; + } + let mid = (a + b) / 2.0; + let m = g(mid); + if !m.x.is_finite() || !m.y.is_finite() { + return false; + } + fit(g, p, m, a, mid, tolerance, depth + 1, out) && fit(g, m, q, mid, b, tolerance, depth + 1, out) +} + +/// The cubics from `p` to `q` along the piece of `span`'s curve from `t0` to `t1` at `step`, or +/// `None` when they do not fit, or would take the budget past [`MAX_OUTLINE_CURVES`]. +/// +/// `p` and `q` are the face's own corners, which a bevel's miter can move off the curve's offset +/// where the curve meets another edge at an angle. The difference is eased out from `p` by `fade.0` +/// and into `q` from `fade.1` (the ends of the first and last sampled edge), as the face's polygon +/// does over those edges, so the curves meet the face's corners. +#[allow(clippy::too_many_arguments)] +fn piece(step: &Along, span: &Span, t0: f64, t1: f64, fade: (f64, f64), p: Point, q: Point, budget: &mut Budget) -> Option> { + if let Some(map) = step.map { + let c = span.curve.subsegment(t0..t1); + let c = CubicBez::new(p, map(c.p1), map(c.p2), q); + let finite = [c.p1, c.p2].iter().all(|q| q.x.is_finite() && q.y.is_finite()); + let fits = || [0.25, 0.5, 0.75].into_iter().all(|u| c.eval(u).distance((step.at)(span, t0 + (t1 - t0) * u)) <= step.tolerance); + if finite && (step.affine || fits()) { + budget.0 = budget.0.saturating_add(1); + return (budget.0 <= MAX_OUTLINE_CURVES).then(|| vec![c]); + } + } + let (dp, dq) = (p - (step.at)(span, t0), q - (step.at)(span, t1)); + // 1 at the end, 0 from `to` on, with no slope at either. + let ease = |t: f64, from: f64, to: f64| { + let x = if to == from { 1.0 } else { ((t - from) / (to - from)).clamp(0.0, 1.0) }; + 1.0 - x * x * (3.0 - 2.0 * x) + }; + let g = |t: f64| (step.at)(span, t) + dp * ease(t, t0, fade.0) + dq * ease(t, t1, fade.1); + let mut out = vec![]; + if !fit(&g, p, q, t0, t1, step.tolerance, 0, &mut out) { + return None; + } + budget.0 = budget.0.saturating_add(out.len()); + (budget.0 <= MAX_OUTLINE_CURVES).then_some(out) +} + +/// Append contour `points` (closed), whose edges follow `ring`'s, to `path`: each run of edges along +/// one piece of curve as cubics, and the rest straight. False when no edge is curved. +fn contour(path: &mut BezPath, ring: &Ring, points: &[Point], step: &Along, budget: &mut Budget) -> bool { + let n = points.len(); + let Some(&first) = points.first() else { return false }; + if ring.spans.len() != n { + return false; + } + path.move_to(first); + let mut curved = false; + let mut i = 0; + while i < n { + let end = |k: usize| points.get((k + 1) % n).copied().unwrap_or(first); + let Some(span) = ring.spans.get(i).copied().flatten() else { + if i + 1 < n { + path.line_to(end(i)); + } + i += 1; + continue; + }; + // The run of edges that follow this curve one after the other. An inset outline is fitted + // one edge at a time, as `wall` fits it, so a cap and its walls share the same curves. + let (mut j, mut t1, mut last) = (i, span.t1, span.t0); + while step.map.is_some() + && let Some(Some(next)) = ring.spans.get(j + 1) + && next.curve == span.curve + && next.t0 == t1 + { + (j, t1, last) = (j + 1, next.t1, next.t0); + } + let (p, q) = (points.get(i).copied().unwrap_or(first), end(j)); + match piece(step, &span, span.t0, t1, (span.t1, last), p, q, budget) { + Some(curves) => { + curved = true; + for c in curves { + path.curve_to(c.p1, c.p2, c.p3); + } + } + // The edge back to the first point is drawn by `close_path`. + None => (i..=j).filter(|k| k + 1 < n).for_each(|k| path.line_to(end(k))), + } + i = j + 1; + } + path.close_path(); + curved +} + +/// The outline of a face made of `rings` at one `step` (a cap, or Rotate's plane), projected as +/// `points` (the face's contours, one for each ring and as long). `None` when no edge is curved. +pub(super) fn face(rings: &[&Ring], points: &[Vec], step: &Along, budget: &mut Budget) -> Option { + if rings.len() != points.len() || rings.iter().all(|r| r.spans.iter().all(Option::is_none)) { + return None; + } + let mut path = BezPath::new(); + let mut curved = false; + for (ring, points) in rings.iter().zip(points) { + curved |= contour(&mut path, ring, points, step, budget); + } + curved.then(|| PathData::from_bezpath(&path)) +} + +/// The outline of a wall's quad `quad` (`a`, `a'`, `b'`, `b` projected: the edge at `near` from +/// `a` to `a'`, then the edge at `far` back from `b'` to `b`), whose edges along the profile follow +/// `span`. An edge without its outline stays straight. `None` when neither edge is curved. +pub(super) fn wall(span: &Span, quad: &[Point], near: Option<&Along>, far: Option<&Along>, budget: &mut Budget) -> Option { + let [a, a2, b2, b] = <[Point; 4]>::try_from(quad).ok()?; + let front = near.and_then(|near| piece(near, span, span.t0, span.t1, (span.t1, span.t0), a, a2, budget)); + let back = far.and_then(|far| piece(far, span, span.t1, span.t0, (span.t0, span.t1), b2, b, budget)); + if front.is_none() && back.is_none() { + return None; + } + let mut path = BezPath::new(); + path.move_to(a); + match front { + Some(curves) => curves.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)), + None => path.line_to(a2), + } + path.line_to(b2); + match back { + Some(curves) => curves.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)), + None => path.line_to(b), + } + path.close_path(); + Some(PathData::from_bezpath(&path)) +} diff --git a/crates/three-d/src/solid/rings.rs b/crates/three-d/src/solid/rings.rs index 81e67cc039..7aed5e4191 100644 --- a/crates/three-d/src/solid/rings.rs +++ b/crates/three-d/src/solid/rings.rs @@ -1,8 +1,7 @@ -use super::{FillRule, ParamCurve, PathData, Point, Rect}; +use super::{FillRule, MAX_SOLID_FACES, ParamCurve, PathData, Point, Rect}; -/// Outline points Extrude & Bevel and Inflate sample at most: every point costs walls, bevel -/// bands and distance tests. -pub(super) const MAX_SOLID_POINTS: usize = 2048; +/// Outline points Extrude & Bevel and Inflate sample at most, and contours they take at most. +pub(super) const MAX_SOLID_POINTS: usize = 65536; /// Outline points Rotate samples at most: it only turns the outline, so an outlined paragraph fits. pub(super) const MAX_PLANE_POINTS: usize = 65536; @@ -10,13 +9,76 @@ pub(super) const MAX_PLANE_POINTS: usize = 65536; /// Pieces a twisted wall's strip is cut into along one edge at most. pub(super) const MAX_PIECES: usize = 64; +/// Pieces a curve takes at most, where its tolerance asks for them. +pub(super) const CURVE_PIECES: u32 = 32; + +/// The fewest pieces a curve of a solid over its budget is held to: a curve whose tolerance asks +/// for fewer takes fewer. +pub(super) const MIN_CURVE_PIECES: u32 = 4; + +const TOO_COMPLEX_SHAPE: &str = "The shape is too complex for a 3D effect"; +pub(super) const TOO_COMPLEX_SURFACE: &str = "The 3D surface is too complex; simplify the shape"; + /// How many straight pieces follow `c` within `tolerance` (Wang's bound on a cubic's distance from -/// its chords), 1 to 32. +/// its chords), 1 to [`CURVE_PIECES`]. fn pieces(c: vectorcraft_geom::CubicBez, tolerance: f64) -> u32 { let d = |a: Point, b: Point, c: Point| (a.to_vec2() - 2.0 * b.to_vec2() + c.to_vec2()).hypot(); let bend = d(c.p0, c.p1, c.p2).max(d(c.p1, c.p2, c.p3)); let n = (0.75 * bend / tolerance).sqrt().ceil(); - if n.is_finite() { (n as u32).clamp(1, 32) } else { 32 } + if n.is_finite() { (n as u32).clamp(1, CURVE_PIECES) } else { CURVE_PIECES } +} + +/// The most pieces each curve of a solid's outline takes, counted on `path` before any point is +/// sampled: [`CURVE_PIECES`] when the outline fits within [`MAX_SOLID_POINTS`] points and +/// [`MAX_SOLID_FACES`] faces, else the largest number down to [`MIN_CURVE_PIECES`] that fits, the +/// same for every curve. A curve whose tolerance (see [`sample`]) asks for fewer pieces takes +/// fewer. The faces are counted as `per_edge` for each edge of the outline and `fixed` more. +/// +/// An error when the outline takes more than [`MAX_SOLID_POINTS`] points, or contours, with +/// every curve held to [`MIN_CURVE_PIECES`], and when its faces do not fit with that many. +pub(super) fn curve_pieces(path: &PathData, size: f64, per_edge: usize, fixed: usize) -> Result { + let tolerance = (size / 2000.0).max(0.05); + // How many curves ask for each number of pieces. + let mut curves = [0usize; CURVE_PIECES as usize + 1]; + let (mut lines, mut segments, mut open) = (0usize, 0usize, 0usize); + for (contours, sp) in path.subpaths.iter().enumerate() { + if contours >= MAX_SOLID_POINTS { + return Err(TOO_COMPLEX_SHAPE.into()); + } + // A subpath of one anchor draws nothing, as in [`sample`]. + if sp.anchors.len() < 2 { + continue; + } + if sp.anchors.iter().any(|a| [a.p, a.h_in, a.h_out].iter().any(|q| !q.x.is_finite() || !q.y.is_finite())) { + return Err("The shape contains invalid coordinates".into()); + } + let count = if sp.closed { sp.anchors.len() } else { sp.anchors.len() - 1 }; + // Every segment takes a point at least. + segments = segments.saturating_add(count); + if segments > MAX_SOLID_POINTS { + return Err(TOO_COMPLEX_SHAPE.into()); + } + open += usize::from(!sp.closed); + for i in 0..count { + if sp.segment_is_line(i) { + lines += 1; + } else if let Some(n) = curves.get_mut(pieces(sp.segment(i), tolerance) as usize) { + *n += 1; + } + } + } + let points = |most: u32| -> usize { + curves.iter().enumerate().fold(lines, |sum, (asked, n)| sum.saturating_add(n.saturating_mul(asked.min(most as usize)))) + }; + if points(MIN_CURVE_PIECES) > MAX_SOLID_POINTS { + return Err(TOO_COMPLEX_SHAPE.into()); + } + // An open contour is closed by one more edge. + let faces = |most: u32| points(most).saturating_add(open).saturating_mul(per_edge).saturating_add(fixed); + (MIN_CURVE_PIECES..=CURVE_PIECES) + .rev() + .find(|most| points(*most) <= MAX_SOLID_POINTS && faces(*most) <= MAX_SOLID_FACES) + .ok_or_else(|| TOO_COMPLEX_SURFACE.into()) } /// Contours thinner than this on average (twice their area over their perimeter) are dropped when @@ -37,16 +99,9 @@ pub(super) const DEBRIS: f64 = 1e-6; /// are. A profile the boolean refuses is built from its contours as drawn, as it was before /// contours were merged. An empty answer is an answer: contours that cancel (a square drawn twice /// under even-odd), or that are all thinner than [`DEBRIS`], fill nothing, so nothing is built. -pub(super) fn solid_rings(path: &PathData, rule: FillRule, size: f64, limit: usize) -> Result>, String> { - let sampled = sample(path, size, limit)?; - let closed = closed_straight(path); - if !meets(&sampled, &closed) { - return orient(sampled, rule); - } - match vectorcraft_pathops::try_unite_all_with(&[(&closed, rule)], DEBRIS) { - Ok(merged) => sample(&merged, size, limit).map(wound), - Err(_) => orient(sampled, rule), - } +/// Each curve takes at most `most` pieces, on the profile as drawn and on the merged outline. +pub(super) fn solid_rings(path: &PathData, rule: FillRule, size: f64, limit: usize, most: u32) -> Result>, String> { + Ok(solid_rings_traced(path, rule, size, limit, most)?.into_iter().map(|r| r.points).collect()) } /// Do the `sampled` rings of `closed` (the profile as the boolean takes it) meet, so that it must @@ -92,10 +147,10 @@ pub(super) fn closed_straight(path: &PathData) -> std::borrow::Cow<'_, PathData> /// The boolean's rings turned so the filled side is on each one's left. Its holes already run /// against their outlines, so only the direction of the whole is chosen: the one whose rings /// enclose positive area in all. -pub(super) fn wound(mut rings: Vec>) -> Vec> { - rings.retain(|r| signed_area(r).abs() > 1e-9); - if rings.iter().map(|r| signed_area(r)).sum::() < 0.0 { - rings.iter_mut().for_each(|r| r.reverse()); +pub(super) fn wound(mut rings: Vec) -> Vec { + rings.retain(|r| signed_area(r.points()).abs() > 1e-9); + if rings.iter().map(|r| signed_area(r.points())).sum::() < 0.0 { + rings.iter_mut().for_each(Turnable::turn_around); } rings } @@ -188,6 +243,71 @@ fn segments_meet(a: Point, b: Point, c: Point, d: Point, touch: f64) -> bool { dist(a, c, d).min(dist(b, c, d)).min(dist(c, a, b)).min(dist(d, a, b)) <= touch } +/// Where one edge of a sampled ring lies on the curve it follows: the piece of `curve` from `t0` +/// to `t1` (`t1` below `t0` on a ring that runs against its curve). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Span { + pub(super) curve: vectorcraft_geom::CubicBez, + pub(super) t0: f64, + pub(super) t1: f64, +} + +/// A sampled ring with, for each edge (point `i` to point `i + 1`, the last back to the first), +/// the piece of curve it follows, or `None` for a straight edge. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Ring { + pub(super) points: Vec, + pub(super) spans: Vec>, +} + +/// A ring that [`orient`] and [`wound`] can turn around. +pub(super) trait Turnable { + fn points(&self) -> &[Point]; + fn turn_around(&mut self); +} + +impl Turnable for Vec { + fn points(&self) -> &[Point] { + self + } + fn turn_around(&mut self) { + self.reverse(); + } +} + +impl Turnable for Ring { + fn points(&self) -> &[Point] { + &self.points + } + fn turn_around(&mut self) { + // The ring keeps its first point, an anchor of the art, so that a run of edges along one + // curve doesn't start part way along it. Edge `j` of the turned ring is edge `n - 1 - j` + // of the ring, run the other way. + self.points.reverse(); + if !self.points.is_empty() { + self.points.rotate_right(1); + } + self.spans.reverse(); + for s in self.spans.iter_mut().flatten() { + std::mem::swap(&mut s.t0, &mut s.t1); + } + } +} + +/// [`solid_rings`] with the piece of curve each edge follows. +pub(super) fn solid_rings_traced(path: &PathData, rule: FillRule, size: f64, limit: usize, most: u32) -> Result, String> { + let sampled = sample_traced(path, size, limit, most)?; + let closed = closed_straight(path); + let points: Vec> = sampled.iter().map(|r| r.points.clone()).collect(); + if !meets(&points, &closed) { + return orient(sampled, rule); + } + match vectorcraft_pathops::try_unite_all_with(&[(&closed, rule)], DEBRIS) { + Ok(merged) => sample_traced(&merged, size, limit, most).map(wound), + Err(_) => orient(sampled, rule), + } +} + /// The rings of a shape: closed polygons with the filled side on their left, (-dy, dx): outer /// outlines run one way and holes the other, so nonzero winding fills them as the art is. Curves /// are followed within a tolerance of 1/2000 of `size` (at least 0.05 pt), so small curves take @@ -197,12 +317,17 @@ fn segments_meet(a: Point, b: Point, c: Point, d: Point, touch: f64) -> bool { /// is left out: a contour inside another that runs the same way doesn't cut a hole, as it would /// if nesting alone decided (#1724). pub(super) fn rings(path: &PathData, rule: FillRule, size: f64, limit: usize) -> Result>, String> { - orient(sample(path, size, limit)?, rule) + orient(sample(path, size, limit, CURVE_PIECES)?, rule) } /// The closed polygons that follow `path`'s subpaths, as [`rings`] samples them, each running as -/// its subpath does. -pub(super) fn sample(path: &PathData, size: f64, limit: usize) -> Result>, String> { +/// its subpath does, each curve in at most `most` pieces. +pub(super) fn sample(path: &PathData, size: f64, limit: usize, most: u32) -> Result>, String> { + Ok(sample_traced(path, size, limit, most)?.into_iter().map(|r| r.points).collect()) +} + +/// [`sample`] with the piece of curve each edge follows. +fn sample_traced(path: &PathData, size: f64, limit: usize, most: u32) -> Result, String> { let tolerance = (size / 2000.0).max(0.05); let mut count = 0; let mut out = vec![]; @@ -210,36 +335,46 @@ pub(super) fn sample(path: &PathData, size: f64, limit: usize) -> Result= 2) { let segments = if sp.closed { sp.anchors.len() } else { sp.anchors.len() - 1 }; if segments > limit { - return Err("The shape is too complex for a 3D effect".into()); + return Err(TOO_COMPLEX_SHAPE.into()); } - let mut ring: Vec = vec![]; + // Each point with the piece of curve of the edge that ends at it. + let mut ring: Vec<(Point, Option)> = vec![]; if let Some(first) = sp.anchors.first() { - ring.push(first.p); + ring.push((first.p, None)); } for i in 0..segments { let curve = sp.segment(i); - let samples = if sp.segment_is_line(i) { 1 } else { pieces(curve, tolerance) }; + let line = sp.segment_is_line(i); + let samples = if line { 1 } else { pieces(curve, tolerance).min(most.max(1)) }; count += samples as usize; if count > limit { - return Err("The shape is too complex for a 3D effect".into()); + return Err(TOO_COMPLEX_SHAPE.into()); } for k in 1..=samples { - ring.push(curve.eval(f64::from(k) / f64::from(samples))); + let (t0, t1) = (f64::from(k - 1) / f64::from(samples), f64::from(k) / f64::from(samples)); + ring.push((curve.eval(t1), (!line).then_some(Span { curve, t0, t1 }))); } } - if ring.iter().any(|p| !p.x.is_finite() || !p.y.is_finite() || p.x.abs() > 1e8 || p.y.abs() > 1e8) { + if ring.iter().any(|(p, _)| !p.x.is_finite() || !p.y.is_finite() || p.x.abs() > 1e8 || p.y.abs() > 1e8) { return Err("The shape contains invalid coordinates".into()); } - ring.dedup_by(|a, b| a.distance(*b) < 1e-9); - while ring.len() > 1 && ring.first().zip(ring.last()).is_some_and(|(a, b)| a.distance(*b) < 1e-9) { - ring.pop(); + ring.dedup_by(|a, b| a.0.distance(b.0) < 1e-9); + // The last point back on the first closes the ring along the edge that ends at it. + while ring.len() > 1 && ring.first().zip(ring.last()).is_some_and(|(a, b)| a.0.distance(b.0) < 1e-9) { + let closing = ring.pop().and_then(|(_, s)| s); + if let Some(first) = ring.first_mut() { + first.1 = closing; + } } + let points: Vec = ring.iter().map(|(p, _)| *p).collect(); // Rings with no area are kept here: a contour that crosses itself into lobes that cancel // (a bowtie) has none, and [`edges_meet`] must see it. [`orient`] leaves them out. A flat // ring, every point on one line, fills nothing under either rule and is left out now, so // that it doesn't send the profile through the boolean. - if ring.len() >= 3 && !flat(&ring) { - out.push(ring); + if points.len() >= 3 && !flat(&points) { + let n = points.len(); + let spans = (0..n).map(|i| ring.get((i + 1) % n).and_then(|(_, s)| *s)).collect(); + out.push(Ring { points, spans }); } } Ok(out) @@ -247,15 +382,15 @@ pub(super) fn sample(path: &PathData, size: f64, limit: usize) -> Result>, rule: FillRule) -> Result>, String> { - out.retain(|r| signed_area(r).abs() > 1e-9); +fn orient(mut out: Vec, rule: FillRule) -> Result, String> { + out.retain(|r| signed_area(r.points()).abs() > 1e-9); // Which rings hold which: each ring against the others, its edges walked only where its // bounds hold the point, and within [`MAX_CONTAINMENT_EDGES`] edges and pairs in all (a pair // whose bounds miss the point costs a step too: many small rings are a square of pairs). - let too_complex = || String::from("The shape is too complex for a 3D effect"); + let too_complex = || String::from(TOO_COMPLEX_SHAPE); let mut work = 0usize; - let mut within = |out: &[Vec], bounds: &[Rect], i: usize| -> Result, String> { - let p = out.get(i).and_then(|r| r.first()).copied().unwrap_or_default(); + let mut within = |out: &[R], bounds: &[Rect], i: usize| -> Result, String> { + let p = out.get(i).and_then(|r| r.points().first()).copied().unwrap_or_default(); let mut held_by = vec![]; for (j, (o, b)) in out.iter().zip(bounds).enumerate() { work = work.saturating_add(1); @@ -265,18 +400,18 @@ fn orient(mut out: Vec>, rule: FillRule) -> Result>, S } continue; } - work = work.saturating_add(o.len()); + work = work.saturating_add(o.points().len()); if work > MAX_CONTAINMENT_EDGES { return Err(too_complex()); } - if contains(o, p) { + if contains(o.points(), p) { held_by.push(j); } } Ok(held_by) }; - let bounds_of = |out: &[Vec]| -> Vec { - out.iter().map(|r| r.iter().map(|q| Rect::from_points(*q, *q)).reduce(|a, b| a.union(b)).unwrap_or_default()).collect() + let bounds_of = |out: &[R]| -> Vec { + out.iter().map(|r| r.points().iter().map(|q| Rect::from_points(*q, *q)).reduce(|a, b| a.union(b)).unwrap_or_default()).collect() }; if rule == FillRule::NonZero { let turn = |r: &[Point]| if signed_area(r) > 0.0 { 1 } else { -1 }; @@ -284,8 +419,8 @@ fn orient(mut out: Vec>, rule: FillRule) -> Result>, S let mut edge = Vec::with_capacity(out.len()); for (i, r) in out.iter().enumerate() { // The winding number just outside the ring, and just inside it. - let outside: i32 = within(&out, &bounds, i)?.into_iter().filter_map(|j| out.get(j)).map(|o| turn(o)).sum(); - edge.push((outside != 0) != (outside + turn(r) != 0)); + let outside: i32 = within(&out, &bounds, i)?.into_iter().filter_map(|j| out.get(j)).map(|o| turn(o.points())).sum(); + edge.push((outside != 0) != (outside + turn(r.points()) != 0)); } let mut edge = edge.into_iter(); out.retain(|_| edge.next().unwrap_or(true)); @@ -294,8 +429,8 @@ fn orient(mut out: Vec>, rule: FillRule) -> Result>, S let bounds = bounds_of(&out); let holes: Vec = (0..out.len()).map(|i| within(&out, &bounds, i).map(|held| held.len() % 2 == 1)).collect::>()?; for (r, hole) in out.iter_mut().zip(holes) { - if (signed_area(r) > 0.0) == hole { - r.reverse(); + if (signed_area(r.points()) > 0.0) == hole { + r.turn_around(); } } Ok(out) diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index 46d1782875..af9322bc12 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -277,11 +277,14 @@ fn malformed_and_degenerate_input_is_bounded() { // Too many anchors: refused, not truncated. let mut many = BezPath::new(); many.move_to((0.0, 0.0)); - for i in 0..3000 { + for i in 0..70_000 { many.line_to((f64::from(i), f64::from(i % 7))); } many.close_path(); - assert!(extrude(&PathData::from_bezpath(&many), FillRule::EvenOdd, b, Extrude::default(), front()).is_err()); + assert_eq!( + extrude(&PathData::from_bezpath(&many), FillRule::EvenOdd, b, Extrude::default(), front()).unwrap_err(), + "The shape is too complex for a 3D effect" + ); } #[test] @@ -313,6 +316,195 @@ fn a_wider_perspective_brings_the_eye_nearer() { assert!(close(last, 100.0 * eye / (eye - 50.0), 1e-6), "{last}"); } +/// A circle of four cubics about `c`. +fn circle(c: Point, r: f64) -> BezPath { + let k = 0.552_284_749_830_793_6 * r; + let mut b = BezPath::new(); + b.move_to((c.x + r, c.y)); + b.curve_to((c.x + r, c.y + k), (c.x + k, c.y + r), (c.x, c.y + r)); + b.curve_to((c.x - k, c.y + r), (c.x - r, c.y + k), (c.x - r, c.y)); + b.curve_to((c.x - r, c.y - k), (c.x - k, c.y - r), (c.x, c.y - r)); + b.curve_to((c.x + k, c.y - r), (c.x + r, c.y - k), (c.x + r, c.y)); + b.close_path(); + b +} + +/// A "D" with its counter, as outlined type draws one: straight stems, round bowls, and corners +/// where they meet. +fn letter_d() -> BezPath { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((40.0, 0.0)); + b.curve_to((95.0, 0.0), (95.0, 100.0), (40.0, 100.0)); + b.line_to((0.0, 100.0)); + b.close_path(); + b.move_to((20.0, 20.0)); + b.line_to((20.0, 80.0)); + b.line_to((40.0, 80.0)); + b.curve_to((70.0, 80.0), (70.0, 20.0), (40.0, 20.0)); + b.close_path(); + b +} + +/// A path's curved segments, segments, smooth anchors and anchors. +fn anatomy(p: &PathData) -> [usize; 4] { + let mut n = [0; 4]; + for sp in &p.subpaths { + let count = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; + n[0] += (0..count).filter(|i| !sp.segment_is_line(*i)).count(); + n[1] += count; + n[2] += sp.anchors.iter().filter(|a| a.kind == vectorcraft_geom::AnchorKind::Smooth).count(); + n[3] += sp.anchors.len(); + } + n +} + +/// `b` flattened to within 1e-6 pt, each point moved by `map`. +fn fine(b: &BezPath, map: impl Fn(Point) -> Point) -> Vec> { + let mut out: Vec> = vec![]; + vectorcraft_geom::kurbo::flatten(b, 1e-6, |el| match el { + vectorcraft_geom::kurbo::PathEl::MoveTo(p) => out.push(vec![map(p)]), + vectorcraft_geom::kurbo::PathEl::LineTo(p) => out.last_mut().into_iter().for_each(|r| r.push(map(p))), + _ => {} + }); + out +} + +/// How far `p` lies from the closed polygons `target` at most, sampled along each segment. +fn farthest(p: &PathData, target: &[Vec]) -> f64 { + let mut far = 0.0f64; + for sp in &p.subpaths { + let count = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; + for i in 0..count { + let c = sp.segment(i); + for k in 0..=32 { + let q = c.eval(f64::from(k) / 32.0); + assert!(q.x.is_finite() && q.y.is_finite(), "{q:?}"); + far = far.max(edge_distance(target, q)); + } + } + } + far +} + +/// Seen straight on, the front cap of an extruded circle or letter is the art: each curve stays +/// one cubic, smooth anchors stay smooth, and no point lies farther than the curve tolerance from +/// the art. The facet's polygon, which visibility uses, is still the sampled outline. +#[test] +fn a_cap_keeps_the_curves_of_the_art() { + for art in [circle(Point::new(50.0, 50.0), 40.0), letter_d()] { + let (p, b) = shape(&art); + let f = extrude(&p, FillRule::EvenOdd, b, Extrude::default(), front()).unwrap(); + assert_eq!(f.len(), 1); + let cap = f[0].path(); + assert_eq!(anatomy(&cap), anatomy(&p), "{cap:?}"); + assert!(f[0].contours.iter().map(Vec::len).sum::() > anatomy(&p)[3]); + let far = farthest(&cap, &fine(&art, |q| q)); + assert!(far <= outline::CURVE_TOLERANCE, "{far}"); + } +} + +/// Turned and in perspective, the front cap's curves are fitted to the projected circle within +/// the curve tolerance, every anchor stays smooth, and the walls' edges along it are curved too. +#[test] +fn a_cap_in_perspective_fits_the_projected_curves() { + let art = circle(Point::new(50.0, 50.0), 40.0); + let (p, b) = shape(&art); + let o = Extrude { depth: 50.0, ..Extrude::default() }; + for view in [View { rotation_x: 20.0, rotation_y: 30.0, perspective: 60.0, ..front() }, View { perspective: 120.0, ..front() }] { + let f = extrude(&p, FillRule::EvenOdd, b, o, view).unwrap(); + let cap = f.iter().find(|f| f.depth == f64::MAX).unwrap().path(); + let [curves, segments, smooth, anchors] = anatomy(&cap); + assert!(curves >= 4 && curves == segments && smooth == anchors, "{:?}", anatomy(&cap)); + let camera = Camera::new(view, b, o.depth); + let projected = fine(&art, |q| camera.project(camera.place(q, o.depth / 2.0))); + let far = farthest(&cap, &projected); + assert!(far <= outline::CURVE_TOLERANCE + 1e-6, "{far}"); + if view.rotation_y != 0.0 { + assert!(f.iter().filter(|f| f.depth != f64::MAX).any(|f| anatomy(&f.path())[0] == 2), "the walls' edges along the circle are curved"); + } + } +} + +/// A cap inset by a bevel and the walls next to it draw the edge they share as the same curves, so +/// no gap or overlap opens between them. +#[test] +fn a_beveled_cap_and_its_walls_share_their_curves() { + for (r, width) in [(40.0, 4.0), (400.0, 40.0)] { + for art in [circle(Point::new(r, r), r), letter_d()] { + let (p, b) = shape(&art); + let o = Extrude { depth: 50.0, bevel: Some(Bevel { inside: true, width, height: width, ..Bevel::default() }), ..Extrude::default() }; + let f = extrude(&p, FillRule::EvenOdd, b, o, View { rotation_x: 20.0, rotation_y: 30.0, ..front() }).unwrap(); + let caps: Vec<&Facet> = f.iter().filter(|f| f.depth == f64::MAX).collect(); + let outlines: Vec> = caps.iter().flat_map(|f| fine(&f.path().to_bezpath(), |q| q)).collect(); + let on_cap = |q: Point| caps.iter().flat_map(|f| f.contours.iter().flatten()).any(|v| v.distance(q) < 1e-9); + let (mut far, mut shared) = (0.0f64, 0); + for wall in f.iter().filter(|f| f.depth != f64::MAX && f.outline.is_some()) { + let path = wall.path(); + for sp in &path.subpaths { + for i in (0..sp.anchors.len()).filter(|i| !sp.segment_is_line(*i)) { + let c = sp.segment(i); + if !on_cap(c.p0) || !on_cap(c.p3) { + continue; + } + shared += 1; + for k in 0..=16 { + far = far.max(edge_distance(&outlines, c.eval(f64::from(k) / 16.0))); + } + } + } + } + assert!(shared > 0, "no wall shares a curved edge with a cap"); + assert!(far <= 1e-4, "{far}"); + } + } +} + +/// A twisted, tapered back cap follows the turned, scaled art; a cap inset by a bevel stays +/// within the sampling tolerance of the solid; a tiny circle and a curve with a handle of zero +/// length keep their cubics. +#[test] +fn twisted_beveled_tiny_and_degenerate_caps_keep_their_curves() { + let art = circle(Point::new(50.0, 50.0), 40.0); + let (p, b) = shape(&art); + let o = Extrude { depth: 50.0, twist: 45.0, taper: 0.5, ..Extrude::default() }; + let behind = View { rotation_y: 180.0, ..front() }; + let f = extrude(&p, FillRule::EvenOdd, b, o, behind).unwrap(); + let cap = f.iter().find(|f| f.depth == f64::MAX).unwrap().path(); + assert_eq!(anatomy(&cap)[0], 4); + let camera = Camera::new(behind, b, o.depth); + let back = fine(&art, |q| section(&[q], b, &o, 1.0).first().map_or(q, |q| camera.project(camera.place(*q, -o.depth / 2.0)))); + let far = farthest(&cap, &back); + assert!(far <= outline::CURVE_TOLERANCE + 1e-6, "{far}"); + + // Where a curve meets a straight edge at a corner, the bevel's miter moves the cap's corner off + // the curve's offset; the cap's curves still meet it. + let bevel = Extrude { bevel: Some(Bevel { inside: true, width: 4.0, height: 4.0, ..Bevel::default() }), ..Extrude::default() }; + for art in [art.clone(), letter_d()] { + let (p, b) = shape(&art); + let f = extrude(&p, FillRule::EvenOdd, b, bevel, front()).unwrap(); + let cap = f.iter().find(|f| f.depth == f64::MAX).unwrap(); + // An offset curve is no cubic: it may take several, but no edge of a curve stays straight. + let ([curves, segments, ..], [art_curves, art_segments, ..]) = (anatomy(&cap.path()), anatomy(&p)); + assert!(curves >= art_curves && segments - curves == art_segments - art_curves, "{:?}", cap.path()); + let far = farthest(&cap.path(), &cap.contours); + assert!(far <= 2.0 * 0.05, "{far}"); + } + + let mut flat = PathData::from_bezpath(&art); + if let Some(a) = flat.subpaths.first_mut().and_then(|sp| sp.anchors.first_mut()) { + a.h_out = a.p; + } + for p in [PathData::from_bezpath(&circle(Point::new(1.0, 1.0), 0.01)), flat] { + let b = p.bounds().unwrap(); + let f = extrude(&p, FillRule::NonZero, b, Extrude::default(), front()).unwrap(); + let cap = f[0].path(); + assert_eq!(anatomy(&cap)[0], anatomy(&p)[0], "{cap:?}"); + let far = farthest(&cap, &fine(&p.to_bezpath(), |q| q)); + assert!(far <= outline::CURVE_TOLERANCE, "{far}"); + } +} + #[test] fn the_inflate_membrane_matches_known_solutions() { // ∇²φ = −1, zero on the outline: a disc of radius r peaks at r²/4, a square of side l at @@ -321,11 +513,11 @@ fn the_inflate_membrane_matches_known_solutions() { c.extend(vectorcraft_geom::kurbo::Shape::path_elements(&vectorcraft_geom::kurbo::Circle::new((100.0, 100.0), 50.0), 0.01)); let (p, b) = shape(&c); let r = rings(&p, FillRule::EvenOdd, 100.0, MAX_SOLID_POINTS).unwrap(); - let disc = Membrane::solve(&r, &Edges::new(&r), b.origin(), b.width() / 48.0, 49, 49); + let disc = Membrane::solve(&r, &Edges::new(&r).unwrap(), b.origin(), b.width() / 48.0, 49, 49); assert!(close(disc.peak, 50.0 * 50.0 / 4.0, 625.0 * 0.02), "{}", disc.peak); let (p, b) = shape(&square(0.0, 0.0, 100.0)); let r = rings(&p, FillRule::EvenOdd, 100.0, MAX_SOLID_POINTS).unwrap(); - let sq = Membrane::solve(&r, &Edges::new(&r), b.origin(), 100.0 / 48.0, 49, 49); + let sq = Membrane::solve(&r, &Edges::new(&r).unwrap(), b.origin(), 100.0 / 48.0, 49, 49); assert!(close(sq.peak, 0.07367 * 100.0 * 100.0, 736.7 * 0.02), "{}", sq.peak); // Smooth across the middle: no crease where a distance-to-the-edge height would have one // (the diagonals). The second difference along a diagonal stays small and even. @@ -374,8 +566,7 @@ fn bumps(count: usize) -> (PathData, Rect) { } /// Curves are followed within a tolerance rather than by sixteen points each: small curves take a -/// few points, so shapes of many curves (outlined type) fit; Rotate, which only turns the outline, -/// takes far more. +/// few points, so shapes of many curves (outlined type) fit, in a solid and in Rotate. #[test] fn small_curves_take_few_points_and_rotate_takes_large_outlines() { // 300 curves were 4,800 points at sixteen each, over the old limit of 1,024. @@ -383,10 +574,13 @@ fn small_curves_take_few_points_and_rotate_takes_large_outlines() { assert!(extrude(&p, FillRule::EvenOdd, r, Extrude::default(), front()).is_ok()); assert!(inflate(&p, FillRule::EvenOdd, r, Inflate { volume: 20.0, ..Inflate::default() }, front()).is_ok()); assert!(plane(&p, FillRule::EvenOdd, r, front()).is_ok()); - // 4,000 curves: too many for a solid, not for Rotate. + // 4,000 curves fit a solid and Rotate alike; 70,000 fit neither. let (p, r) = bumps(4000); - assert!(extrude(&p, FillRule::EvenOdd, r, Extrude::default(), front()).unwrap_err().contains("too complex")); + assert!(extrude(&p, FillRule::EvenOdd, r, Extrude::default(), front()).is_ok()); assert_eq!(plane(&p, FillRule::EvenOdd, r, front()).unwrap().len(), 1); + let (p, r) = bumps(70_000); + assert_eq!(extrude(&p, FillRule::EvenOdd, r, Extrude::default(), front()).unwrap_err(), "The shape is too complex for a 3D effect"); + assert_eq!(plane(&p, FillRule::EvenOdd, r, front()).unwrap_err(), "The shape is too complex for a 3D effect"); // Each piece stays within the tolerance of the curve: a circle's chords sag at most 0.05 pt // here (1/2000 of its 100 pt size is less). let mut c = BezPath::new(); @@ -421,7 +615,7 @@ fn twisted_pieces_stay_within_the_facet_limit() { fn the_edge_index_finds_the_nearest_edge() { let (p, r) = bumps(200); let rings = rings(&p, FillRule::EvenOdd, r.width(), MAX_SOLID_POINTS).unwrap(); - let edges = Edges::new(&rings); + let edges = Edges::new(&rings).unwrap(); for k in 0..400 { let t = f64::from(k); let q = Point::new(-300.0 + (t * 37.0) % 1400.0, -50.0 + (t * 13.0) % 130.0); @@ -437,7 +631,7 @@ fn the_edge_index_looks_along_the_side_from_outside() { let ring = |b: BezPath| rings(&shape(&b).0, FillRule::EvenOdd, 64.0, MAX_SOLID_POINTS).unwrap().remove(0); // Straight ahead of the point, a little further up its side, and the far corner (a 64 pt grid). let rings = vec![ring(square(2.5, 0.0, 1.0)), ring(square(0.0, 4.2, 0.8)), ring(square(63.0, 63.0, 1.0))]; - let edges = Edges::new(&rings); + let edges = Edges::new(&rings).unwrap(); let q = Point::new(-10.0, 0.5); let (fast, slow) = (edges.distance(q), edge_distance(&rings, q)); assert!((fast - slow).abs() < 1e-9, "{fast} against {slow}"); @@ -1019,7 +1213,7 @@ fn flat_far_and_too_large_merges() { let squares: Vec<_> = (0..12).map(|i| rect(i as f64 * 20.0, 0.0, i as f64 * 20.0 + 10.0, 10.0)).collect(); let line = vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 300.0), Point::new(50.0, 300.0), Point::new(100.0, 300.0)], false); let with_line = PathData::new(squares.iter().cloned().chain([line]).collect()); - assert!(!rings::meets(&rings::sample(&with_line, 300.0, usize::MAX).unwrap(), &rings::closed_straight(&with_line))); + assert!(!rings::meets(&rings::sample(&with_line, 300.0, usize::MAX, rings::CURVE_PIECES).unwrap(), &rings::closed_straight(&with_line))); assert!(close(area(&plane(&with_line, FillRule::NonZero, with_line.bounds().unwrap(), front()).unwrap()), 1200.0, 1e-6)); // Far from the origin the boolean snaps wider than 1e-6 (1.4e-6 at 9.9e7), and so does the // test for meeting: squares 1.35e-6 apart there are one outline, one cap of both areas. @@ -1049,9 +1243,8 @@ fn flat_far_and_too_large_merges() { let b = wide.bounds().unwrap(); let joined = plane(&wide, FillRule::NonZero, b, front()).unwrap(); assert_eq!(joined.iter().map(|f| f.contours.len()).sum::(), 2, "the squares joined, the lobe apart"); - // 24 bars each way: 192 points as drawn, some 2,400 once every hole between them is traced: - // past Extrude's and Inflate's 2,048 the shape is too complex (its contours as drawn cross, so - // they can't be built as they are), and Rotate's 65,536 takes it. + // 24 bars each way: 192 points as drawn, some 2,400 once every hole between them is traced, + // within the 65,536 points Extrude & Bevel, Inflate and Rotate take. let mut bars = vec![]; for i in 0..24 { let x = i as f64 * 10.0; @@ -1061,9 +1254,18 @@ fn flat_far_and_too_large_merges() { let grid = PathData::new(bars); let b = grid.bounds().unwrap(); for rule in [FillRule::NonZero, FillRule::EvenOdd] { - assert_eq!(extrude(&grid, rule, b, Extrude::default(), front()).unwrap_err(), "The shape is too complex for a 3D effect", "{rule:?}"); - assert_eq!(inflate(&grid, rule, b, Inflate::default(), front()).unwrap_err(), "The shape is too complex for a 3D effect", "{rule:?}"); - assert!(close(area(&plane(&grid, rule, b, front()).unwrap()), vectorcraft_pathops::area(&grid, rule), 1e-6), "{rule:?}: Rotate"); + // With a limit of 2,048 points the grid fits as drawn and its merged outline does not: its + // contours as drawn cross, so they can't be built as they are. + assert!(rings::sample(&grid, 240.0, 2048, rings::CURVE_PIECES).is_ok()); + assert_eq!( + rings::solid_rings(&grid, rule, 240.0, 2048, rings::CURVE_PIECES), + Err("The shape is too complex for a 3D effect".into()), + "{rule:?}" + ); + let expected = vectorcraft_pathops::area(&grid, rule); + assert!(close(area(&extrude(&grid, rule, b, Extrude::default(), front()).unwrap()), expected, 1e-6), "{rule:?}: Extrude & Bevel"); + assert!(!inflate(&grid, rule, b, Inflate::default(), front()).unwrap().is_empty(), "{rule:?}: Inflate"); + assert!(close(area(&plane(&grid, rule, b, front()).unwrap()), expected, 1e-6), "{rule:?}: Rotate"); } } @@ -1076,7 +1278,7 @@ fn meets_within_twice_the_boolean_tolerance() { let rect = |x0: f64, y0: f64, x1: f64, y1: f64| { vectorcraft_geom::SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true) }; - let meets = |p: &PathData| rings::meets(&rings::sample(p, 300.0, usize::MAX).unwrap(), &rings::closed_straight(p)); + let meets = |p: &PathData| rings::meets(&rings::sample(p, 300.0, usize::MAX, rings::CURVE_PIECES).unwrap(), &rings::closed_straight(p)); // Two triangles whose facing 45° edges are 1.4e-6 apart, the second's corners 0.99e-6 lower on // the page (greater y) than the first's: snapped onto the first's heights, they are joined. let d = 0.99e-6; @@ -1159,7 +1361,7 @@ fn meets_within_twice_the_boolean_tolerance() { fn the_merged_rings_are_turned_as_a_whole() { let outline = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; let hole = vec![Point::new(2.0, 2.0), Point::new(2.0, 8.0), Point::new(8.0, 8.0), Point::new(8.0, 2.0)]; - let turned = rings::wound(vec![outline.iter().rev().copied().collect(), hole.iter().rev().copied().collect()]); + let turned = rings::wound::>(vec![outline.iter().rev().copied().collect(), hole.iter().rev().copied().collect()]); assert!(rings::signed_area(&turned[0]) > 0.0 && rings::signed_area(&turned[1]) < 0.0); let kept = rings::wound(vec![outline.clone(), hole.clone()]); assert_eq!(kept, vec![outline, hole]); diff --git a/crates/three-d/src/solid/tests_limits.rs b/crates/three-d/src/solid/tests_limits.rs new file mode 100644 index 0000000000..bd70096232 --- /dev/null +++ b/crates/three-d/src/solid/tests_limits.rs @@ -0,0 +1,197 @@ +use vectorcraft_geom::{Anchor, SubPath}; + +use super::*; + +const SHAPE: &str = "The shape is too complex for a 3D effect"; +const SURFACE: &str = "The 3D surface is too complex; simplify the shape"; + +/// A closed ring of `count` curved petals around a circle of `radius`: each curve leaves its anchor +/// outward, `lift` points out, and comes back to the next anchor, so a larger lift asks for more +/// pieces per curve. +fn petals(count: usize, radius: f64, lift: f64) -> PathData { + let chord = std::f64::consts::TAU * radius / count as f64; + let anchors = (0..count) + .map(|i| { + let (s, c) = (std::f64::consts::TAU * i as f64 / count as f64).sin_cos(); + let p = Point::new(radius * 2.0 + radius * c, radius * 2.0 + radius * s); + let (out, along) = (Vec2::new(c, s) * lift, Vec2::new(-s, c) * (chord / 3.0)); + Anchor::with_handles(p, p + out - along, p + out + along) + }) + .collect(); + PathData::new(vec![SubPath::new(anchors, true)]) +} + +/// A closed polygon of `count` straight edges around a circle. +fn polygon(count: usize, radius: f64) -> PathData { + let anchors = (0..count) + .map(|i| { + let (s, c) = (std::f64::consts::TAU * i as f64 / count as f64).sin_cos(); + Anchor::corner(Point::new(radius * 2.0 + radius * c, radius * 2.0 + radius * s)) + }) + .collect(); + PathData::new(vec![SubPath::new(anchors, true)]) +} + +/// Turned so that the walls and bevels show. +fn turned() -> View { + View { rotation_x: -18.0, rotation_y: -26.0, rotation_z: 8.0, ..View::default() } +} + +fn size(path: &PathData) -> f64 { + let b = path.bounds().unwrap(); + b.width().max(b.height()) +} + +/// How many points the outline samples to, each curve in at most `most` pieces. +fn points(path: &PathData, most: u32) -> usize { + rings::sample(path, size(path), usize::MAX, most).unwrap().iter().map(Vec::len).sum() +} + +fn built(facets: &[Facet]) -> bool { + !facets.is_empty() + && facets.len() <= MAX_SOLID_FACES + && facets.iter().flat_map(|f| f.contours.iter().flatten()).all(|p| p.x.is_finite() && p.y.is_finite()) +} + +#[test] +fn two_thousand_curves_extrude_with_a_bevel_and_inflate() { + let path = petals(2000, 500.0, 4.0); + let b = path.bounds().unwrap(); + // Every curve takes several pieces: far more points than 2,048, all of them kept. + let sampled = points(&path, rings::CURVE_PIECES); + assert!(sampled >= 3 * 2000, "{sampled}"); + assert_eq!(rings::curve_pieces(&path, size(&path), 2, 2), Ok(rings::CURVE_PIECES)); + let bevel = Extrude { bevel: Some(Bevel::default()), ..Extrude::default() }; + let extruded = extrude(&path, FillRule::NonZero, b, bevel, turned()).unwrap(); + assert!(built(&extruded) && extruded.len() > sampled, "{}", extruded.len()); + let inflated = inflate(&path, FillRule::NonZero, b, Inflate::default(), turned()).unwrap(); + assert!(built(&inflated), "{}", inflated.len()); +} + +#[test] +fn an_outline_at_the_point_limit_is_taken_and_one_past_it_is_refused_before_sampling() { + let at = polygon(MAX_SOLID_POINTS, 20_000.0); + assert_eq!(rings::curve_pieces(&at, size(&at), 1, 2), Ok(rings::CURVE_PIECES)); + assert!(built(&extrude(&at, FillRule::NonZero, at.bounds().unwrap(), Extrude::default(), turned()).unwrap())); + let past = polygon(MAX_SOLID_POINTS + 1, 20_000.0); + assert_eq!(rings::curve_pieces(&past, size(&past), 1, 2), Err(SHAPE.to_string())); + assert_eq!(extrude(&past, FillRule::NonZero, past.bounds().unwrap(), Extrude::default(), turned()), Err(SHAPE.to_string())); + assert_eq!(inflate(&past, FillRule::NonZero, past.bounds().unwrap(), Inflate::default(), turned()), Err(SHAPE.to_string())); +} + +#[test] +fn faces_at_the_limit_are_taken_and_one_past_it_is_refused_before_sampling() { + // 40,960 straight edges in four bands are exactly the face limit. + let path = polygon(MAX_SOLID_FACES / 4, 20_000.0); + assert_eq!(rings::curve_pieces(&path, size(&path), 4, 0), Ok(rings::CURVE_PIECES)); + assert_eq!(rings::curve_pieces(&path, size(&path), 4, 1), Err(SURFACE.to_string())); + // A rounded bevel gives 20,000 edges nine bands each, past the limit. + let path = polygon(20_000, 20_000.0); + let rounded = Extrude { bevel: Some(Bevel { shape: BevelShape::Rounded, ..Bevel::default() }), ..Extrude::default() }; + assert_eq!(extrude(&path, FillRule::NonZero, path.bounds().unwrap(), rounded, turned()), Err(SURFACE.to_string())); +} + +#[test] +fn curves_over_the_budget_take_fewer_pieces_down_to_four() { + let path = petals(2000, 500.0, 20.0); + let s = size(&path); + assert_eq!(points(&path, rings::CURVE_PIECES), 6 * 2000, "six pieces a curve within the tolerance"); + // 16 faces an edge: 12,000 points are too many, 10,000 at five pieces a curve fit. + assert_eq!(rings::curve_pieces(&path, s, 16, 0), Ok(5)); + assert_eq!(points(&path, 5), 5 * 2000); + // At four pieces a curve, 21 faces an edge are still too many. + assert_eq!(rings::curve_pieces(&path, s, 21, 0), Err(SURFACE.to_string())); + // Twisted 96°, the walls are 16 slices: built with five pieces a curve. + let b = path.bounds().unwrap(); + let twisted = extrude(&path, FillRule::NonZero, b, Extrude { twist: 96.0, hidden: true, ..Extrude::default() }, turned()).unwrap(); + assert!(built(&twisted) && twisted.len() > MAX_FACES, "{}", twisted.len()); + // Twisted 360°, 60 slices are too many even at four pieces a curve. + assert_eq!(extrude(&path, FillRule::NonZero, b, Extrude { twist: 360.0, ..Extrude::default() }, turned()), Err(SURFACE.to_string())); +} + +#[test] +fn five_and_ten_thousand_curves_build_at_the_defaults() { + let five = petals(5000, 1250.0, 2.0); + assert!(built(&inflate(&five, FillRule::NonZero, five.bounds().unwrap(), Inflate::default(), turned()).unwrap())); + assert!(built(&extrude(&five, FillRule::NonZero, five.bounds().unwrap(), Extrude::default(), turned()).unwrap())); + let ten = petals(10_000, 2500.0, 4.0); + let b = ten.bounds().unwrap(); + assert!(points(&ten, rings::CURVE_PIECES) > 10_000); + assert!(built(&extrude(&ten, FillRule::NonZero, b, Extrude::default(), turned()).unwrap())); + let deep = Extrude { twist: 360.0, bevel: Some(Bevel { shape: BevelShape::Rounded, repeat: 4, ..Bevel::default() }), ..Extrude::default() }; + assert_eq!(extrude(&ten, FillRule::NonZero, b, deep, turned()), Err(SURFACE.to_string())); +} + +#[test] +fn many_empty_contours_and_invalid_handles_are_refused_before_sampling() { + // Contours of one anchor and of none draw nothing, yet each is counted. + let lone = |i: usize| SubPath::new(if i.is_multiple_of(2) { vec![] } else { vec![Anchor::corner(Point::new(1.0, i as f64))] }, false); + let square = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true); + let at = PathData::new((0..MAX_SOLID_POINTS - 1).map(lone).chain([square.clone()]).collect()); + assert_eq!(rings::curve_pieces(&at, 10.0, 1, 2), Ok(rings::CURVE_PIECES)); + let past = PathData::new((0..MAX_SOLID_POINTS).map(lone).chain([square.clone()]).collect()); + assert_eq!(rings::curve_pieces(&past, 10.0, 1, 2), Err(SHAPE.to_string())); + let b = Rect::new(0.0, 0.0, 10.0, 10.0); + assert_eq!(extrude(&past, FillRule::NonZero, b, Extrude::default(), turned()), Err(SHAPE.to_string())); + let mut bad = square; + bad.anchors[1].h_out = Point::new(f64::NAN, 0.0); + let bad = PathData::new(vec![bad]); + assert_eq!(rings::curve_pieces(&bad, 10.0, 1, 2), Err("The shape contains invalid coordinates".to_string())); + assert_eq!(inflate(&bad, FillRule::NonZero, b, Inflate::default(), turned()), Err("The shape contains invalid coordinates".to_string())); +} + +/// A comb of `teeth` teeth, 100 wide and 100 tall, on a strip along its foot: its outline +/// crosses every cell of the grid Inflate fills. +fn comb(teeth: usize) -> PathData { + let w = 100.0 / teeth as f64; + let mut points: Vec = (0..teeth) + .flat_map(|k| { + let x = k as f64 * w; + [Point::new(x, 0.0), Point::new(x, 100.0), Point::new(x + w / 2.0, 100.0), Point::new(x + w / 2.0, 0.0)] + }) + .collect(); + points.extend([Point::new(100.0, -1.0), Point::new(0.0, -1.0)]); + PathData::new(vec![SubPath::polyline(&points, true)]) +} + +/// Inflate `path` with the grid work its edge index may take set to `budget`. +fn inflated_within(path: &PathData, budget: usize) -> Result, String> { + GRID_BUDGET.with(|b| b.set(budget)); + let out = inflate(path, FillRule::NonZero, path.bounds().unwrap(), Inflate::default(), turned()); + GRID_BUDGET.with(|b| b.set(MAX_GRID_WORK)); + out +} + +#[test] +fn inflate_at_its_grid_work_budget_builds_and_one_past_it_is_refused() { + let path = comb(200); + assert!(built(&inflated_within(&path, MAX_GRID_WORK).unwrap())); + let work = GRID_WORK.with(std::cell::Cell::get); + assert!(work > 0); + assert!(built(&inflated_within(&path, work).unwrap())); + assert_eq!(GRID_WORK.with(std::cell::Cell::get), work, "the same work at its budget"); + assert_eq!(inflated_within(&path, work - 1), Err(SURFACE.to_string())); +} + +#[test] +fn the_edge_index_at_its_entry_limit_is_built_and_one_past_it_is_refused() { + // A diagonal across the whole grid of 64 by 64 buckets is filed in every bucket, each way. + let diagonal = vec![Point::new(0.0, 0.0), Point::new(64.0, 64.0)]; + assert_eq!(MAX_EDGE_ENTRIES, 2048 * 2 * 64 * 64); + let mut rings = vec![diagonal; 2048]; + assert!(Edges::new(&rings).is_ok_and(|e| e.work() == MAX_EDGE_ENTRIES)); + // A small triangle in one bucket: three entries more. + rings.push(vec![Point::new(0.0, 0.0), Point::new(0.5, 0.0), Point::new(0.0, 0.5)]); + assert_eq!(Edges::new(&rings).err(), Some(SURFACE.to_string())); +} + +#[test] +fn a_comb_that_crosses_every_cell_is_refused_once_its_grid_work_is_spent() { + // Two thousand curves take a small share of the budget. + let curves = petals(2000, 500.0, 4.0); + assert!(built(&inflate(&curves, FillRule::NonZero, curves.bounds().unwrap(), Inflate::default(), turned()).unwrap())); + assert!(GRID_WORK.with(std::cell::Cell::get) < MAX_GRID_WORK / 16); + // 16,002 points, each clipped in every cell its ring meets. + let path = comb(4000); + assert_eq!(inflate(&path, FillRule::NonZero, path.bounds().unwrap(), Inflate::default(), turned()), Err(SURFACE.to_string())); +} diff --git a/crates/three-d/src/tests.rs b/crates/three-d/src/tests.rs index e2b6985fbc..1b0ffa3ffc 100644 --- a/crates/three-d/src/tests.rs +++ b/crates/three-d/src/tests.rs @@ -4,6 +4,7 @@ mod caps; mod classic; mod lighting; mod multiple_lights; +mod profile_limits; mod smooth; #[test] diff --git a/crates/three-d/src/tests/caps.rs b/crates/three-d/src/tests/caps.rs index 32fc5ac0b3..cae43f4a5a 100644 --- a/crates/three-d/src/tests/caps.rs +++ b/crates/three-d/src/tests/caps.rs @@ -93,14 +93,14 @@ fn caps_share_surface_limits_and_malformed_inputs_stay_bounded() { assert!(faces.len() <= 384); let mut excessive = BezPath::new(); excessive.move_to((40.0, 0.0)); - for i in 1..=1024 { + for i in 1..=MAX_PROFILE_POINTS { excessive.line_to((40.0, i as f64)); } - assert!(revolve(&PathData::from_bezpath(&excessive), Rect::new(0.0, 0.0, 40.0, 1024.0), options()).is_err()); + assert!(revolve(&PathData::from_bezpath(&excessive), Rect::new(0.0, 0.0, 40.0, MAX_PROFILE_POINTS as f64), options()).is_err()); assert!(revolve(&PathData::default(), bounds, options()).unwrap().is_empty()); // Viewed along the axis, the side walls disappear but the caps still consume // the same face budget. Repeated rings cannot bypass it through degenerate walls. - let repeated = PathData::new(vec![path.subpaths[0].clone(); 129]); + let repeated = PathData::new(vec![path.subpaths[0].clone(); 1025]); let o = Revolve { segments: 128, ..options() }; assert!(revolve(&repeated, bounds, Revolve { cap_ends: false, ..o }).unwrap().is_empty()); assert!(revolve(&repeated, bounds, o).unwrap_err().contains("surface is too complex")); diff --git a/crates/three-d/src/tests/profile_limits.rs b/crates/three-d/src/tests/profile_limits.rs new file mode 100644 index 0000000000..148cf4fccc --- /dev/null +++ b/crates/three-d/src/tests/profile_limits.rs @@ -0,0 +1,150 @@ +use crate::*; +use vectorcraft_geom::{Anchor, SubPath}; + +/// A closed star of `points` tips: twice as many straight edges. +fn star(points: usize) -> PathData { + let anchors = (0..points * 2) + .map(|i| { + let (s, c) = (i as f64 * std::f64::consts::PI / points as f64).sin_cos(); + let r = if i % 2 == 0 { 100.0 } else { 60.0 }; + Anchor::corner(Point::new(200.0 + r * c, 200.0 + r * s)) + }) + .collect(); + PathData::new(vec![SubPath::new(anchors, true)]) +} + +/// An open wave of `anchors` smooth anchors: one curved segment between each two. +fn wave(anchors: usize) -> PathData { + let anchors = (0..anchors) + .map(|i| { + let p = Point::new(100.0 + if i % 2 == 0 { 0.0 } else { 20.0 }, i as f64); + Anchor::smooth(p, p + Vec2::new(6.0, 0.3)) + }) + .collect(); + PathData::new(vec![SubPath::new(anchors, false)]) +} + +fn revolved(path: &PathData, options: Revolve) -> Result, String> { + revolve(path, path.bounds().unwrap(), options) +} + +#[test] +fn a_star_of_600_points_revolves_at_the_default_segments() { + let faces = revolved(&star(600), Revolve::default()).unwrap(); + // The tip on the axis gives two edges with a side of no length. + assert!((1198 * 64 * 2..=1200 * 64 * 2).contains(&faces.len()), "{}", faces.len()); + let refused = revolved(&star(600), Revolve { segments: 128, ..Revolve::default() }).unwrap_err(); + assert!(refused.contains("reduce Segments"), "{refused}"); +} + +#[test] +fn a_curved_profile_past_the_old_limit_takes_fewer_samples_for_each_curve() { + let wave = wave(200); + assert!(revolved(&wave, Revolve::default()).is_ok()); + let samples = revolve_curve_samples([&wave], Revolve::default()).unwrap(); + assert!((MIN_CURVE_SAMPLES..CURVE_SAMPLES).contains(&samples), "{samples}"); +} + +#[test] +fn a_profile_within_the_limits_keeps_every_sample() { + assert_eq!(revolve_curve_samples([&wave(50)], Revolve::default()), Ok(CURVE_SAMPLES)); + assert_eq!(revolve_curve_samples([&star(5)], Revolve::default()), Ok(CURVE_SAMPLES)); +} + +#[test] +fn two_thousand_curves_fit_at_low_segments_and_are_refused_before_any_face_at_high() { + let wave = wave(2001); + let samples = revolve_curve_samples([&wave], Revolve { segments: 8, ..Revolve::default() }).unwrap(); + assert!((MIN_CURVE_SAMPLES..CURVE_SAMPLES).contains(&samples), "{samples}"); + assert!(revolved(&wave, Revolve { segments: 8, ..Revolve::default() }).is_ok()); + let refused = revolve_curve_samples([&wave], Revolve { segments: 128, ..Revolve::default() }).unwrap_err(); + assert!(refused.contains("reduce Segments"), "{refused}"); + assert_eq!(revolved(&wave, Revolve { segments: 128, ..Revolve::default() }), Err(refused)); +} + +#[test] +fn too_many_anchors_are_refused_as_a_profile() { + let refused = revolve_curve_samples([&wave(MAX_PROFILE_POINTS + 1)], Revolve { segments: 8, ..Revolve::default() }).unwrap_err(); + assert_eq!(refused, TOO_COMPLEX_PROFILE); +} + +#[test] +fn every_contour_takes_a_point_even_an_empty_one() { + // Contours of one anchor and of none, with no segment between them. + let lone = |i: usize| SubPath::new(if i.is_multiple_of(2) { vec![] } else { vec![Anchor::corner(Point::new(100.0, i as f64))] }, false); + let path = PathData::new((0..=MAX_PROFILE_POINTS).map(lone).collect()); + assert_eq!(revolve_curve_samples([&path], Revolve::default()), Err(TOO_COMPLEX_PROFILE.to_string())); + assert_eq!(hole_segments(&path, FillRule::NonZero), Err(TOO_COMPLEX_PROFILE.to_string()), "before any contour is built"); + let given = Revolve { curve_samples: Some(CURVE_SAMPLES), ..Revolve::default() }; + assert_eq!(revolve_mesh(&path, FillRule::NonZero, path.bounds().unwrap(), given).map(|_| ()), Err(TOO_COMPLEX_PROFILE.to_string())); +} + +#[test] +fn a_profile_at_the_point_limit_is_taken_and_one_past_it_is_refused() { + let straight = |anchors: usize| { + let anchors = (0..anchors).map(|i| Anchor::corner(Point::new(100.0 + (i % 2) as f64, i as f64))).collect(); + PathData::new(vec![SubPath::new(anchors, false)]) + }; + let narrow = Revolve { angle: 1.0, cap_ends: false, segments: 8, ..Revolve::default() }; + assert_eq!(revolve_curve_samples([&straight(MAX_PROFILE_POINTS)], narrow), Ok(CURVE_SAMPLES)); + assert_eq!(revolve_curve_samples([&straight(MAX_PROFILE_POINTS + 1)], narrow), Err(TOO_COMPLEX_PROFILE.to_string())); +} + +#[test] +fn the_profiles_of_one_object_share_one_budget() { + let (one, other) = (star(600), star(600)); + let o = Revolve::default(); + assert!(revolve_curve_samples([&one], o).is_ok()); + assert!(revolve_curve_samples([&other], o).is_ok()); + let refused = revolve_curve_samples([&one, &other], o).unwrap_err(); + assert!(refused.contains("reduce Segments"), "{refused}"); + // Contours of one profile count together as well. + let both = PathData::new(one.subpaths.iter().chain(&other.subpaths).cloned().collect()); + assert_eq!(revolve_curve_samples([&both], o), Err(refused)); +} + +#[test] +fn deeply_nested_contours_stop_the_search_for_holes() { + // Concentric triangles: each tests every contour outside it. + let triangle = |r: f64| { + let anchors = [(0.0, -r), (r, r), (-r, r)].iter().map(|(x, y)| Anchor::corner(Point::new(200_000.0 + x, 200_000.0 + y))).collect(); + SubPath::new(anchors, true) + }; + let nested = PathData::new((1..=4000).map(|i| triangle(i as f64)).collect()); + assert_eq!(hole_segments(&nested, FillRule::NonZero), Err(TOO_COMPLEX_PROFILE.to_string())); + let few = PathData::new((1..=4).map(|i| triangle(i as f64)).collect()); + assert_eq!(hole_segments(&few, FillRule::EvenOdd).map(|h| h.len()), Ok(4)); +} + +#[test] +fn a_point_is_tested_only_against_the_contours_near_it() { + // 3,000 separate squares: each segment's middle lies in the bounds of its own square only. + let squares = (0..3000) + .map(|i| { + let (x, y) = ((i % 60) as f64 * 20.0, (i / 60) as f64 * 20.0); + let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)]; + SubPath::new(corners.iter().map(|(x, y)| Anchor::corner(Point::new(*x, *y))).collect(), true) + }) + .collect(); + let (holes, work) = hole_segments_counted(&PathData::new(squares), FillRule::NonZero).unwrap(); + assert!(holes.iter().flatten().all(|hole| !hole)); + assert!(work < 200_000, "{work}"); +} + +#[test] +fn overlapping_contours_are_holes_only_where_they_overlap() { + let square = |x: f64, y: f64, side: f64| { + let corners = [(x, y), (x + side, y), (x + side, y + side), (x, y + side)]; + SubPath::new(corners.iter().map(|(x, y)| Anchor::corner(Point::new(*x, *y))).collect(), true) + }; + let overlapping = PathData::new(vec![square(0.0, 0.0, 100.0), square(40.0, 40.0, 100.0)]); + let expected = vec![vec![false, true, true, false], vec![true, false, false, true]]; + assert_eq!(hole_segments(&overlapping, FillRule::EvenOdd), Ok(expected)); +} + +#[test] +fn given_samples_are_used_for_each_curve() { + let wave = wave(4); + let at = |samples| revolved(&wave, Revolve { curve_samples: Some(samples), cap_ends: false, segments: 8, ..Revolve::default() }).unwrap().len(); + assert_eq!(at(4) * 2, at(8)); +} diff --git a/crates/three-d/src/tests/smooth.rs b/crates/three-d/src/tests/smooth.rs index c651723262..085255ecbc 100644 --- a/crates/three-d/src/tests/smooth.rs +++ b/crates/three-d/src/tests/smooth.rs @@ -118,6 +118,6 @@ fn unshaded_legacy_degenerate_and_high_complexity_surfaces_stay_bounded() { } assert!(revolve(&p, b, Revolve { smooth_shading: true, angle: 0.0, ..o }).unwrap().is_empty()); let mut p = path("M40 0"); - p.subpaths[0].anchors.extend((1..400).map(|i| vectorcraft_geom::Anchor::corner(Point::new(40.0 + (i % 2) as f64, i as f64)))); + p.subpaths[0].anchors.extend((1..1100).map(|i| vectorcraft_geom::Anchor::corner(Point::new(40.0 + (i % 2) as f64, i as f64)))); assert!(revolve(&p, p.bounds().unwrap(), Revolve { smooth_shading: true, segments: 128, offset: 30.0, ..o }).is_err()); } diff --git a/crates/tools/src/addons/measure_inspect.rs b/crates/tools/src/addons/measure_inspect.rs index 1ea8a9324d..b7cb13a6e1 100644 --- a/crates/tools/src/addons/measure_inspect.rs +++ b/crates/tools/src/addons/measure_inspect.rs @@ -11,6 +11,7 @@ use vectorcraft_doc::{NodeId, Unit}; use vectorcraft_geom::{Point, Vec2}; use vectorcraft_pathops::addons::pathtools::{Inspection, inspect}; +use crate::guides::DrawSnap; use crate::xform::measure; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -27,6 +28,8 @@ pub struct MeasureInspectTool { before: Option<(Point, Point)>, /// The path under the pointer and what it reads there. hover: Option<(NodeId, Inspection)>, + /// Snapping for both ends of a measurement. + snap: DrawSnap, } /// An area of `pt2` square points in `unit` (`12.5 mm²`). @@ -87,7 +90,7 @@ impl Tool for MeasureInspectTool { match ev.kind { PointerKind::Move => self.hover = Self::inspect_at(cx, ev.pos), PointerKind::Down => { - let (p, _) = crate::guides::snap_draw(cx, ev.pos, &[]); + let p = self.snap.measure(cx, ev.pos, None); self.before = self.line; self.line = Some((p, p)); self.dragging = true; @@ -95,7 +98,7 @@ impl Tool for MeasureInspectTool { } PointerKind::Drag | PointerKind::Up if self.dragging => { if let Some((a, _)) = self.line { - self.line = Some((a, crate::xform::measure_end_point(cx, a, ev.pos, ev.mods.shift))); + self.line = Some((a, crate::xform::measure_end_point(cx, &mut self.snap, a, ev.pos, ev.mods.shift))); } self.dragging = ev.kind == PointerKind::Drag; } @@ -138,6 +141,7 @@ impl Tool for MeasureInspectTool { out.push(Overlay::Anchor { p: at, color: ORANGE, filled: i.anchor.is_some(), size: 6.0 }); out.push(Overlay::Measure { p: at + off, text: readout(cx, i) }); } + out.extend(self.snap.guides().iter().filter(|_| self.dragging).cloned()); out } @@ -161,7 +165,8 @@ impl Tool for MeasureInspectTool { mod tests { use super::*; use crate::testutil::*; - use vectorcraft_doc::Selection; + use vectorcraft_doc::{CharStyle, Document, Node, NodeKind, Selection, TextObject}; + use vectorcraft_text::{FontDb, layout as layout_text}; #[test] fn a_drag_measures_and_hovering_a_path_reads_it() { @@ -227,4 +232,55 @@ mod tests { assert!((o["distance"].as_f64().unwrap() - 36.0).abs() < 1e-9, "on the 9 pt grid: {o}"); assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "kept horizontal: {o}"); } + + /// With Snap to Glyph on, both ends and a Shift-drag's end land on the guides of live type. + #[test] + fn its_ends_land_on_glyph_guides_with_snap_to_glyph() { + let mut d = Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let text = TextObject::point(Point::new(100.0, 300.0), "Hg", CharStyle { size: 60.0, ..Default::default() }); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(text.clone())))).unwrap(); + let lay = layout_text(FontDb::global(), &text); + let base = (text.xf * lay.line_xf * Point::new(lay.lines[0].x0, lay.lines[0].baseline)).y; + let (s, p) = (Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let run = |c: &ToolContext, from: Point, to: Point, shift: bool| { + let mods = Mods { shift, ..Mods::default() }; + let mut t = MeasureInspectTool::default(); + t.pointer(c, &PointerEvent::new(PointerKind::Down, from.x, from.y)); + t.pointer(c, &PointerEvent::new(PointerKind::Up, to.x, to.y).with_mods(mods)); + let o = t.options(); + let a = Point::new(o["x"].as_f64().unwrap(), o["y"].as_f64().unwrap()); + (a, a + Vec2::new(o["dx"].as_f64().unwrap(), o["dy"].as_f64().unwrap())) + }; + let (from, to) = (Point::new(400.0, base + 2.0), Point::new(450.0, base - 40.0)); + assert_eq!(run(&on, from, to, false).0, Point::new(400.0, base)); + let (from, to) = (Point::new(300.0, base - 100.0), Point::new(401.0, base + 1.0)); + let landed = run(&on, from, to, true).1; + assert!(landed.distance(Point::new(400.0, base)) < 1e-9, "{landed:?}"); + let off = ToolContext { snap_to_glyph: false, ..on }; + let stayed = run(&off, from, to, true).1; + assert!(stayed.distance(to) < 1e-9, "{stayed:?}"); + } + + /// The guide an end lands on shows while the drag lasts. + #[test] + fn a_drag_shows_the_glyph_guide_it_lands_on() { + let mut d = Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let text = TextObject::point(Point::new(100.0, 300.0), "Hg", CharStyle { size: 60.0, ..Default::default() }); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(text.clone())))).unwrap(); + let lay = layout_text(FontDb::global(), &text); + let base = (text.xf * lay.line_xf * Point::new(lay.lines[0].x0, lay.lines[0].baseline)).y; + let (s, p) = (Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let mut t = MeasureInspectTool::default(); + t.pointer(&on, &PointerEvent::new(PointerKind::Down, 400.0, 50.0)); + let (drag, up) = (PointerKind::Drag, PointerKind::Up); + let count = |t: &MeasureInspectTool| t.overlays(&on).iter().filter(|o| !matches!(o, Overlay::Measure { .. })).count(); + t.pointer(&on, &PointerEvent::new(drag, 450.0, base + 2.0)); + assert!(count(&t) > 1, "the measured line and the guide"); + t.pointer(&on, &PointerEvent::new(up, 450.0, base + 2.0)); + assert_eq!(count(&t), 1, "the measured line alone"); + } } diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index 90c73620a1..4ee448830d 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -547,6 +547,11 @@ impl Tool for SmartPenTool { key == ToolKey::Tab && (self.press.is_some() || self.active(cx).is_some()) } + /// A path being drawn: Escape ends it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.path.is_some() + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.stop(); self.marquee = None; diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 054db258d4..741e962290 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -178,6 +178,10 @@ pub struct ToolContext<'a> { pub raster_sample: u32, /// General → Use Preview Bounds: the bounding box measures visual bounds (strokes included). pub preview_bounds: bool, + /// Type › Measure Type by Glyph Bounds: the bounding box measures each point type object + /// selected as an object (not inside a selected group) by the ink of its glyphs + /// ([`vectorcraft_effects::preview::Measure`]). + pub glyph_bounds: bool, /// The session's memo of the selection tools' measurements for the document as it is /// ([`select::PreviewMemo`]); without one they measure on every call. pub preview_memo: Option<&'a select::PreviewMemo>, @@ -284,6 +288,11 @@ pub struct ToolContext<'a> { } impl ToolContext<'_> { + /// How the bounding box measures the selection: [`Self::preview_bounds`] and + /// [`Self::glyph_bounds`]. + pub fn bounds_measure(&self) -> vectorcraft_effects::preview::Measure { + vectorcraft_effects::preview::Measure { preview: self.preview_bounds, glyphs: self.glyph_bounds } + } /// Tolerance in document units for `px` screen pixels. pub fn tol(&self, px: f64) -> f64 { px / self.zoom.max(1e-9) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 44bbbf44b2..53fbd3f3f5 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -67,8 +67,13 @@ pub struct DimensionTool { snap: crate::guides::DrawSnap, /// Where the next Linear pick lands, as last worked out for the pointer (for the overlays). snapped: Option<(Point, Option)>, + /// Whether the press under way began on an anchor a Linear click picks. + press_on_anchor: bool, } +/// How near an anchor (screen pixels) a pick snaps to it. +const ANCHOR_REACH: f64 = 8.0; + /// `at` as a Shift click picks it: the direction from `last` snapped to 45° steps (from the /// constrain angle), the distance kept. fn constrained(cx: &ToolContext, last: Point, at: Point) -> Point { @@ -119,10 +124,45 @@ fn anchor_near(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<(usize, [edge.segment, next] .into_iter() .filter_map(|i| Some((i, sp.anchors.get(i)?.p))) - .filter(|(_, a)| a.distance(p) <= cx.tol(8.0)) + .filter(|(_, a)| a.distance(p) <= cx.tol(ANCHOR_REACH)) .min_by(|(_, a), (_, b)| a.distance(p).total_cmp(&b.distance(p))) } +/// The anchor nearest `p` within reach, on any editable path (the topmost on a tie), as a link to +/// its path. Bounded work, and dimension artwork is skipped, as in [`pick`]. +fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> { + type Best = Option<(f64, Point, PointRef)>; + fn visit(n: &Node, p: Point, reach: f64, budget: &mut usize, best: &mut Best) { + if *budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() { + return; + } + if let Some(path) = n.path_data() { + for (subpath, sp) in path.subpaths.iter().enumerate() { + for (anchor, a) in sp.anchors.iter().enumerate() { + if *budget == 0 { + return; + } + *budget -= 1; + let d = a.p.distance(p); + if d <= reach && best.as_ref().is_none_or(|(nearest, ..)| d < *nearest) { + *best = Some((d, a.p, PointRef { node: n.id, subpath, anchor })); + } + } + } + } + if let Some(ch) = n.children() { + for c in ch.iter().rev() { + visit(c, p, reach, budget, best); + } + } + } + let (reach, mut budget, mut best) = (cx.tol(ANCHOR_REACH), 20_000usize, None); + for n in cx.doc.layers.iter().rev() { + visit(n, p, reach, &mut budget, &mut best); + } + best.map(|(_, at, r)| (at, r)) +} + /// The point of `edge` closest to `p`. fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { use vectorcraft_geom::kurbo::ParamCurveNearest; @@ -138,25 +178,22 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { } impl DimensionTool { - /// Where a Linear pick at `p` lands: on an anchor of the line under the pointer, within reach - /// (kept as a link to its path); else where Smart Guides put it (another object's anchor or - /// centre, in line with one, or for the second point on a construction guide through the - /// first), its guides showing; else on the closest point of that line; else `p` itself. + /// Where a Linear pick at `p` lands: on the nearest anchor of any path, within reach (kept as + /// a link to its path); else where Smart Guides put it (another object's anchor or centre, in + /// line with one, or for the second point on a construction guide through the first), its + /// guides showing; else on the closest point of the line under the pointer; else `p` itself. fn snap_linear(&mut self, cx: &ToolContext, p: Point) -> (Point, Option) { let leave = self.points.last().map(|(first, _)| crate::guides::Leave::segment(cx, *first, false)); let guided = self.snap.hover(cx, p, &[], leave.as_ref()); - let edge = pick(cx, p); - if let Some(edge) = &edge - && let Some((anchor, point)) = anchor_near(cx, edge, p) - { + if let Some((point, reference)) = anchor_under(cx, p) { self.snap.clear(); - return (point, Some(PointRef { node: edge.node, subpath: edge.subpath, anchor })); + return (point, Some(reference)); } if guided.distance(p) > 1e-9 { return (guided, None); } // Not on an anchor or a guide: snap to the closest point of the line (#2432). - (edge.and_then(|e| nearest_on(cx, &e, p)).unwrap_or(p), None) + (pick(cx, p).and_then(|e| nearest_on(cx, &e, p)).unwrap_or(p), None) } fn target(&self, cx: &ToolContext, p: Point) -> Option { let edge = pick(cx, p)?; @@ -243,6 +280,7 @@ impl DimensionTool { fn reset(&mut self) { self.pending = None; self.press = None; + self.press_on_anchor = false; self.points.clear(); self.lines.clear(); self.dragging = false; @@ -355,6 +393,10 @@ impl Tool for DimensionTool { self.press = Some((ev.pos, None)); return self.preview(cx, ev.pos); } + // A Linear press on an anchor picks the anchor unless it drags past the anchor's + // reach: moving a few pixels before the release does not drag out the dimension of + // a segment under the pointer. + self.press_on_anchor = self.kind == Kind::Linear && anchor_under(cx, ev.pos).is_some(); self.press = Some((ev.pos, self.target(cx, ev.pos))); vec![] } @@ -364,7 +406,7 @@ impl Tool for DimensionTool { } if self.pending.is_none() && let Some((start, Some(target))) = self.press.clone() - && start.distance(ev.pos) > cx.tol(3.0) + && start.distance(ev.pos) > cx.tol(if self.press_on_anchor { ANCHOR_REACH } else { 3.0 }) && self.points.is_empty() && self.lines.is_empty() { @@ -543,6 +585,76 @@ mod tests { assert!(matches!(placed.last(), Some(Action::Commit)), "{placed:?}"); } + /// A Linear press on an anchor picks that anchor even when the pointer moves a few pixels + /// before the release: it does not drag out the dimension of a segment that ends there. Both + /// picks keep their links to the path, so the dimension measures between the two anchors. + #[test] + fn a_press_on_an_anchor_picks_it_when_the_pointer_moves() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let mut t = DimensionTool::default(); + for ((x, y), (dx, dy)) in [((100.0, 100.0), (3.5, 1.0)), ((200.0, 200.0), (-4.0, -2.0))] { + assert!(t.pointer(&c, &ev(PointerKind::Down, x, y)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Drag, x + dx, y + dy)).is_empty(), "no segment dimension is dragged out"); + assert!(t.pointer(&c, &ev(PointerKind::Up, x + dx, y + dy)).is_empty(), "nothing is committed"); + } + let d = t.pending.as_ref().expect("both anchors were picked"); + assert_eq!((d.a, d.b), (Point::new(100.0, 100.0), Point::new(200.0, 200.0))); + let anchor = |anchor| Some(PointRef { node: id, subpath: 0, anchor }); + assert_eq!(d.source, Some(DimensionSource::Points { a: anchor(0), b: anchor(2), vertex: None })); + // Dragged past the anchor's reach, the press drags out the dimension of a segment there. + let mut t = DimensionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0)); + assert!(t.pointer(&c, &ev(PointerKind::Drag, 103.0, 106.0)).is_empty()); + let acts = t.pointer(&c, &ev(PointerKind::Drag, 100.0, 60.0)); + assert!(matches!(acts.first(), Some(Action::Begin(_))), "{acts:?}"); + assert!(matches!(t.pointer(&c, &ev(PointerKind::Up, 100.0, 60.0)).last(), Some(Action::Commit))); + } + + /// The anchors of a live rectangle are picked the same way. + #[test] + fn a_press_on_a_live_shapes_anchor_picks_it() { + let (d, id) = doc_with_live_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = DimensionTool::default(); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 100.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 197.0, 102.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 197.0, 102.0)); + let [(at, Some(r))] = t.points.as_slice() else { panic!("{:?}", t.points) }; + assert_eq!((*at, r.node), (Point::new(200.0, 100.0), id)); + } + + /// An anchor of a compound path inside nested groups, lying just inside another object's + /// edge, is picked and linked, though that edge is nearer the pointer than any of the + /// compound path's own segments. A press there that moves a few pixels picks it too. + #[test] + fn an_anchor_under_another_objects_edge_is_picked() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, NodeKind}; + use vectorcraft_geom::Rect; + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (outer, inner, compound) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut path = vectorcraft_geom::shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)); + path.subpaths.extend(vectorcraft_geom::shapes::rectangle(Rect::new(150.0, 103.0, 180.0, 130.0)).subpaths); + let art = Node::path(compound, path, Appearance::default_art()); + let inner_group = Node::new(inner, NodeKind::Group { children: vec![Arc::new(art)], clip: false }); + let group = Node::new(outer, NodeKind::Group { children: vec![Arc::new(inner_group)], clip: false }); + d.insert(Some(l), 0, group).unwrap(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let corner = (Point::new(150.0, 103.0), Some(PointRef { node: compound, subpath: 1, anchor: 0 })); + let mut t = DimensionTool::default(); + assert_eq!(t.snap_linear(&c, Point::new(151.0, 101.0)), corner); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 151.0, 101.0)); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 155.0, 100.0)).is_empty(), "no segment dimension is dragged out"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 155.0, 100.0)); + assert_eq!(t.points, vec![corner]); + } + #[test] fn placement_press_previews_without_a_prior_move() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index a2ffbbf870..1477cd5bba 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -557,7 +557,7 @@ fn hit_frame_edge(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Vec Vec<(NodeId, usize, usize, Anchor)> { let mut v = vec![]; for &id in &cx.selection.objects { - let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue }; + let Some(pd) = cx.doc.node(id).and_then(handle_path) else { continue }; let shown = cx.selection.partial(id); v.extend(pd.anchors().filter(|(si, ai, _)| shown.is_none_or(|set| set.contains(&(*si, *ai)))).map(|(si, ai, a)| { let mut a = *a; @@ -579,6 +579,33 @@ fn handle_anchors(cx: &ToolContext) -> Vec<(NodeId, usize, usize, Anchor)> { v } +/// The path whose direction handles Direct Selection shows and drags on `n` once it is selected: +/// a path's, or type on a path's path (#3565), in document space. +fn handle_path(n: &Node) -> Option> { + match &n.kind { + NodeKind::Path { path, .. } => Some(Cow::Borrowed(path)), + NodeKind::Text(t) if is_path_type(n) => t.type_path().map(Cow::Owned), + _ => None, + } +} + +/// The direction handles of selected type on a path ([`handle_anchors`]), drawn by the tool: +/// the canvas draws only a path's own (#3565). +fn type_path_handles(cx: &ToolContext) -> Vec { + let mut out = vec![]; + for (id, _, _, a) in handle_anchors(cx) { + if !cx.doc.node(id).is_some_and(is_path_type) { + continue; + } + let color = cx.doc.layer_color(id); + for h in [a.h_in, a.h_out].into_iter().filter(|h| h.distance(a.p) > 1e-6) { + out.push(Overlay::Line { a: a.p, b: h, color, dashed: false }); + out.push(Overlay::Handle { p: h, color }); + } + } + out +} + /// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and /// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path, /// subpath, anchor, is_out). @@ -897,8 +924,9 @@ impl Tool for DirectSelectionTool { let (q, guides) = self.handle_snap.snap(cx, (id, si, ai), p, ev.mods.shift); self.snapped = snapped(q.to_vec2(), p.to_vec2(), ev.mods.shift, &guides); self.guides = guides; + let cmd = if cx.doc.node(id).is_some_and(is_path_type) { "text.setPathHandle" } else { "path.setHandle" }; vec![Action::Preview( - "path.setHandle".into(), + cmd.into(), json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}), )] } @@ -1001,6 +1029,7 @@ impl Tool for DirectSelectionTool { out.push(Overlay::Path { path, color: cx.doc.layer_color(sp.instance), width: 1.0, dashed: false }); } out.extend(frame_overlays(cx, &self.frame_anchors(cx))); + out.extend(type_path_handles(cx)); let drag = if let State::Bracket(b) = &self.state { Some(b) } else { None }; out.extend(pathtype::overlays(cx, self.bracket_hover, drag)); } @@ -1437,7 +1466,7 @@ impl DirectSelectionTool { // them, an edge on a gridline on each axis), not that point (#3835). let grid = segment && (cx.snap_to_grid || cx.snap_to_pixel); self.partial_grid = - grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds(cx.selection, cx.doc, cx.preview_bounds))); + grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()))); } let mut d = move_delta(start, p, ev.mods.shift, cx.constrain_angle); let unsnapped = d; @@ -1474,7 +1503,7 @@ impl DirectSelectionTool { self.partial_snap = (!cx.selection.anchors.is_empty()).then(|| PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); let grid = self.partial_snap.is_some() && grab.is_none() && (cx.snap_to_grid || cx.snap_to_pixel); self.partial_grid = - grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds(cx.selection, cx.doc, cx.preview_bounds))); + grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()))); let copy = ev.mods.alt && self.partial_snap.is_none(); out.push(Action::Begin(if copy { "Copy".into() } else { "Move".into() })); self.state = State::MoveObject { start, grab, hold, began: true, deselect: None }; diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 7948b47072..d7d4bb85b4 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2334,3 +2334,38 @@ fn a_press_on_a_clipping_path_in_a_dynamic_instance_picks_it() { outline.iter().find_map(|o| if let Overlay::Path { path, .. } = o { Some(vectorcraft_geom::kurbo::Shape::bounding_box(path)) } else { None }); assert_eq!(drawn, Some(Rect::new(310.0, 310.0, 320.0, 320.0))); } + +/// #3565: selected type on a path shows its path's direction handles, as a path selected whole +/// shows its own, and a press on one drags it with `text.setPathHandle` (Shift: 45° steps round +/// its anchor; Alt: that side only); none with Show handles when multiple anchors are selected off. +#[test] +fn type_on_a_path_shows_and_drags_its_paths_handles() { + let (mut d, text) = doc_with_path_type(); + let Some(vectorcraft_doc::NodeKind::Text(t)) = d.node_mut(text).map(|n| &mut n.kind) else { panic!("type") }; + let vectorcraft_doc::TextKind::OnPath { path, .. } = &mut t.kind else { panic!("on a path") }; + path.subpaths[0].anchors[0].h_out = Point::new(100.0, 200.0); + path.subpaths[0].anchors[1].h_in = Point::new(400.0, 200.0); + let p = paint(); + let mut s = Selection::default(); + s.add(text); + let c = cx(&d, &s, &p); + let handles = |c: &ToolContext| -> Vec { + DirectSelectionTool::new(false).overlays(c).iter().filter_map(|o| if let Overlay::Handle { p, .. } = o { Some(*p) } else { None }).collect() + }; + assert_eq!(handles(&c), vec![Point::new(100.0, 200.0), Point::new(400.0, 200.0)]); + let mut t = DirectSelectionTool::new(false); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 101.0, 201.0)), vec![Action::Begin("Reshape".into())]); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 210.0).with_mods(Mods { alt: true, ..Mods::default() })); + assert!( + matches!(&a[..], [Action::Preview(n, v)] if n == "text.setPathHandle" && v["id"] == text.0 && v["subpath"] == 0 && v["anchor"] == 0 && v["which"] == "out" && v["independent"] == true), + "{a:?}" + ); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 210.0)), vec![Action::Commit]); + let mut t = DirectSelectionTool::new(false); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 399.0, 201.0)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 390.0, 120.0).with_mods(Mods { shift: true, ..Mods::default() })); + let Some(Action::Preview(n, v)) = a.first() else { panic!("{a:?}") }; + assert_eq!((n.as_str(), &v["anchor"], &v["which"]), ("text.setPathHandle", &json!(1), &json!("in"))); + assert!((v["x"].as_f64().unwrap() - 400.0).abs() < 1e-9, "Shift keeps it straight above its anchor: {v}"); + assert!(handles(&ToolContext { handles_multiple: false, ..cx(&d, &s, &p) }).is_empty()); +} diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs index 70ad9a7e4a..b92f8adfba 100644 --- a/crates/tools/src/draw2/curvature.rs +++ b/crates/tools/src/draw2/curvature.rs @@ -649,6 +649,10 @@ impl Tool for CurvatureTool { self.id = Some(cx.selection.objects[0]); } } + /// A path being drawn: Escape ends it. + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.active(cx).is_some() + } fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { matches!(key, ToolKey::Backspace | ToolKey::Delete) && self.drag.is_none() diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 0b117b95b5..32941c5f71 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -288,6 +288,11 @@ pub fn square(d: Vec2) -> Vec2 { /// state: hovering gathers them again only after the document, the selection, what is left out, /// the window or the snapping options changed; a press always gathers them afresh, and the drag /// it starts keeps them, the document then showing the drag's own previews. +/// +/// The Measure and Measure & Inspect tools keep one too, for the ends of a drag only. They do not +/// ask it while hovering. [`Self::measure`] gathers [`Targets::for_measure`] instead, and a press +/// reuses those targets while nothing they depend on changed. It has guides to show only while +/// Snap to Glyph gives guides. #[derive(Default)] pub struct DrawSnap { /// The targets, and what they were gathered for (none: for one drag only). @@ -348,6 +353,23 @@ impl DrawSnap { self.snap(cx, p, from) } + /// Snap an end of a measurement at `p` ([`Targets::for_measure`]), reusing the targets while + /// nothing they depend on changed, so a drag lays out the type once. With Snap to Glyph giving + /// no guides, [`Self::guides`] stays empty. + pub fn measure(&mut self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> Point { + let key = SnapKey::of(cx, &[]); + let glyphs = key.snap_to_glyph.is_some(); + if self.targets.as_ref().is_none_or(|(k, _)| k.as_ref() != Some(&key)) { + let snap = PointSnap::new(cx, || Targets::for_measure(cx.doc, visible(cx), key.snap_to_glyph)); + self.targets = Some((Some(key), snap)); + } + let q = self.snap(cx, p, from); + if !glyphs { + self.guides.clear(); + } + q + } + /// Snap the point pressed at `p` onto the art's anchors and paths alone, within the Smart /// Guides snapping tolerance (the Knife's straight cut). The targets serve this press only. pub fn press_on_paths(&mut self, cx: &ToolContext, p: Point) -> Point { @@ -406,8 +428,12 @@ impl HandleSnap { /// Where the handle of anchor `ai` of subpath `si` of path `id` goes with the pointer at `p`, /// and the guides showing why. pub fn snap(&mut self, cx: &ToolContext, (id, si, ai): (NodeId, usize, usize), p: Point, shift: bool) -> (Point, Vec) { - let path = cx.doc.node(id).and_then(|n| n.path_data()); - if shift && let Some(a) = path.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) { + // A path's anchor, or one of type on a path's path (#3565), in document space. + let anchor = cx.doc.node(id).and_then(|n| match &n.kind { + vectorcraft_doc::NodeKind::Text(t) => t.type_path()?.subpaths.get(si)?.anchors.get(ai).copied(), + _ => n.path_data()?.subpaths.get(si)?.anchors.get(ai).copied(), + }); + if shift && let Some(a) = anchor { return (a.p + constrain_angle_from(p - a.p, 45.0, cx.constrain_angle), vec![]); } if self.0.targets.is_none() { diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 17b24ec16f..e4039e6d9c 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -213,6 +213,17 @@ impl Targets { t.index() } + /// Targets for the ends of a measurement: [`Self::collect`]'s, and with `glyphs` (Snap to Glyph + /// on) the guides those options ask for from the live text in `visible` (all of it for None), + /// without the outlines' anchor points, which Anchor Point gives the Pen and moved objects. + pub fn for_measure(doc: &Document, visible: Option, glyphs: Option) -> Self { + let mut t = Self::collect(doc, &[], None); + if let Some(o) = glyphs { + t.push_glyphs(doc, &[], visible, GlyphSnap { anchors: false, ..o }); + } + t.index() + } + /// Targets for a dragged direction handle of path `id`: the other art, and the anchors of `id` /// (its bounds and the segments through the handle move with it, so they would chase it). pub fn for_handle(doc: &Document, id: NodeId) -> Self { diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 557fe52b11..c397231495 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -162,6 +162,12 @@ pub trait Tool: Send { fn claims_key(&self, _cx: &ToolContext, _key: ToolKey) -> bool { false } + /// Has the tool started something that Escape ends while no button is pressed (a path being + /// drawn, the Blend tool's first pick)? That Escape ends nothing else, such as isolation mode or + /// a rotated view. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + false + } /// Does the tool want typed text (Type tool editing)? Single-key shortcuts are suppressed. fn wants_text(&self) -> bool { false @@ -536,6 +542,7 @@ pub(crate) mod testutil { freeform_point: None, raster_sample: 1, preview_bounds: false, + glyph_bounds: false, preview_memo: None, unit: Unit::Points, stroke_unit: Unit::Points, diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 5edc14ad42..d64b4b162b 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -153,6 +153,10 @@ impl Tool for BlendTool { fn busy(&self) -> bool { self.first.is_some() } + /// A first pick, or adding to the blend just made: Escape ends either. + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.first(cx).is_some() + } /// Escape drops the object picked first and stops adding to the blend just made, so the next /// click picks a new first object. The document and the selection stay as they are. fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec { @@ -525,8 +529,10 @@ mod tests { let c = cx(&d, &s, &p); let mut t = BlendTool { first: None, chained: true, ..Default::default() }; assert!(t.first(&c).is_some()); + assert!(!t.busy() && t.ends_on_escape(&c), "Escape has adding to the blend to end"); assert!(t.key(&c, crate::ToolKey::Escape, Mods::default()).is_empty()); assert!(t.first(&c).is_none(), "Escape ends adding to the blend just made"); + assert!(!t.ends_on_escape(&c), "and then has nothing to end"); assert_eq!(t.pointer(&c, &down(150.0, 150.0)), picks(a)); assert!(esc(&mut BlendTool::default()).is_empty(), "nothing to drop"); } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index e5906db59f..bc564fced3 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -242,6 +242,10 @@ impl Tool for PenTool { fn busy(&self) -> bool { self.drag.is_some() || self.handle.is_some() || self.convert.is_some() } + /// A path being drawn: Escape ends it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.path.is_some() + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let tol = cx.tol(5.0).max(cx.point_tol()); // The path a press began is the selected one by the next event. diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index e39837c7c4..fe666bd671 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -419,7 +419,7 @@ struct MemoState { struct Measured { revision: (u64, u64), objects: Vec, - preview: bool, + measure: vectorcraft_effects::preview::Measure, bounds: Option>, oriented: Option>, by_object: HashMap>>, @@ -427,7 +427,7 @@ struct Measured { impl Measured { fn is_for(&self, cx: &ToolContext) -> bool { - self.revision == cx.revision && self.preview == cx.preview_bounds && self.objects == cx.selection.objects + self.revision == cx.revision && self.measure == cx.bounds_measure() && self.objects == cx.selection.objects } } @@ -450,7 +450,7 @@ impl PreviewMemo { let fresh = || Measured { revision: cx.revision, objects: cx.selection.objects.clone(), - preview: cx.preview_bounds, + measure: cx.bounds_measure(), bounds: None, oriented: None, by_object: HashMap::new(), @@ -487,15 +487,16 @@ fn remembered(cx: &ToolContext, slot: impl Fn(&mut Measured) -> &mut O } /// Selection bounds used for the bounding box: visual bounds as drawn with Use Preview Bounds -/// ([`vectorcraft_effects::preview`]), else geometric bounds. +/// ([`vectorcraft_effects::preview`]), else geometric bounds, with point type measured by its +/// glyphs with Measure Type by Glyph Bounds ([`ToolContext::bounds_measure`]). pub fn selection_bounds(cx: &ToolContext) -> Option { - remembered(cx, |m| &mut m.bounds, || vectorcraft_effects::preview::bounds_of(cx.doc, &cx.selection.objects, cx.preview_bounds)) + remembered(cx, |m| &mut m.bounds, || vectorcraft_effects::preview::bounds_of_with(cx.doc, &cx.selection.objects, cx.bounds_measure())) } /// [`selection_bounds`] square to the selection's own angle: the bounding box the Selection tool /// shows and drags (rotated after a rotation). pub fn selection_box(cx: &ToolContext) -> Option { - remembered(cx, |m| &mut m.oriented, || vectorcraft_effects::preview::oriented_bounds(cx.doc, &cx.selection.objects, cx.preview_bounds)) + remembered(cx, |m| &mut m.oriented, || vectorcraft_effects::preview::oriented_bounds_with(cx.doc, &cx.selection.objects, cx.bounds_measure())) } /// [`selection_box`] while the canvas shows it (View › Show Bounding Box, and no anchors selected @@ -527,7 +528,7 @@ fn object_bounds(cx: &ToolContext, id: NodeId) -> Option { /// which compares the whole selection: a walk of every selected object checking it each time takes /// time in the square of their number. fn with_object_bounds(cx: &ToolContext, walk: impl FnOnce(&mut dyn FnMut(NodeId) -> Option) -> R) -> R { - let mut measure = |id: NodeId| vectorcraft_effects::preview::bounds_of(cx.doc, &[id], cx.preview_bounds); + let mut measure = |id: NodeId| vectorcraft_effects::preview::bounds_of_with(cx.doc, &[id], cx.bounds_measure()); let Some(mut st) = cx.preview_memo.and_then(|memo| memo.0.try_borrow_mut().ok()) else { return walk(&mut measure); }; diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 9921d8f5b4..2b1151742a 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2255,6 +2255,30 @@ fn the_preview_memo_measures_once_per_revision_selection_and_preview_bounds() { assert_eq!(selection_bounds(&c).map(|r| r.x1), Some(250.0)); } +/// With Measure Type by Glyph Bounds, the bounding box of selected point type is the ink of its +/// glyphs; the memo measures again when only that setting changes. +#[test] +fn the_bounding_box_of_point_type_follows_measure_type_by_glyph_bounds() { + use vectorcraft_doc::{CharStyle, Document, Node, NodeKind, TextObject}; + let mut d = Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let text = TextObject::point(Point::new(100.0, 300.0), "Hg", CharStyle { size: 60.0, ..Default::default() }); + let ink = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text).ink_bounds().unwrap(); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(text.clone())))).unwrap(); + let (mut s, p, memo) = (Selection::default(), paint(), PreviewMemo::default()); + s.set([id]); + let at = |glyph_bounds| { + let c = ToolContext { revision: (1, 1), glyph_bounds, preview_memo: Some(&memo), ..cx(&d, &s, &p) }; + (selection_box(&c).map(|b| b.rect), object_bounds(&c, id)) + }; + let em = d.node(id).and_then(|n| n.geometric_bounds()); + assert_eq!(at(false), (em, em)); + let glyphs = Some(text.xf.transform_rect_bbox(ink)); + assert_eq!(at(true), (glyphs, glyphs)); + assert_ne!(glyphs, em); + assert_eq!(memo.measurements(), 4, "the same revision measured again for the setting"); +} + /// A double-click on a symbol instance edits its symbol in symbol editing mode (`symbol.edit`), and /// one outside the symbol's art in that mode leaves it, as it leaves isolation mode. An instance /// inside the art of the symbol being edited is not entered. diff --git a/crates/tools/src/xform/measure.rs b/crates/tools/src/xform/measure.rs index 62b2071806..e3a0090561 100644 --- a/crates/tools/src/xform/measure.rs +++ b/crates/tools/src/xform/measure.rs @@ -7,6 +7,7 @@ use serde_json::{Value, json}; use vectorcraft_geom::{Point, Vec2}; use super::CYAN; +use crate::guides::DrawSnap; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; #[derive(Default)] @@ -15,6 +16,8 @@ pub struct MeasureTool { dragging: bool, /// The line measured before the drag under way, which Escape puts back. before: Option<(Point, Point)>, + /// Snapping for both ends, its targets kept while nothing they depend on changes. + snap: DrawSnap, } /// (distance, angle in degrees counter-clockwise, dx, dy) @@ -29,10 +32,10 @@ pub fn measure(a: Point, b: Point) -> (f64, f64, f64, f64) { /// tool snaps a Shift-drawn end. With Snap to Point alone, the point `p` snaps to (an anchor, or /// in line with a ruler guide) is projected instead. When the snapped point lies nearer another /// step (the grid rounds it past the halfway angle) or behind the start, it is turned back onto -/// the pointer's step. -pub(crate) fn end_point(cx: &ToolContext, a: Point, p: Point, shift: bool) -> Point { +/// the pointer's step. With View › Snap to Glyph on, the guides of live type are targets too. +pub(crate) fn end_point(cx: &ToolContext, snap: &mut DrawSnap, a: Point, p: Point, shift: bool) -> Point { if !shift { - return crate::guides::snap_draw(cx, p, &[]).0; + return snap.measure(cx, p, None); } let d = vectorcraft_geom::constrain_angle_from(p - a, 45.0, cx.constrain_angle); let len = d.hypot(); @@ -41,10 +44,10 @@ pub(crate) fn end_point(cx: &ToolContext, a: Point, p: Point, shift: bool) -> Po } let u = d / len; let to_point = cx.snap_to_point && !(cx.smart_guides || cx.snap_to_grid || cx.snap_to_pixel); - let s = if to_point { crate::guides::snap_draw(cx, p, &[]).0 } else { p }; + let s = if to_point { snap.measure(cx, p, None) } else { p }; let q = a + u * (s - a).dot(u); let leave = crate::guides::Leave::segment(cx, a, true); - let r = crate::guides::PointSnap::new(cx, || crate::guides::Targets::collect(cx.doc, &[], None)).snap_from(cx, q, Some(&leave)).0; + let r = snap.measure(cx, q, Some(&leave)); let v = r - a; if v.cross(u).abs() <= 1e-9 * v.hypot().max(1.0) && v.dot(u) >= 0.0 { r } else { a + u * v.hypot() } } @@ -61,14 +64,14 @@ impl Tool for MeasureTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { match ev.kind { PointerKind::Down => { - let (p, _) = crate::guides::snap_draw(cx, ev.pos, &[]); + let p = self.snap.measure(cx, ev.pos, None); self.before = self.line; self.line = Some((p, p)); self.dragging = true; } PointerKind::Drag | PointerKind::Up if self.dragging => { if let Some((a, _)) = self.line { - self.line = Some((a, end_point(cx, a, ev.pos, ev.mods.shift))); + self.line = Some((a, end_point(cx, &mut self.snap, a, ev.pos, ev.mods.shift))); } self.dragging = ev.kind == PointerKind::Drag; } @@ -86,10 +89,8 @@ impl Tool for MeasureTool { } fn overlays(&self, cx: &ToolContext) -> Vec { - let Some((a, b)) = self.line else { return vec![] }; - if a == b { - return vec![]; - } + let guides = self.snap.guides().iter().filter(|_| self.dragging).cloned(); + let Some((a, b)) = self.line.filter(|(a, b)| a != b) else { return guides.collect() }; let mut out = vec![Overlay::Line { a, b, color: CYAN, dashed: false }]; // Measurement Labels decides the readout; the line the tool draws stays. if cx.measurement_labels { @@ -99,6 +100,7 @@ impl Tool for MeasureTool { text: format!("D: {}\nAngle: {ang:.1}°\n{}", cx.len(dist), cx.offset_label(dx, dy)), }); } + out.extend(guides); out } @@ -121,7 +123,11 @@ impl Tool for MeasureTool { mod tests { use super::*; use crate::testutil::*; - use vectorcraft_doc::Selection; + use crate::{GlyphSnap, ScreenFrame}; + use vectorcraft_doc::{CharStyle, Document, Node, NodeKind, Selection, TextObject}; + use vectorcraft_geom::kurbo::{ParamCurve, Shape}; + use vectorcraft_geom::{Affine, Rect}; + use vectorcraft_text::{FontDb, layout as layout_text}; #[test] fn horizontal_drag_reports_positive_zero_angle() { @@ -324,4 +330,265 @@ mod tests { assert_eq!(t.options(), first); assert!((t.options()["distance"].as_f64().unwrap() - 50.0).abs() < 1e-9); } + + /// A document holding point type `text` at (100, 300), 60 pt, turned `angle` radians about + /// where it starts, and the type. + fn type_doc(text: &str, angle: f64, visible: bool, locked: bool) -> (Document, TextObject) { + let mut d = Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let at = Point::new(100.0, 300.0); + let mut t = TextObject::point(at, text, CharStyle { size: 60.0, ..Default::default() }); + t.xf = Affine::rotate_about(angle, at) * t.xf; + let mut n = Node::new(id, NodeKind::Text(Box::new(t.clone()))); + (n.visible, n.locked) = (visible, locked); + d.insert(Some(l), 0, n).unwrap(); + (d, t) + } + + /// Where the baseline of `t`'s first line starts on the page, and its unit direction. + fn baseline(t: &TextObject) -> (Point, Vec2) { + let lay = layout_text(FontDb::global(), t); + let (m, line) = (t.xf * lay.line_xf, &lay.lines[0]); + let (at, along) = (m * Point::new(line.x0, line.baseline), m * Point::new(line.x0 + 1.0, line.baseline)); + (at, (along - at) / (along - at).hypot()) + } + + /// The y of the x-height of `t`'s first glyph, in type that isn't turned. + fn x_height(t: &TextObject) -> f64 { + let lay = layout_text(FontDb::global(), t); + let g = &lay.glyphs[0]; + (t.xf * g.xf * Point::new(0.0, -FontDb::global().face_by_id(g.font_id).unwrap().x_height())).y + } + + /// The bounds on the page of glyph `i` of `t`, which isn't turned. + fn glyph_bounds(t: &TextObject, i: usize) -> Rect { + t.xf.transform_rect_bbox(layout_text(FontDb::global(), t).glyphs[i].outline.bounding_box()) + } + + /// Where a measurement dragged from `from` to `to` starts and ends. + fn measured(tool: &mut dyn Tool, cx: &ToolContext, from: Point, to: Point, shift: bool) -> (Point, Point) { + let mods = Mods { shift, ..Mods::default() }; + tool.pointer(cx, &PointerEvent::new(PointerKind::Down, from.x, from.y)); + tool.pointer(cx, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(mods)); + tool.pointer(cx, &PointerEvent::new(PointerKind::Up, to.x, to.y).with_mods(mods)); + let o = tool.options(); + let a = Point::new(o["x"].as_f64().unwrap(), o["y"].as_f64().unwrap()); + (a, a + Vec2::new(o["dx"].as_f64().unwrap(), o["dy"].as_f64().unwrap())) + } + + /// Snap to Glyph: both ends land on a line of type's baseline and x-height and on its glyphs' + /// bounds, each only while its option is on. With Snap to Glyph off they stay at the pointer. + #[test] + fn its_ends_land_on_glyph_guides_with_snap_to_glyph() { + let (d, t) = type_doc("Hg", 0.0, true, false); + let (s, p) = (Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let (base, x) = (baseline(&t).0.y, x_height(&t)); + let (from, to) = (Point::new(400.0, base + 2.0), Point::new(450.0, x + 2.0)); + let (a, b) = measured(&mut MeasureTool::default(), &on, from, to, false); + assert_eq!(a, Point::new(400.0, base), "the press lands on the baseline"); + assert_eq!(b, Point::new(450.0, x), "the end lands on the x-height"); + let off = ToolContext { snap_to_glyph: false, ..on }; + assert_eq!(measured(&mut MeasureTool::default(), &off, from, to, false), (from, to)); + // The Character panel's options: without Baseline and Glyph Bounds (the bottom of `H` is + // on the baseline) the press stays, and without x-height the end does. + let o = GlyphSnap { baseline: false, bounds: false, x_height: false, ..GlyphSnap::default() }; + let without = ToolContext { glyph_snap: o, ..on }; + assert_eq!(measured(&mut MeasureTool::default(), &without, from, to, false), (from, to)); + // A corner of the box of `H`, which only Glyph Bounds gives there. + let corner = Point::new(glyph_bounds(&t, 0).x1, glyph_bounds(&t, 0).y0); + let near = corner + Vec2::new(1.5, -1.0); + let bounds = ToolContext { glyph_snap: GlyphSnap { anchors: false, ..GlyphSnap::default() }, ..on }; + let landed = measured(&mut MeasureTool::default(), &bounds, Point::new(400.0, 50.0), near, false).1; + assert!(landed.distance(corner) < 1e-9, "{landed:?} vs {corner:?}"); + let plain = measured(&mut MeasureTool::default(), &off, Point::new(400.0, 50.0), near, false).1; + assert!((plain.x - corner.x).abs() > 1e-3, "{plain:?}"); + } + + /// A Shift-drag's end stays on its 45° step and slides along it to where it meets a glyph guide. + #[test] + fn a_shift_drag_slides_along_its_step_to_a_glyph_guide() { + let (d, t) = type_doc("Hg", 0.0, true, false); + let (s, p) = (Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let x = x_height(&t); + let (from, to) = (Point::new(300.0, x - 100.0), Point::new(401.0, x + 1.0)); + let landed = measured(&mut MeasureTool::default(), &on, from, to, true).1; + assert!(landed.distance(Point::new(400.0, x)) < 1e-9, "{landed:?}"); + let off = ToolContext { snap_to_glyph: false, ..on }; + let stayed = measured(&mut MeasureTool::default(), &off, from, to, true).1; + assert!(stayed.distance(to) < 1e-9, "{stayed:?}"); + } + + /// Proximity Guides pull an end, with every other option off. Anchor Point does not. + #[test] + fn proximity_guides_pull_an_end_and_a_glyphs_anchor_points_do_not() { + let (d, t) = type_doc("HHHH", 0.0, true, false); + let (s, p) = (Selection::default(), paint()); + let none = GlyphSnap { baseline: false, x_height: false, bounds: false, proximity: false, angular: false, anchors: false }; + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let off = ToolContext { snap_to_glyph: false, ..on }; + let start = Point::new(400.0, 50.0); + let end = |c: &ToolContext, to: Point| measured(&mut MeasureTool::default(), c, start, to, false).1; + let lay = layout_text(FontDb::global(), &t); + let edge = (t.xf * lay.glyphs[1].origin).x; + let to = Point::new(edge + 2.0, 100.0); + assert_eq!(end(&ToolContext { glyph_snap: GlyphSnap { proximity: true, ..none }, ..on }, to).x, edge); + assert_eq!(end(&off, to).x, to.x); + let anchor = t.xf * lay.glyphs[1].outline.segments().next().unwrap().start(); + let to = anchor + Vec2::new(1.5, -1.0); + assert_eq!(end(&ToolContext { glyph_snap: GlyphSnap { anchors: true, ..none }, ..on }, to), end(&off, to)); + } + + /// While a drag snaps with Snap to Glyph on, the guide shows; the drag's end hides it, and with + /// Snap to Glyph off there is only the measured line and its readout. + #[test] + fn a_drag_shows_the_glyph_guide_it_lands_on() { + let (d, t) = type_doc("Hg", 0.0, true, false); + let (s, p) = (Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let to = Point::new(450.0, baseline(&t).0.y + 2.0); + let guides = |c: &ToolContext, to: Point, up: bool| { + let mut tool = MeasureTool::default(); + tool.pointer(c, &PointerEvent::new(PointerKind::Down, 400.0, 50.0)); + tool.pointer(c, &PointerEvent::new(if up { PointerKind::Up } else { PointerKind::Drag }, to.x, to.y)); + tool.overlays(c).iter().filter(|o| !matches!(o, Overlay::Measure { .. })).count() - 1 + }; + assert!(guides(&on, to, false) > 0, "the guide shows during the drag"); + assert_eq!(guides(&on, to, true), 0, "the guide goes when the drag ends"); + // Off, an end still lines up with a rectangle's top edge, as it always has, with no guide. + let (rect, _) = doc_with_rect(); + let off = ToolContext { snap_to_glyph: false, ..cx(&rect, &s, &p) }; + let near = Point::new(450.0, 101.0); + assert_eq!(measured(&mut MeasureTool::default(), &off, Point::new(400.0, 50.0), near, false).1.y, 100.0); + assert_eq!(guides(&off, near, false), 0, "no guide with Snap to Glyph off"); + } + + /// In rotated type the guides run at its angle: the end lands on the baseline, only with + /// Angular Guides on. + #[test] + fn its_ends_land_on_the_guides_of_rotated_type() { + let (d, t) = type_doc("H", 30f64.to_radians(), true, false); + let (s, p) = (Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let (at, dir) = baseline(&t); + let to = at + dir * 250.0 + Vec2::new(-dir.y, dir.x) * 2.0; + let off_line = |c: &ToolContext| (measured(&mut MeasureTool::default(), c, Point::new(20.0, 20.0), to, false).1 - at).cross(dir).abs(); + assert!(off_line(&on) < 1e-6, "{}", off_line(&on)); + let flat = ToolContext { glyph_snap: GlyphSnap { angular: false, ..GlyphSnap::default() }, ..on }; + assert!(off_line(&flat) > 1.0, "{}", off_line(&flat)); + } + + /// A paragraph gives glyph bounds only: no x-height, and the box of a glyph on a later line. + #[test] + fn a_paragraph_gives_the_measure_tool_glyph_bounds_only() { + let (d, t) = type_doc("H\nH", 0.0, true, false); + let (s, p) = (Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let start = Point::new(400.0, 50.0); + let to = Point::new(450.0, x_height(&t) + 2.0); + assert_eq!(measured(&mut MeasureTool::default(), &on, start, to, false).1, to, "no x-height guide"); + let lay = layout_text(FontDb::global(), &t); + assert_eq!(lay.lines.len(), 2); + let top = glyph_bounds(&t, lay.glyphs.len() - 1).y0; + assert_eq!(measured(&mut MeasureTool::default(), &on, start, Point::new(450.0, top - 2.0), false).1, Point::new(450.0, top)); + } + + /// Hidden type gives no guides. Locked type does, as it does for the drawing tools. + #[test] + fn hidden_type_gives_no_glyph_guides_and_locked_type_does() { + let (s, p) = (Selection::default(), paint()); + let drag = |d: &Document, base: f64| { + let c = ToolContext { snap_to_glyph: true, ..cx(d, &s, &p) }; + measured(&mut MeasureTool::default(), &c, Point::new(400.0, 50.0), Point::new(450.0, base + 2.0), false).1 + }; + let (hidden, t) = type_doc("Hg", 0.0, false, false); + let base = baseline(&t).0.y; + assert_eq!(drag(&hidden, base).y, base + 2.0); + let (locked, _) = type_doc("Hg", 0.0, true, true); + assert_eq!(drag(&locked, base).y, base); + } + + /// Grid and pixel snapping come first; Snap to Glyph needs Smart Guides and Alignment Guides. + #[test] + fn glyph_guides_keep_their_place_among_the_other_snaps() { + let (d, t) = type_doc("Hg", 0.0, true, false); + let (s, p) = (Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let base = baseline(&t).0.y; + let (start, to) = (Point::new(400.0, 50.0), Point::new(450.0, base + 2.0)); + let end = |c: &ToolContext| measured(&mut MeasureTool::default(), c, start, to, false).1; + assert_eq!(end(&on), Point::new(to.x, base)); + let grid = ToolContext { snap_to_grid: true, ..on }; + assert_eq!(end(&grid), vectorcraft_geom::snap::snap_point_to_grid(to, grid.grid_step())); + assert_eq!(end(&ToolContext { snap_to_pixel: true, ..on }), Point::new(to.x.round(), to.y.round())); + assert_eq!(end(&ToolContext { smart_guides: false, snap_to_point: true, ..on }), to); + assert_eq!(end(&ToolContext { alignment_guides: false, ..on }), to); + } + + /// The snapping distance is in screen pixels, so a zoomed-out view reaches farther; type + /// outside the window gives no guides. + #[test] + fn glyph_guides_follow_the_view() { + let (d, t) = type_doc("Hg", 0.0, true, false); + let (s, p) = (Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let base = baseline(&t).0.y; + let (start, to) = (Point::new(400.0, 50.0), Point::new(450.0, base - 5.0)); + let end = |c: &ToolContext| measured(&mut MeasureTool::default(), c, start, to, false).1; + assert_eq!(end(&on), to, "5 pt is out of reach at 100%"); + assert_eq!(end(&ToolContext { zoom: 0.25, ..on }), Point::new(to.x, base)); + let frame = |origin: Point| ScreenFrame { origin, right: Vec2::new(1.0, 0.0), down: Vec2::new(0.0, 1.0), size: (800.0, 600.0) }; + let near = Point::new(to.x, base + 2.0); + let end = |c: &ToolContext| measured(&mut MeasureTool::default(), c, start, near, false).1; + assert_eq!(end(&ToolContext { screen: Some(frame(Point::ZERO)), ..on }), Point::new(to.x, base)); + assert_eq!(end(&ToolContext { screen: Some(frame(Point::new(0.0, 1000.0))), ..on }), near); + } + + /// A drag lays out the type once: it keeps the guides its press gathered until the document + /// or a snapping option changes. + #[test] + fn a_drag_keeps_the_glyph_guides_its_press_gathered() { + let (d, t) = type_doc("Hg", 0.0, true, false); + let (empty, s, p) = (Document::new(500.0, 500.0), Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let base = baseline(&t).0.y; + let to = Point::new(450.0, base + 2.0); + let end = |tool: &MeasureTool| { + let o = tool.options(); + o["y"].as_f64().unwrap() + o["dy"].as_f64().unwrap() + }; + let mut tool = MeasureTool::default(); + tool.pointer(&on, &PointerEvent::new(PointerKind::Down, 400.0, 50.0)); + // The same revision: the guides of the press still serve, though this document has no type. + let later = ToolContext { snap_to_glyph: true, ..cx(&empty, &s, &p) }; + tool.pointer(&later, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert_eq!(end(&tool), base); + // A new revision gathers them again. + let edited = ToolContext { revision: (1, 0), ..later }; + tool.pointer(&edited, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert_eq!(end(&tool), to.y); + // So does turning Snap to Glyph off during the drag. + let mut tool = MeasureTool::default(); + tool.pointer(&on, &PointerEvent::new(PointerKind::Down, 400.0, 50.0)); + tool.pointer(&ToolContext { snap_to_glyph: false, ..on }, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert_eq!(end(&tool), to.y); + } + + /// Escape brings back the last result, and the next drag still lands on the guides. + #[test] + fn escape_leaves_the_glyph_guides_for_the_next_drag() { + let (d, t) = type_doc("Hg", 0.0, true, false); + let (s, p) = (Selection::default(), paint()); + let on = ToolContext { snap_to_glyph: true, ..cx(&d, &s, &p) }; + let base = baseline(&t).0.y; + let mut tool = MeasureTool::default(); + let to = Point::new(450.0, base + 2.0); + let first = measured(&mut tool, &on, Point::new(400.0, 50.0), to, false); + tool.pointer(&on, &PointerEvent::new(PointerKind::Down, 300.0, 60.0)); + tool.pointer(&on, &PointerEvent::new(PointerKind::Drag, 320.0, base + 2.0)); + tool.key(&on, ToolKey::Escape, Mods::default()); + assert!((tool.options()["y"].as_f64().unwrap() - first.0.y).abs() < 1e-9); + assert_eq!(measured(&mut tool, &on, Point::new(300.0, 60.0), to, false).1, Point::new(450.0, base)); + } } diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 04ecc971b0..5cabbed6b8 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -118,7 +118,7 @@ impl TransformTool { return Some(*p); } // Anchors selected with Direct Selection transform alone, about their own centre. - vectorcraft_effects::preview::anchor_bounds(cx.selection, cx.doc, cx.preview_bounds) + vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()) .map(|b| b.center()) .or_else(|| selection_box(cx).map(|b| b.center())) } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 49775e2419..0f5152d2bb 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -53,6 +53,8 @@ impl VectorcraftApp { // The place cursor's clicks and drags place their files through the app // ([`place::place_from_cursor`]). session.place_cursor_requests = true; + // A script runs a slice per frame, so the window keeps drawing and Stop can be pressed. + session.script_frames = true; let views = session.documents().iter().map(View::of).collect(); let view_uids = session.documents().iter().map(|d| d.uid).collect(); let known = session.documents().iter().map(|d| d.uid).collect(); @@ -124,6 +126,7 @@ impl VectorcraftApp { updates_rt: Default::default(), frame_rate: Default::default(), canvas_rect: None, + control_rotate_press: None, hover_doc: None, titlebar_from_env: false, custom_titlebar: false, @@ -232,6 +235,19 @@ impl VectorcraftApp { /// eframe isn't a dependency of this crate (the host owns the event loop); these entry points are /// called from the host's `eframe::App` impl. impl VectorcraftApp { + /// Applies the work that finished off the UI thread. It stays pending while a script runs, since + /// every change to the documents ends in a busy error until the script ends. + pub(crate) fn poll_finished_work(&mut self) { + if self.session.script_running() { + return; + } + background::poll(self); + opening::poll(self); + plugin_runs::poll(self); + trace_runs::poll(self); + placing::poll(self); + } + /// The language the UI is drawn in: the Preferences dialog's choice while it is open (so a /// change shows before OK), else the `interfaceLanguage` preference (`auto` = the system's). pub fn ui_language(&self) -> i18n::Lang { @@ -321,12 +337,12 @@ impl VectorcraftApp { // A Paste the host read before this iteration's formats were written must still wait for // them, even if the worker below finishes them during this same tick. ctx.data_mut(|d| d.insert_temp(egui::Id::unique("clipboard.pending-at-tick"), self.clipboard_publishing.is_pending())); - background::poll(self); screen_color::poll(self, ctx); - opening::poll(self); - plugin_runs::poll(self); - trace_runs::poll(self); - placing::poll(self); + self.poll_finished_work(); + crate::script_runs::poll(self); + if self.session.script_running() && !self.session.script_waiting() { + ctx.request_repaint(); + } #[cfg(not(target_arch = "wasm32"))] self.tick_link_updates(ctx, now); crate::addons::select::link_status::refresh(self, now); @@ -351,7 +367,12 @@ impl VectorcraftApp { crate::ime::close_viewport(self, ctx); self.ime_context.end_viewport(ctx.viewport_id()); unsaved::finish_pending(self); - if self.file_sheet_open() { + if self.session.script_running() { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + if self.ui.dialog.is_none() { + self.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, serde_json::json!({}))); + } + } else if self.file_sheet_open() { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); self.status(picks::busy()); } else if unsaved::any_dirty(self) { diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index d5ca8a1968..9e698b1bff 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -404,6 +404,10 @@ impl VectorcraftApp { if let Err(e) = switched { self.ui.status = e.to_string(); } + if before != self.session.tool_id() { + // A control gesture cannot resume after another tool has owned the pointer. + self.control_rotate_press = None; + } // A newly chosen Artboard tool starts on the active artboard (the view's). if before != "artboard" && self.session.tool_id() == "artboard" diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 9895149917..6aa3eab765 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -137,13 +137,14 @@ impl VectorcraftApp { /// frame: it is measured once per revision. pub fn selection_box(&mut self) -> Option { let st = self.session.active()?; - let key = (st.uid, st.revision, self.session.prefs.use_preview_bounds); + let measure = self.session.bounds_measure(); + let key = (st.uid, st.revision, measure); if let Some((k, b)) = self.canvas.selection_box && k == key { return b; } - let b = match vectorcraft_effects::preview::anchor_bounds(&st.selection, &st.doc, self.session.prefs.use_preview_bounds) { + let b = match vectorcraft_effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) { Some(r) => Some(vectorcraft_doc::OrientedBox::aligned(r)), None => self.session.transform_box(&st.selection.objects), }; diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 4badbd6287..1e69fc57d5 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -7,7 +7,7 @@ pub struct CanvasCache { pub key: Option, /// The document the frame shown was rendered from, and the options it was rendered with, with /// [`Self::key`]: when only the document changes, the canvas renders again only where it - /// changed ([`vectorcraft_render::changed`]). + /// changed, measured by [`Self::renderer`], which drew it ([`vectorcraft_render::Renderer::changed`]). pub shown: Option<(std::sync::Arc, vectorcraft_render::RenderOptions)>, pub last_ms: f64, /// The frame shown drew raster effects from rasters made before their objects moved, or at a @@ -51,8 +51,9 @@ pub struct CanvasCache { /// The selected objects' outlines, anchors and handles as drawn in the last frame. A frame that /// does not draw them drops them ([`canvas::show`]). pub selection_marks: canvas::SelectionMarks, - /// [`VectorcraftApp::selection_box`] for (document uid, revision, Use Preview Bounds). - pub selection_box: Option<((u64, u64, bool), Option)>, + /// [`VectorcraftApp::selection_box`] for (document uid, revision, Use Preview Bounds and + /// Measure Type by Glyph Bounds). + pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option)>, /// [`VectorcraftApp::selection_bounds`] for (document uid, revision). pub selection_bounds: Option<((u64, u64), Option)>, /// [`VectorcraftApp::content_bounds`] for (document uid, revision). diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 69ba945b90..6fc9baab5c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -77,6 +77,7 @@ use tool_overlays::{ print_tiling_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, }; pub(crate) use view::animated_zoom; +pub(crate) use view::drag_rotation; pub use view::fit; use view::scroll_bars; #[cfg(test)] @@ -543,8 +544,9 @@ fn ruler_bands(app: &VectorcraftApp, ui: &Ui, xf: &Xf, (full, rect): (egui::Rect let painter = ui.painter_at(rect); if let Some(origin) = origin_preview { let at = xf.to_screen(origin); - painter.line_segment([pos2(at.x, rect.top()), pos2(at.x, rect.bottom())], Stroke::new(1.0, t.text_dim)); - painter.line_segment([pos2(rect.left(), at.y), pos2(rect.right(), at.y)], Stroke::new(1.0, t.text_dim)); + let color = dim_on_canvas(t, app.outline_view()); + painter.line_segment([pos2(at.x, rect.top()), pos2(at.x, rect.bottom())], Stroke::new(1.0, color)); + painter.line_segment([pos2(rect.left(), at.y), pos2(rect.right(), at.y)], Stroke::new(1.0, color)); } // View › Rulers › Show Video Rulers counts the active artboard in video pixels. let video = app.ui.view.video_rulers.then(|| crate::dialogs::artboard_options::active_index(app)); @@ -739,6 +741,10 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { // rendered again, here, into the texture. `last_ms` stays the whole frame's. (_, _, Some(region)) => { let t0 = now_ms(); + if region.is_none() { + // Nothing in view to draw again: what was made to measure the edit isn't drawn. + app.canvas.renderer.let_go_of_measured(); + } if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { let part = app.canvas.renderer.render(doc, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))) * view, &opts); let color = color_image(&part); @@ -751,6 +757,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.perf.render_ms = now_ms() - t0; } (Some(worker), true, None) => { + // The worker draws the frame: what this thread's renderer made to measure the edit + // isn't drawn here. + app.canvas.renderer.let_go_of_measured(); let queued = worker.submit(crate::render_worker::Job { key: key.clone(), doc: doc.clone(), @@ -786,8 +795,17 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { } } -/// The pasteboard, the artboards' shadows and paper, and the outline mode's white artboards, of -/// document `st`, in Outline when `outline`. +/// The canvas color in Outline, whatever the interface brightness and Canvas Color: the paths draw +/// as black hairlines, and the artboards as their edges only. +const OUTLINE_CANVAS: Color32 = Color32::WHITE; + +/// The color of the artboards' names and the ruler origin's crosshair in Outline, on +/// [`OUTLINE_CANVAS`]. +const OUTLINE_DIM: Color32 = Color32::from_gray(0x4b); + +/// The pasteboard and the artboards' shadows and paper of document `st`, or in Outline (`outline`) +/// the whole canvas in [`OUTLINE_CANVAS`], with no paper drawn for the artboards: no Simulate +/// Colored Paper color, no artboard background color, and no paper with View › Hide Artboards. fn paint_paper( app: &VectorcraftApp, st: &vectorcraft_engine::DocState, @@ -798,6 +816,12 @@ fn paint_paper( (t, outline): (&Tokens, bool), ) { let doc = &st.doc; + if outline { + // The art draws in black on white over the pasteboard and the artboards alike, and the + // artboards show as their edges (`artboard_outlines`). + painter.rect_filled(rect, 0.0, OUTLINE_CANVAS); + return; + } // Pasteboard, artboard shadows and paper (Document Setup: the transparency grid's look, the // simulated paper colour; a white Background Contents hides the grid). // An artboard with a background color draws its paper in that color. With Simulate Colored Paper @@ -808,7 +832,7 @@ fn paint_paper( // View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038). let setup = &doc.setup; painter.rect_filled(rect, 0.0, if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }); - } else if !outline { + } else { let setup = &doc.setup; let grid = (st.transparency_grid && setup.background == vectorcraft_doc::Background::Transparent).then(|| checker_texture(ui.ctx(), setup)); let paper = if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }; @@ -826,10 +850,6 @@ fn paint_paper( } } } - } else { - for ab in &doc.artboards { - painter.add(Shape::convex_polygon(xf.quad(ab.rect), Color32::WHITE, Stroke::NONE)); - } } } @@ -1000,16 +1020,22 @@ fn artboard_outlines(app: &VectorcraftApp, ui: &Ui, painter: &egui::Painter, xf: let tool_selected = artboards::tool_labelled(app); let editing_name = ui.data(|d| d.get_temp::(name_edit_id()).map(|e| e.index)); let unlabelled = |i: usize| editing_name == Some(i) || u64::try_from(i).ok().is_some_and(|idx| tool_selected.contains(&idx)); - artboard_edges(app, doc, (painter, xf, t), active_ab, unlabelled); + artboard_edges(app, doc, (painter, xf, t), (active_ab, dim_on_canvas(t, app.outline_view())), unlabelled); } -/// The edges, bleeds, marks and names of `doc`'s artboards, `active_ab` the active one; the -/// artboards `unlabelled` gives are not named. +/// The color of the artboards' names and the ruler origin's crosshair over the pasteboard, or over +/// [`OUTLINE_CANVAS`] in Outline (`outline`). +fn dim_on_canvas(t: &Tokens, outline: bool) -> Color32 { + if outline { OUTLINE_DIM } else { t.text_dim } +} + +/// The edges, bleeds, marks and names of `doc`'s artboards, `active_ab` the active one, the names +/// in `label`; the artboards `unlabelled` gives are not named. fn artboard_edges( app: &VectorcraftApp, doc: &vectorcraft_doc::Document, (painter, xf, t): (&egui::Painter, &Xf, &Tokens), - active_ab: usize, + (active_ab, label): (usize, Color32), unlabelled: impl Fn(usize) -> bool, ) { let artboard_tool = app.session.tool_id() == "artboard"; @@ -1027,7 +1053,7 @@ fn artboard_edges( // At the artboard's own top-left corner, which a rotated view turns away from its // bounding box's (#1095). let corner = xf.to_screen(Point::new(ab.rect.x0, ab.rect.y0)); - artboard_label(painter, corner, (ab.rect.width() * xf.zoom) as f32, &format!("{:02} - {}", i + 1, ab.name), t.text_dim); + artboard_label(painter, corner, (ab.rect.width() * xf.zoom) as f32, &format!("{:02} - {}", i + 1, ab.name), label); } } } diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index 5af09ab3bf..c5bbe90882 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -20,6 +20,8 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: .active() .filter(|_| app.session.tool_id() == "intertwine") .and_then(|st| vectorcraft_tools::intertwine::menu_target(&st.doc, &st.selection.objects, p).map(|(g, m)| (st.uid, g, p, m))); + // Auto Spell Check: the underlined word right-clicked, for its suggestions. + app.ui.context_spelling = if app.ui.view.auto_spell_check { super::tool_overlays::misspelled_word_at(app, p) } else { None }; let on_artboards = app.session.tool_id() == "artboard"; if on_artboards { crate::panels::artboards::right_click(app, p); @@ -39,6 +41,7 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: app.ui.context_locked = None; app.ui.context_intertwine = None; app.ui.context_artboards = None; + app.ui.context_spelling = None; } if let Some((id, p)) = clicked { crate::menus::invoke(app, &id, p); diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 5fbc2b9038..43e5df0bcd 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -337,14 +337,8 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) } } Drag::RotateView { start_angle, start_rot, snaps } => { - let c = rect.center(); - let a = (p.y - c.y).atan2(p.x - c.x) as f64; - let mut deg = start_rot + (a - start_angle).to_degrees(); - if snaps && m.shift { - deg = (deg / 15.0).round() * 15.0; - } if let Some(vm) = app.view_mut() { - vm.rotation = vectorcraft_geom::normalize_deg(deg); + vm.rotation = super::view::drag_rotation(rect.center(), p, start_angle, start_rot, snaps && m.shift); } } Drag::ZoomBox { start } => { diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index fb9872a777..fcda53def0 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -106,6 +106,7 @@ pub(super) fn mark_options(app: &VectorcraftApp, curve_points_from_tool: bool) - } } +/// Draw selection marks and widgets, keeping the box but hiding dot marks during Halftone Preview. pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf, curve_points_from_tool: bool, marks: &mut SelectionMarks) { // The Selection tool's bounding box (rotated with the objects after a rotation), also shown by // the shape tools that keep a shape just drawn ready to adjust while they draw none (#5477). It @@ -140,7 +141,8 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: None => b, }); let st = app.session.active(); - let big = st.is_some_and(|st| too_many_anchors(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)))); + let show_marks = !crate::dialogs::halftone::previewing(app); + let big = show_marks && st.is_some_and(|st| too_many_anchors(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)))); let big_bounds = if big { app.selection_bounds() } else { None }; let app = &*app; let Some(st) = app.session.active() else { return }; @@ -152,24 +154,27 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: let options = mark_options(app, curve_points_from_tool); let grow = options.look.grow; let anchor = |direct: bool| grow + if direct { 5.0 } else { 4.0 }; - // Too many paths to outline: the selection's bounds stand for them. - if let Some((b, id)) = big_bounds.zip(st.selection.objects.first()) { - stroke_path(p, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, Stroke::new(1.0, c32(st.doc.layer_color(*id)))); + // The temporary halftone selects its dots; their marks obscure the art (#6369). + if show_marks { + // Too many paths to outline: the selection's bounds stand for them. + if let Some((b, id)) = big_bounds.zip(st.selection.objects.first()) { + stroke_path(p, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, Stroke::new(1.0, c32(st.doc.layer_color(*id)))); + } + // The key object (Align to Key Object): its outline drawn thicker, or its bounds when it has + // too many paths to outline. + let key = st.selection.key.and_then(|k| Some((k, st.doc.node(k)?))); + let (key_bounds, key_outline) = match key { + Some((k, n)) if too_many_anchors([n]) => (Some((k, n)), None), + Some((k, _)) => (None, Some(k)), + None => (None, None), + }; + if let Some((k, n)) = key_bounds + && let Some(b) = n.geometric_bounds_with(&symbols) + { + stroke_path(p, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, Stroke::new(KEY_OUTLINE, c32(st.doc.layer_color(k)))); + } + marks.paint(st, p, xf, &options, key_outline, if big { &[] } else { &st.selection.objects }); } - // The key object (Align to Key Object): its outline drawn thicker, or its bounds when it has - // too many paths to outline. - let key = st.selection.key.and_then(|k| Some((k, st.doc.node(k)?))); - let (key_bounds, key_outline) = match key { - Some((k, n)) if too_many_anchors([n]) => (Some((k, n)), None), - Some((k, _)) => (None, Some(k)), - None => (None, None), - }; - if let Some((k, n)) = key_bounds - && let Some(b) = n.geometric_bounds_with(&symbols) - { - stroke_path(p, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, Stroke::new(KEY_OUTLINE, c32(st.doc.layer_color(k)))); - } - marks.paint(st, p, xf, &options, key_outline, if big { &[] } else { &st.selection.objects }); // The spine of each selected blend (or of the blend a selected key object belongs to). let mut spines = vec![]; for id in &st.selection.objects { diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 5bd974bf92..13b56e6f1e 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -12,7 +12,8 @@ use super::outline::{c32, node_outline, stroke_path, too_many_anchors}; use super::view::fit_zoom; use super::{ Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, cache_key, - frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, pos2, rulers, shows_artboards, textured_quad, vec2, view_rects, + dim_on_canvas, frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, pos2, rulers, shows_artboards, textured_quad, vec2, + view_rects, }; use crate::doc_windows::Win; use crate::thumb_worker::ThumbWorker; @@ -315,7 +316,7 @@ pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look); } if shows_artboards(app) { - artboard_edges(app, &st.doc, (&painter, &xf, &t), v.artboard, |_| false); + artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false); } if app.ui.view.guides { guides_of(app, st, (&painter, &xf, &t), rect); diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 8684cea057..64fc3599f5 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -35,8 +35,10 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo /// objects showing those bitmaps' files cover (`Some(None)`: none), grown to whole eighths of the /// frame, as long as they are at most half of it. None: render the whole frame. Frames the worker /// renders stay whole: its renderer keeps the rasters of the art's effects, this thread's doesn't. +/// What changed is measured by this thread's renderer, which drew the frame shown: it keeps what +/// it measures (a 3D effect's art) to draw the part again. pub(super) fn changed_pixels( - app: &VectorcraftApp, + app: &mut VectorcraftApp, key: &CacheKey, doc: &vectorcraft_doc::Document, opts: &vectorcraft_render::RenderOptions, @@ -60,7 +62,7 @@ pub(super) fn changed_pixels( } else { vectorcraft_render::placed_area(doc, &vectorcraft_render::placed_document::made_between(shown_key.placed, key.placed)?) }; - match vectorcraft_render::changed(shown, doc).and(placed) { + match app.canvas.renderer.changed(shown, doc, opts).and(placed) { vectorcraft_render::Changed::Nothing => Some(None), vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) { None => Some(None), diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index df8e53de1d..a891179a6b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -210,6 +210,27 @@ fn command_cursor_settings_refresh_hover_cursor_while_view_moves() { assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Crosshair)); } +/// A script that changes Caps Lock refreshes the pointer when its run ends. +#[test] +fn a_script_run_refreshes_hover_cursor_while_view_moves() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.session.select_tool("pen", vectorcraft_engine::ViewInfo::default()).unwrap(); + app.hover_doc = Some(Point::new(200.0, 150.0)); + let mods = Mods::default(); + let view = vectorcraft_engine::ViewInfo::default(); + assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Pen)); + app.run("script.run", json!({"source": "vc.run('view.capsLock', {on: true});"})).unwrap(); + for _ in 0..1_000 { + if !app.session.script_running() { + break; + } + crate::script_runs::poll(&mut app); + } + assert!(app.session.caps_lock); + assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Crosshair)); +} + /// #826: in a turned view each ruler still has ticks along its whole length; at 0° the top one /// reads x where the canvas has it. #[test] @@ -1546,6 +1567,73 @@ fn cmd_with_another_tool_drags_with_the_selection_tool_used_last() { assert_eq!(cmd_drag(&mut app, inside, inside), "selection"); } +/// #6369: only the selection box remains over the temporary halftone, and the original +/// selection's marks come back when Preview is turned off or the dialog is cancelled. +#[test] +fn halftone_preview_hides_dot_outlines_and_keeps_selection_bounds() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.ui.view.bounding_box = true; + let original = app.run("shape.ellipse", json!({"x": 50, "y": 50, "width": 120, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let original = vectorcraft_doc::NodeId(original); + app.run("paint.setFill", json!({"color": "#000000"})).unwrap(); + let canvas = egui::Context::default(); + let dialog = egui::Context::default(); + let dialog_frame = |app: &mut VectorcraftApp| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = dialog.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + let has_interior_marks = |app: &mut VectorcraftApp| { + frame(app, &canvas, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let corners = app.selection_box().unwrap().corners().map(|p| xf.to_screen(p)); + let inside = egui::Rect::from_points(&corners).shrink(10.0); + let st = app.session.active().unwrap(); + let color = c32(st.doc.layer_color(st.selection.objects[0])); + let points = drawn_in(app, &canvas, color, 1.0); + assert!(corners.iter().all(|p| points.contains(p)), "the outer selection box is still drawn"); + points.iter().any(|p| inside.contains(*p)) + }; + assert!(has_interior_marks(&mut app), "the selected ellipse shows its outline"); + + app.run("ui.menuDialog", json!({"command": "object.vectorHalftone"})).unwrap(); + dialog_frame(&mut app); + assert!(app.session.in_interaction()); + assert_ne!(app.session.active().unwrap().selection.objects, vec![original], "the halftone is previewed and selected"); + assert!(!has_interior_marks(&mut app), "selection marks cover the halftone dots"); + + let set_preview = |app: &mut VectorcraftApp, on| { + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(on)); + dialog_frame(app); + }; + set_preview(&mut app, false); + assert_eq!(app.session.active().unwrap().selection.objects, vec![original]); + assert!(has_interior_marks(&mut app), "turning Preview off restores the outline"); + + set_preview(&mut app, true); + assert!(!has_interior_marks(&mut app), "turning Preview back on hides the dot marks again"); + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.active().unwrap().selection.objects, vec![original]); + assert!(has_interior_marks(&mut app), "Cancel restores the outline"); + + app.run("ui.menuDialog", json!({"command": "object.move"})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + dialog_frame(&mut app); + assert!(app.session.in_interaction()); + assert!(has_interior_marks(&mut app), "another dialog's preview keeps selection marks"); + crate::dialogs::cancel(&mut app); + + app.run("ui.menuDialog", json!({"command": "object.vectorHalftone"})).unwrap(); + dialog_frame(&mut app); + assert!(!has_interior_marks(&mut app)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && !app.session.in_interaction()); + assert!(has_interior_marks(&mut app), "OK restores ordinary selection marks on the applied dots"); +} + /// #525: a selection with more anchors than the overlay draws (a traced photo) shows its bounds, /// not every outline and anchor, which made a mesh larger than the GPU takes; an ordinary one /// still shows its outline and anchors. @@ -4189,6 +4277,203 @@ fn outline_is_per_document_and_new_documents_start_in_preview() { assert!(app.run("view.outline", json!({})).is_err()); } +/// One headless canvas frame → (the colors of the filled rectangles that cover the canvas, the +/// fills of the shapes laid over an artboard, the artboards' edges drawn, the colors of the +/// artboards' names). +fn canvas_look(app: &mut VectorcraftApp, ctx: &egui::Context) -> (Vec, Vec, usize, Vec) { + let s = shapes(app, ctx); + let canvas = app.canvas_rect.unwrap(); + let xf = Xf::new(canvas, app.view().unwrap()); + let quads: Vec> = app.session.active().unwrap().doc.artboards.iter().map(|a| xf.quad(a.rect).to_vec()).collect(); + let on = |p: &[Pos2]| quads.iter().any(|q| q.len() == p.len() && q.iter().zip(p).all(|(a, b)| (*a - *b).length() < 0.01)); + let covers: Vec = s + .iter() + .filter_map(|s| match s { + Shape::Rect(r) if r.rect.contains_rect(canvas) => Some(r.fill), + _ => None, + }) + .collect(); + let papers: Vec = s + .iter() + .filter_map(|s| match s { + Shape::Path(p) if p.fill != Color32::TRANSPARENT && on(&p.points) => Some(p.fill), + _ => None, + }) + .collect(); + let edges = s.iter().filter(|s| matches!(s, Shape::Path(p) if p.closed && p.fill == Color32::TRANSPARENT && on(&p.points))).count(); + let names: Vec = s + .iter() + .filter_map(|s| match s { + Shape::Text(t) if names_an_artboard(t.galley.text()) => Some(t.fallback_color), + _ => None, + }) + .collect(); + (covers, papers, edges, names) +} + +/// In Outline, in every interface brightness, color scheme and User Interface › Canvas Color, the +/// whole canvas is white, pasteboard included, so the black outlines of art on the pasteboard show. +/// The artboards draw no paper there, only their edges, and their names draw in a dark gray. In +/// Preview the pasteboard keeps its color and the artboards their white paper. +#[test] +fn outline_draws_on_a_white_canvas_with_artboards_as_edges() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + for brightness in crate::theme::Brightness::ALL { + for scheme in crate::theme::Scheme::ALL { + // Canvas Color: matching the brightness, Dark Gray and Medium Gray, as `prefs_dialog` sets it. + for canvas_color in [None, Some(Color32::from_gray(0x5a)), Some(Color32::from_gray(0x96))] { + let ctx = egui::Context::default(); + crate::theme::apply_with(&ctx, brightness, Default::default(), scheme); + if let Some(c) = canvas_color { + let mut t = Tokens::get(&ctx); + t.pasteboard = c; + ctx.data_mut(|d| d.insert_temp(egui::Id::NULL, t)); + } + let case = format!("{brightness:?} {scheme:?} {canvas_color:?}"); + let pasteboard = Tokens::get(&ctx).pasteboard; + assert_ne!(pasteboard, Color32::WHITE, "{case}"); + app.view_mut().unwrap().outline = false; + let (covers, papers, edges, names) = canvas_look(&mut app, &ctx); + assert_eq!(covers.last(), Some(&pasteboard), "{case}: Preview keeps the pasteboard"); + assert_eq!(papers, [Color32::WHITE; 2], "{case}: and the artboards' paper"); + assert_eq!(edges, 2, "{case}"); + assert_eq!(names, [Tokens::get(&ctx).text_dim; 2], "{case}"); + app.view_mut().unwrap().outline = true; + let (covers, papers, edges, names) = canvas_look(&mut app, &ctx); + assert_eq!(covers.last(), Some(&Color32::WHITE), "{case}: the canvas is white in Outline"); + assert!(!covers.contains(&pasteboard), "{case}: no pasteboard in Outline"); + assert!(papers.is_empty(), "{case}: no paper over the artboards in Outline: {papers:?}"); + assert_eq!(edges, 2, "{case}: the artboards show as their edges"); + assert_eq!(names, [OUTLINE_DIM; 2], "{case}: names readable on white"); + } + } + } +} + +/// In Outline the canvas stays white with Simulate Colored Paper on, with an artboard's own +/// background color, and with View › Hide Artboards, which in Preview show the paper color, the +/// artboard's color and the paper color over the whole canvas. +#[test] +fn outline_draws_no_colored_paper() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + { + let doc = std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc); + doc.setup.simulate_paper = true; + doc.setup.grid_colors = [vectorcraft_color::Color::rgb(0.9, 0.8, 0.6), vectorcraft_color::Color::rgb(0.5, 0.5, 0.5)]; + doc.artboards[1].color = Some(vectorcraft_color::Color::rgb(0.6, 0.8, 1.0)); + } + let paper = crate::panels::c32(&app.session.active().unwrap().doc.setup.paper()); + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, crate::theme::Brightness::Dark); + app.view_mut().unwrap().outline = false; + let (_, papers, _, _) = canvas_look(&mut app, &ctx); + assert_eq!(papers.len(), 2); + assert_eq!(papers[0], paper, "Preview: the simulated paper"); + assert_ne!(papers[1], paper, "Preview: the artboard's own color"); + app.view_mut().unwrap().outline = true; + let (covers, papers, edges, _) = canvas_look(&mut app, &ctx); + assert_eq!(covers.last(), Some(&Color32::WHITE)); + assert!(papers.is_empty(), "{papers:?}"); + assert_eq!(edges, 2); + app.ui.view.artboards = false; + app.view_mut().unwrap().outline = false; + let (covers, _, edges, _) = canvas_look(&mut app, &ctx); + assert_eq!(covers.last(), Some(&paper), "Preview with Hide Artboards: the paper over the whole canvas"); + assert_eq!(edges, 0); + app.view_mut().unwrap().outline = true; + let (covers, papers, edges, _) = canvas_look(&mut app, &ctx); + assert_eq!(covers.last(), Some(&Color32::WHITE), "Outline with Hide Artboards"); + assert!(!covers.contains(&paper)); + assert!(papers.is_empty()); + assert_eq!(edges, 0); +} + +/// A split-view pane or floating window draws its own view's Outline, whatever the current view +/// shows: the white canvas and dark gray artboard names in Outline, and the pasteboard and the +/// theme's names in Preview. +#[test] +fn a_pane_draws_its_own_views_outline() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + crate::doc_windows::new_window(&mut app).unwrap(); + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, crate::theme::Brightness::Dark); + let t = Tokens::get(&ctx); + let other = (0, 1); + for pane_outline in [true, false] { + crate::doc_windows::view_mut(&mut app, other).unwrap().outline = pane_outline; + app.view_mut().unwrap().outline = !pane_outline; + let cell = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 400.0)); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + panes::pane(&mut app, ui, other, cell); + }); + out.textures_delta.clear(); + let mut s = vec![]; + fn flat(s: Shape, out: &mut Vec) { + match s { + Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)), + s => out.push(s), + } + } + out.shapes.into_iter().for_each(|c| flat(c.shape, &mut s)); + let fills: Vec = s.iter().filter_map(|s| if let Shape::Rect(r) = s { Some(r.fill) } else { None }).collect(); + let names: Vec = s + .iter() + .filter_map(|s| if let Shape::Text(x) = s { names_an_artboard(x.galley.text()).then_some(x.fallback_color) } else { None }) + .collect(); + let (canvas, name) = if pane_outline { (Color32::WHITE, OUTLINE_DIM) } else { (t.pasteboard, t.text_dim) }; + assert_eq!(fills.first(), Some(&canvas), "pane in Outline: {pane_outline}"); + assert_eq!(names, [name; 2], "pane in Outline: {pane_outline}"); + } +} + +/// While the rulers' origin is dragged out of their corner, its crosshair draws over the canvas in +/// the theme's dim text color in Preview, and in Outline in the dark gray that shows on the white +/// canvas. +#[test] +fn the_ruler_origin_crosshair_shows_on_the_outline_canvas() { + use egui::Event; + for outline in [false, true] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.view_mut().unwrap().outline = outline; + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, crate::theme::Brightness::Dark); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let corner = pos2(rect.left() - RULER / 2.0, rect.top() - RULER / 2.0); + let to = rect.center(); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(corner)]); + frame(&mut app, &ctx, vec![button(corner, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(to)]); + let (s, mut delta) = frame_output(&mut app, &ctx); + delta.clear(); + let lines: Vec = s + .iter() + .filter_map(|s| match s { + Shape::LineSegment { points, stroke } + if (points[0].x - to.x).abs() < 1.5 + && (points[1].x - to.x).abs() < 1.5 + && points[0].y <= rect.top() + 1.0 + && points[1].y >= rect.bottom() - 1.0 => + { + Some(stroke.color) + } + _ => None, + }) + .collect(); + let want = if outline { OUTLINE_DIM } else { Tokens::get(&ctx).text_dim }; + assert_eq!(lines, [want], "Outline: {outline}"); + frame(&mut app, &ctx, vec![button(to, false)]); + } +} + /// #3797: a preferences file saved while View › Outline was an interface setting still loads, with /// its other view settings, and its Outline value does not put a document in Outline. #[test] @@ -4645,7 +4930,7 @@ fn wheel_over_a_numeric_panel_field_does_not_start_a_canvas_zoom_glide() { /// `ui.wheel`: with Zoom with Mouse Wheel off, Cmd/Ctrl-wheel zooms about the pointer while the /// option is off and scrolls sideways while it is on, and a trackpad pinch, two fingers spread on a touch /// screen, Alt + Cmd/Ctrl-wheel and Alt-wheel still zoom. A Cmd/Ctrl-wheel notch with a plain -/// one right after it scrolls two notches in all, and a trackpad gesture during which Cmd/Ctrl +/// one right after it scrolls two notches in all, and a wheel gesture during which Cmd/Ctrl /// is pressed and released scrolls sideways until the gesture ends, while an Alt gesture that /// pauses past egui's scroll timeout no longer holds Alt for the next move. With Zoom with /// Mouse Wheel also on, Cmd/Ctrl-wheel scrolls sideways and the wheel zooms. @@ -4747,16 +5032,16 @@ fn cmd_wheel_scrolls_sideways_preference() { (zoom - 1.25).abs() < 1e-6 && moved.x > notch - 0.5 && moved.x < 1.25 * notch + 0.5 && moved.y.abs() < 1e-3, "on: a pinch during a Cmd-wheel notch zooms by the pinch, and the notch scrolls sideways ({zoom}, {moved:?})" ); - // A trackpad gesture starts with no modifier, and Cmd is pressed and released during it: - // egui keeps Cmd in its wheel state until the gesture ends, and the canvas keeps scrolling - // sideways until then. + // A gesture egui names as a wheel starts with no modifier, and Cmd is pressed and released + // during it: egui keeps Cmd in its wheel state until the gesture ends, and the canvas keeps + // scrolling sideways until then. let before = *app.view().unwrap(); let swipe = |phase, modifiers| egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, 6.0), phase, modifiers, - source: egui::MouseWheelSource::Unknown, + source: egui::MouseWheelSource::Wheel, }; app.synthetic.extend([ egui::Event::PointerMoved(at), @@ -4772,7 +5057,7 @@ fn cmd_wheel_scrolls_sideways_preference() { let scroll = (after.center - before.center) * after.zoom; assert!( (after.zoom / before.zoom - 1.0).abs() < 1e-9 && (scroll.x + 12.0).abs() < 0.01 && scroll.y == 0.0, - "on: a trackpad gesture scrolls sideways to its end after Cmd is let go ({}, {scroll:?})", + "on: a wheel gesture scrolls sideways to its end after Cmd is let go ({}, {scroll:?})", after.zoom / before.zoom ); // An Alt-wheel gesture pauses past egui's scroll timeout with no frame in between: egui @@ -4820,6 +5105,184 @@ fn cmd_wheel_scrolls_sideways_preference() { assert!(zooms_in(turn(&mut app, "")), "with Zoom with Mouse Wheel: the wheel zooms in about the pointer"); } +/// With Scroll Sideways with Cmd/Ctrl + Wheel on, Cmd/Ctrl with a touchpad zooms about the pointer +/// while whole line notches scroll sideways: a trackpad or point source, line deltas smaller than +/// a notch, and a whole notch later in the same turn. With Zoom with Mouse Wheel on, Cmd/Ctrl with +/// a touchpad zooms too. +#[test] +fn cmd_with_a_touchpad_zooms_and_a_whole_notch_scrolls_sideways() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + let mut t = 0.0; + let mut run = |app: &mut VectorcraftApp, events: Vec| { + t += 1.0 / 60.0; + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), + time: Some(t), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + run(&mut app, vec![]); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() + vec2(60.0, 40.0); + let ev = |unit, dy: f32, source| egui::Event::MouseWheel { + unit, + delta: vec2(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::COMMAND, + source, + }; + // Sends each event on its own frame, then lets egui finish and end the turn: + // → (zoom ratio, scroll in points, how far the point under `at` moved). + let mut turn = |app: &mut VectorcraftApp, events: Vec| { + let before = *app.view().unwrap(); + run(app, vec![egui::Event::PointerMoved(at)]); + for e in events { + run(app, vec![e]); + } + for _ in 0..40 { + run(app, vec![]); + } + let after = *app.view().unwrap(); + let moved = Xf::new(rect, &after).to_doc(at).distance(Xf::new(rect, &before).to_doc(at)); + (after.zoom / before.zoom, (after.center - before.center) * after.zoom, moved) + }; + use egui::{MouseWheelSource as S, MouseWheelUnit as U}; + let zooms_in = |(zoom, _, moved): (f64, _, f64)| zoom > 1.0005 && moved < 1e-6; + let zooms_by = |(zoom, _, moved): (f64, vectorcraft_geom::Vec2, f64), want: f64| (zoom / want - 1.0).abs() < 1e-6 && moved < 1e-6; + // `lines` wheel lines to the left. + let line = f64::from(ctx.options(|o| o.input_options.line_scroll_speed)); + let sideways = |(zoom, scroll, _): (f64, vectorcraft_geom::Vec2, f64), lines: f64| { + (zoom - 1.0).abs() < 1e-9 && (scroll.x + lines * line).abs() < 0.5 && scroll.y == 0.0 + }; + assert!(app.session.prefs.ctrl_wheel_scrolls_sideways, "the option is on by default"); + // A wheel message of 30 is a quarter of a 120 notch, and arrives as a quarter line. The zoom + // is exponential in the wheel's motion, so more motion in a turn multiplies the quarter's. + let small = turn(&mut app, vec![ev(U::Line, 0.25, S::Unknown)]); + assert!(zooms_in(small), "a line delta smaller than a notch zooms"); + let quarter = small.0; + assert!( + zooms_by(turn(&mut app, vec![ev(U::Line, 0.25, S::Unknown), ev(U::Line, 0.25, S::Unknown)]), quarter.powi(2)), + "several small deltas zoom" + ); + assert!( + zooms_by(turn(&mut app, vec![ev(U::Line, 0.25, S::Unknown), ev(U::Line, 1.0, S::Unknown)]), quarter.powi(5)), + "a whole notch in the same turn adds its zoom" + ); + let point = turn(&mut app, vec![ev(U::Point, 6.0, S::Unknown)]); + assert!(zooms_in(point), "point deltas of an unnamed source zoom"); + assert!(zooms_by(turn(&mut app, vec![ev(U::Point, 6.0, S::Trackpad)]), point.0), "a trackpad scroll zooms as far"); + assert!(zooms_by(turn(&mut app, vec![ev(U::Point, 6.0, S::Momentum)]), point.0), "its momentum zooms as far"); + assert!(sideways(turn(&mut app, vec![ev(U::Line, 1.0, S::Unknown)]), 1.0), "a whole notch scrolls sideways"); + assert!(sideways(turn(&mut app, vec![ev(U::Line, 2.0, S::Unknown)]), 2.0), "a turn of two notches scrolls sideways"); + assert!(sideways(turn(&mut app, vec![ev(U::Line, 0.25, S::Wheel)]), 0.25), "a part of a line from a named wheel scrolls sideways"); + // A turn ends when the wheel goes idle, so the next whole notch scrolls sideways again. + assert!(zooms_in(turn(&mut app, vec![ev(U::Line, 0.25, S::Unknown)])), "a touchpad turn"); + assert!(sideways(turn(&mut app, vec![ev(U::Line, 1.0, S::Unknown)]), 1.0), "the notch after it scrolls sideways"); + app.session.execute("prefs.set", &json!({"key": "zoomWithMouseWheel", "value": true})).unwrap(); + let small = turn(&mut app, vec![ev(U::Line, 0.25, S::Unknown)]); + assert!(zooms_in(small), "with Zoom with Mouse Wheel: a small line delta zooms"); + let quarter = small.0; + assert!( + zooms_by(turn(&mut app, vec![ev(U::Line, 0.25, S::Unknown), ev(U::Line, 1.0, S::Unknown)]), quarter.powi(5)), + "with Zoom with Mouse Wheel: a whole notch in the same turn adds its zoom" + ); + assert!(zooms_in(turn(&mut app, vec![ev(U::Point, 6.0, S::Trackpad)])), "with Zoom with Mouse Wheel: a trackpad scroll zooms"); + assert!(sideways(turn(&mut app, vec![ev(U::Line, 1.0, S::Unknown)]), 1.0), "with Zoom with Mouse Wheel: a whole notch scrolls sideways"); +} + +/// A wheel turn that a touchpad began ends with an End or Cancel phase, also in the frame the next +/// notch arrives, and after egui's scroll timeout with no frame in between. Under either +/// preference, the whole notch after it scrolls sideways. A notch inside the turn zooms. +#[test] +fn a_touchpad_wheel_turn_ends_with_its_end_phase_or_the_scroll_timeout() { + use egui::{MouseWheelSource as S, MouseWheelUnit as U, TouchPhase as P}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + let mut t = 0.0; + let frame_time = 1.0 / 60.0; + let mut run = |app: &mut VectorcraftApp, dt: f64, events: Vec| { + t += dt; + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), + time: Some(t), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + run(&mut app, frame_time, vec![]); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() + vec2(60.0, 40.0); + let line = f64::from(ctx.options(|o| o.input_options.line_scroll_speed)); + let ev = + |unit, dy: f32, phase, source| egui::Event::MouseWheel { unit, delta: vec2(0.0, dy), phase, modifiers: egui::Modifiers::COMMAND, source }; + // Point deltas zoom at once, so no glide is left when the next event comes. + let small = || ev(U::Point, 6.0, P::Move, S::Unknown); + let notch = || ev(U::Line, 1.0, P::Move, S::Unknown); + // A frame with a small delta, then `events` in one frame `dt` seconds later, and the wheel + // going idle: → (zoom ratio, scroll in points) since the small delta. + let mut turn = |app: &mut VectorcraftApp, dt: f64, events: Vec| { + run(app, frame_time, vec![egui::Event::PointerMoved(at)]); + run(app, frame_time, vec![small()]); + let before = *app.view().unwrap(); + run(app, dt, events); + for _ in 0..40 { + run(app, frame_time, vec![]); + } + let after = *app.view().unwrap(); + (after.zoom / before.zoom, (after.center - before.center) * after.zoom) + }; + let sideways = |(zoom, scroll): (f64, vectorcraft_geom::Vec2)| (zoom - 1.0).abs() < 1e-9 && (scroll.x + line).abs() < 0.5 && scroll.y == 0.0; + for wheel_zooms in [false, true] { + app.session.execute("prefs.set", &json!({"key": "zoomWithMouseWheel", "value": wheel_zooms})).unwrap(); + assert!(turn(&mut app, frame_time, vec![notch()]).0 > 1.01, "a notch inside the turn zooms ({wheel_zooms})"); + assert!( + turn(&mut app, frame_time, vec![ev(U::Point, 0.0, P::Start, S::Trackpad), notch()]).0 > 1.01, + "a Start phase does not end the turn ({wheel_zooms})" + ); + for phase in [P::End, P::Cancel] { + let r = turn(&mut app, frame_time, vec![ev(U::Point, 0.0, phase, S::Trackpad), notch()]); + assert!(sideways(r), "the notch after {phase:?} in the same frame scrolls sideways ({wheel_zooms}, {r:?})"); + } + let (zoom, scroll) = turn(&mut app, 0.2, vec![notch()]); + assert!( + (zoom - 1.0).abs() < 1e-9 && scroll.x < -1.0 && scroll.y == 0.0, + "the notch after the scroll timeout scrolls sideways ({wheel_zooms}, {zoom}, {scroll:?})" + ); + } +} + +/// Which wheel events count as a touchpad: a named trackpad or its momentum, never a named wheel, +/// and for an unnamed source, point deltas or line and page deltas more than 0.001 from a whole +/// number on either axis. +#[test] +fn fine_steps_tells_touchpad_input_from_whole_notches() { + use egui::{MouseWheelSource as S, MouseWheelUnit as U}; + for unit in [U::Point, U::Line, U::Page] { + for delta in [vec2(0.0, 1.0), vec2(0.0, 0.25), vec2(-1.5, 0.0)] { + assert!(view::fine_steps(unit, delta, S::Trackpad), "{unit:?} {delta:?} from a trackpad"); + assert!(view::fine_steps(unit, delta, S::Momentum), "{unit:?} {delta:?} from its momentum"); + assert!(!view::fine_steps(unit, delta, S::Wheel), "{unit:?} {delta:?} from a named wheel"); + } + } + assert!(view::fine_steps(U::Point, vec2(0.0, 1.0), S::Unknown), "whole points from an unnamed source"); + for unit in [U::Line, U::Page] { + for (x, y) in [(0.0, 0.25), (0.0, -0.25), (0.25, 1.0), (1.0, -0.5), (0.0, 0.002), (0.0, 0.998), (0.0, 1.002), (0.0, 1.0 / 120.0)] { + assert!(view::fine_steps(unit, vec2(x, y), S::Unknown), "{unit:?} ({x}, {y}) is finer than a notch"); + } + for (x, y) in [(0.0, 0.0), (0.0, 1.0), (0.0, -1.0), (0.0, 2.0), (-3.0, 1.0), (0.0, 0.9995), (0.0, 1.0005), (0.0, 0.0005)] { + assert!(!view::fine_steps(unit, vec2(x, y), S::Unknown), "{unit:?} ({x}, {y}) is a whole notch"); + } + } +} + /// With Scroll Sideways with Cmd/Ctrl + Wheel on and Animated Zoom off, Alt + Cmd-wheel zooms /// about the pointer by egui's Cmd-wheel zoom, as Cmd-wheel does with the option off, and /// Cmd-wheel alone scrolls sideways. @@ -10657,6 +11120,73 @@ fn direct_selection_shows_the_bounding_box_while_cmd_is_held() { assert!(app.ui.view.bounding_box, "View › Show Bounding Box is unchanged"); } +/// An edit to a 3D effect renders the part it changed on this thread, measured by the renderer +/// that drew the frame shown ([`vectorcraft_render::Renderer::changed`]): it draws the part with +/// the 3D art it made to measure it. +#[test] +fn an_edit_to_a_3d_effect_redraws_with_the_art_measured() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + app.canvas.worker_started = true; // render on this thread + let id = app.run("shape.rectangle", json!({"x": 380, "y": 280, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "ids": [id], "params": {"depth": 60.0}})).unwrap(); + let ctx = egui::Context::default(); + shapes(&mut app, &ctx); + assert_eq!(app.canvas.renderer.stats.three_d_built, 1, "the whole frame made the art"); + app.run("effect.setParams", json!({"ids": [id], "index": 0, "item": null, "params": {"depth": 5.0}})).unwrap(); + // Drawing only a part keeps the whole frame's time; drawing it whole measures it again. + app.canvas.last_ms = 7.25; + shapes(&mut app, &ctx); + assert!(!app.canvas.from_worker); + assert_eq!(app.canvas.last_ms, 7.25, "only the part that changed was drawn"); + assert_eq!(app.canvas.renderer.stats.three_d_built, 0, "the part was drawn with the art made to measure the edit"); +} + +/// An edit to a 3D effect off the view, and one the render worker draws, leave none of the art made +/// to measure them held by this thread's renderer. +#[test] +fn art_measured_for_an_edit_not_drawn_here_is_let_go() { + for worker in [false, true] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + app.canvas.worker_started = true; // render on this thread + // Off the view, or filling it, for the worker to draw. + let (x, size) = if worker { (0, 800) } else { (5000, 40) }; + let id = app.run("shape.rectangle", json!({"x": x, "y": 0, "width": size, "height": size})).unwrap()["id"].clone(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "ids": [id], "params": {"depth": 60.0}})).unwrap(); + let ctx = egui::Context::default(); + shapes(&mut app, &ctx); + // A worker whose jobs the test receives: none finishes unless the test says so. + let mut jobs = None; + if worker { + let (w, rx, done) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(w); + jobs = Some((rx, done)); + app.canvas.last_ms = 100.0; + } + app.run("effect.setParams", json!({"ids": [id], "index": 0, "item": null, "params": {"depth": 5.0}})).unwrap(); + // Measured through the canvas's renderer, the edit holds the art made for it. + let (shown, opts) = app.canvas.shown.clone().unwrap(); + let now = app.session.active().unwrap().doc.clone(); + app.canvas.renderer.changed(&shown, &now, &opts); + assert!(app.canvas.renderer.measured_bytes() > 0, "worker {worker}: art held"); + if !worker { + app.canvas.last_ms = 7.25; + } + shapes(&mut app, &ctx); + if !worker { + // Nothing in view to draw: no frame, whole or part, began since the measure. + assert_eq!(app.canvas.last_ms, 7.25, "not drawn whole"); + assert!(app.canvas.renderer.stats.three_d_built > 0, "no part drawn"); + } + if let Some((rx, _)) = &jobs { + assert!(rx.try_recv().is_ok(), "the worker draws it"); + } + assert_eq!(app.canvas.renderer.measured_bytes(), 0, "worker {worker}"); + app.canvas.worker = None; + } +} + /// The real canvas decision must stay visible without a native host, with no painted glyph. #[cfg(target_os = "macos")] #[test] diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index b90af09a4b..67f6ac861a 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -144,13 +144,7 @@ pub(super) fn spelling_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: } walk(&st.doc.layers, &mut |n| { let NodeKind::Text(tx) = &n.kind else { return }; - // An effect on the type or on one of its fills or strokes, shown (the Appearance panel's - // eye): the helpx page's "Auto spell check isn't available for text with effects applied". - let shown = |fx: &[vectorcraft_doc::Effect]| fx.iter().any(|e| e.visible); - if shown(&n.appearance.effects) - || n.appearance.items.iter().any(|i| shown(i.effects())) - || n.geometric_bounds().is_none_or(|b| !egui::Rect::from_points(&xf.quad(b)).intersects(clip)) - { + if !auto_spell_checks(n) || n.geometric_bounds().is_none_or(|b| !egui::Rect::from_points(&xf.quad(b)).intersects(clip)) { return; } let lines = match last.remove(&n.id) { @@ -164,6 +158,85 @@ pub(super) fn spelling_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: }); } +/// Whether Auto Spell Check marks `n`'s words: not with an effect shown (the Appearance panel's +/// eye) on the type or on one of its fills or strokes, as the helpx page says "Auto spell check +/// isn't available for text with effects applied". +fn auto_spell_checks(n: &Node) -> bool { + let shown = |fx: &[vectorcraft_doc::Effect]| fx.iter().any(|e| e.visible); + !shown(&n.appearance.effects) && !n.appearance.items.iter().any(|i| shown(i.effects())) +} + +/// The word with Auto Spell Check's red line at `p` (document space): in the topmost visible type +/// object whose glyphs `p` is on, when that object isn't locked and Auto Spell Check marks it and +/// its word at `p` is one it underlines, with what its language's dictionary suggests instead. For the context menu's suggestions, Ignore All and Add +/// to Dictionary ([Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html)). +pub(crate) fn misspelled_word_at(app: &mut VectorcraftApp, p: Point) -> Option { + let st = app.session.active()?; + // The topmost type whose glyphs `p` is on, and whether it or a layer or group holding it is + // locked: a word under other type isn't the one right-clicked, whether that type's word there + // is right or not. + let mut top: Option<(vectorcraft_doc::NodeId, bool)> = None; + // Back to front as drawn at `p`: an Intertwine group's members by their tier there, those of + // one tier in their stacking order ([`vectorcraft_doc::intertwine`]). + fn walk(nodes: &[std::sync::Arc], p: Point, locked: bool, f: &mut impl FnMut(&Node, bool)) { + for n in nodes.iter().filter(|n| n.visible) { + let locked = locked || n.locked; + f(n, locked); + let Some(children) = n.children() else { continue }; + if matches!(n.kind, NodeKind::Intertwine { .. }) { + let mut drawn = children.to_vec(); + drawn.sort_by_key(|c| vectorcraft_doc::intertwine::tier_at(c, p)); + walk(&drawn, p, locked, f); + } else { + walk(children, p, locked, f); + } + } + } + // A later hit is on top. + walk(&st.doc.layers, p, false, &mut |n, locked| { + let NodeKind::Text(tx) = &n.kind else { return }; + if n.geometric_bounds().is_none_or(|b| !b.contains(p)) { + return; + } + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx); + let on = vectorcraft_text::selection_quads(&lay, 0, tx.plain_text().len()).iter().any(|q| in_quad(q.map(|c| tx.xf * c), p)); + if on { + top = Some((n.id, locked)); + } + }); + let (id, locked) = top?; + let n = st.doc.node(id)?; + let NodeKind::Text(tx) = &n.kind else { return None }; + if locked || !auto_spell_checks(n) { + return None; + } + let (words, _) = vectorcraft_engine::cmd::spelling::misspellings(tx, &st.spelling_ignored, MAX_UNDERLINED); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx); + let w = words + .into_iter() + .find(|w| vectorcraft_text::selection_quads(&lay, w.range.start, w.range.end).iter().any(|q| in_quad(q.map(|c| tx.xf * c), p)))?; + let word = tx.plain_text().get(w.range.clone())?.to_string(); + let uid = st.uid; + let suggestions = app + .session + .execute("text.spelling.suggest", &serde_json::json!({ "word": word, "lang": w.lang.tag() })) + .ok() + .and_then(|r| r.get("suggestions").and_then(|s| s.as_array()).map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect())) + .unwrap_or_default(); + Some(crate::state::ContextSpelling { uid, id, start: w.range.start, end: w.range.end, word, suggestions }) +} + +/// Whether `p` is inside the convex quad `q` (its corners in order, either way round) or on its +/// edge. +fn in_quad(q: [Point; 4], p: Point) -> bool { + let sides = (0..4).map(|i| { + let (a, b) = (q[i], q[(i + 1) % 4]); + (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) + }); + let sides: Vec = sides.collect(); + sides.iter().all(|s| *s >= 0.0) || sides.iter().all(|s| *s <= 0.0) +} + /// The most words underlined in one text object: past it the rest of the object isn't checked, /// so a long story of unknown words costs one check's worth. const MAX_UNDERLINED: usize = 1_000; diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index 39bc805453..60cb6687b4 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -1,6 +1,16 @@ use super::drag::{drag_id, drop_press}; use super::{CornerRadius, Drag, Point, Pos2, Rect, SCROLL_BAR, Sense, Stroke, Tokens, Ui, VectorcraftApp, View, Xf, pos2, vec2}; +/// The mouse and control-channel Rotate View gestures use the same angle and Shift snapping. +pub(crate) fn drag_rotation(center: Pos2, point: Pos2, start_angle: f64, start_rotation: f64, snap: bool) -> f64 { + let angle = (point.y - center.y).atan2(point.x - center.x) as f64; + let mut degrees = start_rotation + (angle - start_angle).to_degrees(); + if snap { + degrees = (degrees / 15.0).round() * 15.0; + } + vectorcraft_geom::normalize_deg(degrees) +} + /// Fit the view (View → Fit Artboard / Fit All / Actual Size, Arrange Tools › Zoom to Selection). pub fn fit(app: &mut VectorcraftApp, how: &str) { let Some(rect) = app.canvas_rect else { @@ -65,6 +75,9 @@ pub(super) struct WheelTurn { /// When the last wheel event came (`InputState::time`), and whether a trackpad sent it. last: f64, trackpad: bool, + /// A wheel event of this turn came from a touchpad ([`fine_steps`]), so Cmd/Ctrl zooms for the + /// rest of the turn, also through a whole notch. + fine: bool, /// The zoom (natural log) wheel notches still have to glide in. pub(super) glide: f64, } @@ -351,11 +364,26 @@ struct ThumbDrag { max: f32, } +/// Whether a wheel event comes from a touchpad and not from a mouse wheel's notches. egui names +/// the source on the Mac and reports `Unknown` elsewhere. There, point deltas (Wayland) and line +/// deltas that are not whole notches (Windows and X11) count as a touchpad. A browser reports a +/// mouse wheel in points, so the web build counts only line deltas that are not whole notches. +pub(super) fn fine_steps(unit: egui::MouseWheelUnit, delta: egui::Vec2, source: egui::MouseWheelSource) -> bool { + let notch = |d: f32| (d - d.round()).abs() < 1e-3; + match source { + egui::MouseWheelSource::Trackpad | egui::MouseWheelSource::Momentum => true, + egui::MouseWheelSource::Wheel => false, + egui::MouseWheelSource::Unknown if unit == egui::MouseWheelUnit::Point => !cfg!(target_arch = "wasm32"), + egui::MouseWheelSource::Unknown => !notch(delta.x) || !notch(delta.y), + } +} + /// What the wheel, a pinch and a two-finger drag on a touch screen did over the canvas this frame: /// a zoom factor (about the pointer) and a scroll (screen points the content moves). The wheel scrolls, Cmd- and Alt-wheel (Option /// on the Mac) zoom; with General › Scroll Sideways with Cmd/Ctrl + Wheel, Cmd/Ctrl-wheel scrolls /// sideways instead, and Alt + Cmd/Ctrl-wheel still zooms. With General › Zoom with Mouse Wheel the -/// wheel and Alt-wheel zoom, Shift-wheel scrolls up and down and Cmd/Ctrl-wheel sideways. `line` and `page`: points +/// wheel and Alt-wheel zoom, Shift-wheel scrolls up and down and Cmd/Ctrl-wheel sideways. Cmd/Ctrl +/// with a touchpad ([`fine_steps`]) zooms under either preference. `line` and `page`: points /// per wheel line and page. `turn`: kept by the caller across frames. With Performance › Animated /// Zoom (`animate`) a mouse wheel's notches zoom in a glide over a few frames, as scrolling does /// (#888); off, each notch zooms on the frame it arrives (#4283). A trackpad's fine steps zoom at @@ -385,7 +413,7 @@ pub(super) fn wheel( // `turn.alt` follows `turn.held` after each Start or Move, so a trackpad gesture that held // Alt keeps zooming until it ends, also after Alt is let go. for e in &i.events { - if let egui::Event::MouseWheel { phase, modifiers, source, .. } = e { + if let egui::Event::MouseWheel { unit, delta, phase, modifiers, source, .. } = e { // A wheel event that comes after egui's scroll timeout ends the turn first, as // `on_wheel_event` does (1 s for fingers resting on a trackpad mid-gesture, else // 0.15 s), also when no frame ran in between. @@ -393,9 +421,11 @@ pub(super) fn wheel( if i.time - turn.last > timeout { turn.gesture = false; turn.held = egui::Modifiers::NONE; + turn.fine = false; } turn.last = i.time; turn.trackpad = *source == egui::MouseWheelSource::Trackpad; + turn.fine |= fine_steps(*unit, *delta, *source); match phase { egui::TouchPhase::Start => { turn.gesture = true; @@ -413,6 +443,7 @@ pub(super) fn wheel( egui::TouchPhase::End | egui::TouchPhase::Cancel => { turn.gesture = false; turn.held = egui::Modifiers::NONE; + turn.fine = false; } } } @@ -420,6 +451,7 @@ pub(super) fn wheel( if !i.is_scrolling() { turn.gesture = false; turn.held = egui::Modifiers::NONE; + turn.fine = false; } let (mut zoom, mut scroll) = (f64::from(i.zoom_delta()), i.smooth_scroll_delta); // Scroll Sideways with Cmd/Ctrl + Wheel: while egui's wheel state holds Cmd/Ctrl without @@ -427,7 +459,7 @@ pub(super) fn wheel( // default speed, which the app keeps. The canvas scrolls sideways by those points instead. // A trackpad or web pinch still zooms. With fingers on a touch screen, egui's zoom is the // fingers' alone, and the canvas leaves it as it is. - if prefs.ctrl_wheel_scrolls_sideways && turn.held.command && !turn.held.alt && i.multi_touch().is_none() { + if prefs.ctrl_wheel_scrolls_sideways && turn.held.command && !turn.held.alt && !turn.fine && i.multi_touch().is_none() { let pinch: f64 = i.events.iter().filter_map(|e| if let egui::Event::Zoom(f) = e { Some(f64::from(*f)) } else { None }).product(); let wheel_zoom = zoom / pinch; if wheel_zoom.is_finite() && wheel_zoom > 0.0 { @@ -461,9 +493,15 @@ pub(super) fn wheel( let mut scroll = pan; for e in &i.events { match e { - egui::Event::MouseWheel { unit, delta, modifiers, .. } => { + egui::Event::MouseWheel { unit, delta, phase, modifiers, source, .. } => { let d = points(unit, *delta); - if modifiers.command { + // The turn ends after egui's scroll timeout, as above. + if i.time - turn.last > 0.150 { + turn.fine = false; + } + turn.last = i.time; + turn.fine |= fine_steps(*unit, *delta, *source); + if modifiers.command && !turn.fine { scroll.x += d.x + d.y; } else if modifiers.shift { scroll.y += d.x + d.y; @@ -474,6 +512,9 @@ pub(super) fn wheel( turn.glide += f64::from(d.y) * WHEEL_ZOOM; scroll.x += d.x; } + if matches!(phase, egui::TouchPhase::End | egui::TouchPhase::Cancel) { + turn.fine = false; + } } egui::Event::Zoom(f) => zoom *= f64::from(*f), _ => {} diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 9fbd02327b..8995080215 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -179,12 +179,18 @@ pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) { } right = left - gap; } - let busy: Vec<&str> = app - .background - .jobs - .iter() - .filter(|j| !j.label.is_empty() && !j.cancelled()) - .map(|j| j.label.as_str()) + let script = app.session.script_running().then_some("Running a script"); + if script.is_some() { + let left = (right - 52.0).max(area.left()); + let stop = egui::Rect::from_min_max(egui::pos2(left, area.top() + 1.0), egui::pos2(right, area.bottom() - 1.0)); + if ui.put(stop, egui::Button::new(tl!("Stop")).small()).clicked() { + app.session.script_interrupt().set(); + } + right = left - gap; + } + let busy: Vec<&str> = script + .into_iter() + .chain(app.background.jobs.iter().filter(|j| !j.label.is_empty() && !j.cancelled()).map(|j| j.label.as_str())) .chain(app.opening.pending.iter().map(|p| p.label.as_str())) .chain(app.placing.pending.iter().map(|p| p.label.as_str())) .collect(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6af51d95a3..419d4ab903 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -234,6 +234,8 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { fields.remove("floating_panels"); } json!({ + "scriptRunning": app.session.script_running(), + "scriptReport": app.session.script_report(), "tool": app.session.tool_id(), "toolOptions": app.session.tool_options(), "ui": ui, @@ -608,10 +610,116 @@ pub(crate) fn save_screenshot_with_limit( #[cfg(test)] mod tests; +/// The window and coordinate mapping where a control-channel Rotate View drag began. +#[derive(Clone, Copy)] +pub(crate) struct RotateViewPress { + window: (u64, u32), + document_resets: u64, + xf: Xf, + start_angle: f64, + start_rotation: f64, +} + +/// Rotate View belongs to the canvas, not the engine's placeholder tool. Keep its press mapping +/// across requests so document-coordinate drags do not move again as the view turns underneath. +fn rotate_view_pointer( + app: &mut VectorcraftApp, + kind: PointerKind, + position: vectorcraft_geom::Point, + screen: bool, + shift: bool, +) -> Result<(), String> { + let window = app.session.active().zip(crate::doc_windows::current(app)).map(|(d, w)| (d.uid, w.1)).ok_or("no document")?; + let document_resets = app.session.tool_resets(); + let stored = if kind == PointerKind::Down { None } else { app.control_rotate_press }; + if kind == PointerKind::Drag && stored.is_none() { + return Err("Rotate View needs a down event before a drag".into()); + } + let mut press = match stored { + Some(press) => press, + None => { + let rect = app.canvas_rect.ok_or("no canvas yet")?; + let view = app.view().ok_or("no document")?; + RotateViewPress { window, document_resets, xf: Xf::new(rect, view), start_angle: 0.0, start_rotation: view.rotation } + } + }; + // A gesture cannot turn a different document/view or resume after its document was reset. + if (press.window, press.document_resets) != (window, document_resets) { + return Err("the Rotate View gesture's window or document changed".into()); + } + let point = if screen { egui::pos2(position.x as f32, position.y as f32) } else { press.xf.to_screen(position) }; + let center = press.xf.rect.center(); + if !point.is_finite() || !center.is_finite() { + return Err("Rotate View needs finite canvas coordinates".into()); + } + match kind { + PointerKind::Down => { + press.start_angle = (point.y - center.y).atan2(point.x - center.x) as f64; + app.control_rotate_press = Some(press); + } + PointerKind::Drag => { + app.view_mut().ok_or("no document")?.rotation = + crate::canvas::drag_rotation(center, point, press.start_angle, press.start_rotation, shift); + } + PointerKind::Up => { + app.control_rotate_press = None; + } + PointerKind::Move | PointerKind::DoubleClick => {} + } + Ok(()) +} + +/// A Rotate View packet accepts only the documented boolean modifier fields. +fn validate_rotate_view_mods(value: Option<&Value>) -> Result<(), String> { + let Some(value) = value else { return Ok(()) }; + let Some(fields) = value.as_object() else { return Err("Rotate View `mods` must be an object of booleans".into()) }; + if fields.iter().any(|(key, value)| !matches!(key.as_str(), "shift" | "alt" | "cmd" | "ctrl" | "space") || !value.is_boolean()) { + return Err("Rotate View `mods` accepts only boolean shift, alt, cmd, ctrl and space".into()); + } + Ok(()) +} + +/// Reject malformed coordinates and modifiers before any event can change the angle or press. +fn validate_rotate_view_events(params: &Value, events: &[Value]) -> Result<(), String> { + validate_rotate_view_mods(params.get("mods"))?; + for event in events { + for axis in ["x", "y"] { + if event.get(axis).and_then(Value::as_f64).filter(|value| value.is_finite()).is_none() { + return Err(format!("Rotate View `{axis}` must be a finite number")); + } + } + validate_rotate_view_mods(event.get("mods"))?; + if event.get("space").is_some_and(|space| !matches!(space.as_str(), Some("doc" | "screen"))) { + return Err("Rotate View `space` must be doc or screen".into()); + } + } + Ok(()) +} + /// `ui.pointer`: pointer events through the tools. fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + let rotating = app.session.tool_id() == "rotateView"; + let before = if rotating { app.view().map(|view| view.rotation) } else { None }; + let outcome = pointer_events_inner(app, ctx, req); + if rotating && matches!(&outcome, Outcome::Done(reply) if reply.get("ok").and_then(Value::as_bool) == Some(false)) { + // A failed packet must neither leave a partial turn nor allow a later drag to resume it. + app.control_rotate_press = None; + if let (Some(before), Some(view)) = (before, app.view_mut()) { + view.rotation = before; + } + ctx.request_repaint(); + } + outcome +} + +/// Apply a pointer packet after Rotate View validation; other tools retain their existing routing. +fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { let p = &req.params; let Some(events) = p.get("events").and_then(Value::as_array) else { return err("missing `events`") }; + let rotating = app.session.tool_id() == "rotateView"; + if rotating && let Err(error) = validate_rotate_view_events(p, events) { + return err(error); + } let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); let view = app.view_info(); let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v)); @@ -634,6 +742,13 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.0); let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.0); let screen = e.get("space").and_then(Value::as_str) == Some("screen"); + let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base_mods); + if rotating { + if let Err(e) = rotate_view_pointer(app, kind, vectorcraft_geom::Point::new(x, y), screen, mods.shift) { + return err(e); + } + continue; + } let pos = if screen { match xf { Some(xf) => xf.to_doc(egui::pos2(x as f32, y as f32)), @@ -642,7 +757,6 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe } else { vectorcraft_geom::Point::new(x, y) }; - let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base_mods); // A tilt given in screen axes leans the same way on the page as on the screen. let pen = PointerEvent::json_pen(e).map(|q| match xf { Some(xf) if screen => crate::canvas::pose_on_page(q, &xf), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1f59647c13..38ccc908d8 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -26,6 +26,7 @@ mod command; pub mod composite_fonts; pub mod confirm; pub mod corners; +pub mod custom_dictionary; pub mod dimension; mod document_setup; mod duotone; @@ -109,6 +110,7 @@ pub mod save_style_library; pub mod save_swatch_library; pub mod save_symbol_library; pub mod script_check; +pub mod script_run; pub mod shape_builder_options; pub(crate) mod shapes; pub mod shortcut_import; @@ -152,8 +154,8 @@ pub(crate) use export_for_screens::{ saved_options as screen_saved_options, saved_rows as screen_saved_rows, }; pub(crate) use form::{humanize, number_list_text, plugin_color_button, read_number_list, unit_suffix}; -pub(crate) use new_document::preset_name; pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card}; +pub(crate) use new_document::{popup_open as new_document_popup_open, preset_name}; pub use png_options::open as open_raster_options; pub use save_pdf::{open as open_save_pdf, open_preset as open_pdf_preset}; pub use tools::open_tool_dialog; @@ -404,6 +406,9 @@ registry! { PluginImport: [plugin::IMPORT_KIND] => plugin::IMPORT_SPEC, PluginInstall: [plugin::INSTALL_KIND] => plugin::INSTALL_SPEC, ScriptCheck: [script_check::KIND] => script_check::SPEC, + ScriptRun: [script_run::KIND] => script_run::SPEC, + ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC, + ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, @@ -428,6 +433,7 @@ registry! { NewBrush: [new_brush::KIND] => new_brush::SPEC, EditSelection: [edit_selection::KIND] => edit_selection::SPEC, EditViews: [edit_views::KIND] => edit_views::SPEC, + EditCustomDictionary: [custom_dictionary::KIND] => custom_dictionary::SPEC, PerspectivePlane: [perspective_plane::KIND] => perspective_plane::SPEC, LayerOptions: [layer_options::KIND] => layer_options::SPEC, LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC, @@ -560,6 +566,10 @@ pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Valu /// opened over (`ui.dialog.cancel`). pub fn cancel(app: &mut VectorcraftApp) { missing_fonts::requeue_replaced(app); + // More Settings' pop-up and Save Preset end on their own; New Document stays. + if app.ui.dialog.as_mut().is_some_and(new_document::close_popup) { + return; + } if let Some(d) = app.ui.dialog.take() { if d.kind == swatch_conflict::KIND { crate::placing::cancel_swatch_paste(app); @@ -570,6 +580,10 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == safe_mode::STOPPED { safe_mode::cancel_stopped(app); } + // The growth question's Cancel button is its Stop button. + if d.kind == script_run::GROWTH_KIND { + app.session.script_request_stop(); + } // Toolbar-only Flare options start no preview and must not cancel a gesture // that was already active before opening them. The generic parameter dialog has a spec // without a preview, yet previews some commands (Grid Repeat Options) when asked to. diff --git a/crates/ui-egui/src/dialogs/custom_dictionary.rs b/crates/ui-egui/src/dialogs/custom_dictionary.rs new file mode 100644 index 0000000000..8a61f7095d --- /dev/null +++ b/crates/ui-egui/src/dialogs/custom_dictionary.rs @@ -0,0 +1,334 @@ +//! Edit › Edit Custom Dictionary…: the custom dictionary's words in a list, with an Entry field and +//! Add, Delete and Change, as the public +//! [Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html) +//! page describes it: enter a word and Add it, select a word and Delete it, or select a word, edit it +//! in the Entry field and Change it. Nothing changes until Done, which deletes and adds the words +//! that differ in one `text.spelling.editDictionary`, all or none; Cancel leaves the dictionary as +//! it was. +//! +//! Fields: `orig` (the words when the dialog opened), `words` (as edited, sorted), `entry` (the +//! Entry field) and `selected` (the word picked, or null). + +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::spelling::custom_word; + +use super::{DialogSpec, form}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Edit Custom Dictionary. +pub const KIND: &str = "editCustomDictionary"; + +/// The command its menu item runs: with no params, it opens this dialog. +pub const COMMAND: &str = "text.spelling.dictionary"; + +/// The command Done runs: every delete and add, saved once. +const EDIT: &str = "text.spelling.editDictionary"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Edit Custom Dictionary").into(), body, confirm, ok: Some("Done"), min_width: 420.0, ..DialogSpec::FORM }; + +/// Open Edit Custom Dictionary on the custom dictionary's words. +pub fn open(app: &mut VectorcraftApp) -> Result { + let words = app.run(COMMAND, json!({})).map_err(|e| e.to_string())?.get("words").cloned().unwrap_or_else(|| json!([])); + app.ui.dialog = Some(Dialog::new(KIND, json!({ "orig": words, "words": words, "entry": "", "selected": null }))); + Ok(Value::Null) +} + +fn list(d: &Dialog, key: &str) -> Vec { + d.fields.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()).unwrap_or_default() +} + +/// The word picked in the list, while it is still there. +fn selected(d: &Dialog, words: &[String]) -> Option { + d.fields.get("selected").and_then(Value::as_str).filter(|w| words.iter().any(|x| x == w)).map(String::from) +} + +/// What the buttons can do now: the Entry field as a dictionary word that isn't in the list yet +/// (for Add and Change), and the word picked (for Delete and Change). +fn actions(d: &Dialog) -> (Option, Option) { + let words = list(d, "words"); + let entry = custom_word(&d.str("entry")).filter(|w| !words.contains(w)); + (entry, selected(d, &words)) +} + +fn set_words(d: &mut Dialog, mut words: Vec, selected: Option<&str>) { + words.sort(); + words.dedup(); + d.fields.insert("words".into(), json!(words)); + d.fields.insert("selected".into(), json!(selected)); +} + +/// Add: the Entry field's word joins the list, picked. +fn add(d: &mut Dialog) { + let (Some(w), _) = actions(d) else { return }; + let mut words = list(d, "words"); + words.push(w.clone()); + set_words(d, words, Some(&w)); +} + +/// Delete: the word picked leaves the list; the one after it (or before, for the last) is picked. +fn delete(d: &mut Dialog) { + let (_, Some(w)) = actions(d) else { return }; + let mut words = list(d, "words"); + let Some(i) = words.iter().position(|x| *x == w) else { return }; + words.remove(i); + let next = words.get(i).or_else(|| words.last()).cloned(); + if let Some(n) = &next { + d.fields.insert("entry".into(), json!(n)); + } + set_words(d, words, next.as_deref()); +} + +/// Change: the word picked becomes the Entry field's word. +fn change(d: &mut Dialog) { + let (Some(to), Some(w)) = actions(d) else { return }; + let mut words: Vec = list(d, "words").into_iter().filter(|x| *x != w).collect(); + words.push(to.clone()); + set_words(d, words, Some(&to)); +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let words = list(d, "words"); + let current = selected(d, &words); + let (entry, picked) = actions(d); + let mut pick = None; + let (mut added, mut deleted, mut changed) = (false, false, false); + widgets::dim_label(ui, tl!("Entry:")); + form::text(ui, d, "entry", 380.0); + ui.add_space(8.0); + ui.horizontal_top(|ui| { + widgets::list_box(ui, |ui| { + ui.set_width(260.0); + let row = ui.spacing().interact_size.y; + egui::ScrollArea::vertical().id_salt("custom-dictionary").min_scrolled_height(200.0).max_height(200.0).show_rows( + ui, + row, + words.len(), + |ui, range| { + ui.set_width(ui.available_width()); + for w in words.get(range).unwrap_or_default() { + if ui.selectable_label(current.as_ref() == Some(w), w.as_str()).clicked() { + pick = Some(w.clone()); + } + } + }, + ); + }); + ui.add_space(16.0); + ui.vertical(|ui| { + added = ui.add_enabled_ui(entry.is_some(), |ui| widgets::flat_button(ui, tl!("Add"), 90.0).clicked()).inner; + ui.add_space(6.0); + deleted = ui.add_enabled_ui(picked.is_some(), |ui| widgets::flat_button(ui, tl!("Delete"), 90.0).clicked()).inner; + ui.add_space(6.0); + changed = ui.add_enabled_ui(entry.is_some() && picked.is_some(), |ui| widgets::flat_button(ui, tl!("Change"), 90.0).clicked()).inner; + }); + }); + // Picking a word puts it in the Entry field, to edit for Change. + if let Some(w) = pick { + d.fields.insert("entry".into(), json!(w)); + d.fields.insert("selected".into(), json!(w)); + } + if added { + add(d); + } else if deleted { + delete(d); + } else if changed { + change(d); + } + false +} + +/// Done: deletes the words no longer in the list and adds the new ones in one +/// `text.spelling.editDictionary`, saved once. When it can't be saved, none of it is kept: the +/// dialog stays open with the error, its list as edited, and Cancel leaves the dictionary as it was. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let (orig, words) = (list(d, "orig"), list(d, "words")); + let remove: Vec<&String> = orig.iter().filter(|w| !words.contains(w)).collect(); + let add: Vec<&String> = words.iter().filter(|w| !orig.contains(w)).collect(); + app.run(EDIT, json!({ "remove": remove, "add": add })).map_err(|e| e.to_string())?; + app.ui.dialog = None; + Ok(Value::Null) +} + +#[cfg(test)] +mod tests { + use egui::{Event, PointerButton, Pos2, Rect, vec2}; + use serde_json::{Value, json}; + + use crate::VectorcraftApp; + + // The custom dictionary is the whole process's: each test here uses words no other test does. + const A: &str = "zqvdicta"; + const B: &str = "zqvdictb"; + const M: &str = "zqvdictm"; + const X: &str = "zqvdictx"; + const Y: &str = "zqvdicty"; + + fn app() -> VectorcraftApp { + VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()) + } + + fn has(app: &mut VectorcraftApp, w: &str) -> bool { + app.run("text.spelling.dictionary", json!({})).unwrap()["words"].as_array().unwrap().contains(&json!(w)) + } + + fn forget(app: &mut VectorcraftApp, words: &[&str]) { + for w in words { + let _ = app.run("text.spelling.removeWord", json!({ "word": w })); + } + } + + fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + } + + /// The dialog's list, of `mine` (other tests may have their words in the dictionary meanwhile). + fn words(app: &VectorcraftApp, mine: &[&str]) -> Vec { + super::list(app.ui.dialog.as_ref().unwrap(), "words").into_iter().filter(|w| mine.contains(&w.as_str())).collect() + } + + /// One frame of the dialog on an 800 × 600 window → the text painted, with its rect. + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Rect)> { + // A window takes a sizing frame and fades in: each frame is a quarter second on. + let time = ctx.input(|i| i.time) + 0.25; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v + } + + fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + } + + fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> Vec<(String, Rect)> { + frame(app, ctx, vec![]); + let texts = frame(app, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(at)]); + frame(app, ctx, vec![press(true)]); + frame(app, ctx, vec![press(false)]); + frame(app, ctx, vec![]) + } + + /// Edit › Edit Custom Dictionary… (beside Spelling, as the public page has it) opens the + /// dialog on the custom dictionary's words. + #[test] + fn the_edit_menu_opens_it_on_the_custom_dictionary() { + let mut app = app(); + forget(&mut app, &[M]); + app.run("text.spelling.addWord", json!({ "word": M })).unwrap(); + let e = crate::menus::menu_entries(&app).into_iter().find(|e| e.label == "Edit Custom Dictionary…").expect("in the Edit menu"); + assert_eq!((e.path.as_slice(), e.command.as_deref(), e.enabled), (&["Edit".to_string()][..], Some(super::COMMAND), true)); + crate::menus::invoke(&mut app, super::COMMAND, json!({})); + let d = app.ui.dialog.as_ref().expect("Edit Custom Dictionary opens"); + assert_eq!(d.kind, super::KIND); + assert_eq!(words(&app, &[M]), [M]); + forget(&mut app, &[M]); + } + + /// Add, Delete and Change edit the list; nothing changes in the dictionary until Done, which + /// applies them; Cancel leaves it as it was. + #[test] + fn add_delete_and_change_apply_on_done() { + let mut app = app(); + forget(&mut app, &[A, B, "zqvdictc"]); + app.run("text.spelling.addWord", json!({ "word": A })).unwrap(); + super::open(&mut app).unwrap(); + let ctx = context(); + // Add: the Entry field's word (kept in lower case) joins the list. + set(&mut app, "entry", json!(" ZqvDictB ")); + click(&mut app, &ctx, "Add"); + assert_eq!(words(&app, &[A, B, "zqvdictc"]), [A, B]); + assert!(!has(&mut app, B), "not until Done"); + // Change: pick A, edit it in the Entry field. + set(&mut app, "selected", json!(A)); + set(&mut app, "entry", json!("zqvdictc")); + click(&mut app, &ctx, "Change"); + assert_eq!(words(&app, &[A, B, "zqvdictc"]), [B, "zqvdictc"]); + // Delete the word picked. + set(&mut app, "selected", json!(B)); + click(&mut app, &ctx, "Delete"); + assert_eq!(words(&app, &[A, B, "zqvdictc"]), ["zqvdictc"]); + // Cancel: the dictionary is as it was. + crate::dialogs::cancel(&mut app); + assert!(has(&mut app, A) && !has(&mut app, B) && !has(&mut app, "zqvdictc")); + // Again, then Done. + super::open(&mut app).unwrap(); + set(&mut app, "selected", json!(A)); + set(&mut app, "entry", json!("zqvdictc")); + click(&mut app, &ctx, "Change"); + set(&mut app, "entry", json!(B)); + click(&mut app, &ctx, "Add"); + click(&mut app, &ctx, "Done"); + assert!(app.ui.dialog.is_none(), "Done closes it"); + assert!(!has(&mut app, A) && has(&mut app, B) && has(&mut app, "zqvdictc")); + forget(&mut app, &[A, B, "zqvdictc"]); + } + + /// Done that can't be saved keeps none of the edits: the dialog stays open with the error and + /// Cancel leaves the dictionary as it was. + #[test] + fn a_done_that_cant_be_saved_changes_nothing() { + const P: &str = "zqvdictp"; + const Q: &str = "zqvdictq"; + let mut app = app(); + forget(&mut app, &[P, Q]); + app.run("text.spelling.addWord", json!({ "word": P })).unwrap(); + let folder = vectorcraft_testkit::temp_dir("custom-dictionary-done").join("Custom Dictionary.txt"); + std::fs::create_dir_all(&folder).unwrap(); + let mut failing = self::app(); + failing.session.attach_custom_dictionary(folder); + super::open(&mut failing).unwrap(); + let ctx = context(); + set(&mut failing, "selected", json!(P)); + click(&mut failing, &ctx, "Delete"); + set(&mut failing, "entry", json!(Q)); + click(&mut failing, &ctx, "Add"); + assert_eq!(words(&failing, &[P, Q]), [Q]); + click(&mut failing, &ctx, "Done"); + assert!(failing.ui.dialog.is_some(), "the dialog stays open with the error"); + assert!(has(&mut app, P) && !has(&mut app, Q), "neither the delete nor the add is kept"); + crate::dialogs::cancel(&mut failing); + assert!(has(&mut app, P) && !has(&mut app, Q)); + forget(&mut app, &[P, Q]); + } + + /// Add and Change need one word that isn't in the list yet; Delete and Change need a word + /// picked. A button that can't act does nothing. + #[test] + fn the_buttons_act_only_on_a_word_they_can_take() { + let mut app = app(); + forget(&mut app, &[X, Y]); + app.run("text.spelling.addWord", json!({ "word": X })).unwrap(); + super::open(&mut app).unwrap(); + let ctx = context(); + for entry in ["", "two words", X, &"z".repeat(65)] { + set(&mut app, "entry", json!(entry)); + assert_eq!(super::actions(app.ui.dialog.as_ref().unwrap()).0, None, "{entry:?}"); + click(&mut app, &ctx, "Add"); + assert_eq!(words(&app, &[X, Y]), [X], "{entry:?} isn't added"); + } + // Nothing picked: Delete and Change do nothing. + set(&mut app, "entry", json!(Y)); + click(&mut app, &ctx, "Delete"); + click(&mut app, &ctx, "Change"); + assert_eq!(words(&app, &[X, Y]), [X]); + crate::dialogs::cancel(&mut app); + forget(&mut app, &[X]); + } +} diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 93688542c1..febbc6488a 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -24,9 +24,40 @@ pub(super) const SPEC: DialogSpec = DialogSpec { preview: true, // Load Texture… adds the texture it reads. passes: |d, field| field == vectorcraft_effects::pixel::TEXTURE_IMAGE && matches!(d.str("__effect").as_str(), GLASS | TEXTURIZER), + // OK could only fail the same way: off, beside the reason the dialog shows (#6140). + ok_enabled: Some(|_, d| !(vectorcraft_effects::is_three_d(&d.str("__effect")) && d.fields.contains_key(form::REFUSED))), ..DialogSpec::FORM }; +/// The field holding the values a 3D effect's dialog last tried with Preview off. +const TRIED: &str = "__tried"; + +/// A 3D effect refuses objects it can't build from and values it can't draw, in the dialog as OK +/// would: shows why under Preview (#6140). With Preview off no preview has tried `params`, so they +/// are tried here, when they change, and rolled back at once. +fn three_d_refusal(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, cmd: &str, params: Value) { + if d.bool("preview") { + d.fields.remove(TRIED); + } else if !app.session.in_interaction() && d.fields.get(TRIED) != Some(¶ms) { + // Waits for another interaction to end: trying inside it would replace its preview and + // cancel it. A failure to begin leaves no interaction: the preview below then reports it. + let _ = app.session.begin_interaction(&d.str("__label")); + match app.session.preview(cmd, ¶ms) { + Ok(_) => { + d.fields.remove(form::REFUSED); + } + Err(e) => form::note_refusal(d, &e), + } + // Only a try: without an interaction there is nothing to roll back. + let _ = app.session.cancel_interaction(); + d.fields.insert(TRIED.into(), params); + } + if let Some(why) = d.fields.get(form::REFUSED).and_then(Value::as_str) { + ui.add_space(6.0); + ui.add(egui::Label::new(egui::RichText::new(why).color(Tokens::get(ui.ctx()).warning)).wrap()); + } +} + /// The effect's name (`__label`, English) in the UI language: the catalog may carry it with or /// without its trailing ellipsis. A plug-in effect's name is shown as it is. fn heading_label(d: &Dialog) -> String { @@ -170,7 +201,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if vectorcraft_effects::is_three_d(&id) { super::revolve::body(app, ui, d); let (cmd, params) = command(d); - form::preview(app, ui, d, &d.str("__label"), cmd, params); + form::preview(app, ui, d, &d.str("__label"), cmd, params.clone()); + three_d_refusal(app, ui, d, cmd, params); return false; } // Plug-in effects get fields from their parameter schema; colour adjustments their sliders. diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 4fe560bb58..03c862171d 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -1,15 +1,31 @@ //! Effect → Effect Gallery: browse Photoshop-style raster filters by category, build a stack, and //! apply it as separate appearance effects in one undo step. +//! +//! Each filter has a thumbnail, and the dialog has its own preview, as the +//! [Filter Gallery](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html) +//! describes. Both are an original drawing made for VectorCraft (a small landscape), passed through +//! the filter. The thumbnails use each filter's defaults. The preview uses the visible stack, or +//! the filter being browsed when the stack is empty. The canvas preview and the one-undo OK are +//! unchanged. + +use std::collections::HashMap; use egui; use serde_json::{Map, Value, json}; -use vectorcraft_effects::{EffectInfo, PIXEL_EFFECTS}; +use vectorcraft_effects::{EffectInfo, PIXEL_EFFECTS, PixelSpace}; +use vectorcraft_geom::{Affine, Point}; use super::{DialogSpec, effect, form}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; +/// Thumbnail of one filter, in pixels. The drawing is original; the filter is this app's. +const THUMB: usize = 36; +/// In-dialog preview, in pixels, drawn at twice this size. +const PREVIEW_W: usize = 120; +const PREVIEW_H: usize = 84; + /// Dialog kind for the Effect Gallery. pub const KIND: &str = "effectGallery"; @@ -248,6 +264,196 @@ fn effect_label(id: &str) -> String { vectorcraft_effects::effect_info(id).map(|e| tl!(e.label).trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string()) } +/// Where the preview rasters sit: one document point per pixel, origin at the top-left. +fn preview_space(w: usize, h: usize) -> PixelSpace { + let (wf, hf) = (w as f64, h as f64); + PixelSpace { + to_doc: Affine::IDENTITY, + px: 1.0, + center: Point::new(wf / 2.0, hf / 2.0), + channels: vectorcraft_effects::pixel::Channels::Rgb, + line: 1.0, + extent: 0.5 * wf.hypot(hf), + } +} + +fn byte(v: f32) -> u8 { + if !v.is_finite() { + return 0; + } + v.round().clamp(0.0, 255.0) as u8 +} + +/// An original landscape for the gallery (sky, sun, hills, a house, a river). Not a copied picture. +fn sample_drawing(w: usize, h: usize) -> Vec { + let mut out = vec![0u8; w.saturating_mul(h).saturating_mul(4)]; + if w == 0 || h == 0 || out.len() != w * h * 4 { + return out; + } + for y in 0..h { + for x in 0..w { + let xf = x as f32 / w as f32; + let yf = y as f32 / h as f32; + let mut rgb = [90.0 + 90.0 * (1.0 - yf), 150.0 + 50.0 * (1.0 - yf), 200.0 + 40.0 * yf]; + let (dx, dy) = (xf - 0.78, yf - 0.22); + if dx * dx + dy * dy < 0.012 { + rgb = [252.0, 206.0, 64.0]; + } + let hill = 0.58 + 0.08 * (xf * std::f32::consts::TAU).sin(); + if yf > hill { + rgb = [46.0, 110.0 + 40.0 * (1.0 - (yf - hill).clamp(0.0, 1.0)), 52.0]; + } + if (0.16..0.40).contains(&xf) && (0.46..0.70).contains(&yf) { + rgb = [196.0, 64.0, 48.0]; + } + let roof = 0.46 - (xf - 0.28).abs() * 1.15; + if (0.12..0.44).contains(&xf) && yf > roof && yf < 0.48 { + rgb = [92.0, 48.0, 36.0]; + } + if (0.22..0.32).contains(&xf) && (0.52..0.62).contains(&yf) { + rgb = [255.0, 236.0, 150.0]; + } + if yf > 0.80 && (yf * 18.0 + xf * 9.0).sin() > -0.15 { + rgb = [36.0, 78.0, 196.0]; + } + let i = (y * w + x) * 4; + out[i] = byte(rgb[0]); + out[i + 1] = byte(rgb[1]); + out[i + 2] = byte(rgb[2]); + out[i + 3] = 255; + } + } + out +} + +/// Run one Photoshop-style filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` +/// is not one of those filters or the buffer is the wrong size. +fn apply_pixel(id: &str, params: &Map, data: &mut [u8], w: usize, h: usize) { + let Some(n) = w.checked_mul(h).and_then(|n| n.checked_mul(4)) else { return }; + if n != data.len() || w == 0 || h == 0 { + return; + } + let effect = vectorcraft_doc::Effect { id: id.to_string(), params: Value::Object(params.clone()), visible: true }; + let Some(vectorcraft_effects::RasterFx::Pixel(fx)) = vectorcraft_effects::raster_effects(std::slice::from_ref(&effect)).into_iter().next() else { + return; + }; + fx.apply(data, w, h, &preview_space(w, h)); +} + +fn filtered(id: &str, params: &Map, w: usize, h: usize) -> Vec { + let mut data = sample_drawing(w, h); + apply_pixel(id, params, &mut data, w, h); + data +} + +/// The drawing with `jobs` applied in order (the visible stack, or the filter being browsed). +fn preview_rgba(jobs: &[(String, Map)], w: usize, h: usize) -> Vec { + let mut data = sample_drawing(w, h); + for (id, params) in jobs { + apply_pixel(id, params, &mut data, w, h); + } + data +} + +fn thumb_pixels(id: &str) -> Vec { + static CACHE: std::sync::LazyLock>>> = + std::sync::LazyLock::new(|| std::sync::Mutex::new(HashMap::new())); + if let Some(px) = CACHE.lock().unwrap_or_else(|e| e.into_inner()).get(id).cloned() { + return px; + } + // The filter runs outside the lock: a thumbnail is a few thousand pixels, and two threads + // computing the same one just keep one copy. + let px = filtered(id, &default_params(id), THUMB, THUMB); + CACHE.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), px.clone()); + px +} + +/// Straight RGBA for egui, from the filters' premultiplied bytes. +fn color_image(data: &[u8], w: usize, h: usize) -> egui::ColorImage { + let mut pixels = Vec::with_capacity(w.saturating_mul(h)); + let (rows, _) = data.as_chunks::<4>(); + for p in rows { + let a = u32::from(p[3]); + let (r, g, b) = if a == 0 { + (0, 0, 0) + } else if a == 255 { + (p[0], p[1], p[2]) + } else { + let s = |c: u8| ((u32::from(c) * 255 + a / 2) / a).min(255) as u8; + (s(p[0]), s(p[1]), s(p[2])) + }; + pixels.push(egui::Color32::from_rgba_unmultiplied(r, g, b, p[3])); + } + if pixels.len() != w.saturating_mul(h) { + return egui::ColorImage::filled([w.max(1), h.max(1)], egui::Color32::TRANSPARENT); + } + egui::ColorImage::new([w, h], pixels) +} + +fn thumb_tex(ctx: &egui::Context, id: &str) -> egui::TextureHandle { + let key = egui::Id::unique("effect-gallery-thumbs"); + if let Some(tex) = ctx.data(|d| d.get_temp::>(key).and_then(|m| m.get(id).cloned())) { + return tex; + } + let tex = ctx.load_texture(format!("effect-gallery-thumb-{id}"), color_image(&thumb_pixels(id), THUMB, THUMB), egui::TextureOptions::NEAREST); + ctx.data_mut(|d| { + d.get_temp_mut_or_insert_with(key, HashMap::new).insert(id.to_string(), tex.clone()); + }); + tex +} + +/// What the in-dialog preview shows: the visible stack, or the browsed filter when nothing is stacked. +fn preview_jobs(d: &Dialog, stack: &[StackEntry], browse: &str) -> Vec<(String, Map)> { + if !stack.is_empty() { + return stack.iter().filter(|e| e.visible).map(|e| (e.effect.clone(), e.params.clone())).collect(); + } + if browse.is_empty() { + return Vec::new(); + } + let params = if d.fields.get("browseEffect").and_then(Value::as_str) == Some(browse) { browse_params(d) } else { default_params(browse) }; + vec![(browse.to_string(), params)] +} + +fn preview_key(jobs: &[(String, Map)]) -> String { + let rows: Vec = jobs.iter().map(|(id, params)| json!({ "effect": id, "params": params })).collect(); + serde_json::to_string(&Value::Array(rows)).unwrap_or_default() +} + +fn preview_tex(ctx: &egui::Context, key: &str, rgba: &[u8]) -> egui::TextureHandle { + let id = egui::Id::unique("effect-gallery-preview"); + if let Some(tex) = ctx.data(|d| d.get_temp::<(String, egui::TextureHandle)>(id).filter(|(k, _)| k == key).map(|(_, tex)| tex)) { + return tex; + } + let tex = ctx.load_texture("effect-gallery-preview", color_image(rgba, PREVIEW_W, PREVIEW_H), egui::TextureOptions::LINEAR); + ctx.data_mut(|d| d.insert_temp(id, (key.to_string(), tex.clone()))); + tex +} + +fn preview_area(ui: &mut egui::Ui, d: &Dialog, stack: &[StackEntry], browse: &str) { + let t = Tokens::get(ui.ctx()); + widgets::subheader(ui, tl!("Preview")); + let jobs = preview_jobs(d, stack, browse); + let key = preview_key(&jobs); + let rgba = preview_rgba(&jobs, PREVIEW_W, PREVIEW_H); + let tex = preview_tex(ui.ctx(), &key, &rgba); + #[cfg(test)] + PREVIEWS_PAINTED.with(|c| c.set(c.get() + 1)); + let (img_w, img_h) = (PREVIEW_W as f32 * 2.0, PREVIEW_H as f32 * 2.0); + ui.horizontal(|ui| { + let spare = (ui.available_width() - img_w).max(0.0); + ui.add_space(spare / 2.0); + let (rect, _) = ui.allocate_exact_size(egui::vec2(img_w, img_h), egui::Sense::hover()); + ui.painter().rect_filled(rect, 2.0, t.panel_darker); + let inner = rect.shrink(4.0); + ui.painter().image(tex.id(), inner, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + }); + let caption = jobs.iter().map(|(id, _)| effect_label(id)).collect::>().join(", "); + if !caption.is_empty() { + ui.label(egui::RichText::new(caption).color(t.text_dim)); + } + ui.add_space(8.0); +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); let cat = category_ix(d); @@ -263,6 +469,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if stack_sel >= stack.len() && !stack.is_empty() { stack_sel = stack.len() - 1; } + preview_area(ui, d, &stack, &sel); + let (param_effect, mut param_values) = param_target(d, &stack, stack_sel, &sel); if !param_effect.is_empty() { widgets::subheader(ui, tl!("Settings")); @@ -293,12 +501,15 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(8.0); ui.vertical(|ui| { widgets::subheader(ui, tl!("Filters")); - ui.set_width(220.0); - egui::ScrollArea::vertical().max_height(220.0).show(ui, |ui| { + ui.set_width(248.0); + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { for e in &effects { let picked = e.id == sel; let name = tl!(e.label).trim_end_matches('…').to_string(); - let resp = ui.add(egui::Button::selectable(picked, name)); + let image = egui::Image::from_texture(&thumb_tex(ui.ctx(), e.id)).fit_to_exact_size(egui::vec2(THUMB as f32, THUMB as f32)); + #[cfg(test)] + THUMBS_PAINTED.with(|c| c.set(c.get() + 1)); + let resp = ui.add(egui::Button::selectable(picked, (image, name)).min_size(egui::vec2(200.0, THUMB as f32 + 4.0))); if resp.clicked() { set_selected(d, e.id); set_stack_focus(d, false); @@ -418,6 +629,12 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { r } +#[cfg(test)] +thread_local! { + static THUMBS_PAINTED: std::cell::Cell = const { std::cell::Cell::new(0) }; + static PREVIEWS_PAINTED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + #[cfg(test)] mod tests { use serde_json::json; @@ -476,4 +693,49 @@ mod tests { assert!(!n.appearance.effects[1].visible); assert_eq!(st.history.undo.len(), steps + 1); } + + #[test] + fn gallery_shows_thumbnails_and_an_in_dialog_preview() { + let plain = super::sample_drawing(super::THUMB, super::THUMB); + let mut seen = Vec::new(); + for cat in 0..super::CATEGORIES.len() { + for e in super::effects_in_category(cat) { + let thumb = super::thumb_pixels(e.id); + assert_eq!(thumb.len(), super::THUMB * super::THUMB * 4, "{}", e.id); + assert_ne!(thumb, plain, "{} thumbnail is the untouched drawing", e.id); + seen.push(thumb); + } + } + assert!(seen.len() > 2); + assert_ne!(seen[0], seen[1], "two filters share one thumbnail"); + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + super::THUMBS_PAINTED.with(|c| c.set(0)); + super::PREVIEWS_PAINTED.with(|c| c.set(0)); + frame(&mut app); + let thumbs = super::THUMBS_PAINTED.with(|c| c.get()); + let previews = super::PREVIEWS_PAINTED.with(|c| c.get()); + let artistic = super::effects_in_category(0).len() as u32; + assert!(thumbs >= artistic, "painted {thumbs} thumbnails, Artistic has {artistic}"); + assert!(previews >= 1, "the dialog has a preview area"); + + let d = app.ui.dialog.as_ref().unwrap(); + let stack = super::stack_of(d); + let jobs = super::preview_jobs(d, &stack, &super::selected_id(d)); + assert_eq!(jobs.len(), 1, "an empty stack previews the filter being browsed"); + let shown = super::preview_rgba(&jobs, super::PREVIEW_W, super::PREVIEW_H); + assert_ne!(shown, super::sample_drawing(super::PREVIEW_W, super::PREVIEW_H)); + + let soft = super::filtered("artistic.cutout", &super::default_params("artistic.cutout"), super::PREVIEW_W, super::PREVIEW_H); + let hard = super::filtered( + "artistic.cutout", + &serde_json::from_value(json!({"levels": 8, "edgeSimplicity": 0, "edgeFidelity": 3})).unwrap(), + super::PREVIEW_W, + super::PREVIEW_H, + ); + assert_ne!(soft, hard, "the preview follows the filter's settings"); + } } diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 3cd0a51110..4859348935 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -316,6 +316,21 @@ mod tests { assert!(!transparent_left(&app)); } + /// Cancel with the Save Preset row showing closes the dialog and rolls the preview back. + #[test] + fn cancel_while_saving_a_preset_closes_the_dialog() { + let mut app = scene(); + let before = app.session.doc().unwrap().doc.clone(); + app.run("ui.flattenTransparencyDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + frame(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert(SAVING.into(), json!(true)); + frame(&mut app); + super::super::cancel(&mut app); + assert!(app.ui.dialog.is_none() && !app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().doc, before, "Cancel rolls back"); + } + #[test] fn ok_says_in_the_status_bar_when_an_image_could_not_be_decoded() { const WARNING: &str = "an image couldn't be decoded and is missing from the picture"; diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index be4f9e80cc..c87cfb7e63 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -966,6 +966,19 @@ fn rail_ends_w(ui: &mut egui::Ui, width: f32, (left, right): (&str, &str)) { /// The field where [`preview`] keeps the parameters it last previewed. pub(super) const PREVIEWED: &str = "__previewed"; +/// The field holding why the dialog's command last refused its values, for the dialog to show. +pub(super) const REFUSED: &str = "__refused"; + +/// Keeps why the command refused the dialog's values in [`REFUSED`]: a refused value's message is +/// written for the user, so it goes without the command's id that the error's text puts before it. +pub(super) fn note_refusal(d: &mut Dialog, e: &vectorcraft_engine::EngineError) { + let why = match e { + vectorcraft_engine::EngineError::BadParams { msg, .. } => msg.clone(), + other => other.to_string(), + }; + d.fields.insert(REFUSED.into(), json!(why)); +} + /// The Preview checkbox of a dialog that previews `cmd` on the canvas: while it is on, `params` run /// again on the interaction's snapshot whenever they differ from the last preview (whether a widget /// or `ui.dialog.set` changed them); turning it off rolls back. @@ -1022,8 +1035,14 @@ pub(super) fn preview_now(app: &mut crate::VectorcraftApp, d: &mut Dialog, label if d.fields.get(PREVIEWED) != Some(¶ms) || !app.session.in_interaction() { let _ = app.session.begin_interaction(label); match app.session.preview(cmd, ¶ms) { - Ok(r) => result = Some(r), - Err(e) => app.status(e.to_string()), + Ok(r) => { + d.fields.remove(REFUSED); + result = Some(r); + } + Err(e) => { + note_refusal(d, &e); + app.status(e.to_string()); + } } d.fields.insert(PREVIEWED.into(), params); } diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index 653b16fc9e..5084754fc9 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -29,6 +29,12 @@ pub fn fields() -> Value { json!({"shape": "circle", "frequency": 20, "angle": 45, "mode": "mono", "color": "#000000", "invert": false, "clip": true, "keepOriginal": false, "preview": true}) } +/// Whether the open Object → Vector Halftone dialog is showing its temporary dot group. +pub(crate) fn previewing(app: &VectorcraftApp) -> bool { + app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND) + && app.session.active().and_then(|st| st.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == CMD) +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { screen_fields(ui, d); form::check(ui, d, "keepOriginal", tl!("Keep Original")); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 982dd7c6fc..8e02009339 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1,14 +1,16 @@ //! File → New: category tabs (Recent, Saved and the built-in categories of `file.newPresets`) //! over a grid of preset cards, and a Preset Details column (name and Save Preset, size and //! units, orientation, artboards, bleed, background contents, Advanced Options, More Settings); -//! Close and Create. More Settings is the classic form of the same fields (artboard layout, -//! spacing and columns, profile and size lists), so both share one set of fields and widgets. +//! Close and Create. More Settings opens a pop-up over the dialog with the artboard layout, spacing +//! and columns, editing the same fields. Save Preset turns the top of Preset Details into the +//! preset's name, Cancel and Save, and hides Close and Create until the preset is saved or canceled; +//! the rows under it stay editable and are what the preset stores. //! //! Fields: `file.new`'s params (`preset`, `name`, `width`, `height` (pt), `units`, `artboards`, //! `artboardLayout`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi`, -//! `previewMode`), plus `category` (the tab, also More Settings' Profile), `advanced` (Advanced -//! Options open), `bleedLinked` and `presetName` (Save Preset's name). Setting `preset` fills the -//! fields from that preset; changing any of them afterwards makes the settings custom. +//! `previewMode`), plus `category` (the tab), `advanced` (Advanced Options open), `bleedLinked` and +//! `presetName` (Save Preset's name). Setting `preset` fills the fields from that preset; changing +//! any of them afterwards makes the settings custom. use serde_json::{Map, Value, json}; use vectorcraft_doc::Unit; @@ -20,11 +22,11 @@ use crate::theme::{self, Tokens}; use crate::{VectorcraftApp, widgets}; pub(super) const KIND: &str = "newDocument"; -/// More Settings. +/// New Document with its More Settings pop-up open. pub(super) const MORE: &str = "newDocumentMore"; pub(super) const SPEC: DialogSpec = DialogSpec { inputs: |_| &["presetName"], ..DialogSpec::window(show, confirm) }; -pub(super) const MORE_SPEC: DialogSpec = DialogSpec { inputs: |_| &["presetName"], ..DialogSpec::window(show_more, confirm) }; +pub(super) const MORE_SPEC: DialogSpec = SPEC; /// The fields `file.new` takes. const PARAMS: [&str; 12] = [ @@ -44,8 +46,11 @@ const PARAMS: [&str; 12] = [ /// The preset the fields were last filled from, as `apply` set them; a Recent or Saved card keeps /// its own units here, which the units chosen in Preset Details don't change. const APPLIED: &str = "__applied"; -/// Save Preset's name field is showing. +/// Preset Details is saving a preset (Save Preset's name, Cancel and Save are showing). const SAVING: &str = "__saving"; +/// Preset Details has drawn the saving top: set from the mode's second frame, so the first one fills +/// in the default name and focuses it. +const SAVING_SHOWN: &str = "__savingShown"; /// The units New Document offers (all ten). const UNITS: [Unit; 10] = [ Unit::Pixels, @@ -65,6 +70,10 @@ const COLOR_MODES: [(&str, &str); 2] = [("rgb", "RGB Color"), ("cmyk", "CMYK Col const DETAILS: f32 = 292.0; /// Height of the dialog's content. const HEIGHT: f32 = 600.0; +/// Height of the top of Preset Details in either state: the rows under it don't move. +const HEADER: f32 = 100.0; +/// Width of the More Settings pop-up's rows. +const MORE_WIDTH: f32 = 310.0; /// Open New Document on the most recent settings (or Letter), named after the next untitled /// document. @@ -116,8 +125,17 @@ fn sync(app: &VectorcraftApp, d: &mut Dialog) { } } -/// Create the document; the dialog stays open when that fails (bad size, …). +/// Create the document; the dialog stays open when that fails (bad size, …). While a preset is being +/// saved this is its Save, and no document is created. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.bool(SAVING) { + let mut d = d.clone(); + let r = save_preset(app, &mut d); + if r.is_ok() { + app.ui.dialog = Some(d); + } + return r; + } let p = params(app, d); let r = app.run("file.new", Value::Object(p)); if r.is_ok() { @@ -175,17 +193,45 @@ fn window(ctx: &egui::Context, id: &str, margin: i8, add: impl FnOnce(&mut egui: super::modal::show(ctx, id, egui::Id::unique(("dialog", id)), -20.0, margin, add); } +/// Whether More Settings' pop-up is open over New Document. +pub(crate) fn popup_open(d: &Dialog) -> bool { + d.kind == MORE +} + +/// Close New Document's More Settings pop-up, or else leave its Save Preset, keeping the fields. +/// False when neither is showing, or `d` is another dialog. +pub(super) fn close_popup(d: &mut Dialog) -> bool { + if d.kind != KIND && d.kind != MORE { + return false; + } + if popup_open(d) { + d.kind = KIND.into(); + return true; + } + let saving = d.bool(SAVING); + if saving { + d.fields.insert(SAVING.into(), json!(false)); + d.fields.remove(SAVING_SHOWN); + } + saving +} + /// What the buttons of a window asked for. #[derive(Default)] struct Buttons { create: bool, close: bool, + /// More Settings' pop-up was open as the frame began: Enter is the pop-up's. + popup: bool, + /// A preset was being saved as the frame began: nothing creates the document this frame. + saving: bool, } impl Buttons { /// Act on the buttons (Enter also creates) once the window is drawn. fn finish(self, app: &mut VectorcraftApp, ctx: &egui::Context, d: Dialog) { - let create = self.create || ctx.input(|i| i.key_pressed(egui::Key::Enter)) && !ctx.memory(|m| m.focused().is_some()); + let enter = !self.popup && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) && !ctx.memory(|m| m.focused().is_some()); + let create = !self.saving && !d.bool(SAVING) && (self.create || enter); app.ui.dialog = Some(d); if self.close { app.ui.dialog = None; @@ -199,7 +245,7 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; sync(app, &mut d); let t = Tokens::get(ctx); - let mut b = Buttons::default(); + let mut b = Buttons { popup: popup_open(&d), saving: d.bool(SAVING), ..Default::default() }; window(ctx, KIND, 0, |ui| { // No heading: the top margin (14) and the empty part of the category tabs' row (30) move the // window. @@ -220,6 +266,10 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); }); }); + // While More Settings' pop-up is open, a click outside it only closes it. + if b.popup { + ui.interact(ui.min_rect(), ui.scope_id().with("newdoc-popup-shield"), egui::Sense::CLICK | egui::Sense::DRAG); + } }); b.finish(app, ctx, d); } @@ -356,17 +406,24 @@ fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut let t = Tokens::get(ui.ctx()); ui.spacing_mut().item_spacing = egui::vec2(6.0, 4.0); let top = ui.cursor().top(); - ui.label(egui::RichText::new(tl!("PRESET DETAILS")).font(theme::semibold(11.0)).color(t.text_dim)); - ui.add_space(8.0); - let caption = form::caption(ui, tl!("Document Name")); - ui.horizontal(|ui| { - ui.label_inputs_by(caption.id, |ui| form::text(ui, d, "name", DETAILS - 50.0)); - save_button(app, ui, d); - }); - if d.bool(SAVING) { - save_row(app, ui, d); + let saving = d.bool(SAVING); + if saving { + let opening = !d.bool(SAVING_SHOWN); + d.fields.insert(SAVING_SHOWN.into(), json!(true)); + save_header(app, ui, d, opening); + } else { + d.fields.remove(SAVING_SHOWN); + ui.label(egui::RichText::new(tl!("PRESET DETAILS")).font(theme::semibold(11.0)).color(t.text_dim)); + ui.add_space(8.0); + let caption = form::caption(ui, tl!("Document Name")); + ui.horizontal(|ui| { + ui.label_inputs_by(caption.id, |ui| form::text(ui, d, "name", DETAILS - 50.0)); + if widgets::icon_button(ui, "save", tl!("Save Preset"), false, 26.0).clicked() { + d.fields.insert(SAVING.into(), json!(true)); + } + }); } - ui.add_space(8.0); + ui.add_space((HEADER - (ui.cursor().top() - top)).max(0.0)); let unit = unit(d); let caption = form::caption(ui, tl!("Width")); ui.horizontal(|ui| { @@ -387,7 +444,7 @@ fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut ui.add_space(6.0); ui.vertical(|ui| { let caption = form::caption(ui, tl!("Artboards")); - ui.label_inputs_by(caption.id, |ui| artboards(ui, d, 76.0)); + ui.label_inputs_by(caption.id, |ui| artboards(ui, d, "newdoc-artboards", 76.0)); }); }); ui.add_space(8.0); @@ -399,8 +456,9 @@ fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut ui.add_space(8.0); advanced(ui, d, 110.0, DETAILS - 116.0); ui.add_space(12.0); - if widgets::flat_button(ui, tl!("More Settings"), DETAILS).clicked() { - d.kind = MORE.into(); + more_settings(ui, d); + if saving { + return; } // Close and Create at the bottom right. ui.add_space((HEIGHT - (ui.cursor().top() - top) - 28.0).max(12.0)); @@ -411,44 +469,159 @@ fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut }); } -/// The Save Preset button beside the name: it shows or hides [`save_row`]. -fn save_button(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - if widgets::icon_button(ui, "save", tl!("Save Preset"), d.bool(SAVING), 26.0).clicked() { - let saving = !d.bool(SAVING); - d.fields.insert(SAVING.into(), json!(saving)); - if saving && d.str("presetName").is_empty() { - let template = "Preset {number}"; - let name = crate::i18n::fmt(tl!(template), &[("number", &(app.session.prefs.new_doc_presets.len() + 1).to_string())]); - d.fields.insert("presetName".into(), json!(name)); - } +/// The key under which a layer remembers that its first field should take the keyboard focus. +fn pending_focus(ui: &egui::Ui) -> egui::Id { + ui.layer_id().id.with("newdoc-focus") +} + +/// Draw `add`; its first enabled field takes the keyboard focus, with its text selected, when +/// `opening` says so or a failed Save asked for it. +fn focus_first(ui: &mut egui::Ui, opening: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let pending = pending_focus(ui); + if opening { + ui.data_mut(|m| m.insert_temp(pending, true)); + } + // The first frame of a new window only measures it: no field can take the focus until the next. + let focus = !ui.is_sizing_pass() && ui.data(|m| m.get_temp::(pending)).unwrap_or(false); + if focus { + ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true)); + } + let r = add(ui); + if focus && ui.data_mut(|m| m.remove_temp::(widgets::dialog_focus_flag())).is_none() { + ui.data_mut(|m| m.remove::(pending)); + } + r +} + +/// The top of Preset Details while a preset is being saved: the heading, the preset's name, Cancel +/// and Save. Enter in the name is Save. `opening` on the mode's first frame. +fn save_header(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, opening: bool) { + let t = Tokens::get(ui.ctx()); + if opening && d.str("presetName").is_empty() { + d.fields.insert("presetName".into(), json!(new_preset_name(app))); + } + ui.label(egui::RichText::new(tl!("Save Document Preset")).font(theme::semibold(13.0)).color(t.text)); + ui.add_space(5.0); + let name = focus_first(ui, opening, |ui| form::text_edit_named(ui, d, "presetName", tl!("Preset Name"), DETAILS - 14.0)); + let enter = name.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + ui.add_space(4.0); + let (mut save, mut cancel) = (enter, false); + ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 28.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + save |= widgets::primary_button(ui, tl!("Save")).clicked(); + ui.add_space(8.0); + cancel = widgets::secondary_button(ui, tl!("Cancel")).clicked(); + }); + if cancel { + d.fields.insert(SAVING.into(), json!(false)); + d.fields.remove(SAVING_SHOWN); + } else if save && let Err(e) = save_preset(app, d) { + app.status(e); + let pending = pending_focus(ui); + ui.data_mut(|m| m.insert_temp(pending, true)); } } -/// Save Preset: the preset's name, Save and Cancel. -fn save_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - ui.add_space(4.0); - let caption = form::caption(ui, tl!("Preset Name")); - ui.horizontal(|ui| { - let name = ui.label_inputs_by(caption.id, |ui| form::text_edit(ui, d, "presetName", DETAILS - 140.0)); - let enter = name.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); - if widgets::flat_button(ui, tl!("Save"), 54.0).clicked() || enter { - let mut p: Map = PARAMS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - p.insert("name".into(), json!(d.str("presetName"))); - p.remove("preset"); - match app.run("file.newPresets.save", Value::Object(p)) { - Ok(r) => { - d.fields.insert(SAVING.into(), json!(false)); - d.fields.insert("category".into(), json!("Saved")); - d.fields.insert("preset".into(), r["name"].clone()); - d.fields.remove(APPLIED); +/// Save Preset's default name: the first "Preset N" no saved preset has (`file.newPresets.save` +/// replaces a preset of the same name). +fn new_preset_name(app: &VectorcraftApp) -> String { + let saved = &app.session.prefs.new_doc_presets; + let template = "Preset {number}"; + (1..=saved.len() + 1) + .map(|n| crate::i18n::fmt(tl!(template), &[("number", &n.to_string())])) + .find(|name| !saved.iter().any(|p| p.name.trim().eq_ignore_ascii_case(name.trim()))) + .unwrap_or_default() +} + +/// Save the fields as the preset named `presetName` and leave saving, on the saved preset. +fn save_preset(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { + let mut p: Map = PARAMS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); + p.insert("name".into(), json!(d.str("presetName"))); + p.remove("preset"); + let r = app.run("file.newPresets.save", Value::Object(p))?; + d.fields.insert(SAVING.into(), json!(false)); + d.fields.remove(SAVING_SHOWN); + // The next Save Preset offers a new default name instead of this preset's. + d.fields.remove("presetName"); + d.fields.insert("category".into(), json!("Saved")); + d.fields.insert("preset".into(), r["name"].clone()); + d.fields.remove(APPLIED); + Ok(r) +} + +/// The More Settings button and its pop-up, which holds what Preset Details doesn't: the artboard +/// layout, spacing and columns. Done, a click outside it and Escape close it; the fields it edited +/// stay as they are. +fn more_settings(ui: &mut egui::Ui, d: &mut Dialog) { + let button = widgets::flat_button(ui, tl!("More Settings"), DETAILS); + let mut open = (d.kind == MORE) != button.clicked(); + let mut done = false; + let opening = button.ctx.read_response(egui::Popup::default_response_id(&button)).is_none(); + egui::Popup::from_response(&button) + .open_bool(&mut open) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .align(egui::RectAlign::TOP_END) + .accessible_name(tl!("More Settings")) + .show(|ui| done = more_settings_popup(ui, opening, d)); + d.kind = if open && !done { MORE } else { KIND }.into(); +} + +/// More Settings' pop-up. True when Done (or Enter) finished with it. +fn more_settings_popup(ui: &mut egui::Ui, opening: bool, d: &mut Dialog) -> bool { + const L: f32 = 150.0; + let t = Tokens::get(ui.ctx()); + let (lay, cols, spacing, rtl) = layout(d); + let n = d.f64("artboards", 1.0); + let several = n > 1.0; + let room = ui.ctx().content_rect().size() - egui::Vec2::splat(4.0 * super::EDGE_GAP) - egui::vec2(0.0, 44.0); + focus_first(ui, opening, |ui| { + egui::ScrollArea::both().id_salt("newdoc-popup-rows").max_width(room.x.max(0.0)).max_height(room.y.max(0.0)).show(ui, |ui| { + ui.set_width(MORE_WIDTH); + ui.label(egui::RichText::new(tl!("More Settings")).font(theme::semibold(13.0)).color(t.text)); + ui.add_space(6.0); + widgets::label_row(ui, tl!("Number of Artboards:"), L, |ui| artboards(ui, d, "newdoc-popup-artboards", 76.0)); + widgets::label_row(ui, "", L, |ui| { + for (l, icon) in [ + (ArtboardLayout::GridByRow, "dc-grid-view"), + (ArtboardLayout::GridByColumn, "grid-3x3"), + (ArtboardLayout::Row, "arrow-left-right"), + (ArtboardLayout::Column, "arrow-up-down"), + ] { + if widgets::icon_button_enabled(ui, icon, l.label(), lay == l, several, 26.0).clicked() { + set_layout(d, "layout", json!(l.id())); + } } - Err(e) => app.status(e), - } - } - if widgets::flat_button(ui, tl!("Cancel"), 60.0).clicked() { - d.fields.insert(SAVING.into(), json!(false)); - } + ui.add_space(6.0); + if widgets::icon_button_enabled(ui, "chevrons-left", tl!("Change to Right-to-Left Layout"), rtl, several, 26.0).clicked() { + set_layout(d, "rightToLeft", json!(!rtl)); + } + }); + ui.add_enabled_ui(several, |ui| { + widgets::label_row(ui, tl!("Spacing:"), L, |ui| { + if let Some(v) = widgets::num_field(ui, "newdoc-spacing", Some(spacing), unit(d), 100.0) { + set_layout(d, "spacing", json!(v.max(0.0))); + } + }); + let grid = matches!(lay, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn); + ui.add_enabled_ui(grid, |ui| { + widgets::label_row(ui, tl!("Columns:"), L, |ui| { + if let Some(v) = widgets::spin_plain(ui, "newdoc-columns", cols as f64, "", 0, 76.0, 1.0, 1.0, &[]) { + set_layout(d, "columns", json!(v.round().clamp(1.0, n) as u64)); + } + }); + }); + }); + }); }); + ui.add_space(8.0); + // A bad value in a field keeps the pop-up open, as it keeps a dialog open. + let rejected = ui.data_mut(|m| m.remove_temp::(widgets::dialog_reject_commit_flag())).unwrap_or(false); + let enter = !rejected && ui.input(|i| i.key_pressed(egui::Key::Enter)) && ui.memory(|m| m.focused().is_none()); + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + let mut done = false; + ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { + done = widgets::primary_button(ui, tl!("Done")).clicked() || enter; + }); + done } fn units_dropdown(ui: &mut egui::Ui, d: &mut Dialog, width: f32) { @@ -481,10 +654,10 @@ fn orientation(ui: &mut egui::Ui, d: &mut Dialog) { }); } -fn artboards(ui: &mut egui::Ui, d: &mut Dialog, width: f32) { +fn artboards(ui: &mut egui::Ui, d: &mut Dialog, id: &str, width: f32) { let n = d.f64("artboards", 1.0); ui.horizontal(|ui| { - if let Some(v) = widgets::spin_plain(ui, "newdoc-artboards", n, "", 0, width, 1.0, 1.0, &[]) { + if let Some(v) = widgets::spin_plain(ui, id, n, "", 0, width, 1.0, 1.0, &[]) { d.fields.insert("artboards".into(), json!(v.round().clamp(1.0, MAX_ARTBOARDS as f64) as u64)); } }); @@ -543,131 +716,10 @@ fn advanced(ui: &mut egui::Ui, d: &mut Dialog, label: f32, field: f32) { } } -/// More Settings: the classic form of the same fields. -fn show_more(app: &mut VectorcraftApp, ctx: &egui::Context) { - let Some(mut d) = app.ui.dialog.clone() else { return }; - sync(app, &mut d); - let t = Tokens::get(ctx); - let mut b = Buttons::default(); - let mut templates = false; - const L: f32 = 150.0; - window(ctx, MORE, 22, |ui| { - ui.set_width(560.0); - super::modal::heading(ui, tl!("More Settings")); - ui.add_space(12.0); - widgets::label_row(ui, tl!("Name:"), L, |ui| { - form::text(ui, &mut d, "name", 300.0); - save_button(app, ui, &mut d); - }); - if d.bool(SAVING) { - // Under the name, in the fields' column. - widgets::label_row(ui, "", L, |ui| { - ui.vertical(|ui| save_row(app, ui, &mut d)); - }); - } - // Profile: the preset categories (the tabs); Size: the profile's presets. - let profiles: Vec<&str> = newdoc::CATEGORIES.iter().map(|c| c.0).collect(); - let profile = profiles.iter().find(|p| p.eq_ignore_ascii_case(&d.str("category"))).copied().unwrap_or("[Custom]"); - widgets::label_row(ui, tl!("Profile:"), L, |ui| { - if let Some(p) = widgets::dropdown(ui, "newdoc-profile", profile, &profiles, 220.0).and_then(|i| profiles.get(i)) { - d.fields.insert("category".into(), json!(p)); - if let Some(first) = newdoc::category(&app.session, p).and_then(|v| v.into_iter().next()) { - apply(&mut d, &first); - } - } - }); - ui.add_space(6.0); - let (lay, cols, spacing, rtl) = layout(&d); - let n = d.f64("artboards", 1.0); - let several = n > 1.0; - widgets::label_row(ui, tl!("Number of Artboards:"), L, |ui| { - artboards(ui, &mut d, 76.0); - ui.add_space(10.0); - for (l, icon) in [ - (ArtboardLayout::GridByRow, "dc-grid-view"), - (ArtboardLayout::GridByColumn, "grid-3x3"), - (ArtboardLayout::Row, "arrow-left-right"), - (ArtboardLayout::Column, "arrow-up-down"), - ] { - if widgets::icon_button_enabled(ui, icon, l.label(), lay == l, several, 26.0).clicked() { - set_layout(&mut d, "layout", json!(l.id())); - } - } - ui.add_space(6.0); - if widgets::icon_button_enabled(ui, "chevrons-left", tl!("Change to Right-to-Left Layout"), rtl, several, 26.0).clicked() { - set_layout(&mut d, "rightToLeft", json!(!rtl)); - } - }); - ui.add_enabled_ui(several, |ui| { - widgets::label_row(ui, tl!("Spacing:"), L, |ui| { - if let Some(v) = widgets::num_field(ui, "newdoc-spacing", Some(spacing), unit(&d), 100.0) { - set_layout(&mut d, "spacing", json!(v.max(0.0))); - } - ui.add_space(20.0); - widgets::field_label(ui, egui::RichText::new(tl!("Columns:")).color(t.text)); - let grid = matches!(lay, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn); - ui.add_enabled_ui(grid, |ui| { - if let Some(v) = widgets::spin_plain(ui, "newdoc-columns", cols as f64, "", 0, 76.0, 1.0, 1.0, &[]) { - set_layout(&mut d, "columns", json!(v.round().clamp(1.0, n) as u64)); - } - }); - }); - }); - ui.add_space(6.0); - let sizes = newdoc::category(&app.session, profile).unwrap_or_default(); - let size_names: Vec<&str> = sizes.iter().map(|s| s.name.as_str()).collect(); - let preset = d.str("preset"); - widgets::label_row(ui, tl!("Size:"), L, |ui| { - // The profile's sizes are built in; the preset may be one the user saved. - let shown = if preset.is_empty() { tl!("Custom") } else { preset_name(&preset) }; - if let Some(s) = super::mixed_dropdown(ui, "newdoc-size", shown, &size_names, 220.0, |_| true).and_then(|i| sizes.get(i)) { - apply(&mut d, s); - } - }); - let unit = unit(&d); - widgets::label_row(ui, tl!("Width:"), L, |ui| { - form::length(ui, &mut d, "width", unit, 120.0); - ui.add_space(20.0); - ui.label(egui::RichText::new(tl!("Units:")).color(t.text)); - units_dropdown(ui, &mut d, 120.0); - }); - widgets::label_row(ui, tl!("Height:"), L, |ui| { - form::length(ui, &mut d, "height", unit, 120.0); - ui.add_space(20.0); - ui.label(egui::RichText::new(tl!("Orientation:")).color(t.text)); - orientation(ui, &mut d); - }); - ui.add_space(4.0); - widgets::label_row(ui, tl!("Bleed:"), L, |ui| form::bleed(ui, &mut d, unit, 64.0)); - ui.add_space(4.0); - widgets::label_row(ui, tl!("Background Contents:"), L, |ui| background(ui, &mut d, 220.0)); - ui.add_space(8.0); - advanced(ui, &mut d, L, 220.0); - ui.add_space(16.0); - ui.horizontal(|ui| { - templates = widgets::secondary_button(ui, tl!("Templates…")).on_hover_text(tl!("New from Template")).clicked(); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - b.create |= widgets::primary_button(ui, tl!("Create Document")).clicked(); - ui.add_space(8.0); - // Cancel goes back to New Document. - if widgets::secondary_button(ui, tl!("Cancel")).clicked() { - d.kind = KIND.into(); - } - }); - }); - }); - if templates { - app.ui.dialog = None; - if let Err(e) = app.run("file.newFromTemplate", json!({})) { - app.status(e); - } - return; - } - b.finish(app, ctx, d); -} - #[cfg(test)] mod tests { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use vectorcraft_engine::Session; @@ -792,6 +844,26 @@ mod tests { run(&mut app, vec![press(false)]); assert!(app.ui.dialog.is_none(), "the double-click created it: {:?}", app.ui.status); assert_eq!(app.session.documents().len(), 1); + + // While a preset is being saved, a click fills the fields and a double-click creates nothing. + app.run("file.newDialog", json!({})).unwrap(); + set(&mut app, "category", json!("Mobile")); + set(&mut app, "preset", json!("Letter")); + set(&mut app, super::SAVING, json!(true)); + // Far enough from the clicks above that the next two count as a click and a double-click. + for _ in 0..12 { + run(&mut app, vec![]); + } + let at = card(&mut app, &mut run); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![egui::Event::PointerMoved(at), press(true)]); + run(&mut app, vec![press(false)]); + assert!(field(&app, "preset").as_str().is_some_and(|p| p == "Phone 393×852"), "a click fills the fields: {:?}", field(&app, "preset")); + run(&mut app, vec![press(true)]); + run(&mut app, vec![press(false)]); + run(&mut app, vec![]); + assert_eq!(app.session.documents().len(), 1, "nothing was created while saving"); + assert_eq!(field(&app, super::SAVING), json!(true)); } /// A category tab opens on its first preset, so Orientation matches its (landscape) cards, and @@ -878,14 +950,14 @@ mod tests { assert!(selected(&out), "the turned preset stays chosen: {:?}", field(&app, "preset")); } - /// The document's name field has a caption of its own under the Preset Details heading, and - /// the column stays inside the dialog's height with Save Preset and Advanced Options open. + /// The document's name field has a caption of its own under the Preset Details heading, the + /// column stays inside the dialog's height with Advanced Options open in both states, and saving + /// a preset replaces only the top of the column: the rows under it do not move. #[test] fn the_name_field_is_captioned_and_the_column_fits() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.newDialog", json!({})).unwrap(); set(&mut app, "advanced", json!(true)); - set(&mut app, super::SAVING, json!(true)); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let mut time = 0.0; @@ -897,8 +969,6 @@ mod tests { out.textures_delta.clear(); out }; - run(&mut app); - let out = run(&mut app); fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { match s { egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), @@ -906,13 +976,33 @@ mod tests { _ => {} } } - let mut texts = vec![]; - out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); - let at = |name: &str| texts.iter().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("{name} is missing: {texts:?}")); - let (heading, caption, value) = (at("PRESET DETAILS"), at("Document Name"), at("Untitled-1")); + let mut texts_of = |app: &mut VectorcraftApp| { + run(app); + let out = run(app); + let mut texts = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + texts + }; + let texts = texts_of(&mut app); + let at = |texts: &[(String, egui::Rect)], name: &str| { + texts.iter().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("{name} is missing: {texts:?}")) + }; + let (heading, caption, value) = (at(&texts, "PRESET DETAILS"), at(&texts, "Document Name"), at(&texts, "Untitled-1")); assert!(heading.bottom() <= caption.top() && caption.bottom() <= value.top(), "{heading:?} {caption:?} {value:?}"); - assert!(value.bottom() <= at("Preset Name").top(), "the preset's own name field follows"); - let used = at("Create").bottom() - heading.top(); + let used = at(&texts, "Create").bottom() - heading.top(); + assert!(used <= super::HEIGHT, "the column used {used}"); + let width = at(&texts, "Width").top(); + + set(&mut app, super::SAVING, json!(true)); + let saving = texts_of(&mut app); + for gone in ["PRESET DETAILS", "Document Name", "Close", "Create"] { + assert!(saving.iter().all(|(t, _)| t != gone), "{gone} shows while saving"); + } + let (heading, cancel) = (at(&saving, "Save Document Preset"), at(&saving, "Cancel")); + assert!(heading.bottom() <= cancel.top()); + assert!(cancel.bottom() <= at(&saving, "Width").top(), "Cancel and Save are above the rows"); + assert_eq!(at(&saving, "Width").top(), width, "the rows stay where they were"); + let used = at(&saving, "More Settings").bottom() - heading.top(); assert!(used <= super::HEIGHT, "the column used {used}"); } @@ -957,7 +1047,7 @@ mod tests { let out = frame(&mut app); assert!(!out.shapes.is_empty()); } - // More Settings shares the fields; Cancel goes back. + // More Settings edits the same fields. app.ui.dialog.as_mut().unwrap().kind = super::MORE.into(); set(&mut app, "artboards", json!(3)); frame(&mut app); @@ -977,48 +1067,380 @@ mod tests { assert_eq!(app.session.prefs.recent_new_docs[0].name, "Zine"); } - /// Save Preset works in More Settings too (#4893), saving its settings: the artboard layout - /// only More Settings shows among them. - #[test] - fn more_settings_saves_a_preset_of_its_settings() { + type Harness = egui_kittest::Harness<'static, VectorcraftApp>; + + /// New Document open in a harness of `size`, with the app's key handling and the dialogs drawn. + fn harness(size: egui::Vec2) -> Harness { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.newDialog", json!({})).unwrap(); - app.ui.dialog.as_mut().unwrap().kind = super::MORE.into(); - set(&mut app, "artboards", json!(4)); - set(&mut app, "artboardLayout", json!({"layout": "column", "spacing": 30})); - set(&mut app, super::SAVING, json!(true)); - set(&mut app, "presetName", json!("Strip")); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let mut time = 0.0; - let mut run = |app: &mut VectorcraftApp, events| { - time += 0.5; - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))); - let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); - out.textures_delta.clear(); - out - }; - run(&mut app, vec![]); - let out = run(&mut app, vec![]); - fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Pos2)>) { - match s { - egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect().center())), - egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), - _ => {} + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::shortcuts::handle(app, ui.ctx()); + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + h + } + + fn big() -> Harness { + harness(egui::vec2(1400.0, 1000.0)) + } + + /// Open a pop-up as a control client would, with `artboards` set, and let it draw. + fn open_more(h: &mut Harness, artboards: u64) { + set(h.state_mut(), "artboards", json!(artboards)); + h.state_mut().ui.dialog.as_mut().unwrap().kind = super::MORE.into(); + h.run_steps(4); + } + + fn kind(h: &Harness) -> String { + h.state().ui.dialog.as_ref().unwrap().kind.clone() + } + + /// A primary click at `at`, as a pointer makes it. + fn click_at(h: &mut Harness, at: egui::Pos2) { + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + } + + /// Press Save Preset, leaving the preset's name focused. + fn start_saving(h: &mut Harness) { + h.get_by_label("Save Preset").click(); + h.run_steps(4); + } + + /// Replace the text of field `label` with `text` and press Enter. + fn enter_in(h: &mut Harness, label: &str, text: &str) { + let all = egui::Modifiers { ctrl: true, command: true, ..Default::default() }; + h.get_by_role_and_label(Role::TextInput, label).focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, label).type_text(text); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + } + + /// More Settings opens over New Document with only what Preset Details lacks, its first field + /// takes the keyboard focus, and Done leaves New Document open with what the pop-up set. + #[test] + fn more_settings_is_a_popup_holding_only_the_artboard_layout() { + let mut h = big(); + h.get_by_label("More Settings").click(); + h.run_steps(4); + assert_eq!(kind(&h), super::MORE); + assert!(h.get_by_role_and_label(Role::TextInput, "Number of Artboards:").is_focused(), "the pop-up's first field has the focus"); + for shown in ["Number of Artboards:", "Spacing:", "Columns:", "Create", "Close"] { + let _ = h.get_by_label(shown); + } + for gone in [ + "Name:", + "Profile:", + "Size:", + "Width:", + "Height:", + "Units:", + "Orientation:", + "Bleed:", + "Background Contents:", + "Create Document", + "Templates…", + ] { + assert!(h.query_by_label(gone).is_none(), "{gone} is in the pop-up"); + } + h.get_by_label("Done").click(); + h.run_steps(3); + assert_eq!(kind(&h), super::KIND, "Done goes back to New Document"); + assert!(h.query_by_label("Spacing:").is_none()); + assert!(h.state().session.documents().is_empty()); + } + + /// Escape, a click outside and `ui.dialog.cancel` each close only the pop-up, and the fields it + /// edited stay set. Escape on New Document itself then closes the dialog. + #[test] + fn a_popup_closes_on_its_own_and_keeps_the_values() { + let mut h = big(); + open_more(&mut h, 4); + h.get_by_label(super::ArtboardLayout::Column.label()).click(); + h.run_steps(3); + assert_eq!(kind(&h), super::MORE, "a click inside keeps it open"); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(kind(&h), super::KIND, "Escape closes only the pop-up"); + assert_eq!(field(h.state(), "artboardLayout")["layout"], json!("column")); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(h.state().ui.dialog.is_none(), "the next Escape closes New Document"); + + let mut h = big(); + open_more(&mut h, 4); + let outside = h.get_by_label("PRESET DETAILS").rect().center(); + click_at(&mut h, outside); + assert_eq!(kind(&h), super::KIND, "a click outside closes the pop-up"); + assert_eq!(field(h.state(), "artboards"), json!(4)); + + open_more(&mut h, 4); + crate::dialogs::cancel(h.state_mut()); + assert_eq!(kind(&h), super::KIND, "ui.dialog.cancel closes only the pop-up"); + set(h.state_mut(), super::SAVING, json!(true)); + crate::dialogs::cancel(h.state_mut()); + assert_eq!((kind(&h), field(h.state(), super::SAVING)), (super::KIND.to_string(), json!(false)), "and Save Preset's"); + crate::dialogs::cancel(h.state_mut()); + assert!(h.state().ui.dialog.is_none(), "with no pop-up it cancels New Document"); + } + + /// A click that lands on Create, Close, a preset card or a category tab while the pop-up is open + /// only closes the pop-up: New Document stays open with the values the pop-up set. + #[test] + fn a_click_outside_the_popup_does_not_reach_the_dialog() { + let mut reached = vec![]; + for target in ["Create", "Close", "card", "Web"] { + let mut h = big(); + open_more(&mut h, 4); + let (category, preset) = (field(h.state(), "category"), field(h.state(), "preset")); + let at = if target == "card" { + // The Print tab's second card: the first is the chosen one. + let tab = h.get_by_label("Print").rect(); + egui::pos2(tab.left() + 146.0 + 12.0 + 73.0, tab.bottom() + 120.0) + } else { + h.get_by_label(target).rect().center() + }; + click_at(&mut h, at); + let kept = h.state().ui.dialog.is_some() + && kind(&h) == super::KIND + && h.state().session.documents().is_empty() + && field(h.state(), "artboards") == json!(4) + && (field(h.state(), "category"), field(h.state(), "preset")) == (category, preset); + if !kept { + reached.push(target); } } - let mut texts = vec![]; - out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); - assert!(texts.iter().any(|(t, _)| t == "Preset Name"), "the preset's name field shows"); - let at = texts.iter().find(|(t, _)| t == "Save").map(|(_, p)| *p).expect("a Save button"); - let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - run(&mut app, vec![egui::Event::PointerMoved(at), press(true)]); - run(&mut app, vec![press(false)]); - let saved = app.session.prefs.new_doc_presets.iter().find(|p| p.name == "Strip").expect("saved"); + assert!(reached.is_empty(), "the click reached {reached:?}"); + } + + /// Enter applies the field and closes the pop-up. It does not create the document. + #[test] + fn enter_in_a_popup_does_not_create_the_document() { + let mut h = big(); + open_more(&mut h, 3); + enter_in(&mut h, "Spacing:", "25"); + assert_eq!(kind(&h), super::KIND, "Enter closes the pop-up"); + assert_eq!(field(h.state(), "artboardLayout")["spacing"], json!(25.0)); + assert!(h.state().session.documents().is_empty(), "no document was made"); + } + + /// One artboard disables the layout, Spacing and Columns; Columns stays within the artboards + /// and Spacing is not negative. + #[test] + fn the_popup_keeps_the_layout_rules() { + let mut h = big(); + open_more(&mut h, 1); + for name in [super::ArtboardLayout::Row.label(), "Change to Right-to-Left Layout"] { + assert!(h.get_by_label(name).accesskit_node().is_disabled(), "{name}"); + } + for name in ["Spacing:", "Columns:"] { + assert!(h.get_by_role_and_label(Role::TextInput, name).accesskit_node().is_disabled(), "{name}"); + } + open_more(&mut h, 3); + assert!(!h.get_by_role_and_label(Role::TextInput, "Spacing:").accesskit_node().is_disabled()); + enter_in(&mut h, "Columns:", "99"); + assert_eq!(field(h.state(), "artboardLayout")["columns"], json!(3)); + open_more(&mut h, 3); + enter_in(&mut h, "Spacing:", "-5"); + assert_eq!(field(h.state(), "artboardLayout")["spacing"], json!(0.0)); + } + + /// Saving swaps the top of Preset Details for the heading, the preset's name, Cancel and Save, and + /// hides Close and Create; the rows under it stay editable, and Enter in one of them neither saves + /// nor creates. + #[test] + fn save_preset_is_a_mode_of_the_panel() { + let mut h = big(); + start_saving(&mut h); + let _ = (h.get_by_label("Save Document Preset"), h.get_by_label("Cancel"), h.get_by_label("Save")); + for gone in ["PRESET DETAILS", "Create", "Close"] { + assert!(h.query_by_label(gone).is_none(), "{gone} shows while saving"); + } + assert!(h.query_by_role_and_label(Role::TextInput, "Document Name").is_none(), "the document's name is hidden"); + let _ = (h.get_by_label("Advanced Options"), h.get_by_label("More Settings")); + enter_in(&mut h, "Artboards", "2"); + assert_eq!(field(h.state(), "artboards"), json!(2), "the rows stay editable"); + assert_eq!(field(h.state(), super::SAVING), json!(true), "Enter in a row does not save"); + assert!(h.state().session.documents().is_empty() && h.state().session.prefs.new_doc_presets.is_empty()); + h.get_by_label("More Settings").click(); + h.run_steps(4); + assert_eq!(kind(&h), super::MORE, "More Settings opens while saving"); + } + + /// Save Preset focuses the default name with its text selected, Enter in it is Save, and the + /// saved preset keeps the fields. + #[test] + fn enter_in_the_preset_name_saves() { + let mut h = big(); + set(h.state_mut(), "artboards", json!(3)); + h.run_steps(2); + start_saving(&mut h); + assert_eq!(field(h.state(), "presetName"), json!("Preset 1")); + assert!(h.get_by_role_and_label(Role::TextInput, "Preset Name").is_focused()); + h.event(egui::Event::Text("Trio".into())); + h.run_steps(2); + assert_eq!(field(h.state(), "presetName"), json!("Trio"), "typing replaced the selected text"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + let saved = h.state().session.prefs.new_doc_presets.iter().find(|p| p.name == "Trio").expect("Enter saved it"); + assert_eq!(saved.artboards, 3); + assert_eq!((field(h.state(), super::SAVING), field(h.state(), "artboards")), (json!(false), json!(3)), "the fields stay"); + assert_eq!(field(h.state(), "name"), json!("Untitled-1")); + assert!(h.state().session.documents().is_empty() && h.state().ui.dialog.is_some()); + } + + /// Save Preset's default name is the first "Preset N" no saved preset has, after a save as well. + #[test] + fn the_next_save_offers_a_new_name() { + let mut h = big(); + start_saving(&mut h); + assert_eq!(field(h.state(), "presetName"), json!("Preset 1")); + h.get_by_label("Save").click(); + h.run_steps(3); + start_saving(&mut h); + assert_eq!(field(h.state(), "presetName"), json!("Preset 2"), "not the saved preset's name"); + set(h.state_mut(), "presetName", json!("preset 3")); + h.run_steps(2); + h.get_by_label("Save").click(); + h.run_steps(3); + start_saving(&mut h); + assert_eq!(field(h.state(), "presetName"), json!("Preset 2"), "not a name a saved preset has"); + } + + /// A New Document that opens already saving (as a control client can set it) fills in and focuses + /// the default name, also after the last one was closed while saving. + #[test] + fn a_dialog_that_opens_saving_fills_in_the_name() { + let mut h = big(); + start_saving(&mut h); + h.state_mut().ui.dialog = None; + h.run_steps(2); + h.state_mut().run("file.newDialog", json!({})).unwrap(); + set(h.state_mut(), super::SAVING, json!(true)); + h.run_steps(4); + assert_eq!(field(h.state(), "presetName"), json!("Preset 1")); + assert!(h.get_by_role_and_label(Role::TextInput, "Preset Name").is_focused()); + } + + /// Enter that is still held after Enter saved a preset does not create the document. + #[test] + fn a_held_enter_after_a_save_does_not_create() { + let mut h = big(); + start_saving(&mut h); + let enter = |repeat| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat, modifiers: Default::default() }; + // Pressed and not released: the next presses are the key's repeats. + h.event(enter(false)); + h.run_steps(1); + assert_eq!(field(h.state(), super::SAVING), json!(false), "Enter saved"); + for _ in 0..3 { + h.event(enter(true)); + h.run_steps(1); + } + assert!(h.state().session.documents().is_empty() && h.state().ui.dialog.is_some()); + } + + /// Escape in the mode is Cancel: it saves nothing, keeps edits made to the fields, and New Document + /// stays open. The Cancel button does the same. + #[test] + fn escape_and_cancel_leave_saving_and_keep_the_edits() { + let mut h = big(); + start_saving(&mut h); + set(h.state_mut(), "artboards", json!(5)); + h.run_steps(2); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!((field(h.state(), super::SAVING), field(h.state(), "artboards")), (json!(false), json!(5)), "Escape keeps the edits"); + assert!(h.state().session.prefs.new_doc_presets.is_empty(), "and saves nothing"); + assert!(h.state().ui.dialog.is_some(), "and New Document stays open"); + + start_saving(&mut h); + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert_eq!(field(h.state(), super::SAVING), json!(false)); + let _ = h.get_by_label("Create"); + } + + /// `ui.dialog.confirm` while saving is Save: it stores the preset and creates no document. + #[test] + fn confirm_while_saving_does_not_create_a_document() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + frame(&mut app); + set(&mut app, super::SAVING, json!(true)); + set(&mut app, "presetName", json!("Zed")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.session.documents().is_empty() && app.session.prefs.new_doc_presets.iter().any(|p| p.name == "Zed")); + assert_eq!((field(&app, super::SAVING), field(&app, "category")), (json!(false), json!("Saved"))); + set(&mut app, super::SAVING, json!(true)); + set(&mut app, "presetName", json!("")); + assert!(crate::dialogs::confirm(&mut app).is_err(), "an empty name is refused"); + assert_eq!(field(&app, super::SAVING), json!(true)); + assert!(app.session.documents().is_empty()); + } + + /// The preset keeps the artboard layout, spacing and columns set in More Settings' pop-up + /// (#4893), and New Document stays open on it. An empty name stays in the mode. + #[test] + fn save_preset_saves_what_more_settings_set() { + let mut h = big(); + open_more(&mut h, 4); + enter_in(&mut h, "Spacing:", "30"); + open_more(&mut h, 4); + h.get_by_label(super::ArtboardLayout::Column.label()).click(); + h.run_steps(3); + h.get_by_label("Change to Right-to-Left Layout").click(); + h.run_steps(3); + h.get_by_label("Done").click(); + h.run_steps(3); + h.get_by_label("Save Preset").click(); + h.run_steps(4); + assert!(field(h.state(), super::SAVING) == json!(true) && h.get_by_role_and_label(Role::TextInput, "Preset Name").is_focused()); + let _ = (h.get_by_label("Save"), h.get_by_label("Cancel")); + set(h.state_mut(), "presetName", json!(" ")); + h.run_steps(2); + h.get_by_label("Save").click(); + h.run_steps(3); + assert_eq!(field(h.state(), super::SAVING), json!(true), "an empty name stays in the mode"); + set(h.state_mut(), "presetName", json!("Strip")); + h.run_steps(2); + h.get_by_label("Save").click(); + h.run_steps(3); + let saved = h.state().session.prefs.new_doc_presets.iter().find(|p| p.name == "Strip").expect("saved"); assert_eq!(saved.artboards, 4); + assert!(saved.right_to_left); assert_eq!((saved.layout, saved.spacing), (super::ArtboardLayout::Column, 30.0)); - assert_eq!((field(&app, "category"), field(&app, "preset"), field(&app, super::SAVING)), (json!("Saved"), json!("Strip"), json!(false))); - assert_eq!(app.ui.dialog.as_ref().unwrap().kind, super::MORE, "More Settings stays open"); + assert_eq!( + (field(h.state(), "category"), field(h.state(), "preset"), field(h.state(), super::SAVING)), + (json!("Saved"), json!("Strip"), json!(false)) + ); + assert_eq!(kind(&h), super::KIND, "New Document stays open"); + assert!(h.state().session.documents().is_empty()); + } + + /// In a small window the pop-up stays on screen, and its button stays in view under rows that scroll. + #[test] + fn the_popup_stays_inside_a_small_window() { + let mut h = harness(egui::vec2(480.0, 260.0)); + open_more(&mut h, 3); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 260.0)); + for label in ["Number of Artboards:", "Done"] { + assert!(screen.contains_rect(h.get_by_label(label).rect()), "{label} is off screen"); + } } } diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 8c13a9b612..7bb471a76e 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -137,6 +137,35 @@ fn summary_warnings_are_translated() { assert_eq!(warning_line(fr, "no row: for this note"), "⚠ no row\u{a0}: for this note"); } +/// The warnings and the error for a page longer than 14,400 pt are translated: a PDF 1.5 file +/// written as PDF 1.6, a page with a `UserUnit`, a PDF/X-4 page in points, a refused PDF/X-1a +/// file and a page too narrow for the `UserUnit` its long side needs. +#[test] +fn long_page_notes_are_translated() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 56_692.91, "height": 2_834.65})).unwrap(); + let mut notes: Vec = vec![]; + for p in [json!({"compatibility": "1.5"}), json!({"preset": "PDF/X-4:2010"})] { + let r = s.execute("document.exportPdf", &p).unwrap(); + let warnings = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()); + notes.extend(warnings.filter(|w| w.contains("14,400 pt")).map(str::to_string)); + } + notes.push(s.execute("document.exportPdf", &json!({"preset": "PDF/X-1a:2001"})).unwrap_err().to_string()); + s.execute("file.new", &json!({"width": 85_040, "height": 17})).unwrap(); + let r = s.execute("document.exportPdf", &json!({})).unwrap(); + let warnings = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()); + notes.extend(warnings.filter(|w| w.contains("too long and narrow")).map(str::to_string)); + assert_eq!(notes.len(), 5, "{notes:?}"); + let english = ["has no UserUnit, which", "apps that ignore UserUnit", "apps that keep to the limit", "real numbers up to", "too long and narrow"]; + for code in ["de", "fr", "ja", "zh-hans"] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + for note in ¬es { + let shown = warning_line(lang, note); + assert!(english.iter().all(|e| !shown.contains(e)), "{code}: {shown}"); + } + } +} + /// A placed image whose pixel data can't be decoded is left out of the PDF, and the status bar /// shows the note raster exports give. #[test] diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs new file mode 100644 index 0000000000..2ef43cb8fe --- /dev/null +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -0,0 +1,147 @@ +//! File › Scripts › Other Script…: choosing a JavaScript file and the warning before it runs +//! (`script.run` runs it), the question a run that keeps adding art asks, and the question quitting +//! asks while a script runs. +//! +//! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it +//! asks for a `.js` or `.jsx` file (the web opens the browser's file picker). With Preferences › +//! General › Show External Script Warning off, the chosen script runs at once. Warning fields: +//! `name`, `script` (`script.run`'s params) and `dontShow` (true: turn the warning off). + +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; + +use super::DialogSpec; +use crate::state::Dialog; +use crate::theme::{self, Tokens}; +use crate::{FilePick, VectorcraftApp, widgets}; + +/// The dialog kind of the warning before a script runs. +pub const KIND: &str = "scriptRun"; +/// The dialog kind of the question a run asks when it has added a great deal. +pub const GROWTH_KIND: &str = "scriptGrowth"; +/// The dialog kind of the question quitting asks while a script runs. +pub const CLOSE_KIND: &str = "scriptClose"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Run Script").into(), + body, + confirm, + ok: Some("Run"), + min_width: 420.0, + max_width: Some(520.0), + ..DialogSpec::FORM +}; + +pub(super) const GROWTH_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("A Script Is Running").into(), + body: |_, ui, _| { + ui.label(tl!("This script has added a great many objects. Continue, or stop it and undo what it did?")); + false + }, + confirm: growth_confirm, + ok: Some("Continue"), + cancel: Some("Stop"), + min_width: 420.0, + max_width: Some(520.0), + ..DialogSpec::FORM +}; + +pub(super) const CLOSE_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("A Script Is Running").into(), + body: |_, ui, _| { + ui.label(tl!("Stop the script and undo what it did? Then quit again.")); + false + }, + confirm: close_confirm, + ok: Some("Stop"), + min_width: 420.0, + max_width: Some(520.0), + ..DialogSpec::FORM +}; + +/// A file the web's picker delivered: its name and bytes, or `None` for a file over +/// [`vectorcraft_engine::script::MAX_SOURCE_BYTES`], which is not read. +pub type ScriptInbox = std::sync::Arc>)>>>; + +/// Shows the warning for the next script the web's picker delivered, once no dialog is open. A +/// picker that was canceled delivers nothing. +pub(crate) fn drain(app: &mut VectorcraftApp) { + if app.ui.dialog.is_some() { + return; + } + let Some((name, bytes)) = app.services.script_inbox.as_ref().and_then(|q| q.lock().unwrap_or_else(|e| e.into_inner()).pop()) else { return }; + let result = match bytes.as_deref().map(std::str::from_utf8) { + None => Err(TOO_LARGE.to_string()), + Some(Ok(source)) => chosen(app, json!({"source": source, "name": name})), + Some(Err(_)) => Err("the script is not UTF-8 text".to_string()), + }; + if let Err(e) = result { + app.status(e); + } +} + +/// `ui.runScript`: the script at `path` or given as `source`; without either, pick a file. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { + if p.get("path").is_some() || p.get("source").is_some() { + return chosen(app, p.clone()); + } + if let Some(pick) = app.services.script_async.as_mut() { + pick(); + return Ok(Value::Null); + } + let pick = FilePick { filters: vec![FilePick::filter("Scripts", RUN_EXTS)], ..Default::default() }; + let path = crate::picks::open(app, &pick).ok_or("cancelled")?; + chosen(app, json!({ "path": path })) +} + +/// A script was chosen: `params` are `script.run`'s. It runs after the warning, when that is on. +pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result { + let path = params.get("path").and_then(Value::as_str); + if path.is_some_and(|path| !runs(path)) { + return Err("Choose a .js or .jsx script".into()); + } + if !app.session.prefs.show_external_script_warning { + return app.run("script.run", params); + } + let name = params.get("name").and_then(Value::as_str).or(path).map_or_else(|| "script".to_string(), vectorcraft_engine::cmd::fileio::file_name); + app.ui.dialog = Some(Dialog::new(KIND, json!({"name": name, "script": params, "dontShow": false}))); + Ok(Value::Null) +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(d.fields.get("name").and_then(Value::as_str).unwrap_or_default()).font(theme::semibold(12.5)).color(t.text_strong)); + ui.add_space(4.0); + ui.label(tl!("A script can change the open documents and can write files through the commands it runs. Run only scripts you trust.")); + ui.add_space(8.0); + let dont_show = d.fields.get("dontShow").and_then(Value::as_bool).unwrap_or(false); + if widgets::check(ui, tl!("Do not show this warning again"), dont_show, true) { + d.fields.insert("dontShow".into(), json!(!dont_show)); + } + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.get("dontShow").and_then(Value::as_bool).unwrap_or(false) { + app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false}))?; + } + let script = d.fields.get("script").cloned().unwrap_or(Value::Null); + app.ui.dialog = None; + app.run("script.run", script) +} + +fn growth_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { + app.ui.dialog = None; + app.session.script_continue(); + Ok(Value::Null) +} + +fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { + app.ui.dialog = None; + if app.session.script_abandon() { + let error = app.session.script_failure_text().unwrap_or_default(); + crate::script_runs::failed(app, error); + app.sync_views(); + } + Ok(Value::Null) +} diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 7783e205f8..c5bdfea5c8 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -660,6 +660,7 @@ impl PluginIntField { budget: Default::default(), paint_output: false, commands: Vec::new(), + command_allowlist: Vec::new(), }; let mut f = PluginIntField { ctx, d: Dialog::new(plugin::KIND, json!({ "seed": start })), m, pos: egui::Pos2::ZERO }; fn number_rect(shape: &egui::Shape, text: &str) -> Option { diff --git a/crates/ui-egui/src/dialogs/tests_accessibility.rs b/crates/ui-egui/src/dialogs/tests_accessibility.rs index 8525fd8bb2..d3ef1ce8ce 100644 --- a/crates/ui-egui/src/dialogs/tests_accessibility.rs +++ b/crates/ui-egui/src/dialogs/tests_accessibility.rs @@ -86,9 +86,8 @@ fn document_setup_names_each_bleed_side() { fn new_document_names_its_fields_by_their_captions() { let mut app = app(); app.run("file.newDialog", json!({})).unwrap(); - app.ui.dialog.as_mut().expect("New Document is open").fields.insert("__saving".into(), json!(true)); let h = strict(app); - for name in ["Document Name", "Preset Name", "Width", "Height", "Artboards"] { + for name in ["Document Name", "Width", "Height", "Artboards"] { let _ = h.get_by_role_and_label(Role::TextInput, name); } for name in ["Units", "Background Contents"] { @@ -96,7 +95,7 @@ fn new_document_names_its_fields_by_their_captions() { } } -/// New Document's More Settings, with Save Preset open, leaves no field unnamed. +/// New Document's More Settings pop-up and Save Preset mode leave no field unnamed. #[test] fn new_document_more_settings_names_its_fields() { let mut app = app(); @@ -104,8 +103,11 @@ fn new_document_more_settings_names_its_fields() { let d = app.ui.dialog.as_mut().expect("New Document is open"); d.kind = super::new_document::MORE.into(); d.fields.insert("__saving".into(), json!(true)); + d.fields.insert("artboards".into(), json!(3)); let h = strict(app); - let _ = h.get_by_role_and_label(Role::TextInput, "Preset Name"); + for name in ["Preset Name", "Number of Artboards:", "Spacing:", "Columns:"] { + let _ = h.get_by_role_and_label(Role::TextInput, name); + } } /// Split Into Grid keeps translated visible labels while naming row and column gutter and total diff --git a/crates/ui-egui/src/dialogs/tests_revolve_gizmo.rs b/crates/ui-egui/src/dialogs/tests_revolve_gizmo.rs index 0249bb1999..46c912170b 100644 --- a/crates/ui-egui/src/dialogs/tests_revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/tests_revolve_gizmo.rs @@ -2,6 +2,7 @@ use super::*; use crate::{dialogs, theme}; use egui::{Event, Modifiers, PointerButton}; +use serde_json::Value; use vectorcraft_effects::revolve_options; use vectorcraft_engine::Session; @@ -284,3 +285,90 @@ fn selected_light_gizmo_edits_only_that_light_and_escape_restores_the_list() { h.release(p + vec2(80.0, 0.0), Modifiers::NONE); assert_eq!(h.app.ui.dialog.as_ref().unwrap().fields["lights"], before); } + +impl Harness { + /// A fresh document where `build` runs and Extrude & Bevel's dialog opens, its Preview `on`. + fn extrude_dialog(build: &[(&str, Value)], on: bool) -> Self { + let mut h = Self::new(); + dialogs::cancel(&mut h.app); + h.app.run("file.new", json!({"width":300,"height":300})).unwrap(); + for (id, p) in build { + h.app.run(id, p.clone()).unwrap(); + } + h.app.run("effect.dialog", json!({"effect": vectorcraft_effects::EXTRUDE})).unwrap(); + h.app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(on)); + h.settle(); + h + } + + fn ok_is_on(&self) -> bool { + let d = self.app.ui.dialog.as_ref().unwrap(); + dialogs::spec(&d.kind).ok_enabled.is_none_or(|f| f(&self.app, d)) + } + + /// Does the next frame of the dialog draw a text holding `text`? + fn shows(&mut self, text: &str) -> bool { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1280.0, 900.0))), ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| dialogs::show(&mut self.app, ui.ctx())); + out.textures_delta.clear(); + out.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.job.text.contains(text))) + } +} + +fn an_image() -> Vec<(&'static str, Value)> { + let data = vectorcraft_format::base64_encode(&crate::tests_sysclip::blue_png()); + vec![("file.place", json!({"name": "blue.png", "dataBase64": data, "link": false, "at": [150, 150]}))] +} + +/// #6140: on an object a 3D effect can't take, the dialog says why in its own words, and OK, which +/// could only fail, is off, where it used to look as if OK did nothing. +#[test] +fn a_refused_3d_effect_says_why_and_turns_ok_off() { + let mut h = Harness::extrude_dialog(&an_image(), true); + assert!(!h.ok_is_on()); + assert!(h.shows("can't build a solid from an image")); + assert!(!h.shows("effect.apply"), "the reason is written without the command's id"); + let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + h.frame(vec![enter], Modifiers::NONE); + assert!(h.app.ui.dialog.is_some()); +} + +/// With Preview off from the start, nothing has tried the effect: the dialog still finds out, +/// and trying it leaves no preview open. +#[test] +fn a_refused_3d_effect_is_found_with_preview_off() { + let mut h = Harness::extrude_dialog(&an_image(), false); + assert!(!h.ok_is_on()); + assert!(h.shows("can't build a solid from an image")); + assert!(!h.app.session.in_interaction()); +} + +/// With Preview off, trying the values waits for another interaction to end: trying them during +/// one would replace its preview and cancel it. +#[test] +fn a_3d_effect_with_preview_off_leaves_another_interaction_alone() { + let mut h = Harness::extrude_dialog(&an_image(), false); + h.app.session.begin_interaction("Drag").unwrap(); + let d = h.app.ui.dialog.as_mut().unwrap(); + d.fields.remove("__tried"); + d.fields.remove(dialogs::form::REFUSED); + h.settle(); + assert!(h.app.session.in_interaction(), "the other interaction goes on"); + assert!(h.ok_is_on(), "nothing has tried the values yet"); + h.app.session.cancel_interaction().unwrap(); + assert!(h.shows("can't build a solid from an image")); + assert!(!h.ok_is_on()); + assert!(!h.app.session.in_interaction()); +} + +/// An object the effect can take keeps OK on, with Preview on or off, and shows no reason. +#[test] +fn an_accepted_3d_effect_keeps_ok_on() { + let build = [("shape.rectangle", json!({"x":60,"y":60,"width":100,"height":100}))]; + for on in [true, false] { + let mut h = Harness::extrude_dialog(&build, on); + assert!(h.ok_is_on(), "Preview {on}"); + assert!(!h.shows("requires a path"), "Preview {on}"); + assert_eq!(h.app.session.in_interaction(), on); + } +} diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 1896b8ed92..0014047657 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -12,6 +12,8 @@ //! the mouse wheel turned over the closed field applies the next family (or previous one) to the //! selected text, one undo step per notch. The menu's order at the first turn stays fixed until the //! pointer leaves the field or the text selection changes; steps stop at its first and last family. +//! The field takes the wheel only when the pointer was moved onto it after the field last moved or +//! was covered by a window or overlay, and the wheel stream began there. use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -24,6 +26,7 @@ use vectorcraft_text::FontClass; use crate::VectorcraftApp; use crate::theme::Tokens; use crate::widgets; +use crate::widgets::{ArmedWheelField, WheelStream, WheelStreamOwner}; /// What happened in the menu this frame. #[derive(Clone, Debug, PartialEq)] @@ -478,6 +481,8 @@ struct WheelFields { pending: HashMap>, queued: Vec, replay: Vec, + armed: Option, + stream: WheelStream, } #[cfg(not(target_arch = "wasm32"))] @@ -524,6 +529,7 @@ impl egui::Plugin for WheelLayerSnapshot { let id = event.field.with("wheel"); if !active { ctx.data_mut(|d| d.remove::(id)); + fields.stream.release(event.field); if let Some(target) = ctx.layer_id_at(event.position) { fields.replay.push(ReplayWheel { target, position: event.position, event: event.event }); } @@ -636,7 +642,8 @@ pub(crate) fn sync_wheel_target(app: &VectorcraftApp, ctx: &egui::Context, viewp let key = wheel_fields_id(viewport); let (previous, mut fields) = ctx.data(|d| (d.get_temp::(key.with("target")), d.get_temp::(key))); if previous.is_some_and(|old| old != target) { - fields = None; + // A new target keeps the armed field and the running wheel stream. + fields = fields.map(|old| WheelFields { pass: old.pass, armed: old.armed, stream: old.stream, ..Default::default() }); } let mut hidden = Vec::new(); if let Some(fields) = &mut fields { @@ -678,6 +685,9 @@ fn remember_wheel_field(ui: &Ui, resp: &egui::Response, enabled: bool) -> Vec) -> Vec { let key = wheel_fields_id(ui.ctx().viewport_id()); let pass = ui.ctx().cumulative_pass_nr(); + // A window or overlay over the pointer covers the field even when no input arrives. + let pointer = ui.data_mut(|d| d.get_temp_mut_or_default::(key).pointer).or_else(|| ui.ctx().input(|i| i.pointer.latest_pos())); + let covered = pointer.is_some_and(|p| resp.interact_rect.contains(p) && ui.ctx().layer_id_at(p) != Some(resp.layer_id)); ui.data_mut(|d| { let mut fields: WheelFields = d.get_temp(key).unwrap_or_default(); if fields.pass != pass { @@ -685,6 +695,16 @@ fn remember_owned_wheel_field(ui: &Ui, resp: &egui::Response, enabled: bool, men fields.fields.clear(); } fields.fields.retain(|f| f.id != resp.id); + if let Some(armed) = &mut fields.armed + && armed.id == resp.id + { + if armed.rect == resp.interact_rect && pass.saturating_sub(armed.pass) <= 1 && !covered { + armed.pass = pass; + } else { + fields.armed = None; + fields.stream.release(resp.id); + } + } if enabled { fields.fields.push(WheelField { id: resp.id, menu, owner, rect: resp.interact_rect, layer: resp.layer_id }); } @@ -695,7 +715,10 @@ fn remember_owned_wheel_field(ui: &Ui, resp: &egui::Response, enabled: bool, men } /// Take the closed font fields' wheel events before egui smooths and combines them. Other -/// events stay in the input, so scrolling elsewhere keeps its own delta and event order. +/// events stay in the input, so scrolling elsewhere keeps its own delta and event order. A field +/// takes a wheel stream only when the stream begins with the pointer over it and the pointer was +/// moved onto it after the field last moved or was covered. A stream that began anywhere else +/// stays there until it ends, and a stream that leaves its field does not return to it. pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { let key = wheel_fields_id(raw.viewport_id); let Some(mut fields) = ctx.data(|d| d.get_temp::(key)) else { return }; @@ -712,7 +735,10 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { if pass < fields.pass || pass.saturating_sub(fields.pass) > 1 { fields.fields.clear(); fields.pointer = None; + fields.armed = None; + fields.stream.release_any(); } + let now = raw.time.unwrap_or_else(|| ctx.input_for(raw.viewport_id, |i| i.time) + f64::from(raw.predicted_dt)); if fields.pending_frame != frame { fields.pending_frame = frame; fields.pending.clear(); @@ -766,8 +792,20 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { { fields.activating.push(id); } + if matches!(event, egui::Event::MouseWheel { .. }) { + fields.stream.note_input(now); + } match event { egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } => { + if pointer != Some(*p) { + let pass = fields.pass; + fields.armed = fields.fields.iter().rev().find(|f| over(f, Some(*p))).map(|f| ArmedWheelField { id: f.id, rect: f.rect, pass }); + if let Some(WheelStreamOwner::Field(id)) = fields.stream.owner + && !fields.fields.iter().any(|f| f.id == id && over(f, Some(*p))) + { + fields.stream.release(id); + } + } mark_queued_wheel_leaves(&mut fields, Some(*p)); for field in &fields.fields { if pointer.is_some_and(|point| field.rect.contains(point)) @@ -782,6 +820,8 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { } egui::Event::PointerGone => { pointer = None; + fields.armed = None; + fields.stream.release_any(); mark_queued_wheel_leaves(&mut fields, None); for field in &fields.fields { if !fields.queued.iter().any(|event| event.field == field.id) { @@ -790,8 +830,13 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { } } } - egui::Event::MouseWheel { unit, delta, modifiers, .. } if modifiers.is_none() && delta.y != 0.0 => { - if let Some(field) = fields.fields.iter().rev().find(|f| !fields.activating.contains(&f.id) && over(f, pointer)).copied() { + egui::Event::MouseWheel { unit, delta, modifiers, source, .. } if modifiers.is_none() && delta.y != 0.0 => { + let under = fields.fields.iter().rev().find(|f| !fields.activating.contains(&f.id) && over(f, pointer)).copied(); + let starts_on_field = under + .filter(|f| fields.armed.is_some_and(|armed| armed.id == f.id) && !matches!(source, egui::MouseWheelSource::Momentum)) + .map(|f| f.id); + let owner = *fields.stream.owner.get_or_insert(starts_on_field.map_or(WheelStreamOwner::Elsewhere, WheelStreamOwner::Field)); + if let Some(field) = under.filter(|f| owner == WheelStreamOwner::Field(f.id)) { let amount = -match unit { egui::MouseWheelUnit::Point => delta.y / line, egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => delta.y, @@ -823,6 +868,10 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { captured = true; return false; } + fields.stream.owner = Some(WheelStreamOwner::Elsewhere); + } + egui::Event::MouseWheel { delta, .. } if *delta != egui::Vec2::ZERO => { + fields.stream.owner.get_or_insert(WheelStreamOwner::Elsewhere); } _ => {} } @@ -848,6 +897,7 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { fields.pointer = pointer; ctx.data_mut(|d| d.insert_temp(key, fields)); if captured { + ctx.data_mut(|d| d.insert_temp(widgets::taken_from_raw_id(raw.viewport_id), now)); ctx.request_repaint(); } } diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 73db46de30..a054794379 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -355,6 +355,335 @@ fn activating_the_family_popup_leaves_its_wheel_input_available() { } } +/// A family field at `top`, the input's clock at `time`. Returns the wheel events left in the +/// input, the notches the field took and the point in the middle of the field. +fn stream_frame(ctx: &egui::Context, top: Option, time: f64, events: Vec) -> (usize, i32, egui::Pos2) { + covered_stream_frame(ctx, top, false, time, events) +} + +/// [`stream_frame`], with an overlay over the whole field when `covered` is set. +fn covered_stream_frame(ctx: &egui::Context, top: Option, covered: bool, time: f64, events: Vec) -> (usize, i32, egui::Pos2) { + let mut raw = egui::RawInput { time: Some(time), events, ..Default::default() }; + super::take_raw_wheel(ctx, &mut raw); + let left = raw.events.iter().filter(|e| matches!(e, egui::Event::MouseWheel { .. })).count(); + let mut notches = 0; + let mut point = egui::Pos2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + let Some(top) = top else { return }; + let rect = egui::Rect::from_min_size(egui::pos2(10.0, top), egui::vec2(120.0, 24.0)); + let resp = ui.put(rect, egui::Button::new("Family")); + point = resp.rect.center(); + for turn in super::remember_wheel_field(ui, &resp, true) { + if let super::WheelInput::Notches(n) = turn { + notches += n; + } + } + if covered { + let cover = rect.expand(5.0); + egui::Area::new(egui::Id::unique("stream overlay")).order(egui::Order::Foreground).fixed_pos(cover.min).show(ui.ctx(), |ui| { + ui.allocate_exact_size(cover.size(), egui::Sense::click()); + }); + } + }); + out.textures_delta.clear(); + (left, notches, point) +} + +fn stream_turn(phase: egui::TouchPhase, source: egui::MouseWheelSource, dy: f32) -> egui::Event { + egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: egui::vec2(0.0, dy), phase, modifiers: Default::default(), source } +} + +fn plain_turn() -> egui::Event { + stream_turn(egui::TouchPhase::Move, egui::MouseWheelSource::Unknown, -1.0) +} + +/// A context with a family field drawn at `top` for three frames, from clock time 100. +fn stream_context(top: f32) -> (egui::Context, egui::Pos2) { + let ctx = egui::Context::default(); + let mut point = egui::Pos2::ZERO; + for i in 0..3 { + point = stream_frame(&ctx, Some(top), 100.0 + f64::from(i), vec![]).2; + } + (ctx, point) +} + +/// A wheel stream the family field took stays its own when the pointer moves onto a number field +/// beside it: the number field steps only after the wheel pauses for the stream gap. +#[test] +fn a_stream_the_family_field_took_leaves_a_number_field_beside_it() { + let ctx = egui::Context::default(); + let value = std::cell::Cell::new(10.0); + let (family, number) = (std::cell::Cell::new(egui::Pos2::ZERO), std::cell::Cell::new(egui::Pos2::ZERO)); + let frame = |time: f64, events: Vec| { + let mut raw = egui::RawInput { time: Some(time), events, ..Default::default() }; + super::take_raw_wheel(&ctx, &mut raw); + let mut notches = 0; + let mut out = ctx.run_ui(raw, |ui| { + let resp = ui.put(egui::Rect::from_min_size(egui::pos2(10.0, 40.0), egui::vec2(120.0, 24.0)), egui::Button::new("Family")); + family.set(resp.rect.center()); + for turn in super::remember_wheel_field(ui, &resp, true) { + if let super::WheelInput::Notches(n) = turn { + notches += n; + } + } + ui.add_space(40.0); + let top = ui.cursor().top(); + if let Some(v) = crate::widgets::plain_field(ui, "size", value.get(), "", 0, 80.0) { + value.set(v); + } + number.set(egui::pos2(ui.min_rect().left() + 20.0, (top + ui.min_rect().bottom()) / 2.0)); + }); + out.textures_delta.clear(); + notches + }; + for i in 0..3 { + frame(100.0 + f64::from(i), vec![]); + } + assert_eq!(frame(110.0, vec![egui::Event::PointerMoved(family.get()), plain_turn()]), 1, "the family field took the turn"); + frame(110.1, vec![egui::Event::PointerMoved(number.get()), plain_turn()]); + assert_eq!(value.get(), 10.0, "the stream began on the family field"); + frame(110.1 + crate::widgets::WHEEL_STREAM_GAP + 0.1, vec![plain_turn()]); + assert_eq!(value.get(), 9.0, "a new stream"); +} + +/// A field that moved under a pointer that stayed put leaves the wheel, including a reported +/// pointer position that did not change, until the pointer really moves. +#[test] +fn a_field_that_slides_under_a_still_pointer_leaves_the_wheel() { + let (ctx, point) = stream_context(40.0); + let below = egui::pos2(point.x, point.y + 200.0); + stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(below)]); + stream_frame(&ctx, Some(40.0 + 200.0), 111.0, vec![]); + let (left, notches, moved) = stream_frame(&ctx, Some(240.0), 120.0, vec![plain_turn()]); + assert_eq!(moved, below); + assert_eq!((left, notches), (1, 0), "the pointer did not move"); + let (left, notches, _) = stream_frame(&ctx, Some(240.0), 130.0, vec![egui::Event::PointerMoved(below), plain_turn()]); + assert_eq!((left, notches), (1, 0), "a report of the same position is not a move"); + let nudged = below + egui::vec2(2.0, 0.0); + let (left, notches, _) = stream_frame(&ctx, Some(240.0), 140.0, vec![egui::Event::PointerMoved(nudged), plain_turn()]); + assert_eq!((left, notches), (0, 1), "the pointer moved onto the field"); +} + +/// A field the pointer was moved onto loses that when the field moves, even back to the same +/// place, or when it is missing from a pass. +#[test] +fn a_field_that_moves_away_and_back_needs_the_pointer_moved_again() { + let (ctx, point) = stream_context(40.0); + stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point)]); + stream_frame(&ctx, Some(44.0), 111.0, vec![]); + stream_frame(&ctx, Some(40.0), 112.0, vec![]); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 120.0, vec![plain_turn()]); + assert_eq!((left, notches), (1, 0), "the field moved after the pointer did"); + + let (ctx, point) = stream_context(40.0); + stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point)]); + stream_frame(&ctx, None, 111.0, vec![]); + stream_frame(&ctx, Some(40.0), 112.0, vec![]); + stream_frame(&ctx, Some(40.0), 113.0, vec![]); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 120.0, vec![plain_turn()]); + assert_eq!((left, notches), (1, 0), "the field was gone for a pass"); + + let (ctx, point) = stream_context(40.0); + stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point), egui::Event::PointerGone]); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 120.0, vec![plain_turn()]); + assert_eq!((left, notches), (1, 0), "the pointer left the window"); +} + +/// An overlay that comes and goes over a still pointer, with no input while it is up, leaves the +/// field needing the pointer moved again; a stream the field held leaves it. +#[test] +fn a_field_covered_by_an_overlay_needs_the_pointer_moved_again() { + let (ctx, point) = stream_context(40.0); + stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point)]); + covered_stream_frame(&ctx, Some(40.0), true, 111.0, vec![]); + covered_stream_frame(&ctx, Some(40.0), true, 112.0, vec![]); + stream_frame(&ctx, Some(40.0), 113.0, vec![]); + stream_frame(&ctx, Some(40.0), 114.0, vec![]); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 120.0, vec![plain_turn()]); + assert_eq!((left, notches), (1, 0), "the overlay covered the field"); + let nudged = point + egui::vec2(2.0, 0.0); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 130.0, vec![egui::Event::PointerMoved(nudged), plain_turn()]); + assert_eq!((left, notches), (0, 1), "the pointer moved onto the field again"); + + let (ctx, point) = stream_context(40.0); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (0, 1)); + covered_stream_frame(&ctx, Some(40.0), true, 110.1, vec![]); + covered_stream_frame(&ctx, Some(40.0), true, 110.2, vec![]); + stream_frame(&ctx, Some(40.0), 110.3, vec![]); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.4, vec![plain_turn()]); + assert_eq!((left, notches), (1, 0), "the overlay covered the field during the stream"); +} + +/// A field missing from a pass loses the pointer's placement while another font field keeps +/// drawing in that pass, as when a panel collapses and the Control bar's field stays. +#[test] +fn a_field_gone_for_a_pass_beside_another_field_needs_the_pointer_moved_again() { + let ctx = egui::Context::default(); + let field_at = |ui: &mut egui::Ui, top: f32| { + let rect = egui::Rect::from_min_size(egui::pos2(10.0, top), egui::vec2(120.0, 24.0)); + let resp = ui.put(rect, egui::Button::new("Family")); + super::remember_wheel_field(ui, &resp, true); + }; + let frame = |time: f64, family: bool, events: Vec| { + let mut raw = egui::RawInput { time: Some(time), events, ..Default::default() }; + super::take_raw_wheel(&ctx, &mut raw); + let left = raw.events.iter().filter(|e| matches!(e, egui::Event::MouseWheel { .. })).count(); + let mut out = ctx.run_ui(raw, |ui| { + field_at(ui, 200.0); + if family { + field_at(ui, 40.0); + } + }); + out.textures_delta.clear(); + left + }; + for i in 0..3 { + frame(100.0 + f64::from(i), true, vec![]); + } + let point = egui::pos2(70.0, 52.0); + assert_eq!(frame(110.0, true, vec![egui::Event::PointerMoved(point), plain_turn()]), 0, "the pointer moved onto the field"); + frame(120.0, false, vec![]); + frame(121.0, true, vec![]); + frame(122.0, true, vec![]); + assert_eq!(frame(130.0, true, vec![plain_turn()]), 1, "the field was gone for a pass"); +} + +/// A pointer at rest on a field that stayed put keeps stepping it, stream after stream. +#[test] +fn a_pointer_resting_on_its_field_keeps_the_wheel_across_streams() { + let (ctx, point) = stream_context(40.0); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (0, 1)); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0 + crate::widgets::WHEEL_STREAM_GAP / 2.0, vec![plain_turn()]); + assert_eq!((left, notches), (0, 1), "the same stream"); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 200.0, vec![plain_turn()]); + assert_eq!((left, notches), (0, 1), "a new stream, with the pointer still on the field"); +} + +/// A stream that began elsewhere stays there when the pointer moves onto a field, until a gap +/// with no wheel input ends it. +#[test] +fn a_wheel_stream_that_began_elsewhere_stays_there_until_a_gap() { + let (ctx, point) = stream_context(40.0); + let away = point + egui::vec2(0.0, 200.0); + let step = crate::widgets::WHEEL_STREAM_GAP * 0.8; + let (left, _, _) = stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(away), plain_turn()]); + assert_eq!(left, 1, "the stream began off the field"); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0 + step, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (1, 0), "a nudge onto the field does not take a running stream"); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0 + 2.0 * step, vec![plain_turn()]); + assert_eq!((left, notches), (1, 0), "each event renews the stream"); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0 + 2.0 * step + crate::widgets::WHEEL_STREAM_GAP, vec![plain_turn()]); + assert_eq!((left, notches), (0, 1), "the stream ended, and the pointer was moved onto the field"); +} + +/// A stream that leaves its field goes to what is under the pointer and does not come back. +#[test] +fn a_wheel_stream_that_leaves_its_field_does_not_return() { + let (ctx, point) = stream_context(40.0); + let away = point + egui::vec2(0.0, 200.0); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (0, 1)); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.1, vec![egui::Event::PointerMoved(away), plain_turn()]); + assert_eq!((left, notches), (1, 0), "the pointer left the field"); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.2, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (1, 0), "the stream stays off the field"); +} + +/// A stream loses its field when the pointer leaves without a wheel turn or when the field moves. +#[test] +fn a_wheel_stream_loses_its_field_when_the_pointer_leaves_or_the_field_moves() { + let (ctx, point) = stream_context(40.0); + let away = point + egui::vec2(0.0, 200.0); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (0, 1)); + stream_frame(&ctx, Some(40.0), 110.1, vec![egui::Event::PointerMoved(away)]); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.2, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (1, 0), "the pointer left the field during the stream"); + + let (ctx, point) = stream_context(40.0); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (0, 1)); + stream_frame(&ctx, Some(44.0), 110.1, vec![]); + let (left, notches, _) = stream_frame(&ctx, Some(44.0), 110.2, vec![plain_turn()]); + assert_eq!((left, notches), (1, 0), "the field moved during the stream"); + + let (ctx, point) = stream_context(40.0); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (0, 1)); + stream_frame(&ctx, Some(40.0), 110.1, vec![egui::Event::PointerGone]); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.2, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (1, 0), "the pointer left the window during the stream"); +} + +/// Trackpad momentum and zero-delta phase events keep their stream going, and momentum alone does +/// not start a stream on a field. +#[test] +fn trackpad_momentum_stays_with_its_stream() { + use egui::{MouseWheelSource::Momentum, MouseWheelSource::Trackpad, TouchPhase}; + let (ctx, point) = stream_context(40.0); + let away = point + egui::vec2(0.0, 200.0); + let step = crate::widgets::WHEEL_STREAM_GAP * 0.8; + stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(away), stream_turn(TouchPhase::Move, Trackpad, -1.0)]); + // The fingers lift with no delta, the pointer moves onto the field, and momentum follows. + stream_frame(&ctx, Some(40.0), 110.0 + step, vec![stream_turn(TouchPhase::End, Trackpad, 0.0)]); + let (left, notches, _) = + stream_frame(&ctx, Some(40.0), 110.0 + 2.0 * step, vec![egui::Event::PointerMoved(point), stream_turn(TouchPhase::Start, Momentum, -1.0)]); + assert_eq!((left, notches), (1, 0), "momentum continues the stream that began off the field"); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 200.0, vec![stream_turn(TouchPhase::Move, Momentum, -1.0)]); + assert_eq!((left, notches), (1, 0), "momentum does not start a stream on the field"); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 300.0, vec![stream_turn(TouchPhase::Move, Trackpad, -1.0)]); + assert_eq!((left, notches), (0, 1), "fingers on the trackpad do"); +} + +/// A stream that began as a sideways scroll stays off the field when it turns vertical. +#[test] +fn a_sideways_turn_that_starts_a_stream_keeps_it_off_the_field() { + let (ctx, point) = stream_context(40.0); + let sideways = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(-1.0, 0.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point), sideways]); + assert_eq!((left, notches), (1, 0)); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.1, vec![plain_turn()]); + assert_eq!((left, notches), (1, 0), "the stream began as a sideways scroll"); +} + +/// A stream loses its field when a layout pass is skipped, even though the field comes back in the +/// same place before the stream ends. +#[test] +fn a_wheel_stream_loses_its_field_when_a_pass_is_skipped() { + let (ctx, point) = stream_context(40.0); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point), plain_turn()]); + assert_eq!((left, notches), (0, 1)); + stream_frame(&ctx, None, 110.1, vec![]); + stream_frame(&ctx, Some(40.0), 110.2, vec![]); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.3, vec![plain_turn()]); + assert_eq!((left, notches), (1, 0), "the field missed a pass during the stream"); +} + +/// A modified turn is left in the input and keeps the stream away from the field. +#[test] +fn a_modified_turn_that_starts_a_stream_keeps_it_off_the_field() { + let (ctx, point) = stream_context(40.0); + let zoom = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::COMMAND, + source: egui::MouseWheelSource::Unknown, + }; + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.0, vec![egui::Event::PointerMoved(point), zoom]); + assert_eq!((left, notches), (1, 0)); + let (left, notches, _) = stream_frame(&ctx, Some(40.0), 110.1, vec![plain_turn()]); + assert_eq!((left, notches), (1, 0), "the stream began as a modified turn"); +} + /// The Font Technology filter's Variable is the font adjective, not the Variables panel's noun. #[test] fn the_variable_filter_is_named_as_fonts_are() { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 97f8b70064..354d811a34 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -284,7 +284,6 @@ font-technology Variable Променливи Update While Dragging Обновяване при плъзгане Hide Video Rulers Скриване на видеолинийките Background Contents Съдържание на фона - Background Contents: Съдържание на фона: Background: Фон: Backspace Backspace Bar Graph Tool Инструмент „Стълбчеста диаграма“ @@ -568,6 +567,7 @@ font-technology Variable Променливи Coming soon — tracked in the parity plan Очаквайте скоро — следи се в плана за съвместимост Command Click to Select Objects Behind Щракване с Command за избор на обекти отзад Command Dialog Диалогов прозорец за команда + Command API Reference Справочник за API на командите Community Общност Compatibility: Съвместимост: Compatible Gradient and Gradient Mesh Printing Съвместим печат на градиент и градиентна мрежа @@ -654,7 +654,6 @@ font-technology Variable Променливи Couldn't {} {name}: {e} Неуспешно {name} на {}: {e} Create Създаване Create Clipping Mask Създаване на маска за изрязване - Create Document Създаване на документ Create from Guides Създаване от водачи Create from Selection Създаване от селекцията Create From: Създаване от: @@ -1826,6 +1825,7 @@ font-technology Variable Променливи Lock (⌘2) Заключване (⌘2) Lock Grid Заключване на мрежата Lock Guides Заключване на водачите + Lock Guides by Default Заключване на водачите по подразбиране Lock Others Заключване на другите Lock Slices Заключване на фрагментите Lock Station Point Заключване на базовата точка @@ -2074,7 +2074,6 @@ font-technology Variable Променливи New Color Group… Нова цветова група… New Document Presets Предварителни настройки за нов документ New file Нов файл - New from Template Нов от шаблон New from Template… Нов от шаблон… New Graphic Style Нов графичен стил New Graphic Style (Alt-click to name it) Нов графичен стил (кликнете с Alt, за да го наименувате) @@ -2858,6 +2857,7 @@ digits Malayalam Малаялам Save PDF Preset Запази PDF предварителна настройка Save Perspective Grid Preset Запази предварителна настройка на перспективната мрежа Save Preset Запази предварителна настройка + Save Document Preset Запази предварителна настройка на документа Save Preset… Запази предварителна настройка… Save Print Preset Запази предварителна настройка за печат Save Recovery Data Запази данни за възстановяване @@ -3052,6 +3052,13 @@ digits Malayalam Малаялам Settings… Настройки… Setup… Настройка… Shadows and Glows Сенки и блясъци + Game HUD Игрови HUD + Health Fill Здраве + Mana Glow Мана + Damage Flash Щета + Quest Outline Квест + Coin Shine Монета + Boss Alert Бос Shape Фигура Shape Builder Създател на фигури Shape Builder Regions Области на създателя на фигури @@ -3422,7 +3429,6 @@ digits Malayalam Малаялам Template Шаблон Templates Шаблони Templates Folder Папка с шаблони - Templates… Шаблони… Text Displayed in Cell: Текст, показван в клетката: Text Export Options Опции за експортиране на текст Text Fill & Stroke Color Цвят на запълване и щрих на текста @@ -3955,6 +3961,15 @@ axis Both И двете @msg Combine Slices: the slices have no bounds Обединяване на парчета: парчетата нямат граници @msg Convert to Artboards: selection has no area Преобразуване в работни области: селекцията няма площ @msg Convert to Shape: no rectangles or ellipses selected Преобразуване в фигура: няма избрани правоъгълници или елипси + Run Изпълни + Run Script Изпълни скрипт + Stop Script Спри скрипта + Show External Script Warning Показвай предупреждение за външни скриптове + A Script Is Running Изпълнява се скрипт + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скриптът може да променя отворените документи и да записва файлове чрез командите, които изпълнява. Изпълнявайте само скриптове, на които имате доверие. + Do not show this warning again Не показвай повече това предупреждение + Stop the script and undo what it did? Then quit again. Да се спре ли скриптът и да се отменят ли промените му? След това излезте отново. + This script has added a great many objects. Continue, or stop it and undo what it did? Този скрипт добави изключително много обекти. Да продължи ли, или да се спре и да се отменят промените му? @msg Copied the script report Копиран е отчетът за скрипта @msg Corners edits the corners of a path Ъглите редактират ъглите на пътя @msg Couldn't copy to the system clipboard: {e} Неуспешно копиране в системния клипборд: {e} @@ -4980,7 +4995,8 @@ lighting Light Светлина Bevel both sides Фасет от двете страни Presets Предварителни настройки @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Един обект може да има само един 3D ефект. Редактирайте параметрите на съществуващия ефект или го премахнете предварително. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} в момента изисква път или съставен път. Първо преобразувайте текста, изображенията и групите в пътища. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} в момента изисква път, съставен път, текст, група, преливане или екземпляр на символ. Първо разширете другите обекти. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} не може да създаде тяло от изображение: първо го трасирайте с Обект › Трасиране на изображение › Създаване. @msg {label} requires a shape with at least two anchors {label} изисква форма с поне две опорни точки @msg The shape is too complex for a 3D effect Формата е твърде сложна за 3D ефект @msg The 3D surface is too complex; simplify the shape 3D повърхността е твърде сложна; опростете формата @@ -5787,6 +5803,7 @@ axis Y Axis Y ос Show its progress, see Cancel and write log lines Показване на напредъка, разпознаване на отказ и записване на редове в дневника Keep settings of its own Съхраняване на собствени настройки Keep a cache of its own, which you can clear Съхраняване на собствен кеш, който можете да изчистите + Run these commands on the document: {ids} Изпълняване на тези команди върху документа: {ids} Clear Plug-in Cache Изчистване на кеша на добавката # Actions panel: action sets (#3712). New Set… Нов набор… @@ -5836,6 +5853,11 @@ axis Y Axis Y ос Button Бутон Panel Панел UI Frames UI рамки + Map Markers Маркери на карта + Pin Карфица + Flag Флаг + Crosshair Мерник + Checkpoint Контролна точка Open Symbol Library Отваряне на библиотека със символи Save Symbol Library Запазване на библиотека със символи Save Symbol Library… Запази библиотека със символи… @@ -5884,6 +5906,11 @@ axis Y Axis Y ос User Brush Library 9 Потребителска библиотека с четки 9 User Brush Library 10 Потребителска библиотека с четки 10 Art Ribbons Арт ленти + Zigzag Зигзаг + Burst Ray Лъч на удар + Dash Trail Пунктирна следа + Speed Line Линия на скорост + Game Trails Игрови следи Calligraphic Nibs Калиграфски писци Pattern Borders Бордюри с мостри Scatter Shapes Разсеяни фигури @@ -5896,6 +5923,8 @@ axis Y Axis Y ос # Align panel menu › Align to Glyph Bounds (#4231). Point Text Точков текст Area Text Текст в зона +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Измерване на текста по границите на глифа # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Показване на опциите за прилепване към глиф Hide Snap to Glyph Options Скриване на опциите за прилепване към глиф @@ -6430,3 +6459,5 @@ breakText Glyphs Глифи # Align to Pixel Grid Align to Pixel Grid Подравняване към пикселната мрежа @msg side is left or right, not `{s}` side е left или right, а не `{s}` + Edit Custom Dictionary Редактиране на потребителски речник + Entry: Запис: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 00859a6552..d1fc0ea540 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -600,6 +600,7 @@ Hide Guides Sakrij vodilice Show Guides Prikaži vodilice Lock Guides Zaključaj vodilice + Lock Guides by Default Zaključaj vodilice po zadanom Unlock Guides Otključaj vodilice Make Guides Napravi vodilice Release Guides Oslobodi vodilice @@ -765,6 +766,13 @@ Other Library… Druga biblioteka… Graphic Style Libraries Biblioteke grafičkih stilova Shadows and Glows Sjene i sjajevi + Game HUD Igraći HUD + Health Fill Zdravlje + Mana Glow Mana + Damage Flash Šteta + Quest Outline Zadatak + Coin Shine Novčić + Boss Alert Bos Outlines and Rules Obrisi i linije Hand-Drawn Ručno crtano Gradient Finishes Gradijentne završnice @@ -964,6 +972,7 @@ lighting Light Svjetlo Color Picker… Birač boja… Coming soon — tracked in the parity plan Uskoro — prati se u planu usklađenosti Command Dialog Dijalog naredbe + Command API Reference Referenca API-ja naredbi Copy Selected Style Kopiraj odabrani stil Corners… Uglovi… Define Perspective Grid… Definiši mrežu perspektive… @@ -2531,15 +2540,12 @@ digits Malayalam Malajalam Selected Swatches Odabrani uzorci boja Advanced Options Napredne opcije Background Contents Sadržaj pozadine - Background Contents: Sadržaj pozadine: BLANK DOCUMENT PRESETS PREDLOŠCI PRAZNIH DOKUMENATA Bleed Napust Change to Right-to-Left Layout Prebaci na raspored s desna nalijevo Columns: Kolone: - Create Document Kreiraj dokument Documents you create appear here. Dokumenti koje kreirate pojavljuju se ovdje. More Settings Više postavki - New from Template Novo iz predloška Number of Artboards: Broj radnih ploča: Orientation: Orijentacija: PRESET DETAILS DETALJI PREDLOŠKA @@ -2550,7 +2556,6 @@ digits Malayalam Malajalam RECENT NEDAVNO RECENT (1) NEDAVNO (1) SAVED SAČUVANO - Templates… Predlošci… Transparent (Default) Prozirno (zadano) Save for Office Documents Sačuvaj za Office dokumente Transparent Background Prozirna pozadina @@ -3486,6 +3491,7 @@ theme Appearance Izgled Arrange by Row Rasporedi po redu Arrange by Column Rasporedi po koloni Save Preset Sačuvaj predložak + Save Document Preset Sačuvaj predložak dokumenta Screen (72 ppi) Ekran (72 ppi) Social Square Post 1080×1080 Kvadratna objava za društvene mreže 1080×1080 Distribute Rasporedi ravnomjerno @@ -4320,6 +4326,15 @@ imageTrace Outline Obris @msg Combine Slices: the slices have no bounds Kombinuj isječke: isječci nemaju granice @msg Convert to Artboards: selection has no area Pretvori u radne ploče: odabir nema površinu @msg Convert to Shape: no rectangles or ellipses selected Pretvori u oblik: nisu odabrani pravougaonici ni elipse + Run Pokreni + Run Script Pokreni skriptu + Stop Script Zaustavi skriptu + Show External Script Warning Prikaži upozorenje za vanjske skripte + A Script Is Running Skripta se izvršava + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skripta može mijenjati otvorene dokumente i pisati datoteke putem naredbi koje pokreće. Pokrećite samo skripte kojima vjerujete. + Do not show this warning again Ne prikazuj više ovo upozorenje + Stop the script and undo what it did? Then quit again. Zaustaviti skriptu i poništiti ono što je uradila? Zatim ponovo izađite. + This script has added a great many objects. Continue, or stop it and undo what it did? Ova skripta je dodala veoma mnogo objekata. Nastaviti, ili je zaustaviti i poništiti ono što je uradila? @msg Copied the script report Izvještaj skripte kopiran @msg Corners edits the corners of a path Uglovi uređuje uglove putanje @msg Couldn't copy to the system clipboard: {e} Nije moguće kopirati u sistemski međuspremnik: {e} @@ -5489,7 +5504,8 @@ mark-style Japanese Japanski Bevel both sides Zakošenje s obje strane Presets Unaprijed postavljene vrijednosti @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Objekat prima jedan 3D efekat. Uredite opcije postojećeg efekta ili ga prvo uklonite. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} trenutno zahtijeva putanju ili složenu putanju. Prvo pretvorite tekst, slike i grupe u putanje. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} trenutno zahtijeva putanju, složenu putanju, tekst, grupu, stapanje ili instancu simbola. Prvo proširite ostale objekte. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} ne može napraviti tijelo od slike: prvo je pratite pomoću Objekat › Praćenje slike › Napravi. @msg {label} requires a shape with at least two anchors {label} zahtijeva oblik s najmanje dva sidra @msg The shape is too complex for a 3D effect Oblik je previše složen za 3D efekat @msg The 3D surface is too complex; simplify the shape 3D površina je previše složena; pojednostavite oblik @@ -5809,6 +5825,7 @@ axis Y Axis Y osa Show its progress, see Cancel and write log lines Prikazati napredak, prepoznati otkazivanje i zapisivati redove dnevnika Keep settings of its own Čuvati vlastite postavke Keep a cache of its own, which you can clear Čuvati vlastitu predmemoriju koju možete očistiti + Run these commands on the document: {ids} Izvršavati ove naredbe na dokumentu: {ids} Clear Plug-in Cache Očisti predmemoriju dodatka @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} dozvola `{permission}` zahtijeva nivo API-ja dodataka {PROGRESS_API}: navedite `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} modul uvozi `env.{name}` s drugim tipom od domaćinovog: domaćinov tip je {signature} @@ -5880,6 +5897,11 @@ axis Y Axis Y osa Button Dugme Panel Panel UI Frames UI okviri + Map Markers Markeri mape + Pin Pin + Flag Zastava + Crosshair Nišan + Checkpoint Kontrolna tačka Open Symbol Library Otvori biblioteku simbola Save Symbol Library Sačuvaj biblioteku simbola Save Symbol Library… Sačuvaj biblioteku simbola… @@ -5934,6 +5956,11 @@ axis Y Axis Y osa User Brush Library 9 Korisnička biblioteka četkica 9 User Brush Library 10 Korisnička biblioteka četkica 10 Art Ribbons Umjetničke trake + Zigzag Cik-cak + Burst Ray Zraka udara + Dash Trail Isprekidani trag + Speed Line Linija brzine + Game Trails Tragovi igre Calligraphic Nibs Kaligrafski vrhovi Pattern Borders Ivice od uzoraka Scatter Shapes Raspršeni oblici @@ -5952,6 +5979,8 @@ axis Y Axis Y osa Live preview Pregled uživo Point Text Tačkasti tekst Area Text Tekst u oblasti +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Mjeri tekst po granicama glifa Show Snap to Glyph Options Prikaži opcije prianjanja uz glif Hide Snap to Glyph Options Sakrij opcije prianjanja uz glif Snap to Glyph Options Opcije prianjanja uz glif @@ -6481,3 +6510,5 @@ shape Open Otvoren # Align to Pixel Grid Align to Pixel Grid Poravnaj s mrežom piksela @msg side is left or right, not `{s}` side je left ili right, a ne `{s}` + Edit Custom Dictionary Uredi prilagođeni rječnik + Entry: Unos: diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 53ebd517f5..9e77ecb32f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -362,6 +362,11 @@ antiAlias Sharp Nítid Art Brush Options Opcions del pinzell artístic Art Optimized Optimitzat per a l’art Art Ribbons Cintes d’art + Zigzag Zigzag + Burst Ray Raig d’impacte + Dash Trail Estela discontínua + Speed Line Línia de velocitat + Game Trails Esteles de joc Art using a deleted global swatch keeps its colour. L’art que utilitza una mostra global suprimida conserva el seu color. Artboard Tauler Artboard Options Opcions del tauler @@ -423,7 +428,6 @@ antiAlias Sharp Nítid Back Enrere Background Color: Color de fons: Background Contents Contingut del fons - Background Contents: Contingut del fons: Background Level Nivell de fons Background: Fons: Backspace Retrocés @@ -444,6 +448,11 @@ antiAlias Sharp Nítid Button Botó Panel Panell UI Frames Marcs d’IU + Map Markers Marcadors de mapa + Pin Xinxeta + Flag Bandera + Crosshair Punt de mira + Checkpoint Punt de control Batch Lot Batch… Lot… Bearing Orientació @@ -795,6 +804,7 @@ antiAlias Sharp Nítid Command Ordre Command Click to Select Objects Behind Clic amb Ordre per seleccionar els objectes del darrere Command Dialog Diàleg d’ordres + Command API Reference Referència de l’API d’ordres Comment not closed Comentari no tancat Commenting, filling in form fields and signing Comentar, emplenar camps de formulari i signar Commits Commits @@ -917,7 +927,6 @@ antiAlias Sharp Nítid Create Clipping Mask Crea una màscara de retall Create Compound Path From Ellipses Crea un traçat compost a partir d’el·lipses Create Dimension Crea una dimensió - Create Document Crea un document Create from Guides Crea a partir de guies Create from Selection Crea a partir de la selecció Create From: Crea a partir de: @@ -2339,6 +2348,7 @@ digits Malayalam Malaiàlam Lock Artboards Bloca els taulers Lock Grid Bloca la quadrícula Lock Guides Bloca les guies + Lock Guides by Default Bloca les guies per defecte Lock Others Bloca la resta Lock Selected Bloca la selecció Lock Slices Bloca els talls @@ -2597,7 +2607,6 @@ digits Malayalam Malaiàlam New Design Disseny nou New Document Presets Preajustos de document nous New file Fitxer nou - New from Template Nou a partir d’una plantilla New from Template… Nou a partir d’una plantilla… New Graphic Style Estil gràfic nou New Graphic Style (Alt-click to name it) Estil gràfic nou (Alt+clic per posar-hi nom) @@ -3643,6 +3652,7 @@ digits Malayalam Malaiàlam Save PDF Preset Desa el preajust de PDF Save Perspective Grid Preset Desa el preajust de quadrícula en perspectiva Save Preset Desa el preajust + Save Document Preset Desa el preajust de document Save Preset… Desa el preajust… Save Print Preset Desa el preajust d’impressió Save Recovery Data Desa les dades de recuperació @@ -3921,6 +3931,13 @@ digits Malayalam Malaiàlam Shading Sombra Shadow Intensity Intensitat de l’ombra Shadows and Glows Ombres i resplendors + Game HUD HUD de joc + Health Fill Salut + Mana Glow Mana + Damage Flash Dany + Quest Outline Missió + Coin Shine Moneda + Boss Alert Cap Shape Forma Shape Builder Constructor de formes Shape Builder Delete Suprimeix del constructor de formes @@ -4369,7 +4386,6 @@ digits Malayalam Malaiàlam Template literal not closed El literal de plantilla no està tancat Templates Plantilles Templates Folder Carpeta de plantilles - Templates… Plantilles… Tetrad Tètrada Tetrad 2 Tètrada 2 Tetrad 3 Tètrada 3 @@ -5155,6 +5171,28 @@ digits Malayalam Malaiàlam @msg control must be fillStroke, coloring, drawMode or screenMode control ha de ser fillStroke, coloring, drawMode o screenMode @msg Convert to Artboards: selection has no area Converteix en taulers: la selecció no té àrea @msg Convert to Shape: no rectangles or ellipses selected Converteix en forma: no s’ha seleccionat cap rectangle ni el·lipse + Run Executa + Run Script Executa l'script + Stop Script Atura l'script + Show External Script Warning Mostra l'avís dels scripts externs + A Script Is Running S'està executant un script + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script pot canviar els documents oberts i escriure fitxers mitjançant les ordres que executa. Executeu només scripts de confiança. + Do not show this warning again No tornis a mostrar aquest avís + Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir. + This script has added a great many objects. Continue, or stop it and undo what it did? Aquest script ha afegit moltíssims objectes. Voleu continuar, o aturar-lo i desfer el que ha fet? +@msg Choose a .js or .jsx script Trieu un script .js o .jsx +@msg Ran {name} S'ha executat {name} +@msg The script was stopped and its changes were undone L'script s'ha aturat i s'han desfet els seus canvis +@msg a script is running: stop it or wait for it to finish s'està executant un script: atureu-lo o espereu que acabi +@msg this is a compiled script, which cannot be run; use its source text aquest és un script compilat, que no es pot executar; useu el seu text font +@msg the script is not UTF-8 text l'script no és text UTF-8 +@msg the script is too large to run l'script és massa gran per executar-lo +@msg a drag or an undo group is open; finish it before running a script hi ha un arrossegament o un grup de desfer obert; acabeu-lo abans d'executar un script +@msg the script left a document that cannot be kept l'script ha deixat un document que no es pot conservar +@msg the script's run is no longer available l'execució de l'script ja no està disponible +@msg a failed command changed undo steps that could not be put back, so the script was stopped una ordre fallida ha canviat passos de desfer que no s'han pogut restaurar, així que l'script s'ha aturat +@msg a recovery copy could not be written, so the script was not run no s'ha pogut escriure una còpia de recuperació, per tant l'script no s'ha executat +@msg Running a script S'està executant un script @msg Copied the script report S’ha copiat l’informe de l’script @msg Corners edits the corners of a path Cantonades edita les cantonades d’un traçat @msg could not decode image: {0} no s’ha pogut descodificar la imatge: {0} @@ -5254,6 +5292,11 @@ digits Malayalam Malaiàlam @msg Invalid panel layout; restored the default dock Disposició de panells no vàlida; s’ha restaurat l’acoblament per defecte @msg invalid parameters for `{cmd}`: {msg} paràmetres no vàlids per a `{cmd}`: {msg} @msg invalid PDF setting: {0} configuració del PDF no vàlida: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la pàgina del tauler {n} fa {size}, més que el límit de pàgina del PDF de 14.400 pt (200 in): s’escriu amb un UserUnit de {unit}, de manera que les aplicacions que ignoren UserUnit la mostren tantes vegades més petita +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la pàgina del tauler {n} fa {size}, més que el límit de pàgina del PDF de 14.400 pt (200 in): les pàgines {label} s’escriuen sense UserUnit, en punts, i les aplicacions que respecten el límit retallen la pàgina a 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 el PDF 1.5 no té UserUnit, que una pàgina de més de 14.400 pt (200 in) necessita per mantenir la mida: el fitxer s’escriu com a PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la pàgina del tauler {n} fa {size}, massa llarga i estreta per als costats de pàgina del PDF de 3 a 14.400 unitats: s'escriu amb una UserUnit de {unit}, que manté el costat curt en 3 unitats o més, i les aplicacions que respecten el límit retallen el costat llarg a 14.400 unitats +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard els fitxers {label} admeten nombres reals fins a {max}, i la pàgina del tauler {n}, de {side} pt, en necessita de més grans: trieu PDF 1.6 o posterior sense estàndard PDF/X, o un tauler més petit @msg Invalid real scale Escala real no vàlida @msg invalid restored panel group grup de panells restaurat no vàlid @msg invalid stroke widths amplades de traç no vàlides @@ -5434,6 +5477,7 @@ digits Malayalam Malaiàlam @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out S’ha carregat “{name}”: s’ha omès {n} pas|S’ha carregat “{name}”: s’han omès {n} passos @msg not an action set file no és un fitxer de conjunt d’accions @msg the action set file is larger than 8 MiB el fitxer de conjunt d’accions supera els 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: la referència superaria els {MAX_BYTES} bytes @msg the action set file holds more than 1,000 actions el fitxer de conjunt d’accions conté més de 1.000 accions @msg the action set file needs a later version of VectorCraft el fitxer de conjunt d’accions necessita una versió més recent del VectorCraft @msg an action in the action set file has more than 10,000 steps una acció del fitxer de conjunt d’accions té més de 10.000 passos @@ -5854,6 +5898,11 @@ digits Malayalam Malaiàlam @msg unknown parameter `{key}`; did you mean `{near}`? paràmetre desconegut `{key}`; volies dir `{near}`? @msg unknown parameter `{key}`; the command takes no parameters paràmetre desconegut `{key}`; l’ordre no admet cap paràmetre @msg unknown parameter `{key}`; the command takes: {keys} paràmetre desconegut `{key}`; l’ordre admet: {keys} +@msg the params must be an object, not {got} els paràmetres han de ser un objecte, no {got} +@msg unknown parameter `{path}`; the object takes no keys paràmetre desconegut `{path}`; l’objecte no admet claus +@msg unknown parameter `{path}`; it takes: {keys} paràmetre desconegut `{path}`; admet: {keys} +@msg missing `{path}` falta `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` ha de ser {expected}, no {got} @msg unknown preference `{key}` preferència desconeguda `{key}` @msg unknown preset (one of {_1}) preajust desconegut (un de {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) preajust desconegut `{name}` (high, medium, low o un de desat: consulta flattener.presets.list) @@ -5912,7 +5961,8 @@ digits Malayalam Malaiàlam @msg {key} must be a finite coordinate {key} ha de ser una coordenada finita @msg {key} must be an array of non-negative integer object ids {key} ha de ser una matriu d’identificadors d’objecte enters no negatius @msg {key} must be Unix seconds (an integer) or null {key} ha de ser segons Unix (un enter) o null -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} actualment requereix un traçat o un traçat compost. Converteix primer els textos, les imatges i els grups en traçats. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} actualment requereix un traçat, un traçat compost, text, un grup, una fusió o una instància de símbol. Expandeix primer els altres objectes. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} no pot crear un sòlid a partir d’una imatge: traça-la primer amb Objecte › Traçat d’imatge › Crea. @msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} conserva 1 dels {n} taulers del document: el fitxer es reobre amb un. Activa Conserva les capacitats d’edició per conservar-los tots. @msg {label} produced an empty result {label} ha produït un resultat buit @msg {label} requires a shape with at least two anchors {label} requereix una forma amb com a mínim dos punts d’ancoratge @@ -5947,6 +5997,20 @@ digits Malayalam Malaiàlam Show its progress, see Cancel and write log lines Mostrar el progrés, detectar la cancel·lació i escriure línies de registre Keep settings of its own Desar una configuració pròpia Keep a cache of its own, which you can clear Desar una memòria cau pròpia, que podeu buidar + Run these commands on the document: {ids} Executar aquestes ordres al document: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» inclou `{id}` a `commandAllowlist`, que un complement no pot cridar +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: el `commandAllowlist` del manifest no la inclou +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: l’ID o els arguments són fora de la memòria del mòdul +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: l’ID o els arguments no són UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: els arguments no són un objecte JSON +@msg only a filter with the usual budget declares `commandAllowlist` només un filtre amb el pressupost habitual declara `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) crides d’ordres ({MAX_CALLS} crides i {MAX_CALL_BYTES} bytes per execució) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) mida d’una crida d’ordre (vc_call `{shown}`: {len} bytes, límit {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` com a màxim {MAX_ALLOWED_COMMANDS} ordres a `commandAllowlist` +@msg a plug-in may not call this command un complement no pot cridar aquesta ordre +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` necessita el permís `commands`, i `commands` necessita un `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` inclou `{shown}`, que no és un ID d’ordre o hi apareix dues vegades Clear Plug-in Cache Buida la memòria cau del complement @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} el permís `{permission}` necessita el nivell d’API de complements {PROGRESS_API}: indiqueu `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} el mòdul importa `env.{name}` amb un tipus diferent del de l’amfitrió: el de l’amfitrió és {signature} @@ -6062,6 +6126,8 @@ theme Appearance Aparença # Align panel menu › Align to Glyph Bounds (#4231). Point Text Text de punt Area Text Text d’àrea +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Mesura el text pels límits del glif # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Mostra les opcions d’ajust al glif Hide Snap to Glyph Options Amaga les opcions d’ajust al glif @@ -6643,3 +6709,8 @@ breakText Glyphs Glifs Align to Pixel Grid Alinea a la quadrícula de píxels @msg only paths and compound paths can be aligned to the pixel grid només els traçats i els traçats compostos es poden alinear a la quadrícula de píxels @msg side is left or right, not `{s}` side ha de ser left o right, no `{s}` + Ignore All Ignora-ho tot + Add to Dictionary Afegeix al diccionari + No Suggestions No hi ha suggeriments + Edit Custom Dictionary Edita el diccionari personalitzat + Entry: Entrada: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3c9090be2a..de1723b906 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -609,6 +609,7 @@ Hide Guides Skrýt vodítka Show Guides Zobrazit vodítka Lock Guides Zamknout vodítka + Lock Guides by Default Ve výchozím stavu zamknout vodítka Unlock Guides Odemknout vodítka Make Guides Vytvořit vodítka Release Guides Uvolnit vodítka @@ -774,6 +775,13 @@ Other Library… Jiná knihovna… Graphic Style Libraries Knihovny grafických stylů Shadows and Glows Stíny a záře + Game HUD Herní HUD + Health Fill Život + Mana Glow Mana + Damage Flash Poškození + Quest Outline Úkol + Coin Shine Mince + Boss Alert Boss Outlines and Rules Obrysy a linky Hand-Drawn Ručně kreslené Gradient Finishes Přechodové povrchy @@ -984,6 +992,7 @@ lighting Light Světlo Color Picker… Výběr barvy… Coming soon — tracked in the parity plan Připravujeme — sledováno v plánu parity Command Dialog Dialogové okno příkazu + Command API Reference Reference API příkazů Copy Selected Style Kopírovat vybraný styl Corners… Rohy… Define Perspective Grid… Definovat perspektivní mřížku… @@ -2562,15 +2571,12 @@ digits Malayalam Malajálamské Selected Swatches Vybrané položky vzorníku Advanced Options Rozšířené možnosti Background Contents Obsah pozadí - Background Contents: Obsah pozadí: BLANK DOCUMENT PRESETS PŘEDNASTAVENÍ PRÁZDNÝCH DOKUMENTŮ Bleed Spadávka Change to Right-to-Left Layout Změnit na rozvržení zprava doleva Columns: Sloupce: - Create Document Vytvořit dokument Documents you create appear here. Zde se zobrazí dokumenty, které vytvoříte. More Settings Další nastavení - New from Template Nový ze šablony Number of Artboards: Počet pracovních ploch: Orientation: Orientace: PRESET DETAILS PODROBNOSTI PŘEDNASTAVENÍ @@ -2581,7 +2587,6 @@ digits Malayalam Malajálamské RECENT NEDÁVNÉ RECENT (1) NEDÁVNÉ (1) SAVED ULOŽENÉ - Templates… Šablony… Transparent (Default) Průhledné (výchozí) Save for Office Documents Uložit pro kancelářské dokumenty Transparent Background Průhledné pozadí @@ -3536,6 +3541,7 @@ theme Appearance Motiv Arrange by Row Uspořádat po řádcích Arrange by Column Uspořádat po sloupcích Save Preset Uložit přednastavení + Save Document Preset Uložit přednastavení dokumentu Screen (72 ppi) Obrazovka (72 ppi) Social Square Post 1080×1080 Čtvercový příspěvek pro sociální sítě 1080×1080 Distribute Rozmístit @@ -4378,6 +4384,28 @@ imageTrace Outline Obrys @msg Combine Slices: the slices have no bounds Spojit řezy: řezy nemají hranice @msg Convert to Artboards: selection has no area Převést na pracovní plochy: výběr nemá žádnou plochu @msg Convert to Shape: no rectangles or ellipses selected Převést na tvar: nejsou vybrány žádné obdélníky ani elipsy + Run Spustit + Run Script Spustit skript + Stop Script Zastavit skript + Show External Script Warning Zobrazit upozornění u externích skriptů + A Script Is Running Běží skript + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skript může měnit otevřené dokumenty a prostřednictvím příkazů, které spouští, zapisovat soubory. Spouštějte jen skripty, kterým důvěřujete. + Do not show this warning again Toto upozornění již nezobrazovat + Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu. + This script has added a great many objects. Continue, or stop it and undo what it did? Tento skript přidal velmi mnoho objektů. Pokračovat, nebo jej zastavit a vrátit jeho změny? +@msg Choose a .js or .jsx script Vyberte skript .js nebo .jsx +@msg Ran {name} Spuštěno: {name} +@msg The script was stopped and its changes were undone Skript byl zastaven a jeho změny byly vráceny +@msg a script is running: stop it or wait for it to finish běží skript: zastavte jej nebo počkejte na jeho dokončení +@msg this is a compiled script, which cannot be run; use its source text toto je zkompilovaný skript, který nelze spustit; použijte jeho zdrojový text +@msg the script is not UTF-8 text skript není text v kódování UTF-8 +@msg the script is too large to run skript je příliš velký na spuštění +@msg a drag or an undo group is open; finish it before running a script je otevřené tažení nebo skupina kroků zpět; před spuštěním skriptu ji dokončete +@msg the script left a document that cannot be kept skript zanechal dokument, který nelze zachovat +@msg the script's run is no longer available běh skriptu již není k dispozici +@msg a failed command changed undo steps that could not be put back, so the script was stopped neúspěšný příkaz změnil kroky zpět, které nebylo možné obnovit, proto byl skript zastaven +@msg a recovery copy could not be written, so the script was not run záložní kopii se nepodařilo zapsat, proto skript nebyl spuštěn +@msg Running a script Běží skript @msg Copied the script report Zpráva o skriptu zkopírována @msg Corners edits the corners of a path Rohy upravuje rohy cesty @msg Couldn't copy to the system clipboard: {e} Nelze kopírovat do systémové schránky: {e} @@ -4620,6 +4648,11 @@ imageTrace Outline Obrys @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) vnitřní chyba v `{cmd}`: {msg} (dokument zůstal ve stavu před příkazem; nahlaste prosím tuto chybu) @msg internal error: {msg} (please report this bug) vnitřní chyba: {msg} (nahlaste prosím tuto chybu) @msg invalid PDF setting: {0} neplatné nastavení PDF: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller stránka pracovní plochy {n} má {size}, což přesahuje limit stránky PDF 14 400 pt (200 in): zapisuje se s UserUnit {unit}, takže aplikace, které UserUnit ignorují, ji zobrazí tolikrát menší +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in stránka pracovní plochy {n} má {size}, což přesahuje limit stránky PDF 14 400 pt (200 in): stránky {label} se zapisují bez UserUnit, v bodech, a aplikace, které limit dodržují, stránku oříznou na 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 nemá UserUnit, který stránka delší než 14 400 pt (200 in) potřebuje, aby si zachovala velikost: soubor se zapíše jako PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units stránka pracovní plochy {n} má rozměr {size} a je příliš dlouhá a úzká pro strany stránky PDF od 3 do 14 400 jednotek: zapisuje se s UserUnit {unit}, která drží kratší stranu na 3 jednotkách nebo více, a aplikace, které limit dodržují, ořežou delší stranu na 14 400 jednotek +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard soubory {label} pojmou reálná čísla nejvýše {max} a stránka pracovní plochy {n}, dlouhá {side} pt, potřebuje větší: zvolte PDF 1.6 nebo novější bez standardu PDF/X, nebo menší pracovní plochu @msg invalid image data for `{0}` neplatná obrazová data pro `{0}` @msg invalid parameters for `{cmd}`: {msg} neplatné parametry pro `{cmd}`: {msg} @msg is not an image VectorCraft reads není obraz, který VectorCraft umí přečíst @@ -4724,6 +4757,7 @@ imageTrace Outline Obrys @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Načteno „{name}“: vynechán {n} krok|Načteno „{name}“: vynechány {n} kroky|Načteno „{name}“: vynecháno {n} kroků @msg not an action set file není to soubor sady akcí @msg the action set file is larger than 8 MiB soubor sady akcí je větší než 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: reference by byla větší než {MAX_BYTES} bajtů @msg the action set file holds more than 1,000 actions soubor sady akcí obsahuje více než 1 000 akcí @msg the action set file needs a later version of VectorCraft soubor sady akcí vyžaduje novější verzi aplikace VectorCraft @msg an action in the action set file has more than 10,000 steps akce v souboru sady akcí má více než 10 000 kroků @@ -5587,7 +5621,8 @@ mark-style Japanese Japonské Bevel both sides Zkosení na obou stranách Presets Předvolby @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Objekt může mít jen jeden 3D efekt. Upravte volby stávajícího efektu, nebo jej nejprve odstraňte. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} zatím vyžaduje cestu nebo složenou cestu. Nejprve převeďte text, obrazy a skupiny na cesty. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} zatím vyžaduje cestu, složenou cestu, text, skupinu, prolnutí nebo instanci symbolu. Ostatní objekty nejprve rozložte. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} nedokáže vytvořit těleso z obrazu: nejprve jej vektorizujte příkazem Objekt › Vektorizace obrazu › Vytvořit. @msg {label} requires a shape with at least two anchors {label} vyžaduje tvar alespoň se dvěma kotevními body @msg The shape is too complex for a 3D effect Tvar je pro 3D efekt příliš složitý @msg The 3D surface is too complex; simplify the shape 3D povrch je příliš složitý; zjednodušte tvar @@ -5595,6 +5630,11 @@ mark-style Japanese Japonské @msg unknown parameter `{key}`; did you mean `{near}`? neznámý parametr `{key}`; mysleli jste `{near}`? @msg unknown parameter `{key}`; the command takes no parameters neznámý parametr `{key}`; příkaz nemá žádné parametry @msg unknown parameter `{key}`; the command takes: {keys} neznámý parametr `{key}`; příkaz přijímá: {keys} +@msg the params must be an object, not {got} parametry musí být objekt, nikoli {got} +@msg unknown parameter `{path}`; the object takes no keys neznámý parametr `{path}`; objekt nepřijímá žádné klíče +@msg unknown parameter `{path}`; it takes: {keys} neznámý parametr `{path}`; přijímá: {keys} +@msg missing `{path}` chybí `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` musí být {expected}, nikoli {got} Load EPS into Clipboard Načíst EPS do schránky @msg an image of {w} × {h} pixels is too large to draw obraz o velikosti {w} × {h} obrazových bodů je příliš velký na vykreslení @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: není obraz PNG, JPEG, WebP, TIFF ani BMP @@ -5936,6 +5976,20 @@ axis Y Axis osa Y Show its progress, see Cancel and write log lines Zobrazit průběh, rozpoznat zrušení a zapisovat řádky protokolu Keep settings of its own Uchovávat vlastní nastavení Keep a cache of its own, which you can clear Uchovávat vlastní mezipaměť, kterou můžete vymazat + Run these commands on the document: {ids} Spouštět v dokumentu tyto příkazy: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ uvádí v `commandAllowlist` příkaz `{id}`, který zásuvný modul nesmí volat +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: `commandAllowlist` manifestu ho neuvádí +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID nebo argumenty leží mimo paměť modulu +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID nebo argumenty nejsou v UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumenty nejsou objekt JSON +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` deklaruje pouze filtr s obvyklým rozpočtem +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) volání příkazů ({MAX_CALLS} volání a {MAX_CALL_BYTES} bajtů na běh) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) velikost volání příkazu (vc_call `{shown}`: {len} bajtů, limit {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` nejvýše {MAX_ALLOWED_COMMANDS} příkazů v `commandAllowlist` +@msg a plug-in may not call this command zásuvný modul nesmí volat tento příkaz +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` potřebuje oprávnění `commands` a `commands` potřebuje `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` uvádí `{shown}`, což není ID příkazu nebo je uvedeno dvakrát Clear Plug-in Cache Vymazat mezipaměť zásuvného modulu @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} oprávnění `{permission}` vyžaduje úroveň API zásuvných modulů {PROGRESS_API}: uveďte `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} modul importuje `env.{name}` s jiným typem, než má hostitel: typ hostitele je {signature} @@ -6025,6 +6079,11 @@ axis Y Axis osa Y Button Tlačítko Panel Panel UI Frames Rámce UI + Map Markers Mapové značky + Pin Špendlík + Flag Vlajka + Crosshair Zaměřovač + Checkpoint Kontrolní bod Open Symbol Library Otevřít knihovnu symbolů Save Symbol Library Uložit knihovnu symbolů Save Symbol Library… Uložit knihovnu symbolů… @@ -6079,6 +6138,11 @@ axis Y Axis osa Y User Brush Library 9 Uživatelská knihovna štětců 9 User Brush Library 10 Uživatelská knihovna štětců 10 Art Ribbons Obrazové stuhy + Zigzag Cikcak + Burst Ray Paprsek nárazu + Dash Trail Čárkovaná stopa + Speed Line Rychlostní čára + Game Trails Herní stopy Calligraphic Nibs Kaligrafická pera Pattern Borders Vzorkové okraje Scatter Shapes Rozptýlené tvary @@ -6099,6 +6163,8 @@ axis Y Axis osa Y # Align panel menu › Align to Glyph Bounds (#4231). Point Text Bodový text Area Text Text v oblasti +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Měřit text podle hranic glyfů # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Zobrazit možnosti přichytávání ke glyfům Hide Snap to Glyph Options Skrýt možnosti přichytávání ke glyfům @@ -6662,3 +6728,8 @@ breakText Glyphs Glyfy Align to Pixel Grid Zarovnat na mřížku obrazových bodů @msg only paths and compound paths can be aligned to the pixel grid na mřížku obrazových bodů lze zarovnat jen cesty a složené cesty @msg side is left or right, not `{s}` side je left nebo right, ne `{s}` + Ignore All Ignorovat vše + Add to Dictionary Přidat do slovníku + No Suggestions Žádné návrhy + Edit Custom Dictionary Upravit vlastní slovník + Entry: Položka: diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index df445718bf..77687493e5 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -559,6 +559,7 @@ Hide Guides Skjul hjælpelinjer Show Guides Vis hjælpelinjer Lock Guides Lås hjælpelinjer + Lock Guides by Default Lås hjælpelinjer som standard Unlock Guides Lås hjælpelinjer op Make Guides Opret hjælpelinjer Release Guides Frigør hjælpelinjer @@ -711,6 +712,13 @@ Other Library… Andet bibliotek… Graphic Style Libraries Biblioteker med grafiske stile Shadows and Glows Skygger og gløder + Game HUD Spil-HUD + Health Fill Helbred + Mana Glow Mana + Damage Flash Skade + Quest Outline Quest + Coin Shine Mønt + Boss Alert Boss Outlines and Rules Konturer og linjer Hand-Drawn Håndtegnet Gradient Finishes Gradientfinish @@ -905,6 +913,7 @@ lighting Light Lys Color Picker… Farvevælger… Coming soon — tracked in the parity plan Kommer snart — følges i paritetsplanen Command Dialog Kommandodialog + Command API Reference API-reference for kommandoer Copy Selected Style Kopiér markeret typografi Corners… Hjørner… Define Perspective Grid… Definér perspektivgitter… @@ -2350,15 +2359,12 @@ digits Malayalam Malayalam Selected Swatches Markerede farveprøver Advanced Options Avancerede indstillinger Background Contents Baggrundens indhold - Background Contents: Baggrundens indhold: BLANK DOCUMENT PRESETS TOMME DOKUMENTFORUDINDSTILLINGER Bleed Beskæring Change to Right-to-Left Layout Skift til højre-til-venstre-layout Columns: Kolonner: - Create Document Opret dokument Documents you create appear here. Dokumenter, du opretter, vises her. More Settings Flere indstillinger - New from Template Nyt fra skabelon Number of Artboards: Antal tegnebrætter: Orientation: Orientering: PRESET DETAILS FORUDINDSTILLINGSDETALJER @@ -2369,7 +2375,6 @@ digits Malayalam Malayalam RECENT SENESTE RECENT (1) SENESTE (1) SAVED GEMT - Templates… Skabeloner… Transparent (Default) Gennemsigtig (standard) Save for Office Documents Gem til Office-dokumenter Transparent Background Gennemsigtig baggrund @@ -3273,6 +3278,7 @@ theme Appearance Udseende Arrange by Row Arranger efter række Arrange by Column Arranger efter kolonne Save Preset Gem forudindstilling + Save Document Preset Gem dokumentforudindstilling Screen (72 ppi) Skærm (72 ppi) Social Square Post 1080×1080 Socialt firkantet opslag 1080×1080 Distribute Fordel @@ -4074,6 +4080,15 @@ imageTrace Outline Kontur @msg Combine Slices: the slices have no bounds Kombinér udsnit: udsnittene har ingen grænser @msg Convert to Artboards: selection has no area Konvertér til tegneflader: markeringen har intet areal @msg Convert to Shape: no rectangles or ellipses selected Konvertér til figur: ingen rektangler eller ellipser er markeret + Run Kør + Run Script Kør script + Stop Script Stop script + Show External Script Warning Vis advarsel om eksterne scripts + A Script Is Running Et script kører + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Et script kan ændre de åbne dokumenter og skrive filer gennem de kommandoer, det kører. Kør kun scripts, du stoler på. + Do not show this warning again Vis ikke denne advarsel igen + Stop the script and undo what it did? Then quit again. Stop scriptet og fortryd det, det har gjort? Afslut derefter igen. + This script has added a great many objects. Continue, or stop it and undo what it did? Dette script har tilføjet rigtig mange objekter. Fortsæt, eller stop det og fortryd det, det har gjort? @msg Copied the script report Kopierede scriptrapporten @msg Corners edits the corners of a path Hjørner redigerer hjørnerne på en kurve @msg Couldn't copy to the system clipboard: {e} Kunne ikke kopiere til systemets udklipsholder: {e} @@ -5142,7 +5157,8 @@ mark-style Japanese Japansk Bevel both sides Facet på begge sider Presets Forudindstillinger @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Et objekt kan kun have én 3D-effekt. Redigér den eksisterende effekts indstillinger, eller fjern den først. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} kræver i øjeblikket en sti eller en sammensat sti. Konvertér tekst, billeder og grupper til stier først. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} kræver i øjeblikket en sti, en sammensat sti, tekst, en gruppe, en blanding eller en symbolforekomst. Udvid andre objekter først. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} kan ikke bygge et legeme ud fra et billede: spor det først med Objekt › Billedsporing › Opret. @msg {label} requires a shape with at least two anchors {label} kræver en form med mindst to ankerpunkter @msg The shape is too complex for a 3D effect Formen er for kompleks til en 3D-effekt @msg The 3D surface is too complex; simplify the shape 3D-fladen er for kompleks; forenkl formen @@ -5802,6 +5818,7 @@ axis Y Axis Y-akse Show its progress, see Cancel and write log lines Vise sin fremdrift, se en annullering og skrive logrækker Keep settings of its own Gemme sine egne indstillinger Keep a cache of its own, which you can clear Gemme sin egen cache, som du kan rydde + Run these commands on the document: {ids} Køre disse kommandoer på dokumentet: {ids} Clear Plug-in Cache Ryd plug-in-cache # Actions panel: action sets (#3712). New Set… Nyt sæt… @@ -5851,6 +5868,11 @@ axis Y Axis Y-akse Button Knap Panel Panel UI Frames UI-rammer + Map Markers Kortmarkører + Pin Nål + Flag Flag + Crosshair Sigtekorn + Checkpoint Kontrolpunkt Open Symbol Library Åbn symbolbibliotek Save Symbol Library Gem symbolbibliotek Save Symbol Library… Gem symbolbibliotek… @@ -5899,6 +5921,11 @@ axis Y Axis Y-akse User Brush Library 9 Brugerpenselbibliotek 9 User Brush Library 10 Brugerpenselbibliotek 10 Art Ribbons Kunstbånd + Zigzag Zigzag + Burst Ray Burststråle + Dash Trail Streget spor + Speed Line Hastighedslinje + Game Trails Spilspor Calligraphic Nibs Kalligrafiske penne Pattern Borders Mønsterborter Scatter Shapes Spredte former @@ -5911,6 +5938,8 @@ axis Y Axis Y-akse # Align panel menu › Align to Glyph Bounds (#4231). Point Text Punkttekst Area Text Områdetekst +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Mål tekst efter glyfafgrænsning # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Vis indstillinger for fastgørelse til tegn Hide Snap to Glyph Options Skjul indstillinger for fastgørelse til tegn @@ -6444,3 +6473,5 @@ breakText Glyphs Glyffer # Align to Pixel Grid Align to Pixel Grid Juster efter pixelgitter @msg side is left or right, not `{s}` side er left eller right, ikke `{s}` + Edit Custom Dictionary Redigér egen ordliste + Entry: Opslag: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6c6c48238f..7e2619386b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -272,7 +272,6 @@ font-technology Variable Variabel Update While Dragging Beim Ziehen aktualisieren Hide Video Rulers Videolineale ausblenden Background Contents Hintergrundinhalt - Background Contents: Hintergrundinhalt: Background: Hintergrund: Backspace Rücktaste Bar Graph Tool Balkendiagramm-Werkzeug @@ -561,6 +560,7 @@ font-technology Variable Variabel Coming soon — tracked in the parity plan Demnächst verfügbar – im Paritätsplan vermerkt Command Click to Select Objects Behind Cmd-Klick wählt dahinterliegende Objekte aus Command Dialog Befehlsdialog + Command API Reference API-Referenz der Befehle Community Community Compatibility: Kompatibilität: Compatible Gradient and Gradient Mesh Printing Kompatibles Drucken von Verläufen und Verlaufsgittern @@ -647,7 +647,6 @@ font-technology Variable Variabel Couldn't {} {name}: {e} Fehler bei „{}“ für {name}: {e} Create Erstellen Create Clipping Mask Schnittmaske erstellen - Create Document Dokument erstellen Create from Guides Aus Hilfslinien erstellen Create from Selection Aus Auswahl erstellen Create From: Erstellen aus: @@ -1893,6 +1892,7 @@ file-filter Templates Vorlagen Lock (⌘2) Sperren (⌘2) Lock Grid Raster sperren Lock Guides Hilfslinien sperren + Lock Guides by Default Hilfslinien standardmäßig sperren Lock Others Andere sperren Lock Slices Slices sperren Lock Station Point Standpunkt sperren @@ -2099,7 +2099,6 @@ file-filter Templates Vorlagen New Color Group… Neue Farbgruppe… New Document Presets Vorgaben für neue Dokumente New file Neue Datei - New from Template Neu aus Vorlage New from Template… Neu aus Vorlage… New Graphic Style Neuer Grafikstil New Graphic Style (Alt-click to name it) Neuer Grafikstil (Alt-Klick, um ihn zu benennen) @@ -2891,6 +2890,7 @@ digits Malayalam Malayalam Save PDF Preset PDF-Vorgabe speichern Save Perspective Grid Preset Vorgabe für Perspektivenraster speichern Save Preset Vorgabe speichern + Save Document Preset Dokumentvorgabe speichern Preset {number} Vorgabe {number} Save Preset… Vorgabe speichern… Save Print Preset Druckvorgabe speichern @@ -3099,6 +3099,13 @@ digits Malayalam Malayalam Settings… Einstellungen… Setup… Einrichten… Shadows and Glows Schatten und Leuchteffekte + Game HUD Spiel-HUD + Health Fill Leben + Mana Glow Mana + Damage Flash Schaden + Quest Outline Quest + Coin Shine Münze + Boss Alert Boss Shape Form Shape Builder Formerstellung Shape Builder Regions Formerstellungsbereiche @@ -3454,7 +3461,6 @@ effect Points Punkte Template Vorlage Templates Vorlagen Templates Folder Vorlagenordner - Templates… Vorlagen… Text Displayed in Cell: In der Zelle angezeigter Text: Text Export Options Textexportoptionen Text Fill & Stroke Color Flächen- und Konturfarbe des Texts @@ -3983,6 +3989,28 @@ theme Appearance Erscheinungsbild @msg Combine Slices: the slices have no bounds Slices kombinieren: Die Slices haben keine Begrenzung @msg Convert to Artboards: selection has no area In Zeichenflächen umwandeln: Die Auswahl hat keine Fläche @msg Convert to Shape: no rectangles or ellipses selected In Form umwandeln: keine Rechtecke oder Ellipsen ausgewählt + Run Ausführen + Run Script Skript ausführen + Stop Script Skript stoppen + Show External Script Warning Warnung bei externen Skripten anzeigen + A Script Is Running Ein Skript wird ausgeführt + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ein Skript kann die geöffneten Dokumente ändern und über die ausgeführten Befehle Dateien schreiben. Führen Sie nur Skripte aus, denen Sie vertrauen. + Do not show this warning again Diese Warnung nicht mehr anzeigen + Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut. + This script has added a great many objects. Continue, or stop it and undo what it did? Dieses Skript hat sehr viele Objekte hinzugefügt. Fortfahren oder das Skript stoppen und seine Änderungen rückgängig machen? +@msg Choose a .js or .jsx script Wählen Sie ein .js- oder .jsx-Skript +@msg Ran {name} {name} ausgeführt +@msg The script was stopped and its changes were undone Das Skript wurde gestoppt und seine Änderungen wurden rückgängig gemacht +@msg a script is running: stop it or wait for it to finish ein Skript wird ausgeführt: stoppen Sie es oder warten Sie, bis es fertig ist +@msg this is a compiled script, which cannot be run; use its source text dies ist ein kompiliertes Skript, das nicht ausgeführt werden kann; verwenden Sie seinen Quelltext +@msg the script is not UTF-8 text das Skript ist kein UTF-8-Text +@msg the script is too large to run das Skript ist zu groß zum Ausführen +@msg a drag or an undo group is open; finish it before running a script ein Ziehvorgang oder eine Rückgängig-Gruppe ist offen; schließen Sie sie ab, bevor Sie ein Skript ausführen +@msg the script left a document that cannot be kept das Skript hat ein Dokument hinterlassen, das nicht behalten werden kann +@msg the script's run is no longer available der Lauf des Skripts ist nicht mehr verfügbar +@msg a failed command changed undo steps that could not be put back, so the script was stopped ein fehlgeschlagener Befehl hat Rückgängig-Schritte geändert, die nicht wiederhergestellt werden konnten, daher wurde das Skript angehalten +@msg a recovery copy could not be written, so the script was not run eine Wiederherstellungskopie konnte nicht geschrieben werden, daher wurde das Skript nicht ausgeführt +@msg Running a script Skript wird ausgeführt @msg Copied the script report Skriptbericht kopiert @msg Corners edits the corners of a path „Ecken“ bearbeitet die Ecken eines Pfads @msg Couldn't copy to the system clipboard: {e} In die Systemzwischenablage konnte nicht kopiert werden: {e} @@ -4226,6 +4254,11 @@ theme Appearance Erscheinungsbild @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) interner Fehler in `{cmd}`: {msg} (das Dokument wurde im vorherigen Zustand belassen; bitte melden Sie diesen Fehler) @msg internal error: {msg} (please report this bug) interner Fehler: {msg} (bitte melden Sie diesen Fehler) @msg invalid PDF setting: {0} ungültige PDF-Einstellung: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller die Seite der Zeichenfläche {n} ist {size} groß und damit länger als die PDF-Seitengrenze von 14.400 pt (200 in): sie wird mit einer UserUnit von {unit} geschrieben, daher zeigen Apps, die UserUnit ignorieren, sie entsprechend oft kleiner an +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in die Seite der Zeichenfläche {n} ist {size} groß und damit länger als die PDF-Seitengrenze von 14.400 pt (200 in): {label}-Seiten werden ohne UserUnit in Punkt geschrieben, und Apps, die die Grenze einhalten, schneiden die Seite auf 200 in ab +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 hat keine UserUnit, die eine Seite länger als 14.400 pt (200 in) braucht, um ihre Größe zu behalten: die Datei wird als PDF 1.6 geschrieben +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units die Seite der Zeichenfläche {n} ist {size} groß und damit zu lang und schmal für PDF-Seitenlängen von 3 bis 14.400 Einheiten: sie wird mit einer UserUnit von {unit} geschrieben, die die kurze Seite bei mindestens 3 Einheiten hält, und Apps, die die Grenze einhalten, schneiden die lange Seite auf 14.400 Einheiten ab +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-Dateien fassen reelle Zahlen bis {max}, und die Seite der Zeichenfläche {n} mit {side} pt Länge braucht größere: wählen Sie PDF 1.6 oder höher ohne PDF/X-Standard oder eine kleinere Zeichenfläche @msg invalid image data for `{0}` ungültige Bilddaten für `{0}` @msg invalid parameters for `{cmd}`: {msg} ungültige Parameter für `{cmd}`: {msg} @msg is not an image VectorCraft reads ist kein Bild, das VectorCraft lesen kann @@ -4331,6 +4364,7 @@ theme Appearance Erscheinungsbild @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out „{name}“ geladen: {n} Schritt wurde ausgelassen|„{name}“ geladen: {n} Schritte wurden ausgelassen @msg not an action set file keine Aktionssatzdatei @msg the action set file is larger than 8 MiB die Aktionssatzdatei ist größer als 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: die Referenz wäre größer als {MAX_BYTES} Byte @msg the action set file holds more than 1,000 actions die Aktionssatzdatei enthält mehr als 1.000 Aktionen @msg the action set file needs a later version of VectorCraft die Aktionssatzdatei erfordert eine neuere Version von VectorCraft @msg an action in the action set file has more than 10,000 steps eine Aktion in der Aktionssatzdatei hat mehr als 10.000 Schritte @@ -5154,7 +5188,8 @@ lighting Light Licht Bevel both sides Abgeflachte Kante beidseitig Presets Vorgaben @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Ein Objekt kann nur einen 3D-Effekt haben. Bearbeiten Sie die Optionen des vorhandenen Effekts oder entfernen Sie ihn zuerst. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} erfordert derzeit einen Pfad oder zusammengesetzten Pfad. Wandeln Sie Text, Bilder und Gruppen zuerst in Pfade um. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} erfordert derzeit einen Pfad, zusammengesetzten Pfad, Text, eine Gruppe, eine Angleichung oder eine Symbolinstanz. Wandeln Sie andere Objekte zuerst um. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} kann aus einem Bild keinen Körper erstellen: Zeichnen Sie es zuerst mit Objekt › Bildnachzeichner › Erstellen nach. @msg {label} requires a shape with at least two anchors {label} erfordert eine Form mit mindestens zwei Ankerpunkten @msg The shape is too complex for a 3D effect Die Form ist für einen 3D-Effekt zu komplex @msg The 3D surface is too complex; simplify the shape Die 3D-Oberfläche ist zu komplex; vereinfachen Sie die Form @@ -5162,6 +5197,11 @@ lighting Light Licht @msg unknown parameter `{key}`; did you mean `{near}`? unbekannter Parameter `{key}`; meinten Sie `{near}`? @msg unknown parameter `{key}`; the command takes no parameters unbekannter Parameter `{key}`; der Befehl hat keine Parameter @msg unknown parameter `{key}`; the command takes: {keys} unbekannter Parameter `{key}`; der Befehl akzeptiert: {keys} +@msg the params must be an object, not {got} die Parameter müssen ein Objekt sein, nicht {got} +@msg unknown parameter `{path}`; the object takes no keys unbekannter Parameter `{path}`; das Objekt akzeptiert keine Schlüssel +@msg unknown parameter `{path}`; it takes: {keys} unbekannter Parameter `{path}`; akzeptiert werden: {keys} +@msg missing `{path}` `{path}` fehlt +@msg `{path}` must be {expected}, not {got} `{path}` muss {expected} sein, nicht {got} Load EPS into Clipboard EPS in die Zwischenablage laden @msg an image of {w} × {h} pixels is too large to draw ein Bild mit {w} × {h} Pixeln ist zu groß, um gezeichnet zu werden @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: kein PNG-, JPEG-, WebP-, TIFF- oder BMP-Bild @@ -5519,6 +5559,20 @@ axis Y Axis Y-Achse Show its progress, see Cancel and write log lines Den Fortschritt anzeigen, ein Abbrechen erkennen und Protokollzeilen schreiben Keep settings of its own Eigene Einstellungen speichern Keep a cache of its own, which you can clear Einen eigenen Cache anlegen, den Sie leeren können + Run these commands on the document: {ids} Diese Befehle im Dokument ausführen: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ führt `{id}` in `commandAllowlist` auf, den ein Plug-in nicht aufrufen darf +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: die `commandAllowlist` des Manifests führt ihn nicht auf +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: die ID oder die Argumente liegen außerhalb des Speichers des Moduls +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: die ID oder die Argumente sind kein UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: die Argumente sind kein JSON-Objekt +@msg only a filter with the usual budget declares `commandAllowlist` nur ein Filter mit dem üblichen Budget deklariert `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) Befehlsaufrufe ({MAX_CALLS} Aufrufe und {MAX_CALL_BYTES} Byte pro Lauf) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) Größe eines Befehlsaufrufs (vc_call `{shown}`: {len} Byte, Grenze {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` höchstens {MAX_ALLOWED_COMMANDS} Befehle in `commandAllowlist` +@msg a plug-in may not call this command ein Plug-in darf diesen Befehl nicht aufrufen +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` braucht die Berechtigung `commands`, und `commands` braucht eine `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` nennt `{shown}`, das keine Befehls-ID ist oder doppelt aufgeführt ist Clear Plug-in Cache Plug-in-Cache leeren @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} die Berechtigung `{permission}` braucht die Plug-in-API-Stufe {PROGRESS_API}: Geben Sie `api` {PROGRESS_API} an @msg the module imports `env.{name}` with another type than the host's: it is {signature} das Modul importiert `env.{name}` mit einem anderen Typ als dem des Hosts: Der Typ des Hosts ist {signature} @@ -5608,6 +5662,11 @@ axis Y Axis Y-Achse Button Schaltfläche Panel Bedienfeld UI Frames UI-Rahmen + Map Markers Kartenmarkierungen + Pin Stecknadel + Flag Flagge + Crosshair Fadenkreuz + Checkpoint Kontrollpunkt Open Symbol Library Symbol-Bibliothek öffnen Save Symbol Library Symbol-Bibliothek speichern Save Symbol Library… Symbol-Bibliothek speichern… @@ -5662,6 +5721,11 @@ axis Y Axis Y-Achse User Brush Library 9 Benutzer-Pinsel-Bibliothek 9 User Brush Library 10 Benutzer-Pinsel-Bibliothek 10 Art Ribbons Bildbänder + Zigzag Zickzack + Burst Ray Stoßstrahl + Dash Trail Strichelspur + Speed Line Geschwindigkeitslinie + Game Trails Spielspuren Calligraphic Nibs Kalligrafie-Federn Pattern Borders Musterbordüren Scatter Shapes Streuformen @@ -5682,6 +5746,8 @@ axis Y Axis Y-Achse # Align panel menu › Align to Glyph Bounds (#4231). Point Text Punkttext Area Text Flächentext +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Text an Glyphenbegrenzung messen # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Optionen für „An Glyphe ausrichten“ einblenden Hide Snap to Glyph Options Optionen für „An Glyphe ausrichten“ ausblenden @@ -6249,3 +6315,8 @@ breakText Glyphs Glyphen Align to Pixel Grid Am Pixelraster ausrichten @msg only paths and compound paths can be aligned to the pixel grid nur Pfade und zusammengesetzte Pfade können am Pixelraster ausgerichtet werden @msg side is left or right, not `{s}` side ist left oder right, nicht `{s}` + Ignore All Alle ignorieren + Add to Dictionary Zum Wörterbuch hinzufügen + No Suggestions Keine Vorschläge + Edit Custom Dictionary Benutzerwörterbuch bearbeiten + Entry: Eintrag: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b2d4f2a6ea..a95d84be33 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -275,7 +275,6 @@ font-technology Variable Μεταβλητές Update While Dragging Ενημέρωση κατά τη μεταφορά Hide Video Rulers Απόκρυψη χαράκων βίντεο Background Contents Περιεχόμενα φόντου - Background Contents: Περιεχόμενο φόντου: Background: Φόντο: Backspace Backspace Bar Graph Tool Ραβδόγραμμα (Bar Graph Tool) @@ -543,6 +542,7 @@ font-technology Variable Μεταβλητές Coming soon — tracked in the parity plan Προσεχώς — περιλαμβάνεται στο σχέδιο αντιστοιχίας λειτουργιών Command Click to Select Objects Behind Command-κλικ για επιλογή αντικειμένων από πίσω Command Dialog Παράθυρο εντολών + Command API Reference Αναφορά API εντολών Community Κοινότητα Compatibility: Συμβατότητα: Compatible Gradient and Gradient Mesh Printing Συμβατή εκτύπωση ντεγκραντέ και πλέγματος ντεγκραντέ @@ -628,7 +628,6 @@ font-technology Variable Μεταβλητές Couldn't {} {name}: {e} Δεν ήταν δυνατή η {} του {name}: {e} Create Δημιουργία Create Clipping Mask Δημιουργία μάσκας αποκοπής - Create Document Δημιουργία εγγράφου Create from Guides Δημιουργία από οδηγούς Create from Selection Δημιουργία από επιλογή Create From: Δημιουργία από: @@ -1725,6 +1724,7 @@ font-technology Variable Μεταβλητές Location: Θέση: Lock Κλείδωμα Lock Guides Κλείδωμα οδηγών + Lock Guides by Default Κλείδωμα οδηγών από προεπιλογή Lock Slices Κλείδωμα τομών Low Χαμηλή Luminosity Φωτεινότητα @@ -2074,7 +2074,6 @@ font-technology Variable Μεταβλητές Temperature Θερμοκρασία Template Πρότυπο Templates Πρότυπα - Templates… Πρότυπα… Threshold Κατώφλι Tile Παράθεση Tint Χρωματική απόχρωση @@ -2233,6 +2232,28 @@ axis Both Και τα δύο @msg Combine Slices: the slices have no bounds Συνδυασμός τομών: οι τομές δεν έχουν όρια @msg Convert to Artboards: selection has no area Μετατροπή σε πίνακες σχεδίασης: η επιλογή δεν έχει επιφάνεια @msg Convert to Shape: no rectangles or ellipses selected Μετατροπή σε σχήμα: δεν έχουν επιλεγεί ορθογώνια ή ελλείψεις + Run Εκτέλεση + Run Script Εκτέλεση σεναρίου + Stop Script Διακοπή σεναρίου + Show External Script Warning Εμφάνιση προειδοποίησης για εξωτερικά σενάρια + A Script Is Running Εκτελείται ένα σενάριο + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ένα σενάριο μπορεί να αλλάξει τα ανοιχτά έγγραφα και να γράψει αρχεία μέσω των εντολών που εκτελεί. Εκτελείτε μόνο σενάρια που εμπιστεύεστε. + Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση + Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο. + This script has added a great many objects. Continue, or stop it and undo what it did? Αυτό το σενάριο πρόσθεσε πάρα πολλά αντικείμενα. Συνέχεια, ή διακοπή και αναίρεση όσων έκανε; +@msg Choose a .js or .jsx script Επιλέξτε ένα σενάριο .js ή .jsx +@msg Ran {name} Εκτελέστηκε: {name} +@msg The script was stopped and its changes were undone Το σενάριο διακόπηκε και οι αλλαγές του αναιρέθηκαν +@msg a script is running: stop it or wait for it to finish εκτελείται ένα σενάριο: διακόψτε το ή περιμένετε να τελειώσει +@msg this is a compiled script, which cannot be run; use its source text αυτό είναι μεταγλωττισμένο σενάριο που δεν μπορεί να εκτελεστεί· χρησιμοποιήστε το πηγαίο κείμενό του +@msg the script is not UTF-8 text το σενάριο δεν είναι κείμενο UTF-8 +@msg the script is too large to run το σενάριο είναι πολύ μεγάλο για εκτέλεση +@msg a drag or an undo group is open; finish it before running a script είναι ανοιχτή μια μεταφορά ή ομάδα αναίρεσης· ολοκληρώστε την πριν εκτελέσετε σενάριο +@msg the script left a document that cannot be kept το σενάριο άφησε ένα έγγραφο που δεν μπορεί να διατηρηθεί +@msg the script's run is no longer available η εκτέλεση του σεναρίου δεν είναι πλέον διαθέσιμη +@msg a failed command changed undo steps that could not be put back, so the script was stopped μια εντολή που απέτυχε άλλαξε βήματα αναίρεσης που δεν ήταν δυνατό να επαναφερθούν, οπότε το σενάριο σταμάτησε +@msg a recovery copy could not be written, so the script was not run δεν ήταν δυνατή η εγγραφή αντιγράφου ανάκτησης, οπότε το σενάριο δεν εκτελέστηκε +@msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε @msg Corners edits the corners of a path Η εντολή Γωνίες επεξεργάζεται τις γωνίες μιας διαδρομής @msg Couldn't copy to the system clipboard: {e} Δεν ήταν δυνατή η αντιγραφή στο πρόχειρο συστήματος: {e} @@ -2902,7 +2923,6 @@ theme Appearance Εμφάνιση New Color Group… Νέα ομάδα χρωμάτων… New Document Presets Νέες προεπιλογές εγγράφου New file Νέο αρχείο - New from Template Νέο από πρότυπο New from Template… Νέο από πρότυπο… New Graphic Style Νέο στυλ γραφικών New Graphic Style (Alt-click to name it) Νέο στυλ γραφικών (Alt-κλικ για ονομασία) @@ -3466,6 +3486,7 @@ digits Malayalam Μαλαγιάλαμ Save PDF Preset Αποθήκευση προεπιλογής PDF Save Perspective Grid Preset Αποθήκευση προεπιλογής πλέγματος προοπτικής Save Preset Αποθήκευση προεπιλογής + Save Document Preset Αποθήκευση προεπιλογής εγγράφου Save Print Preset Αποθήκευση προεπιλογής εκτύπωσης Save Recovery Data Αποθήκευση δεδομένων ανάκτησης Save Save for Web Preset Αποθήκευση προεπιλογής για ιστό @@ -3580,6 +3601,13 @@ digits Malayalam Μαλαγιάλαμ Set Zoom Ορισμός ζουμ Setup… Ρύθμιση… Shadows and Glows Σκιές και λάμψεις + Game HUD HUD παιχνιδιού + Health Fill Υγεία + Mana Glow Μάνα + Damage Flash Ζημιά + Quest Outline Αποστολή + Coin Shine Νόμισμα + Boss Alert Αρχηγός Shape Builder Regions Περιοχές δημιουργίας σχημάτων Shape Effects Εφέ σχημάτων Shape Mode Λειτουργία σχήματος @@ -4265,6 +4293,11 @@ digits Malayalam Μαλαγιάλαμ @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) εσωτερικό σφάλμα στην εντολή `{cmd}`: {msg} (το έγγραφο έμεινε αμετάβλητο· αναφέρετε το σφάλμα) @msg internal error: {msg} (please report this bug) εσωτερικό σφάλμα: {msg} (αναφέρετε το σφάλμα) @msg invalid PDF setting: {0} μη έγκυρη ρύθμιση PDF: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller η σελίδα του πίνακα σχεδίασης {n} είναι {size}, μεγαλύτερη από το όριο σελίδας PDF των 14.400 pt (200 in): γράφεται με UserUnit {unit}, οπότε οι εφαρμογές που αγνοούν το UserUnit την εμφανίζουν τόσες φορές μικρότερη +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in η σελίδα του πίνακα σχεδίασης {n} είναι {size}, μεγαλύτερη από το όριο σελίδας PDF των 14.400 pt (200 in): οι σελίδες {label} γράφονται χωρίς UserUnit, σε στιγμές, και οι εφαρμογές που τηρούν το όριο κόβουν τη σελίδα στις 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 το PDF 1.5 δεν έχει UserUnit, που χρειάζεται μια σελίδα μεγαλύτερη από 14.400 pt (200 in) για να κρατήσει το μέγεθός της: το αρχείο γράφεται ως PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units η σελίδα του πίνακα σχεδίασης {n} είναι {size}, πολύ μακριά και στενή για τις πλευρές σελίδας PDF από 3 έως 14.400 μονάδες: γράφεται με UserUnit {unit}, που κρατά τη μικρή πλευρά στις 3 μονάδες ή περισσότερο, και οι εφαρμογές που τηρούν το όριο κόβουν τη μεγάλη πλευρά στις 14.400 μονάδες +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard τα αρχεία {label} δέχονται πραγματικούς αριθμούς έως {max}, και η σελίδα του πίνακα σχεδίασης {n}, μήκους {side} pt, χρειάζεται μεγαλύτερους: επιλέξτε PDF 1.6 ή νεότερο χωρίς πρότυπο PDF/X, ή μικρότερο πίνακα σχεδίασης @msg invalid image data for `{0}` μη έγκυρα δεδομένα εικόνας για `{0}` @msg invalid parameters for `{cmd}`: {msg} μη έγκυρες παράμετροι για `{cmd}`: {msg} @msg is not an image VectorCraft reads δεν είναι μορφή εικόνας που μπορεί να διαβάσει το VectorCraft @@ -4369,6 +4402,7 @@ digits Malayalam Μαλαγιάλαμ @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Φορτώθηκε το «{name}»: παραλείφθηκε {n} βήμα|Φορτώθηκε το «{name}»: παραλείφθηκαν {n} βήματα @msg not an action set file δεν είναι αρχείο συνόλου ενεργειών @msg the action set file is larger than 8 MiB το αρχείο συνόλου ενεργειών είναι μεγαλύτερο από 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: η αναφορά θα ήταν μεγαλύτερη από {MAX_BYTES} byte @msg the action set file holds more than 1,000 actions το αρχείο συνόλου ενεργειών περιέχει περισσότερες από 1.000 ενέργειες @msg the action set file needs a later version of VectorCraft το αρχείο συνόλου ενεργειών απαιτεί νεότερη έκδοση του VectorCraft @msg an action in the action set file has more than 10,000 steps μια ενέργεια στο αρχείο συνόλου ενεργειών έχει περισσότερα από 10.000 βήματα @@ -4948,7 +4982,8 @@ digits Malayalam Μαλαγιάλαμ Bevel Inside Εσωτερική λοξότμηση Bevel both sides Λοξότμηση και των δύο πλευρών @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Ένα αντικείμενο δέχεται ένα εφέ 3D. Επεξεργαστείτε τις επιλογές του υπάρχοντος εφέ ή αφαιρέστε το πρώτα. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. Το {label} απαιτεί προς το παρόν διαδρομή ή σύνθετη διαδρομή. Μετατρέψτε πρώτα το κείμενο, τις εικόνες και τις ομάδες σε διαδρομές. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. Το {label} απαιτεί προς το παρόν διαδρομή, σύνθετη διαδρομή, κείμενο, ομάδα, ανάμειξη ή στιγμιότυπο συμβόλου. Επεκτείνετε πρώτα τα άλλα αντικείμενα. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. Το {label} δεν μπορεί να δημιουργήσει στερεό από εικόνα: ανιχνεύστε την πρώτα με Αντικείμενο › Ανίχνευση περιγραμμάτων εικόνας › Κατασκευαστής. @msg {label} requires a shape with at least two anchors το {label} απαιτεί σχήμα με τουλάχιστον δύο σημεία αγκύρωσης @msg The shape is too complex for a 3D effect Το σχήμα είναι πολύ σύνθετο για εφέ 3D @msg The 3D surface is too complex; simplify the shape Η επιφάνεια 3D είναι πολύ σύνθετη· απλοποιήστε το σχήμα @@ -4956,6 +4991,11 @@ digits Malayalam Μαλαγιάλαμ @msg unknown parameter `{key}`; did you mean `{near}`? άγνωστη παράμετρος `{key}`· μήπως εννοείτε `{near}`; @msg unknown parameter `{key}`; the command takes no parameters άγνωστη παράμετρος `{key}`· η εντολή δεν δέχεται παραμέτρους @msg unknown parameter `{key}`; the command takes: {keys} άγνωστη παράμετρος `{key}`· η εντολή δέχεται: {keys} +@msg the params must be an object, not {got} οι παράμετροι πρέπει να είναι αντικείμενο, όχι {got} +@msg unknown parameter `{path}`; the object takes no keys άγνωστη παράμετρος `{path}`· το αντικείμενο δεν δέχεται κλειδιά +@msg unknown parameter `{path}`; it takes: {keys} άγνωστη παράμετρος `{path}`· δέχεται: {keys} +@msg missing `{path}` λείπει το `{path}` +@msg `{path}` must be {expected}, not {got} Το `{path}` πρέπει να είναι {expected}, όχι {got} 1 Layer 1 επίπεδο 1 bit 1 bit 16 Colors 16 χρώματα @@ -5887,6 +5927,20 @@ axis Y Axis Άξονας Y Show its progress, see Cancel and write log lines Εμφάνιση της προόδου, αναγνώριση της ακύρωσης και εγγραφή γραμμών καταγραφής Keep settings of its own Διατήρηση δικών του ρυθμίσεων Keep a cache of its own, which you can clear Διατήρηση δικής του κρυφής μνήμης, την οποία μπορείτε να εκκαθαρίσετε + Run these commands on the document: {ids} Εκτέλεση αυτών των εντολών στο έγγραφο: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call το «{name}» αναφέρει το `{id}` στο `commandAllowlist`, το οποίο ένα πρόσθετο δεν επιτρέπεται να καλέσει +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: το `commandAllowlist` του μανιφέστου δεν την αναφέρει +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: το αναγνωριστικό ή τα ορίσματα βρίσκονται εκτός της μνήμης της λειτουργικής μονάδας +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: το αναγνωριστικό ή τα ορίσματα δεν είναι UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: τα ορίσματα δεν είναι αντικείμενο JSON +@msg only a filter with the usual budget declares `commandAllowlist` μόνο ένα φίλτρο με τον συνήθη προϋπολογισμό δηλώνει `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) κλήσεις εντολών ({MAX_CALLS} κλήσεις και {MAX_CALL_BYTES} byte ανά εκτέλεση) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) μέγεθος κλήσης εντολής (vc_call `{shown}`: {len} byte, όριο {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` το πολύ {MAX_ALLOWED_COMMANDS} εντολές στο `commandAllowlist` +@msg a plug-in may not call this command ένα πρόσθετο δεν επιτρέπεται να καλέσει αυτή την εντολή +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` το `commandAllowlist` χρειάζεται το δικαίωμα `commands`, και το `commands` χρειάζεται ένα `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice το `commandAllowlist` αναφέρει το `{shown}`, που δεν είναι αναγνωριστικό εντολής ή αναφέρεται δύο φορές Clear Plug-in Cache Εκκαθάριση κρυφής μνήμης προσθέτου @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} το δικαίωμα `{permission}` χρειάζεται το επίπεδο API προσθέτων {PROGRESS_API}: δώστε `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} η λειτουργική μονάδα εισάγει το `env.{name}` με άλλον τύπο από αυτόν του κεντρικού υπολογιστή: ο τύπος του είναι {signature} @@ -5976,6 +6030,11 @@ axis Y Axis Άξονας Y Button Κουμπί Panel Πίνακας UI Frames Πλαίσια UI + Map Markers Δείκτες χάρτη + Pin Καρφίτσα + Flag Σημαία + Crosshair Σταυρόνημα + Checkpoint Σημείο ελέγχου Open Symbol Library Άνοιγμα βιβλιοθήκης συμβόλων Save Symbol Library Αποθήκευση βιβλιοθήκης συμβόλων Save Symbol Library… Αποθήκευση βιβλιοθήκης συμβόλων… @@ -6030,6 +6089,11 @@ axis Y Axis Άξονας Y User Brush Library 9 Βιβλιοθήκη πινέλων χρήστη 9 User Brush Library 10 Βιβλιοθήκη πινέλων χρήστη 10 Art Ribbons Γραφικές κορδέλες + Zigzag Ζιγκζάγκ + Burst Ray Ακτίνα κρούσης + Dash Trail Διακεκομμένο ίχνος + Speed Line Γραμμή ταχύτητας + Game Trails Ίχνη παιχνιδιού Calligraphic Nibs Καλλιγραφικές πένες Pattern Borders Περιθώρια μοτίβου Scatter Shapes Σχήματα διασποράς @@ -6050,6 +6114,8 @@ axis Y Axis Άξονας Y # Align panel menu › Align to Glyph Bounds (#4231). Point Text Κείμενο σημείου Area Text Κείμενο περιοχής +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Μέτρηση κειμένου με βάση τα όρια γλυφής # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Εμφάνιση επιλογών προσκόλλησης σε γλυφή Hide Snap to Glyph Options Απόκρυψη επιλογών προσκόλλησης σε γλυφή @@ -6614,3 +6680,8 @@ breakText Glyphs Γλύφοι Align to Pixel Grid Στοίχιση στο πλέγμα εικονοστοιχείων @msg only paths and compound paths can be aligned to the pixel grid μόνο διαδρομές και σύνθετες διαδρομές μπορούν να στοιχιστούν στο πλέγμα εικονοστοιχείων @msg side is left or right, not `{s}` το side είναι left ή right, όχι `{s}` + Ignore All Παράβλεψη όλων + Add to Dictionary Προσθήκη στο λεξικό + No Suggestions Καμία πρόταση + Edit Custom Dictionary Επεξεργασία προσαρμοσμένου λεξικού + Entry: Λήμμα: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9d50594110..e0903d19d7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -297,7 +297,6 @@ font-technology Variable Variables Update While Dragging Actualizar al arrastrar Hide Video Rulers Ocultar reglas de video Background Contents Contenido de fondo - Background Contents: Contenido de fondo: Background: Fondo: Backspace Retroceso Bar Graph Tool Herramienta Gráfico de barras @@ -583,6 +582,7 @@ font-technology Variable Variables Coming soon — tracked in the parity plan Próximamente: incluido en el plan de paridad Command Click to Select Objects Behind Cmd+clic para seleccionar objetos de detrás Command Dialog Cuadro de diálogo de comando + Command API Reference Referencia de la API de comandos Community Comunidad Compatibility: Compatibilidad: Compatible Gradient and Gradient Mesh Printing Impresión compatible de degradados y mallas de degradado @@ -669,7 +669,6 @@ font-technology Variable Variables Couldn't {} {name}: {e} No se pudo {} {name}: {e} Create Crear Create Clipping Mask Crear máscara de recorte - Create Document Crear documento Create from Guides Crear a partir de guías Create from Selection Crear a partir de la selección Create From: Crear a partir de: @@ -1896,6 +1895,7 @@ font-technology Variable Variables Lock (⌘2) Bloquear (⌘2) Lock Grid Bloquear cuadrícula Lock Guides Bloquear guías + Lock Guides by Default Bloquear guías de forma predeterminada Lock Others Bloquear otros Lock Slices Bloquear sectores Lock Station Point Bloquear punto de estación @@ -2146,7 +2146,6 @@ font-technology Variable Variables New Color Group… Nuevo grupo de colores… New Document Presets Preajustes de documento nuevo New file Archivo nuevo - New from Template Nuevo a partir de plantilla New from Template… Nuevo a partir de plantilla… New Graphic Style Nuevo estilo gráfico New Graphic Style (Alt-click to name it) Nuevo estilo gráfico (Alt+clic para darle nombre) @@ -2933,6 +2932,7 @@ digits Malayalam Malayálam Save PDF Preset Guardar preajuste de PDF Save Perspective Grid Preset Guardar preajuste de cuadrícula de perspectiva Save Preset Guardar preajuste + Save Document Preset Guardar preajuste de documento Save Preset… Guardar preajuste… Save Print Preset Guardar preajuste de impresión Save Recovery Data Guardar datos de recuperación @@ -3139,6 +3139,13 @@ digits Malayalam Malayálam Settings… Ajustes… Setup… Configuración… Shadows and Glows Sombras y resplandores + Game HUD HUD de juego + Health Fill Salud + Mana Glow Maná + Damage Flash Daño + Quest Outline Misión + Coin Shine Moneda + Boss Alert Jefe Shape Forma Shape Builder Generador de formas Shape Builder Regions Regiones del generador de formas @@ -3510,7 +3517,6 @@ digits Malayalam Malayálam Template Plantilla Templates Plantillas Templates Folder Carpeta de plantillas - Templates… Plantillas… Text Displayed in Cell: Texto mostrado en la celda: Text Export Options Opciones de exportación de texto Text Fill & Stroke Color Color de relleno y trazo del texto @@ -4068,6 +4074,28 @@ axis Both Ambos @msg Combine Slices: the slices have no bounds Combinar sectores: los sectores no tienen límites @msg Convert to Artboards: selection has no area Convertir en mesas de trabajo: la selección no tiene área @msg Convert to Shape: no rectangles or ellipses selected Convertir en forma: no hay rectángulos ni elipses seleccionados + Run Ejecutar + Run Script Ejecutar script + Stop Script Detener script + Show External Script Warning Mostrar advertencia de scripts externos + A Script Is Running Se está ejecutando un script + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script puede cambiar los documentos abiertos y escribir archivos mediante los comandos que ejecuta. Ejecute solo scripts de confianza. + Do not show this warning again No volver a mostrar esta advertencia + Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir. + This script has added a great many objects. Continue, or stop it and undo what it did? Este script ha añadido muchísimos objetos. ¿Continuar, o detenerlo y deshacer lo que hizo? +@msg Choose a .js or .jsx script Elija un script .js o .jsx +@msg Ran {name} Se ejecutó {name} +@msg The script was stopped and its changes were undone El script se detuvo y sus cambios se deshicieron +@msg a script is running: stop it or wait for it to finish se está ejecutando un script: deténgalo o espere a que termine +@msg this is a compiled script, which cannot be run; use its source text este es un script compilado, que no se puede ejecutar; use su texto fuente +@msg the script is not UTF-8 text el script no es texto UTF-8 +@msg the script is too large to run el script es demasiado grande para ejecutarlo +@msg a drag or an undo group is open; finish it before running a script hay un arrastre o un grupo de deshacer abierto; termínelo antes de ejecutar un script +@msg the script left a document that cannot be kept el script dejó un documento que no se puede conservar +@msg the script's run is no longer available la ejecución del script ya no está disponible +@msg a failed command changed undo steps that could not be put back, so the script was stopped un comando fallido cambió pasos de deshacer que no se pudieron restaurar, así que el script se detuvo +@msg a recovery copy could not be written, so the script was not run no se pudo escribir una copia de recuperación, así que el script no se ejecutó +@msg Running a script Ejecutando un script @msg Copied the script report Se copió el informe del script @msg Corners edits the corners of a path Esquinas edita las esquinas de un trazado @msg Couldn't copy to the system clipboard: {e} No se pudo copiar al portapapeles del sistema: {e} @@ -4311,6 +4339,11 @@ axis Both Ambos @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) error interno en `{cmd}`: {msg} (el documento quedó como estaba; por favor, informa de este error) @msg internal error: {msg} (please report this bug) error interno: {msg} (por favor, informa de este error) @msg invalid PDF setting: {0} ajuste de PDF no válido: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la página de la mesa de trabajo {n} mide {size}, más que el límite de página de PDF de 14.400 pt (200 in): se escribe con un UserUnit de {unit}, así que las aplicaciones que ignoran UserUnit la muestran ese número de veces más pequeña +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la página de la mesa de trabajo {n} mide {size}, más que el límite de página de PDF de 14.400 pt (200 in): las páginas {label} se escriben sin UserUnit, en puntos, y las aplicaciones que respetan el límite recortan la página a 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 no tiene UserUnit, que una página de más de 14.400 pt (200 in) necesita para conservar su tamaño: el archivo se escribe como PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la página de la mesa de trabajo {n} mide {size}, demasiado larga y estrecha para los lados de página de PDF de 3 a 14.400 unidades: se escribe con una UserUnit de {unit}, que mantiene el lado corto en 3 unidades o más, y las aplicaciones que respetan el límite recortan el lado largo a 14.400 unidades +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard los archivos {label} admiten números reales de hasta {max}, y la página de la mesa de trabajo {n}, de {side} pt, necesita otros mayores: elija PDF 1.6 o posterior sin estándar PDF/X, o una mesa de trabajo más pequeña @msg invalid image data for `{0}` datos de imagen no válidos para `{0}` @msg invalid parameters for `{cmd}`: {msg} parámetros no válidos para `{cmd}`: {msg} @msg is not an image VectorCraft reads no es una imagen que VectorCraft pueda leer @@ -4415,6 +4448,7 @@ axis Both Ambos @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Se cargó “{name}”: se omitió {n} paso|Se cargó “{name}”: se omitieron {n} pasos @msg not an action set file no es un archivo de conjunto de acciones @msg the action set file is larger than 8 MiB el archivo de conjunto de acciones supera los 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: la referencia superaría los {MAX_BYTES} bytes @msg the action set file holds more than 1,000 actions el archivo de conjunto de acciones contiene más de 1000 acciones @msg the action set file needs a later version of VectorCraft el archivo de conjunto de acciones necesita una versión más reciente de VectorCraft @msg an action in the action set file has more than 10,000 steps una acción del archivo de conjunto de acciones tiene más de 10 000 pasos @@ -5528,7 +5562,8 @@ mark-style Japanese Japonesas Bevel both sides Bisel en ambos lados Presets Ajustes preestablecidos @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Un objeto admite un solo efecto 3D. Edite las opciones del efecto existente o quítelo primero. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} requiere por ahora un trazado o un trazado compuesto. Convierta primero el texto, las imágenes y los grupos en trazados. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} requiere por ahora un trazado, un trazado compuesto, texto, un grupo, una fusión o una instancia de símbolo. Expanda primero los demás objetos. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} no puede crear un sólido a partir de una imagen: cálquela primero con Objeto › Calco de imagen › Crear. @msg {label} requires a shape with at least two anchors {label} requiere una forma con al menos dos puntos de ancla @msg The shape is too complex for a 3D effect La forma es demasiado compleja para un efecto 3D @msg The 3D surface is too complex; simplify the shape La superficie 3D es demasiado compleja; simplifique la forma @@ -5536,6 +5571,11 @@ mark-style Japanese Japonesas @msg unknown parameter `{key}`; did you mean `{near}`? parámetro desconocido `{key}`; ¿quiso decir `{near}`? @msg unknown parameter `{key}`; the command takes no parameters parámetro desconocido `{key}`; el comando no tiene parámetros @msg unknown parameter `{key}`; the command takes: {keys} parámetro desconocido `{key}`; el comando acepta: {keys} +@msg the params must be an object, not {got} los parámetros deben ser un objeto, no {got} +@msg unknown parameter `{path}`; the object takes no keys parámetro desconocido `{path}`; el objeto no acepta claves +@msg unknown parameter `{path}`; it takes: {keys} parámetro desconocido `{path}`; acepta: {keys} +@msg missing `{path}` falta `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` debe ser {expected}, no {got} Load EPS into Clipboard Cargar EPS en el portapapeles @msg an image of {w} × {h} pixels is too large to draw una imagen de {w} × {h} píxeles es demasiado grande para dibujarse @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: no es una imagen PNG, JPEG, WebP, TIFF ni BMP @@ -5878,6 +5918,20 @@ axis Y Axis Eje Y Show its progress, see Cancel and write log lines Mostrar su progreso, detectar la cancelación y escribir líneas de registro Keep settings of its own Guardar una configuración propia Keep a cache of its own, which you can clear Guardar una caché propia, que usted puede vaciar + Run these commands on the document: {ids} Ejecutar estos comandos en el documento: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” incluye `{id}` en `commandAllowlist`, que un plugin no puede llamar +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: el `commandAllowlist` del manifiesto no lo incluye +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: el ID o los argumentos están fuera de la memoria del módulo +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: el ID o los argumentos no son UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: los argumentos no son un objeto JSON +@msg only a filter with the usual budget declares `commandAllowlist` solo un filtro con el presupuesto habitual declara `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) llamadas a comandos ({MAX_CALLS} llamadas y {MAX_CALL_BYTES} bytes por ejecución) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) tamaño de una llamada a comando (vc_call `{shown}`: {len} bytes, límite {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` como máximo {MAX_ALLOWED_COMMANDS} comandos en `commandAllowlist` +@msg a plug-in may not call this command un plugin no puede llamar a este comando +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` necesita el permiso `commands`, y `commands` necesita un `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` incluye `{shown}`, que no es un ID de comando o aparece dos veces Clear Plug-in Cache Vaciar caché del plugin @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} el permiso `{permission}` necesita el nivel de API de plugins {PROGRESS_API}: indique `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} el módulo importa `env.{name}` con un tipo distinto del del host: el del host es {signature} @@ -5967,6 +6021,11 @@ axis Y Axis Eje Y Button Botón Panel Panel UI Frames Marcos de IU + Map Markers Marcadores de mapa + Pin Chincheta + Flag Bandera + Crosshair Punto de mira + Checkpoint Punto de control Open Symbol Library Abrir biblioteca de símbolos Save Symbol Library Guardar biblioteca de símbolos Save Symbol Library… Guardar biblioteca de símbolos… @@ -6021,6 +6080,11 @@ axis Y Axis Eje Y User Brush Library 9 Biblioteca de pinceles del usuario 9 User Brush Library 10 Biblioteca de pinceles del usuario 10 Art Ribbons Cintas de ilustración + Zigzag Zigzag + Burst Ray Rayo de impacto + Dash Trail Estela discontinua + Speed Line Línea de velocidad + Game Trails Estelas de juego Calligraphic Nibs Plumillas caligráficas Pattern Borders Bordes de motivo Scatter Shapes Formas de dispersión @@ -6041,6 +6105,8 @@ axis Y Axis Eje Y # Align panel menu › Align to Glyph Bounds (#4231). Point Text Texto de punto Area Text Texto de área +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Medir el texto por los límites del glifo # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Mostrar opciones de ajuste a glifo Hide Snap to Glyph Options Ocultar opciones de ajuste a glifo @@ -6605,3 +6671,8 @@ breakText Glyphs Glifos Align to Pixel Grid Alinear con cuadrícula de píxeles @msg only paths and compound paths can be aligned to the pixel grid solo los trazados y los trazados compuestos se pueden alinear con la cuadrícula de píxeles @msg side is left or right, not `{s}` side es left o right, no `{s}` + Ignore All Omitir todo + Add to Dictionary Añadir al diccionario + No Suggestions No hay sugerencias + Edit Custom Dictionary Editar diccionario personalizado + Entry: Entrada: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index dbdf5d111e..b593200aa5 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -600,6 +600,7 @@ Hide Guides Piilota apuviivat Show Guides Näytä apuviivat Lock Guides Lukitse apuviivat + Lock Guides by Default Lukitse apuviivat oletuksena Unlock Guides Avaa apuviivojen lukitus Make Guides Luo apuviivat Release Guides Vapauta apuviivat @@ -765,6 +766,13 @@ Other Library… Muu kirjasto… Graphic Style Libraries Grafiikkatyylikirjastot Shadows and Glows Varjot ja hehkut + Game HUD Peli-HUD + Health Fill Terveys + Mana Glow Mana + Damage Flash Vahinko + Quest Outline Tehtävä + Coin Shine Kolikko + Boss Alert Bossi Outlines and Rules Ääriviivat ja viivat Hand-Drawn Käsin piirretyt Gradient Finishes Liukuväriviimeistelyt @@ -963,6 +971,7 @@ lighting Light Valo Color Picker… Värivalitsin… Coming soon — tracked in the parity plan Tulossa pian — seurataan yhdenmukaisuussuunnitelmassa Command Dialog Komentovalintaikkuna + Command API Reference Komentojen API-viite Copy Selected Style Kopioi valittu tyyli Corners… Kulmat… Define Perspective Grid… Määritä perspektiiviruudukko… @@ -2506,15 +2515,12 @@ digits Malayalam Malajalam Selected Swatches Valitut värimallit Advanced Options Lisäasetukset Background Contents Taustan sisältö - Background Contents: Taustan sisältö: BLANK DOCUMENT PRESETS TYHJÄN ASIAKIRJAN ESIASETUKSET Bleed Leikkuuvara Change to Right-to-Left Layout Vaihda oikealta vasemmalle -asetteluun Columns: Sarakkeet: - Create Document Luo asiakirja Documents you create appear here. Luomasi asiakirjat näkyvät tässä. More Settings Lisää asetuksia - New from Template Uusi mallista Number of Artboards: Piirtoalustojen määrä: Orientation: Suunta: PRESET DETAILS ESIASETUKSEN TIEDOT @@ -2525,7 +2531,6 @@ digits Malayalam Malajalam RECENT VIIMEISIMMÄT RECENT (1) VIIMEISIMMÄT (1) SAVED TALLENNETUT - Templates… Mallit… Transparent (Default) Läpinäkyvä (oletus) Save for Office Documents Tallenna Office-asiakirjoja varten Transparent Background Läpinäkyvä tausta @@ -3474,6 +3479,7 @@ theme Appearance Ulkoasu Arrange by Row Järjestä riveittäin Arrange by Column Järjestä sarakkeittain Save Preset Tallenna esiasetus + Save Document Preset Tallenna asiakirjan esiasetus Screen (72 ppi) Näyttö (72 ppi) Social Square Post 1080×1080 Neliömäinen somejulkaisu 1080×1080 Distribute Jaa tasaisesti @@ -4292,6 +4298,28 @@ imageTrace Outline Ääriviiva @msg Combine Slices: the slices have no bounds Yhdistä viipaleet: viipaleilla ei ole rajoja @msg Convert to Artboards: selection has no area Muunna piirtoalustoiksi: valinnalla ei ole pinta-alaa @msg Convert to Shape: no rectangles or ellipses selected Muunna muodoksi: suorakulmioita tai ellipsejä ei ole valittu + Run Suorita + Run Script Suorita komentosarja + Stop Script Pysäytä komentosarja + Show External Script Warning Näytä ulkoisten komentosarjojen varoitus + A Script Is Running Komentosarja on käynnissä + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Komentosarja voi muuttaa avoimia asiakirjoja ja kirjoittaa tiedostoja suorittamillaan komennoilla. Suorita vain komentosarjoja, joihin luotat. + Do not show this warning again Älä näytä tätä varoitusta uudelleen + Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen. + This script has added a great many objects. Continue, or stop it and undo what it did? Tämä komentosarja on lisännyt hyvin paljon objekteja. Jatketaanko, vai pysäytetäänkö se ja kumotaan sen muutokset? +@msg Choose a .js or .jsx script Valitse .js- tai .jsx-komentosarja +@msg Ran {name} Suoritettu: {name} +@msg The script was stopped and its changes were undone Komentosarja pysäytettiin ja sen muutokset kumottiin +@msg a script is running: stop it or wait for it to finish komentosarja on käynnissä: pysäytä se tai odota sen valmistumista +@msg this is a compiled script, which cannot be run; use its source text tämä on käännetty komentosarja, jota ei voi suorittaa; käytä sen lähdetekstiä +@msg the script is not UTF-8 text komentosarja ei ole UTF-8-tekstiä +@msg the script is too large to run komentosarja on liian suuri suoritettavaksi +@msg a drag or an undo group is open; finish it before running a script vetäminen tai kumousryhmä on kesken; viimeistele se ennen komentosarjan suorittamista +@msg the script left a document that cannot be kept komentosarja jätti asiakirjan, jota ei voi säilyttää +@msg the script's run is no longer available komentosarjan suoritus ei ole enää käytettävissä +@msg a failed command changed undo steps that could not be put back, so the script was stopped epäonnistunut komento muutti kumoamisvaiheita, joita ei voitu palauttaa, joten komentosarja pysäytettiin +@msg a recovery copy could not be written, so the script was not run palautuskopiota ei voitu kirjoittaa, joten komentosarjaa ei suoritettu +@msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin @msg Corners edits the corners of a path Kulmat-toiminto muokkaa polun kulmia @msg Couldn't copy to the system clipboard: {e} Järjestelmän leikepöydälle ei voitu kopioida: {e} @@ -4528,6 +4556,11 @@ imageTrace Outline Ääriviiva @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) sisäinen virhe kohteessa `{cmd}`: {msg} (asiakirja jätettiin ennalleen; ilmoita tästä virheestä) @msg internal error: {msg} (please report this bug) sisäinen virhe: {msg} (ilmoita tästä virheestä) @msg invalid PDF setting: {0} virheellinen PDF-asetus: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller piirtoalustan {n} sivu on {size}, pidempi kuin PDF:n 14 400 pt:n (200 in) sivuraja: se kirjoitetaan UserUnit-arvolla {unit}, joten UserUnitin ohittavat sovellukset näyttävät sen niin monta kertaa pienempänä +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in piirtoalustan {n} sivu on {size}, pidempi kuin PDF:n 14 400 pt:n (200 in) sivuraja: {label}-sivut kirjoitetaan ilman UserUnitia, pisteinä, ja rajaa noudattavat sovellukset rajaavat sivun 200 in:iin +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5:ssä ei ole UserUnitia, jota yli 14 400 pt:n (200 in) sivu tarvitsee säilyttääkseen kokonsa: tiedosto kirjoitetaan PDF 1.6:na +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units piirtoalustan {n} sivu on {size}, liian pitkä ja kapea PDF:n sivuille, jotka ovat 3:sta 14 400 yksikköön: se kirjoitetaan UserUnit-arvolla {unit}, joka pitää lyhyen sivun vähintään 3 yksikössä, ja rajaa noudattavat sovellukset leikkaavat pitkän sivun 14 400 yksikköön +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-tiedostot sallivat reaaliluvut enintään {max}, ja piirtoalustan {n} sivu, {side} pt pitkä, tarvitsee suurempia: valitse PDF 1.6 tai uudempi ilman PDF/X-standardia tai pienempi piirtoalusta @msg invalid image data for `{0}` virheellinen kuvadata kohteelle `{0}` @msg invalid parameters for `{cmd}`: {msg} virheelliset parametrit kohteelle `{cmd}`: {msg} @msg is not an image VectorCraft reads ei ole kuva, jota VectorCraft lukee @@ -4632,6 +4665,7 @@ imageTrace Outline Ääriviiva @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Ladattiin ”{name}”: jätettiin pois {n} vaihe|Ladattiin ”{name}”: jätettiin pois {n} vaihetta @msg not an action set file ei ole toimintosarjatiedosto @msg the action set file is larger than 8 MiB toimintosarjatiedosto on suurempi kuin 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: viite olisi suurempi kuin {MAX_BYTES} tavua @msg the action set file holds more than 1,000 actions toimintosarjatiedostossa on yli 1 000 toimintoa @msg the action set file needs a later version of VectorCraft toimintosarjatiedosto vaatii uudemman VectorCraft-version @msg an action in the action set file has more than 10,000 steps toimintosarjatiedoston toiminnossa on yli 10 000 vaihetta @@ -5471,7 +5505,8 @@ mark-style Japanese Japanilainen Bevel both sides Viiste molemmin puolin Presets Esiasetukset @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Objektilla voi olla yksi 3D-tehoste. Muokkaa olemassa olevan tehosteen asetuksia tai poista se ensin. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} vaatii tällä hetkellä polun tai yhdistelmäpolun. Muunna teksti, kuvat ja ryhmät ensin poluiksi. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} vaatii tällä hetkellä polun, yhdistelmäpolun, tekstin, ryhmän, sulautuksen tai symbolin ilmentymän. Laajenna muut objektit ensin. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} ei voi luoda kappaletta kuvasta: jäljitä se ensin komennolla Objekti › Kuvan jäljitys › Luo. @msg {label} requires a shape with at least two anchors {label} vaatii muodon, jossa on vähintään kaksi ankkuria @msg The shape is too complex for a 3D effect Muoto on liian monimutkainen 3D-tehosteelle @msg The 3D surface is too complex; simplify the shape 3D-pinta on liian monimutkainen; yksinkertaista muotoa @@ -5479,6 +5514,11 @@ mark-style Japanese Japanilainen @msg unknown parameter `{key}`; did you mean `{near}`? tuntematon parametri `{key}`; tarkoititko `{near}`? @msg unknown parameter `{key}`; the command takes no parameters tuntematon parametri `{key}`; komento ei ota parametreja @msg unknown parameter `{key}`; the command takes: {keys} tuntematon parametri `{key}`; komennon parametrit: {keys} +@msg the params must be an object, not {got} parametrien on oltava objekti, ei {got} +@msg unknown parameter `{path}`; the object takes no keys tuntematon parametri `{path}`; objekti ei ota avaimia +@msg unknown parameter `{path}`; it takes: {keys} tuntematon parametri `{path}`; parametrit: {keys} +@msg missing `{path}` `{path}` puuttuu +@msg `{path}` must be {expected}, not {got} `{path}` on oltava {expected}, ei {got} Load EPS into Clipboard Lataa EPS leikepöydälle @msg an image of {w} × {h} pixels is too large to draw kuva, jonka koko on {w} × {h} pikseliä, on liian suuri piirrettäväksi @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: ei ole PNG-, JPEG-, WebP-, TIFF- tai BMP-kuva @@ -5966,6 +6006,20 @@ axis Y Axis Y-akseli Show its progress, see Cancel and write log lines Näyttää edistymisensä, havaita peruutuksen ja kirjoittaa lokirivejä Keep settings of its own Säilyttää omat asetuksensa Keep a cache of its own, which you can clear Säilyttää oman välimuistin, jonka voit tyhjentää + Run these commands on the document: {ids} Suorittaa nämä komennot asiakirjassa: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” luettelee `commandAllowlist`-luettelossa komennon `{id}`, jota laajennus ei saa kutsua +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: manifestin `commandAllowlist` ei luettele sitä +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: tunnus tai argumentit ovat moduulin muistin ulkopuolella +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: tunnus tai argumentit eivät ole UTF-8:aa +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumentit eivät ole JSON-objekti +@msg only a filter with the usual budget declares `commandAllowlist` vain tavallisen budjetin suodatin voi määrittää `commandAllowlist`-luettelon +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) komentokutsut ({MAX_CALLS} kutsua ja {MAX_CALL_BYTES} tavua ajoa kohden) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) komentokutsun koko (vc_call `{shown}`: {len} tavua, raja {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` enintään {MAX_ALLOWED_COMMANDS} komentoa `commandAllowlist`-luettelossa +@msg a plug-in may not call this command laajennus ei saa kutsua tätä komentoa +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` tarvitsee käyttöoikeuden `commands`, ja `commands` tarvitsee `commandAllowlist`-luettelon +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` mainitsee kohteen `{shown}`, joka ei ole komennon tunnus tai on luettelossa kahdesti Clear Plug-in Cache Tyhjennä laajennuksen välimuisti @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} käyttöoikeus `{permission}` vaatii laajennus-API:n tason {PROGRESS_API}: anna `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} moduuli tuo kohteen `env.{name}` eri tyyppisenä kuin isäntä: isännän tyyppi on {signature} @@ -6055,6 +6109,11 @@ axis Y Axis Y-akseli Button Painike Panel Paneeli UI Frames UI-kehykset + Map Markers Karttamerkit + Pin Nasta + Flag Lippu + Crosshair Tähtäin + Checkpoint Tarkastuskohta Open Symbol Library Avaa symbolikirjasto Save Symbol Library Tallenna symbolikirjasto Save Symbol Library… Tallenna symbolikirjasto… @@ -6109,6 +6168,11 @@ axis Y Axis Y-akseli User Brush Library 9 Käyttäjän sivellinkirjasto 9 User Brush Library 10 Käyttäjän sivellinkirjasto 10 Art Ribbons Kuvitusnauhat + Zigzag Siksak + Burst Ray Iskusäde + Dash Trail Katkoviiva + Speed Line Nopeusviiva + Game Trails Pelijäljet Calligraphic Nibs Kalligrafiakärjet Pattern Borders Kuvioreunukset Scatter Shapes Sirontamuodot @@ -6129,6 +6193,8 @@ axis Y Axis Y-akseli # Align panel menu › Align to Glyph Bounds (#4231). Point Text Pisteteksti Area Text Alueteksti +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Mittaa teksti merkin rajoista # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Näytä merkkiin kohdistuksen asetukset Hide Snap to Glyph Options Piilota merkkiin kohdistuksen asetukset @@ -6697,3 +6763,8 @@ breakText Glyphs Merkit Align to Pixel Grid Tasaa pikseliruudukkoon @msg only paths and compound paths can be aligned to the pixel grid vain polut ja yhdistelmäpolut voi tasata pikseliruudukkoon @msg side is left or right, not `{s}` side on left tai right, ei `{s}` + Ignore All Ohita kaikki + Add to Dictionary Lisää sanastoon + No Suggestions Ei ehdotuksia + Edit Custom Dictionary Muokkaa omaa sanastoa + Entry: Merkintä: diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 7c6d1fb0e9..6dd4e37a41 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -298,7 +298,6 @@ font-technology Variable Variables Update While Dragging Mettre à jour pendant le déplacement Hide Video Rulers Masquer les règles vidéo Background Contents Contenu de l’arrière-plan - Background Contents: Contenu de l’arrière-plan : Background: Arrière-plan : Backspace Retour arrière Bar Graph Tool Outil Graphe à barres @@ -584,6 +583,7 @@ font-technology Variable Variables Coming soon — tracked in the parity plan Bientôt disponible — prévu dans le plan de parité Command Click to Select Objects Behind Cmd+clic pour sélectionner les objets situés derrière Command Dialog Boîte de dialogue des commandes + Command API Reference Référence de l’API des commandes Community Communauté Compatibility: Compatibilité : Compatible Gradient and Gradient Mesh Printing Impression compatible des dégradés et des filets de dégradé @@ -670,7 +670,6 @@ font-technology Variable Variables Couldn't {} {name}: {e} Impossible de {} {name} : {e} Create Créer Create Clipping Mask Créer un masque d’écrêtage - Create Document Créer un document Create from Guides Créer à partir des repères Create from Selection Créer à partir de la sélection Create From: Créer à partir de : @@ -1890,6 +1889,7 @@ font-technology Variable Variables Lock (⌘2) Verrouiller (⌘2) Lock Grid Verrouiller la grille Lock Guides Verrouiller les repères + Lock Guides by Default Verrouiller les repères par défaut Lock Others Verrouiller les autres Lock Slices Verrouiller les tranches Lock Station Point Verrouiller le point d’observation @@ -2138,7 +2138,6 @@ font-technology Variable Variables New Color Group… Nouveau groupe de couleurs… New Document Presets Paramètres prédéfinis de nouveau document New file Nouveau fichier - New from Template Nouveau d’après un modèle New from Template… Nouveau d’après un modèle… New Graphic Style Nouveau style graphique New Graphic Style (Alt-click to name it) Nouveau style graphique (Alt+clic pour le nommer) @@ -2925,6 +2924,7 @@ digits Malayalam Malayalam Save PDF Preset Enregistrer le paramètre prédéfini PDF Save Perspective Grid Preset Enregistrer le paramètre prédéfini de grille de perspective Save Preset Enregistrer le paramètre prédéfini + Save Document Preset Enregistrer le paramètre prédéfini du document Save Preset… Enregistrer le paramètre prédéfini… Save Print Preset Enregistrer le paramètre prédéfini d’impression Save Recovery Data Enregistrer les données de récupération @@ -3131,6 +3131,13 @@ digits Malayalam Malayalam Settings… Réglages… Setup… Configuration… Shadows and Glows Ombres et lueurs + Game HUD HUD de jeu + Health Fill Santé + Mana Glow Mana + Damage Flash Dégâts + Quest Outline Quête + Coin Shine Pièce + Boss Alert Boss Shape Forme Shape Builder Concepteur de forme Shape Builder Regions Zones du Concepteur de forme @@ -3502,7 +3509,6 @@ digits Malayalam Malayalam Template Modèle Templates Modèles Templates Folder Dossier des modèles - Templates… Modèles… Text Displayed in Cell: Texte affiché dans la cellule : Text Export Options Options d’exportation du texte Text Fill & Stroke Color Couleur de fond et de contour du texte @@ -4057,6 +4063,28 @@ axis Both Les deux @msg Combine Slices: the slices have no bounds Combiner les tranches : les tranches n’ont pas de limites @msg Convert to Artboards: selection has no area Convertir en plans de travail : la sélection n’a pas de surface @msg Convert to Shape: no rectangles or ellipses selected Convertir en forme : aucun rectangle ni aucune ellipse sélectionné + Run Exécuter + Run Script Exécuter le script + Stop Script Arrêter le script + Show External Script Warning Afficher l’avertissement des scripts externes + A Script Is Running Un script est en cours d’exécution + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script peut modifier les documents ouverts et écrire des fichiers au moyen des commandes qu’il exécute. N’exécutez que des scripts de confiance. + Do not show this warning again Ne plus afficher cet avertissement + Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau. + This script has added a great many objects. Continue, or stop it and undo what it did? Ce script a ajouté un très grand nombre d’objets. Continuer, ou l’arrêter et annuler ce qu’il a fait ? +@msg Choose a .js or .jsx script Choisissez un script .js ou .jsx +@msg Ran {name} {name} exécuté +@msg The script was stopped and its changes were undone Le script a été arrêté et ses modifications ont été annulées +@msg a script is running: stop it or wait for it to finish un script est en cours d’exécution : arrêtez-le ou attendez qu’il se termine +@msg this is a compiled script, which cannot be run; use its source text ce script est compilé et ne peut pas être exécuté ; utilisez son texte source +@msg the script is not UTF-8 text le script n’est pas du texte UTF-8 +@msg the script is too large to run le script est trop volumineux pour être exécuté +@msg a drag or an undo group is open; finish it before running a script un glissement ou un groupe d’annulation est ouvert ; terminez-le avant d’exécuter un script +@msg the script left a document that cannot be kept le script a laissé un document qui ne peut pas être conservé +@msg the script's run is no longer available l’exécution du script n’est plus disponible +@msg a failed command changed undo steps that could not be put back, so the script was stopped une commande en échec a modifié des étapes d’annulation qui n’ont pas pu être rétablies, le script a donc été arrêté +@msg a recovery copy could not be written, so the script was not run une copie de récupération n’a pas pu être écrite, le script n’a donc pas été exécuté +@msg Running a script Exécution d’un script @msg Copied the script report Rapport du script copié @msg Corners edits the corners of a path Angles modifie les angles d’un tracé @msg Couldn't copy to the system clipboard: {e} Impossible de copier dans le presse-papiers du système : {e} @@ -4299,6 +4327,11 @@ axis Both Les deux @msg installing from a path is not available on the web; pass the module as `dataBase64` l’installation depuis un chemin n’est pas disponible sur le web ; transmettez le module sous forme de `dataBase64` @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) erreur interne dans `{cmd}` : {msg} (le document est resté tel qu’il était ; veuillez signaler ce bogue) @msg internal error: {msg} (please report this bug) erreur interne : {msg} (veuillez signaler ce bogue) +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la page du plan de travail {n} mesure {size}, plus que la limite de page PDF de 14 400 pt (200 in) : elle est écrite avec une UserUnit de {unit}, donc les applications qui ignorent UserUnit l’affichent autant de fois plus petite +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la page du plan de travail {n} mesure {size}, plus que la limite de page PDF de 14 400 pt (200 in) : les pages {label} sont écrites sans UserUnit, en points, et les applications qui respectent la limite coupent la page à 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 n’a pas d’UserUnit, dont une page de plus de 14 400 pt (200 in) a besoin pour garder sa taille : le fichier est écrit en PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la page du plan de travail {n} mesure {size}, trop longue et étroite pour les côtés de page PDF de 3 à 14 400 unités : elle est écrite avec une UserUnit de {unit}, qui garde le petit côté à 3 unités ou plus, et les apps qui respectent la limite coupent le grand côté à 14 400 unités +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard les fichiers {label} acceptent des nombres réels jusqu’à {max}, et la page du plan de travail {n}, longue de {side} pt, en demande de plus grands : choisissez PDF 1.6 ou ultérieur sans norme PDF/X, ou un plan de travail plus petit @msg invalid PDF setting: {0} réglage PDF non valide : {0} @msg invalid image data for `{0}` données d’image non valides pour `{0}` @msg invalid parameters for `{cmd}`: {msg} paramètres non valides pour `{cmd}` : {msg} @@ -4404,6 +4437,7 @@ axis Both Les deux @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out « {name} » chargé : {n} étape a été ignorée|« {name} » chargé : {n} étapes ont été ignorées @msg not an action set file ce n’est pas un fichier de jeu de scripts @msg the action set file is larger than 8 MiB le fichier de jeu de scripts dépasse 8 Mio +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}` : la référence dépasserait {MAX_BYTES} octets @msg the action set file holds more than 1,000 actions le fichier de jeu de scripts contient plus de 1 000 scripts @msg the action set file needs a later version of VectorCraft le fichier de jeu de scripts nécessite une version plus récente de VectorCraft @msg an action in the action set file has more than 10,000 steps un script du fichier de jeu de scripts compte plus de 10 000 étapes @@ -5158,7 +5192,8 @@ lighting Light Lumière Bevel both sides Biseau des deux côtés Presets Paramètres prédéfinis @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Un objet n'accepte qu'un seul effet 3D. Modifiez les options de l'effet existant ou supprimez-le d'abord. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} nécessite pour l'instant un tracé ou un tracé transparent. Convertissez d'abord le texte, les images et les groupes en tracés. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} nécessite pour l'instant un tracé, un tracé transparent, du texte, un groupe, un dégradé de formes ou une instance de symbole. Décomposez d'abord les autres objets. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} ne peut pas créer de solide à partir d'une image : vectorisez-la d'abord avec Objet › Vectorisation de l’image › Créer. @msg {label} requires a shape with at least two anchors {label} nécessite une forme comportant au moins deux points d'ancrage @msg The shape is too complex for a 3D effect La forme est trop complexe pour un effet 3D @msg The 3D surface is too complex; simplify the shape La surface 3D est trop complexe ; simplifiez la forme @@ -5166,6 +5201,11 @@ lighting Light Lumière @msg unknown parameter `{key}`; did you mean `{near}`? paramètre inconnu `{key}` ; vouliez-vous dire `{near}` ? @msg unknown parameter `{key}`; the command takes no parameters paramètre inconnu `{key}` ; la commande n’a aucun paramètre @msg unknown parameter `{key}`; the command takes: {keys} paramètre inconnu `{key}` ; la commande accepte : {keys} +@msg the params must be an object, not {got} les paramètres doivent être un objet, pas {got} +@msg unknown parameter `{path}`; the object takes no keys paramètre inconnu `{path}` ; l’objet n’accepte aucune clé +@msg unknown parameter `{path}`; it takes: {keys} paramètre inconnu `{path}` ; il accepte : {keys} +@msg missing `{path}` `{path}` manquant +@msg `{path}` must be {expected}, not {got} `{path}` doit être {expected}, pas {got} 1 Layer 1 calque 1 bit 1 bit 16 Colors 16 couleurs @@ -5931,6 +5971,20 @@ axis Y Axis Axe Y Show its progress, see Cancel and write log lines Afficher sa progression, détecter l’annulation et écrire des lignes de journal Keep settings of its own Conserver ses propres réglages Keep a cache of its own, which you can clear Conserver son propre cache, que vous pouvez vider + Run these commands on the document: {ids} Exécuter ces commandes sur le document : {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call « {name} » indique `{id}` dans `commandAllowlist`, qu’un module externe ne peut pas appeler +@msg vc_call `{shown}`: {why} vc_call `{shown}` : {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}` : le `commandAllowlist` du manifeste ne l’indique pas +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}` : l’ID ou les arguments se trouvent hors de la mémoire du module +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}` : l’ID ou les arguments ne sont pas en UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}` : les arguments ne sont pas un objet JSON +@msg only a filter with the usual budget declares `commandAllowlist` seul un filtre au budget habituel déclare `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) appels de commandes ({MAX_CALLS} appels et {MAX_CALL_BYTES} octets par exécution) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) taille d’un appel de commande (vc_call `{shown}` : {len} octets, limite {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` au plus {MAX_ALLOWED_COMMANDS} commandes dans `commandAllowlist` +@msg a plug-in may not call this command un module externe ne peut pas appeler cette commande +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` a besoin de l’autorisation `commands`, et `commands` a besoin d’un `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` indique `{shown}`, qui n’est pas un ID de commande ou figure deux fois Clear Plug-in Cache Vider le cache du module externe @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} l’autorisation `{permission}` nécessite le niveau d’API de module externe {PROGRESS_API} : indiquez `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} le module importe `env.{name}` avec un autre type que celui de l’hôte : celui de l’hôte est {signature} @@ -6020,6 +6074,11 @@ axis Y Axis Axe Y Button Bouton Panel Panneau UI Frames Cadres d’IU + Map Markers Marqueurs de carte + Pin Épingle + Flag Drapeau + Crosshair Réticule + Checkpoint Point de contrôle Open Symbol Library Ouvrir une bibliothèque de symboles Save Symbol Library Enregistrer la bibliothèque de symboles Save Symbol Library… Enregistrer la bibliothèque de symboles… @@ -6074,6 +6133,11 @@ axis Y Axis Axe Y User Brush Library 9 Bibliothèque de formes utilisateur 9 User Brush Library 10 Bibliothèque de formes utilisateur 10 Art Ribbons Rubans d'illustration + Zigzag Zigzag + Burst Ray Rayon d’impact + Dash Trail Traînée tiretée + Speed Line Ligne de vitesse + Game Trails Traînées de jeu Calligraphic Nibs Plumes calligraphiques Pattern Borders Bordures de motif Scatter Shapes Formes de dispersion @@ -6094,6 +6158,8 @@ axis Y Axis Axe Y # Align panel menu › Align to Glyph Bounds (#4231). Point Text Texte de point Area Text Texte captif +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Mesurer le texte d’après les limites du glyphe # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Afficher les options de magnétisme du glyphe Hide Snap to Glyph Options Masquer les options de magnétisme du glyphe @@ -6657,3 +6723,8 @@ breakText Glyphs Glyphes Align to Pixel Grid Aligner sur la grille de pixels @msg only paths and compound paths can be aligned to the pixel grid seuls les tracés et les tracés transparents peuvent être alignés sur la grille de pixels @msg side is left or right, not `{s}` side vaut left ou right, pas `{s}` + Ignore All Tout ignorer + Add to Dictionary Ajouter au dictionnaire + No Suggestions Aucune suggestion + Edit Custom Dictionary Modifier le dictionnaire personnalisé + Entry: Entrée : diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 1dac03decb..3397e7f347 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -394,6 +394,7 @@ antiAlias Sharp शार्प Area / Path Type एरिया / पाथ टाइप Area Graph Tool एरिया ग्राफ़ टूल Area Text एरिया टेक्स्ट + Measure Type by Glyph Bounds टाइप को ग्लिफ़ की सीमाओं से मापें Area Text Objects एरिया टेक्स्ट ऑब्जेक्ट Area Type एरिया टाइप Area Type Options एरिया टाइप ऑप्शन्स @@ -420,6 +421,11 @@ antiAlias Sharp शार्प Art Brush Options आर्ट ब्रश ऑप्शन्स Art Optimized आर्टवर्क के लिए अनुकूलित Art Ribbons आर्ट रिबन + Zigzag ज़िगज़ैग + Burst Ray बर्स्ट रे + Dash Trail डैश ट्रेल + Speed Line स्पीड लाइन + Game Trails गेम ट्रेल्स Art using a deleted global swatch keeps its colour. हटाए गए ग्लोबल स्वॉच वाला आर्टवर्क अपना रंग बनाए रखता है। Artboard आर्टबोर्ड Artboard {n} of {total} {total} में से आर्टबोर्ड {n} @@ -491,7 +497,6 @@ antiAlias Sharp शार्प Back वापस Background Color: बैकग्राउंड रंग: Background Contents बैकग्राउंड सामग्री - Background Contents: बैकग्राउंड सामग्री: Background Level बैकग्राउंड स्तर Background: बैकग्राउंड: Backspace Backspace @@ -514,6 +519,11 @@ antiAlias Sharp शार्प Button बटन Panel पैनल UI Frames UI फ़्रेम + Map Markers मानचित्र चिह्न + Pin पिन + Flag झंडा + Crosshair क्रॉसहेयर + Checkpoint चेकपॉइंट Batch बैच Batch Trace Folder फ़ोल्डर बैच ट्रेस करें Batch… बैच… @@ -897,6 +907,7 @@ antiAlias Sharp शार्प Command कमांड Command Click to Select Objects Behind कमांड पीछे ऑब्जेक्ट्स का सिलेक्ट करने के लिए क्लिक करें Command Dialog कमान डायलॉग + Command API Reference कमांड API संदर्भ Comment not closed टिप्पणी बंद नहीं Commenting, filling in form fields and signing टिप्पणी करना, फॉर्म फ़ील्ड में भरना और हस्ताक्षर करना Commits कमिट्स @@ -1029,7 +1040,6 @@ antiAlias Sharp शार्प Create Clipping Mask क्लिपिंग मास्क बनाएँ Create Compound Path From Ellipses एलिप्स से कंपाउंड पाथ बनाएँ Create Dimension आयाम बनाएँ - Create Document डॉक्यूमेंट बनाएं Create from Guides गाइड से बनाएँ Create from Selection सिलेक्शन से बनाएँ Create From: से बनाएँ: @@ -2555,6 +2565,7 @@ antiAlias Sharp शार्प Lock Artboards लॉक आर्टबोर्ड Lock Grid लॉक ग्रिड Lock Guides गाइड्स लॉक करें + Lock Guides by Default गाइड्स डिफ़ॉल्ट रूप से लॉक करें Lock Others लॉक अन्य Lock Selected लॉक सिलेक्टेड Lock Slices स्लाइस लॉक करें @@ -2836,7 +2847,6 @@ antiAlias Sharp शार्प New Design नई डिजाइन New Document Presets नया डॉक्यूमेंट प्रीसेट New file नई फ़ाइल - New from Template टेम्पलेट से नया New from Template… टेम्पलेट से नया… New Graphic Style नई ग्राफिक स्टाइल New Graphic Style (Alt-click to name it) नया ग्राफ़िक स्टाइल (नाम देने के लिए Alt-क्लिक करें) @@ -3957,6 +3967,7 @@ antiAlias Sharp शार्प Save PDF Preset PDF प्रीसेट सेव करें Save Perspective Grid Preset सेव पर्सपेक्टिव ग्रिड प्रीसेट Save Preset प्रीसेट सेव करें + Save Document Preset डॉक्यूमेंट प्रीसेट सेव करें Save Preset… प्रीसेट सेव करें… Save Print Preset सेव करें प्रिंट प्रीसेट Save Recovery Data रिकवरी डेटा सेव करें @@ -4232,6 +4243,13 @@ antiAlias Sharp शार्प Shading शेडिंग Shadow Intensity शैडो तीव्रता Shadows and Glows छाया और चमक + Game HUD गेम HUD + Health Fill स्वास्थ्य + Mana Glow माना + Damage Flash क्षति + Quest Outline क्वेस्ट + Coin Shine सिक्का + Boss Alert बॉस Shaft: दस्ता: Shape शेप Shape Builder शेप बिल्डर @@ -4736,7 +4754,6 @@ antiAlias Sharp शार्प Template literal not closed टेम्पलेट साक्षर नहीं बंद Templates टेम्पलेट्स Templates Folder टेम्पलेट्स फ़ोल्डर - Templates… टेम्पलेट्स… Tetrad टेट्राड Tetrad 2 टेट्राड 2 Tetrad 3 टेट्राड 3 @@ -5275,6 +5292,20 @@ antiAlias Sharp शार्प Show its progress, see Cancel and write log lines अपनी प्रगति दिखाना, रद्द करने का अनुरोध देखना और लॉग पंक्तियाँ लिखना Keep settings of its own अपनी सेटिंग्स रखना Keep a cache of its own, which you can clear अपना कैश रखना, जिसे आप साफ़ कर सकते हैं + Run these commands on the document: {ids} दस्तावेज़ पर ये कमांड चलाना: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” `commandAllowlist` में `{id}` सूचीबद्ध करता है, जिसे कोई प्लग-इन कॉल नहीं कर सकता +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: मैनिफ़ेस्ट की `commandAllowlist` में यह सूचीबद्ध नहीं है +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: आईडी या आर्ग्युमेंट मॉड्यूल की मेमोरी के बाहर हैं +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: आईडी या आर्ग्युमेंट UTF-8 नहीं हैं +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: आर्ग्युमेंट JSON ऑब्जेक्ट नहीं हैं +@msg only a filter with the usual budget declares `commandAllowlist` केवल सामान्य बजट वाला फ़िल्टर `commandAllowlist` घोषित करता है +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) कमांड कॉल (हर रन में {MAX_CALLS} कॉल और {MAX_CALL_BYTES} बाइट) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) कमांड कॉल का आकार (vc_call `{shown}`: {len} बाइट, सीमा {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist` में अधिकतम {MAX_ALLOWED_COMMANDS} कमांड +@msg a plug-in may not call this command कोई प्लग-इन इस कमांड को कॉल नहीं कर सकता +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` को `commands` अनुमति चाहिए, और `commands` को `commandAllowlist` चाहिए +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` में `{shown}` है, जो कमांड आईडी नहीं है या दो बार सूचीबद्ध है Clear Plug-in Cache प्लग-इन कैश साफ़ करें @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} अनुमति `{permission}` के लिए प्लग-इन API स्तर {PROGRESS_API} चाहिए: `api` {PROGRESS_API} दें @msg the module imports `env.{name}` with another type than the host's: it is {signature} मॉड्यूल `env.{name}` को होस्ट से अलग प्रकार के साथ आयात करता है: होस्ट का प्रकार {signature} है @@ -5400,7 +5431,8 @@ antiAlias Sharp शार्प @msg {key} must name a registered panel {key} एक पंजीकृत पैनल का नाम होना चाहिए @msg {kind} files have no transparency, and the file would have {what}: flatten it first (object.flattenTransparency) {kind} फ़ाइलों में पारदर्शिता नहीं होती और इस फ़ाइल में {what} होगा: पहले इसे फ़्लैट करें (object.flattenTransparency) @msg {kind} images can't be opened (see document.formats) {kind} इमेज ओपन नहीं हो सकतीं (document.formats देखें) -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} वर्तमान में एक पाथ या यौगिक पाथ की आवश्यकता होती है। पहले पाथ के लिए प्रकार, इमेज और समूहों को परिवर्तित करें। +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} के लिए वर्तमान में एक पाथ, यौगिक पाथ, टाइप, समूह, ब्लेंड या सिंबल इंस्टेंस आवश्यक है। पहले अन्य ऑब्जेक्ट को एक्सपैंड करें। +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} इमेज से ठोस नहीं बना सकता: पहले ऑब्जेक्ट › इमेज ट्रेस › बनाएँ से उसे ट्रेस करें। @msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} डॉक्यूमेंट के {n} आर्टबोर्ड में से 1 रखता है: फ़ाइल एक के साथ फिर से खुलती है। उन्हें रखने के लिए संरक्षित संपादन क्षमताओं को चालू करें। @msg {label} must be a number {label} एक नंबर होना चाहिए @msg {label} must be a number above 0 and at most {max} {label} 0 से ऊपर और सबसे {max} पर होना चाहिए @@ -6129,6 +6161,28 @@ antiAlias Sharp शार्प @msg control must be fillStroke, coloring, drawMode or screenMode control को fillStroke, coloring, drawMode या screenMode होना चाहिए @msg Convert to Artboards: selection has no area आर्टबोर्ड में कनवर्ट करें: सिलेक्शन में कोई क्षेत्र नहीं है @msg Convert to Shape: no rectangles or ellipses selected आकार में कनवर्ट करें: कोई आयत या अंडाकार सिलेक्शन नहीं + Run चलाएँ + Run Script स्क्रिप्ट चलाएँ + Stop Script स्क्रिप्ट रोकें + Show External Script Warning बाहरी स्क्रिप्ट की चेतावनी दिखाएँ + A Script Is Running एक स्क्रिप्ट चल रही है + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. स्क्रिप्ट खुले दस्तावेज़ बदल सकती है और अपने चलाए कमांड से फ़ाइलें लिख सकती है। केवल भरोसेमंद स्क्रिप्ट चलाएँ। + Do not show this warning again यह चेतावनी फिर न दिखाएँ + Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें। + This script has added a great many objects. Continue, or stop it and undo what it did? इस स्क्रिप्ट ने बहुत सारे ऑब्जेक्ट जोड़े हैं। जारी रखें, या इसे रोककर इसके बदलाव पूर्ववत करें? +@msg Choose a .js or .jsx script .js या .jsx स्क्रिप्ट चुनें +@msg Ran {name} {name} चलाई गई +@msg The script was stopped and its changes were undone स्क्रिप्ट रोकी गई और उसके बदलाव पूर्ववत किए गए +@msg a script is running: stop it or wait for it to finish एक स्क्रिप्ट चल रही है: उसे रोकें या पूरा होने की प्रतीक्षा करें +@msg this is a compiled script, which cannot be run; use its source text यह कंपाइल की हुई स्क्रिप्ट है, जिसे चलाया नहीं जा सकता; इसका स्रोत पाठ इस्तेमाल करें +@msg the script is not UTF-8 text स्क्रिप्ट UTF-8 पाठ नहीं है +@msg the script is too large to run स्क्रिप्ट चलाने के लिए बहुत बड़ी है +@msg a drag or an undo group is open; finish it before running a script कोई ड्रैग या पूर्ववत समूह खुला है; स्क्रिप्ट चलाने से पहले उसे पूरा करें +@msg the script left a document that cannot be kept स्क्रिप्ट ने ऐसा दस्तावेज़ छोड़ा है जिसे रखा नहीं जा सकता +@msg the script's run is no longer available स्क्रिप्ट का रन अब उपलब्ध नहीं है +@msg a failed command changed undo steps that could not be put back, so the script was stopped एक विफल कमांड ने पूर्ववत चरण बदल दिए जिन्हें वापस नहीं रखा जा सका, इसलिए स्क्रिप्ट रोक दी गई +@msg a recovery copy could not be written, so the script was not run रिकवरी प्रति नहीं लिखी जा सकी, इसलिए स्क्रिप्ट नहीं चलाई गई +@msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट @msg copy needs path: the file to copy into the document's folder copy: प्रतिलिपि की जरूरत है पाथ: फ़ाइल को डॉक्यूमेंट के फ़ोल्डर में कॉपी करने के लिए @msg copy takes images only: relink placed documents where their files are copy: प्रतिलिपि केवल इमेज को लेती है: डॉक्यूमेंट्स को फिर से लिंक करें जहां उनकी फ़ाइलें हैं @@ -6454,6 +6508,11 @@ antiAlias Sharp शार्प @msg invalid parameters for `{cmd}`: {msg} `{cmd}` के लिए अमान्य पैरामीटर: {msg} @msg invalid pattern tile choice अमान्य पैटर्न टाइल ऑप्शन @msg invalid PDF setting: {0} Invalid PDF सेटिंग: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller आर्टबोर्ड {n} का पेज {size} है, जो PDF की 14,400 pt (200 in) की पेज सीमा से लंबा है: इसे {unit} के UserUnit के साथ लिखा जाता है, इसलिए UserUnit को अनदेखा करने वाले ऐप इसे उतने गुना छोटा दिखाते हैं +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in आर्टबोर्ड {n} का पेज {size} है, जो PDF की 14,400 pt (200 in) की पेज सीमा से लंबा है: {label} पेज बिना UserUnit के, पॉइंट में लिखे जाते हैं, और सीमा मानने वाले ऐप पेज को 200 in पर काट देते हैं +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 में UserUnit नहीं है, जिसकी 14,400 pt (200 in) से लंबे पेज को अपना आकार बनाए रखने के लिए ज़रूरत होती है: फ़ाइल PDF 1.6 के रूप में लिखी जाती है +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units आर्टबोर्ड {n} का पेज {size} है, जो PDF की 3 से 14,400 इकाई की पेज भुजाओं के लिए बहुत लंबा और संकरा है: इसे {unit} की UserUnit के साथ लिखा जाता है, जो छोटी भुजा को 3 इकाई या अधिक पर रखती है, और सीमा का पालन करने वाले ऐप लंबी भुजा को 14,400 इकाई पर काट देते हैं +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} फ़ाइलें {max} तक की वास्तविक संख्याएँ रखती हैं, और आर्टबोर्ड {n} का {side} pt लंबा पेज इससे बड़ी संख्याएँ माँगता है: बिना PDF/X मानक के PDF 1.6 या बाद का चुनें, या छोटा आर्टबोर्ड @msg invalid point अमानवीय बिंदु @msg Invalid point अमानवीय बिंदु @msg Invalid real scale अमानवीय वास्तविक पैमाने @@ -7387,6 +7446,7 @@ antiAlias Sharp शार्प @msg the action has no steps कार्रवाई में कोई कदम नहीं है @msg the action set file holds more than 1,000 actions एक्शन सेट फ़ाइल 1,000 से अधिक कार्यों को रखती है @msg the action set file is larger than 8 MiB एक्शन सेट फ़ाइल 8 MiB से बड़ा है +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: संदर्भ {MAX_BYTES} बाइट से बड़ा होगा @msg the action set file needs a later version of VectorCraft एक्शन सेट फ़ाइल को वेक्टर क्रेफ्ट के बाद के संस्करण की आवश्यकता होती है @msg the action set ids are not a list कार्रवाई सेट ids एक सूची नहीं हैं @msg the action sets changed; nothing was deleted कार्रवाई सेट बदल गया; कुछ भी नहीं हटा दिया गया था @@ -7794,6 +7854,11 @@ antiAlias Sharp शार्प @msg unknown parameter `{key}`; did you mean `{near}`? अज्ञात पैरामीटर `{key}`; क्या आपको `{near}` का मतलब है? @msg unknown parameter `{key}`; the command takes no parameters अज्ञात पैरामीटर `{key}`; कमांड कोई पैरामीटर नहीं लेता है @msg unknown parameter `{key}`; the command takes: {keys} अज्ञात पैरामीटर `{key}`; कमांड लेता है: {keys} +@msg the params must be an object, not {got} पैरामीटर एक ऑब्जेक्ट होने चाहिए, {got} नहीं +@msg unknown parameter `{path}`; the object takes no keys अज्ञात पैरामीटर `{path}`; ऑब्जेक्ट कोई कुंजी नहीं लेता +@msg unknown parameter `{path}`; it takes: {keys} अज्ञात पैरामीटर `{path}`; यह लेता है: {keys} +@msg missing `{path}` लापता `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` {expected} होना चाहिए, {got} नहीं @msg unknown PDF preset `{name}` (presets: {_1}) अज्ञात PDF प्रीसेट `{name}` (presets: {_1}) @msg unknown pieLegend `{v}` (none, standard or wedges) अज्ञात pieLegend `{v}` (one, मानक या wedges) @msg unknown piePosition `{v}` (even, ratio or stacked) अज्ञात piePosition `{v}` (यहां तक कि अनुपात या स्टैक्ड) @@ -8104,3 +8169,8 @@ theme Appearance अपीयरेंस @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` इंपोर्टर 1 से {MAX_EXTENSIONS} `extensions` घोषित करता है @msg an importer always gets an import's budget: leave `budget` out इंपोर्टर को हमेशा इंपोर्ट का बजट मिलता है: `budget` छोड़ दें @msg side is left or right, not `{s}` side left या right होना चाहिए, `{s}` नहीं + Ignore All सभी को अनदेखा करें + Add to Dictionary शब्दकोश में जोड़ें + No Suggestions कोई सुझाव नहीं + Edit Custom Dictionary कस्टम शब्दकोश संपादित करें + Entry: प्रविष्टि: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87842df37e..4b813215e0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -393,7 +393,6 @@ font-technology Variable Változó Update While Dragging Frissítés húzás közben Hide Video Rulers Videovonalzók elrejtése Background Contents Háttértartalom - Background Contents: Háttértartalom: Background: Háttér: Backspace Backspace Balance Egyensúly @@ -761,6 +760,7 @@ font-technology Variable Változó Command Parancs Command Click to Select Objects Behind Cmd+kattintás a mögöttes objektumok kijelöléséhez Command Dialog Parancs párbeszédablaka + Command API Reference Parancsok API-referenciája Commenting, filling in form fields and signing Megjegyzések, űrlapmezők kitöltése és aláírás Commits Commitok Community Közösség @@ -864,7 +864,6 @@ font-technology Variable Változó Craquelure… Repedezettség… Create Létrehozás Create Clipping Mask Vágómaszk létrehozása - Create Document Dokumentum létrehozása Create from Guides Létrehozás segédvonalakból Create from Selection Létrehozás a kijelölésből Create From: Létrehozás ebből: @@ -2377,6 +2376,7 @@ file-filter Templates Sablonok Lock (⌘2) Zárolás (⌘2) Lock Grid Rács zárolása Lock Guides Segédvonalak zárolása + Lock Guides by Default Segédvonalak zárolása alapértelmezetten Lock Others Többi zárolása Lock Slices Szeletek zárolása Lock Station Point Nézőpont zárolása @@ -2598,7 +2598,6 @@ file-filter Templates Sablonok New Data Set… Új adatkészlet… New Document Presets Új dokumentum előbeállításai New file Új fájl - New from Template Új sablonból New from Template… Új sablonból… New Graphic Style Új grafikai stílus New Graphic Style (Alt-click to name it) Új grafikai stílus (Alt+kattintás: elnevezéssel) @@ -3516,6 +3515,7 @@ mark-style Japanese Japán Save PDF Preset PDF-előbeállítás mentése Save Perspective Grid Preset Perspektivikus rács előbeállításának mentése Save Preset Előbeállítás mentése + Save Document Preset Dokumentum-előbeállítás mentése Preset {number} Előbeállítás {number} Save Preset… Előbeállítás mentése… Save Print Preset Nyomtatási előbeállítás mentése @@ -3753,6 +3753,13 @@ mark-style Japanese Japán Shades of Gray Szürkeárnyalatok Shading Árnyékolás Shadows and Glows Árnyékok és ragyogások + Game HUD Játék HUD + Health Fill Életerő + Mana Glow Mana + Damage Flash Sebzés + Quest Outline Küldetés + Coin Shine Érme + Boss Alert Főellenség Shape Alakzat Shape Builder Alakzatépítő Shape Builder Regions Alakzatépítő területei @@ -4164,7 +4171,6 @@ mark-style Japanese Japán Template Sablon Templates Sablonok Templates Folder Sablonok mappája - Templates… Sablonok… Tetrad Tetrád Tetrad 2 Tetrád 2 Tetrad 3 Tetrád 3 @@ -4863,6 +4869,28 @@ imageTrace Outline Körvonal @msg compressed (RLE) bitmaps can't be read yet a tömörített (RLE) bitképek még nem olvashatók @msg Convert to Artboards: selection has no area Átalakítás rajztáblákká: a kijelölésnek nincs területe @msg Convert to Shape: no rectangles or ellipses selected Átalakítás alakzattá: nincs kijelölt téglalap vagy ellipszis + Run Futtatás + Run Script Parancsfájl futtatása + Stop Script Parancsfájl leállítása + Show External Script Warning Figyelmeztetés külső parancsfájlok előtt + A Script Is Running Egy parancsfájl fut + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. A parancsfájl módosíthatja a megnyitott dokumentumokat, és a futtatott parancsokkal fájlokat írhat. Csak megbízható parancsfájlokat futtasson. + Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés + Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra. + This script has added a great many objects. Continue, or stop it and undo what it did? Ez a parancsfájl nagyon sok objektumot adott hozzá. Folytatja, vagy leállítja és visszavonja a módosításait? +@msg Choose a .js or .jsx script Válasszon .js vagy .jsx parancsfájlt +@msg Ran {name} Lefutott: {name} +@msg The script was stopped and its changes were undone A parancsfájl leállt, a módosításai visszavonva +@msg a script is running: stop it or wait for it to finish egy parancsfájl fut: állítsa le, vagy várja meg, hogy befejeződjön +@msg this is a compiled script, which cannot be run; use its source text ez lefordított parancsfájl, amely nem futtatható; használja a forrásszövegét +@msg the script is not UTF-8 text a parancsfájl nem UTF-8 szöveg +@msg the script is too large to run a parancsfájl túl nagy a futtatáshoz +@msg a drag or an undo group is open; finish it before running a script húzás vagy visszavonási csoport van folyamatban; fejezze be a parancsfájl futtatása előtt +@msg the script left a document that cannot be kept a parancsfájl olyan dokumentumot hagyott hátra, amely nem tartható meg +@msg the script's run is no longer available a parancsfájl futása már nem érhető el +@msg a failed command changed undo steps that could not be put back, so the script was stopped egy sikertelen parancs olyan visszavonási lépéseket módosított, amelyeket nem lehetett visszaállítani, ezért a parancsfájl leállt +@msg a recovery copy could not be written, so the script was not run a helyreállítási másolatot nem sikerült kiírni, ezért a parancsfájl nem futott le +@msg Running a script Parancsfájl futtatása @msg Copied the script report Szkriptjelentés másolva @msg Corners edits the corners of a path a Sarkok parancs egy útvonal sarkait szerkeszti @msg could not decode image: {0} a kép nem dekódolható: {0} @@ -4949,6 +4977,11 @@ imageTrace Outline Körvonal @msg Invalid panel layout; restored the default dock Érvénytelen panelelrendezés; az alapértelmezett dokk visszaállítva @msg invalid parameters for `{cmd}`: {msg} érvénytelen paraméterek (`{cmd}`): {msg} @msg invalid PDF setting: {0} érvénytelen PDF-beállítás: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller a(z) {n}. rajztábla oldala {size}, hosszabb a PDF 14 400 pt-os (200 in) oldalkorlátjánál: {unit} UserUnit értékkel íródik, így a UserUnit-ot figyelmen kívül hagyó alkalmazások ennyiszer kisebbnek mutatják +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in a(z) {n}. rajztábla oldala {size}, hosszabb a PDF 14 400 pt-os (200 in) oldalkorlátjánál: a(z) {label} oldalak UserUnit nélkül, pontokban íródnak, és a korlátot betartó alkalmazások 200 in-re vágják az oldalt +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 a PDF 1.5-ben nincs UserUnit, amelyre egy 14 400 pt-nál (200 in) hosszabb oldalnak szüksége van a mérete megtartásához: a fájl PDF 1.6-ként íródik +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units a(z) {n}. rajztábla oldala {size}, túl hosszú és keskeny a PDF 3 és 14 400 egység közötti oldalaihoz: {unit} UserUnit értékkel íródik, amely a rövid oldalt legalább 3 egységen tartja, és a korlátot betartó alkalmazások a hosszú oldalt 14 400 egységre vágják +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard a(z) {label} fájlok legfeljebb {max} értékű valós számokat tárolnak, a(z) {n}. rajztábla {side} pt hosszú oldalához pedig nagyobbak kellenek: válassza a PDF 1.6-os vagy újabb verziót PDF/X szabvány nélkül, vagy egy kisebb rajztáblát @msg invalid restored panel group érvénytelen visszaállított panelcsoport @msg is not an image VectorCraft reads nem olyan kép, amelyet a VectorCraft olvas @msg it ends inside a group or compound path egy csoporton vagy összetett útvonalon belül ér véget @@ -5097,6 +5130,7 @@ imageTrace Outline Körvonal @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out „{name}” betöltve; kihagyott lépések: {n} @msg not an action set file nem műveletkészlet-fájl @msg the action set file is larger than 8 MiB a műveletkészlet-fájl nagyobb 8 MiB-nál +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: a referencia nagyobb lenne {MAX_BYTES} bájtnál @msg the action set file holds more than 1,000 actions a műveletkészlet-fájl több mint 1000 műveletet tartalmaz @msg the action set file needs a later version of VectorCraft a műveletkészlet-fájlhoz a VectorCraft újabb verziója kell @msg an action in the action set file has more than 10,000 steps a műveletkészlet-fájl egyik műveletében több mint 10 000 lépés van @@ -5570,7 +5604,8 @@ imageTrace Outline Körvonal Bevel both sides Élletörés mindkét oldalon Presets Készletek @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Egy objektumnak csak egy 3D effektusa lehet. Szerkessze a meglévő effektus beállításait, vagy előbb távolítsa el. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} egyelőre görbét vagy összetett görbét igényel. Előbb alakítsa görbévé a szöveget, a képeket és a csoportokat. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} egyelőre görbét, összetett görbét, szöveget, csoportot, összemosást vagy szimbólumpéldányt igényel. Előbb bontsa ki az egyéb objektumokat. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} képből nem tud testet létrehozni: előbb vektorizálja az Objektum › Képvektorizálás › Létrehozás paranccsal. @msg {label} requires a shape with at least two anchors {label} legalább két szerkesztőpontos alakzatot igényel @msg The shape is too complex for a 3D effect Az alakzat túl összetett a 3D effektushoz @msg The 3D surface is too complex; simplify the shape A 3D felület túl összetett; egyszerűsítse az alakzatot @@ -5578,6 +5613,11 @@ imageTrace Outline Körvonal @msg unknown parameter `{key}`; did you mean `{near}`? ismeretlen paraméter: `{key}`; erre gondolt: `{near}`? @msg unknown parameter `{key}`; the command takes no parameters ismeretlen paraméter: `{key}`; a parancsnak nincs paramétere @msg unknown parameter `{key}`; the command takes: {keys} ismeretlen paraméter: `{key}`; a parancs ezeket fogadja el: {keys} +@msg the params must be an object, not {got} a paramétereknek objektumnak kell lenniük, nem ez: {got} +@msg unknown parameter `{path}`; the object takes no keys ismeretlen paraméter: `{path}`; az objektum nem fogad el kulcsokat +@msg unknown parameter `{path}`; it takes: {keys} ismeretlen paraméter: `{path}`; ezeket fogadja el: {keys} +@msg missing `{path}` hiányzik: `{path}` +@msg `{path}` must be {expected}, not {got} `{path}`: {expected} kell, nem ez: {got} Load EPS into Clipboard EPS betöltése a vágólapra @msg an image of {w} × {h} pixels is too large to draw egy {w} × {h} pixeles kép túl nagy a kirajzoláshoz @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: nem PNG, JPEG, WebP, TIFF vagy BMP kép @@ -5919,6 +5959,20 @@ axis Y Axis Y tengely Show its progress, see Cancel and write log lines Megjelenítheti az előrehaladását, észlelheti a megszakítást és naplósorokat írhat Keep settings of its own Saját beállításokat tárolhat Keep a cache of its own, which you can clear Saját gyorsítótárat tárolhat, amelyet Ön kiüríthet + Run these commands on the document: {ids} Ezeket a parancsokat futtathatja a dokumentumon: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call a(z) „{name}” a(z) `{id}` parancsot sorolja fel a `commandAllowlist` listában, amelyet bővítmény nem hívhat meg +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: a jegyzék `commandAllowlist` listája nem sorolja fel +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: az azonosító vagy az argumentumok a modul memóriáján kívül esnek +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: az azonosító vagy az argumentumok nem UTF-8 kódolásúak +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: az argumentumok nem JSON-objektumot alkotnak +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` listát csak a szokásos keretű szűrő adhat meg +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) parancshívások (futásonként {MAX_CALLS} hívás és {MAX_CALL_BYTES} bájt) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) parancshívás mérete (vc_call `{shown}`: {len} bájt, korlát {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` legfeljebb {MAX_ALLOWED_COMMANDS} parancs a `commandAllowlist` listában +@msg a plug-in may not call this command bővítmény nem hívhatja meg ezt a parancsot +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` a `commandAllowlist` listához a `commands` engedély szükséges, a `commands` engedélyhez pedig `commandAllowlist` lista +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice a `commandAllowlist` a(z) `{shown}` elemet nevezi meg, amely nem parancsazonosító, vagy kétszer szerepel Clear Plug-in Cache Bővítmény gyorsítótárának kiürítése @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} a(z) `{permission}` engedélyhez {PROGRESS_API}. szintű bővítmény-API kell: adja meg az `api` {PROGRESS_API} értéket @msg the module imports `env.{name}` with another type than the host's: it is {signature} a modul az `env.{name}` elemet a gazdaprogramétól eltérő típussal importálja: a gazdaprogram típusa {signature} @@ -6008,6 +6062,11 @@ axis Y Axis Y tengely Button Gomb Panel Panel UI Frames UI keretek + Map Markers Térképjelölők + Pin Gombostű + Flag Zászló + Crosshair Célkereszt + Checkpoint Ellenőrzőpont Open Symbol Library Szimbólumkönyvtár megnyitása Save Symbol Library Szimbólumkönyvtár mentése Save Symbol Library… Szimbólumkönyvtár mentése… @@ -6062,6 +6121,11 @@ axis Y Axis Y tengely User Brush Library 9 Felhasználói ecsetkönyvtár 9 User Brush Library 10 Felhasználói ecsetkönyvtár 10 Art Ribbons Grafikus szalagok + Zigzag Cikkcakk + Burst Ray Ütéssugár + Dash Trail Szaggatott nyom + Speed Line Sebességvonal + Game Trails Játéknyomok Calligraphic Nibs Kalligrafikus tollhegyek Pattern Borders Mintázatszegélyek Scatter Shapes Szórt alakzatok @@ -6082,6 +6146,8 @@ axis Y Axis Y tengely # Align panel menu › Align to Glyph Bounds (#4231). Point Text Pontszöveg Area Text Területszöveg +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Szöveg mérése a glifahatárok szerint # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Glifához illesztés beállításainak megjelenítése Hide Snap to Glyph Options Glifához illesztés beállításainak elrejtése @@ -6646,3 +6712,8 @@ breakText Glyphs Glifák Align to Pixel Grid Igazítás a pixelrácshoz @msg only paths and compound paths can be aligned to the pixel grid csak útvonalak és összetett útvonalak igazíthatók a pixelrácshoz @msg side is left or right, not `{s}` a side értéke left vagy right lehet, nem `{s}` + Ignore All Az összes kihagyása + Add to Dictionary Hozzáadás a szótárhoz + No Suggestions Nincs javaslat + Edit Custom Dictionary Egyéni szótár szerkesztése + Entry: Bejegyzés: diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 476a6988f5..33d229c85a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -559,6 +559,7 @@ Hide Guides Sembunyikan panduan Show Guides Tampilkan panduan Lock Guides Kunci panduan + Lock Guides by Default Kunci panduan secara default Unlock Guides Buka kunci panduan Make Guides Buat panduan Release Guides Lepaskan panduan @@ -711,6 +712,13 @@ Other Library… Pustaka lain… Graphic Style Libraries Pustaka gaya grafis Shadows and Glows Bayangan dan pendar + Game HUD HUD Game + Health Fill Nyawa + Mana Glow Mana + Damage Flash Damage + Quest Outline Quest + Coin Shine Koin + Boss Alert Boss Outlines and Rules Garis luar dan garis Hand-Drawn Gambar tangan Gradient Finishes Finishing gradien @@ -905,6 +913,7 @@ lighting Light Cahaya Color Picker… Pemilih warna… Coming soon — tracked in the parity plan Segera hadir — dilacak dalam rencana paritas Command Dialog Dialog perintah + Command API Reference Referensi API perintah Copy Selected Style Salin gaya terpilih Corners… Sudut… Define Perspective Grid… Definisikan kisi perspektif… @@ -2350,15 +2359,12 @@ digits Malayalam Malayalam Selected Swatches Swatch terpilih Advanced Options Opsi lanjutan Background Contents Konten latar belakang - Background Contents: Konten latar belakang: BLANK DOCUMENT PRESETS PRESET DOKUMEN KOSONG Bleed Bleed Change to Right-to-Left Layout Ubah ke tata letak kanan ke kiri Columns: Kolom: - Create Document Buat dokumen Documents you create appear here. Dokumen yang Anda buat muncul di sini. More Settings Pengaturan lainnya - New from Template Baru dari templat Number of Artboards: Jumlah artboard: Orientation: Orientasi: PRESET DETAILS DETAIL PRESET @@ -2369,7 +2375,6 @@ digits Malayalam Malayalam RECENT TERKINI RECENT (1) TERKINI (1) SAVED TERSIMPAN - Templates… Templat… Transparent (Default) Transparan (default) Save for Office Documents Simpan untuk dokumen Office Transparent Background Latar belakang transparan @@ -3273,6 +3278,7 @@ theme Appearance Tampilan Arrange by Row Susun per baris Arrange by Column Susun per kolom Save Preset Simpan preset + Save Document Preset Simpan preset dokumen Screen (72 ppi) Layar (72 ppi) Social Square Post 1080×1080 Postingan persegi media sosial 1080×1080 Distribute Distribusikan @@ -4074,6 +4080,15 @@ imageTrace Outline Kontur @msg Combine Slices: the slices have no bounds Gabungkan irisan: irisan tidak memiliki batas @msg Convert to Artboards: selection has no area Konversi ke artboard: seleksi tidak memiliki area @msg Convert to Shape: no rectangles or ellipses selected Konversi ke bentuk: tidak ada persegi panjang atau elips yang dipilih + Run Jalankan + Run Script Jalankan Skrip + Stop Script Hentikan Skrip + Show External Script Warning Tampilkan Peringatan Skrip Eksternal + A Script Is Running Skrip Sedang Berjalan + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrip dapat mengubah dokumen yang terbuka dan menulis file melalui perintah yang dijalankannya. Jalankan hanya skrip yang Anda percayai. + Do not show this warning again Jangan tampilkan peringatan ini lagi + Stop the script and undo what it did? Then quit again. Hentikan skrip dan batalkan yang telah dilakukannya? Lalu keluar lagi. + This script has added a great many objects. Continue, or stop it and undo what it did? Skrip ini telah menambahkan sangat banyak objek. Lanjutkan, atau hentikan dan batalkan yang telah dilakukannya? @msg Copied the script report Berhasil menyalin laporan skrip @msg Corners edits the corners of a path Corners menyunting sudut jalur @msg Couldn't copy to the system clipboard: {e} Tidak dapat menyalin ke papan klip sistem: {e} @@ -5142,7 +5157,8 @@ mark-style Japanese Jepang Bevel both sides Bevel di kedua sisi Presets Preset @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Sebuah objek hanya menerima satu efek 3D. Edit opsi efek yang sudah ada, atau hapus dulu efek tersebut. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} saat ini memerlukan jalur atau jalur majemuk. Konversikan dulu teks, gambar, dan grup menjadi jalur. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} saat ini memerlukan jalur, jalur majemuk, teks, grup, blend, atau instans simbol. Perluas dulu objek lainnya. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} tidak dapat membuat benda padat dari gambar: lacak dulu dengan Objek › Image Trace › Buat. @msg {label} requires a shape with at least two anchors {label} memerlukan bentuk dengan setidaknya dua jangkar @msg The shape is too complex for a 3D effect Bentuknya terlalu kompleks untuk efek 3D @msg The 3D surface is too complex; simplify the shape Permukaan 3D terlalu kompleks; sederhanakan bentuknya @@ -5802,6 +5818,7 @@ axis Y Axis Sumbu Y Show its progress, see Cancel and write log lines Menampilkan kemajuannya, mengenali pembatalan, dan menulis baris log Keep settings of its own Menyimpan pengaturannya sendiri Keep a cache of its own, which you can clear Menyimpan cache-nya sendiri, yang dapat Anda kosongkan + Run these commands on the document: {ids} Menjalankan perintah ini pada dokumen: {ids} Clear Plug-in Cache Kosongkan cache plug-in # Actions panel: action sets (#3712). New Set… Set baru… @@ -5851,6 +5868,11 @@ axis Y Axis Sumbu Y Button Tombol Panel Panel UI Frames Bingkai UI + Map Markers Penanda Peta + Pin Pin + Flag Bendera + Crosshair Bidik silang + Checkpoint Pos pemeriksaan Open Symbol Library Buka pustaka simbol Save Symbol Library Simpan pustaka simbol Save Symbol Library… Simpan pustaka simbol… @@ -5899,6 +5921,11 @@ axis Y Axis Sumbu Y User Brush Library 9 Pustaka kuas pengguna 9 User Brush Library 10 Pustaka kuas pengguna 10 Art Ribbons Pita seni + Zigzag Zigzag + Burst Ray Sinar ledakan + Dash Trail Jejak putus-putus + Speed Line Garis kecepatan + Game Trails Jejak game Calligraphic Nibs Pena kaligrafi Pattern Borders Bingkai pola Scatter Shapes Bentuk sebar @@ -5911,6 +5938,8 @@ axis Y Axis Sumbu Y # Align panel menu › Align to Glyph Bounds (#4231). Point Text Teks titik Area Text Teks area +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Ukur teks menurut batas glif # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Tampilkan opsi snap ke glif Hide Snap to Glyph Options Sembunyikan opsi snap ke glif @@ -6444,3 +6473,5 @@ breakText Glyphs Glif # Align to Pixel Grid Align to Pixel Grid Sejajarkan ke grid piksel @msg side is left or right, not `{s}` side adalah left atau right, bukan `{s}` + Edit Custom Dictionary Edit kamus kustom + Entry: Entri: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f10e1f272e..b5fd752e9b 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -297,7 +297,6 @@ font-technology Variable Variabili Update While Dragging Aggiorna durante il trascinamento Hide Video Rulers Nascondi righelli video Background Contents Contenuto sfondo - Background Contents: Contenuto sfondo: Background: Sfondo: Backspace Backspace Bar Graph Tool Strumento Grafico a barre @@ -583,6 +582,7 @@ font-technology Variable Variabili Coming soon — tracked in the parity plan Prossimamente — previsto nel piano di parità Command Click to Select Objects Behind Cmd+clic per selezionare gli oggetti retrostanti Command Dialog Finestra dei comandi + Command API Reference Riferimento API dei comandi Community Comunità Compatibility: Compatibilità: Compatible Gradient and Gradient Mesh Printing Stampa compatibile di sfumature e trame sfumatura @@ -669,7 +669,6 @@ font-technology Variable Variabili Couldn't {} {name}: {e} Impossibile {} {name}: {e} Create Crea Create Clipping Mask Crea maschera di ritaglio - Create Document Crea documento Create from Guides Crea da guide Create from Selection Crea dalla selezione Create From: Crea da: @@ -1925,6 +1924,7 @@ file-filter Templates Modelli Lock (⌘2) Blocca (⌘2) Lock Grid Blocca griglia Lock Guides Blocca guide + Lock Guides by Default Blocca guide per impostazione predefinita Lock Others Blocca altri Lock Slices Blocca sezioni Lock Station Point Blocca punto di osservazione @@ -2175,7 +2175,6 @@ file-filter Templates Modelli New Color Group… Nuovo gruppo colori… New Document Presets Preset nuovo documento New file Nuovo file - New from Template Nuovo da modello New from Template… Nuovo da modello… New Graphic Style Nuovo stile grafico New Graphic Style (Alt-click to name it) Nuovo stile grafico (Alt+clic per assegnare un nome) @@ -2967,6 +2966,7 @@ digits Malayalam Malayalam Save PDF Preset Salva preset PDF Save Perspective Grid Preset Salva preset griglia prospettica Save Preset Salva preset + Save Document Preset Salva preset documento Preset {number} Preset {number} Save Preset… Salva preset… Save Print Preset Salva preset di stampa @@ -3175,6 +3175,13 @@ digits Malayalam Malayalam Settings… Impostazioni… Setup… Configurazione… Shadows and Glows Ombre e bagliori + Game HUD HUD di gioco + Health Fill Salute + Mana Glow Mana + Damage Flash Danno + Quest Outline Missione + Coin Shine Moneta + Boss Alert Boss Shape Forma Shape Builder Generatore forme Shape Builder Regions Aree del Generatore forme @@ -3546,7 +3553,6 @@ digits Malayalam Malayalam Template Modello Templates Modelli Templates Folder Cartella modelli - Templates… Modelli… Text Displayed in Cell: Testo visualizzato nella cella: Text Export Options Opzioni di esportazione testo Text Fill & Stroke Color Colore riempimento e traccia testo @@ -4110,6 +4116,28 @@ axis Both Entrambi @msg Combine Slices: the slices have no bounds Combina sezioni: le sezioni non hanno limiti @msg Convert to Artboards: selection has no area Converti in tavole da disegno: la selezione non ha area @msg Convert to Shape: no rectangles or ellipses selected Converti in forma: nessun rettangolo o ellisse selezionato + Run Esegui + Run Script Esegui script + Stop Script Interrompi script + Show External Script Warning Mostra avviso per gli script esterni + A Script Is Running È in esecuzione uno script + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Uno script può modificare i documenti aperti e scrivere file tramite i comandi che esegue. Esegui solo script di cui ti fidi. + Do not show this warning again Non mostrare più questo avviso + Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo. + This script has added a great many objects. Continue, or stop it and undo what it did? Questo script ha aggiunto moltissimi oggetti. Continuare, oppure interromperlo e annullare ciò che ha fatto? +@msg Choose a .js or .jsx script Scegli uno script .js o .jsx +@msg Ran {name} {name} eseguito +@msg The script was stopped and its changes were undone Lo script è stato interrotto e le sue modifiche sono state annullate +@msg a script is running: stop it or wait for it to finish è in esecuzione uno script: interrompilo o attendi che finisca +@msg this is a compiled script, which cannot be run; use its source text questo è uno script compilato, che non può essere eseguito; usa il suo testo sorgente +@msg the script is not UTF-8 text lo script non è testo UTF-8 +@msg the script is too large to run lo script è troppo grande per essere eseguito +@msg a drag or an undo group is open; finish it before running a script è aperto un trascinamento o un gruppo di annullamento; completalo prima di eseguire uno script +@msg the script left a document that cannot be kept lo script ha lasciato un documento che non può essere conservato +@msg the script's run is no longer available l'esecuzione dello script non è più disponibile +@msg a failed command changed undo steps that could not be put back, so the script was stopped un comando non riuscito ha modificato passaggi di annullamento che non è stato possibile ripristinare, quindi lo script è stato interrotto +@msg a recovery copy could not be written, so the script was not run non è stato possibile scrivere una copia di recupero, quindi lo script non è stato eseguito +@msg Running a script Esecuzione di uno script @msg Copied the script report Rapporto dello script copiato @msg Corners edits the corners of a path Angoli modifica gli angoli di un tracciato @msg Couldn't copy to the system clipboard: {e} Impossibile copiare negli appunti di sistema: {e} @@ -4353,6 +4381,11 @@ axis Both Entrambi @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) errore interno in `{cmd}`: {msg} (il documento è rimasto com'era; segnala questo bug) @msg internal error: {msg} (please report this bug) errore interno: {msg} (segnala questo bug) @msg invalid PDF setting: {0} impostazione PDF non valida: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la pagina della tavola da disegno {n} misura {size}, più del limite di pagina PDF di 14.400 pt (200 in): viene scritta con una UserUnit di {unit}, quindi le app che ignorano UserUnit la mostrano altrettante volte più piccola +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la pagina della tavola da disegno {n} misura {size}, più del limite di pagina PDF di 14.400 pt (200 in): le pagine {label} vengono scritte senza UserUnit, in punti, e le app che rispettano il limite tagliano la pagina a 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 non ha UserUnit, che serve a una pagina più lunga di 14.400 pt (200 in) per mantenere le sue dimensioni: il file viene scritto come PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la pagina della tavola da disegno {n} misura {size}, troppo lunga e stretta per i lati di pagina PDF da 3 a 14.400 unità: viene scritta con una UserUnit di {unit}, che tiene il lato corto a 3 unità o più, e le app che rispettano il limite tagliano il lato lungo a 14.400 unità +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard i file {label} accettano numeri reali fino a {max}, e la pagina della tavola da disegno {n}, lunga {side} pt, ne richiede di più grandi: scegli PDF 1.6 o successivo senza standard PDF/X, oppure una tavola da disegno più piccola @msg invalid image data for `{0}` dati immagine non validi per `{0}` @msg invalid parameters for `{cmd}`: {msg} parametri non validi per `{cmd}`: {msg} @msg is not an image VectorCraft reads non è un'immagine che VectorCraft sa leggere @@ -4457,6 +4490,7 @@ axis Both Entrambi @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Caricato “{name}”: {n} passaggio è stato omesso|Caricato “{name}”: {n} passaggi sono stati omessi @msg not an action set file non è un file di set di azioni @msg the action set file is larger than 8 MiB il file del set di azioni supera 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: il riferimento supererebbe {MAX_BYTES} byte @msg the action set file holds more than 1,000 actions il file del set di azioni contiene più di 1.000 azioni @msg the action set file needs a later version of VectorCraft il file del set di azioni richiede una versione più recente di VectorCraft @msg an action in the action set file has more than 10,000 steps un’azione nel file del set di azioni ha più di 10.000 passaggi @@ -5196,7 +5230,8 @@ lighting Light Luce Bevel both sides Smusso su entrambi i lati Presets Predefiniti @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Un oggetto può avere un solo effetto 3D. Modificate le opzioni dell'effetto esistente oppure rimuovetelo prima. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} richiede per ora un tracciato o un tracciato composto. Convertite prima testo, immagini e gruppi in tracciati. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} richiede per ora un tracciato, un tracciato composto, testo, un gruppo, una fusione o un'istanza di simbolo. Espandete prima gli altri oggetti. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} non può creare un solido da un'immagine: ricalcatela prima con Oggetto › Ricalco immagine › Crea. @msg {label} requires a shape with at least two anchors {label} richiede una forma con almeno due punti di ancoraggio @msg The shape is too complex for a 3D effect La forma è troppo complessa per un effetto 3D @msg The 3D surface is too complex; simplify the shape La superficie 3D è troppo complessa; semplificate la forma @@ -5204,6 +5239,11 @@ lighting Light Luce @msg unknown parameter `{key}`; did you mean `{near}`? parametro sconosciuto `{key}`; forse intendevate `{near}`? @msg unknown parameter `{key}`; the command takes no parameters parametro sconosciuto `{key}`; il comando non ha parametri @msg unknown parameter `{key}`; the command takes: {keys} parametro sconosciuto `{key}`; il comando accetta: {keys} +@msg the params must be an object, not {got} i parametri devono essere un oggetto, non {got} +@msg unknown parameter `{path}`; the object takes no keys parametro sconosciuto `{path}`; l'oggetto non accetta chiavi +@msg unknown parameter `{path}`; it takes: {keys} parametro sconosciuto `{path}`; accetta: {keys} +@msg missing `{path}` manca `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` deve essere {expected}, non {got} Load EPS into Clipboard Carica EPS negli appunti @msg an image of {w} × {h} pixels is too large to draw un'immagine di {w} × {h} pixel è troppo grande per essere disegnata @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: non è un'immagine PNG, JPEG, WebP, TIFF o BMP @@ -5553,6 +5593,20 @@ axis Y Axis Asse Y Show its progress, see Cancel and write log lines Mostrare il proprio avanzamento, rilevare l’annullamento e scrivere righe di registro Keep settings of its own Conservare impostazioni proprie Keep a cache of its own, which you can clear Conservare una cache propria, che è possibile svuotare + Run these commands on the document: {ids} Eseguire questi comandi sul documento: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” elenca `{id}` in `commandAllowlist`, che un plug-in non può chiamare +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: il `commandAllowlist` del manifesto non lo elenca +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: l’ID o gli argomenti si trovano fuori dalla memoria del modulo +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: l’ID o gli argomenti non sono UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: gli argomenti non sono un oggetto JSON +@msg only a filter with the usual budget declares `commandAllowlist` solo un filtro con il budget consueto dichiara `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) chiamate di comandi ({MAX_CALLS} chiamate e {MAX_CALL_BYTES} byte per esecuzione) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) dimensione di una chiamata di comando (vc_call `{shown}`: {len} byte, limite {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` al massimo {MAX_ALLOWED_COMMANDS} comandi in `commandAllowlist` +@msg a plug-in may not call this command un plug-in non può chiamare questo comando +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` richiede l’autorizzazione `commands`, e `commands` richiede un `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` elenca `{shown}`, che non è un ID di comando o è elencato due volte Clear Plug-in Cache Svuota cache del plug-in @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} l’autorizzazione `{permission}` richiede il livello API dei plug-in {PROGRESS_API}: indicare `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} il modulo importa `env.{name}` con un tipo diverso da quello dell’host: quello dell’host è {signature} @@ -5642,6 +5696,11 @@ axis Y Axis Asse Y Button Pulsante Panel Pannello UI Frames Cornici UI + Map Markers Marcatori mappa + Pin Spillo + Flag Bandiera + Crosshair Mirino + Checkpoint Punto di controllo Open Symbol Library Apri libreria simboli Save Symbol Library Salva libreria simboli Save Symbol Library… Salva libreria simboli… @@ -5696,6 +5755,11 @@ axis Y Axis Asse Y User Brush Library 9 Libreria pennelli utente 9 User Brush Library 10 Libreria pennelli utente 10 Art Ribbons Nastri grafici + Zigzag Zigzag + Burst Ray Raggio d’impatto + Dash Trail Scia tratteggiata + Speed Line Linea di velocità + Game Trails Scia di gioco Calligraphic Nibs Pennini calligrafici Pattern Borders Bordi a motivo Scatter Shapes Forme a dispersione @@ -5716,6 +5780,8 @@ axis Y Axis Asse Y # Align panel menu › Align to Glyph Bounds (#4231). Point Text Testo per punti Area Text Testo in area +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Misura il testo in base ai limiti del glifo # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Mostra opzioni di aggancio a glifo Hide Snap to Glyph Options Nascondi opzioni di aggancio a glifo @@ -6283,3 +6349,8 @@ breakText Glyphs Glifi Align to Pixel Grid Allinea alla griglia pixel @msg only paths and compound paths can be aligned to the pixel grid solo i tracciati e i tracciati composti possono essere allineati alla griglia pixel @msg side is left or right, not `{s}` side è left o right, non `{s}` + Ignore All Ignora tutto + Add to Dictionary Aggiungi al dizionario + No Suggestions Nessun suggerimento + Edit Custom Dictionary Modifica dizionario personalizzato + Entry: Voce: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b2c2b37a0f..56fc8a5907 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -627,6 +627,7 @@ digits Malayalam マラヤーラム数字 Guides ガイド Hide Guides ガイドを隠す Lock Guides ガイドをロック + Lock Guides by Default ガイドを初期設定でロック Make Guides ガイドを作成 Release Guides ガイドを解除 Clear Guides ガイドを消去 @@ -798,6 +799,13 @@ digits Malayalam マラヤーラム数字 Other Library… その他のライブラリ… Graphic Style Libraries グラフィックスタイルライブラリ Shadows and Glows シャドウと光彩 + Game HUD ゲーム HUD + Health Fill 体力 + Mana Glow マナ + Damage Flash ダメージ + Quest Outline クエスト + Coin Shine コイン + Boss Alert ボス Outlines and Rules アウトラインと罫線 Hand-Drawn 手描き風 Gradient Finishes グラデーション仕上げ @@ -1076,7 +1084,6 @@ antiAlias Sharp シャープ Update While Dragging ドラッグ中に更新 Hide Video Rulers ビデオ定規を隠す Background Contents 背景のカラー - Background Contents: 背景のカラー: Background: 背景: Bar Graph Tool 棒グラフツール Baseline Shift ベースラインシフト @@ -1253,6 +1260,7 @@ antiAlias Sharp シャープ Coming soon — tracked in the parity plan 近日対応予定 Command Click to Select Objects Behind Command+クリックで背面のオブジェクトを選択 Command Dialog コマンドダイアログ + Command API Reference コマンド API リファレンス Community コミュニティ Compatibility: 互換性: Compatible Gradient and Gradient Mesh Printing 互換性のあるグラデーションとグラデーションメッシュのプリント @@ -1302,7 +1310,6 @@ antiAlias Sharp シャープ Corners… コーナー… Chamfer 面取り Create Clipping Mask クリッピングマスクを作成 - Create Document ドキュメントを作成 Create From: 作成元: Create Graph グラフを作成 Create New Layer 新規レイヤーを作成 @@ -2362,7 +2369,6 @@ antiAlias Sharp シャープ New Symbol… 新規シンボル… New Workspace 新規ワークスペース New file 新規ファイル - New from Template テンプレートから新規作成 New theme from the current color 現在のカラーから新規テーマ New {kind} Style… 新規{kind}スタイル… Next 次へ @@ -2905,6 +2911,7 @@ mark-style Japanese 日本式 Save PDF Preset PDF プリセットを保存 Save Perspective Grid Preset 遠近グリッドプリセットを保存 Save Preset プリセットを保存 + Save Document Preset ドキュメントプリセットを保存 Preset {number} プリセット {number} Save Preset… 保存… Save Print Preset プリントプリセットを保存 @@ -3253,7 +3260,6 @@ mark-style Japanese 日本式 Target Contents 内容をターゲット Target: ターゲット: Templates Folder テンプレートフォルダー - Templates… テンプレート… Text Displayed in Cell: セルに表示するテキスト: Text Export Options テキスト書き出しオプション Text Import Options テキスト読み込みオプション @@ -4601,6 +4607,11 @@ swatch Bright Violet ビビッドバイオレット @msg artboard {0} does not exist アートボード {0} は存在しません @msg cannot read PDF: {0} PDF を読み込めません: {0} @msg invalid PDF setting: {0} PDF の設定が正しくありません: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller アートボード {n} のページは {size} で、PDF のページ上限 14,400 pt (200 in) を超えています: UserUnit {unit} で書き出されるため、UserUnit を無視するアプリではその倍率だけ小さく表示されます +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in アートボード {n} のページは {size} で、PDF のページ上限 14,400 pt (200 in) を超えています: {label} のページは UserUnit なしでポイント単位で書き出され、上限を守るアプリではページが 200 in で切り取られます +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 には、14,400 pt (200 in) を超えるページがサイズを保つために必要な UserUnit がありません: ファイルは PDF 1.6 として書き出されます +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units アートボード {n} のページは {size} で、PDF のページ辺 3 から 14,400 単位には長く細すぎます: 短辺を 3 単位以上に保つ UserUnit {unit} で書き出され、上限を守るアプリは長辺を 14,400 単位で切り取ります +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} ファイルの実数は {max} までですが、アートボード {n} の {side} pt のページにはそれより大きな値が必要です: PDF/X 規格なしの PDF 1.6 以降を選ぶか、アートボードを小さくしてください @msg page {0} does not exist (the PDF has {1}) ページ {0} は存在しません (この PDF のページ数は {1} です) @msg thumbnail: no page {n} (the file has 1) thumbnail: ページ {n} は存在しません (このファイルのページ数は 1 です) @msg the PDF has no pages PDF にページがありません @@ -4803,6 +4814,7 @@ swatch Bright Violet ビビッドバイオレット @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out 「{name}」を読み込みました。{n} 個のステップは省きました @msg not an action set file アクションセットファイルではありません @msg the action set file is larger than 8 MiB アクションセットファイルが 8 MiB を超えています +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: リファレンスが {MAX_BYTES} バイトを超えます @msg the action set file holds more than 1,000 actions アクションセットファイルのアクションが 1,000 個を超えています @msg the action set file needs a later version of VectorCraft このアクションセットファイルには新しいバージョンの VectorCraft が必要です @msg an action in the action set file has more than 10,000 steps アクションセットファイルに 10,000 ステップを超えるアクションがあります @@ -4819,6 +4831,28 @@ swatch Bright Violet ビビッドバイオレット @msg the library item is damaged ライブラリの項目が破損しています @msg {_1} font families available {_1} 個のフォントファミリーを使用できます @msg {_1} has no {_2} style {_1} には {_2} スタイルがありません + Run 実行 + Run Script スクリプトを実行 + Stop Script スクリプトを停止 + Show External Script Warning 外部スクリプトの警告を表示 + A Script Is Running スクリプトの実行中 + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. スクリプトは開いているドキュメントを変更でき、実行するコマンドを通じてファイルを書き込むこともできます。信頼できるスクリプトだけを実行してください。 + Do not show this warning again 今後この警告を表示しない + Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。 + This script has added a great many objects. Continue, or stop it and undo what it did? このスクリプトは非常に多くのオブジェクトを追加しました。続行しますか、それとも停止して変更を取り消しますか? +@msg Choose a .js or .jsx script .js または .jsx スクリプトを選択してください +@msg Ran {name} {name} を実行しました +@msg The script was stopped and its changes were undone スクリプトを停止し、変更を取り消しました +@msg a script is running: stop it or wait for it to finish スクリプトの実行中です: 停止するか、終了するまでお待ちください +@msg this is a compiled script, which cannot be run; use its source text これはコンパイル済みのスクリプトなので実行できません。ソーステキストを使用してください +@msg the script is not UTF-8 text スクリプトは UTF-8 テキストではありません +@msg the script is too large to run スクリプトが大きすぎて実行できません +@msg a drag or an undo group is open; finish it before running a script ドラッグまたは取り消しグループが開いています。スクリプトを実行する前に完了してください +@msg the script left a document that cannot be kept スクリプトが保持できないドキュメントを残しました +@msg the script's run is no longer available スクリプトの実行は利用できなくなりました +@msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗したコマンドが元に戻せない取り消し手順を変更したため、スクリプトを停止しました +@msg a recovery copy could not be written, so the script was not run 復元用のコピーを書き込めなかったため、スクリプトは実行されませんでした +@msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました @msg Exported {path} {path} を書き出しました @msg no CSS to copy: select objects with CSS of their own コピーする CSS がありません: 独自の CSS を持つオブジェクトを選択してください @@ -5238,7 +5272,8 @@ lighting Light ライト Bevel both sides 両面にベベル Presets プリセット @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. 1 つのオブジェクトに適用できる 3D 効果は 1 つです。既存の効果のオプションを編集するか、先に削除してください。 -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} には現在、パスまたは複合パスが必要です。テキスト、画像、グループは先にパスに変換してください。 +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} には現在、パス、複合パス、テキスト、グループ、ブレンド、またはシンボルインスタンスが必要です。その他のオブジェクトは先に拡張してください。 +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} は画像から立体を作成できません。先に「オブジェクト › 画像トレース › 作成」でトレースしてください。 @msg {label} requires a shape with at least two anchors {label} には 2 つ以上のアンカーポイントを持つシェイプが必要です @msg The shape is too complex for a 3D effect シェイプが複雑すぎるため 3D 効果を適用できません @msg The 3D surface is too complex; simplify the shape 3D サーフェスが複雑すぎます。シェイプを単純化してください @@ -5246,6 +5281,11 @@ lighting Light ライト @msg unknown parameter `{key}`; did you mean `{near}`? `{key}` は不明なパラメーターです。`{near}` のことですか? @msg unknown parameter `{key}`; the command takes no parameters `{key}` は不明なパラメーターです。このコマンドにパラメーターはありません @msg unknown parameter `{key}`; the command takes: {keys} `{key}` は不明なパラメーターです。このコマンドで使えるパラメーター: {keys} +@msg the params must be an object, not {got} パラメーターはオブジェクトにしてください ({got} は使えません) +@msg unknown parameter `{path}`; the object takes no keys `{path}` は不明なパラメーターです。このオブジェクトにはキーを指定できません +@msg unknown parameter `{path}`; it takes: {keys} `{path}` は不明なパラメーターです。使えるパラメーター: {keys} +@msg missing `{path}` `{path}` が指定されていません +@msg `{path}` must be {expected}, not {got} `{path}` は {expected} にしてください ({got} は使えません) Load EPS into Clipboard EPS をクリップボードに読み込む @msg an image of {w} × {h} pixels is too large to draw {w} × {h} ピクセルの画像は大きすぎて描画できません @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: PNG、JPEG、WebP、TIFF、BMP のいずれの画像でもありません @@ -5618,6 +5658,20 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 進行状況の表示、キャンセルの検知、ログ行の書き込み Keep settings of its own 独自の設定の保持 Keep a cache of its own, which you can clear 消去できる独自のキャッシュの保持 + Run these commands on the document: {ids} ドキュメントでのこれらのコマンドの実行: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」は `commandAllowlist` にプラグインが呼び出せない `{id}` を挙げています +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: マニフェストの `commandAllowlist` にありません +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID または引数がモジュールのメモリの外にあります +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID または引数が UTF-8 ではありません +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: 引数が JSON オブジェクトではありません +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` を宣言できるのは通常の予算のフィルターだけです +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) コマンド呼び出し (1 回の実行につき {MAX_CALLS} 回、{MAX_CALL_BYTES} バイト) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) コマンド呼び出しのサイズ (vc_call `{shown}`: {len} バイト、上限 {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist` のコマンドは最大 {MAX_ALLOWED_COMMANDS} 個です +@msg a plug-in may not call this command プラグインはこのコマンドを呼び出せません +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` には権限 `commands` が必要で、`commands` には `commandAllowlist` が必要です +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` の `{shown}` はコマンド ID ではないか、2 回挙げられています Clear Plug-in Cache プラグインのキャッシュを消去 @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} 権限 `{permission}` にはプラグイン API レベル {PROGRESS_API} が必要です。`api` {PROGRESS_API} を指定してください @msg the module imports `env.{name}` with another type than the host's: it is {signature} モジュールが `env.{name}` をホストと異なる型でインポートしています。ホストの型は {signature} です @@ -5707,6 +5761,11 @@ axis Y Axis Y 軸 Button ボタン Panel パネル UI Frames UIフレーム + Map Markers マップマーカー + Pin ピン + Flag 旗 + Crosshair クロスヘア + Checkpoint チェックポイント Open Symbol Library シンボルライブラリを開く Save Symbol Library シンボルライブラリを保存 Save Symbol Library… シンボルライブラリを保存… @@ -5761,6 +5820,11 @@ axis Y Axis Y 軸 User Brush Library 9 ユーザーブラシライブラリ 9 User Brush Library 10 ユーザーブラシライブラリ 10 Art Ribbons アートリボン + Zigzag ジグザグ + Burst Ray バーストレイ + Dash Trail ダッシュトレイル + Speed Line スピードライン + Game Trails ゲームトレイル Calligraphic Nibs カリグラフィペン先 Pattern Borders パターンボーダー Scatter Shapes 散布シェイプ @@ -5781,6 +5845,8 @@ axis Y Axis Y 軸 # Align panel menu › Align to Glyph Bounds (#4231). Point Text ポイント文字 Area Text エリア内文字 +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds 文字を字形の境界で測定 # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options グリフにスナップのオプションを表示 Hide Snap to Glyph Options グリフにスナップのオプションを隠す @@ -6348,3 +6414,8 @@ breakText Glyphs 字形 Align to Pixel Grid ピクセルグリッドに整合 @msg only paths and compound paths can be aligned to the pixel grid ピクセルグリッドに整合できるのはパスと複合パスのみです @msg side is left or right, not `{s}` side は left または right です(`{s}` ではありません) + Ignore All すべて無視 + Add to Dictionary 辞書に追加 + No Suggestions 候補なし + Edit Custom Dictionary カスタム辞書を編集 + Entry: エントリ: diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a625c7bf51..388dd4a01e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -521,6 +521,7 @@ Hide Guides დამხმარე ხაზების დამალვა Show Guides დამხმარე ხაზების ჩვენება Lock Guides დამხმარე ხაზების ჩაკეტვა + Lock Guides by Default დამხმარე ხაზების ნაგულისხმევად ჩაკეტვა Unlock Guides დამხმარე ხაზების განბლოკვა Make Guides დამხმარე ხაზების შექმნა Release Guides დამხმარე ხაზების მოხსნა @@ -661,6 +662,13 @@ Other Library… სხვა ბიბლიოთეკა… Graphic Style Libraries გრაფიკული სტილების ბიბლიოთეკები Shadows and Glows ჩრდილები და ნათებები + Game HUD თამაშის HUD + Health Fill სიცოცხლე + Mana Glow მანა + Damage Flash ზიანი + Quest Outline ქვესტი + Coin Shine მონეტა + Boss Alert ბოსი Outlines and Rules კონტურები და ხაზები Hand-Drawn ხელით დახატული Gradient Finishes გრადიენტული ზედაპირები @@ -857,6 +865,7 @@ lighting Light სინათლე Color Picker… ფერის ამრჩევი… Coming soon — tracked in the parity plan მალე — აღრიცხულია თანხვედრის გეგმაში Command Dialog ბრძანების დიალოგი + Command API Reference ბრძანებების API ცნობარი Copy Selected Style მონიშნული სტილის კოპირება Corners… კუთხეები… Define Perspective Grid… პერსპექტივის ბადის განსაზღვრა… @@ -2252,15 +2261,12 @@ digits Malayalam მალაიალამური Selected Swatches მონიშნული ფერის ნიმუშები Advanced Options დამატებითი პარამეტრები Background Contents ფონის შიგთავსი - Background Contents: ფონის შიგთავსი: BLANK DOCUMENT PRESETS ცარიელი დოკუმენტის პრესეტები Bleed ჭრისპირა არე Change to Right-to-Left Layout მარჯვნიდან მარცხნივ განლაგებაზე გადასვლა Columns: სვეტები: - Create Document დოკუმენტის შექმნა Documents you create appear here. თქვენ მიერ შექმნილი დოკუმენტები აქ გამოჩნდება. More Settings მეტი პარამეტრი - New from Template შაბლონიდან შექმნა Number of Artboards: სამუშაო დაფების რაოდენობა: Orientation: ორიენტაცია: PRESET DETAILS პრესეტის დეტალები @@ -2270,7 +2276,6 @@ digits Malayalam მალაიალამური Preview Mode გადახედვის რეჟიმი RECENT ბოლოდროინდელი SAVED შენახული - Templates… შაბლონები… Transparent (Default) გამჭვირვალე (ნაგულისხმევი) Save for Office Documents შენახვა Office-ის დოკუმენტებისთვის Transparent Background გამჭვირვალე ფონი @@ -3095,6 +3100,7 @@ theme Appearance იერსახე Arrange by Row სტრიქონების მიხედვით დალაგება Arrange by Column სვეტების მიხედვით დალაგება Save Preset პრესეტის შენახვა + Save Document Preset დოკუმენტის პრესეტის შენახვა Screen (72 ppi) ეკრანი (72 ppi) Social Square Post 1080×1080 კვადრატული პოსტი 1080×1080 Distribute განაწილება @@ -4081,6 +4087,11 @@ font-technology Variable ცვლადი @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) შიდა შეცდომა `{cmd}`-ში: {msg} (დოკუმენტი წინანდელ მდგომარეობაში დარჩა; გთხოვთ, შეგვატყობინოთ ამ ხარვეზის შესახებ) @msg internal error: {msg} (please report this bug) შიდა შეცდომა: {msg} (გთხოვთ, შეგვატყობინოთ ამ ხარვეზის შესახებ) @msg invalid PDF setting: {0} PDF-ის არასწორი პარამეტრი: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller სამუშაო დაფა {n}-ის გვერდი არის {size}, რაც აღემატება PDF-ის გვერდის ლიმიტს 14 400 pt (200 in): ის იწერება UserUnit {unit}-ით, ამიტომ აპები, რომლებიც UserUnit-ს უგულებელყოფენ, მას ამდენჯერ პატარას აჩვენებენ +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in სამუშაო დაფა {n}-ის გვერდი არის {size}, რაც აღემატება PDF-ის გვერდის ლიმიტს 14 400 pt (200 in): {label} გვერდები იწერება UserUnit-ის გარეშე, პუნქტებში, და აპები, რომლებიც ლიმიტს იცავენ, გვერდს 200 in-ზე ჭრიან +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5-ს არ აქვს UserUnit, რომელიც 14 400 pt-ზე (200 in) გრძელ გვერდს ზომის შესანარჩუნებლად სჭირდება: ფაილი იწერება როგორც PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units სამუშაო დაფა {n}-ის გვერდი არის {size}, ძალიან გრძელი და ვიწრო PDF-ის 3-დან 14 400 ერთეულამდე გვერდის მხარეებისთვის: ის იწერება UserUnit {unit}-ით, რომელიც მოკლე მხარეს 3 ერთეულზე ან მეტზე ინარჩუნებს, ხოლო ზღვრის დამცველი აპები გრძელ მხარეს 14 400 ერთეულამდე ჭრიან +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} ფაილები ინახავს ნამდვილ რიცხვებს {max}-მდე, სამუშაო დაფა {n}-ის {side} pt სიგრძის გვერდს კი უფრო დიდი სჭირდება: აირჩიეთ PDF 1.6 ან უფრო ახალი PDF/X სტანდარტის გარეშე, ან უფრო პატარა სამუშაო დაფა @msg invalid image data for `{0}` არასწორი გამოსახულების მონაცემები `{0}`-სთვის @msg invalid parameters for `{cmd}`: {msg} `{cmd}`: არასწორი პარამეტრები — {msg} @msg is not an image VectorCraft reads ეს არ არის გამოსახულება, რომელსაც VectorCraft კითხულობს @@ -4182,6 +4193,7 @@ font-technology Variable ცვლადი @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out ჩაიტვირთა „{name}“; გამოტოვებული ნაბიჯები: {n} @msg not an action set file ეს არ არის მოქმედებების ნაკრების ფაილი @msg the action set file is larger than 8 MiB მოქმედებების ნაკრების ფაილი 8 MiB-ზე დიდია +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: ცნობარი {MAX_BYTES} ბაიტზე დიდი იქნებოდა @msg the action set file holds more than 1,000 actions მოქმედებების ნაკრების ფაილი 1000-ზე მეტ მოქმედებას შეიცავს @msg the action set file needs a later version of VectorCraft მოქმედებების ნაკრების ფაილს VectorCraft-ის უფრო ახალი ვერსია სჭირდება @msg an action in the action set file has more than 10,000 steps მოქმედებების ნაკრების ფაილში ერთ-ერთ მოქმედებას 10 000-ზე მეტი ნაბიჯი აქვს @@ -4959,7 +4971,8 @@ font-technology Variable ცვლადი Bevel both sides წაკვეთა ორივე მხარეს Presets პრესეტები @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. ობიექტს ერთი 3D ეფექტი შეიძლება ჰქონდეს. შეცვალეთ არსებული ეფექტის პარამეტრები ან ჯერ წაშალეთ ის. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label}: ამჟამად საჭიროა ტრაექტორია ან შედგენილი ტრაექტორია. ჯერ გარდაქმენით ტექსტი, გამოსახულებები და ჯგუფები ტრაექტორიებად. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}: ამჟამად საჭიროა ტრაექტორია, შედგენილი ტრაექტორია, ტექსტი, ჯგუფი, გადასვლა ან სიმბოლოს ეგზემპლარი. ჯერ გაშალეთ სხვა ობიექტები. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}: გამოსახულებიდან მყარი სხეულის აგება შეუძლებელია. ჯერ მოახდინეთ მისი ვექტორიზაცია ბრძანებით ობიექტი › გამოსახულების ვექტორიზაცია › შექმნა. @msg {label} requires a shape with at least two anchors {label}: საჭიროა ფიგურა მინიმუმ ორი საყრდენი წერტილით @msg The shape is too complex for a 3D effect ფიგურა ზედმეტად რთულია 3D ეფექტისთვის @msg The 3D surface is too complex; simplify the shape 3D ზედაპირი ზედმეტად რთულია; გაამარტივეთ ფიგურა @@ -4967,6 +4980,11 @@ font-technology Variable ცვლადი @msg unknown parameter `{key}`; did you mean `{near}`? უცნობი პარამეტრი `{key}`; იქნებ `{near}` იგულისხმეთ? @msg unknown parameter `{key}`; the command takes no parameters უცნობი პარამეტრი `{key}`; ბრძანება პარამეტრებს არ იღებს @msg unknown parameter `{key}`; the command takes: {keys} უცნობი პარამეტრი `{key}`; ბრძანება იღებს: {keys} +@msg the params must be an object, not {got} პარამეტრები უნდა იყოს ობიექტი და არა {got} +@msg unknown parameter `{path}`; the object takes no keys უცნობი პარამეტრი `{path}`; ობიექტი გასაღებებს არ იღებს +@msg unknown parameter `{path}`; it takes: {keys} უცნობი პარამეტრი `{path}`; იღებს: {keys} +@msg missing `{path}` აკლია `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` უნდა იყოს {expected} და არა {got} file-filter All readable files ყველა წაკითხვადი ფაილი file-filter All placeable files ყველა განთავსებადი ფაილი file-filter Swatch libraries ფერის ნიმუშების ბიბლიოთეკები @@ -5128,6 +5146,28 @@ mark-style Japanese იაპონური Auto Grouping ავტომატური დაჯგუფება Ignore Color ფერის იგნორირება imageTrace Outline კონტური + Run გაშვება + Run Script სკრიპტის გაშვება + Stop Script სკრიპტის შეჩერება + Show External Script Warning გარე სკრიპტის გაფრთხილების ჩვენება + A Script Is Running სკრიპტი მუშაობს + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. სკრიპტს შეუძლია ღია დოკუმენტების შეცვლა და მის მიერ გაშვებული ბრძანებებით ფაილების ჩაწერა. გაუშვით მხოლოდ სანდო სკრიპტები. + Do not show this warning again აღარ აჩვენო ეს გაფრთხილება + Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით. + This script has added a great many objects. Continue, or stop it and undo what it did? ამ სკრიპტმა ძალიან ბევრი ობიექტი დაამატა. გაგრძელდეს, თუ შეჩერდეს და გაუქმდეს მისი ცვლილებები? +@msg Choose a .js or .jsx script აირჩიეთ .js ან .jsx სკრიპტი +@msg Ran {name} გაშვებულია: {name} +@msg The script was stopped and its changes were undone სკრიპტი შეჩერდა და მისი ცვლილებები გაუქმდა +@msg a script is running: stop it or wait for it to finish სკრიპტი მუშაობს: შეაჩერეთ ან დაელოდეთ დასრულებას +@msg this is a compiled script, which cannot be run; use its source text ეს კომპილირებული სკრიპტია და მისი გაშვება შეუძლებელია; გამოიყენეთ მისი საწყისი ტექსტი +@msg the script is not UTF-8 text სკრიპტი არ არის UTF-8 ტექსტი +@msg the script is too large to run სკრიპტი გასაშვებად ძალიან დიდია +@msg a drag or an undo group is open; finish it before running a script ღიაა გადათრევა ან გაუქმების ჯგუფი; დაასრულეთ სკრიპტის გაშვებამდე +@msg the script left a document that cannot be kept სკრიპტმა დატოვა დოკუმენტი, რომლის შენახვა შეუძლებელია +@msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი +@msg a failed command changed undo steps that could not be put back, so the script was stopped წარუმატებელმა ბრძანებამ შეცვალა გაუქმების ნაბიჯები, რომელთა აღდგენა ვერ მოხერხდა, ამიტომ სკრიპტი შეჩერდა +@msg a recovery copy could not be written, so the script was not run აღდგენის ასლის ჩაწერა ვერ მოხერხდა, ამიტომ სკრიპტი არ გაეშვა +@msg Running a script სკრიპტი მუშაობს @msg Copied the script report კოპირებულია სკრიპტის ანგარიში @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ტრაექტორიის წანაცვლება: წანაცვლების შემდეგ მონიშნული ტრაექტორიებიდან არაფერი რჩება (შიგნით წანაცვლება ფიგურებზე დიდია) @msg {path}: not a file {path}: ფაილი არ არის @@ -5859,6 +5899,20 @@ axis Y Axis Y ღერძი Show its progress, see Cancel and write log lines პროგრესის ჩვენება, გაუქმების შემჩნევა და ჟურნალის სტრიქონების ჩაწერა Keep settings of its own საკუთარი პარამეტრების შენახვა Keep a cache of its own, which you can clear საკუთარი ქეშის შენახვა, რომლის გასუფთავებაც შეგიძლიათ + Run these commands on the document: {ids} ამ ბრძანებების გაშვება დოკუმენტზე: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ `commandAllowlist`-ში ასახელებს `{id}`-ს, რომლის გამოძახებაც პლაგინს არ შეუძლია +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: მანიფესტის `commandAllowlist` მას არ ასახელებს +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID ან არგუმენტები მოდულის მეხსიერების გარეთაა +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID ან არგუმენტები UTF-8 არ არის +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: არგუმენტები JSON ობიექტი არ არის +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist`-ის გამოცხადება მხოლოდ ჩვეულებრივი ბიუჯეტის ფილტრს შეუძლია +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) ბრძანებების გამოძახებები ({MAX_CALLS} გამოძახება და {MAX_CALL_BYTES} ბაიტი ერთ გაშვებაზე) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) ბრძანების გამოძახების ზომა (vc_call `{shown}`: {len} ბაიტი, ლიმიტი {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` მაქსიმუმ {MAX_ALLOWED_COMMANDS} ბრძანება `commandAllowlist`-ში +@msg a plug-in may not call this command პლაგინს ამ ბრძანების გამოძახება არ შეუძლია +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist`-ს სჭირდება ნებართვა `commands`, ხოლო `commands`-ს სჭირდება `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` ასახელებს `{shown}`-ს, რომელიც ბრძანების ID არ არის ან ორჯერაა ჩამოთვლილი Clear Plug-in Cache პლაგინის ქეშის გასუფთავება @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} ნებართვას `{permission}` სჭირდება პლაგინის API-ის დონე {PROGRESS_API}: მიუთითეთ `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} მოდულს შემოაქვს `env.{name}` ჰოსტისგან განსხვავებული ტიპით: ჰოსტის ტიპია {signature} @@ -5948,6 +6002,11 @@ axis Y Axis Y ღერძი Button ღილაკი Panel პანელი UI Frames UI ჩარჩოები + Map Markers რუკის ნიშნულები + Pin ქინძისთავი + Flag დროშა + Crosshair სამიზნე + Checkpoint საკონტროლო წერტილი Open Symbol Library სიმბოლოების ბიბლიოთეკის გახსნა Save Symbol Library სიმბოლოების ბიბლიოთეკის შენახვა Save Symbol Library… სიმბოლოების ბიბლიოთეკის შენახვა… @@ -6002,6 +6061,11 @@ axis Y Axis Y ღერძი User Brush Library 9 მომხმარებლის ფუნჯების ბიბლიოთეკა 9 User Brush Library 10 მომხმარებლის ფუნჯების ბიბლიოთეკა 10 Art Ribbons ნახატის ლენტები + Zigzag ზიგზაგი + Burst Ray დარტყმის სხივი + Dash Trail წყვეტილი კვალი + Speed Line სიჩქარის ხაზი + Game Trails თამაშის კვალი Calligraphic Nibs კალიგრაფიული წვერები Pattern Borders პატერნის ბორდიურები Scatter Shapes გაბნეული ფიგურები @@ -6095,6 +6159,8 @@ swatch Bright Violet კაშკაშა იისფერი # Align panel menu › Align to Glyph Bounds (#4231). Point Text წერტილოვანი ტექსტი Area Text არის ტექსტი +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds ტექსტის გაზომვა გლიფის საზღვრებით # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options გლიფზე მიბმის პარამეტრების ჩვენება Hide Snap to Glyph Options გლიფზე მიბმის პარამეტრების დამალვა @@ -6723,3 +6789,8 @@ font-script Japanese იაპონური Align to Pixel Grid პიქსელურ ბადეზე გასწორება @msg only paths and compound paths can be aligned to the pixel grid პიქსელურ ბადეზე მხოლოდ ტრაექტორიების და შედგენილი ტრაექტორიების გასწორებაა შესაძლებელი @msg side is left or right, not `{s}` side არის left ან right და არა `{s}` + Ignore All ყველას იგნორირება + Add to Dictionary ლექსიკონში დამატება + No Suggestions შემოთავაზებები არ არის + Edit Custom Dictionary მომხმარებლის ლექსიკონის რედაქტირება + Entry: ჩანაწერი: diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e281e83162..03930932a7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -622,6 +622,7 @@ digits Malayalam 말라얄람어 Guides 안내선 Hide Guides 안내선 숨기기 Lock Guides 안내선 잠그기 + Lock Guides by Default 기본적으로 안내선 잠그기 Make Guides 안내선 만들기 Release Guides 안내선 해제 Clear Guides 안내선 지우기 @@ -791,6 +792,13 @@ digits Malayalam 말라얄람어 Other Library… 다른 라이브러리… Graphic Style Libraries 그래픽 스타일 라이브러리 Shadows and Glows 그림자와 광선 + Game HUD 게임 HUD + Health Fill 체력 + Mana Glow 마나 + Damage Flash 피해 + Quest Outline 퀘스트 + Coin Shine 코인 + Boss Alert 보스 Outlines and Rules 윤곽선과 괘선 Hand-Drawn 손그림 Gradient Finishes 그레이디언트 마감 @@ -1066,7 +1074,6 @@ antiAlias Sharp 날카롭게 Update While Dragging 드래그하는 동안 업데이트 Hide Video Rulers 비디오 눈금자 숨기기 Background Contents 배경 내용 - Background Contents: 배경 내용: Background: 배경: Bar Graph Tool 막대 그래프 도구 Baseline Shift 기준선 이동 @@ -1243,6 +1250,7 @@ antiAlias Sharp 날카롭게 Coming soon — tracked in the parity plan 곧 제공 예정 — 기능 동등성 계획에서 관리 중 Command Click to Select Objects Behind Command-클릭으로 뒤쪽 개체 선택 Command Dialog 명령 대화상자 + Command API Reference 명령 API 참조 Community 커뮤니티 Compatibility: 호환성: Compatible Gradient and Gradient Mesh Printing 호환 그레이디언트 및 그레이디언트 메시 인쇄 @@ -1292,7 +1300,6 @@ antiAlias Sharp 날카롭게 Corners… 모퉁이… Chamfer 모따기 Create Clipping Mask 클리핑 마스크 만들기 - Create Document 문서 만들기 Create From: 만들기 기준: Create Graph 그래프 만들기 Create New Layer 새 레이어 만들기 @@ -2352,7 +2359,6 @@ antiAlias Sharp 날카롭게 New Symbol… 새 심볼… New Workspace 새 작업 영역 New file 새 파일 - New from Template 템플릿에서 새로 만들기 New theme from the current color 현재 색상으로 새 테마 만들기 New {kind} Style… 새 {kind} 스타일… Next 다음 @@ -2894,6 +2900,7 @@ mark-style Japanese 일본식 Save PDF Preset PDF 사전 설정 저장 Save Perspective Grid Preset 원근 격자 사전 설정 저장 Save Preset 사전 설정 저장 + Save Document Preset 문서 사전 설정 저장 Preset {number} 사전 설정 {number} Save Preset… 사전 설정 저장… Save Print Preset 인쇄 사전 설정 저장 @@ -3242,7 +3249,6 @@ mark-style Japanese 일본식 Target Contents 대상 내용 Target: 대상: Templates Folder 템플릿 폴더 - Templates… 템플릿… Text Displayed in Cell: 셀에 표시할 텍스트: Text Export Options 텍스트 내보내기 옵션 Text Import Options 텍스트 가져오기 옵션 @@ -4528,6 +4534,11 @@ theme Appearance 외관 @msg artboard {0} does not exist 아트보드 {0}이(가) 없습니다 @msg cannot read PDF: {0} PDF를 읽을 수 없습니다: {0} @msg invalid PDF setting: {0} 잘못된 PDF 설정: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller 아트보드 {n}의 페이지는 {size}로 PDF 페이지 한도 14,400 pt (200 in)보다 깁니다: UserUnit {unit}(으)로 기록되므로 UserUnit을 무시하는 앱에서는 그 배수만큼 작게 표시됩니다 +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in 아트보드 {n}의 페이지는 {size}로 PDF 페이지 한도 14,400 pt (200 in)보다 깁니다: {label} 페이지는 UserUnit 없이 포인트 단위로 기록되며, 한도를 지키는 앱은 페이지를 200 in으로 자릅니다 +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5에는 14,400 pt (200 in)보다 긴 페이지가 크기를 유지하는 데 필요한 UserUnit이 없습니다: 파일이 PDF 1.6으로 기록됩니다 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units 아트보드 {n}의 페이지는 {size}로, PDF 페이지 변 3에서 14,400 단위에 비해 너무 길고 좁습니다: 짧은 변을 3 단위 이상으로 유지하는 UserUnit {unit}로 기록되며, 한도를 지키는 앱은 긴 변을 14,400 단위로 자릅니다 +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} 파일은 실수를 최대 {max}까지 담는데 아트보드 {n}의 {side} pt 페이지에는 더 큰 값이 필요합니다: PDF/X 표준 없이 PDF 1.6 이상을 선택하거나 더 작은 아트보드를 사용하세요 @msg page {0} does not exist (the PDF has {1}) 페이지 {0}이(가) 없습니다(PDF의 페이지 수: {1}) @msg thumbnail: no page {n} (the file has 1) thumbnail: 페이지 {n}이(가) 없습니다(파일의 페이지 수: 1) @msg the PDF has no pages PDF에 페이지가 없습니다 @@ -4730,6 +4741,7 @@ theme Appearance 외관 @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out “{name}”을(를) 불러왔습니다. 단계 {n}개를 제외했습니다 @msg not an action set file 액션 세트 파일이 아닙니다 @msg the action set file is larger than 8 MiB 액션 세트 파일이 8 MiB보다 큽니다 +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: 참조가 {MAX_BYTES}바이트보다 커집니다 @msg the action set file holds more than 1,000 actions 액션 세트 파일의 액션이 1,000개를 넘습니다 @msg the action set file needs a later version of VectorCraft 이 액션 세트 파일을 열려면 최신 버전의 VectorCraft가 필요합니다 @msg an action in the action set file has more than 10,000 steps 액션 세트 파일에 단계가 10,000개를 넘는 액션이 있습니다 @@ -4746,6 +4758,28 @@ theme Appearance 외관 @msg the library item is damaged 라이브러리 항목이 손상되었습니다 @msg {_1} font families available 사용 가능한 글꼴 패밀리 {_1}개 @msg {_1} has no {_2} style {_1}에는 {_2} 스타일이 없습니다 + Run 실행 + Run Script 스크립트 실행 + Stop Script 스크립트 중지 + Show External Script Warning 외부 스크립트 경고 표시 + A Script Is Running 스크립트 실행 중 + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 스크립트는 열려 있는 문서를 변경하고 실행하는 명령을 통해 파일을 쓸 수 있습니다. 신뢰할 수 있는 스크립트만 실행하세요. + Do not show this warning again 이 경고를 다시 표시하지 않음 + Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요. + This script has added a great many objects. Continue, or stop it and undo what it did? 이 스크립트가 매우 많은 개체를 추가했습니다. 계속할까요, 아니면 중지하고 변경 내용을 취소할까요? +@msg Choose a .js or .jsx script .js 또는 .jsx 스크립트를 선택하세요 +@msg Ran {name} {name} 실행됨 +@msg The script was stopped and its changes were undone 스크립트를 중지하고 변경 내용을 취소했습니다 +@msg a script is running: stop it or wait for it to finish 스크립트 실행 중: 중지하거나 끝날 때까지 기다리세요 +@msg this is a compiled script, which cannot be run; use its source text 컴파일된 스크립트이므로 실행할 수 없습니다. 소스 텍스트를 사용하세요 +@msg the script is not UTF-8 text 스크립트가 UTF-8 텍스트가 아닙니다 +@msg the script is too large to run 스크립트가 너무 커서 실행할 수 없습니다 +@msg a drag or an undo group is open; finish it before running a script 드래그 또는 실행 취소 그룹이 열려 있습니다. 스크립트를 실행하기 전에 완료하세요 +@msg the script left a document that cannot be kept 스크립트가 유지할 수 없는 문서를 남겼습니다 +@msg the script's run is no longer available 스크립트 실행을 더 이상 사용할 수 없습니다 +@msg a failed command changed undo steps that could not be put back, so the script was stopped 실패한 명령이 되돌릴 수 없는 실행 취소 단계를 변경하여 스크립트를 중지했습니다 +@msg a recovery copy could not be written, so the script was not run 복구 사본을 쓸 수 없어 스크립트를 실행하지 않았습니다 +@msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 @msg Exported {path} {path}을(를) 내보냈습니다 @msg no CSS to copy: select objects with CSS of their own 복사할 CSS가 없습니다: 자체 CSS가 있는 개체를 선택하세요 @@ -5157,7 +5191,8 @@ lighting Light 광원 Bevel both sides 양면 베벨 Presets 사전 설정 @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. 오브젝트에는 3D 효과를 하나만 적용할 수 있습니다. 기존 효과의 옵션을 편집하거나 먼저 제거하십시오. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label}에는 현재 패스 또는 컴파운드 패스가 필요합니다. 문자, 이미지 및 그룹을 먼저 패스로 변환하십시오. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}에는 현재 패스, 컴파운드 패스, 문자, 그룹, 블렌드 또는 심볼 인스턴스가 필요합니다. 기타 개체를 먼저 확장하십시오. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}은(는) 이미지로 입체를 만들 수 없습니다. 먼저 개체 › 이미지 추적 › 만들기로 추적하십시오. @msg {label} requires a shape with at least two anchors {label}에는 고정점이 두 개 이상인 모양이 필요합니다 @msg The shape is too complex for a 3D effect 모양이 너무 복잡하여 3D 효과를 적용할 수 없습니다 @msg The 3D surface is too complex; simplify the shape 3D 표면이 너무 복잡합니다. 모양을 단순화하십시오 @@ -5165,6 +5200,11 @@ lighting Light 광원 @msg unknown parameter `{key}`; did you mean `{near}`? 알 수 없는 매개변수 `{key}`: `{near}`을(를) 의미하셨습니까? @msg unknown parameter `{key}`; the command takes no parameters 알 수 없는 매개변수 `{key}`: 이 명령에는 매개변수가 없습니다 @msg unknown parameter `{key}`; the command takes: {keys} 알 수 없는 매개변수 `{key}`: 이 명령이 받는 매개변수: {keys} +@msg the params must be an object, not {got} 매개변수는 객체여야 합니다({got} 사용 불가) +@msg unknown parameter `{path}`; the object takes no keys 알 수 없는 매개변수 `{path}`: 이 객체는 키를 받지 않습니다 +@msg unknown parameter `{path}`; it takes: {keys} 알 수 없는 매개변수 `{path}`: 받는 매개변수: {keys} +@msg missing `{path}` `{path}`이(가) 없습니다 +@msg `{path}` must be {expected}, not {got} `{path}`은(는) {expected}이어야 합니다({got} 사용 불가) Load EPS into Clipboard EPS를 클립보드로 불러오기 @msg an image of {w} × {h} pixels is too large to draw {w} × {h}픽셀 이미지는 너무 커서 그릴 수 없습니다 @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: PNG, JPEG, WebP, TIFF 또는 BMP 이미지가 아닙니다 @@ -5514,6 +5554,20 @@ axis Y Axis Y축 Show its progress, see Cancel and write log lines 진행률 표시, 취소 감지 및 로그 줄 쓰기 Keep settings of its own 자체 설정 보관 Keep a cache of its own, which you can clear 지울 수 있는 자체 캐시 보관 + Run these commands on the document: {ids} 문서에서 다음 명령 실행: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”의 `commandAllowlist`에 플러그인이 호출할 수 없는 `{id}`가 있습니다 +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: 매니페스트의 `commandAllowlist`에 없습니다 +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID 또는 인수가 모듈의 메모리 밖에 있습니다 +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID 또는 인수가 UTF-8이 아닙니다 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: 인수가 JSON 객체가 아닙니다 +@msg only a filter with the usual budget declares `commandAllowlist` 보통 예산의 필터만 `commandAllowlist`를 선언할 수 있습니다 +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) 명령 호출(실행당 {MAX_CALLS}회, {MAX_CALL_BYTES}바이트) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) 명령 호출 크기(vc_call `{shown}`: {len}바이트, 제한 {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist`의 명령은 최대 {MAX_ALLOWED_COMMANDS}개입니다 +@msg a plug-in may not call this command 플러그인은 이 명령을 호출할 수 없습니다 +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist`에는 `commands` 권한이 필요하고, `commands`에는 `commandAllowlist`가 필요합니다 +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist`의 `{shown}`은(는) 명령 ID가 아니거나 두 번 나열되었습니다 Clear Plug-in Cache 플러그인 캐시 지우기 @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} `{permission}` 권한에는 플러그인 API 수준 {PROGRESS_API}이(가) 필요합니다. `api` {PROGRESS_API}을(를) 지정하십시오 @msg the module imports `env.{name}` with another type than the host's: it is {signature} 모듈이 `env.{name}`을(를) 호스트와 다른 형식으로 가져옵니다. 호스트의 형식은 {signature}입니다 @@ -5603,6 +5657,11 @@ axis Y Axis Y축 Button 버튼 Panel 패널 UI Frames UI 프레임 + Map Markers 지도 마커 + Pin 핀 + Flag 깃발 + Crosshair 십자선 + Checkpoint 체크포인트 Open Symbol Library 심볼 라이브러리 열기 Save Symbol Library 심볼 라이브러리 저장 Save Symbol Library… 심볼 라이브러리 저장… @@ -5657,6 +5716,11 @@ axis Y Axis Y축 User Brush Library 9 사용자 브러시 라이브러리 9 User Brush Library 10 사용자 브러시 라이브러리 10 Art Ribbons 아트 리본 + Zigzag 지그재그 + Burst Ray 버스트 레이 + Dash Trail 대시 트레일 + Speed Line 스피드 라인 + Game Trails 게임 트레일 Calligraphic Nibs 서예 펜촉 Pattern Borders 패턴 테두리 Scatter Shapes 흩뿌리기 모양 @@ -5677,6 +5741,8 @@ axis Y Axis Y축 # Align panel menu › Align to Glyph Bounds (#4231). Point Text 포인트 문자 Area Text 영역 문자 +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds 글리프 경계로 문자 측정 # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options 글리프에 스냅 옵션 표시 Hide Snap to Glyph Options 글리프에 스냅 옵션 숨기기 @@ -6244,3 +6310,8 @@ breakText Glyphs 글리프 Align to Pixel Grid 픽셀 격자에 정렬 @msg only paths and compound paths can be aligned to the pixel grid 패스와 컴파운드 패스만 픽셀 격자에 정렬할 수 있습니다 @msg side is left or right, not `{s}` side는 left 또는 right입니다(`{s}` 아님) + Ignore All 모두 무시 + Add to Dictionary 사전에 추가 + No Suggestions 제안 없음 + Edit Custom Dictionary 사용자 사전 편집 + Entry: 항목: diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 073203ca3d..c5151622d4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -573,6 +573,7 @@ Hide Guides Hulplijnen verbergen Show Guides Hulplijnen tonen Lock Guides Hulplijnen vergrendelen + Lock Guides by Default Hulplijnen standaard vergrendelen Unlock Guides Hulplijnen ontgrendelen Make Guides Hulplijnen maken Release Guides Hulplijnen vrijgeven @@ -725,6 +726,13 @@ Other Library… Andere bibliotheek… Graphic Style Libraries Bibliotheken met grafische stijlen Shadows and Glows Schaduwen en gloed + Game HUD Game-HUD + Health Fill Leven + Mana Glow Mana + Damage Flash Schade + Quest Outline Quest + Coin Shine Munt + Boss Alert Baas Outlines and Rules Omtrekken en lijnen Hand-Drawn Handgetekend Gradient Finishes Verloopafwerkingen @@ -919,6 +927,7 @@ lighting Light Licht Color Picker… Kleurkiezer… Coming soon — tracked in the parity plan Binnenkort beschikbaar — opgenomen in het pariteitsplan Command Dialog Opdrachtdialoogvenster + Command API Reference API-naslag voor opdrachten Copy Selected Style Geselecteerde stijl kopiëren Corners… Hoeken… Define Perspective Grid… Perspectiefraster definiëren… @@ -2364,15 +2373,12 @@ digits Malayalam Malayalam Selected Swatches Geselecteerde stalen Advanced Options Geavanceerde opties Background Contents Achtergrondinhoud - Background Contents: Achtergrondinhoud: BLANK DOCUMENT PRESETS LEGE DOCUMENTVOORINSTELLINGEN Bleed Afrulling Change to Right-to-Left Layout Omschakelen naar lay-out van rechts naar links Columns: Kolommen: - Create Document Document maken Documents you create appear here. Documenten die je maakt, verschijnen hier. More Settings Meer instellingen - New from Template Nieuw uit sjabloon Number of Artboards: Aantal tekenborden: Orientation: Oriëntatie: PRESET DETAILS VOORINSTELLINGSDETAILS @@ -2383,7 +2389,6 @@ digits Malayalam Malayalam RECENT RECENT RECENT (1) RECENT (1) SAVED OPGESLAGEN - Templates… Sjablonen… Transparent (Default) Transparant (standaard) Save for Office Documents Opslaan voor Office-documenten Transparent Background Transparante achtergrond @@ -3287,6 +3292,7 @@ theme Appearance Vormgeving Arrange by Row Ordenen op rij Arrange by Column Ordenen op kolom Save Preset Voorinstelling opslaan + Save Document Preset Documentvoorinstelling opslaan Screen (72 ppi) Scherm (72 ppi) Social Square Post 1080×1080 Vierkante socialmediapost 1080×1080 Distribute Verdelen @@ -4088,6 +4094,15 @@ imageTrace Outline Contour @msg Combine Slices: the slices have no bounds Slices combineren: de slices hebben geen grenzen @msg Convert to Artboards: selection has no area Converteren naar tekengebieden: de selectie heeft geen oppervlakte @msg Convert to Shape: no rectangles or ellipses selected Converteren naar vorm: geen rechthoeken of ellipsen geselecteerd + Run Uitvoeren + Run Script Script uitvoeren + Stop Script Script stoppen + Show External Script Warning Waarschuwing voor externe scripts tonen + A Script Is Running Er wordt een script uitgevoerd + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Een script kan de geopende documenten wijzigen en via de uitgevoerde opdrachten bestanden schrijven. Voer alleen scripts uit die u vertrouwt. + Do not show this warning again Deze waarschuwing niet meer tonen + Stop the script and undo what it did? Then quit again. Het script stoppen en de wijzigingen ervan ongedaan maken? Sluit daarna opnieuw af. + This script has added a great many objects. Continue, or stop it and undo what it did? Dit script heeft heel veel objecten toegevoegd. Doorgaan, of het stoppen en de wijzigingen ervan ongedaan maken? @msg Copied the script report Scriptrapport gekopieerd @msg Corners edits the corners of a path Hoeken bewerkt de hoeken van een pad @msg Couldn't copy to the system clipboard: {e} Kon niet naar het systeemklembord kopiëren: {e} @@ -5154,7 +5169,8 @@ mark-style Japanese Japans Bevel both sides Afschuining aan beide zijden Presets Voorinstellingen @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Een object kan maar één 3D-effect hebben. Pas de opties van het bestaande effect aan of verwijder het eerst. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} vereist momenteel een pad of samengesteld pad. Zet tekst, afbeeldingen en groepen eerst om naar paden. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} vereist momenteel een pad, samengesteld pad, tekst, groep, vermenging of symboolinstantie. Breid andere objecten eerst uit. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} kan geen massief object maken van een afbeelding: traceer deze eerst met Object › Afbeelding traceren › Maken. @msg {label} requires a shape with at least two anchors {label} vereist een vorm met minstens twee ankerpunten @msg The shape is too complex for a 3D effect De vorm is te complex voor een 3D-effect @msg The 3D surface is too complex; simplify the shape Het 3D-oppervlak is te complex; vereenvoudig de vorm @@ -5853,6 +5869,7 @@ axis Y Axis Y-as Show its progress, see Cancel and write log lines De voortgang tonen, een annulering zien en logregels schrijven Keep settings of its own Eigen instellingen bewaren Keep a cache of its own, which you can clear Een eigen cache bewaren, die u kunt legen + Run these commands on the document: {ids} Deze opdrachten op het document uitvoeren: {ids} Clear Plug-in Cache Plug-incache legen # Actions panel: action sets (#3712). New Set… Nieuwe set… @@ -5902,6 +5919,11 @@ axis Y Axis Y-as Button Knop Panel Paneel UI Frames UI-kaders + Map Markers Kaartmarkeringen + Pin Speld + Flag Vlag + Crosshair Vizier + Checkpoint Controlepunt Open Symbol Library Symboolbibliotheek openen Save Symbol Library Symboolbibliotheek opslaan Save Symbol Library… Symboolbibliotheek opslaan… @@ -5950,6 +5972,11 @@ axis Y Axis Y-as User Brush Library 9 Penseelbibliotheek van gebruiker 9 User Brush Library 10 Penseelbibliotheek van gebruiker 10 Art Ribbons Illustratielinten + Zigzag Zigzag + Burst Ray Inslagstraal + Dash Trail Streepspoor + Speed Line Snelheidslijn + Game Trails Spelsporen Calligraphic Nibs Kalligrafische penpunten Pattern Borders Patroonranden Scatter Shapes Strooivormen @@ -5962,6 +5989,8 @@ axis Y Axis Y-as # Align panel menu › Align to Glyph Bounds (#4231). Point Text Punttekst Area Text Vlaktekst +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Tekst meten op glyphbegrenzing # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Opties voor uitlijnen op glyph tonen Hide Snap to Glyph Options Opties voor uitlijnen op glyph verbergen @@ -6495,3 +6524,5 @@ breakText Glyphs Glyphs # Align to Pixel Grid Align to Pixel Grid Uitlijnen op pixelraster @msg side is left or right, not `{s}` side is left of right, niet `{s}` + Edit Custom Dictionary Aangepast woordenboek bewerken + Entry: Item: diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8d1be1679e..58016a4bd0 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -566,6 +566,7 @@ Hide Guides Ukryj linie pomocnicze Show Guides Pokaż linie pomocnicze Lock Guides Zablokuj linie pomocnicze + Lock Guides by Default Domyślnie blokuj linie pomocnicze Unlock Guides Odblokuj linie pomocnicze Make Guides Utwórz linie pomocnicze Release Guides Uwolnij linie pomocnicze @@ -721,6 +722,13 @@ Other Library… Inna biblioteka… Graphic Style Libraries Biblioteki stylów graficznych Shadows and Glows Cienie i blaski + Game HUD HUD gry + Health Fill Zdrowie + Mana Glow Mana + Damage Flash Obrażenia + Quest Outline Zadanie + Coin Shine Moneta + Boss Alert Boss Outlines and Rules Kontury i linie Hand-Drawn Rysowane odręcznie Gradient Finishes Wykończenia gradientowe @@ -920,6 +928,7 @@ lighting Light Światło Color Picker… Próbnik kolorów… Coming soon — tracked in the parity plan Już wkrótce — ujęte w planie zgodności Command Dialog Okno polecenia + Command API Reference Dokumentacja API poleceń Copy Selected Style Kopiuj zaznaczony styl Corners… Narożniki… Define Perspective Grid… Zdefiniuj siatkę perspektywy… @@ -2476,15 +2485,12 @@ digits Malayalam Malajalam Selected Swatches Zaznaczone próbki Advanced Options Opcje zaawansowane Background Contents Zawartość tła - Background Contents: Zawartość tła: BLANK DOCUMENT PRESETS USTAWIENIA PUSTEGO DOKUMENTU Bleed Spad Change to Right-to-Left Layout Zmień na układ od prawej do lewej Columns: Kolumny: - Create Document Utwórz dokument Documents you create appear here. Tu pojawią się utworzone dokumenty. More Settings Więcej ustawień - New from Template Nowy z szablonu Number of Artboards: Liczba obszarów kompozycji: Orientation: Orientacja: PRESET DETAILS SZCZEGÓŁY USTAWIENIA @@ -2494,7 +2500,6 @@ digits Malayalam Malajalam Preview Mode Tryb podglądu RECENT OSTATNIE SAVED ZAPISANE - Templates… Szablony… Transparent (Default) Przezroczyste (domyślnie) Save for Office Documents Zapisz dla dokumentów biurowych Transparent Background Przezroczyste tło @@ -3415,6 +3420,7 @@ theme Appearance Wygląd Arrange by Row Ułóż według wierszy Arrange by Column Ułóż według kolumn Save Preset Zapisz ustawienie + Save Document Preset Zapisz ustawienie dokumentu Screen (72 ppi) Ekran (72 ppi) Social Square Post 1080×1080 Kwadratowy post społecznościowy 1080×1080 Distribute Rozmieść @@ -4201,6 +4207,28 @@ imageTrace Outline Kontur @msg Combine Slices: the slices have no bounds Połącz plasterki: plasterki nie mają granic @msg Convert to Artboards: selection has no area Konwertuj na obszary kompozycji: zaznaczenie nie ma powierzchni @msg Convert to Shape: no rectangles or ellipses selected Konwertuj na kształt: nie zaznaczono prostokątów ani elips + Run Uruchom + Run Script Uruchom skrypt + Stop Script Zatrzymaj skrypt + Show External Script Warning Pokazuj ostrzeżenie o skryptach zewnętrznych + A Script Is Running Skrypt jest uruchomiony + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrypt może zmieniać otwarte dokumenty i zapisywać pliki za pomocą wykonywanych poleceń. Uruchamiaj tylko skrypty, którym ufasz. + Do not show this warning again Nie pokazuj więcej tego ostrzeżenia + Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie. + This script has added a great many objects. Continue, or stop it and undo what it did? Ten skrypt dodał bardzo wiele obiektów. Kontynuować, czy zatrzymać go i cofnąć jego zmiany? +@msg Choose a .js or .jsx script Wybierz skrypt .js lub .jsx +@msg Ran {name} Wykonano: {name} +@msg The script was stopped and its changes were undone Skrypt został zatrzymany, a jego zmiany cofnięte +@msg a script is running: stop it or wait for it to finish skrypt jest uruchomiony: zatrzymaj go lub poczekaj na jego zakończenie +@msg this is a compiled script, which cannot be run; use its source text to jest skrypt skompilowany, którego nie można uruchomić; użyj jego tekstu źródłowego +@msg the script is not UTF-8 text skrypt nie jest tekstem UTF-8 +@msg the script is too large to run skrypt jest zbyt duży, aby go uruchomić +@msg a drag or an undo group is open; finish it before running a script otwarte jest przeciąganie lub grupa cofania; zakończ je przed uruchomieniem skryptu +@msg the script left a document that cannot be kept skrypt pozostawił dokument, którego nie można zachować +@msg the script's run is no longer available uruchomienie skryptu nie jest już dostępne +@msg a failed command changed undo steps that could not be put back, so the script was stopped nieudane polecenie zmieniło kroki cofania, których nie udało się przywrócić, więc skrypt został zatrzymany +@msg a recovery copy could not be written, so the script was not run nie udało się zapisać kopii odzyskiwania, więc skrypt nie został uruchomiony +@msg Running a script Uruchamianie skryptu @msg Copied the script report Skopiowano raport skryptu @msg Corners edits the corners of a path Narożniki edytuje narożniki ścieżki @msg Couldn't copy to the system clipboard: {e} Nie udało się skopiować do schowka systemowego: {e} @@ -4443,6 +4471,11 @@ imageTrace Outline Kontur @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) błąd wewnętrzny w `{cmd}`: {msg} (dokument pozostał bez zmian; zgłoś ten błąd) @msg internal error: {msg} (please report this bug) błąd wewnętrzny: {msg} (zgłoś ten błąd) @msg invalid PDF setting: {0} nieprawidłowe ustawienie PDF: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller strona obszaru kompozycji {n} ma {size}, czyli więcej niż limit strony PDF wynoszący 14 400 pt (200 in): jest zapisywana z UserUnit {unit}, więc aplikacje ignorujące UserUnit pokazują ją tyle razy mniejszą +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in strona obszaru kompozycji {n} ma {size}, czyli więcej niż limit strony PDF wynoszący 14 400 pt (200 in): strony {label} są zapisywane bez UserUnit, w punktach, a aplikacje przestrzegające limitu przycinają stronę do 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 nie ma UserUnit, którego strona dłuższa niż 14 400 pt (200 in) potrzebuje, aby zachować rozmiar: plik jest zapisywany jako PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units strona obszaru kompozycji {n} ma {size} i jest za długa i za wąska dla boków strony PDF od 3 do 14 400 jednostek: jest zapisywana z UserUnit {unit}, która utrzymuje krótszy bok na co najmniej 3 jednostkach, a aplikacje przestrzegające limitu przycinają dłuższy bok do 14 400 jednostek +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard pliki {label} mieszczą liczby rzeczywiste do {max}, a strona obszaru kompozycji {n} o długości {side} pt wymaga większych: wybierz PDF 1.6 lub nowszy bez standardu PDF/X albo mniejszy obszar kompozycji @msg invalid image data for `{0}` nieprawidłowe dane obrazu dla `{0}` @msg invalid parameters for `{cmd}`: {msg} nieprawidłowe parametry dla `{cmd}`: {msg} @msg is not an image VectorCraft reads nie jest obrazem obsługiwanym przez VectorCraft @@ -4547,6 +4580,7 @@ imageTrace Outline Kontur @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Wczytano „{name}”: pominięto {n} krok|Wczytano „{name}”: pominięto {n} kroki|Wczytano „{name}”: pominięto {n} kroków @msg not an action set file to nie jest plik zestawu operacji @msg the action set file is larger than 8 MiB plik zestawu operacji jest większy niż 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: dokumentacja byłaby większa niż {MAX_BYTES} bajtów @msg the action set file holds more than 1,000 actions plik zestawu operacji zawiera ponad 1000 operacji @msg the action set file needs a later version of VectorCraft plik zestawu operacji wymaga nowszej wersji programu VectorCraft @msg an action in the action set file has more than 10,000 steps operacja w pliku zestawu operacji ma ponad 10 000 kroków @@ -5417,7 +5451,8 @@ mark-style Japanese Japońskie Bevel both sides Faza po obu stronach Presets Ustawienia @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Obiekt może mieć jeden efekt 3D. Edytuj opcje istniejącego efektu lub najpierw go usuń. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} wymaga obecnie ścieżki lub ścieżki złożonej. Najpierw przekonwertuj tekst, obrazy i grupy na ścieżki. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} wymaga obecnie ścieżki, ścieżki złożonej, tekstu, grupy, przejścia lub wystąpienia symbolu. Najpierw rozszerz inne obiekty. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} nie może utworzyć bryły z obrazu: najpierw obrysuj go poleceniem Obiekt › Obrys obrazu › Utwórz. @msg {label} requires a shape with at least two anchors {label} wymaga kształtu z co najmniej dwoma punktami @msg The shape is too complex for a 3D effect Kształt jest zbyt złożony dla efektu 3D @msg The 3D surface is too complex; simplify the shape Powierzchnia 3D jest zbyt złożona; uprość kształt @@ -5434,6 +5469,11 @@ mark-style Japanese Japońskie @msg unknown parameter `{key}`; did you mean `{near}`? nieznany parametr `{key}`; czy chodziło o `{near}`? @msg unknown parameter `{key}`; the command takes no parameters nieznany parametr `{key}`; polecenie nie przyjmuje parametrów @msg unknown parameter `{key}`; the command takes: {keys} nieznany parametr `{key}`; polecenie przyjmuje: {keys} +@msg the params must be an object, not {got} parametry muszą być obiektem, a nie {got} +@msg unknown parameter `{path}`; the object takes no keys nieznany parametr `{path}`; obiekt nie przyjmuje kluczy +@msg unknown parameter `{path}`; it takes: {keys} nieznany parametr `{path}`; przyjmuje: {keys} +@msg missing `{path}` brak `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` musi być {expected}, a nie {got} Load EPS into Clipboard Wczytaj EPS do schowka @msg an image of {w} × {h} pixels is too large to draw obraz o wymiarach {w} × {h} pikseli jest zbyt duży, aby go narysować @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: to nie jest obraz PNG, JPEG, WebP, TIFF ani BMP @@ -5790,6 +5830,20 @@ axis Y Axis Oś Y Show its progress, see Cancel and write log lines Pokazywać swój postęp, wykrywać anulowanie i zapisywać wiersze dziennika Keep settings of its own Przechowywać własne ustawienia Keep a cache of its own, which you can clear Przechowywać własną pamięć podręczną, którą możesz wyczyścić + Run these commands on the document: {ids} Uruchamiać w dokumencie te polecenia: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}” wymienia w `commandAllowlist` polecenie `{id}`, którego wtyczka nie może wywołać +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: `commandAllowlist` manifestu go nie wymienia +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID lub argumenty leżą poza pamięcią modułu +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID lub argumenty nie są w UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumenty nie są obiektem JSON +@msg only a filter with the usual budget declares `commandAllowlist` tylko filtr ze zwykłym budżetem deklaruje `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) wywołania poleceń ({MAX_CALLS} wywołań i {MAX_CALL_BYTES} bajtów na uruchomienie) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) rozmiar wywołania polecenia (vc_call `{shown}`: {len} bajtów, limit {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` najwyżej {MAX_ALLOWED_COMMANDS} poleceń w `commandAllowlist` +@msg a plug-in may not call this command wtyczka nie może wywołać tego polecenia +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` potrzebuje uprawnienia `commands`, a `commands` potrzebuje `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` wymienia `{shown}`, które nie jest ID polecenia lub występuje dwa razy Clear Plug-in Cache Wyczyść pamięć podręczną wtyczki @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} uprawnienie `{permission}` wymaga poziomu API wtyczek {PROGRESS_API}: podaj `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} moduł importuje `env.{name}` z innym typem niż typ hosta: typ hosta to {signature} @@ -5879,6 +5933,11 @@ axis Y Axis Oś Y Button Przycisk Panel Panel UI Frames Ramki UI + Map Markers Znaczniki mapy + Pin Pinezka + Flag Flaga + Crosshair Celownik + Checkpoint Punkt kontrolny Open Symbol Library Otwórz bibliotekę symboli Save Symbol Library Zapisz bibliotekę symboli Save Symbol Library… Zapisz bibliotekę symboli… @@ -5933,6 +5992,11 @@ axis Y Axis Oś Y User Brush Library 9 Biblioteka pędzli użytkownika 9 User Brush Library 10 Biblioteka pędzli użytkownika 10 Art Ribbons Wstęgi artystyczne + Zigzag Zygzak + Burst Ray Promień uderzenia + Dash Trail Ślad kreskowany + Speed Line Linia prędkości + Game Trails Ślady gry Calligraphic Nibs Stalówki kaligraficzne Pattern Borders Obramowania wzorków Scatter Shapes Kształty rozproszone @@ -5953,6 +6017,8 @@ axis Y Axis Oś Y # Align panel menu › Align to Glyph Bounds (#4231). Point Text Tekst punktowy Area Text Tekst akapitowy +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Mierz tekst według granic glifów # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Pokaż opcje przyciągania do glifów Hide Snap to Glyph Options Ukryj opcje przyciągania do glifów @@ -6518,3 +6584,8 @@ breakText Glyphs Glify Align to Pixel Grid Wyrównaj do siatki pikseli @msg only paths and compound paths can be aligned to the pixel grid do siatki pikseli można wyrównać tylko ścieżki i ścieżki złożone @msg side is left or right, not `{s}` side to left lub right, a nie `{s}` + Ignore All Ignoruj wszystko + Add to Dictionary Dodaj do słownika + No Suggestions Brak sugestii + Edit Custom Dictionary Edytuj słownik użytkownika + Entry: Wpis: diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index ebe44a68cf..b0d940693f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -283,7 +283,6 @@ antiAlias Sharp Nítido Update While Dragging Atualizar ao Arrastar Hide Video Rulers Ocultar Réguas de Vídeo Background Contents Conteúdo do Plano de Fundo - Background Contents: Conteúdo do Plano de Fundo: Background: Plano de Fundo: Bar Graph Tool Ferramenta Gráfico de Barras Baseline Shift Deslocamento da Linha de Base @@ -533,6 +532,7 @@ antiAlias Sharp Nítido Coming soon — tracked in the parity plan Em breve — rastreado no plano de paridade Command Click to Select Objects Behind Clique com Comando para Selecionar Objetos Atrás Command Dialog Diálogo de Comandos + Command API Reference Referência da API de Comandos Community Comunidade Compatibility: Compatibilidade: Compatible Gradient and Gradient Mesh Printing Impressão Compatível de Gradiente e Malha de Gradiente @@ -596,7 +596,6 @@ antiAlias Sharp Nítido Corners… Cantos… Create Criar Create Clipping Mask Criar Máscara de Recorte - Create Document Criar Documento Create From: Criar De: Create Gradient Mesh… Criar Malha de Gradiente… Create Graph Criar Gráfico @@ -1617,6 +1616,7 @@ antiAlias Sharp Nítido Lock (⌘2) Bloquear (⌘2) Lock Grid Bloquear Grade Lock Guides Bloquear Guias + Lock Guides by Default Bloquear Guias por Padrão Lock Slices Bloquear Fatias Lock Station Point Bloquear Ponto de Estação Lossless (lossy WebP isn't available yet) Sem Perdas (WebP com perdas ainda não está disponível) @@ -1792,7 +1792,6 @@ antiAlias Sharp Nítido Duplicate Toolbar Duplicar Barra de Ferramentas Delete Toolbar Excluir Barra de Ferramentas New file Novo arquivo - New from Template Novo a partir de Modelo New from Template… Novo a partir de Modelo… New theme from the current color Novo tema a partir da cor atual New {kind} Style… Novo Estilo de {kind}… @@ -2457,6 +2456,7 @@ digits Malayalam Malaiala Save PDF Preset Salvar Predefinido de PDF Save Perspective Grid Preset Salvar Predefinido de Grade de Perspectiva Save Preset Salvar Predefinido + Save Document Preset Salvar Predefinido de Documento Save Preset… Salvar Predefinido… Save Print Preset Salvar Predefinido de Impressão Save Recovery Data Salvar Dados de Recuperação @@ -2631,6 +2631,13 @@ digits Malayalam Malaiala Set the selected color to the current color Definir a cor selecionada para a cor atual Setup… Configuração… Shadows and Glows Sombras e Brilhos + Game HUD HUD de jogo + Health Fill Vida + Mana Glow Mana + Damage Flash Dano + Quest Outline Missão + Coin Shine Moeda + Boss Alert Chefe Shape Forma Shape Builder Construtor de Formas Shape Builder Regions Regiões do Construtor de Formas @@ -2880,7 +2887,6 @@ digits Malayalam Malaiala Target: Alvo: Temperature/Tint… Temperatura/Tom… Templates Folder Pasta de Modelos - Templates… Modelos… Text Displayed in Cell: Texto Exibido na Célula: Text Export Options Opções de Exportação de Texto Text Fill & Stroke Color Cor de Preenchimento e Traçado do Texto @@ -3883,6 +3889,11 @@ axis Both Ambos @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) erro interno em `{cmd}`: {msg} (o documento foi mantido como estava; relate este bug) @msg internal error: {msg} (please report this bug) erro interno: {msg} (relate este bug) @msg invalid PDF setting: {0} configuração de PDF inválida: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller a página da prancheta {n} tem {size}, mais que o limite de página do PDF de 14.400 pt (200 in): ela é gravada com um UserUnit de {unit}, então apps que ignoram UserUnit a mostram essa quantidade de vezes menor +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in a página da prancheta {n} tem {size}, mais que o limite de página do PDF de 14.400 pt (200 in): páginas {label} são gravadas sem UserUnit, em pontos, e apps que respeitam o limite cortam a página em 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 o PDF 1.5 não tem UserUnit, de que uma página com mais de 14.400 pt (200 in) precisa para manter seu tamanho: o arquivo é gravado como PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units a página da prancheta {n} tem {size}, longa e estreita demais para os lados de página do PDF, de 3 a 14.400 unidades: ela é gravada com uma UserUnit de {unit}, que mantém o lado menor em 3 unidades ou mais, e os apps que seguem o limite cortam o lado maior em 14.400 unidades +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard os arquivos {label} aceitam números reais de até {max}, e a página da prancheta {n}, com {side} pt, precisa de números maiores: escolha PDF 1.6 ou posterior sem padrão PDF/X, ou uma prancheta menor @msg invalid image data for `{0}` dados de imagem inválidos para `{0}` @msg invalid parameters for `{cmd}`: {msg} parâmetros inválidos para `{cmd}`: {msg} @msg is not an image VectorCraft reads não é uma imagem que o VectorCraft lê @@ -3987,6 +3998,7 @@ axis Both Ambos @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out “{name}” carregado: {n} etapa foi omitida|“{name}” carregado: {n} etapas foram omitidas @msg not an action set file não é um arquivo de conjunto de ações @msg the action set file is larger than 8 MiB o arquivo de conjunto de ações tem mais de 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: a referência teria mais de {MAX_BYTES} bytes @msg the action set file holds more than 1,000 actions o arquivo de conjunto de ações contém mais de 1.000 ações @msg the action set file needs a later version of VectorCraft o arquivo de conjunto de ações requer uma versão mais recente do VectorCraft @msg an action in the action set file has more than 10,000 steps uma ação do arquivo de conjunto de ações tem mais de 10.000 etapas @@ -4505,6 +4517,11 @@ axis Both Ambos @msg unknown parameter `{key}`; did you mean `{near}`? parâmetro desconhecido `{key}`; você quis dizer `{near}`? @msg unknown parameter `{key}`; the command takes no parameters parâmetro desconhecido `{key}`; o comando não tem parâmetros @msg unknown parameter `{key}`; the command takes: {keys} parâmetro desconhecido `{key}`; o comando aceita: {keys} +@msg the params must be an object, not {got} os parâmetros devem ser um objeto, não {got} +@msg unknown parameter `{path}`; the object takes no keys parâmetro desconhecido `{path}`; o objeto não aceita chaves +@msg unknown parameter `{path}`; it takes: {keys} parâmetro desconhecido `{path}`; aceita: {keys} +@msg missing `{path}` falta `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` deve ser {expected}, não {got} Load EPS into Clipboard Carregar EPS na Área de Transferência Drawer menu Menu da gaveta Toolbar: Show Controls Barra de ferramentas: Mostrar controles @@ -5019,6 +5036,28 @@ axis Both Ambos [Normal Paragraph Style] [Estilo de Parágrafo Normal] Joins Junções Axis Eixo + Run Executar + Run Script Executar script + Stop Script Parar script + Show External Script Warning Mostrar aviso de scripts externos + A Script Is Running Um script está em execução + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Um script pode alterar os documentos abertos e gravar arquivos pelos comandos que executa. Execute apenas scripts em que você confia. + Do not show this warning again Não mostrar este aviso novamente + Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente. + This script has added a great many objects. Continue, or stop it and undo what it did? Este script adicionou muitíssimos objetos. Continuar, ou pará-lo e desfazer o que ele fez? +@msg Choose a .js or .jsx script Escolha um script .js ou .jsx +@msg Ran {name} {name} executado +@msg The script was stopped and its changes were undone O script foi parado e suas alterações foram desfeitas +@msg a script is running: stop it or wait for it to finish um script está em execução: pare-o ou aguarde até que termine +@msg this is a compiled script, which cannot be run; use its source text este é um script compilado, que não pode ser executado; use seu texto-fonte +@msg the script is not UTF-8 text o script não é texto UTF-8 +@msg the script is too large to run o script é grande demais para ser executado +@msg a drag or an undo group is open; finish it before running a script há um arraste ou um grupo de desfazer aberto; conclua-o antes de executar um script +@msg the script left a document that cannot be kept o script deixou um documento que não pode ser mantido +@msg the script's run is no longer available a execução do script não está mais disponível +@msg a failed command changed undo steps that could not be put back, so the script was stopped um comando que falhou alterou etapas de desfazer que não puderam ser restauradas, então o script foi interrompido +@msg a recovery copy could not be written, so the script was not run não foi possível gravar uma cópia de recuperação, portanto o script não foi executado +@msg Running a script Executando um script @msg Copied the script report Relatório do script copiado @msg This shortcut file is in a form VectorCraft can't read. Este arquivo de atalhos está em um formato que o VectorCraft não consegue ler. @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis deve ser "vertical", "horizontal" ou um ângulo em graus, não `{v}` @@ -5527,7 +5566,8 @@ mark-style Japanese Japonesas Bevel both sides Chanfro nos Dois Lados Presets Predefinidos @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Um objeto aceita apenas um efeito 3D. Edite as opções do efeito existente ou remova-o primeiro. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} exige, por enquanto, um caminho ou caminho composto. Converta antes texto, imagens e grupos em caminhos. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} exige, por enquanto, um caminho, caminho composto, texto, grupo, mesclagem ou instância de símbolo. Expanda antes os outros objetos. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} não pode criar um sólido a partir de uma imagem: rastreie-a antes com Objeto › Rastreamento de Imagem › Criar. @msg {label} requires a shape with at least two anchors {label} exige uma forma com pelo menos dois pontos de ancoragem @msg The shape is too complex for a 3D effect A forma é complexa demais para um efeito 3D @msg The 3D surface is too complex; simplify the shape A superfície 3D é complexa demais; simplifique a forma @@ -5851,6 +5891,20 @@ axis Y Axis Eixo Y Show its progress, see Cancel and write log lines Mostrar seu progresso, detectar o cancelamento e gravar linhas de log Keep settings of its own Guardar configurações próprias Keep a cache of its own, which you can clear Guardar um cache próprio, que você pode limpar + Run these commands on the document: {ids} Executar estes comandos no documento: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” lista `{id}` em `commandAllowlist`, que um plug-in não pode chamar +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: o `commandAllowlist` do manifesto não o lista +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: o ID ou os argumentos estão fora da memória do módulo +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: o ID ou os argumentos não são UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: os argumentos não são um objeto JSON +@msg only a filter with the usual budget declares `commandAllowlist` somente um filtro com o orçamento habitual declara `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) chamadas de comandos ({MAX_CALLS} chamadas e {MAX_CALL_BYTES} bytes por execução) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) tamanho de uma chamada de comando (vc_call `{shown}`: {len} bytes, limite {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` no máximo {MAX_ALLOWED_COMMANDS} comandos em `commandAllowlist` +@msg a plug-in may not call this command um plug-in não pode chamar este comando +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` precisa da permissão `commands`, e `commands` precisa de um `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` lista `{shown}`, que não é um ID de comando ou aparece duas vezes Clear Plug-in Cache Limpar cache do plug-in @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} a permissão `{permission}` exige o nível de API de plug-in {PROGRESS_API}: informe `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} o módulo importa `env.{name}` com um tipo diferente do tipo do host: o do host é {signature} @@ -5940,6 +5994,11 @@ axis Y Axis Eixo Y Button Botão Panel Painel UI Frames Molduras de IU + Map Markers Marcadores de mapa + Pin Alfinete + Flag Bandeira + Crosshair Mira + Checkpoint Ponto de verificação Open Symbol Library Abrir Biblioteca de Símbolos Save Symbol Library Salvar Biblioteca de Símbolos Save Symbol Library… Salvar Biblioteca de Símbolos… @@ -5994,6 +6053,11 @@ axis Y Axis Eixo Y User Brush Library 9 Biblioteca de Pincéis do Usuário 9 User Brush Library 10 Biblioteca de Pincéis do Usuário 10 Art Ribbons Fitas de Arte + Zigzag Zigue-zague + Burst Ray Raio de impacto + Dash Trail Rastro tracejado + Speed Line Linha de velocidade + Game Trails Rastros de jogo Calligraphic Nibs Penas Caligráficas Pattern Borders Bordas de Padrão Scatter Shapes Formas de Dispersão @@ -6014,6 +6078,8 @@ axis Y Axis Eixo Y # Align panel menu › Align to Glyph Bounds (#4231). Point Text Texto de Ponto Area Text Texto de Área +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Medir Texto pelos Limites do Glifo # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Mostrar Opções de Ajuste ao Glifo Hide Snap to Glyph Options Ocultar Opções de Ajuste ao Glifo @@ -6735,3 +6801,8 @@ swatch Yellow Green Verde-amarelado Align to Pixel Grid Alinhar à Grade de Pixels @msg only paths and compound paths can be aligned to the pixel grid somente caminhos e caminhos compostos podem ser alinhados à grade de pixels @msg side is left or right, not `{s}` side é left ou right, não `{s}` + Ignore All Ignorar Tudo + Add to Dictionary Adicionar ao Dicionário + No Suggestions Nenhuma Sugestão + Edit Custom Dictionary Editar Dicionário Personalizado + Entry: Entrada: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index dc6402e831..a00325e8b8 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -295,7 +295,6 @@ font-technology Variable Вариативные Update While Dragging Обновлять при перетаскивании Hide Video Rulers Скрыть видео-линейки Background Contents Содержимое фона - Background Contents: Содержимое фона: Background: Фон: Backspace Backspace Bar Graph Tool Инструмент «Гистограмма» @@ -581,6 +580,7 @@ font-technology Variable Вариативные Coming soon — tracked in the parity plan Скоро — отслеживается в плане развития Command Click to Select Objects Behind Cmd+щелчок для выбора объектов позади Command Dialog Диалоговое окно команды + Command API Reference Справочник по API команд Community Сообщество Compatibility: Совместимость: Compatible Gradient and Gradient Mesh Printing Совместимая печать градиентов и градиентных сеток @@ -667,7 +667,6 @@ font-technology Variable Вариативные Couldn't {} {name}: {e} Не удалось {} {name}: {e} Create Создать Create Clipping Mask Создать маску обрезки - Create Document Создать документ Create from Guides Создать из направляющих Create from Selection Создать из выделения Create From: Создать из: @@ -1922,6 +1921,7 @@ file-filter Templates Шаблоны Lock (⌘2) Заблокировать (⌘2) Lock Grid Заблокировать сетку Lock Guides Заблокировать направляющие + Lock Guides by Default Блокировать направляющие по умолчанию Lock Others Заблокировать остальные Lock Slices Заблокировать фрагменты Lock Station Point Заблокировать точку стояния @@ -2170,7 +2170,6 @@ file-filter Templates Шаблоны New Color Group… Новая цветовая группа… New Document Presets Наборы новых документов New file Новый файл - New from Template Создать из шаблона New from Template… Создать из шаблона… New Graphic Style Новый графический стиль New Graphic Style (Alt-click to name it) Новый графический стиль (Alt+щелчок, чтобы задать имя) @@ -2962,6 +2961,7 @@ digits Malayalam Малаялам Save PDF Preset Сохранить набор PDF Save Perspective Grid Preset Сохранить набор сетки перспективы Save Preset Сохранить набор + Save Document Preset Сохранить набор документа Preset {number} Набор {number} Save Preset… Сохранить набор… Save Print Preset Сохранить набор печати @@ -3170,6 +3170,13 @@ digits Malayalam Малаялам Settings… Параметры… Setup… Настройка… Shadows and Glows Тени и свечения + Game HUD Игровой HUD + Health Fill Здоровье + Mana Glow Мана + Damage Flash Урон + Quest Outline Квест + Coin Shine Монета + Boss Alert Босс Shape Фигура Shape Builder Создание фигур Shape Builder Regions Области создания фигур @@ -3541,7 +3548,6 @@ digits Malayalam Малаялам Template Шаблон Templates Шаблоны Templates Folder Папка шаблонов - Templates… Шаблоны… Text Displayed in Cell: Текст, отображаемый в ячейке: Text Export Options Параметры экспорта текста Text Fill & Stroke Color Цвет заливки и обводки текста @@ -4104,6 +4110,28 @@ axis Both Оба @msg Combine Slices: the slices have no bounds Объединение фрагментов: у фрагментов нет границ @msg Convert to Artboards: selection has no area Преобразование в монтажные области: у выделения нет области @msg Convert to Shape: no rectangles or ellipses selected Преобразование в фигуру: не выделены прямоугольники или эллипсы + Run Выполнить + Run Script Выполнить скрипт + Stop Script Остановить скрипт + Show External Script Warning Показывать предупреждение о внешних скриптах + A Script Is Running Выполняется скрипт + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт может изменять открытые документы и записывать файлы с помощью выполняемых команд. Запускайте только те скрипты, которым доверяете. + Do not show this warning again Больше не показывать это предупреждение + Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз. + This script has added a great many objects. Continue, or stop it and undo what it did? Этот скрипт добавил очень много объектов. Продолжить или остановить его и отменить его изменения? +@msg Choose a .js or .jsx script Выберите скрипт .js или .jsx +@msg Ran {name} Выполнено: {name} +@msg The script was stopped and its changes were undone Скрипт остановлен, его изменения отменены +@msg a script is running: stop it or wait for it to finish выполняется скрипт: остановите его или дождитесь завершения +@msg this is a compiled script, which cannot be run; use its source text это скомпилированный скрипт, его нельзя выполнить; используйте его исходный текст +@msg the script is not UTF-8 text скрипт не является текстом UTF-8 +@msg the script is too large to run скрипт слишком велик для выполнения +@msg a drag or an undo group is open; finish it before running a script открыто перетаскивание или группа отмены; завершите их перед запуском скрипта +@msg the script left a document that cannot be kept скрипт оставил документ, который нельзя сохранить +@msg the script's run is no longer available выполнение скрипта больше недоступно +@msg a failed command changed undo steps that could not be put back, so the script was stopped неудавшаяся команда изменила шаги отмены, которые не удалось восстановить, поэтому скрипт остановлен +@msg a recovery copy could not be written, so the script was not run не удалось записать копию для восстановления, поэтому скрипт не выполнен +@msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован @msg Corners edits the corners of a path «Углы» редактирует углы контура @msg Couldn't copy to the system clipboard: {e} Не удалось скопировать в системный буфер обмена: {e} @@ -4347,6 +4375,11 @@ axis Both Оба @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) внутренняя ошибка в `{cmd}`: {msg} (документ оставлен в прежнем состоянии; пожалуйста, сообщите об этой ошибке) @msg internal error: {msg} (please report this bug) внутренняя ошибка: {msg} (пожалуйста, сообщите об этой ошибке) @msg invalid PDF setting: {0} недопустимый параметр PDF: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller страница монтажной области {n} имеет размер {size}, что больше ограничения PDF на размер страницы в 14 400 pt (200 in): она записывается с UserUnit {unit}, поэтому приложения, которые игнорируют UserUnit, показывают её во столько же раз меньше +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in страница монтажной области {n} имеет размер {size}, что больше ограничения PDF на размер страницы в 14 400 pt (200 in): страницы {label} записываются без UserUnit, в пунктах, и приложения, соблюдающие ограничение, обрезают страницу до 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 в PDF 1.5 нет UserUnit, который нужен странице длиннее 14 400 pt (200 in), чтобы сохранить размер: файл записывается как PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units страница монтажной области {n} имеет размер {size} и слишком длинная и узкая для сторон страницы PDF от 3 до 14 400 единиц: она записывается с UserUnit {unit}, которая держит короткую сторону не меньше 3 единиц, а приложения, соблюдающие предел, обрезают длинную сторону до 14 400 единиц +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard файлы {label} вмещают вещественные числа до {max}, а странице монтажной области {n} длиной {side} pt нужны большие: выберите PDF 1.6 или новее без стандарта PDF/X или монтажную область меньшего размера @msg invalid image data for `{0}` недопустимые данные изображения для `{0}` @msg invalid parameters for `{cmd}`: {msg} недопустимые параметры для `{cmd}`: {msg} @msg is not an image VectorCraft reads не является изображением, которое читает VectorCraft @@ -4451,6 +4484,7 @@ axis Both Оба @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Загружено «{name}»: пропущен {n} шаг|Загружено «{name}»: пропущено {n} шага|Загружено «{name}»: пропущено {n} шагов @msg not an action set file это не файл набора действий @msg the action set file is larger than 8 MiB файл набора действий больше 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: справочник был бы больше {MAX_BYTES} байт @msg the action set file holds more than 1,000 actions файл набора действий содержит более 1000 действий @msg the action set file needs a later version of VectorCraft для файла набора действий нужна более новая версия VectorCraft @msg an action in the action set file has more than 10,000 steps в файле набора действий есть действие более чем из 10 000 шагов @@ -5190,7 +5224,8 @@ lighting Light Свет Bevel both sides Фаска с обеих сторон Presets Наборы @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. У объекта может быть только один 3D-эффект. Измените параметры существующего эффекта или сначала удалите его. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label}: пока требуется контур или составной контур. Сначала преобразуйте текст, изображения и группы в контуры. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}: пока требуется контур, составной контур, текст, группа, переход или экземпляр символа. Сначала разберите другие объекты. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}: из изображения нельзя построить тело. Сначала трассируйте его командой Объект › Трассировка изображения › Создать. @msg {label} requires a shape with at least two anchors {label}: требуется фигура не менее чем с двумя опорными точками @msg The shape is too complex for a 3D effect Фигура слишком сложна для 3D-эффекта @msg The 3D surface is too complex; simplify the shape 3D-поверхность слишком сложна; упростите фигуру @@ -5198,6 +5233,11 @@ lighting Light Свет @msg unknown parameter `{key}`; did you mean `{near}`? неизвестный параметр `{key}`; возможно, имелся в виду `{near}`? @msg unknown parameter `{key}`; the command takes no parameters неизвестный параметр `{key}`; у команды нет параметров @msg unknown parameter `{key}`; the command takes: {keys} неизвестный параметр `{key}`; команда принимает: {keys} +@msg the params must be an object, not {got} параметры должны быть объектом, а не {got} +@msg unknown parameter `{path}`; the object takes no keys неизвестный параметр `{path}`; объект не принимает ключей +@msg unknown parameter `{path}`; it takes: {keys} неизвестный параметр `{path}`; принимает: {keys} +@msg missing `{path}` отсутствует `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` должно быть {expected}, а не {got} Load EPS into Clipboard Загрузить EPS в буфер обмена @msg an image of {w} × {h} pixels is too large to draw изображение размером {w} × {h} пикселей слишком велико для отрисовки @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: это не изображение PNG, JPEG, WebP, TIFF или BMP @@ -5547,6 +5587,20 @@ axis Y Axis Ось Y Show its progress, see Cancel and write log lines Показывать свой ход выполнения, замечать отмену и записывать строки журнала Keep settings of its own Хранить собственные настройки Keep a cache of its own, which you can clear Хранить собственный кэш, который можно очистить + Run these commands on the document: {ids} Выполнять в документе эти команды: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» указывает в `commandAllowlist` команду `{id}`, которую модуль вызывать не может +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: в `commandAllowlist` манифеста её нет +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID или аргументы лежат вне памяти модуля +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID или аргументы не в UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: аргументы не являются объектом JSON +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` может объявлять только фильтр с обычным бюджетом +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) вызовы команд ({MAX_CALLS} вызовов и {MAX_CALL_BYTES} байт за запуск) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) размер вызова команды (vc_call `{shown}`: {len} байт, предел {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` не более {MAX_ALLOWED_COMMANDS} команд в `commandAllowlist` +@msg a plug-in may not call this command модуль не может вызывать эту команду +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` для `commandAllowlist` нужно разрешение `commands`, а для `commands` нужен `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` указывает `{shown}`, который не является ID команды или указан дважды Clear Plug-in Cache Очистить кэш модуля @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} разрешению `{permission}` нужен уровень API модулей {PROGRESS_API}: укажите `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} модуль импортирует `env.{name}` с другим типом, чем у хоста: у хоста тип {signature} @@ -5636,6 +5690,11 @@ axis Y Axis Ось Y Button Кнопка Panel Панель UI Frames UI-рамки + Map Markers Маркеры карты + Pin Булавка + Flag Флаг + Crosshair Прицел + Checkpoint Контрольная точка Open Symbol Library Открыть библиотеку символов Save Symbol Library Сохранить библиотеку символов Save Symbol Library… Сохранить библиотеку символов… @@ -5690,6 +5749,11 @@ axis Y Axis Ось Y User Brush Library 9 Пользовательская библиотека кистей 9 User Brush Library 10 Пользовательская библиотека кистей 10 Art Ribbons Художественные ленты + Zigzag Зигзаг + Burst Ray Ударный луч + Dash Trail Пунктирный след + Speed Line Линия скорости + Game Trails Игровые следы Calligraphic Nibs Каллиграфические перья Pattern Borders Узорные каймы Scatter Shapes Рассеянные фигуры @@ -6076,6 +6140,8 @@ theme Appearance Оформление # Align panel menu › Align to Glyph Bounds (#4231). Point Text Точечный текст Area Text Текст в области +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Измерять текст по границам глифа # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Показать параметры привязки к глифу Hide Snap to Glyph Options Скрыть параметры привязки к глифу @@ -6751,3 +6817,8 @@ shape Open Открытый Align to Pixel Grid Выровнять по пиксельной сетке @msg only paths and compound paths can be aligned to the pixel grid по пиксельной сетке можно выровнять только контуры и составные контуры @msg side is left or right, not `{s}` side — это left или right, а не `{s}` + Ignore All Пропустить все + Add to Dictionary Добавить в словарь + No Suggestions Нет вариантов + Edit Custom Dictionary Редактировать пользовательский словарь + Entry: Запись: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index a8ce1904d1..f2b24e7d08 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -286,7 +286,6 @@ font-technology Variable Variabla Update While Dragging Uppdatera vid dragning Hide Video Rulers Dölj videolinjaler Background Contents Bakgrundsinnehåll - Background Contents: Bakgrundsinnehåll: Background: Bakgrund: Backspace Backspace Bar Graph Tool Stapeldiagramverktyg @@ -570,6 +569,7 @@ font-technology Variable Variabla Coming soon — tracked in the parity plan Kommer snart — följs upp i paritetsplanen Command Click to Select Objects Behind Cmd-klicka för att markera objekt bakom Command Dialog Kommandodialog + Command API Reference API-referens för kommandon Community Gemenskap Compatibility: Kompatibilitet: Compatible Gradient and Gradient Mesh Printing Kompatibel utskrift av gradienter och gradientnät @@ -656,7 +656,6 @@ font-technology Variable Variabla Couldn't {} {name}: {e} Det gick inte att {} {name}: {e} Create Skapa Create Clipping Mask Skapa klippmask - Create Document Skapa dokument Create from Guides Skapa från stödlinjer Create from Selection Skapa från markering Create From: Skapa från: @@ -1837,6 +1836,7 @@ font-technology Variable Variabla Lock (⌘2) Lås (⌘2) Lock Grid Lås rutnät Lock Guides Lås stödlinjer + Lock Guides by Default Lås stödlinjer som standard Lock Others Lås övriga Lock Slices Lås skivor Lock Station Point Lås betraktarpunkt @@ -2085,7 +2085,6 @@ font-technology Variable Variabla New Color Group… Ny färggrupp… New Document Presets Förinställningar för nytt dokument New file Ny fil - New from Template Ny från mall New from Template… Ny från mall… New Graphic Style Ny grafikstil New Graphic Style (Alt-click to name it) Ny grafikstil (Alt-klicka för att namnge den) @@ -2869,6 +2868,7 @@ digits Malayalam Malayalam Save PDF Preset Spara PDF-förinställning Save Perspective Grid Preset Spara förinställning för perspektivrutnät Save Preset Spara förinställning + Save Document Preset Spara dokumentförinställning Save Preset… Spara förinställning… Save Print Preset Spara utskriftsförinställning Save Recovery Data Spara återställningsdata @@ -3063,6 +3063,13 @@ digits Malayalam Malayalam Settings… Inställningar… Setup… Konfigurera… Shadows and Glows Skuggor och glöd + Game HUD Spel-HUD + Health Fill Hälsa + Mana Glow Mana + Damage Flash Skada + Quest Outline Uppdrag + Coin Shine Mynt + Boss Alert Boss Shape Form Shape Builder Formbyggare Shape Builder Regions Formbyggarområden @@ -3432,7 +3439,6 @@ digits Malayalam Malayalam Template Mall Templates Mallar Templates Folder Mallmapp - Templates… Mallar… Text Displayed in Cell: Text som visas i cellen: Text Export Options Alternativ för textexport Text Fill & Stroke Color Textens fyllnads- och konturfärg @@ -3978,6 +3984,28 @@ axis Both Båda @msg Combine Slices: the slices have no bounds Kombinera skivor: skivorna har inga gränser @msg Convert to Artboards: selection has no area Konvertera till ritytor: markeringen har ingen area @msg Convert to Shape: no rectangles or ellipses selected Konvertera till form: inga rektanglar eller ellipser är markerade + Run Kör + Run Script Kör skript + Stop Script Stoppa skript + Show External Script Warning Visa varning för externa skript + A Script Is Running Ett skript körs + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ett skript kan ändra de öppna dokumenten och skriva filer genom de kommandon det kör. Kör bara skript du litar på. + Do not show this warning again Visa inte den här varningen igen + Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen. + This script has added a great many objects. Continue, or stop it and undo what it did? Det här skriptet har lagt till väldigt många objekt. Fortsätta, eller stoppa det och ångra det det gjort? +@msg Choose a .js or .jsx script Välj ett .js- eller .jsx-skript +@msg Ran {name} Körde {name} +@msg The script was stopped and its changes were undone Skriptet stoppades och dess ändringar ångrades +@msg a script is running: stop it or wait for it to finish ett skript körs: stoppa det eller vänta tills det är klart +@msg this is a compiled script, which cannot be run; use its source text det här är ett kompilerat skript som inte kan köras; använd dess källtext +@msg the script is not UTF-8 text skriptet är inte UTF-8-text +@msg the script is too large to run skriptet är för stort för att köras +@msg a drag or an undo group is open; finish it before running a script en dragning eller ångragrupp är öppen; avsluta den innan du kör ett skript +@msg the script left a document that cannot be kept skriptet lämnade ett dokument som inte kan behållas +@msg the script's run is no longer available skriptets körning är inte längre tillgänglig +@msg a failed command changed undo steps that could not be put back, so the script was stopped ett misslyckat kommando ändrade ångrasteg som inte kunde återställas, så skriptet stoppades +@msg a recovery copy could not be written, so the script was not run en återställningskopia kunde inte skrivas, så skriptet kördes inte +@msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten @msg Corners edits the corners of a path Hörn redigerar hörnen på en bana @msg Couldn't copy to the system clipboard: {e} Kunde inte kopiera till systemets urklipp: {e} @@ -4215,6 +4243,11 @@ axis Both Båda @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) internt fel i `{cmd}`: {msg} (dokumentet lämnades som det var innan; rapportera gärna felet) @msg internal error: {msg} (please report this bug) internt fel: {msg} (rapportera gärna felet) @msg invalid PDF setting: {0} ogiltig PDF-inställning: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller sidan för rityta {n} är {size}, längre än PDF:s sidgräns på 14 400 pt (200 in): den skrivs med en UserUnit på {unit}, så appar som ignorerar UserUnit visar den så många gånger mindre +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in sidan för rityta {n} är {size}, längre än PDF:s sidgräns på 14 400 pt (200 in): {label}-sidor skrivs utan UserUnit, i punkter, och appar som håller sig till gränsen beskär sidan till 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 har ingen UserUnit, som en sida längre än 14 400 pt (200 in) behöver för att behålla sin storlek: filen skrivs som PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units sidan för rityta {n} är {size}, för lång och smal för PDF:s sidlängder på 3 till 14 400 enheter: den skrivs med UserUnit {unit}, som håller den korta sidan på minst 3 enheter, och appar som följer gränsen klipper den långa sidan vid 14 400 enheter +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-filer rymmer reella tal upp till {max}, och sidan för rityta {n}, {side} pt lång, behöver större: välj PDF 1.6 eller senare utan PDF/X-standard, eller en mindre rityta @msg invalid image data for `{0}` ogiltiga bilddata för `{0}` @msg invalid parameters for `{cmd}`: {msg} ogiltiga parametrar för `{cmd}`: {msg} @msg is not an image VectorCraft reads är inte en bild som VectorCraft kan läsa @@ -4319,6 +4352,7 @@ axis Both Båda @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Läste in ”{name}”: {n} steg utelämnades|Läste in ”{name}”: {n} steg utelämnades @msg not an action set file inte en fil med åtgärdsuppsättning @msg the action set file is larger than 8 MiB filen med åtgärdsuppsättningen är större än 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: referensen skulle bli större än {MAX_BYTES} byte @msg the action set file holds more than 1,000 actions filen med åtgärdsuppsättningen innehåller fler än 1 000 åtgärder @msg the action set file needs a later version of VectorCraft filen med åtgärdsuppsättningen kräver en nyare version av VectorCraft @msg an action in the action set file has more than 10,000 steps en åtgärd i filen med åtgärdsuppsättningen har fler än 10 000 steg @@ -5062,7 +5096,8 @@ lighting Light Ljus Bevel both sides Fasning på båda sidor Presets Förinställningar @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Ett objekt kan bara ha en 3D-effekt. Redigera alternativen för den befintliga effekten eller ta bort den först. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} kräver för närvarande en bana eller sammansatt bana. Konvertera text, bilder och grupper till banor först. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} kräver för närvarande en bana, sammansatt bana, text, grupp, blandning eller symbolinstans. Expandera andra objekt först. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} kan inte skapa en solid av en bild: kalkera den först med Objekt › Bildkalkering › Skapa. @msg {label} requires a shape with at least two anchors {label} kräver en form med minst två ankarpunkter @msg The shape is too complex for a 3D effect Formen är för komplex för en 3D-effekt @msg The 3D surface is too complex; simplify the shape 3D-ytan är för komplex; förenkla formen @@ -5070,6 +5105,11 @@ lighting Light Ljus @msg unknown parameter `{key}`; did you mean `{near}`? okänd parameter `{key}`; menade du `{near}`? @msg unknown parameter `{key}`; the command takes no parameters okänd parameter `{key}`; kommandot tar inga parametrar @msg unknown parameter `{key}`; the command takes: {keys} okänd parameter `{key}`; kommandot tar: {keys} +@msg the params must be an object, not {got} parametrarna måste vara ett objekt, inte {got} +@msg unknown parameter `{path}`; the object takes no keys okänd parameter `{path}`; objektet tar inga nycklar +@msg unknown parameter `{path}`; it takes: {keys} okänd parameter `{path}`; den tar: {keys} +@msg missing `{path}` `{path}` saknas +@msg `{path}` must be {expected}, not {got} `{path}` måste vara {expected}, inte {got} 1 Layer 1 lager 1 bit 1 bit 16 Colors 16 färger @@ -5959,6 +5999,20 @@ axis Y Axis Y-axel Show its progress, see Cancel and write log lines Visa sitt förlopp, se när det avbryts och skriva loggrader Keep settings of its own Spara egna inställningar Keep a cache of its own, which you can clear Spara en egen cache, som du kan tömma + Run these commands on the document: {ids} Köra dessa kommandon på dokumentet: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” anger `{id}` i `commandAllowlist`, som ett plugin inte får anropa +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: manifestets `commandAllowlist` anger det inte +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: id:t eller argumenten ligger utanför modulens minne +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: id:t eller argumenten är inte UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumenten är inte ett JSON-objekt +@msg only a filter with the usual budget declares `commandAllowlist` bara ett filter med den vanliga budgeten anger `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) kommandoanrop ({MAX_CALLS} anrop och {MAX_CALL_BYTES} byte per körning) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) storlek på ett kommandoanrop (vc_call `{shown}`: {len} byte, gräns {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` högst {MAX_ALLOWED_COMMANDS} kommandon i `commandAllowlist` +@msg a plug-in may not call this command ett plugin får inte anropa det här kommandot +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` behöver behörigheten `commands`, och `commands` behöver en `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` anger `{shown}`, som inte är ett kommando-id eller finns två gånger Clear Plug-in Cache Töm pluginets cache @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} behörigheten `{permission}` kräver plugin-API-nivå {PROGRESS_API}: ange `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} modulen importerar `env.{name}` med en annan typ än värdens: värdens typ är {signature} @@ -6048,6 +6102,11 @@ axis Y Axis Y-axel Button Knapp Panel Panel UI Frames UI-ramar + Map Markers Kartmarkörer + Pin Nål + Flag Flagga + Crosshair Hårkors + Checkpoint Kontrollpunkt Open Symbol Library Öppna symbolbibliotek Save Symbol Library Spara symbolbibliotek Save Symbol Library… Spara symbolbibliotek… @@ -6102,6 +6161,11 @@ axis Y Axis Y-axel User Brush Library 9 Användarbibliotek för penslar 9 User Brush Library 10 Användarbibliotek för penslar 10 Art Ribbons Konstband + Zigzag Sicksack + Burst Ray Stötstråle + Dash Trail Streckat spår + Speed Line Hastighetslinje + Game Trails Spår från spel Calligraphic Nibs Kalligrafiska pennspetsar Pattern Borders Mönsterbårder Scatter Shapes Spridningsformer @@ -6122,6 +6186,8 @@ axis Y Axis Y-axel # Align panel menu › Align to Glyph Bounds (#4231). Point Text Punkttext Area Text Områdestext +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Mät text efter glyfgränser # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Visa alternativ för fäst mot glyf Hide Snap to Glyph Options Dölj alternativ för fäst mot glyf @@ -8147,3 +8213,8 @@ digits Hindi Hindi Align to Pixel Grid Justera mot pixelrutnät @msg only paths and compound paths can be aligned to the pixel grid bara banor och sammansatta banor kan justeras mot pixelrutnätet @msg side is left or right, not `{s}` side är left eller right, inte `{s}` + Ignore All Ignorera alla + Add to Dictionary Lägg till i ordlistan + No Suggestions Inga förslag + Edit Custom Dictionary Redigera egen ordlista + Entry: Post: diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7c4df674dc..fd842dd342 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1998,6 +1998,47 @@ fn dataset_import_repeated_column_error_is_translated() { } } +/// The errors of a command's parameter schema are translated in every language that translates +/// every message, with the parameter's path and the refused value kept. +#[test] +fn parameter_schema_errors_are_translated() { + use serde_json::json; + use vectorcraft_engine::Session; + let scanned = message_literals(); + for template in [ + "the params must be an object, not {got}", + "unknown parameter `{path}`; the object takes no keys", + "unknown parameter `{path}`; it takes: {keys}", + "missing `{path}`", + "`{path}` must be {expected}, not {got}", + ] { + assert!(scanned.contains(template), "{template}"); + } + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let errors = [ + (s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": -1})).unwrap_err().to_string(), "`zoom`", "must be", "-1"), + (s.execute("view.saved.new", &json!({"center": [0, 0]})).unwrap_err().to_string(), "`zoom`", "missing", ""), + (s.execute("view.saved.list", &json!(5)).unwrap_err().to_string(), "5", "must be", ""), + ]; + s.execute("view.saved.new", &json!({"name": "A", "center": [0, 0], "zoom": 1})).unwrap(); + let nested = [ + (s.execute("view.saved.edit", &json!({"edits": [{"name": "A"}, {"name": "A", "delete": 1}]})).unwrap_err().to_string(), "`edits[1].delete`"), + (s.execute("view.saved.edit", &json!({"edits": [{"name": "A", "x": 1}]})).unwrap_err().to_string(), "`edits[0].x`"), + ]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (e, kept, english, value) in &errors { + let shown = message(lang, e); + assert!(shown.contains(kept) && shown.contains(value) && !shown.contains(english), "{code}: {shown}"); + } + for (e, kept) in &nested { + let shown = message(lang, e); + assert!(shown.contains(kept) && !shown.contains("unknown parameter") && !shown.contains("must be"), "{code}: {shown}"); + } + } +} + /// The warning for a PDF/X file that leaves out the document's bleed is translated in every catalog, /// alone and in the status bar's note. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c2804006cd..76d73994b5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -282,7 +282,6 @@ font-technology Variable Değişken Update While Dragging Sürüklerken Güncelle Hide Video Rulers Video Cetvellerini Gizle Background Contents Arka Plan İçeriği - Background Contents: Arkaplan İçeriği: Background: Arka plan: Backspace Geri tuşu Bar Graph Tool Çubuk Grafik Aracı @@ -564,6 +563,7 @@ font-technology Variable Değişken Coming soon — tracked in the parity plan Çok yakında — eşlik planında takip ediliyor Command Click to Select Objects Behind Komut Arkasındaki Nesneleri Seçmek İçin Tıklayın Command Dialog Komut İletişim Kutusu + Command API Reference Komut API Başvurusu Community Topluluk Compatibility: Uyumluluk: Compatible Gradient and Gradient Mesh Printing Uyumlu Degrade ve Degrade Mesh Baskı @@ -648,7 +648,6 @@ font-technology Variable Değişken Couldn't {} {name}: {e} {} yapılamadı {name}: {e} Create Oluştur Create Clipping Mask Kırpma Maskesi Oluştur - Create Document Belge Oluştur Create from Guides Rehberlerden Oluştur Create from Selection Seçimden Oluştur Create From: Şuradan Oluştur: @@ -1730,6 +1729,7 @@ font-technology Variable Değişken Lock (⌘2) Kilitle (⌘2) Lock Grid Izgarayı Kilitle Lock Guides Kilit Kılavuzları + Lock Guides by Default Kılavuzları Varsayılan Olarak Kilitle Lock Others Diğerlerini Kilitle Lock Slices Dilimleri Kilitle Lock Station Point Kilit İstasyon Noktası @@ -1958,7 +1958,6 @@ font-technology Variable Değişken New Color Group… Yeni Renk Grubu… New Document Presets Yeni Belge Ön Ayarları New file Yeni dosya - New from Template Şablondan yeni New from Template… Şablondan yeni… New Graphic Style Yeni Grafik Stili New Graphic Style (Alt-click to name it) Yeni Grafik Stili (Adını vermek için Alt tuşuna basarak tıklayın) @@ -2734,6 +2733,7 @@ digits Malayalam Malayalam Save PDF Preset PDF Hazır Ayarını Kaydet Save Perspective Grid Preset Perspektif Izgarası Ön Ayarını Kaydet Save Preset Ön Ayarı Kaydet + Save Document Preset Belge Ön Ayarını Kaydet Save Preset… Ön Ayarı Kaydet… Save Print Preset Yazdırma Ön Ayarını Kaydet Save Recovery Data Kurtarma Verilerini Kaydet @@ -2967,6 +2967,13 @@ digits Malayalam Malayalam Settings… Ayarlar… Setup… Kurulum… Shadows and Glows Gölgeler ve Parıltılar + Game HUD Oyun HUD + Health Fill Can + Mana Glow Mana + Damage Flash Hasar + Quest Outline Görev + Coin Shine Jeton + Boss Alert Boss Shape Şekil Shape Builder Şekil Oluşturucu Shape Builder Regions Şekil Oluşturucu Bölgeleri @@ -3323,7 +3330,6 @@ digits Malayalam Malayalam Template Şablon Templates Şablonlar Templates Folder Şablonlar Klasörü - Templates… Şablonlar… Text Displayed in Cell: Hücrede Görüntülenen Metin: Text Export Options Metin Dışa Aktarma Seçenekleri Text Fill & Stroke Color Metin Dolgu ve Kontur Rengi @@ -3860,6 +3866,28 @@ axis Both Her İkisi @msg Combine Slices: the slices have no bounds Dilimleri Birleştir: dilimlerin sınırları yoktur @msg Convert to Artboards: selection has no area Çalışma Yüzeylerine Dönüştür: seçimin alanı yok @msg Convert to Shape: no rectangles or ellipses selected Şekle Dönüştür: seçili dikdörtgen veya elips yok + Run Çalıştır + Run Script Betiği Çalıştır + Stop Script Betiği Durdur + Show External Script Warning Harici Betik Uyarısını Göster + A Script Is Running Bir Betik Çalışıyor + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Bir betik açık belgeleri değiştirebilir ve çalıştırdığı komutlarla dosya yazabilir. Yalnızca güvendiğiniz betikleri çalıştırın. + Do not show this warning again Bu uyarıyı bir daha gösterme + Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın. + This script has added a great many objects. Continue, or stop it and undo what it did? Bu betik çok sayıda nesne ekledi. Devam edilsin mi, yoksa durdurulup yaptıkları geri mi alınsın? +@msg Choose a .js or .jsx script Bir .js veya .jsx betiği seçin +@msg Ran {name} {name} çalıştırıldı +@msg The script was stopped and its changes were undone Betik durduruldu ve değişiklikleri geri alındı +@msg a script is running: stop it or wait for it to finish bir betik çalışıyor: durdurun veya bitmesini bekleyin +@msg this is a compiled script, which cannot be run; use its source text bu derlenmiş bir betik, çalıştırılamaz; kaynak metnini kullanın +@msg the script is not UTF-8 text betik UTF-8 metni değil +@msg the script is too large to run betik çalıştırılamayacak kadar büyük +@msg a drag or an undo group is open; finish it before running a script bir sürükleme veya geri alma grubu açık; betiği çalıştırmadan önce tamamlayın +@msg the script left a document that cannot be kept betik, saklanamayan bir belge bıraktı +@msg the script's run is no longer available betiğin çalıştırması artık kullanılamıyor +@msg a failed command changed undo steps that could not be put back, so the script was stopped başarısız bir komut geri yüklenemeyen geri alma adımlarını değiştirdi, bu yüzden betik durduruldu +@msg a recovery copy could not be written, so the script was not run kurtarma kopyası yazılamadı, bu nedenle betik çalıştırılmadı +@msg Running a script Betik çalıştırılıyor @msg Copied the script report Komut dosyası raporu kopyalandı @msg Corners edits the corners of a path Köşeler bir yolun köşelerini düzenler @msg Couldn't copy to the system clipboard: {e} Sistem panosuna kopyalanamadı: {e} @@ -4074,6 +4102,11 @@ axis Both Her İkisi @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) `{cmd}`de dahili hata: {msg} (belge daha önce olduğu gibi bırakıldı; lütfen bu hatayı bildirin) @msg internal error: {msg} (please report this bug) dahili hata: {msg} (lütfen bu hatayı bildirin) @msg invalid PDF setting: {0} geçersiz PDF ayarı: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller {n} çalışma yüzeyinin sayfası {size}, PDF'nin 14.400 pt (200 in) sayfa sınırından uzun: {unit} UserUnit değeriyle yazılır, bu yüzden UserUnit'i yok sayan uygulamalar onu o kadar kat küçük gösterir +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in {n} çalışma yüzeyinin sayfası {size}, PDF'nin 14.400 pt (200 in) sayfa sınırından uzun: {label} sayfaları UserUnit olmadan, punto cinsinden yazılır ve sınıra uyan uygulamalar sayfayı 200 in'de keser +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5'te, 14.400 pt (200 in) uzunluğunu aşan bir sayfanın boyutunu koruması için gereken UserUnit yoktur: dosya PDF 1.6 olarak yazılır +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units {n} çalışma yüzeyinin sayfası {size}, PDF'nin 3 ile 14.400 birim arasındaki sayfa kenarları için fazla uzun ve dar: kısa kenarı en az 3 birimde tutan {unit} UserUnit değeriyle yazılır ve sınıra uyan uygulamalar uzun kenarı 14.400 birimde keser +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} dosyaları en fazla {max} değerinde gerçek sayı tutar ve {n} çalışma yüzeyinin {side} pt uzunluğundaki sayfası daha büyüklerini gerektiriyor: PDF/X standardı olmadan PDF 1.6 veya sonrasını ya da daha küçük bir çalışma yüzeyi seçin @msg invalid image data for `{0}` `{0}` için geçersiz resim verileri @msg invalid parameters for `{cmd}`: {msg} `{cmd}` için geçersiz parametreler: {msg} @msg is not an image VectorCraft reads VectorCraft'ın okuduğu bir resim değil @@ -4179,6 +4212,7 @@ axis Both Her İkisi @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out “{name}” yüklendi: {n} adım atlandı @msg not an action set file bir eylem seti dosyası değil @msg the action set file is larger than 8 MiB eylem seti dosyası 8 MiB'den büyük +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: başvuru {MAX_BYTES} bayttan büyük olur @msg the action set file holds more than 1,000 actions eylem seti dosyası 1.000'den fazla eylem içeriyor @msg the action set file needs a later version of VectorCraft eylem seti dosyası VectorCraft'ın daha yeni bir sürümünü gerektiriyor @msg an action in the action set file has more than 10,000 steps eylem seti dosyasındaki bir eylemde 10.000'den fazla adım var @@ -4858,7 +4892,8 @@ lighting Light Işık Bevel both sides Her iki tarafa da eğim verin Presets Ön ayarlar @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Bir nesne bir 3D efekti alır. Mevcut efektin seçeneklerini düzenleyin veya önce onu kaldırın. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} şu anda bir yol veya bileşik yol gerektiriyor. Önce türü, görüntüleri ve grupları yollara dönüştürün. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} şu anda bir yol, bileşik yol, yazı, grup, karışım veya sembol örneği gerektiriyor. Önce diğer nesneleri genişletin. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} bir görüntüden katı cisim oluşturamaz: önce Nesne › Görüntü İzleme › Yap ile izleyin. @msg {label} requires a shape with at least two anchors {label} en az iki bağlantı noktasına sahip bir şekil gerektirir @msg The shape is too complex for a 3D effect Şekli 3 boyutlu bir efekt için fazla karmaşık @msg The 3D surface is too complex; simplify the shape 3 boyutlu yüzey çok karmaşık; şekli basitleştir @@ -4866,6 +4901,11 @@ lighting Light Işık @msg unknown parameter `{key}`; did you mean `{near}`? bilinmeyen parametre `{key}`; `{near}` mi demek istediniz? @msg unknown parameter `{key}`; the command takes no parameters bilinmeyen parametre `{key}`; komut hiçbir parametre almaz @msg unknown parameter `{key}`; the command takes: {keys} bilinmeyen parametre `{key}`; komut şunları alır: {keys} +@msg the params must be an object, not {got} parametreler bir nesne olmalıdır, {got} değil +@msg unknown parameter `{path}`; the object takes no keys bilinmeyen parametre `{path}`; nesne anahtar almaz +@msg unknown parameter `{path}`; it takes: {keys} bilinmeyen parametre `{path}`; şunları alır: {keys} +@msg missing `{path}` `{path}` eksik +@msg `{path}` must be {expected}, not {got} `{path}` {expected} olmalıdır, {got} değil 1 Layer 1 Katman 1 bit 1 bit 16 Colors 16 Renk @@ -5892,6 +5932,20 @@ axis Y Axis Y ekseni Show its progress, see Cancel and write log lines İlerlemesini gösterme, iptali algılama ve günlük satırları yazma Keep settings of its own Kendi ayarlarını saklama Keep a cache of its own, which you can clear Temizleyebileceğiniz kendi önbelleğini saklama + Run these commands on the document: {ids} Belgede şu komutları çalıştırma: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”, `commandAllowlist` içinde bir eklentinin çağıramayacağı `{id}` komutunu listeliyor +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: bildirimin `commandAllowlist` listesinde yok +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: kimlik veya bağımsız değişkenler modülün belleğinin dışında +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: kimlik veya bağımsız değişkenler UTF-8 değil +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: bağımsız değişkenler bir JSON nesnesi değil +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` yalnızca olağan bütçeli bir filtrede bildirilebilir +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) komut çağrıları (çalıştırma başına {MAX_CALLS} çağrı ve {MAX_CALL_BYTES} bayt) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) komut çağrısı boyutu (vc_call `{shown}`: {len} bayt, sınır {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist` içinde en fazla {MAX_ALLOWED_COMMANDS} komut +@msg a plug-in may not call this command bir eklenti bu komutu çağıramaz +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` için `commands` izni, `commands` için de bir `commandAllowlist` gerekir +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist`, komut kimliği olmayan veya iki kez listelenen `{shown}` öğesini adlandırıyor Clear Plug-in Cache Eklenti Önbelleğini Temizle @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} `{permission}` izni için eklenti API düzeyi {PROGRESS_API} gerekir: `api` {PROGRESS_API} verin @msg the module imports `env.{name}` with another type than the host's: it is {signature} modül `env.{name}` öğesini ana bilgisayarınkinden farklı bir türle içe aktarıyor: ana bilgisayarın türü {signature} @@ -5981,6 +6035,11 @@ axis Y Axis Y ekseni Button Düğme Panel Panel UI Frames UI çerçeveleri + Map Markers Harita İşaretleri + Pin İğne + Flag Bayrak + Crosshair Nişangah + Checkpoint Kontrol noktası Open Symbol Library Sembol Kitaplığını Aç Save Symbol Library Sembol Kitaplığını Kaydet Save Symbol Library… Sembol Kitaplığını Kaydet… @@ -6035,6 +6094,11 @@ axis Y Axis Y ekseni User Brush Library 9 Kullanıcı Fırça Kitaplığı 9 User Brush Library 10 Kullanıcı Fırça Kitaplığı 10 Art Ribbons Sanat Şeritleri + Zigzag Zigzag + Burst Ray Darbe ışını + Dash Trail Kesik iz + Speed Line Hız çizgisi + Game Trails Oyun izleri Calligraphic Nibs Kaligrafi Uçları Pattern Borders Desen Kenarlıkları Scatter Shapes Dağılım Şekilleri @@ -6055,6 +6119,8 @@ axis Y Axis Y ekseni # Align panel menu › Align to Glyph Bounds (#4231). Point Text Nokta Metni Area Text Alan Metni +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Yazıyı Glif Sınırlarına Göre Ölç # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Glif'e Yapışma Seçeneklerini Göster Hide Snap to Glyph Options Glif'e Yapışma Seçeneklerini Gizle @@ -6618,3 +6684,8 @@ breakText Glyphs Glifler Align to Pixel Grid Piksel Izgarasına Hizala @msg only paths and compound paths can be aligned to the pixel grid piksel ızgarasına yalnızca yollar ve bileşik yollar hizalanabilir @msg side is left or right, not `{s}` side left veya right olmalıdır, `{s}` değil + Ignore All Tümünü Yoksay + Add to Dictionary Sözlüğe Ekle + No Suggestions Öneri Yok + Edit Custom Dictionary Özel Sözlüğü Düzenle + Entry: Giriş: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0108c96a50..4652ce4ca8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -291,7 +291,6 @@ font-technology Variable Варіативні Update While Dragging Оновлювати під час перетягування Hide Video Rulers Приховати відео-лінійки Background Contents Вміст фону - Background Contents: Вміст фону: Background: Фон: Backspace Backspace Bar Graph Tool Інструмент «Гістограма» @@ -577,6 +576,7 @@ font-technology Variable Варіативні Coming soon — tracked in the parity plan Незабаром відстежується в плані розвитку Command Click to Select Objects Behind Cmd+клацання для вибору об’єктів позаду Command Dialog Діалогове вікно команди + Command API Reference Довідник API команд Community Спільнота Compatibility: Сумісність: Compatible Gradient and Gradient Mesh Printing Сумісний друк градієнтів та градієнтних сіток @@ -663,7 +663,6 @@ font-technology Variable Варіативні Couldn't {} {name}: {e} Не вдалося {} {name}: {e} Create Створити Create Clipping Mask Створити відсічну маску - Create Document Створити документ Create from Guides Створити з напрямних Create from Selection Створити із виділення Create From: Створити з: @@ -1919,6 +1918,7 @@ file-filter Templates Шаблони Lock (⌘2) Заблокувати (⌘2) Lock Grid Заблокувати сітку Lock Guides Заблокувати напрямні + Lock Guides by Default Блокувати напрямні за замовчуванням Lock Others Заблокувати решту Lock Slices Заблокувати фрагменти Lock Station Point Заблокувати точку стояння @@ -2167,7 +2167,6 @@ file-filter Templates Шаблони New Color Group… Нова колірна група… New Document Presets Набір нових документів New file Новий файл - New from Template Створити із шаблону New from Template… Створити із шаблону… New Graphic Style Новий графічний стиль New Graphic Style (Alt-click to name it) Новий графічний стиль (Alt+клацання, щоб задати ім’я) @@ -2959,6 +2958,7 @@ digits Malayalam Малаялам Save PDF Preset Зберегти набір PDF Save Perspective Grid Preset Зберегти набір сітки перспективи Save Preset Зберегти набір + Save Document Preset Зберегти набір документа Preset {number} Набір {number} Save Preset… Зберегти набір… Save Print Preset Зберегти набір друку @@ -3167,6 +3167,13 @@ digits Malayalam Малаялам Settings… Параметри… Setup… Налаштування… Shadows and Glows Тіні та свічення + Game HUD Ігровий HUD + Health Fill Здоров'я + Mana Glow Мана + Damage Flash Шкода + Quest Outline Квест + Coin Shine Монета + Boss Alert Бос Shape Фігура Shape Builder Створення фігур Shape Builder Regions Області створення фігур @@ -3539,7 +3546,6 @@ effect Points Точки Template Шаблон Templates Шаблони Templates Folder Папка шаблонів - Templates… Шаблони… Text Displayed in Cell: Текст, що відображається в комірці: Text Export Options Параметри експорту тексту Text Fill & Stroke Color Колір заливки та обведення тексту @@ -4094,6 +4100,28 @@ axis Both Обидві @msg Combine Slices: the slices have no bounds Об’єднання фрагментів: фрагменти не мають кордонів @msg Convert to Artboards: selection has no area Перетворення на монтажні області: виділення не має області @msg Convert to Shape: no rectangles or ellipses selected Перетворення на фігуру: не виділено прямокутники або еліпси + Run Виконати + Run Script Виконати скрипт + Stop Script Зупинити скрипт + Show External Script Warning Показувати попередження про зовнішні скрипти + A Script Is Running Виконується скрипт + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт може змінювати відкриті документи й записувати файли за допомогою команд, які виконує. Запускайте лише ті скрипти, яким довіряєте. + Do not show this warning again Більше не показувати це попередження + Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз. + This script has added a great many objects. Continue, or stop it and undo what it did? Цей скрипт додав дуже багато об’єктів. Продовжити чи зупинити його та скасувати його зміни? +@msg Choose a .js or .jsx script Виберіть скрипт .js або .jsx +@msg Ran {name} Виконано: {name} +@msg The script was stopped and its changes were undone Скрипт зупинено, його зміни скасовано +@msg a script is running: stop it or wait for it to finish виконується скрипт: зупиніть його або дочекайтеся завершення +@msg this is a compiled script, which cannot be run; use its source text це скомпільований скрипт, його не можна виконати; використайте його вихідний текст +@msg the script is not UTF-8 text скрипт не є текстом UTF-8 +@msg the script is too large to run скрипт завеликий для виконання +@msg a drag or an undo group is open; finish it before running a script відкрито перетягування або групу скасування; завершіть їх перед запуском скрипта +@msg the script left a document that cannot be kept скрипт залишив документ, який не можна зберегти +@msg the script's run is no longer available виконання скрипта більше не доступне +@msg a failed command changed undo steps that could not be put back, so the script was stopped невдала команда змінила кроки скасування, які не вдалося відновити, тому скрипт зупинено +@msg a recovery copy could not be written, so the script was not run не вдалося записати копію для відновлення, тому скрипт не виконано +@msg Running a script Виконується скрипт @msg Copied the script report Звіт про сценарій скопійовано @msg Corners edits the corners of a path «Кути» редагує кути контуру @msg Couldn't copy to the system clipboard: {e} Не вдалося скопіювати до системного буфера обміну: {e} @@ -4337,6 +4365,11 @@ axis Both Обидві @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) внутрішня помилка `{cmd}`: {msg} (документ залишений у попередньому стані; будь ласка, повідомте про цю помилку) @msg internal error: {msg} (please report this bug) внутрішня помилка: {msg} (будь ласка, повідомте про цю помилку) @msg invalid PDF setting: {0} неприпустимий параметр PDF: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller сторінка монтажної області {n} має розмір {size}, що більше за обмеження PDF на розмір сторінки в 14 400 pt (200 in): її записано з UserUnit {unit}, тому застосунки, які ігнорують UserUnit, показують її в стільки ж разів меншою +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in сторінка монтажної області {n} має розмір {size}, що більше за обмеження PDF на розмір сторінки в 14 400 pt (200 in): сторінки {label} записуються без UserUnit, у пунктах, і застосунки, що дотримуються обмеження, обрізають сторінку до 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 у PDF 1.5 немає UserUnit, який потрібен сторінці, довшій за 14 400 pt (200 in), щоб зберегти розмір: файл записується як PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units сторінка монтажної області {n} має розмір {size} і задовга та завузька для сторін сторінки PDF від 3 до 14 400 одиниць: її записано з UserUnit {unit}, що тримає коротку сторону не менше 3 одиниць, а застосунки, які дотримуються межі, обрізають довгу сторону до 14 400 одиниць +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard файли {label} вміщують дійсні числа до {max}, а сторінці монтажної області {n} завдовжки {side} pt потрібні більші: виберіть PDF 1.6 або новіший без стандарту PDF/X чи меншу монтажну область @msg invalid image data for `{0}` неприпустимі дані зображення для `{0}` @msg invalid parameters for `{cmd}`: {msg} неприпустимі параметри для `{cmd}`: {msg} @msg is not an image VectorCraft reads не є зображенням, яке читає VectorCraft @@ -4441,6 +4474,7 @@ axis Both Обидві @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Завантажено «{name}»: пропущено {n} крок|Завантажено «{name}»: пропущено {n} кроки|Завантажено «{name}»: пропущено {n} кроків @msg not an action set file це не файл набору дій @msg the action set file is larger than 8 MiB файл набору дій більший за 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: довідник був би більшим за {MAX_BYTES} байтів @msg the action set file holds more than 1,000 actions файл набору дій містить понад 1000 дій @msg the action set file needs a later version of VectorCraft для файлу набору дій потрібна новіша версія VectorCraft @msg an action in the action set file has more than 10,000 steps у файлі набору дій є дія з понад 10 000 кроків @@ -5176,7 +5210,8 @@ lighting Light Світло Bevel both sides Фаска з обох боків Presets Набори @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Об'єкт може мати лише один 3D-ефект. Змініть параметри наявного ефекту або спершу вилучіть його. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label}: поки що потрібен контур або складений контур. Спершу перетворіть текст, зображення та групи на контури. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}: поки що потрібен контур, складений контур, текст, група, перехід або екземпляр символу. Спершу розберіть інші об'єкти. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}: із зображення не можна побудувати тіло. Спершу трасуйте його командою Об’єкт › Трасування зображення › Створити. @msg {label} requires a shape with at least two anchors {label}: потрібна фігура щонайменше з двома опорними точками @msg The shape is too complex for a 3D effect Фігура надто складна для 3D-ефекту @msg The 3D surface is too complex; simplify the shape 3D-поверхня надто складна; спростіть фігуру @@ -5184,6 +5219,11 @@ lighting Light Світло @msg unknown parameter `{key}`; did you mean `{near}`? невідомий параметр `{key}`; можливо, ви мали на увазі `{near}`? @msg unknown parameter `{key}`; the command takes no parameters невідомий параметр `{key}`; команда не має параметрів @msg unknown parameter `{key}`; the command takes: {keys} невідомий параметр `{key}`; команда приймає: {keys} +@msg the params must be an object, not {got} параметри мають бути об'єктом, а не {got} +@msg unknown parameter `{path}`; the object takes no keys невідомий параметр `{path}`; об'єкт не приймає ключів +@msg unknown parameter `{path}`; it takes: {keys} невідомий параметр `{path}`; приймає: {keys} +@msg missing `{path}` відсутнє `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` має бути {expected}, а не {got} Load EPS into Clipboard Завантажити EPS у буфер обміну @msg an image of {w} × {h} pixels is too large to draw зображення розміром {w} × {h} пікселів завелике для відображення @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: це не зображення PNG, JPEG, WebP, TIFF чи BMP @@ -5533,6 +5573,20 @@ axis Y Axis Вісь Y Show its progress, see Cancel and write log lines Показувати свій поступ, помічати скасування і записувати рядки журналу Keep settings of its own Зберігати власні налаштування Keep a cache of its own, which you can clear Зберігати власний кеш, який можна очистити + Run these commands on the document: {ids} Виконувати в документі ці команди: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» вказує в `commandAllowlist` команду `{id}`, яку модуль викликати не може +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: у `commandAllowlist` маніфесту її немає +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID або аргументи лежать поза пам’яттю модуля +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID або аргументи не в UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: аргументи не є об’єктом JSON +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` може оголошувати лише фільтр зі звичайним бюджетом +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) виклики команд ({MAX_CALLS} викликів і {MAX_CALL_BYTES} байтів за запуск) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) розмір виклику команди (vc_call `{shown}`: {len} байтів, межа {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` щонайбільше {MAX_ALLOWED_COMMANDS} команд у `commandAllowlist` +@msg a plug-in may not call this command модуль не може викликати цю команду +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` для `commandAllowlist` потрібен дозвіл `commands`, а для `commands` потрібен `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` вказує `{shown}`, що не є ID команди або вказане двічі Clear Plug-in Cache Очистити кеш модуля @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} дозволу `{permission}` потрібен рівень API модулів {PROGRESS_API}: укажіть `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} модуль імпортує `env.{name}` з іншим типом, ніж у хоста: у хоста тип {signature} @@ -5622,6 +5676,11 @@ axis Y Axis Вісь Y Button Кнопка Panel Панель UI Frames UI-рамки + Map Markers Маркери карти + Pin Шпилька + Flag Прапор + Crosshair Приціл + Checkpoint Контрольна точка Open Symbol Library Відкрити бібліотеку символів Save Symbol Library Зберегти бібліотеку символів Save Symbol Library… Зберегти бібліотеку символів… @@ -5676,6 +5735,11 @@ axis Y Axis Вісь Y User Brush Library 9 Користувацька бібліотека пензлів 9 User Brush Library 10 Користувацька бібліотека пензлів 10 Art Ribbons Художні стрічки + Zigzag Зигзаг + Burst Ray Ударний промінь + Dash Trail Пунктирний слід + Speed Line Лінія швидкості + Game Trails Ігрові сліди Calligraphic Nibs Каліграфічні пера Pattern Borders Візерункові облямівки Scatter Shapes Розсіяні фігури @@ -5696,6 +5760,8 @@ axis Y Axis Вісь Y # Align panel menu › Align to Glyph Bounds (#4231). Point Text Точковий текст Area Text Текст в області +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Вимірювати текст за межами гліфа # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Показати параметри прив’язки до гліфа Hide Snap to Glyph Options Приховати параметри прив’язки до гліфа @@ -6263,3 +6329,8 @@ breakText Glyphs Гліфи Align to Pixel Grid Вирівняти за піксельною сіткою @msg only paths and compound paths can be aligned to the pixel grid за піксельною сіткою можна вирівняти лише контури і складені контури @msg side is left or right, not `{s}` side — це left або right, а не `{s}` + Ignore All Пропустити все + Add to Dictionary Додати до словника + No Suggestions Немає варіантів + Edit Custom Dictionary Редагувати словник користувача + Entry: Запис: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5b979b003f..4c9dac833c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -320,7 +320,6 @@ font-technology Variable Biến thiên Update While Dragging Cập nhật khi kéo Hide Video Rulers Ẩn thước video Background Contents Nội dung nền - Background Contents: Nội dung nền: Background: Nền: Backspace Backspace Balance Cân bằng @@ -672,6 +671,7 @@ font-technology Variable Biến thiên Coming soon — tracked in the parity plan Sắp ra mắt — đang theo dõi trong kế hoạch đối chiếu tính năng Command Click to Select Objects Behind Command-bấm để chọn đối tượng phía sau Command Dialog Hộp thoại lệnh + Command API Reference Tài liệu tham khảo API lệnh Commits Commit Community Cộng đồng Company Công ty @@ -765,7 +765,6 @@ font-technology Variable Biến thiên Create Tạo Create Clipping Mask Tạo mặt nạ cắt Create Compound Path From Ellipses Tạo đường dẫn phức từ hình elip - Create Document Tạo tài liệu Create from Guides Tạo từ đường căn Create from Selection Tạo từ vùng chọn Create From: Tạo từ: @@ -2203,6 +2202,7 @@ digits Hindi Hindi Lock (⌘2) Khóa (⌘2) Lock Grid Khóa lưới Lock Guides Khóa đường căn + Lock Guides by Default Khóa đường căn theo mặc định Lock Others Khóa các mục khác Lock Slices Khóa lát cắt Lock Station Point Khóa điểm trạm @@ -2408,7 +2408,6 @@ digits Hindi Hindi New Design Thiết kế mới New Document Presets Thiết lập sẵn tài liệu mới New file Tệp mới - New from Template Mới từ mẫu New from Template… Mới từ mẫu… New Graphic Style Kiểu đồ họa mới New Graphic Style (Alt-click to name it) Kiểu đồ họa mới (Alt-bấm để đặt tên) @@ -3272,6 +3271,7 @@ mark-style Japanese Kiểu Nhật Save PDF Preset Lưu thiết lập sẵn PDF Save Perspective Grid Preset Lưu thiết lập sẵn lưới phối cảnh Save Preset Lưu thiết lập sẵn + Save Document Preset Lưu thiết lập sẵn tài liệu Preset {number} Thiết lập sẵn {number} Save Preset… Lưu thiết lập sẵn… Save Print Preset Lưu thiết lập sẵn in @@ -3499,6 +3499,13 @@ mark-style Japanese Kiểu Nhật Setup… Thiết lập… Shading Tô bóng Shadows and Glows Bóng và ánh sáng + Game HUD HUD trò chơi + Health Fill Máu + Mana Glow Mana + Damage Flash Sát thương + Quest Outline Nhiệm vụ + Coin Shine Xu + Boss Alert Trùm Shape Hình dạng Shape Builder Tạo hình dạng Shape Builder Regions Vùng Tạo hình dạng @@ -3873,7 +3880,6 @@ mark-style Japanese Kiểu Nhật Template Mẫu Templates Mẫu Templates Folder Thư mục mẫu - Templates… Mẫu… Text Văn bản Text Displayed in Cell: Văn bản hiển thị trong ô: Text Export Options Tùy chọn xuất văn bản @@ -4512,6 +4518,28 @@ theme Appearance Giao diện @msg compressed (RLE) bitmaps can't be read yet bitmap nén (RLE) chưa thể đọc được @msg Convert to Artboards: selection has no area Chuyển thành bảng vẽ: vùng chọn không có diện tích @msg Convert to Shape: no rectangles or ellipses selected Chuyển thành hình dạng: chưa chọn hình chữ nhật hay hình elip + Run Chạy + Run Script Chạy tập lệnh + Stop Script Dừng tập lệnh + Show External Script Warning Hiện cảnh báo tập lệnh bên ngoài + A Script Is Running Một tập lệnh đang chạy + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Tập lệnh có thể thay đổi các tài liệu đang mở và ghi tệp thông qua các lệnh mà nó chạy. Chỉ chạy những tập lệnh bạn tin cậy. + Do not show this warning again Không hiện lại cảnh báo này + Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại. + This script has added a great many objects. Continue, or stop it and undo what it did? Tập lệnh này đã thêm rất nhiều đối tượng. Tiếp tục, hay dừng lại và hoàn tác những gì nó đã làm? +@msg Choose a .js or .jsx script Chọn một tập lệnh .js hoặc .jsx +@msg Ran {name} Đã chạy {name} +@msg The script was stopped and its changes were undone Tập lệnh đã dừng và các thay đổi của nó đã được hoàn tác +@msg a script is running: stop it or wait for it to finish một tập lệnh đang chạy: hãy dừng nó hoặc chờ nó kết thúc +@msg this is a compiled script, which cannot be run; use its source text đây là tập lệnh đã biên dịch, không thể chạy; hãy dùng văn bản nguồn của nó +@msg the script is not UTF-8 text tập lệnh không phải là văn bản UTF-8 +@msg the script is too large to run tập lệnh quá lớn để chạy +@msg a drag or an undo group is open; finish it before running a script đang có thao tác kéo hoặc nhóm hoàn tác; hãy hoàn thành trước khi chạy tập lệnh +@msg the script left a document that cannot be kept tập lệnh để lại một tài liệu không thể giữ +@msg the script's run is no longer available lần chạy tập lệnh không còn khả dụng +@msg a failed command changed undo steps that could not be put back, so the script was stopped một lệnh thất bại đã thay đổi các bước hoàn tác không thể khôi phục, nên tập lệnh đã bị dừng +@msg a recovery copy could not be written, so the script was not run không thể ghi bản sao khôi phục nên tập lệnh không được chạy +@msg Running a script Đang chạy tập lệnh @msg Copied the script report Đã sao chép báo cáo script @msg Corners edits the corners of a path Corners chỉnh sửa các góc của đường dẫn @msg could not decode image: {0} không thể giải mã ảnh: {0} @@ -4596,6 +4624,11 @@ theme Appearance Giao diện @msg Invalid panel layout; restored the default dock Bố cục bảng không hợp lệ; đã phục hồi dock mặc định @msg invalid parameters for `{cmd}`: {msg} tham số không hợp lệ cho `{cmd}`: {msg} @msg invalid PDF setting: {0} cài đặt PDF không hợp lệ: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller trang của bảng vẽ {n} có kích thước {size}, dài hơn giới hạn trang PDF 14.400 pt (200 in): trang được ghi với UserUnit là {unit}, nên các ứng dụng bỏ qua UserUnit sẽ hiển thị nó nhỏ đi bấy nhiêu lần +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in trang của bảng vẽ {n} có kích thước {size}, dài hơn giới hạn trang PDF 14.400 pt (200 in): các trang {label} được ghi không có UserUnit, theo đơn vị điểm, và các ứng dụng tuân theo giới hạn sẽ cắt trang ở 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 không có UserUnit, thứ mà trang dài hơn 14.400 pt (200 in) cần để giữ kích thước: tệp được ghi dưới dạng PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units trang của bảng vẽ {n} có kích thước {size}, quá dài và hẹp so với cạnh trang PDF từ 3 đến 14.400 đơn vị: trang được ghi với UserUnit {unit}, giữ cạnh ngắn từ 3 đơn vị trở lên, và các ứng dụng tuân theo giới hạn sẽ cắt cạnh dài ở 14.400 đơn vị +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard tệp {label} chỉ chứa số thực tối đa {max}, còn trang của bảng vẽ {n} dài {side} pt cần số lớn hơn: hãy chọn PDF 1.6 trở lên không theo tiêu chuẩn PDF/X, hoặc một bảng vẽ nhỏ hơn @msg invalid restored panel group nhóm bảng được phục hồi không hợp lệ @msg is not an image VectorCraft reads không phải ảnh mà VectorCraft đọc được @msg it ends inside a group or compound path nó kết thúc bên trong một nhóm hoặc đường dẫn phức @@ -4750,6 +4783,7 @@ theme Appearance Giao diện @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Đã tải “{name}”: bỏ qua {n} bước @msg not an action set file không phải tệp bộ hành động @msg the action set file is larger than 8 MiB tệp bộ hành động lớn hơn 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: tài liệu tham khảo sẽ lớn hơn {MAX_BYTES} byte @msg the action set file holds more than 1,000 actions tệp bộ hành động chứa hơn 1.000 hành động @msg the action set file needs a later version of VectorCraft tệp bộ hành động cần phiên bản VectorCraft mới hơn @msg an action in the action set file has more than 10,000 steps một hành động trong tệp bộ hành động có hơn 10.000 bước @@ -5119,6 +5153,11 @@ theme Appearance Giao diện @msg unknown parameter `{key}`; did you mean `{near}`? tham số không xác định `{key}`; ý bạn là `{near}`? @msg unknown parameter `{key}`; the command takes no parameters tham số không xác định `{key}`; lệnh này không nhận tham số @msg unknown parameter `{key}`; the command takes: {keys} tham số không xác định `{key}`; lệnh nhận: {keys} +@msg the params must be an object, not {got} các tham số phải là một đối tượng, không phải {got} +@msg unknown parameter `{path}`; the object takes no keys tham số không xác định `{path}`; đối tượng không nhận khóa nào +@msg unknown parameter `{path}`; it takes: {keys} tham số không xác định `{path}`; nhận: {keys} +@msg missing `{path}` thiếu `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` phải là {expected}, không phải {got} @msg unknown preference `{key}` tùy chọn không xác định `{key}` @msg unknown preset (one of {_1}) thiết lập sẵn không xác định (một trong {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) thiết lập sẵn không xác định `{name}` (high, medium, low hoặc thiết lập đã lưu: xem flattener.presets.list) @@ -5171,7 +5210,8 @@ theme Appearance Giao diện @msg {C}: no effect at index {from} {C}: không có hiệu ứng tại chỉ mục {from} @msg {depth}-bit PSD files in this colour mode can't be read tệp PSD {depth}-bit ở chế độ màu này không thể đọc được @msg {key} must be a finite coordinate {key} phải là tọa độ hữu hạn -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} hiện yêu cầu một đường dẫn hoặc đường dẫn phức. Hãy chuyển văn bản, hình ảnh và nhóm thành đường dẫn trước. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} hiện yêu cầu một đường dẫn, đường dẫn phức, văn bản, nhóm, hòa trộn hoặc thực thể ký hiệu. Hãy mở rộng các đối tượng khác trước. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} không thể tạo khối từ hình ảnh: hãy vector hóa ảnh trước bằng Đối tượng › Vector hóa ảnh › Tạo. @msg {label} produced an empty result {label} tạo ra kết quả trống @msg {label} requires a shape with at least two anchors {label} yêu cầu một hình dạng có ít nhất hai điểm neo @msg {label}: lost track of a shape's style {label}: mất dấu kiểu của hình dạng @@ -5534,6 +5574,20 @@ axis Y Axis Trục Y Show its progress, see Cancel and write log lines Hiển thị tiến độ, nhận biết yêu cầu hủy và ghi các dòng nhật ký Keep settings of its own Lưu cài đặt riêng Keep a cache of its own, which you can clear Lưu bộ nhớ đệm riêng mà bạn có thể xóa + Run these commands on the document: {ids} Chạy các lệnh này trên tài liệu: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” liệt kê `{id}` trong `commandAllowlist`, lệnh mà plug-in không được gọi +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: `commandAllowlist` của manifest không liệt kê lệnh này +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID hoặc đối số nằm ngoài bộ nhớ của mô-đun +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID hoặc đối số không phải UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: đối số không phải là đối tượng JSON +@msg only a filter with the usual budget declares `commandAllowlist` chỉ bộ lọc có ngân sách thông thường mới khai báo `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) lệnh gọi lệnh ({MAX_CALLS} lần gọi và {MAX_CALL_BYTES} byte mỗi lần chạy) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) kích thước lệnh gọi lệnh (vc_call `{shown}`: {len} byte, giới hạn {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` tối đa {MAX_ALLOWED_COMMANDS} lệnh trong `commandAllowlist` +@msg a plug-in may not call this command plug-in không được gọi lệnh này +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` cần quyền `commands`, và `commands` cần một `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` nêu `{shown}`, không phải ID lệnh hoặc được liệt kê hai lần Clear Plug-in Cache Xóa bộ nhớ đệm của plug-in @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} quyền `{permission}` cần API plug-in cấp {PROGRESS_API}: hãy đặt `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} mô-đun nhập `env.{name}` với kiểu khác với kiểu của máy chủ: kiểu của máy chủ là {signature} @@ -5623,6 +5677,11 @@ axis Y Axis Trục Y Button Nút Panel Bảng UI Frames Khung UI + Map Markers Đánh dấu bản đồ + Pin Ghim + Flag Cờ + Crosshair Tâm ngắm + Checkpoint Điểm kiểm tra Open Symbol Library Mở thư viện ký hiệu Save Symbol Library Lưu thư viện ký hiệu Save Symbol Library… Lưu thư viện ký hiệu… @@ -5677,6 +5736,11 @@ axis Y Axis Trục Y User Brush Library 9 Thư viện cọ người dùng 9 User Brush Library 10 Thư viện cọ người dùng 10 Art Ribbons Dải băng nghệ thuật + Zigzag Zigzag + Burst Ray Tia va chạm + Dash Trail Vệt đứt đoạn + Speed Line Đường tốc độ + Game Trails Vệt game Calligraphic Nibs Ngòi bút thư pháp Pattern Borders Viền họa tiết Scatter Shapes Hình phân tán @@ -5697,6 +5761,8 @@ axis Y Axis Trục Y # Align panel menu › Align to Glyph Bounds (#4231). Point Text Chữ điểm Area Text Chữ vùng +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds Đo chữ theo giới hạn glyph # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Hiện tùy chọn hút vào glyph Hide Snap to Glyph Options Ẩn tùy chọn hút vào glyph @@ -6264,3 +6330,8 @@ breakText Glyphs Glyph Align to Pixel Grid Căn theo lưới pixel @msg only paths and compound paths can be aligned to the pixel grid chỉ đường dẫn và đường dẫn phức mới căn theo lưới pixel được @msg side is left or right, not `{s}` side là left hoặc right, không phải `{s}` + Ignore All Bỏ qua tất cả + Add to Dictionary Thêm vào từ điển + No Suggestions Không có gợi ý + Edit Custom Dictionary Chỉnh sửa từ điển tùy chỉnh + Entry: Mục nhập: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d7b40b95d3..c62b176687 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -243,7 +243,6 @@ antiAlias Sharp 锐利 Update While Dragging 拖动时更新 Hide Video Rulers 隐藏视频标尺 Background Contents 背景内容 - Background Contents: 背景内容: Background: 背景: Backspace Backspace Bar Graph Tool 条形图工具 @@ -529,6 +528,7 @@ antiAlias Sharp 锐利 Coming soon — tracked in the parity plan 即将推出 — 在对标计划中跟踪 Command Click to Select Objects Behind 按住 Command 单击选择后方对象 Command Dialog 命令对话框 + Command API Reference 命令 API 参考 Community 社区 Compatibility: 兼容性: Compatible Gradient and Gradient Mesh Printing 兼容渐变和渐变网格打印 @@ -614,7 +614,6 @@ antiAlias Sharp 锐利 Couldn't {} {name}: {e} 无法{} {name}:{e} Create 创建 Create Clipping Mask 创建剪切蒙版 - Create Document 创建文档 Create from Guides 从参考线创建 Create from Selection 从选区创建 Create From: 创建自: @@ -1806,6 +1805,7 @@ file-filter Templates 模板 Lock (⌘2) 锁定 (⌘2) Lock Grid 锁定网格 Lock Guides 锁定参考线 + Lock Guides by Default 默认锁定参考线 Lock Slices 锁定切片 Lock Station Point 锁定基准点 Lossless (lossy WebP isn't available yet) 无失真 (尚未提供有失真的 WebP) @@ -2044,7 +2044,6 @@ file-filter Templates 模板 New Color Group… 新建颜色组… New Document Presets 新建文档预设 New file 新建文件 - New from Template 从模板新建 New from Template… 从模板新建… New Graphic Style 新建图形样式 New Graphic Style (Alt-click to name it) 新建图形样式 (Alt+点击可命名) @@ -2828,6 +2827,7 @@ digits Malayalam 马拉雅拉姆数字 Save PDF Preset 保存 PDF 预设 Save Perspective Grid Preset 存储透视网格预设 Save Preset 保存预设 + Save Document Preset 保存文档预设 Preset {number} 预设 {number} Save Preset… 存储预设… Save Print Preset 保存打印预设 @@ -3005,6 +3005,13 @@ digits Malayalam 马拉雅拉姆数字 Settings… 设置… Setup… 设置… Shadows and Glows 阴影与光晕 + Game HUD 游戏 HUD + Health Fill 生命 + Mana Glow 法力 + Damage Flash 伤害 + Quest Outline 任务 + Coin Shine 金币 + Boss Alert 首领 Shape 形状 Shape Builder 形状生成器 Shape Builder Regions 形状生成器区域 @@ -3374,7 +3381,6 @@ digits Malayalam 马拉雅拉姆数字 Template 模板 Templates 模板 Templates Folder 模板文件夹 - Templates… 模板… Text Displayed in Cell: 单元格中显示的文字: Text Export Options 文本导出选项 Text Fill & Stroke Color 文字填色和描边颜色 @@ -4314,6 +4320,11 @@ imageTrace Outline 轮廓 @msg artboard {0} does not exist 画板 {0} 不存在 @msg cannot read PDF: {0} 无法读取 PDF:{0} @msg invalid PDF setting: {0} PDF 设置无效:{0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller 画板 {n} 的页面为 {size},超过 PDF 的页面上限 14,400 pt (200 in):它以 UserUnit {unit} 写入,因此忽略 UserUnit 的应用会将其显示为缩小相应倍数 +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in 画板 {n} 的页面为 {size},超过 PDF 的页面上限 14,400 pt (200 in):{label} 页面不带 UserUnit,以点为单位写入,遵守上限的应用会将页面裁切为 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 没有 UserUnit,而长于 14,400 pt (200 in) 的页面需要它来保持尺寸:文件将以 PDF 1.6 写入 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units 画板 {n} 的页面为 {size},对 PDF 3 至 14,400 单位的页面边长而言过长过窄:以 UserUnit {unit} 写入,使短边保持 3 单位以上,遵守上限的应用会把长边裁到 14,400 单位 +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} 文件的实数最大为 {max},而画板 {n} 的页面长 {side} pt,需要更大的数:请选择不带 PDF/X 标准的 PDF 1.6 或更高版本,或使用更小的画板 @msg page {0} does not exist (the PDF has {1}) 页面 {0} 不存在 (该 PDF 有 {1} 页) @msg thumbnail: no page {n} (the file has 1) thumbnail:页面 {n} 不存在 (该文件有 1 页) @msg the PDF has no pages 该 PDF 没有页面 @@ -4510,6 +4521,7 @@ imageTrace Outline 轮廓 @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out 已载入“{name}”:已略过 {n} 个步骤 @msg not an action set file 不是动作组文件 @msg the action set file is larger than 8 MiB 动作组文件大于 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`:参考将大于 {MAX_BYTES} 字节 @msg the action set file holds more than 1,000 actions 动作组文件包含超过 1,000 个动作 @msg the action set file needs a later version of VectorCraft 动作组文件需要更高版本的 VectorCraft @msg an action in the action set file has more than 10,000 steps 动作组文件中有动作超过 10,000 个步骤 @@ -4526,6 +4538,28 @@ imageTrace Outline 轮廓 @msg the library item is damaged 库项目已损坏 @msg {_1} font families available 有 {_1} 个可用的字体系列 @msg {_1} has no {_2} style {_1} 没有 {_2} 样式 + Run 运行 + Run Script 运行脚本 + Stop Script 停止脚本 + Show External Script Warning 显示外部脚本警告 + A Script Is Running 脚本正在运行 + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 脚本可以更改打开的文档,并可通过其运行的命令写入文件。请只运行您信任的脚本。 + Do not show this warning again 不再显示此警告 + Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。 + This script has added a great many objects. Continue, or stop it and undo what it did? 此脚本已添加大量对象。要继续,还是停止并撤销其更改? +@msg Choose a .js or .jsx script 请选择 .js 或 .jsx 脚本 +@msg Ran {name} 已运行 {name} +@msg The script was stopped and its changes were undone 脚本已停止,其更改已撤销 +@msg a script is running: stop it or wait for it to finish 脚本正在运行:请停止它或等待其完成 +@msg this is a compiled script, which cannot be run; use its source text 这是已编译的脚本,无法运行;请使用其源文本 +@msg the script is not UTF-8 text 脚本不是 UTF-8 文本 +@msg the script is too large to run 脚本过大,无法运行 +@msg a drag or an undo group is open; finish it before running a script 拖动或撤销组尚未结束;请在运行脚本前完成 +@msg the script left a document that cannot be kept 脚本留下了无法保留的文档 +@msg the script's run is no longer available 脚本运行已不可用 +@msg a failed command changed undo steps that could not be put back, so the script was stopped 失败的命令更改了无法恢复的撤销步骤,因此脚本已停止 +@msg a recovery copy could not be written, so the script was not run 无法写入恢复副本,因此未运行脚本 +@msg Running a script 正在运行脚本 @msg Copied the script report 已复制脚本报告 @msg Exported {path} 已导出 {path} @msg no CSS to copy: select objects with CSS of their own 没有可复制的 CSS:请选择带有自身 CSS 的对象 @@ -5457,7 +5491,8 @@ lighting Light 光源 Bevel both sides 双面斜角 Presets 预设 @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. 一个对象只能应用一种 3D 效果。请编辑现有效果的选项,或先将其移去。 -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label}目前需要路径或复合路径。请先将文字、图像和编组转换为路径。 +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}目前需要路径、复合路径、文字、编组、混合或符号实例。请先扩展其他对象。 +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}无法从图像生成立体:请先使用“对象 › 图像描摹 › 创建”进行描摹。 @msg {label} requires a shape with at least two anchors {label}需要至少有两个锚点的形状 @msg The shape is too complex for a 3D effect 形状过于复杂,无法应用 3D 效果 @msg The 3D surface is too complex; simplify the shape 3D 表面过于复杂;请简化形状 @@ -5465,6 +5500,11 @@ lighting Light 光源 @msg unknown parameter `{key}`; did you mean `{near}`? 未知参数 `{key}`;您是否想输入 `{near}`? @msg unknown parameter `{key}`; the command takes no parameters 未知参数 `{key}`;该命令没有参数 @msg unknown parameter `{key}`; the command takes: {keys} 未知参数 `{key}`;该命令接受:{keys} +@msg the params must be an object, not {got} 参数必须是对象,而不是 {got} +@msg unknown parameter `{path}`; the object takes no keys 未知参数 `{path}`;该对象不接受任何键 +@msg unknown parameter `{path}`; it takes: {keys} 未知参数 `{path}`;它接受:{keys} +@msg missing `{path}` 缺少 `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` 必须是 {expected},而不是 {got} Load EPS into Clipboard 将 EPS 载入剪贴板 @msg an image of {w} × {h} pixels is too large to draw {w} × {h} 像素的图像过大,无法绘制 @msg the JPEG XL file is cut short JPEG XL 文件不完整 @@ -5774,6 +5814,20 @@ axis Y Axis Y 轴 Show its progress, see Cancel and write log lines 显示进度、检测取消请求并写入日志行 Keep settings of its own 保存自己的设置 Keep a cache of its own, which you can clear 保存自己的缓存,您可以清除它 + Run these commands on the document: {ids} 在文档上运行这些命令:{ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”在 `commandAllowlist` 中列出了增效工具不能调用的 `{id}` +@msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`:清单的 `commandAllowlist` 未列出它 +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`:ID 或参数位于模块内存之外 +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`:ID 或参数不是 UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`:参数不是 JSON 对象 +@msg only a filter with the usual budget declares `commandAllowlist` 只有使用通常预算的滤镜才能声明 `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) 命令调用(每次运行 {MAX_CALLS} 次调用和 {MAX_CALL_BYTES} 字节) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) 命令调用大小(vc_call `{shown}`:{len} 字节,上限 {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist` 中最多 {MAX_ALLOWED_COMMANDS} 个命令 +@msg a plug-in may not call this command 增效工具不能调用此命令 +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` 需要权限 `commands`,而 `commands` 需要 `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` 列出的 `{shown}` 不是命令 ID,或列出了两次 Clear Plug-in Cache 清除增效工具缓存 @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} 权限 `{permission}` 需要增效工具 API 级别 {PROGRESS_API}:请设置 `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} 模块以与宿主不同的类型导入 `env.{name}`:宿主的类型为 {signature} @@ -5863,6 +5917,11 @@ axis Y Axis Y 轴 Button 按钮 Panel 面板 UI Frames UI 框架 + Map Markers 地图标记 + Pin 图钉 + Flag 旗帜 + Crosshair 准星 + Checkpoint 检查点 Open Symbol Library 打开符号库 Save Symbol Library 保存符号库 Save Symbol Library… 保存符号库… @@ -5917,6 +5976,11 @@ axis Y Axis Y 轴 User Brush Library 9 用户画笔库 9 User Brush Library 10 用户画笔库 10 Art Ribbons 艺术丝带 + Zigzag 锯齿 + Burst Ray 冲击射线 + Dash Trail 虚线轨迹 + Speed Line 速度线 + Game Trails 游戏轨迹 Calligraphic Nibs 书法笔尖 Pattern Borders 图案边框 Scatter Shapes 散布形状 @@ -5937,6 +6001,8 @@ axis Y Axis Y 轴 # Align panel menu › Align to Glyph Bounds (#4231). Point Text 点文字 Area Text 区域文字 +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds 按字形边界度量文字 # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options 显示靠齐字符选项 Hide Snap to Glyph Options 隐藏靠齐字符选项 @@ -6503,3 +6569,5 @@ breakText Glyphs 字形 Align to Pixel Grid 对齐像素网格 @msg only paths and compound paths can be aligned to the pixel grid 只有路径和复合路径可以对齐像素网格 @msg side is left or right, not `{s}` side 应为 left 或 right,而不是 `{s}` + Edit Custom Dictionary 编辑自定义词典 + Entry: 条目: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9e27d9c7b7..0b3a21250c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -256,7 +256,6 @@ font-technology Variable 可變 Update While Dragging 拖曳時更新 Hide Video Rulers 隱藏視訊尺標 Background Contents 背景內容 - Background Contents: 背景內容: Background: 背景: Backspace Backspace Bar Graph Tool 橫條圖工具 @@ -545,6 +544,7 @@ font-technology Variable 可變 Coming soon — tracked in the parity plan 即將推出 — 已列入功能對等計畫 Command Click to Select Objects Behind Cmd 加按一下可選取後方物件 Command Dialog 指令對話框 + Command API Reference 指令 API 參考 Community 社群 Compatibility: 相容性: Compatible Gradient and Gradient Mesh Printing 相容的漸層與漸層網格列印 @@ -631,7 +631,6 @@ font-technology Variable 可變 Couldn't {} {name}: {e} 無法{} {name}:{e} Create 建立 Create Clipping Mask 建立剪裁遮色片 - Create Document 建立文件 Create from Guides 從參考線建立 Create from Selection 從選取範圍建立 Create From: 建立來源: @@ -2159,6 +2158,11 @@ file-filter Templates 範本 @msg artboard {0} does not exist 工作區域 {0} 不存在 @msg cannot read PDF: {0} 無法讀取 PDF:{0} @msg invalid PDF setting: {0} PDF 設定無效:{0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller 工作區域 {n} 的頁面為 {size},超過 PDF 的頁面上限 14,400 pt (200 in):它以 UserUnit {unit} 寫入,因此忽略 UserUnit 的應用程式會將其顯示為縮小相應倍數 +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in 工作區域 {n} 的頁面為 {size},超過 PDF 的頁面上限 14,400 pt (200 in):{label} 頁面不含 UserUnit,以點為單位寫入,遵守上限的應用程式會將頁面裁切為 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 沒有 UserUnit,而長於 14,400 pt (200 in) 的頁面需要它來保持尺寸:檔案將以 PDF 1.6 寫入 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units 工作區域 {n} 的頁面為 {size},對 PDF 3 至 14,400 單位的頁面邊長而言過長過窄:以 UserUnit {unit} 寫入,使短邊保持 3 單位以上,遵守上限的應用程式會把長邊裁到 14,400 單位 +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} 檔案的實數最大為 {max},而工作區域 {n} 的頁面長 {side} pt,需要更大的數:請選擇不含 PDF/X 標準的 PDF 1.6 或更新版本,或使用較小的工作區域 @msg page {0} does not exist (the PDF has {1}) 頁面 {0} 不存在 (此 PDF 有 {1} 頁) @msg the PDF has no pages 此 PDF 沒有頁面 @msg the PDF is password-protected: give its password 此 PDF 受密碼保護:請提供其密碼 @@ -2354,6 +2358,7 @@ file-filter Templates 範本 @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out 已載入「{name}」:已略過 {n} 個步驟 @msg not an action set file 不是動作組檔案 @msg the action set file is larger than 8 MiB 動作組檔案大於 8 MiB +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`:參考將大於 {MAX_BYTES} 位元組 @msg the action set file holds more than 1,000 actions 動作組檔案包含超過 1,000 個動作 @msg the action set file needs a later version of VectorCraft 動作組檔案需要較新版本的 VectorCraft @msg an action in the action set file has more than 10,000 steps 動作組檔案中有動作超過 10,000 個步驟 @@ -2370,6 +2375,28 @@ file-filter Templates 範本 @msg the library item is damaged 資料庫項目已損毀 @msg {_1} font families available 有 {_1} 個可用的字體家族 @msg {_1} has no {_2} style {_1} 沒有 {_2} 樣式 + Run 執行 + Run Script 執行指令碼 + Stop Script 停止指令碼 + Show External Script Warning 顯示外部指令碼警告 + A Script Is Running 指令碼正在執行 + A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 指令碼可以變更開啟的文件,並可透過其執行的命令寫入檔案。請只執行您信任的指令碼。 + Do not show this warning again 不再顯示此警告 + Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。 + This script has added a great many objects. Continue, or stop it and undo what it did? 此指令碼已新增大量物件。要繼續,還是停止並還原其變更? +@msg Choose a .js or .jsx script 請選擇 .js 或 .jsx 指令碼 +@msg Ran {name} 已執行 {name} +@msg The script was stopped and its changes were undone 指令碼已停止,其變更已還原 +@msg a script is running: stop it or wait for it to finish 指令碼正在執行:請停止它或等待其完成 +@msg this is a compiled script, which cannot be run; use its source text 這是已編譯的指令碼,無法執行;請使用其原始文字 +@msg the script is not UTF-8 text 指令碼不是 UTF-8 文字 +@msg the script is too large to run 指令碼過大,無法執行 +@msg a drag or an undo group is open; finish it before running a script 拖曳或還原群組尚未結束;請在執行指令碼前完成 +@msg the script left a document that cannot be kept 指令碼留下了無法保留的文件 +@msg the script's run is no longer available 指令碼執行已無法使用 +@msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗的命令變更了無法還原的復原步驟,因此指令碼已停止 +@msg a recovery copy could not be written, so the script was not run 無法寫入復原副本,因此未執行指令碼 +@msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 @msg Exported {path} 已匯出 {path} @msg no CSS to copy: select objects with CSS of their own 沒有可複製的 CSS:請選取有自己 CSS 的物件 @@ -2800,6 +2827,7 @@ file-filter Templates 範本 Lock (⌘2) 鎖定 (⌘2) Lock Grid 鎖定格點 Lock Guides 鎖定參考線 + Lock Guides by Default 預設鎖定參考線 Lock Others 鎖定其他 Lock Slices 鎖定切片 Lock Station Point 鎖定基準點 @@ -3064,7 +3092,6 @@ file-filter Templates 範本 New Color Group… 新增顏色群組… New Document Presets 新增文件預設集 New file 新增檔案 - New from Template 從範本新增 New from Template… 從範本新增… New Graphic Style 新增繪圖樣式 New Graphic Style (Alt-click to name it) 新增繪圖樣式 (Alt+點擊可命名) @@ -3861,6 +3888,7 @@ digits Malayalam 馬來亞拉姆數字 Save PDF Preset 儲存 PDF 預設集 Save Perspective Grid Preset 儲存透視格點預設集 Save Preset 儲存預設集 + Save Document Preset 儲存文件預設集 Preset {number} 預設集 {number} Save Preset… 儲存預設集… Save Print Preset 儲存列印預設集 @@ -4067,6 +4095,13 @@ digits Malayalam 馬來亞拉姆數字 Settings… 設定… Setup… 設定… Shadows and Glows 陰影與光暈 + Game HUD 遊戲 HUD + Health Fill 生命 + Mana Glow 魔力 + Damage Flash 傷害 + Quest Outline 任務 + Coin Shine 金幣 + Boss Alert 首領 Shape 形狀 Shape Builder 形狀建立 Shape Builder Regions 形狀建立區域 @@ -4438,7 +4473,6 @@ digits Malayalam 馬來亞拉姆數字 Template 範本 Templates 範本 Templates Folder 範本資料夾 - Templates… 範本… Text Displayed in Cell: 儲存格中顯示的文字: Text Export Options 文字匯出選項 Text Fill & Stroke Color 文字填色與筆畫顏色 @@ -5283,7 +5317,8 @@ lighting Light 光源 Bevel both sides 雙面斜角 Presets 預設集 @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. 一個物件只能套用一種 3D 效果。請編輯現有效果的選項,或先將其移除。 -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label}目前需要路徑或複合路徑。請先將文字、影像和群組轉換為路徑。 +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}目前需要路徑、複合路徑、文字、群組、漸變或符號範例。請先展開其他物件。 +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}無法從影像建立立體:請先使用「物件 › 影像描圖 › 製作」描圖。 @msg {label} requires a shape with at least two anchors {label}需要至少有兩個錨點的形狀 @msg The shape is too complex for a 3D effect 形狀過於複雜,無法套用 3D 效果 @msg The 3D surface is too complex; simplify the shape 3D 表面過於複雜;請簡化形狀 @@ -5291,6 +5326,11 @@ lighting Light 光源 @msg unknown parameter `{key}`; did you mean `{near}`? 未知的參數 `{key}`;您是指 `{near}` 嗎? @msg unknown parameter `{key}`; the command takes no parameters 未知的參數 `{key}`;此指令沒有參數 @msg unknown parameter `{key}`; the command takes: {keys} 未知的參數 `{key}`;此指令接受:{keys} +@msg the params must be an object, not {got} 參數必須是物件,而不是 {got} +@msg unknown parameter `{path}`; the object takes no keys 未知的參數 `{path}`;此物件不接受任何鍵 +@msg unknown parameter `{path}`; it takes: {keys} 未知的參數 `{path}`;它接受:{keys} +@msg missing `{path}` 未提供 `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` 必須是 {expected},而不是 {got} Load EPS into Clipboard 將 EPS 載入剪貼簿 @msg an image of {w} × {h} pixels is too large to draw {w} × {h} 像素的影像過大,無法繪製 @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}:不是 PNG、JPEG、WebP、TIFF 或 BMP 影像 @@ -5571,6 +5611,20 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 顯示進度、偵測取消要求並寫入記錄行 Keep settings of its own 保存自己的設定 Keep a cache of its own, which you can clear 保存自己的快取,您可以清除它 + Run these commands on the document: {ids} 在文件上執行這些指令:{ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」在 `commandAllowlist` 中列出了增效模組不能呼叫的 `{id}` +@msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`:資訊清單的 `commandAllowlist` 未列出它 +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`:ID 或引數位於模組記憶體之外 +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`:ID 或引數不是 UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`:引數不是 JSON 物件 +@msg only a filter with the usual budget declares `commandAllowlist` 只有使用一般預算的濾鏡才能宣告 `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) 指令呼叫(每次執行 {MAX_CALLS} 次呼叫和 {MAX_CALL_BYTES} 位元組) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) 指令呼叫大小(vc_call `{shown}`:{len} 位元組,上限 {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist` 中最多 {MAX_ALLOWED_COMMANDS} 個指令 +@msg a plug-in may not call this command 增效模組不能呼叫此指令 +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` 需要權限 `commands`,而 `commands` 需要 `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` 列出的 `{shown}` 不是指令 ID,或列出了兩次 Clear Plug-in Cache 清除增效模組快取 @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} 權限 `{permission}` 需要增效模組 API 層級 {PROGRESS_API}:請設定 `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} 模組以與主機不同的類型匯入 `env.{name}`:主機的類型為 {signature} @@ -5660,6 +5714,11 @@ axis Y Axis Y 軸 Button 按鈕 Panel 面板 UI Frames UI 框架 + Map Markers 地圖標記 + Pin 圖釘 + Flag 旗幟 + Crosshair 準星 + Checkpoint 檢查點 Open Symbol Library 開啟符號資料庫 Save Symbol Library 儲存符號資料庫 Save Symbol Library… 儲存符號資料庫… @@ -5714,6 +5773,11 @@ axis Y Axis Y 軸 User Brush Library 9 使用者筆刷資料庫 9 User Brush Library 10 使用者筆刷資料庫 10 Art Ribbons 藝術緞帶 + Zigzag 鋸齒 + Burst Ray 衝擊射線 + Dash Trail 虛線軌跡 + Speed Line 速度線 + Game Trails 遊戲軌跡 Calligraphic Nibs 書法筆尖 Pattern Borders 圖樣邊框 Scatter Shapes 散佈形狀 @@ -5734,6 +5798,8 @@ axis Y Axis Y 軸 # Align panel menu › Align to Glyph Bounds (#4231). Point Text 點狀文字 Area Text 區域文字 +# Transform panel menu › Measure Type by Glyph Bounds. + Measure Type by Glyph Bounds 依字符邊界測量文字 # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options 顯示靠齊字符選項 Hide Snap to Glyph Options 隱藏靠齊字符選項 @@ -6301,3 +6367,5 @@ breakText Glyphs 字符 Align to Pixel Grid 對齊像素格點 @msg only paths and compound paths can be aligned to the pixel grid 只有路徑和複合路徑可以對齊像素格點 @msg side is left or right, not `{s}` side 應為 left 或 right,而不是 `{s}` + Edit Custom Dictionary 編輯自訂字典 + Entry: 項目: diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index a75171ae36..50f13e695e 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -172,10 +172,13 @@ pub fn install_plugin(app: &mut VectorcraftApp, p: &Value) -> Result String { +/// What permission `name` lets a plug-in do, in plain words in the UI language, with the ids of +/// the `commands` it may call for `commands`; a name the app doesn't know is shown as it is. +fn permission_words(name: &str, commands: &[String]) -> String { let words = match permissions::Permission::parse(name) { + Some(permissions::Permission::Commands) => { + return crate::i18n::fmt(tl!("Run these commands on the document: {ids}"), &[("ids", &commands.join(", "))]); + } Some(permissions::Permission::DocRead) => tl!("Read the objects it is given"), Some(permissions::Permission::DocWrite) => tl!("Change, add and delete objects in the document"), Some(permissions::Permission::State) => tl!("Keep data of its own with the document"), @@ -244,7 +247,11 @@ pub fn install_module(app: &mut VectorcraftApp, module: Value) -> Result = info["commandAllowlist"] + .as_array() + .map(|ids| ids.iter().filter_map(Value::as_str).map(|id| permissions::display_text(id, permissions::MAX_SHOWN_FIELD)).collect()) + .unwrap_or_default(); + lines.extend(asked.iter().filter_map(Value::as_str).map(|p| format!("• {}", permission_words(p, &commands)))); paragraphs.push(lines.join("\n")); install["grant"] = Value::Array(asked.clone()); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 03acb7597e..932520b184 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -65,6 +65,7 @@ pub mod print; pub mod recovery; pub mod render_worker; pub mod screen_color; +pub mod script_runs; mod scrub; pub mod shortcut_editor; pub mod shortcuts; @@ -186,6 +187,8 @@ pub struct VectorcraftApp { frame_rate: frame_rate::FrameRate, /// Canvas rect of the last frame (screen points), for control-channel coordinate mapping. pub canvas_rect: Option, + /// An unfinished control-channel Rotate View gesture, kept only for this app instance. + pub(crate) control_rotate_press: Option, /// Hover position in document coordinates. pub hover_doc: Option, /// System clipboard: SVG to publish next frame, the last SVG we published (so pasting it back diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index c57a216370..cbc1536fc3 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -127,7 +127,7 @@ pub(super) fn render_items(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Ite ui.menu_button(label, |ui| { widgets::menu_scroll(ui, |ui| { ui.set_min_width(200.0); - render_items(app, ui, children, checks, clicked); + render_items(app, ui, children, checks || only_toggles(app, children), clicked); }); }); } @@ -136,6 +136,13 @@ pub(super) fn render_items(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Ite } } +/// Whether every item of a submenu can be on or off: a menu drawn without check marks (the canvas +/// context menu) still shows them there, since its label alone can't say whether it is on. +fn only_toggles(app: &VectorcraftApp, items: &[Item]) -> bool { + let mut rows = items.iter().filter_map(|it| entry(app, it)).filter(|e| !matches!(e, Entry::Sep)).peekable(); + rows.peek().is_some() && rows.all(|e| matches!(e, Entry::Item(r) if r.checked.is_some())) +} + /// One menu item: its label (with a check mark, or the room for one, under `checks`), its shortcut, /// and Type › Font's samples. fn render_row(app: &VectorcraftApp, ui: &mut egui::Ui, row: &Row, checks: bool, clicked: &mut Option<(String, Value)>) { diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index bc191593a8..abf43a3584 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -14,7 +14,8 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { let roots: Vec<&vectorcraft_doc::Node> = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).collect(); let any = |f: fn(&NodeKind) -> bool| roots.iter().any(|n| f(&n.kind)); let several = roots.len() >= 2; - let mut v = vec![c("Undo", "edit.undo"), c("Redo", "edit.redo"), Sep]; + let mut v = spelling_items(app); + v.extend([c("Undo", "edit.undo"), c("Redo", "edit.redo"), Sep]); if st.isolation.is_some() { v.extend([c("Exit Isolation Mode", "object.exitIsolation"), Sep]); } @@ -91,6 +92,10 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { // The paragraphs of the selected type, or those the Type tool's selection touches. if crate::panels::character::text_style(app).is_some() { v.push(sub("Bullets and Numbering", vec![c("Apply Bullets", "type.applyBullets"), c("Apply Numbers", "type.applyNumbers")])); + // A right-click on type turns Auto Spell Check on or off, as Edit › Spelling does, per + // the public [Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html) + // page. Its submenu holds only toggles, so it shows the check mark (`render_items`). + v.push(sub("Spelling", vec![c("Auto Spell Check", "edit.autoSpellCheck")])); } v.extend([c("Make Guides", "view.guides.make"), Sep, sub("Transform", transform_items())]); if intertwine.is_none() { @@ -108,6 +113,39 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { prune(app, v) } +/// A right-click on a word Auto Spell Check underlined ([`crate::state::UiState::context_spelling`]): +/// the words its dictionary suggests, each replacing it (`text.editRange`, one undo step; +/// `spelling_item_label` shows the word), or No Suggestions; then Ignore All +/// (`text.spelling.ignoreAll`) and Add to Dictionary (`text.spelling.addWord`), as the public +/// [Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html) +/// page lists them. Nothing for another right-click, or after the document or the word changed. +fn spelling_items(app: &VectorcraftApp) -> Vec { + let Some(st) = app.session.active() else { return vec![] }; + let Some(w) = app.ui.context_spelling.as_ref().filter(|w| w.uid == st.uid) else { return vec![] }; + let still = match st.doc.node(w.id).map(|n| &n.kind) { + Some(vectorcraft_doc::NodeKind::Text(t)) => t.plain_text().get(w.start..w.end) == Some(w.word.as_str()), + _ => false, + }; + if !still { + return vec![]; + } + let mut v: Vec = w + .suggestions + .iter() + .map(|s| cp("Suggestion", "text.editRange", json!({ "id": w.id.0, "start": w.start, "end": w.end, "insert": s }))) + .collect(); + if v.is_empty() { + v.push(Item::Header("No Suggestions")); + } + v.extend([ + Sep, + cp("Ignore All", "text.spelling.ignoreAll", json!({ "word": w.word })), + cp("Add to Dictionary", "text.spelling.addWord", json!({ "word": w.word })), + Sep, + ]); + v +} + /// The locked objects under the pointer at the right-click, each unlocked as the Layers panel's /// lock column does. `unlock_item_label` shows each object's name. fn unlock_items(app: &VectorcraftApp) -> Vec { @@ -231,7 +269,8 @@ fn prune(app: &VectorcraftApp, items: Vec) -> Vec { pub fn context_menu_body(app: &VectorcraftApp, ui: &mut egui::Ui, clicked: &mut Option<(String, Value)>) { widgets::menu_scroll(ui, |ui| { ui.set_min_width(200.0); - // Its toggles already say what they do (Show Rulers, Hide Guides): no check-mark gutter. + // Its toggles already say what they do (Show Rulers, Hide Guides): no check-mark gutter, + // except in a submenu of toggles alone (Spelling › Auto Spell Check). render_items(app, ui, &context_items(app), false, clicked); }); } diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 36811ba4ca..5d203fe875 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -1,6 +1,6 @@ use super::context::context_items; use super::invoke::click_target; -use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut, unlock_item_label}; +use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut, spelling_item_label, unlock_item_label}; use super::state::{shortcut_of, shown_state}; use super::tree::menu_tree_named; use super::{Entry, Item, Serialize, Value, VectorcraftApp}; @@ -51,6 +51,7 @@ pub fn entry<'a>(app: &VectorcraftApp, it: &'a Item) -> Option> { source: label, label: effect_item_label(id, p) .or_else(|| unlock_item_label(app, id, p, crate::i18n::current())) + .or_else(|| spelling_item_label(id, p)) .unwrap_or_else(|| display_label(app, id, label)) .into(), shortcut: item_shortcut(id, p), @@ -129,7 +130,9 @@ fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Ve let Some((enabled, _)) = shown_state(app, id, p) else { continue }; out.push(MenuEntry { path: path.clone(), - label: unlock_item_label(app, id, p, crate::i18n::Lang::EN).unwrap_or_else(|| dynamic_label(app, id, l)), + label: unlock_item_label(app, id, p, crate::i18n::Lang::EN) + .or_else(|| spelling_item_label(id, p)) + .unwrap_or_else(|| dynamic_label(app, id, l)), command: Some(id.to_string()), params: p.clone(), enabled, diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7b3adaffe5..c37a8268c2 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -287,6 +287,13 @@ fn open_view_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { } return true; } + // Edit Custom Dictionary…: the custom dictionary's words in a list, to add, delete or change. + if id == crate::dialogs::custom_dictionary::COMMAND && p.as_object().is_none_or(|o| o.is_empty()) { + if let Err(e) = crate::dialogs::custom_dictionary::open(app) { + app.status(e); + } + return true; + } // Edit Views…: the saved views in a list, to rename or delete. if id == "view.saved.edit" && p.as_object().is_none_or(|o| o.is_empty()) { if let Err(e) = crate::dialogs::edit_views::open(app) { diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index e26d0bdec8..148368a279 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -214,6 +214,12 @@ pub(super) fn unlock_item_label(app: &VectorcraftApp, id: &str, p: &Value, lang: Some(crate::panels::layers::shown_name(app, n, lang)) } +/// A context menu suggestion's label: the word it puts in (`text.editRange {insert}`), as it is, +/// untranslated ([`super::context`]'s `spelling_items`). +pub(super) fn spelling_item_label(id: &str, p: &Value) -> Option { + (id == "text.editRange").then(|| p.get("insert")?.as_str().map(str::to_string)).flatten() +} + /// The shortcut a menu item shows: its command's (items without params), a panel's for the /// Window menu's `window.panel {panel}` items, an effect's for the Effect menu's items, or a filter /// plug-in's for Object › Plug-ins' `plugin.dialog {id}` items. @@ -235,6 +241,9 @@ pub fn item_shortcut(id: &str, p: &Value) -> Option<&'static str> { /// Labels only the canvas context menu ([`context_items`]) shows, so the catalog tests can insist /// every one of them is translated (a test checks the list against the menu). pub const CONTEXT_LABELS: &[&str] = &[ + "Ignore All", + "Add to Dictionary", + "No Suggestions", "Isolate Selected Group", "Exit Isolation Mode", "Lock Artboards", diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 9ec98faae7..98d4da9895 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -206,9 +206,13 @@ fn run_ui_part2(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { - crate::panel_docking::reveal_panel(app, "separations").and_then(|_| app.session.execute(id, p).map_err(|e| e.to_string())) + crate::panel_docking::reveal_panel(app, "separations").and_then(|_| { + app.ui.color_settings_scroll = true; + app.session.execute(id, p).map_err(|e| e.to_string()) + }) } // Outline or Preview is a setting of the active document's view. "view.outline" => match app.view_mut() { @@ -969,6 +973,7 @@ fn run_ui_part13(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(crate::trace_runs::cancel_all(app)), "imageTrace.hideRuns" => Ok(crate::trace_runs::hide_all(app)), "ui.checkScript" => crate::dialogs::script_check::command(app, p), + "ui.runScript" => crate::dialogs::script_run::command(app, p), "ui.perspectiveGridDialog" => crate::dialogs::perspective_grid::open(app), "ui.perspectivePresetsDialog" => { crate::dialogs::perspective_presets::open(app, s("selected").as_deref()); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index c51f36e7de..97651d0740 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -1,6 +1,6 @@ use super::slots::{PERSPECTIVE_SLOTS, RECENT_FONT_IDS, RECENT_IDS, SAVED_SELECTION_IDS, SAVED_VIEW_IDS}; use super::submenus::{INSERT_BREAK, INSERT_SPECIAL, INSERT_WHITESPACE, PATH_EFFECTS, TYPE_SIZES, effect_menu, font_items, insert_items}; -use super::{Item, Sep, c, cp, json, sub, todo, todos}; +use super::{Item, Sep, c, cp, json, sub, todos}; /// The in-window and native menu tree. The in-window bar skips the VectorCraft menu (see /// `menu_bar`); the native Mac bar is composed from the whole tree (see `native_menu`). @@ -62,7 +62,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Export Selection…", "file.exportSelection"), Sep, c("Package…", "ui.packageDialog"), - sub("Scripts", vec![c("Check Script…", "ui.checkScript"), todos("Other Script…", "Cmd+F12")]), + sub("Scripts", vec![c("Check Script…", "ui.checkScript"), c("Other Script…", "ui.runScript")]), Sep, c("Document Setup…", "file.documentSetup"), sub( @@ -97,10 +97,10 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { Sep, cp("Find and Replace…", "edit.findReplace", json!({"find": "", "replace": "", "matchCase": false, "wholeWord": false})), cp("Find Next", "edit.findNext", json!({"find": ""})), - sub( - "Spelling", - vec![c("Auto Spell Check", "edit.autoSpellCheck"), todos("Check Spelling…", "Cmd+I"), todo("Edit Custom Dictionary…")], - ), + sub("Spelling", vec![c("Auto Spell Check", "edit.autoSpellCheck"), todos("Check Spelling…", "Cmd+I")]), + // Edit › Edit Custom Dictionary…, beside Spelling, on the public Check and correct + // spelling page. + c("Edit Custom Dictionary…", crate::dialogs::custom_dictionary::COMMAND), Sep, sub( "Edit Colors", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 3b314f8335..fb78fc2075 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1520,6 +1520,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the progress window of the Image Traces running in the background; they go on, shown in the status bar → {hidden: n}", ), + ( + "ui.runScript", + "Other Script…", + "Cmd+F12", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + ), ( "ui.checkScript", "Check Script…", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index a74f47b6a9..3447cd1e15 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -949,6 +949,7 @@ impl Transaction { } if let Some(saved) = &location.group { apply(&mut candidate, Action::ResizeGroup { panel: panel.clone(), height: saved.height })?; + apply(&mut candidate, Action::ResizeFlyoutWidth { panel: panel.clone(), width: saved.flyout_width })?; apply(&mut candidate, Action::SetMinimized { panel: panel.clone(), minimized: saved.minimized })?; } self.workspace.layout = candidate; @@ -1087,6 +1088,7 @@ fn known(action: &Action) -> bool { | Action::SetIconic { panel, .. } | Action::ResizeColumn { panel, .. } | Action::ResizeGroup { panel, .. } + | Action::ResizeFlyoutWidth { panel, .. } | Action::ResizeIconic { panel, .. } | Action::SetNative { panel, .. } | Action::SetMonitor { panel, .. } => registered(panel), @@ -1169,7 +1171,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { if let Some(panel) = app.dock_rt.raise.take() { dock = dock.raise_panel(panel); } - let mut output = dock.show_content(ui, &layout, &style, &mut PanelContent { app: &mut *app }); + let mut output = dock.show_content(ui, &layout, &style, &mut PanelContent { app: &mut *app, layout: &layout }); app.dock_rt.space = craft_ui::docking::float_space(&ctx, area); if let Some(panel) = output.focused.take() { app.dock_rt.focused = Some(panel); @@ -1343,9 +1345,11 @@ pub(crate) fn floating_size(panel: &str) -> egui::Vec2 { /// The panels' content, labels and icons. struct PanelContent<'a> { app: &'a mut VectorcraftApp, + layout: &'a Layout, } impl craft_ui::docking::DockContent for PanelContent<'_> { + /// Draw a registered panel body, fitting untouched flyouts and pinning sized panels' footers. fn body(&mut self, ui: &mut egui::Ui, id: &String) { if id == CANVAS { crate::toolbar::show_beside_canvas(self.app, ui); @@ -1364,15 +1368,23 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { } let width = ui.available_width(); let height = (ui.available_height() - 20.0).max(0.0); - if DockTab::from_id(id).is_some() { - crate::dock::panel_body(self.app, ui, id, width, height); - } else { - // Shrinking to the content's height lets craft-ui fit a float or flyout to it. - crate::widgets::panel_scroll(ui, egui::ScrollArea::vertical().id_salt(("shared-panel-body", id)).auto_shrink([false, true]), |ui| { - let width = ui.available_width(); - crate::dock::panel_body(self.app, ui, id, width, height) - }); - } + let fitted = in_iconic_column(self.layout, id) + && self.layout.location(id).ok().and_then(|location| location.group).is_none_or(|group| group.height.is_none()); + // Properties embeds other panels as sections, so their local button rows + // must remain beside those sections rather than pinning to the outer panel. + let bottom = (!fitted && id != "properties").then_some(back.bottom() - 10.0); + let info = egui::UiStackInfo::default().with_tag_value(crate::widgets::PANEL_FOOTER, bottom); + ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| { + if DockTab::from_id(id).is_some() { + crate::dock::panel_body(self.app, ui, id, width, height); + } else { + // Shrinking to the content's height lets craft-ui fit a float or flyout to it. + crate::widgets::panel_scroll(ui, egui::ScrollArea::vertical().id_salt(("shared-panel-body", id)).auto_shrink([false, true]), |ui| { + let width = ui.available_width(); + crate::dock::panel_body(self.app, ui, id, width, height) + }); + } + }); if field_had_keyboard { keep_field_ending_keys(ui); } diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index abb7f2a63f..db1e6be36c 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -1054,8 +1054,9 @@ fn wheel_over_a_floating_character_font_field_changes_the_font() { h.host.borrow_mut().child_overlay = None; h.frame(vec![]); + h.host.borrow_mut().time += crate::widgets::WHEEL_STREAM_GAP; h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ - Event::PointerMoved(pointer), + Event::PointerMoved(pointer + vec2(1.0, 0.0)), Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, -1.0), @@ -1087,8 +1088,9 @@ fn wheel_over_a_floating_character_font_field_changes_the_font() { h.host.borrow_mut().child_transparent_overlay = None; h.host.borrow_mut().child_pass_through_overlay = Some((viewport, field.expand(10.0))); h.frames(2); + h.host.borrow_mut().time += crate::widgets::WHEEL_STREAM_GAP; h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ - Event::PointerMoved(pointer), + Event::PointerMoved(pointer + vec2(2.0, 0.0)), Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, -1.0), @@ -1453,6 +1455,75 @@ fn wheel_events_on_both_sides_of_an_overlay_are_checked_separately() { assert_eq!(h.ctx.input_for(viewport, |input| input.pointer.latest_pos()), Some(clear)); } +#[test] +fn a_wheel_stream_that_began_outside_a_floating_font_field_stays_outside() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let on = pos2(field.min.x + 4.0, field.center().y); + let off = pos2(field.min.x + 4.0, field.max.y + 60.0); + let turn = Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([Event::PointerMoved(off), turn.clone(), Event::PointerMoved(on), turn]); + h.frames(3); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn a_wheel_stream_leaves_a_floating_font_field_that_an_overlay_covered_before_its_queued_turn() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + let turn = Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), false)); + h.frames(2); + let field_layer = crate::font_menu::wheel_field_layer_for_test(&h.ctx, viewport, pointer).expect("the font field layer"); + let raise_field = |h: &mut Harness| { + h.host.borrow_mut().child_raise_layer = Some((viewport, field_layer)); + h.frame(vec![]); + h.host.borrow_mut().child_raise_layer = None; + h.frame(vec![]); + }; + raise_field(&mut h); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), true)); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([Event::PointerMoved(pointer), turn.clone()]); + h.frames(2); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before, "the overlay covered the field before its queued turn"); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), false)); + raise_field(&mut h); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.push(turn); + h.frames(2); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before, "the stream left the field when the overlay covered it"); +} + #[test] fn leaving_a_floating_font_field_resets_queued_fractional_wheel_input() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 1b8b1a168a..2d33420b9e 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -12,13 +12,16 @@ struct Harness { app: VectorcraftApp, ctx: egui::Context, time: f64, + cursor: egui::CursorIcon, + nodes: Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>, } impl Harness { + /// Create a blank document and settle the initial docking layout over three frames. fn new() -> Self { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let mut h = Self { app, ctx: egui::Context::default(), time: 0.0 }; + let mut h = Self { app, ctx: egui::Context::default(), time: 0.0, cursor: egui::CursorIcon::Default, nodes: Vec::new() }; for _ in 0..3 { h.frame(vec![]); } @@ -40,6 +43,7 @@ impl Harness { self.run(input); } + /// Draw one application frame and retain its cursor and accessibility output for assertions. fn run(&mut self, input: egui::RawInput) { let app = &mut self.app; let mut out = self.ctx.run_ui(input, |ui| { @@ -47,6 +51,8 @@ impl Harness { app.ui(ui); }); out.textures_delta.clear(); + self.cursor = out.platform_output.cursor_icon; + self.nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); } fn hit(&self, hit: &Hit) -> Option { @@ -138,6 +144,120 @@ fn an_icon_opens_its_flyout_and_open_panel_follows() { assert_eq!(craft_ui::docking::flyout::(&h.ctx, area_id()), None); } +/// #5713: real Glyphs and Artboards bodies must retain a flyout resize through +/// content fitting, closing/reopening and serialization of the workspace layout. +#[test] +fn glyphs_and_artboards_flyouts_keep_user_sizes() { + for panel in ["glyphs", "artboards"] { + let mut h = Harness::new(); + let icon = h.hit(&Hit::Icon(panel.into())).unwrap().center(); + h.click(icon); + // Glyphs reserves space from the available height, so its untouched auto-fit + // converges over several frames before the first user resize. + for _ in 0..30 { + h.frame(vec![]); + } + // Area memory can include a panel body's minimum allocation beyond its clip. + // The frame's actual edge widgets describe the visible, resizable rectangle. + let rect = |h: &Harness| { + let id = area_id().with("flyout"); + let left = h.ctx.read_response(id.with("resize-left")).unwrap().rect; + let bottom = h.ctx.read_response(id.with("resize-bottom")).unwrap().rect; + Rect::from_min_max(pos2(left.left(), left.top() - 12.0), pos2(bottom.right() + 12.0, bottom.bottom())) + }; + let before = rect(&h); + for (at, cursor) in [ + (before.left_center() + vec2(2.0, 0.0), egui::CursorIcon::ResizeHorizontal), + (before.center_bottom() - vec2(0.0, 2.0), egui::CursorIcon::ResizeVertical), + ] { + h.frame(vec![Event::PointerMoved(at)]); + h.frame(vec![]); + assert_eq!(h.cursor, cursor, "{panel} at {at:?}, frame {before:?}"); + } + let from = before.left_bottom() + vec2(2.0, -2.0); + h.drag(from, from + vec2(-100.0, 150.0)); + for _ in 0..3 { + h.frame(vec![]); + } + let grown = rect(&h); + assert!((grown.width() - before.width() - 100.0).abs() < 1.0, "{panel}: {before:?} -> {grown:?}"); + assert!((grown.height() - before.height() - 150.0).abs() < 1.0, "{panel}: {before:?} -> {grown:?}"); + assert_eq!(grown.right(), before.right(), "the icon-column edge stays anchored"); + h.click(icon); + assert_eq!(craft_ui::docking::flyout::(&h.ctx, area_id()), None); + h.click(icon); + for _ in 0..3 { + h.frame(vec![]); + } + assert_eq!(rect(&h).size(), grown.size()); + let saved = serde_json::to_string(&h.layout()).unwrap(); + let mut restored = Harness::new(); + restored.app.ui.docking = Some(serde_json::from_str(&saved).unwrap()); + for _ in 0..3 { + restored.frame(vec![]); + } + restored.click(restored.hit(&Hit::Icon(panel.into())).unwrap().center()); + for _ in 0..3 { + restored.frame(vec![]); + } + assert_eq!(rect(&restored).size(), grown.size(), "{panel} saved layout"); + } +} + +/// Footer controls stay at the resized panel's bottom, including empty or short lists. +/// The same shared footer is used by the other icon panels and library windows. +#[test] +fn expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists() { + for (panel, label, artboards) in [ + ("artboards", "New Artboard", 1), + ("artboards", "New Artboard", 30), + ("brushes", "New Brush", 1), + ("swatches", "New Swatch", 1), + ("symbols", "New Symbol", 1), + ("graphicStyles", "New Graphic Style (Alt-click to name it)", 1), + ("appearance", "Add New Stroke", 1), + ("charStyles", "Create New Character Style", 1), + ("paraStyles", "Create New Paragraph Style", 1), + ("colorGuide", "Save color group to Swatch panel", 1), + ("links", "Show Link Info", 1), + ("actions", "Create New Action", 1), + ("variables", "Capture Data Set", 1), + ("assetExport", "Export for Screens…", 1), + ("cssProperties", "Generate CSS: the whole document's CSS while nothing is selected", 1), + ("svgInteractivity", "Link JavaScript Files…", 1), + ("colorThemes", "Add to Swatches", 1), + ("glyphs", "Zoom In", 1), + ] { + let mut h = Harness::new(); + h.ctx.enable_accesskit(); + for _ in 1..artboards { + h.app.run("artboard.new", json!({})).unwrap(); + } + h.app.run("window.panel.dock", json!({"panel":panel,"icon":true})).unwrap(); + let mut layout = h.layout(); + layout.apply(Action::ResizeGroup { panel: panel.into(), height: Some(540.0) }).unwrap(); + layout.apply(Action::ResizeFlyoutWidth { panel: panel.into(), width: Some(420.0) }).unwrap(); + h.app.ui.docking = Some(layout); + h.app.ui.open_panel = Some(panel.into()); + for _ in 0..5 { + h.frame(vec![]); + } + let bottom = h.ctx.read_response(area_id().with("flyout").with("resize-bottom")).unwrap().rect.bottom(); + let control = h + .nodes + .iter() + .find(|(_, node)| node.label() == Some(label)) + .and_then(|(_, node)| node.bounds()) + .unwrap_or_else(|| panic!("missing {label} in {panel}")); + assert!((control.y1 as f32 - (bottom - 10.0)).abs() < 2.0, "{panel}/{artboards}: footer {control:?}, bottom {bottom}"); + if panel == "artboards" && artboards == 1 { + let at = pos2(((control.x0 + control.x1) * 0.5) as f32, ((control.y0 + control.y1) * 0.5) as f32); + h.click(at); + assert_eq!(h.app.session.active().unwrap().doc.artboards.len(), 2, "the pinned New button works"); + } + } +} + #[test] fn a_tab_dragged_out_floats_and_comes_back_where_it_was_after_its_window_closes() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 93d781e5ae..2533ef0292 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -1377,6 +1377,7 @@ enum InclusionChange { Step(usize, usize, usize, bool), } +/// Draw action sets, steps and playback controls, keeping the list above a pinned footer. pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); // The selected action as (set, action). Read as the type it is stored as: egui keeps a @@ -1398,7 +1399,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let mut expanded: BTreeSet = pstate(ui.ctx(), "actions-expanded"); let mut inclusion_changes = Vec::new(); let mut play_req = None; - egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { + let list_height = widgets::panel_list_height(ui, 260.0, 0.0).min(260.0); + egui::ScrollArea::vertical().max_height(list_height).min_scrolled_height(list_height.min(64.0)).show(ui, |ui| { for (si, set) in app.ui.action_sets.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 20.0), egui::Sense::click()); if sets_selected.contains(&si) && selected.is_none() { @@ -1551,9 +1553,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { set_pstate(ui.ctx(), SELECTED_STEP, step_selected); app.ui.action_set = current; app.ui.action_sets_selected = sets_selected; - widgets::divider(ui); + if app.ui.action_sets.is_empty() { + dim_label(ui, tl!("No actions. Press ● to record.")); + } // Bottom bar: stop, record, play, new set, new action, delete. - ui.horizontal(|ui| { + widgets::bottom_bar(ui, |ui| { let recording = app.ui.recording.is_some(); if widgets::icon_button(ui, "square", tl!("Stop Playing/Recording"), false, 24.0).clicked() && let Err(e) = app.run(STOP_RECORDING, json!({})) @@ -1598,9 +1602,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.status(e); } let _ = icons::exists; - if app.ui.action_sets.is_empty() { - dim_label(ui, tl!("No actions. Press ● to record.")); - } } #[cfg(test)] @@ -1608,6 +1609,57 @@ mod tests { use super::*; use vectorcraft_engine::Session; + /// A short sized panel clips the list above its footer and can scroll to select its final row. + #[test] + fn a_short_actions_panel_keeps_its_last_row_reachable_above_the_footer() { + use egui::{Event, PointerButton, Rect, UiBuilder, UiStackInfo, pos2, vec2}; + for height in [60.0, 120.0] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events| { + time += 0.1; + let input = egui::RawInput { + time: Some(time), + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(300.0, height))), + events, + ..Default::default() + }; + let mut output = ctx.run_ui(input, |ui| { + let info = UiStackInfo::default().with_tag_value(widgets::PANEL_FOOTER, Some(height)); + ui.scope_builder(UiBuilder::new().ui_stack_info(info), |ui| show(app, ui)); + }); + output.textures_delta.clear(); + output.shapes + }; + let last_row = |shapes: &[egui::epaint::ClippedShape]| { + shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "Reflect Horizontal" => Some((text.visual_bounding_rect(), shape.clip_rect)), + _ => None, + }) + .expect("the final action is drawn") + }; + for _ in 0..3 { + let shapes = frame(&mut app, vec![]); + assert!(last_row(&shapes).1.bottom() <= height - 31.0, "height={height}: the list overlaps its footer"); + } + for _ in 0..12 { + frame(&mut app, crate::toolbar::tests::wheel(pos2(100.0, 12.0), 1000.0)); + } + let shapes = frame(&mut app, vec![]); + let (row, clip) = last_row(&shapes); + assert!(clip.contains_rect(row), "height={height}: the final row {row:?} is outside {clip:?}"); + let at = row.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + for events in [vec![Event::PointerMoved(at)], vec![button(true)], vec![button(false)]] { + frame(&mut app, events); + } + assert_eq!(pstate::>(&ctx, "actions-selected"), Some((0, 5))); + } + } + #[test] fn defaults_are_valid_commands() { for set in default_sets() { diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index ca1f3c28fc..32963ce68b 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -385,10 +385,22 @@ pub(crate) fn row_popup(app: &mut VectorcraftApp, ctx: &egui::Context, panel: Re let area_id = egui::Id::unique("ap-row-popup"); let shown = ctx.memory(|m| m.area_rect(area_id)); // A press outside it (not one that closes a dropdown the popup opened) or Escape puts it away. + // With a field in it that has the keyboard, a press draws it once more first, so the field lets + // go of the keyboard to that press and commits what was typed, as in a panel (#6429). Escape + // drops what was typed. let pressed_outside = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| shown.is_some_and(|r| !r.contains(p)))); - if pressed_outside && !egui::Popup::is_any_open(ctx) || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + let mut last = false; + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { return close(app); + } else if pressed_outside && !egui::Popup::is_any_open(ctx) { + if !widgets::field_focused_in(ctx, egui::LayerId::new(egui::Order::Foreground, area_id)) { + return close(app); + } + last = true; } + // Fields let go of the keyboard on a click, which this press isn't yet. The app-wide option + // goes back however this function ends, a panic in the panel included. + let _surrender = last.then(|| SurrenderOnPress::set(ctx)); let screen = ctx.content_rect(); let left = panel.left() - POPUP_GAP - POPUP_W; let x = if left >= screen.left() + POPUP_GAP { left } else { (panel.right() + POPUP_GAP).min(screen.right() - POPUP_W - POPUP_GAP) }; @@ -415,6 +427,28 @@ pub(crate) fn row_popup(app: &mut VectorcraftApp, ctx: &egui::Context, panel: Re } }); }); + if last { + close(app); + } +} + +/// While it lives, a press anywhere makes a field let go of the keyboard, as a click does +/// otherwise; dropped, egui's previous `surrender_focus_on` is back ([`row_popup`]'s last frame). +struct SurrenderOnPress(egui::Context, egui::SurrenderFocusOn); + +impl SurrenderOnPress { + fn set(ctx: &egui::Context) -> Self { + let before = ctx.options(|o| o.input_options.surrender_focus_on); + ctx.options_mut(|o| o.input_options.surrender_focus_on = egui::SurrenderFocusOn::Presses); + Self(ctx.clone(), before) + } +} + +impl Drop for SurrenderOnPress { + fn drop(&mut self) { + let before = self.1; + self.0.options_mut(|o| o.input_options.surrender_focus_on = before); + } } /// A row's name that edits the row when clicked ([`link`]), with the tooltip "Click to edit". diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 9790270a44..04f2719e76 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -312,14 +312,11 @@ pub struct MenuFacts { pub(crate) any_art: bool, } -/// Whether an unlocked artboard of `indices` has art that Fit to Artwork Bounds fits it to. +/// Whether an unlocked artboard of `indices` has art that Fit to Artwork Bounds fits it to, kept by +/// the document ([`vectorcraft_engine::DocState::any_art_to_fit`]): the canvas menu asks on every +/// frame it is open without its [`MenuFacts`]. pub(crate) fn fit_has_art(app: &VectorcraftApp, indices: &[usize]) -> bool { - app.session.active().is_some_and(|st| { - indices - .iter() - .filter_map(|i| st.doc.artboards.get(*i)) - .any(|a| !a.locked && vectorcraft_render::encode::art_bounds_on(&st.doc, a.rect).is_some()) - }) + app.session.active().is_some_and(|st| st.any_art_to_fit(indices)) } /// A right-click on the canvas at `p` with the Artboard tool: an artboard under the pointer that @@ -506,6 +503,7 @@ fn select_copies(app: &mut VectorcraftApp, all: &[usize], r: &Value) { } } +/// Draw the artboard list and its commands, filling the space above a sized panel's footer. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let abs: Vec = app.session.active().map(|d| d.doc.artboards.iter().map(|a| a.name.clone()).collect()).unwrap_or_default(); @@ -520,10 +518,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut row_clicked = false; // A row dropped on another row: (from, to), the index it lands at. let mut dropped = None; + let fixed = widgets::panel_footer_bottom(ui).is_some(); + let list_height = widgets::panel_list_height(ui, 220.0, 2.0 + ui.spacing().item_spacing.y); let list_rect = widgets::list_box(ui, |ui| { - ui.set_min_height(110.0); + ui.set_min_height(if fixed { list_height.min(110.0) } else { 110.0 }); ui.spacing_mut().item_spacing.y = 0.0; - let scrolled = egui::ScrollArea::vertical().id_salt("ab-scroll").max_height(220.0).show(ui, |ui| { + let scroll = egui::ScrollArea::vertical() + .id_salt("ab-scroll") + .max_height(list_height) + .min_scrolled_height(list_height.min(64.0)) + .auto_shrink([false, !fixed]); + let scrolled = scroll.show(ui, |ui| { for (i, name) in abs.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click_and_drag()); if resp.drag_started() { diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index 256e7ceaff..23aab10159 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -1656,6 +1656,29 @@ fn the_open_menu_reads_what_the_right_click_measured() { assert!(labels.contains(&"Delete Empty Artboards") && !labels.contains(&"Fit to Artwork Bounds"), "{labels:?}"); } +/// Whether Fit to Artwork Bounds has art to fit is kept for a version of the document, not its +/// revision: a document replaced with no revision moved (composite fonts synced as its tab comes +/// to the front) is measured again. +#[test] +fn fit_to_art_is_measured_for_each_version_of_the_document() { + let mut app = menu_app(2); + assert!(!super::fit_has_art(&app, &[0, 1])); + // Art on the first artboard, the revision left as it was. + let st = app.session.active_mut().unwrap(); + let mut doc = (*st.doc).clone(); + let l = doc.layers[0].id; + let id = doc.alloc_id(); + let art = vectorcraft_doc::Node::path( + id, + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(10.0, 10.0, 20.0, 20.0)), + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0), + ); + doc.insert(Some(l), 0, art).unwrap(); + st.doc = std::sync::Arc::new(doc); + assert!(super::fit_has_art(&app, &[0, 1]), "measured again"); + assert!(!super::fit_has_art(&app, &[1]), "measured for the artboards asked about"); +} + /// `artboard.selectAll` chooses the Artboard tool first when another tool is in use, and fails /// without a document. #[test] diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 5c07441bee..9192aa5f0b 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -212,6 +212,7 @@ fn insert(app: &mut VectorcraftApp, ctx: &egui::Context, ch: char) { } } +/// Browse and insert glyphs from the chosen font, with font controls below the glyph grid. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let db = FontDb::global(); @@ -244,14 +245,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let cols = ((w / cell).floor() as usize).max(1); let rows = chars.len().div_ceil(cols); let px = (cell * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; - let list_h = (ui.available_height() - 64.0).max(cell * 3.0); + let list_h = widgets::panel_list_height(ui, (ui.available_height() - 64.0).max(cell * 3.0), 33.0); let hover_id = egui::Id::unique("gl-hover"); let selected = selected_char(app); // The selected character and the rows shown last frame: the grid scrolls to the selected glyph // only when the selection moves to another character, so it still scrolls freely meanwhile. let follow_id = egui::Id::unique("gl-follow"); let (followed, shown): (Option, std::ops::Range) = ui.ctx().data(|d| d.get_temp(follow_id)).unwrap_or_default(); - let mut area = egui::ScrollArea::vertical().max_height(list_h).auto_shrink([false, false]); + let mut area = egui::ScrollArea::vertical().max_height(list_h).min_scrolled_height(list_h.min(64.0)).auto_shrink([false, false]); if selected != followed && let Some(c) = selected && let Ok(i) = chars.binary_search_by_key(&c, |x| x.0) @@ -308,6 +309,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { /// The family and style menus of the font the panel browses, and Zoom Out and Zoom In. fn font_row(app: &mut VectorcraftApp, ui: &mut Ui, family: &str, style: &str, w: f32) { let db = FontDb::global(); + widgets::panel_footer_space(ui, 24.0); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; // Picks the font the panel browses only: nothing is previewed on the document. @@ -371,10 +373,14 @@ fn alternates(app: &mut VectorcraftApp, ui: &mut Ui, w: f32) { let cols = ((w / cell).floor() as usize).max(1); let rows = list.len().div_ceil(cols); let px = (cell * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; - let list_h = (ui.available_height() - 64.0).max(cell * 3.0); + let list_h = widgets::panel_list_height(ui, (ui.available_height() - 64.0).max(cell * 3.0), 33.0); let mut pick = None; // A scroll position of its own for each character, so the grid starts at the top for another. - let area = egui::ScrollArea::vertical().id_salt(("gl-alternates", id.0, byte)).max_height(list_h).auto_shrink([false, false]); + let area = egui::ScrollArea::vertical() + .id_salt(("gl-alternates", id.0, byte)) + .max_height(list_h) + .min_scrolled_height(list_h.min(64.0)) + .auto_shrink([false, false]); area.show_rows(ui, cell, rows, |ui, range| { for r in range { ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/panels/layers/thumbs.rs b/crates/ui-egui/src/panels/layers/thumbs.rs index 4fcdc03e49..2f15878133 100644 --- a/crates/ui-egui/src/panels/layers/thumbs.rs +++ b/crates/ui-egui/src/panels/layers/thumbs.rs @@ -928,6 +928,7 @@ mod tests { thumbs.receive(ctx, done); } + /// Prioritize the shown document’s thumbnails, requeue them when revisited, and retain cached rows. #[test] fn the_shown_documents_thumbnails_are_made_before_the_queued_ones_of_another() { let ctx = egui::Context::default(); @@ -957,10 +958,15 @@ mod tests { assert!(thumbs.texture(&ctx, &src_b, n, 24).is_some(), "the shown document's thumbnails are shown"); } // Shown again, document 1's rows are asked for again and come back. + // Hold the worker so texture() cannot collect a completed row before the count. + let release = hold(&thumbs); for n in &a_rows { assert!(thumbs.texture(&ctx, &src_a, n, 24).is_none()); } assert_eq!(thumbs.pending.keys().filter(|k| k.0 == 1).count(), 3); + release.send(()).expect("the held job is waiting"); + let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes"); + assert_eq!(held.key.0, (0, NodeId(0))); for _ in &a_rows { receive_checked(&ctx, &mut thumbs, 1, &a, &a_rows); } diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 38cfa604e2..04709b42c7 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -83,7 +83,26 @@ fn profile_dropdown(ui: &mut Ui, id: &str, current: &str, kind: ProfileKind, ext widgets::dropdown_names(ui, id, super::label_or_name(current, extra == Some(current)), &refs, 210.0).and_then(|i| names.get(i).cloned()) } +/// The Color Settings section (Edit › Color Settings… / Assign Profile…), scrolled into view once +/// when one of those commands opened the panel ([`crate::state::UiState::color_settings_scroll`]). fn settings_section(app: &mut VectorcraftApp, ui: &mut Ui) { + let top = ui.cursor().top(); + settings_rows(app, ui); + // Edit › Color Settings… / Assign Profile… opened the panel for this section: scroll it into + // view once, as the plates and Proof Setup above it fill a short window (#6419). At once, not + // animated: the panel has just opened. egui moves the scroll area on a later frame, so ask for + // one rather than wait for the pointer to move. + if app.ui.color_settings_scroll && !ui.is_sizing_pass() { + let rect = egui::Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=ui.min_rect().bottom().max(top)); + ui.scroll_to_rect_animation(rect, Some(egui::Align::TOP), egui::style::ScrollAnimation::none()); + ui.ctx().request_repaint(); + app.ui.color_settings_scroll = false; + } +} + +/// The section's rows: the RGB and CMYK working spaces, intent, black point compensation, Load +/// Profile… and Gamut Check, and the profile the active document is assigned. +fn settings_rows(app: &mut VectorcraftApp, ui: &mut Ui) { let st = cms::active_settings(); widgets::section_header(ui, tl!("Color Settings")); ui.horizontal(|ui| { @@ -215,4 +234,55 @@ mod tests { assert!(panel.iter().any(|(id, _)| id == "tritanopia")); assert!(panel.iter().all(|(id, _)| cms::ProofTarget::parse(id).is_some_and(|t| t.id() == *id))); } + + /// #6419: Edit › Assign Profile… and Color Settings… show the panel scrolled to its Color + /// Settings section, which a window shorter than the panel (a floated panel stops at 320 + /// points) otherwise shows only after scrolling past the plates and Proof Setup. Once: a + /// scroll away afterwards stays. + #[test] + fn color_settings_and_assign_profile_scroll_the_color_settings_into_view() { + const VIEW: f32 = 120.0; + fn find(s: &egui::Shape, text: &str) -> Option { + match s { + egui::Shape::Text(t) if t.galley.text() == text => Some(t.pos.y), + egui::Shape::Vec(v) => v.iter().find_map(|s| find(s, text)), + _ => None, + } + } + // One frame of the panel in a scroll area VIEW points high, scrolled to `offset` when + // given: where the section's Black Point Compensation box shows in the view. + fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, offset: Option) -> f32 { + let mut top = 0.0; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + top = ui.cursor().top(); + let mut area = egui::ScrollArea::vertical().id_salt("separations").max_height(VIEW); + if let Some(y) = offset { + area = area.vertical_scroll_offset(y); + } + area.show(ui, |ui| show(app, ui)); + }); + out.textures_delta.clear(); + out.shapes.iter().find_map(|c| find(&c.shape, "Use Black Point Compensation")).unwrap() - top + } + let visible = |y: f32| (0.0..VIEW).contains(&y); + for id in ["edit.assignProfile", "edit.colorSettings"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let ctx = egui::Context::default(); + let before = frame(&ctx, &mut app, None); + assert!(!visible(before), "the section starts below the view: {before}"); + app.run(id, json!({})).unwrap(); + frame(&ctx, &mut app, None); + assert!(!app.ui.color_settings_scroll); + // egui moves a scroll area on the frame after the request and paints it moved on the + // one after that; both ask for a repaint. + assert!(ctx.has_requested_repaint()); + frame(&ctx, &mut app, None); + assert!(ctx.has_requested_repaint()); + let shown = frame(&ctx, &mut app, None); + assert!(visible(shown), "{id} scrolls the section into the view: {shown}"); + frame(&ctx, &mut app, Some(0.0)); + assert_eq!(frame(&ctx, &mut app, None), before, "scrolled back to the top, it stays there"); + } + } } diff --git a/crates/ui-egui/src/panels/tests_appearance.rs b/crates/ui-egui/src/panels/tests_appearance.rs index 0431d6dec2..3d486dfe23 100644 --- a/crates/ui-egui/src/panels/tests_appearance.rs +++ b/crates/ui-egui/src/panels/tests_appearance.rs @@ -1994,3 +1994,33 @@ fn the_drop_buttons_light_up_while_a_row_is_dragged() { assert_eq!(drop_buttons_on(&ctx, &mut app, vec![]), [false, false], "dark again once it is released"); assert_eq!(stack_items(&app).len(), 2, "released elsewhere: nothing removed"); } + +/// #6429: a dash length typed into the Stroke panel that the Appearance panel's "Stroke:" row or +/// the Properties panel's Stroke link opens sticks when a click outside closes the popup, as it +/// does when Enter ends the edit. The popup used to close without drawing again, so the field +/// never saw itself lose the keyboard and the value went back. +#[test] +fn a_dash_typed_in_a_stroke_popup_sticks_when_a_click_outside_closes_it() { + type Panel = fn(&mut VectorcraftApp, &mut egui::Ui); + let hosts: [(&str, Panel); 2] = [("Stroke:", appearance::show), ("Stroke", super::properties::show)]; + for (link, show) in hosts { + let mut app = app_with_rect(); + run(&mut app, "stroke.set", json!({"dash": [10.0]})); + let ctx = egui::Context::default(); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, link).center(), show); + // The popup's first dash field: a click gives it the keyboard with its text selected. + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "10").center(), show); + frame_events(&ctx, &mut app, vec![egui::Event::Text("4".into())], show); + let dash = |app: &VectorcraftApp| current_stroke(app).and_then(|s| s.dash).map(|d| d.pattern); + assert_eq!(dash(&app), Some(vec![10.0]), "{link}: nothing set while typing"); + click(&ctx, &mut app, egui::pos2(5.0, 3000.0), show); + let surrender = ctx.options(|o| o.input_options.surrender_focus_on); + assert_eq!(surrender, egui::SurrenderFocusOn::Clicks, "{link}: fields let go of the keyboard on a click again"); + frame_events(&ctx, &mut app, vec![], show); + assert_eq!(dash(&app).and_then(|p| p.first().copied()), Some(4.0), "{link}: the typed dash stuck: {:?}", dash(&app)); + let texts = frame_events(&ctx, &mut app, vec![], show); + assert!(!texts.iter().any(|(t, _)| t == "Dashed Line"), "{link}: the popup closed"); + } +} diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index 09ed75af7a..22f863fbd9 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -127,7 +127,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { let under = |e: &crate::menus::MenuEntry| e.path == ["Window", "Brush Libraries"]; let opened: Vec<_> = entries.iter().filter(|e| under(e) && e.command.as_deref() == Some("window.brushLibrary")).map(|e| e.params["library"].clone()).collect(); - assert_eq!(opened, [json!("art-ribbons"), json!("calligraphic-nibs"), json!("pattern-borders"), json!("scatter-shapes")]); + assert_eq!(opened, [json!("art-ribbons"), json!("calligraphic-nibs"), json!("pattern-borders"), json!("scatter-shapes"), json!("game-trails")]); let enabled = |cmd: &str| entries.iter().find(|e| under(e) && e.command.as_deref() == Some(cmd)).map(|e| e.enabled); assert_eq!(enabled("window.brushLibrary.other"), Some(true)); assert_eq!(enabled("ui.saveBrushLibrary"), Some(true), "a new document has the default brushes"); diff --git a/crates/ui-egui/src/panels/tests_strokeux.rs b/crates/ui-egui/src/panels/tests_strokeux.rs index 4ab96f35a4..2c7203270a 100644 --- a/crates/ui-egui/src/panels/tests_strokeux.rs +++ b/crates/ui-egui/src/panels/tests_strokeux.rs @@ -243,3 +243,72 @@ fn a_spinner_step_from_a_weight_shown_as_a_preset_moves_past_it() { } assert_eq!(app.session.shown_stroke().unwrap().width, 1.0); } + +/// The screen rect of the Weight spinner in the Stroke panel, found by its accessibility label, so +/// the tests do not depend on where the panel puts the field. +fn weight_spinner_rect(ctx: &egui::Context, app: &mut VectorcraftApp) -> egui::Rect { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| stroke::show(app, ui)); + out.textures_delta.clear(); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("accessibility is on").nodes; + let b = nodes.iter().find(|(_, n)| n.label() == Some("Step up or down")).expect("the weight spinner").1.bounds().expect("its bounds"); + egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)) +} + +/// With objects of different weights selected the Weight field is blank, and its spinner steps +/// from 0.25 pt (#5349): up gives 0.5 pt and down gives 0 pt, for all of them, whatever the +/// Units > Stroke. +#[test] +fn the_spinner_of_a_blank_weight_steps_from_a_quarter_point() { + use super::tests_appearance::frame_raw; + + for (unit, up, after) in [("points", true, 0.5), ("points", false, 0.0), ("millimeters", true, 0.5), ("millimeters", false, 0.0)] { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut app = app_with_rect(); + app.session.prefs.units_stroke = unit.into(); + let a = app.session.active().unwrap().selection.objects[0]; + let b = run(&mut app, "shape.rectangle", json!({"x": 120, "y": 10, "width": 50, "height": 50}))["id"].as_u64().unwrap(); + run(&mut app, "stroke.set", json!({"ids": [b], "weight": 3})); + run(&mut app, "select.set", json!({ "ids": [a.0, b] })); + texts(&ctx, &mut app, stroke::show); + let sr = weight_spinner_rect(&ctx, &mut app); + // The up arrow is the upper half of the spinner, the down arrow the lower half. + let pos = egui::pos2(sr.center().x, sr.center().y + if up { -sr.height() / 4.0 } else { sr.height() / 4.0 }); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + for event in [egui::Event::PointerMoved(pos), button(true), button(false)] { + frame_raw(&ctx, &mut app, egui::RawInput { events: vec![event], ..Default::default() }, stroke::show); + } + for id in [a.0, b] { + run(&mut app, "select.set", json!({ "ids": [id] })); + assert_eq!(app.session.shown_stroke().unwrap().width, after, "object {id}, up: {up}, {unit}"); + } + } +} + +/// ↑/↓ in the focused blank Weight field step from 0.25 pt too, for every selected object. +#[test] +fn the_arrow_keys_in_a_blank_weight_step_from_a_quarter_point() { + for (key, after) in [(egui::Key::ArrowUp, 0.5), (egui::Key::ArrowDown, 0.0)] { + // A new context each time: the field keeps its text in the context, and the 0.5 pt left by ArrowUp + // would make the blank field of the next run start from 0.5 pt. + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut app = app_with_rect(); + let a = app.session.active().unwrap().selection.objects[0]; + let b = run(&mut app, "shape.rectangle", json!({"x": 120, "y": 10, "width": 50, "height": 50}))["id"].as_u64().unwrap(); + run(&mut app, "stroke.set", json!({"ids": [b], "weight": 3})); + run(&mut app, "select.set", json!({ "ids": [a.0, b] })); + texts(&ctx, &mut app, stroke::show); + // The blank field, right of the spinner. + let sr = weight_spinner_rect(&ctx, &mut app); + click(&ctx, &mut app, egui::pos2(sr.right() + 30.0, sr.center().y), stroke::show); + let press = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + frame_events(&ctx, &mut app, vec![press], stroke::show); + for id in [a.0, b] { + run(&mut app, "select.set", json!({ "ids": [id] })); + assert_eq!(app.session.shown_stroke().unwrap().width, after, "object {id}, {key:?}"); + } + } +} diff --git a/crates/ui-egui/src/panels/tests_symbol_libraries.rs b/crates/ui-egui/src/panels/tests_symbol_libraries.rs index 6482bf3123..7dee49df2b 100644 --- a/crates/ui-egui/src/panels/tests_symbol_libraries.rs +++ b/crates/ui-egui/src/panels/tests_symbol_libraries.rs @@ -113,7 +113,7 @@ fn the_window_menu_and_the_symbols_panel_open_symbol_libraries() { let under = |e: &crate::menus::MenuEntry| e.path == ["Window", "Symbol Libraries"]; let opened: Vec<_> = entries.iter().filter(|e| under(e) && e.command.as_deref() == Some("window.symbolLibrary")).map(|e| e.params["library"].clone()).collect(); - assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames")]); + assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames"), json!("map-markers")]); let has = |cmd: &str| entries.iter().find(|e| under(e) && e.command.as_deref() == Some(cmd)).map(|e| e.enabled); assert_eq!(has("window.symbolLibrary.other"), Some(true)); assert_eq!(has("ui.saveSymbolLibrary"), Some(false), "no symbols to save yet"); diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index b1f8322fd8..2596b218b5 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -576,6 +576,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Scale Strokes & Effects"), true, ss) { set_pref(app, "scaleStrokes", !ss); } + // The panel's values and the bounding box measure point type by its glyphs' ink. + let glyphs = app.session.prefs.type_glyph_bounds; + if menu_item(ui, tl!("Measure Type by Glyph Bounds"), true, glyphs) { + set_pref(app, "typeGlyphBounds", !glyphs); + } ui.separator(); // What the panel transforms (Transform Object Only / Pattern Only / Both), one checked. let current = pattern_mode(app); diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index b5598689a8..67cebc7cd2 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -32,6 +32,26 @@ fn use_preview_bounds_shows_the_visual_size_and_checks_the_align_flyout() { assert!(texts(&mut app, crate::panels::align::menu).iter().any(|t| t == "✓ Use Preview Bounds")); } +/// The panel menu's Measure Type by Glyph Bounds is checked while `typeGlyphBounds` is on, and the +/// bounding box of selected point type then measures its glyphs without a change to the document. +#[test] +fn measure_type_by_glyph_bounds_is_checked_and_resizes_the_box() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("text.create", json!({"x": 20, "y": 200, "size": 100, "text": "Hg"})).unwrap(); + assert!(texts(&mut app, menu).iter().any(|t| t == " Measure Type by Glyph Bounds")); + let em = app.selection_box().unwrap().rect; + let revision = app.session.active().unwrap().revision; + set_pref(&mut app, "typeGlyphBounds", true); + assert!(app.session.prefs.type_glyph_bounds); + assert!(texts(&mut app, menu).iter().any(|t| t == "✓ Measure Type by Glyph Bounds")); + assert_eq!(app.session.active().unwrap().revision, revision); + let glyphs = app.selection_box().unwrap().rect; + assert!(glyphs.height() < em.height() - 10.0, "{glyphs:?} inside {em:?}"); + set_pref(&mut app, "typeGlyphBounds", false); + assert_eq!(app.selection_box().unwrap().rect, em); +} + #[test] fn use_preview_bounds_shows_the_size_after_geometry_effects() { // A 100 × 50 rectangle without a stroke, with Offset Path 10: 120 × 70 as drawn. diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 87aa5cd13f..a8987855eb 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -97,6 +97,7 @@ pub(crate) fn delete_active_dataset(app: &mut VectorcraftApp) { app.run("dataset.delete", json!({})).ok(); } +/// Draw document variables, data sets and their two-row footer of capture and binding controls. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { widgets::dim_label(ui, tl!("No document")); @@ -209,46 +210,49 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The bottom bar: make the selection dynamic, define and delete what the lists show, and // lock the variables. - ui.separator(); - ui.horizontal(|ui| { - if widgets::icon_button_enabled(ui, "type", tl!("Make Text Dynamic"), false, single_type && !locked, 24.0).clicked() { - app.run("variable.makeTextDynamic", json!({})).ok(); - } - if widgets::icon_button_enabled(ui, "eye", tl!("Make Visibility Dynamic"), false, has_selection && !locked, 24.0).clicked() { - app.run("variable.makeVisibilityDynamic", json!({})).ok(); - } - if widgets::icon_button_enabled(ui, "image", tl!("Make Image Dynamic"), false, single_image && !locked, 24.0).clicked() { - app.run("variable.makeImageDynamic", json!({})).ok(); - } - if widgets::icon_button_enabled(ui, "chart-column", tl!("Make Graph Dynamic"), false, selection_graph && !locked, 24.0).clicked() { - app.run("variable.makeGraphDynamic", json!({})).ok(); - } - if widgets::icon_button_enabled(ui, "plus", tl!("New Variable…"), false, !locked, 24.0).clicked() { - crate::menus::invoke(app, "variable.define", json!({})); - } - if widgets::icon_button_enabled(ui, "link-2-off", tl!("Unbind Variable"), false, selection_bound, 24.0).clicked() { - app.run("variable.unbind", json!({"ids": selected})).ok(); - } - // The bin deletes the highlighted variable only, as the reference panel's does. - if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Variable"), false, highlighted.is_some() && !locked, 24.0).clicked() { - delete_highlighted(app); - } - // The lock button is drawn pressed while the variables are locked. - let tip = if locked { tl!("Unlock Variables") } else { tl!("Lock Variables") }; - if widgets::icon_button(ui, "lock", tip, locked, 24.0).clicked() { - app.run("variable.lock", json!({})).ok(); - } - }); - ui.horizontal(|ui| { - // Capture records what the art holds now as a new row (paste: take it in); Update - // writes the art back into the row that is active (save: write it out). - if widgets::icon_button(ui, "clipboard-paste", tl!("Capture Data Set"), false, 24.0).clicked() { - app.run("dataset.capture", json!({})).ok(); - } - let can_update = active.is_some(); - if widgets::icon_button_enabled(ui, "save", tl!("Update Data Set"), false, can_update, 24.0).clicked() { - app.run("dataset.update", json!({})).ok(); - } + let footer_height = 48.0 + 2.0 * ui.spacing().item_spacing.y + 1.0; + widgets::panel_footer(ui, footer_height, |ui| { + ui.add(egui::Separator::default().spacing(1.0)); + ui.horizontal(|ui| { + if widgets::icon_button_enabled(ui, "type", tl!("Make Text Dynamic"), false, single_type && !locked, 24.0).clicked() { + app.run("variable.makeTextDynamic", json!({})).ok(); + } + if widgets::icon_button_enabled(ui, "eye", tl!("Make Visibility Dynamic"), false, has_selection && !locked, 24.0).clicked() { + app.run("variable.makeVisibilityDynamic", json!({})).ok(); + } + if widgets::icon_button_enabled(ui, "image", tl!("Make Image Dynamic"), false, single_image && !locked, 24.0).clicked() { + app.run("variable.makeImageDynamic", json!({})).ok(); + } + if widgets::icon_button_enabled(ui, "chart-column", tl!("Make Graph Dynamic"), false, selection_graph && !locked, 24.0).clicked() { + app.run("variable.makeGraphDynamic", json!({})).ok(); + } + if widgets::icon_button_enabled(ui, "plus", tl!("New Variable…"), false, !locked, 24.0).clicked() { + crate::menus::invoke(app, "variable.define", json!({})); + } + if widgets::icon_button_enabled(ui, "link-2-off", tl!("Unbind Variable"), false, selection_bound, 24.0).clicked() { + app.run("variable.unbind", json!({"ids": selected})).ok(); + } + // The bin deletes the highlighted variable only, as the reference panel's does. + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Variable"), false, highlighted.is_some() && !locked, 24.0).clicked() { + delete_highlighted(app); + } + // The lock button is drawn pressed while the variables are locked. + let tip = if locked { tl!("Unlock Variables") } else { tl!("Lock Variables") }; + if widgets::icon_button(ui, "lock", tip, locked, 24.0).clicked() { + app.run("variable.lock", json!({})).ok(); + } + }); + ui.horizontal(|ui| { + // Capture records what the art holds now as a new row (paste: take it in); Update + // writes the art back into the row that is active (save: write it out). + if widgets::icon_button(ui, "clipboard-paste", tl!("Capture Data Set"), false, 24.0).clicked() { + app.run("dataset.capture", json!({})).ok(); + } + let can_update = active.is_some(); + if widgets::icon_button_enabled(ui, "save", tl!("Update Data Set"), false, can_update, 24.0).clicked() { + app.run("dataset.update", json!({})).ok(); + } + }); }); } diff --git a/crates/ui-egui/src/picks.rs b/crates/ui-egui/src/picks.rs index 28a4d9d114..4122c19410 100644 --- a/crates/ui-egui/src/picks.rs +++ b/crates/ui-egui/src/picks.rs @@ -72,6 +72,7 @@ const DOCUMENT_FREE: &[&str] = &[ "file.newFromTemplate", "ui.installPlugin", "ui.checkScript", + "ui.runScript", "window.swatchLibrary.other", "window.graphicStyleLibrary.other", "ui.libraryPanel.locate", diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 9ef8f3ed74..93b84f488d 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -225,6 +225,54 @@ fn prefs_persist_through_ui_state() { assert_eq!(b.session.prefs.gridline_every, 50.0); } +/// Guides & Grid › Lock Guides by Default: shown in its category, applied by OK, saved with the +/// UI state and read back as locked guides. A file without the key leaves guides unlocked. +#[test] +fn lock_guides_by_default_shows_applies_and_restores() { + let mut a = app(); + a.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + open(&mut a, Some("Guides & Grid")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Lock Guides by Default"), "{text}"); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields["lockGuidesByDefault"], json!(false)); + a.ui.dialog.as_mut().unwrap().fields.insert("lockGuidesByDefault".into(), json!(true)); + confirm(&mut a).unwrap(); + assert!(a.session.guides_locked()); + assert_eq!(crate::menus::dynamic_label(&a, "view.guides.lock", ""), "Unlock Guides"); + assert_eq!(a.ui.engine_prefs["lockGuidesByDefault"], json!(true)); + + let saved = serde_json::to_vec(&a.ui).unwrap(); + let mut b = app(); + assert!(!b.session.guides_locked()); + b.ui = serde_json::from_slice::(&saved).unwrap().sanitized(); + restore(&mut b); + assert!(b.session.guides_locked()); + + let mut older = app(); + older.ui.engine_prefs = json!({"gridlineEvery": 50}); + restore(&mut older); + assert!(!older.session.guides_locked()); +} + +/// OK with the option unchanged keeps the lock from the View menu. OK after turning the option +/// off, as Reset Preferences does in the dialog, unlocks guides. +#[test] +fn preferences_ok_changes_the_guide_lock_only_with_the_option() { + let mut a = app(); + a.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + a.run("view.guides.lock", json!({"locked": true})).unwrap(); + open(&mut a, Some("Guides & Grid")); + confirm(&mut a).unwrap(); + assert!(a.session.guides_locked(), "the option did not change"); + a.run("view.guides.lock", json!({"locked": false})).unwrap(); + a.run("prefs.set", json!({"key": "lockGuidesByDefault", "value": true})).unwrap(); + assert!(a.session.guides_locked()); + open(&mut a, Some("Guides & Grid")); + a.ui.dialog.as_mut().unwrap().fields.insert("lockGuidesByDefault".into(), Prefs::default().to_json()["lockGuidesByDefault"].clone()); + confirm(&mut a).unwrap(); + assert!(!a.session.guides_locked(), "the option went off"); +} + #[test] fn old_pref_files_keep_their_brightness() { let mut a = app(); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs new file mode 100644 index 0000000000..042e24cd31 --- /dev/null +++ b/crates/ui-egui/src/script_runs.rs @@ -0,0 +1,48 @@ +//! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to +//! its end, while the app goes on drawing the documents as they were before the run. The status bar +//! shows it with a Stop button; a run that has added a great deal waits for the person's answer. + +use serde_json::json; + +use crate::VectorcraftApp; +use crate::dialogs::script_run; +use crate::state::Dialog; + +/// Advances the running script by one slice, or asks what its growth needs asked. +pub fn poll(app: &mut VectorcraftApp) { + script_run::drain(app); + if !app.session.script_running() { + return; + } + if app.session.script_waiting() { + if app.ui.dialog.is_none() { + app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); + } + return; + } + let name = app.session.script_name().unwrap_or_default(); + let cursor_settings = (app.session.caps_lock, app.session.prefs.use_precise_cursors); + let Some(result) = app.session.script_pump() else { return }; + if cursor_settings != (app.session.caps_lock, app.session.prefs.use_precise_cursors) { + app.canvas.hover_cursor = None; + } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::GROWTH_KIND) { + app.ui.dialog = None; + } + match result { + Ok(_) => app.status(format!("Ran {name}")), + Err(e) => failed(app, e.to_string()), + } + app.sync_views(); +} + +/// Shows why a run ended without its changes. A stopped run that wrote no file says only that it +/// was stopped; any other failure shows its error, which names the files left written. +pub(crate) fn failed(app: &mut VectorcraftApp, error: String) { + let stopped = app.session.script_report().is_some_and(|r| r["kind"] == "stopped" && r["written"].as_array().is_none_or(Vec::is_empty)); + if stopped { + app.status("The script was stopped and its changes were undone"); + } else { + app.status(error); + } +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 47374c7e69..901c0a3409 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -107,6 +107,11 @@ pub struct Services { /// Files that arrived asynchronously to be placed (web: picked for Place, or dropped on the /// canvas). pub place_inbox: Option, + /// Web: start an async pick of a script to run (it arrives via `script_inbox`; a canceled pick + /// delivers nothing). + pub script_async: Option>, + /// Scripts the web's picker delivered for File › Scripts › Other Script…. + pub script_inbox: Option, /// The system clipboard with all its formats (desktop): Copy offers text, SVG, PDF and PNG, /// Paste takes SVG, PDF, text and bitmaps from other apps. Without it, SVG text only (through /// egui and `clipboard_read`). diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 6d7ac9474f..df87187a65 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -20,7 +20,7 @@ pub(crate) use held_tool::{HeldTool, note_tool_use}; use paste::unclip_chords; pub(crate) use paste::{PasteChord, paste_command}; pub(crate) use presentation::presentation_step; -use presentation::{escape_pair_id, escape_press, escape_resets_rotation, presentation_keys}; +use presentation::{escape_resets_rotation, presentation_keys}; #[cfg(test)] use typing::is_shortcut_chord; pub(crate) use typing::keep_marked_text; @@ -201,8 +201,6 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { crate::ime::controls_without_editor(app, ctx); return; } - // Taken before anything returns, so a press in a field or a dialog ends a pair of Escapes. - let mut escape_pair = escape_press(ctx); // Followed before anything returns, so a key typed in a field isn't taken for a paste. let textless_paste = ctx.input(|i| app.paste_chord.textless_paste(&i.events)); // A numeric field being scrubbed has the keyboard: Escape cancels the drag. @@ -226,7 +224,9 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { } // Escape closes a dropdown list or popover open in the dialog (each closes itself on it) and // leaves the dialog open. - let popup = app.ui.dialog.as_ref().is_some_and(|d| egui::Popup::is_any_open(ctx) || crate::dialogs::brush_options::tips_open(d)); + let popup = app.ui.dialog.as_ref().is_some_and(|d| { + egui::Popup::is_any_open(ctx) || crate::dialogs::brush_options::tips_open(d) || crate::dialogs::new_document_popup_open(d) + }); // Escape in Preferences' search field with text clears the field first. if !popup && pressed_anew(ctx, Key::Escape) && !crate::prefs_dialog::clear_search_on_escape(app, ctx) { crate::dialogs::cancel(app); @@ -236,7 +236,7 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { } if app.ui.screen_mode == 3 { crate::ime::controls_without_editor(app, ctx); - presentation_keys(app, ctx, escape_pair); + presentation_keys(app, ctx); return; } // Escape that cancels a ruler-origin drag or floating Tools move skips the tool and later Escape actions, @@ -266,7 +266,6 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { continue; } if k == Key::Escape && escape_ended_gesture { - remember_escape_pair(ctx, k, escape_pair); continue; } // A key the tool claims (Esc with a loaded place cursor) is only the tool's. @@ -283,7 +282,12 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { .unwrap_or(i.modifiers); crate::canvas::mods(m, false) }); + let ends = k == Key::Escape && app.session.tool_ends_on_escape(view); + let before = (k == Key::Escape && !ends).then(|| document_revision(app)); let r = app.session.tool_key(tk, mods, view); + // An Escape that ended something in the tool (a path being drawn, a selected point) ends + // nothing else. A hover highlight it clears does not count. + let tool_took = ends || before.is_some_and(|b| b != document_revision(app)); // Enter also takes what the tool asks of the UI: Rotate, Scale, Reflect and Shear open // their dialog with it. if claimed || (k == Key::Enter && !busy) { @@ -293,33 +297,9 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, k)); } - if k == Key::Escape && !busy && !claimed && !escape_held_by_drag { - if app.session.active().is_some_and(|d| d.doc.pattern_edit.is_some()) { - let _ = app.run("object.pattern.done", json!({})); - } else if app.session.active().is_some_and(|d| d.isolation.is_some()) { - let _ = app.run("object.exitIsolation", json!({})); - } else if app.session.active().is_some_and(|d| d.global_edit.is_some()) { - let _ = app.run("select.globalEdit", json!({})); - } else if app.ui.flyout.is_some() { - app.ui.flyout = None; - } else if escape_pair.is_some_and(|second| escape_resets_rotation(app, ctx, second)) { - // Escape pressed twice resets a rotated view (with the Rotate View tool, once). - let _ = app.run("view.rotateReset", json!({})); - escape_pair = None; - } else if matches!(app.ui.screen_mode, 1 | 2) - && !egui::Popup::is_any_open(ctx) - && !text_focused_in_previous_frame(ctx) - && ctx.input(|i| { - i.events.iter().any(|e| { - matches!(e, egui::Event::Key { key: Key::Escape, pressed: true, repeat: false, modifiers, .. } if *modifiers == Modifiers::NONE) - }) - }) - { - let _ = app.run("view.screenMode", json!({ "mode": 0 })); - } + if k == Key::Escape && !busy && !claimed && !escape_held_by_drag && !tool_took { + escape_ends_one_thing(app, ctx); } - // An Escape that ended something can start a pair too. One that closed a popup cannot. - remember_escape_pair(ctx, k, escape_pair); if k == Key::Enter && !busy && !claimed { // Enter with a selection tool opens the Move dialog, as a double-click on its button // does. @@ -486,13 +466,45 @@ fn escape_ended_gesture(ctx: &egui::Context) -> bool { held } -fn remember_escape_pair(ctx: &egui::Context, key: Key, escape_pair: Option) { - if key == Key::Escape && escape_pair.is_some() && !egui::Popup::is_any_open(ctx) { - let now = ctx.input(|i| i.time); - ctx.data_mut(|d| d.insert_temp(escape_pair_id(), now)); +/// An Escape that no tool, field, popup or drag took ends the first of these that is on: pattern +/// editing, isolation mode, Global Edit, a tool flyout, a full screen mode and a rotated view. +fn escape_ends_one_thing(app: &mut VectorcraftApp, ctx: &egui::Context) { + if app.session.active().is_some_and(|d| d.doc.pattern_edit.is_some()) { + let _ = app.run("object.pattern.done", json!({})); + } else if app.session.active().is_some_and(|d| d.isolation.is_some()) { + let _ = app.run("object.exitIsolation", json!({})); + } else if app.session.active().is_some_and(|d| d.global_edit.is_some()) { + let _ = app.run("select.globalEdit", json!({})); + } else if app.ui.flyout.is_some() { + app.ui.flyout = None; + } else if app.session.tool_id() == "rotateView" && escape_resets_rotation(app, ctx) { + // With the Rotate View tool, the view resets before a full screen mode ends. + let _ = app.run("view.rotateReset", json!({})); + } else if matches!(app.ui.screen_mode, 1 | 2) + && !egui::Popup::is_any_open(ctx) + && !text_focused_in_previous_frame(ctx) + && ctx.input(|i| { + i.events.iter().any( + |e| matches!(e, egui::Event::Key { key: Key::Escape, pressed: true, repeat: false, modifiers, .. } if *modifiers == Modifiers::NONE), + ) + }) + { + let _ = app.run("view.screenMode", json!({ "mode": 0 })); + } else if escape_resets_rotation(app, ctx) { + // An Escape that has nothing else to end resets a rotated view. After one that ended + // something, the next one does, however long after it comes. A modified Escape does not + // leave a full screen mode, so it resets the view there. + let _ = app.run("view.rotateReset", json!({})); } } +/// What a tool's Escape can change besides what [`vectorcraft_engine::Session::tool_ends_on_escape`] +/// reports: the document's revision (edits and selection changes, such as the Curvature tool +/// letting go of a selected path's current point). +fn document_revision(app: &VectorcraftApp) -> Option { + app.session.active().map(|d| d.revision) +} + /// Dispatch unmodified text keys to command bindings or tools. fn single_key_shortcuts(app: &mut VectorcraftApp, ctx: &egui::Context) { // Single-key tool shortcuts (no Cmd/Ctrl/Alt). With a layout without Latin letters (Persian, diff --git a/crates/ui-egui/src/shortcuts/presentation.rs b/crates/ui-egui/src/shortcuts/presentation.rs index da746cbf5f..1c447d09e6 100644 --- a/crates/ui-egui/src/shortcuts/presentation.rs +++ b/crates/ui-egui/src/shortcuts/presentation.rs @@ -1,45 +1,18 @@ -use super::{Key, VectorcraftApp, is_modifier, json}; +use super::{Key, VectorcraftApp, json}; -/// The second press of Escape pressed twice comes less than this many seconds after the first. -const ESCAPE_PAIR_SECONDS: f64 = 1.0; - -/// The key of the last counted Escape's time in egui's temporary data. -pub(super) fn escape_pair_id() -> egui::Id { - egui::Id::unique("escape-pair") -} - -/// Reads this frame's presses for Escape pressed twice. `None` when the frame has no Escape press, or -/// has another key or pointer button press as well (a key repeat counts as another press, and the -/// modifier keys do not count). Otherwise, whether the last counted Escape came less than -/// [`ESCAPE_PAIR_SECONDS`] before. A press of Escape, another key or a pointer button removes the -/// last counted Escape's time. -pub(super) fn escape_press(ctx: &egui::Context) -> Option { - let (escape, other, now) = ctx.input(|i| { - let (mut escape, mut other) = (false, false); - for e in &i.events { - match e { - egui::Event::Key { key: Key::Escape, pressed: true, repeat: false, .. } => escape = true, - egui::Event::Key { key, pressed: true, .. } if !is_modifier(*key) => other = true, - egui::Event::PointerButton { pressed: true, .. } => other = true, - _ => {} - } - } - (escape, other, i.time) - }); - if !escape && !other { - return None; - } - let counted = ctx.data_mut(|d| d.remove_temp::(escape_pair_id())); - (escape && !other).then(|| counted.is_some_and(|t| now - t < ESCAPE_PAIR_SECONDS)) -} - -/// Does this Escape reset the view's rotation? It does when the view is rotated, no popup is open, -/// neither a ruler-origin drag nor a floating Tools move is ending, and the press is the second of -/// a pair (`second`) or the Rotate View tool is chosen. -pub(super) fn escape_resets_rotation(app: &VectorcraftApp, ctx: &egui::Context, second: bool) -> bool { +/// Does this Escape reset the view's rotation? The caller has checked that nothing earlier took +/// the press. It does when the view is rotated; no popup, modal window (a progress window, About) +/// or Appearance row popup is open; no text field had the keyboard in the last frame (egui takes +/// the focus away on Escape before this runs); no pointer button is held or let go in this frame +/// (a tab or panel drag takes the Escape, in its release frame too); and neither a ruler-origin +/// drag nor a floating Tools move is ending. +pub(super) fn escape_resets_rotation(app: &VectorcraftApp, ctx: &egui::Context) -> bool { app.view().is_some_and(|v| v.rotation != 0.0) - && (second || app.session.tool_id() == "rotateView") && !egui::Popup::is_any_open(ctx) + && !crate::panel_docking::modal_open(app, ctx) + && app.ui.transient_panel.is_none() + && !super::text_focused_in_previous_frame(ctx) + && !ctx.input(|i| i.pointer.any_down() || i.pointer.any_released()) && !crate::canvas::ruler_origin_dragging(ctx) && !crate::tools_float::escape_cancelled_move(ctx) } @@ -48,7 +21,7 @@ pub(super) fn escape_resets_rotation(app: &VectorcraftApp, ctx: &egui::Context, /// the previous and the next artboard ([`presentation_step`]). Every other key press, the text it /// types and the clipboard keys are removed from the input, so no shortcut, tool or field acts on /// them. The macOS menu bar's key equivalents arrive as key presses too ([`crate::native_menu`]). -pub(super) fn presentation_keys(app: &mut VectorcraftApp, ctx: &egui::Context, escape_pair: Option) { +pub(super) fn presentation_keys(app: &mut VectorcraftApp, ctx: &egui::Context) { let (mut leave, mut steps) = (false, vec![]); ctx.input_mut(|i| { i.events.retain(|e| match e { @@ -80,11 +53,6 @@ pub(super) fn presentation_keys(app: &mut VectorcraftApp, ctx: &egui::Context, e } if leave { let _ = app.run("view.presentation", json!({})); - // The Escape that left the mode can start a pair, as in `handle`. - if escape_pair.is_some() && !egui::Popup::is_any_open(ctx) { - let now = ctx.input(|i| i.time); - ctx.data_mut(|d| d.insert_temp(escape_pair_id(), now)); - } } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 64574e52d2..dfe85768cf 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -348,6 +348,21 @@ pub struct ReplaceFontWarning { pub styles: Vec<(String, String)>, } +/// A misspelled word right-clicked on the canvas ([`UiState::context_spelling`]). +#[derive(Clone, Debug, PartialEq)] +pub struct ContextSpelling { + /// The document's `uid`. + pub uid: u64, + /// The type object. + pub id: vectorcraft_doc::NodeId, + /// The word's bytes in the object's plain text, which `text.editRange` replaces. + pub start: usize, + pub end: usize, + pub word: String, + /// What the dictionary of the word's language suggests instead, best first. + pub suggestions: Vec, +} + #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct UiState { @@ -377,6 +392,11 @@ pub struct UiState { /// That popup's first text field is still to take the keyboard. #[serde(skip)] pub transient_focus: bool, + /// The Separations Preview panel is still to scroll its Color Settings section into view: + /// Edit › Color Settings… and Assign Profile… show the panel for it, and the section sits below + /// the plates and Proof Setup, out of sight in a short window (#6419). + #[serde(skip)] + pub color_settings_scroll: bool, /// Type › Find Font…'s last Find In choice (`find_font::FIND_IN`), kept while the app runs. #[serde(skip)] pub find_font_in: String, @@ -415,6 +435,10 @@ pub struct UiState { /// while it is open ([`crate::panels::artboards::MenuFacts`]). Not saved. #[serde(skip)] pub context_artboards: Option, + /// The word with Auto Spell Check's red line under the last right-click on the canvas, for the + /// context menu's suggestions, Ignore All and Add to Dictionary while it is open. Not saved. + #[serde(skip)] + pub context_spelling: Option, /// Which link statuses the active document's images and placed documents have, for Select › /// Linked, Embedded, Missing and Modified to be on only when some do (refreshed by /// [`crate::addons::select::link_status::refresh`]). Not saved. @@ -990,6 +1014,7 @@ impl Default for UiState { open_panel: None, transient_panel: None, transient_focus: false, + color_settings_scroll: false, find_font_in: String::new(), control_bar: false, control_bar_bottom: false, @@ -1002,6 +1027,7 @@ impl Default for UiState { context_locked: None, context_intertwine: None, context_artboards: None, + context_spelling: None, link_statuses: Default::default(), slot_tool: Default::default(), floating_flyouts: vec![], diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 2593115f60..261a250542 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -39,6 +39,7 @@ mod saveext; mod screenmode; mod screenshots; mod script_check; +mod script_run; mod scrub; mod selectall; mod selectescape; diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 6dadd856cd..b443d84586 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -204,7 +204,10 @@ fn labels(items: &[Item]) -> Vec<&'static str> { items .iter() .flat_map(|it| match it { + // A spelling suggestion shows the word it puts in, not its label. + Item::Cmd(_, "text.editRange", _) => vec![], Item::Cmd(l, ..) => vec![*l], + Item::Header(l) => vec![*l], Item::Sub(l, ch) => std::iter::once(*l).chain(labels(ch)).collect(), _ => vec![], }) @@ -288,6 +291,46 @@ fn selected_type_has_apply_numbers() { assert_eq!(text.para_at(0).list.and_then(|l| l.number), Some(vectorcraft_doc::text::NumberStyle::Arabic)); } +/// A right-click on type has Spelling › Auto Spell Check, which turns it on or off as Edit › +/// Spelling does (helpx: Check and correct spelling, "Turn on Auto Spell Check"). The context menu +/// draws no check marks, but this submenu holds only the toggle, so it shows whether it is on; +/// other submenus stay without the room for one. Other art has no Spelling submenu. +#[test] +fn right_click_on_type_turns_auto_spell_check_on_and_off() { + let mut app = app(); + let r = rect(&mut app, 200.0, 150.0); + let t = NodeId(app.run("text.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 24})).unwrap()["id"].as_u64().unwrap()); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = screen(&app, 250.0, 200.0); + assert!(!has(&click(&mut app, &ctx, p, PointerButton::Secondary), "Spelling"), "a rectangle has no Spelling submenu"); + assert_eq!(app.session.active().unwrap().selection.objects, [r]); + let away = screen(&app, 390.0, 290.0); + click(&mut app, &ctx, away, PointerButton::Primary); + // Right-click the type, open Spelling: Auto Spell Check, not checked. + let open_spelling = |app: &mut VectorcraftApp| { + let p = word_at(app, t, 0, 5); + let texts = click(app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, [t], "the type right-clicked is selected"); + frame(app, &ctx, vec![Event::PointerMoved(at(&texts, "Spelling"))]); + frame(app, &ctx, vec![]) + }; + let texts = open_spelling(&mut app); + assert!(texts.iter().any(|(s, _)| s == " Auto Spell Check"), "unchecked, with the room for a check mark: {texts:?}"); + assert!(texts.iter().any(|(s, _)| s == "Transform"), "other items have no gutter: {texts:?}"); + // Agents see it under the Spelling path. + let e = menus::context_entries(&app).into_iter().find(|e| e.command.as_deref() == Some("edit.autoSpellCheck")).expect("Auto Spell Check"); + assert_eq!((e.path.as_slice(), e.label.as_str()), (&["Spelling".to_string()][..], "Auto Spell Check")); + let texts = click(&mut app, &ctx, at(&texts, " Auto Spell Check"), PointerButton::Primary); + assert!(app.ui.view.auto_spell_check, "turned on"); + assert!(!has(&texts, "Spelling"), "the menu closed: {texts:?}"); + let texts = open_spelling(&mut app); + assert!(texts.iter().any(|(s, _)| s == "✓ Auto Spell Check"), "checked: {texts:?}"); + click(&mut app, &ctx, at(&texts, "✓ Auto Spell Check"), PointerButton::Primary); + assert!(!app.ui.view.auto_spell_check, "turned off"); +} + /// The members of the overlap area of Intertwine group `g` at (x, y), in the order they are drawn /// there, bottom first. fn intertwine_order(app: &VectorcraftApp, g: NodeId, x: f64, y: f64) -> Vec { @@ -370,6 +413,18 @@ fn every_context_label_is_a_menu_string() { app.run("layer.setProps", json!({"ids": [a.0], "locked": true})).unwrap(); app.ui.context_locked = Some((app.session.active().unwrap().uid, vec![a])); shown.extend(labels(&menus::context_items(&app))); + // A word Auto Spell Check underlined, with no suggestions: Ignore All, Add to Dictionary. + let text = NodeId(app.run("text.create", json!({"x": 10, "y": 200, "text": "Zqxvbtkw"})).unwrap()["id"].as_u64().unwrap()); + app.ui.context_spelling = Some(crate::state::ContextSpelling { + uid: app.session.active().unwrap().uid, + id: text, + start: 0, + end: 8, + word: "Zqxvbtkw".into(), + suggestions: vec![], + }); + shown.extend(labels(&menus::context_items(&app))); + app.ui.context_spelling = None; // The Lock Artboards and Unlock Artboards submenus of the Artboard tool. app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 80})).unwrap(); app.run("artboard.setProps", json!({"index": 0, "locked": true})).unwrap(); @@ -384,3 +439,172 @@ fn every_context_label_is_a_menu_string() { assert!(shown.contains(label), "`{label}` is listed but the context menu never shows it"); } } + +/// Point type holding `t` at (20, 60), with Auto Spell Check on. +fn spelled(app: &mut VectorcraftApp, t: &str) -> NodeId { + let id = NodeId(app.run("text.create", json!({"x": 20, "y": 60, "text": t, "size": 24})).unwrap()["id"].as_u64().unwrap()); + app.run("select.none", json!({})).unwrap(); + app.run("edit.autoSpellCheck", json!({})).unwrap(); + id +} + +/// Where on screen the middle of bytes `a..b` of type object `id` is. +fn word_at(app: &VectorcraftApp, id: NodeId, a: usize, b: usize) -> Pos2 { + let st = app.session.active().unwrap(); + let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { panic!("type") }; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let q = vectorcraft_text::selection_quads(&lay, a, b)[0].map(|c| t.xf * c); + let c = Point::new(q.iter().map(|p| p.x).sum::() / 4.0, q.iter().map(|p| p.y).sum::() / 4.0); + screen(app, c.x, c.y) +} + +fn plain(app: &VectorcraftApp, id: NodeId) -> String { + match app.session.active().unwrap().doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t.plain_text(), + _ => panic!("type"), + } +} + +/// With Auto Spell Check on, right-clicking an underlined word lists what the dictionary suggests +/// instead, then Ignore All and Add to Dictionary; a suggestion replaces the word in one undo step +/// (helpx: Check and correct spelling, "Correct spelling errors during Auto Spell Check"). +#[test] +fn right_click_on_an_underlined_word_offers_its_suggestions() { + let mut app = app(); + let id = spelled(&mut app, "the speling cat"); + let want: Vec = app.session.execute("text.spelling.suggest", &json!({"word": "speling"})).unwrap()["suggestions"] + .as_array() + .unwrap() + .iter() + .map(|s| s.as_str().unwrap().to_string()) + .collect(); + assert!(!want.is_empty(), "the dictionary has suggestions for `speling`"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = word_at(&app, id, 4, 11); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + for w in &want { + assert!(has(&texts, w), "`{w}` in {texts:?}"); + } + assert!(has(&texts, "Ignore All") && has(&texts, "Add to Dictionary"), "{texts:?}"); + // Agents see them at the top of the menu, a suggestion by its word. + let entries = menus::context_entries(&app); + assert_eq!((entries[0].label.as_str(), entries[0].command.as_deref()), (want[0].as_str(), Some("text.editRange"))); + let steps = app.session.active().unwrap().history.undo.len(); + let texts = click(&mut app, &ctx, at(&texts, &want[0]), PointerButton::Primary); + assert_eq!(plain(&app, id), format!("the {} cat", want[0]), "the word is replaced"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "in one undo step"); + assert!(!has(&texts, "Ignore All"), "the menu closed: {texts:?}"); +} + +/// Ignore All and Add to Dictionary from the menu: the word's line goes, in this document for +/// Ignore All, in every check for Add. A word with nothing to suggest says so. +#[test] +fn ignore_all_and_add_to_dictionary_from_the_context_menu() { + let mut app = app(); + let id = spelled(&mut app, "Qzvxtrwk and Kwqzvxtr"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = word_at(&app, id, 0, 8); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(has(&texts, "No Suggestions"), "{texts:?}"); + click(&mut app, &ctx, at(&texts, "Ignore All"), PointerButton::Primary); + assert!(app.session.active().unwrap().spelling_ignored.contains("qzvxtrwk")); + let p = word_at(&app, id, 13, 21); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + click(&mut app, &ctx, at(&texts, "Add to Dictionary"), PointerButton::Primary); + let added = craft_proof_has(&mut app, "kwqzvxtr"); + app.run("text.spelling.removeWord", json!({"word": "kwqzvxtr"})).unwrap(); + assert!(added, "added to the custom dictionary"); + // Nothing left underlined there: a right-click on it offers no spelling items. + let p = word_at(&app, id, 0, 8); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(!has(&texts, "Ignore All"), "{texts:?}"); +} + +fn craft_proof_has(app: &mut VectorcraftApp, w: &str) -> bool { + app.run("text.spelling.dictionary", json!({})).unwrap()["words"].as_array().unwrap().iter().any(|x| x == w) +} + +/// With Auto Spell Check off, or on a word that is right, a right-click lists no spelling items. +#[test] +fn no_spelling_items_off_a_misspelled_word_or_with_auto_spell_check_off() { + let mut app = app(); + let id = spelled(&mut app, "the Vqzxtrwk"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = word_at(&app, id, 0, 3); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(!has(&texts, "Ignore All"), "a right word: {texts:?}"); + app.run("edit.autoSpellCheck", json!({})).unwrap(); + frame( + &mut app, + &ctx, + vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + ); + let p = word_at(&app, id, 4, 12); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(!has(&texts, "Ignore All"), "off: {texts:?}"); +} + +/// A right word in type on top of an underlined word in other type: the right-click is on the +/// top type, so it lists no spelling items for the word under it. +#[test] +fn a_word_under_other_type_is_not_the_one_right_clicked() { + let mut app = app(); + let under = spelled(&mut app, "Qzvxtrwk"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = word_at(&app, under, 0, 8); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(has(&texts, "Ignore All"), "alone, the word is offered: {texts:?}"); + frame( + &mut app, + &ctx, + vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + ); + app.run("text.create", json!({"x": 20, "y": 60, "text": "the cat sat on the mat", "size": 24})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(!has(&texts, "Ignore All"), "under right type: {texts:?}"); +} + +/// In an Intertwine group, the type drawn on top at the right-click is the one whose word is +/// offered: a member brought to the front there, though earlier in the stacking order. +#[test] +fn in_an_intertwine_group_the_type_drawn_on_top_is_the_one_right_clicked() { + let mut app = app(); + let under = spelled(&mut app, "Qzvxtrwk"); + let over = + NodeId(app.run("text.create", json!({"x": 20, "y": 60, "text": "the cat sat on the mat", "size": 24})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [under.0, over.0]})).unwrap(); + let g = NodeId(app.run("object.intertwine.make", json!({})).unwrap()["id"].as_u64().unwrap()); + app.select_tool("selection"); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + // A point on the word where glyphs of both overlap: Intertwine's areas follow the outlines. + let quad = { + let st = app.session.active().unwrap(); + let Some(NodeKind::Text(t)) = st.doc.node(under).map(|n| &n.kind) else { panic!("type") }; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + vectorcraft_text::selection_quads(&lay, 0, 8)[0].map(|c| t.xf * c) + }; + let (x0, x1) = (quad.iter().map(|c| c.x).fold(f64::MAX, f64::min), quad.iter().map(|c| c.x).fold(f64::MIN, f64::max)); + let (y0, y1) = (quad.iter().map(|c| c.y).fold(f64::MAX, f64::min), quad.iter().map(|c| c.y).fold(f64::MIN, f64::max)); + let overlap = (0..40) + .flat_map(|i| (0..20).map(move |j| Point::new(x0 + (x1 - x0) * (i as f64 + 0.5) / 40.0, y0 + (y1 - y0) * (j as f64 + 0.5) / 20.0))) + .find(|q| app.run("object.intertwine.arrange", json!({"id": g.0, "at": [q.x, q.y], "order": "back", "member": under.0})).is_ok()) + .expect("glyphs of both overlap somewhere on the word"); + let p = screen(&app, overlap.x, overlap.y); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(!has(&texts, "Ignore All"), "under the right type: {texts:?}"); + frame( + &mut app, + &ctx, + vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + ); + app.run("object.intertwine.arrange", json!({"id": g.0, "at": [overlap.x, overlap.y], "order": "front", "member": under.0})).unwrap(); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(has(&texts, "Ignore All"), "brought to the front there: {texts:?}"); +} diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index fa80c359d9..ea79c1d5cc 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -238,8 +238,24 @@ fn panel_frame( family: &str, draw: &dyn Fn(&mut VectorcraftApp, &mut egui::Ui), ) -> (Option, bool) { - let mut input = - egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0))), ..Default::default() }; + panel_frame_at(ctx, app, None, events, family, draw) +} + +/// [`panel_frame`] with the input's clock set to `time` seconds. +fn panel_frame_at( + ctx: &egui::Context, + app: &mut VectorcraftApp, + time: Option, + events: Vec, + family: &str, + draw: &dyn Fn(&mut VectorcraftApp, &mut egui::Ui), +) -> (Option, bool) { + let mut input = egui::RawInput { + time, + events, + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0))), + ..Default::default() + }; app.raw_input_hook(ctx, &mut input); let mut out = ctx.run_ui(input, |ui| { crate::font_menu::end_stale_preview(app, ui.ctx()); @@ -394,13 +410,16 @@ fn wheel_events_use_the_pointer_position_when_they_occurred() { assert_eq!(first_style(&app, id).font_family, "Inter", "the wheel was outside the field"); assert_eq!(app.session.active().unwrap().history.undo.len(), before); assert!(ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. }))), "outside wheel input is left for its owner"); - panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, Default::default()), egui::Event::PointerMoved(outside)], "Inter", &draw); + let after_gap = |ctx: &egui::Context| Some(ctx.input(|i| i.time) + crate::widgets::WHEEL_STREAM_GAP); + let later = after_gap(&ctx); + panel_frame_at(&ctx, &mut app, later, vec![wheel(line, -1.0, Default::default()), egui::Event::PointerMoved(outside)], "Inter", &draw); assert_ne!(first_style(&app, id).font_family, "Inter", "the wheel was over the field before the pointer left"); assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); app.run("edit.undo", json!({})).unwrap(); assert_eq!(first_style(&app, id).font_family, "Inter"); let button = |pos| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; - panel_frame(&ctx, &mut app, vec![button(field), wheel(line, -1.0, Default::default()), button(outside)], "Inter", &draw); + let later = after_gap(&ctx); + panel_frame_at(&ctx, &mut app, later, vec![button(field), wheel(line, -1.0, Default::default()), button(outside)], "Inter", &draw); assert_ne!(first_style(&app, id).font_family, "Inter", "button events also carry the pointer's position"); assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); app.run("edit.undo", json!({})).unwrap(); @@ -412,20 +431,32 @@ fn wheel_events_use_the_pointer_position_when_they_occurred() { source: egui::MouseWheelSource::Unknown, }; panel_frame(&ctx, &mut app, vec![end], "Inter", &draw); - panel_frame( + let later = after_gap(&ctx); + panel_frame_at( &ctx, &mut app, + later, vec![ - wheel(egui::MouseWheelUnit::Point, -2.0, Default::default()), egui::Event::PointerMoved(field), wheel(line, -1.0, Default::default()), egui::Event::PointerMoved(outside), + wheel(egui::MouseWheelUnit::Point, -2.0, Default::default()), ], "Inter", &draw, ); assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); assert_eq!(ctx.input(|i| i.smooth_scroll_delta.y), -2.0, "only the outside wheel contributes to panel scrolling"); + // A fractional turn made before the pointer reached the field does not count toward its notches. + let speed = ctx.options(|o| o.input_options.line_scroll_speed); + let later = after_gap(&ctx); + let early = wheel(egui::MouseWheelUnit::Point, -0.75 * speed, Default::default()); + panel_frame_at(&ctx, &mut app, later, vec![early, egui::Event::PointerMoved(field)], "Inter", &draw); + let later = after_gap(&ctx); + panel_frame_at(&ctx, &mut app, later, vec![wheel(line, -0.5, Default::default())], "Inter", &draw); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1, "half a notch on the field"); + panel_frame(&ctx, &mut app, vec![wheel(line, -0.5, Default::default())], "Inter", &draw); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 2, "a whole notch on the field"); } /// A turn queued for one document cannot restyle another document opened before its UI pass. @@ -514,6 +545,97 @@ fn the_wheel_steps_the_families_in_properties_and_the_control_bar() { } } +/// The Character panel in a scroll area, its family field near the bottom of the view. +fn scrolling_character_panel(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { + ui.add_space(250.0); + crate::panels::character::show(app, ui); + ui.add_space(600.0); + }); +} + +/// Scrolling a panel with a still pointer keeps going when the closed family field slides under +/// the pointer, and the font stays as it was. +#[test] +fn scrolling_a_panel_past_the_family_field_under_a_still_pointer_keeps_the_font() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let draw = scrolling_character_panel; + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.expect("the panel shows the family field"); + let still = egui::pos2(field.x, field.y - 120.0); + panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(still)], "Inter", &draw); + let before = app.session.active().unwrap().history.undo.len(); + let mut passed = false; + for _ in 0..240 { + let at = panel_frame(&ctx, &mut app, vec![wheel(egui::MouseWheelUnit::Point, -6.0, Default::default())], "Inter", &draw).0; + if at.is_some_and(|point| point.y < still.y - 30.0) { + passed = true; + break; + } + } + assert!(passed, "the panel scrolled the field past the pointer"); + assert_eq!(first_style(&app, id).font_family, "Inter"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); +} + +/// A family field that a panel scrolled under a still pointer leaves later wheel input to the +/// panel, including after the stream ends, until the pointer really moves. +#[test] +fn a_family_field_scrolled_under_a_still_pointer_takes_the_wheel_after_the_pointer_moves() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let draw = scrolling_character_panel; + let mut time = 100.0; + let mut field = None; + for _ in 0..3 { + time += 0.02; + field = panel_frame_at(&ctx, &mut app, Some(time), vec![], "Inter", &draw).0; + } + let field = field.expect("the panel shows the family field"); + let still = egui::pos2(field.x, field.y - 40.0); + time += 0.02; + panel_frame_at(&ctx, &mut app, Some(time), vec![egui::Event::PointerMoved(still)], "Inter", &draw); + let before = app.session.active().unwrap().history.undo.len(); + let mut under = false; + for _ in 0..80 { + time += 0.02; + panel_frame_at(&ctx, &mut app, Some(time), vec![wheel(egui::MouseWheelUnit::Point, -3.0, Default::default())], "Inter", &draw); + let mut at = None; + for _ in 0..12 { + time += 0.02; + at = panel_frame_at(&ctx, &mut app, Some(time), vec![], "Inter", &draw).0; + } + if at.is_some_and(|point| (point.y - still.y).abs() < 4.0) { + under = true; + break; + } + } + assert!(under, "the panel scrolled the field under the pointer"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + time += 5.0; + let notch = || wheel(egui::MouseWheelUnit::Line, -1.0, Default::default()); + panel_frame_at(&ctx, &mut app, Some(time), vec![notch()], "Inter", &draw); + assert_eq!(first_style(&app, id).font_family, "Inter", "the still pointer did not arm the field"); + let mut at = None; + for _ in 0..12 { + time += 0.02; + at = panel_frame_at(&ctx, &mut app, Some(time), vec![], "Inter", &draw).0; + } + let at = at.expect("the field is still in view"); + time += 5.0; + panel_frame_at(&ctx, &mut app, Some(time), vec![egui::Event::PointerMoved(at), notch()], "Inter", &draw); + assert_ne!(first_style(&app, id).font_family, "Inter", "the pointer moved onto the field"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); +} + /// #5253: a family the wheel steps to keeps the type's style when it has that style, else takes the /// closest it has, as a family picked from the menu does. The menus that only pick a font ignore /// the wheel. diff --git a/crates/ui-egui/src/tests/numfields.rs b/crates/ui-egui/src/tests/numfields.rs index d83938555e..45801c22ec 100644 --- a/crates/ui-egui/src/tests/numfields.rs +++ b/crates/ui-egui/src/tests/numfields.rs @@ -1007,6 +1007,239 @@ fn the_wheel_scrolls_the_panel_unless_over_a_numeric_field() { } } +/// A wheel notch of `dy` lines (up positive) from `source`, with no pointer movement. +fn notch(dy: f32, source: egui::MouseWheelSource) -> Event { + Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, dy), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE, source } +} + +/// A notch down from a mouse wheel. +fn notch_down() -> Event { + notch(-1.0, egui::MouseWheelSource::Wheel) +} + +/// A panel scrolled with a still pointer keeps scrolling when a number field slides under the +/// pointer, and the field keeps its value. The field used to take each notch that came while it +/// was under the pointer. +#[test] +fn scrolling_a_panel_past_a_number_field_under_a_still_pointer_keeps_the_value() { + let mut f = Field::new(); + let offset = Cell::new(0.0); + let value = Cell::new(10.0); + let draw = |ui: &mut egui::Ui| { + let out = egui::ScrollArea::vertical().max_height(120.0).show(ui, |ui| { + ui.add_space(60.0); + let v = widgets::plain_field(ui, "f", value.get(), "", 0, 80.0).inspect(|&v| value.set(v)); + ui.add_space(600.0); + v + }); + offset.set(out.state.clamped_offset().y); + out.inner + }; + f.frame(vec![], &draw); + f.frame(vec![Event::PointerMoved(Pos2::new(20.0, 20.0))], &draw); + let mut stepped = None; + for _ in 0..30 { + stepped = stepped.or(f.frame(vec![notch_down()], &draw)); + } + for _ in 0..20 { + f.frame(vec![], &draw); + } + assert_eq!((stepped, value.get()), (None, 10.0), "the field kept its value"); + assert!(offset.get() > 200.0, "the panel scrolled the field past the pointer: {}", offset.get()); +} + +/// A number field that slid under a still pointer takes the wheel only after the pointer is moved +/// onto it; an event at the same position is not a move. Until then the panel scrolls. +#[test] +fn a_number_field_that_slid_under_a_still_pointer_steps_after_the_pointer_moves() { + let mut f = Field::new(); + let top = Cell::new(60.0); + let value = Cell::new(10.0); + let draw = |ui: &mut egui::Ui| { + ui.add_space(top.get()); + widgets::plain_field(ui, "f", value.get(), "", 0, 80.0).inspect(|&v| value.set(v)) + }; + f.frame(vec![], &draw); + let at = Pos2::new(20.0, 20.0); + f.frame(vec![Event::PointerMoved(at)], &draw); + top.set(0.0); + f.frame(vec![], &draw); + assert!(f.rect.get().contains(at), "the field is under the pointer"); + for _ in 0..2 { + f.time += crate::widgets::WHEEL_STREAM_GAP; + assert_eq!(f.frame(vec![notch_down()], &draw), None, "the pointer did not move"); + } + f.time += crate::widgets::WHEEL_STREAM_GAP; + assert_eq!(f.frame(vec![Event::PointerMoved(at), notch_down()], &draw), None, "the same position"); + f.time += crate::widgets::WHEEL_STREAM_GAP; + let moved = Pos2::new(21.0, 20.0); + assert_eq!(f.frame(vec![Event::PointerMoved(moved), notch_down()], &draw), Some(9.0)); + // The field moves again under the pointer, in the frame of a turn: the turn is not the field's, + // and the field waits for another move. + top.set(2.0); + assert_eq!(f.frame(vec![notch_down()], &draw), None, "the field moved in the frame of the turn"); + f.time += crate::widgets::WHEEL_STREAM_GAP; + assert_eq!(f.frame(vec![notch_down()], &draw), None, "the field moved"); + f.time += crate::widgets::WHEEL_STREAM_GAP; + assert_eq!(f.frame(vec![Event::PointerMoved(at), notch_down()], &draw), Some(8.0)); +} + +/// A wheel stream stays with what it began on until it pauses for the stream gap: one that began +/// off the field never steps it, one that left the field (the pointer moved off it or out of the +/// window) does not come back to it, and trackpad momentum never starts one on the field. +#[test] +fn a_number_field_wheel_stream_stays_with_what_it_began_on() { + use egui::MouseWheelSource::{Momentum, Trackpad}; + let mut f = Field::new(); + let value = Cell::new(10.0); + let draw = |ui: &mut egui::Ui| widgets::plain_field(ui, "f", value.get(), "", 0, 80.0).inspect(|&v| value.set(v)); + f.frame(vec![], &draw); + let (on, off) = (f.rect.get().center(), Pos2::new(300.0, 150.0)); + let gap = |f: &mut Field| f.time += crate::widgets::WHEEL_STREAM_GAP; + // Began on the field, left it, came back within the stream. + assert_eq!(f.frame(vec![Event::PointerMoved(on), notch_down()], &draw), Some(9.0)); + assert_eq!(f.frame(vec![Event::PointerMoved(off), notch_down()], &draw), None); + assert_eq!(f.frame(vec![Event::PointerMoved(on), notch_down()], &draw), None, "left its field"); + gap(&mut f); + assert_eq!(f.frame(vec![notch_down()], &draw), Some(8.0), "a new stream"); + // Began off the field. + f.frame(vec![Event::PointerMoved(off)], &draw); + gap(&mut f); + assert_eq!(f.frame(vec![notch_down()], &draw), None); + assert_eq!(f.frame(vec![Event::PointerMoved(on), notch_down()], &draw), None, "began off the field"); + gap(&mut f); + assert_eq!(f.frame(vec![notch_down()], &draw), Some(7.0)); + // The pointer left the window. + assert_eq!(f.frame(vec![Event::PointerGone], &draw), None); + assert_eq!(f.frame(vec![Event::PointerMoved(on), notch_down()], &draw), None, "left the window"); + // Momentum after a pause starts no stream on the field, and the stream it starts stays off it. + gap(&mut f); + assert_eq!(f.frame(vec![notch(-1.0, Momentum)], &draw), None, "momentum"); + assert_eq!(f.frame(vec![notch(-1.0, Trackpad)], &draw), None, "the momentum's stream"); + gap(&mut f); + assert_eq!(f.frame(vec![notch(-1.0, Trackpad)], &draw), Some(6.0)); + assert_eq!(value.get(), 6.0); +} + +/// A frame whose turns begin on the field and go on after the pointer moved off it scrolls the +/// panel with all of them and leaves the value. +#[test] +fn a_frame_with_turns_on_and_off_a_number_field_scrolls_the_panel() { + let mut f = Field::new(); + let offset = Cell::new(0.0); + let value = Cell::new(10.0); + let draw = |ui: &mut egui::Ui| { + let out = egui::ScrollArea::vertical().max_height(120.0).show(ui, |ui| { + let v = widgets::plain_field(ui, "f", value.get(), "", 0, 80.0).inspect(|&v| value.set(v)); + ui.add_space(600.0); + v + }); + offset.set(out.state.clamped_offset().y); + out.inner + }; + f.frame(vec![], &draw); + let (on, off) = (Pos2::new(20.0, 12.0), Pos2::new(20.0, 80.0)); + let events = vec![Event::PointerMoved(on), notch_down(), Event::PointerMoved(off), notch_down()]; + assert_eq!(f.frame(events, &draw), None); + assert!(offset.get() > 0.0, "the panel scrolled in the same frame"); + assert_eq!(value.get(), 10.0); +} + +/// A number field that missed a pass (its panel was hidden) waits for the pointer to move onto it +/// again before it takes the wheel, with or without another number field drawn meanwhile. +#[test] +fn a_number_field_that_missed_a_pass_waits_for_a_pointer_move() { + for other in [false, true] { + let mut f = Field::new(); + let shown = Cell::new(true); + let draw = |ui: &mut egui::Ui| { + let v = if shown.get() { widgets::plain_field(ui, "f", 10.0, "", 0, 80.0) } else { None }; + if other { + ui.add_space(100.0); + widgets::plain_field(ui, "other", 1.0, "", 0, 80.0); + } + v + }; + f.frame(vec![], &draw); + let at = Pos2::new(20.0, 12.0); + f.frame(vec![Event::PointerMoved(at)], &draw); + shown.set(false); + f.frame(vec![], &draw); + shown.set(true); + f.frame(vec![], &draw); + assert_eq!(f.frame(vec![notch_down()], &draw), None, "missed a pass, other field {other}"); + f.time += crate::widgets::WHEEL_STREAM_GAP; + assert_eq!(f.frame(vec![Event::PointerMoved(at + vec2(1.0, 0.0)), notch_down()], &draw), Some(9.0), "other field {other}"); + } +} + +/// Two number fields, `a` above `b`; the frame returns `b`'s new value, and `a`'s goes in `a`. +fn two_fields<'a>(a: &'a Cell, b: &'a Cell, rects: &'a Cell<[Rect; 2]>) -> impl Fn(&mut egui::Ui) -> Option + 'a { + move |ui: &mut egui::Ui| { + if let Some(v) = widgets::plain_field(ui, "a", a.get(), "", 0, 80.0) { + a.set(v); + } + let first = ui.min_rect(); + ui.add_space(40.0); + let top = ui.cursor().top(); + let v = widgets::plain_field(ui, "b", b.get(), "", 0, 80.0).inspect(|&v| b.set(v)); + rects.set([first, Rect::from_x_y_ranges(first.x_range(), top..=ui.min_rect().bottom())]); + v + } +} + +/// A stream that began on one number field scrolls the panel when the pointer moves onto another +/// field, until the wheel pauses for the stream gap or the pointer is pressed on the other field. +#[test] +fn a_press_on_a_number_field_gives_it_the_running_wheel_stream() { + let mut f = Field::new(); + let (a, b, rects) = (Cell::new(10.0), Cell::new(20.0), Cell::new([Rect::NOTHING; 2])); + let draw = two_fields(&a, &b, &rects); + f.frame(vec![], &draw); + let [on_a, on_b] = rects.get().map(|r| r.center()); + f.frame(vec![Event::PointerMoved(on_a), notch_down()], &draw); + assert_eq!(a.get(), 9.0, "the stream began on a"); + assert_eq!(f.frame(vec![Event::PointerMoved(on_b), notch_down()], &draw), None, "moved onto b within the stream"); + let press = |pressed| Event::PointerButton { pos: on_b, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + f.frame(vec![press(true), press(false)], &draw); + assert_eq!(f.frame(vec![notch_down()], &draw), Some(19.0), "pressed on b"); + assert_eq!(a.get(), 9.0); + // A press on the field that holds the stream keeps it there. + f.frame(vec![press(true), press(false)], &draw); + assert_eq!(f.frame(vec![notch_down()], &draw), Some(18.0)); +} + +/// A window or overlay that comes and goes over a still pointer, with no input while it is up, +/// leaves the number field under it waiting for the pointer to move onto it again. +#[test] +fn a_number_field_covered_by_an_overlay_waits_for_a_pointer_move() { + let mut f = Field::new(); + let value = Cell::new(10.0); + let covered = Cell::new(false); + let draw = |ui: &mut egui::Ui| { + let v = widgets::plain_field(ui, "f", value.get(), "", 0, 80.0).inspect(|&v| value.set(v)); + if covered.get() { + let cover = ui.min_rect().expand(5.0); + egui::Area::new(egui::Id::unique("numfields overlay")).order(egui::Order::Foreground).fixed_pos(cover.min).show(ui.ctx(), |ui| { + ui.allocate_exact_size(cover.size(), egui::Sense::click()); + }); + } + v + }; + f.frame(vec![], &draw); + let at = f.rect.get().center(); + f.frame(vec![Event::PointerMoved(at)], &draw); + covered.set(true); + f.frame(vec![], &draw); + f.frame(vec![], &draw); + covered.set(false); + f.frame(vec![], &draw); + f.frame(vec![], &draw); + assert_eq!(f.frame(vec![notch_down()], &draw), None, "the overlay covered the field"); + f.time += crate::widgets::WHEEL_STREAM_GAP; + assert_eq!(f.frame(vec![Event::PointerMoved(at + vec2(1.0, 0.0)), notch_down()], &draw), Some(9.0)); +} + /// A wheel turn over an unfocused field steps it without consuming an arrow key in the same frame. #[test] fn hover_wheel_keeps_arrow_keys_for_the_keyboard_focus() { diff --git a/crates/ui-egui/src/tests/rotateview.rs b/crates/ui-egui/src/tests/rotateview.rs index 8f477894a0..2f98a3f3b1 100644 --- a/crates/ui-egui/src/tests/rotateview.rs +++ b/crates/ui-egui/src/tests/rotateview.rs @@ -30,6 +30,13 @@ fn with_document() -> VectorcraftApp { app } +/// Send a control request and keep its success/error value for protocol assertions. +fn control_response(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (request, _) = crate::control::ControlRequest::new(method, params); + let crate::control::Outcome::Done(reply) = crate::control::handle(app, ctx, &request) else { panic!("not done") }; + reply +} + /// Returns the labels of the View › Rotate View items that are checked. fn checked(app: &VectorcraftApp) -> Vec<&'static str> { ANGLES.iter().filter(|(_, a)| menus::checked(app, "view.rotate", &json!({ "angle": a })) == Some(true)).map(|(l, _)| *l).collect() @@ -55,6 +62,157 @@ fn view_rotate_turns_the_view_to_any_angle() { assert_eq!(empty.run("view.rotate", json!({"angle": 30})).unwrap_err(), "no document"); } +/// MCP's `pointer_gesture` reaches `ui.pointer`: view tools must turn the canvas there too, +/// rather than silently sending the gesture to the engine's no-op tool. +#[test] +fn control_rotate_view_gesture_turns_the_canvas_and_reset_restores_it() { + let mut app = with_document(); + let ctx = egui::Context::default(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let view = app.view_mut().unwrap(); + view.center = vectorcraft_geom::Point::new(200.0, 150.0); + view.zoom = 1.0; + let revision = app.session.active().unwrap().revision; + let send = super::synthetic::control; + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 300, "y": 150}]})); + let mut frame = ctx.run_ui(Default::default(), |_| {}); + frame.textures_delta.clear(); + send( + &mut app, + &ctx, + "ui.pointer", + json!({"events": [ + {"kind": "drag", "x": 200, "y": 250}, + {"kind": "up", "x": 200, "y": 250} + ]}), + ); + let view = app.view().unwrap(); + assert!((view.rotation - 90.0).abs() < 1e-3, "{}", view.rotation); + assert_eq!(view.center, vectorcraft_geom::Point::new(200.0, 150.0)); + assert_eq!(view.zoom, 1.0); + assert_eq!(app.session.active().unwrap().revision, revision, "navigation does not edit the document"); + let reset = control_response(&mut app, &ctx, "engine.execute", json!({"command": "view.rotateReset", "params": {}})); + assert_eq!(reset["ok"], true); + assert!(reset["result"].is_null()); + assert_eq!(app.view().unwrap().rotation, 0.0); +} + +/// Repeated document points stay fixed across requests, including Shift snapping from a turned view. +#[test] +fn control_rotate_view_keeps_press_coordinates_and_shift_snapping_across_requests() { + let mut app = with_document(); + let ctx = egui::Context::default(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let view = app.view_mut().unwrap(); + view.center = vectorcraft_geom::Point::new(200.0, 150.0); + view.zoom = 1.0; + view.rotation = 30.0; + let send = super::synthetic::control; + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 300, "y": 150}]})); + let angle = 20_f64.to_radians(); + let (x, y) = (200.0 + 100.0 * angle.cos(), 150.0 + 100.0 * angle.sin()); + for _ in 0..2 { + send(&mut app, &ctx, "ui.pointer", json!({"mods": {"shift": true}, "events": [{"kind": "drag", "x": x, "y": y}]})); + assert_eq!(app.view().unwrap().rotation, 45.0, "the same document point does not turn again as the view changes"); + } + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "up", "x": x, "y": y}]})); + assert_eq!(app.view().unwrap().rotation, 45.0); +} + +/// Invalid coordinates and document changes cannot turn a different view. +#[test] +fn control_rotate_view_rejects_nonfinite_positions_and_a_changed_document() { + let mut app = with_document(); + let ctx = egui::Context::default(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let send = super::synthetic::control; + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + let (req, _) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": 1e300, "y": 0}]})); + let crate::control::Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &req) else { panic!("not done") }; + assert_eq!(reply["ok"], false); + assert_eq!(app.view().unwrap().rotation, 0.0); + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 300, "y": 150}]})); + app.run("file.new", json!({})).unwrap(); + let (req, _) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "drag", "x": 200, "y": 250}]})); + let crate::control::Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &req) else { panic!("not done") }; + assert_eq!(reply["ok"], false); + assert_eq!(app.view().unwrap().rotation, 0.0); +} + +/// An invalid packet leaves the angle unchanged and requires a fresh press, including errors +/// after an otherwise valid drag and malformed releases or hovers. +#[test] +fn control_rotate_view_rejects_malformed_packets_without_leaving_a_press() { + let drag = json!({"kind": "drag", "x": 200, "y": 250}); + for packet in [ + json!({"events": [drag.clone(), {"kind": "drag", "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "drag", "x": "200", "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "drag", "x": 200, "y": 250, "mods": {"shift": "yes"}}]}), + json!({"mods": "shift", "events": [drag.clone()]}), + json!({"events": [drag.clone(), {"kind": "drag", "x": 200, "y": 250, "mods": {"unknown": true}}]}), + json!({"events": [drag.clone(), {"kind": "drag", "x": 1e300, "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "up", "x": 1e300, "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "move", "x": 1e300, "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "doubleclick", "x": 1e300, "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "wiggle", "x": 200, "y": 250}]}), + json!({"events": [drag.clone(), {"kind": "drag", "x": 200, "y": 250, "space": "window"}]}), + json!({"events": null}), + ] { + let mut app = with_document(); + let ctx = egui::Context::default(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let view = app.view_mut().unwrap(); + view.center = vectorcraft_geom::Point::new(200.0, 150.0); + view.zoom = 1.0; + super::synthetic::control(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + super::synthetic::control(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 300, "y": 150}]})); + let reply = control_response(&mut app, &ctx, "ui.pointer", packet.clone()); + assert_eq!(reply["ok"], false, "{packet}: {reply}"); + assert_eq!(app.view().unwrap().rotation, 0.0, "{packet}"); + let resume = control_response(&mut app, &ctx, "ui.pointer", json!({"events": [drag.clone()]})); + assert_eq!(resume["ok"], false, "a failed packet cancels its press: {packet}"); + assert_eq!(app.view().unwrap().rotation, 0.0); + } +} + +/// Screen-space gestures survive frames, stop on release or a tool change, and start afresh +/// from the current angle. A press at the pivot uses the same finite convention as the mouse. +#[test] +fn control_rotate_view_screen_events_require_a_live_press() { + let mut app = with_document(); + let ctx = egui::Context::default(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let view = app.view_mut().unwrap(); + view.center = vectorcraft_geom::Point::new(1200.0, 900.0); + view.zoom = 2.0; + let send = super::synthetic::control; + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + let down = json!({"events": [{"kind": "down", "x": 500, "y": 300, "space": "screen"}]}); + let drag = json!({"events": [{"kind": "drag", "x": 400, "y": 400, "space": "screen"}]}); + assert_eq!(control_response(&mut app, &ctx, "ui.pointer", drag.clone())["ok"], false); + send(&mut app, &ctx, "ui.pointer", down.clone()); + let mut frame = ctx.run_ui(Default::default(), |_| {}); + frame.textures_delta.clear(); + send(&mut app, &ctx, "ui.pointer", drag.clone()); + assert!((app.view().unwrap().rotation - 90.0).abs() < 1e-3); + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "up", "x": 400, "y": 400, "space": "screen"}]})); + assert_eq!(control_response(&mut app, &ctx, "ui.pointer", drag.clone())["ok"], false, "release ends the press"); + send(&mut app, &ctx, "ui.pointer", down.clone()); + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "selection"})); + send(&mut app, &ctx, "ui.tool.select", json!({"tool": "rotateView"})); + assert_eq!(control_response(&mut app, &ctx, "ui.pointer", drag.clone())["ok"], false, "a tool change ends the press"); + send(&mut app, &ctx, "ui.pointer", down); + send(&mut app, &ctx, "ui.pointer", drag); + assert!((app.view().unwrap().rotation.abs() - 180.0).abs() < 1e-3, "a new press starts at the current angle"); + let before = app.view().unwrap().rotation; + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 400, "y": 300, "space": "screen"}]})); + send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "drag", "x": 500, "y": 300, "space": "screen"}]})); + assert!(app.view().unwrap().rotation.is_finite()); + assert!((app.view().unwrap().rotation - before).abs() < 1e-3); +} + #[test] fn the_view_menu_lists_the_status_bar_angles_and_checks_the_current_one() { let mut app = with_document(); @@ -262,80 +420,259 @@ fn key(key: egui::Key, repeat: bool) -> Vec { [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat, modifiers: Default::default() }).to_vec() } -/// The second of two Escape presses less than a second apart resets a rotated view. A press of -/// another key or a pointer button between them, or a longer wait, ends the pair. Shift does not. +fn selected(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().selection.objects.len() +} + +/// One Escape resets a rotated view when it has nothing else to end, with or without a selected +/// object, which stays selected. Shift held down with it (as after a Space+Shift drag) does not +/// change that, and the repeats of a held Escape do nothing more. #[test] -fn escape_pressed_twice_resets_a_rotated_view() { +fn one_escape_resets_a_rotated_view() { let mut w = Window::new(); w.escape(0.0); - assert_eq!(w.rotation(), 30.0, "one Escape"); + assert_eq!(w.rotation(), 0.0, "one Escape with nothing selected"); w.escape(0.5); - assert_eq!(w.rotation(), 0.0, "a second Escape 0.5 s later"); - w.escape(0.5); - assert_eq!(w.rotation(), 0.0, "a third Escape leaves the view at 0°"); + assert_eq!(w.rotation(), 0.0, "a second Escape leaves the view at 0°"); let mut w = Window::new(); - let empty = w.app.canvas_rect.unwrap().left_top() + egui::vec2(20.0, 20.0); + w.app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + w.after(0.0, vec![]); + assert_eq!(selected(&w.app), 1); w.escape(0.0); - w.click(0.2, egui::PointerButton::Primary, empty); - w.escape(0.2); - assert_eq!(w.rotation(), 30.0, "a click between the two"); - let mut w = Window::new(); - w.escape(0.0); - w.after(0.2, key(egui::Key::ArrowRight, false)); - w.escape(0.2); - assert_eq!(w.rotation(), 30.0, "an arrow key between the two"); - let mut w = Window::new(); - w.escape(0.0); - w.after(0.2, key(egui::Key::ShiftLeft, false)); - w.escape(0.2); - assert_eq!(w.rotation(), 0.0, "a Shift press between the two"); + assert_eq!((w.rotation(), selected(&w.app)), (0.0, 1), "one Escape with a selected object, which stays selected"); let mut w = Window::new(); - w.escape(0.0); - w.escape(2.0); - assert_eq!(w.rotation(), 30.0, "two Escapes 2 s apart"); - w.escape(0.5); - assert_eq!(w.rotation(), 0.0, "the later of them starts a pair"); + let shifted = [true, false].map(|pressed| egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed, + repeat: false, + modifiers: egui::Modifiers::SHIFT, + }); + w.after(0.0, shifted.to_vec()); + assert_eq!(w.rotation(), 0.0, "Shift+Escape"); - // A held Escape repeats: the repeats are not a second press. let mut w = Window::new(); w.after(0.0, vec![key(egui::Key::Escape, false)[0].clone()]); + assert_eq!(w.rotation(), 0.0, "the press of a held Escape"); + w.app.run("view.rotate", json!({"angle": 30})).unwrap(); for _ in 0..5 { w.after(0.1, vec![key(egui::Key::Escape, true)[0].clone()]); } w.after(0.1, vec![key(egui::Key::Escape, false)[1].clone()]); - assert_eq!(w.rotation(), 30.0, "Escape held down"); + assert_eq!(w.rotation(), 30.0, "its repeats"); + + let mut w = Window::new(); + w.app.select_tool("rotateView"); + w.escape(0.0); + assert_eq!(w.rotation(), 0.0, "one Escape with the Rotate View tool"); + + // A hover highlight that the Escape clears does not count as something it ends. + let mut w = Window::new(); + w.app.run("shape.rectangle", json!({"x": 150, "y": 100, "width": 120, "height": 80})).unwrap(); + // The new object is the selection, to be put on the path under the pointer. + w.app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + w.app.select_tool("objectsOnPath"); + let view = w.app.view_info(); + let over = vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Move, 150.0, 140.0); + w.app.session.pointer(&over, view).unwrap(); + assert!(!w.app.session.overlays(view).is_empty(), "Objects on Path highlights the path under the pointer"); + w.escape(0.0); + assert_eq!(w.rotation(), 0.0, "one Escape with Objects on Path hovering"); } -/// The first Escape of a pair may end something, such as isolation mode. With the Rotate View -/// tool, one Escape resets the view. +/// An Escape that ends something, such as isolation mode, leaves the view as it is. The next +/// Escape resets it, however long after it comes and whatever is clicked or pressed in between. #[test] -fn escape_after_ending_isolation_or_with_the_rotate_view_tool_resets_the_view() { +fn escape_after_ending_isolation_resets_the_view() { + let isolated_window = || { + let mut w = Window::new(); + w.app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + w.app.run("shape.rectangle", json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap(); + w.app.run("select.all", json!({})).unwrap(); + w.app.run("object.group", json!({})).unwrap(); + menus::invoke(&mut w.app, "object.isolate", json!({})); + w.after(0.0, vec![]); + w + }; + let isolated = |w: &Window| w.app.session.active().unwrap().isolation.is_some(); + let mut w = isolated_window(); + assert!(isolated(&w)); + w.escape(0.0); + assert_eq!((isolated(&w), w.rotation()), (false, 30.0), "the first Escape leaves isolation mode"); + w.escape(5.0); + assert_eq!(w.rotation(), 0.0, "the second resets the view 5 s later"); + + let mut w = isolated_window(); + let empty = w.app.canvas_rect.unwrap().left_top() + egui::vec2(20.0, 20.0); + w.escape(0.0); + assert_eq!((isolated(&w), w.rotation()), (false, 30.0)); + w.click(2.0, egui::PointerButton::Primary, empty); + w.after(0.5, key(egui::Key::ArrowRight, false)); + w.escape(3.0); + assert_eq!(w.rotation(), 0.0, "after a click and an arrow key between the two"); +} + +/// An Escape that ends the path the Pen, the Smart Pen or the Curvature tool is drawing leaves the +/// view as it is, with the rubber band shown or not; the next Escape resets it. +#[test] +fn escape_that_ends_a_path_being_drawn_keeps_the_rotation() { + for (tool, rubber_band) in [("pen", true), ("pen", false), ("smartPen", true), ("smartPen", false), ("curvature", true)] { + let mut w = Window::new(); + w.app.session.prefs.pen_rubber_band = rubber_band; + w.app.select_tool(tool); + let c = w.app.canvas_rect.unwrap().center(); + w.click(0.0, egui::PointerButton::Primary, c); + w.click(0.1, egui::PointerButton::Primary, c + egui::vec2(60.0, 10.0)); + w.after(0.1, vec![egui::Event::PointerMoved(c + egui::vec2(60.0, 80.0))]); + assert!(w.app.session.tool_ends_on_escape(w.app.view_info()), "{tool}: a path is being drawn"); + w.escape(0.2); + assert_eq!(w.rotation(), 30.0, "{tool}, rubber band {rubber_band}: the Escape that ends the path"); + assert!(!w.app.session.tool_ends_on_escape(w.app.view_info()), "{tool}: the path is ended"); + w.escape(3.0); + assert_eq!(w.rotation(), 0.0, "{tool}, rubber band {rubber_band}: the next Escape"); + } +} + +/// In isolation mode, an Escape that ends the Pen's path ends only the path: the next Escape leaves +/// isolation mode, and the one after it resets the view. +#[test] +fn escape_ends_one_thing_at_a_time() { let mut w = Window::new(); w.app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); w.app.run("shape.rectangle", json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap(); w.app.run("select.all", json!({})).unwrap(); w.app.run("object.group", json!({})).unwrap(); menus::invoke(&mut w.app, "object.isolate", json!({})); + w.after(0.0, vec![]); let isolated = |w: &Window| w.app.session.active().unwrap().isolation.is_some(); assert!(isolated(&w)); - w.escape(0.0); - assert_eq!((isolated(&w), w.rotation()), (false, 30.0), "the first Escape leaves isolation mode"); - w.escape(0.5); - assert_eq!(w.rotation(), 0.0, "the second resets the view"); - - let mut w = Window::new(); - w.app.select_tool("rotateView"); - w.escape(0.0); - assert_eq!(w.rotation(), 0.0, "one Escape with the Rotate View tool"); + w.app.select_tool("pen"); + let c = w.app.canvas_rect.unwrap().center(); + w.click(0.0, egui::PointerButton::Primary, c); + w.click(0.1, egui::PointerButton::Primary, c + egui::vec2(60.0, 10.0)); + assert!(w.app.session.tool_ends_on_escape(w.app.view_info()), "a path is being drawn"); + w.escape(0.2); + assert!(!w.app.session.tool_ends_on_escape(w.app.view_info()), "the first Escape ends the path"); + assert_eq!((isolated(&w), w.rotation()), (true, 30.0), "and only the path"); + w.escape(0.2); + assert_eq!((isolated(&w), w.rotation()), (false, 30.0), "the second leaves isolation mode"); + w.escape(0.2); + assert_eq!(w.rotation(), 0.0, "the third resets the view"); } -/// An Escape that closes a popup (the status bar's angle menu, the canvas context menu) does not -/// count, so the Escape after it leaves the view as it is. An Escape while the ruler origin is -/// dragged does not reset the view either, but it counts as the first Escape of a pair. +/// The Escape that leaves the Artboard tool leaves the view as it is; the next resets it. #[test] -fn escape_after_closing_a_popup_or_during_a_ruler_origin_drag_keeps_the_rotation() { +fn escape_after_leaving_the_artboard_tool_resets_the_view() { + let mut w = Window::new(); + w.app.select_tool("artboard"); + w.escape(0.0); + assert_eq!((w.app.session.tool_id(), w.rotation()), ("selection", 30.0), "the first Escape leaves the Artboard tool"); + w.escape(5.0); + assert_eq!(w.rotation(), 0.0, "the next resets the view"); +} + +/// An Escape that a dialog or a full screen mode takes leaves the view as it is; the next resets it. +#[test] +fn escape_in_a_dialog_or_a_full_screen_mode_keeps_the_rotation() { + let mut w = Window::new(); + menus::invoke(&mut w.app, "view.rotate", json!({})); + w.after(0.0, vec![]); + assert!(w.app.ui.dialog.is_some(), "Rotate View asks for an angle"); + w.escape(0.0); + assert_eq!((w.app.ui.dialog.is_none(), w.rotation()), (true, 30.0), "Escape closes the dialog"); + w.escape(0.5); + assert_eq!(w.rotation(), 0.0, "the next Escape"); + + for mode in [1, 2] { + let mut w = Window::new(); + w.app.ui.screen_mode = mode; + w.after(0.0, vec![]); + w.escape(0.0); + assert_eq!((w.app.ui.screen_mode, w.rotation()), (0, 30.0), "Escape leaves screen mode {mode}"); + w.escape(0.5); + assert_eq!(w.rotation(), 0.0, "the next Escape after screen mode {mode}"); + + // Shift+Escape does not leave a full screen mode, so it resets the view there. + let mut w = Window::new(); + w.app.ui.screen_mode = mode; + w.after(0.0, vec![]); + let shifted = [true, false].map(|pressed| egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed, + repeat: false, + modifiers: egui::Modifiers::SHIFT, + }); + w.after(0.0, shifted.to_vec()); + assert_eq!((w.app.ui.screen_mode, w.rotation()), (mode, 0.0), "Shift+Escape in screen mode {mode}"); + } + + let mut w = Window::new(); + w.app.run("view.presentation", json!({})).unwrap(); + w.after(0.0, vec![]); + assert_eq!(w.app.ui.screen_mode, 3, "Presentation Mode"); + w.escape(0.0); + assert_eq!((w.app.ui.screen_mode != 3, w.rotation()), (true, 30.0), "Escape leaves Presentation Mode"); + w.escape(0.5); + assert_eq!(w.rotation(), 0.0, "the next Escape after Presentation Mode"); +} + +/// An Escape while About or an Appearance row's popup is open, or while a pointer button is held +/// outside the canvas (a scroll bar, a tab or a panel being dragged) or let go in the same frame, +/// leaves the view as it is. +#[test] +fn escape_with_a_window_open_or_a_button_held_keeps_the_rotation() { + let mut w = Window::new(); + w.app.ui.about = true; + w.after(0.0, vec![]); + w.escape(0.0); + assert_eq!(w.rotation(), 30.0, "an Escape with About open"); + + // An Appearance row's popup (here, the Stroke panel's) closes on Escape as the frame is drawn. + let mut w = Window::new(); + w.app.ui.transient_panel = Some("stroke".into()); + w.escape(0.0); + assert_eq!(w.rotation(), 30.0, "an Escape with an Appearance row's popup open"); + + let mut w = Window::new(); + let bar = w.app.canvas_rect.unwrap().right_center() + egui::vec2(4.0, 0.0); + let button = |pressed| egui::Event::PointerButton { pos: bar, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + w.after(0.0, vec![egui::Event::PointerMoved(bar), button(true)]); + w.escape(0.1); + assert_eq!(w.rotation(), 30.0, "an Escape with the button held"); + let mut release = vec![button(false)]; + release.extend(key(egui::Key::Escape, false)); + w.after(0.1, release); + assert_eq!(w.rotation(), 30.0, "an Escape in the frame the button is let go"); + w.escape(0.1); + assert_eq!(w.rotation(), 0.0, "an Escape after the release"); +} + +/// An Escape in a text field ends the editing and leaves the view as it is. +#[test] +fn escape_in_a_text_field_keeps_the_rotation() { + let mut w = Window::new(); + w.ctx.enable_accesskit(); + let out = w.after(0.0, vec![]); + let tree = out.platform_output.accesskit_update.expect("the window's accessibility tree"); + let field = tree.nodes.iter().find(|(_, node)| node.role() == egui::accesskit::Role::TextInput).map(|(id, _)| *id).expect("a text field"); + let field = w + .ctx + .viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, ws)| ws.iter()).find(|r| r.id.accesskit_id() == field).copied()) + .expect("the text field's widget"); + w.ctx.memory_mut(|m| m.request_focus(field.id)); + w.after(0.0, vec![]); + assert!(w.ctx.egui_wants_keyboard_input(), "the field has the keyboard"); + w.escape(0.0); + assert_eq!(w.rotation(), 30.0, "the Escape in the field"); +} + +/// An Escape that closes a popup (the status bar's angle menu, the canvas context menu) or ends a +/// drag of the ruler origin leaves the view as it is; the next Escape resets it. +#[test] +fn escape_that_closes_a_popup_or_ends_a_ruler_origin_drag_keeps_the_rotation() { let mut w = Window::new(); // Find the actual combo by its accessible name, which is present in both build profiles; // `Id`'s debug source (including "rot-combo") only exists with debug assertions enabled. @@ -354,8 +691,9 @@ fn escape_after_closing_a_popup_or_during_a_ruler_origin_drag_keeps_the_rotation assert!(craft_ui::ComboBox::is_open(&w.ctx, combo.id), "the angle menu is open"); w.escape(0.2); assert!(!egui::Popup::is_any_open(&w.ctx), "Escape closes it"); + assert_eq!(w.rotation(), 30.0, "the Escape that closes the angle menu"); w.escape(0.2); - assert_eq!(w.rotation(), 30.0, "an Escape after the angle menu closed"); + assert_eq!(w.rotation(), 0.0, "the next Escape"); let mut w = Window::new(); w.click(0.0, egui::PointerButton::Secondary, w.app.canvas_rect.unwrap().center()); @@ -363,8 +701,9 @@ fn escape_after_closing_a_popup_or_during_a_ruler_origin_drag_keeps_the_rotation assert!(egui::Popup::is_any_open(&w.ctx), "a right click opens the context menu"); w.escape(0.2); assert!(!egui::Popup::is_any_open(&w.ctx), "Escape closes it"); + assert_eq!(w.rotation(), 30.0, "the Escape that closes the context menu"); w.escape(0.2); - assert_eq!(w.rotation(), 30.0, "an Escape after the context menu closed"); + assert_eq!(w.rotation(), 0.0, "the next Escape"); // With the Rotate View tool, the Escape that closes the menu leaves the view as it is too. let mut w = Window::new(); w.app.select_tool("rotateView"); @@ -391,5 +730,5 @@ fn escape_after_closing_a_popup_or_during_a_ruler_origin_drag_keeps_the_rotation assert_eq!(w.rotation(), 30.0, "two Escapes while the ruler origin is dragged"); w.after(0.1, vec![button(to, false)]); w.escape(0.2); - assert_eq!(w.rotation(), 0.0, "an Escape after the drag ends pairs with the last one"); + assert_eq!(w.rotation(), 0.0, "an Escape after the drag ends"); } diff --git a/crates/ui-egui/src/tests/screenmode.rs b/crates/ui-egui/src/tests/screenmode.rs index 56bcca519a..3154ccb6d9 100644 --- a/crates/ui-egui/src/tests/screenmode.rs +++ b/crates/ui-egui/src/tests/screenmode.rs @@ -677,7 +677,7 @@ fn a_tool_flyout_takes_escape_before_full_screen() { } #[test] -fn a_rotation_pair_exits_full_screen_then_resets_with_selection_tool() { +fn escape_exits_full_screen_then_resets_the_rotation_with_selection_tool() { for mode in [1, 2] { let ctx = egui::Context::default(); let mut app = in_screen_mode(&ctx, mode); @@ -686,7 +686,7 @@ fn a_rotation_pair_exits_full_screen_then_resets_with_selection_tool() { assert_eq!(app.ui.screen_mode, 0, "first Escape in mode {mode}"); assert_eq!(app.view().unwrap().rotation, 30.0); frame(&mut app, &ctx, escape()); - assert_eq!(app.view().unwrap().rotation, 0.0, "second Escape after mode {mode}"); + assert_eq!(app.view().unwrap().rotation, 0.0, "the next Escape after mode {mode}"); } } diff --git a/crates/ui-egui/src/tests/script_check.rs b/crates/ui-egui/src/tests/script_check.rs index ccaa6c7a8c..0ff703eb3b 100644 --- a/crates/ui-egui/src/tests/script_check.rs +++ b/crates/ui-egui/src/tests/script_check.rs @@ -46,7 +46,7 @@ fn file_scripts_holds_check_script_above_other_script() { let (_, file) = tree.iter().find(|(t, _)| *t == "File").unwrap(); let scripts = file.iter().find_map(|i| if let menus::Item::Sub("Scripts", items) = i { Some(items) } else { None }).unwrap(); assert!( - matches!(scripts.as_slice(), [menus::Item::Cmd("Check Script…", "ui.checkScript", _), menus::Item::Todo("Other Script…", _)]), + matches!(scripts.as_slice(), [menus::Item::Cmd("Check Script…", "ui.checkScript", _), menus::Item::Cmd("Other Script…", "ui.runScript", _)]), "{scripts:?}" ); } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs new file mode 100644 index 0000000000..08ac8e1917 --- /dev/null +++ b/crates/ui-egui/src/tests/script_run.rs @@ -0,0 +1,283 @@ +//! File › Scripts › Other Script… (`ui.runScript`): the chooser, the warning and its preference, +//! a run advanced frame by frame, Stop, and the questions a run and quitting ask. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use crate::{VectorcraftApp, dialogs, menus, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app +} + +fn folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vc-script-run-ui-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +fn finish(app: &mut VectorcraftApp) { + for _ in 0..10_000 { + if !app.session.script_running() { + return; + } + script_runs::poll(app); + } + panic!("the script did not end"); +} + +const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); vc.run('shape.rectangle', {x:20,y:0,width:10,height:10});"; + +fn confirm(app: &mut VectorcraftApp) -> Result { + dialogs::confirm(app) +} + +#[test] +fn the_warning_comes_before_the_run_and_cancel_runs_nothing() { + let mut app = app(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": DRAW, "name": "draw.js"})).unwrap().unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.fields["name"].as_str()), (dialogs::script_run::KIND, Some("draw.js"))); + assert!(!app.session.script_running()); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert!(!app.session.script_running()); + finish(&mut app); + assert_eq!(objects(&app), 0); +} + +#[test] +fn a_run_goes_frame_by_frame_and_is_one_undo_step() { + let mut app = app(); + let dir = folder("draw"); + let path = dir.join("Dessin (été) #1.JSX"); + std::fs::write(&path, DRAW).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["name"], "Dessin (été) #1.JSX"); + confirm(&mut app).unwrap(); + assert!(app.session.script_running()); + assert_eq!(objects(&app), 0, "nothing shows until the run commits"); + finish(&mut app); + assert_eq!(objects(&app), 2); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(app.ui.status, "Ran Dessin (été) #1.JSX"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(objects(&app), 0); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn do_not_show_again_is_remembered_and_the_script_still_runs() { + let mut app = app(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": DRAW})).unwrap().unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("dontShow".into(), json!(true)); + confirm(&mut app).unwrap(); + finish(&mut app); + assert!(!app.session.prefs.show_external_script_warning); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": DRAW})).unwrap().unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(app.session.script_running()); + finish(&mut app); + assert_eq!(objects(&app), 4); +} + +#[test] +fn only_js_and_jsx_files_are_taken() { + let mut app = app(); + for name in ["a.txt", "a.jsxbin", "a"] { + let e = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "path": name })).unwrap().unwrap_err(); + assert!(e.contains(".js or .jsx"), "{name}: {e}"); + } + assert!(app.ui.dialog.is_none()); +} + +#[test] +fn stop_puts_the_document_back_and_says_so() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = format!("{DRAW} while (true) {{}}"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_running()); + assert!(app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap_err().contains("a script is running")); + app.run("script.stop", json!({})).unwrap(); + finish(&mut app); + assert_eq!(objects(&app), 0); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); +} + +#[test] +fn a_script_error_goes_to_the_status_bar() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "throw new Error('nope');", "name": "x.js"})).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.ui.status, "x.js: line 1, column 1: Error: nope (thrown)"); +} + +/// An app whose script picker is the web's: picks are counted and files arrive through its inbox. +fn app_with_picker() -> (VectorcraftApp, dialogs::script_run::ScriptInbox, std::rc::Rc>) { + let mut app = app(); + let inbox = dialogs::script_run::ScriptInbox::default(); + let picks = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = picks.clone(); + app.services.script_async = Some(Box::new(move || counted.set(counted.get() + 1))); + app.services.script_inbox = Some(inbox.clone()); + (app, inbox, picks) +} + +#[test] +fn a_canceled_web_pick_does_not_take_a_dropped_script() { + let (mut app, _inbox, picks) = app_with_picker(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({})).unwrap().unwrap(); + assert_eq!(picks.get(), 1); + // A pick that was canceled delivers nothing, and the next file that opens is an ordinary open. + script_runs::poll(&mut app); + let _ = crate::io::open_bytes(&mut app, "dropped.js", DRAW.as_bytes(), None); + assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != dialogs::script_run::KIND)); + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 0); +} + +#[test] +fn a_web_pick_goes_to_the_warning_and_waits_for_an_open_dialog() { + let (mut app, inbox, _picks) = app_with_picker(); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, json!({}))); + inbox.lock().unwrap().push(("picked.js".to_string(), Some(DRAW.as_bytes().to_vec()))); + script_runs::poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, dialogs::script_run::CLOSE_KIND); + assert_eq!(inbox.lock().unwrap().len(), 1, "the file waits"); + app.ui.dialog = None; + script_runs::poll(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.fields["name"].as_str()), (dialogs::script_run::KIND, Some("picked.js"))); + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(objects(&app), 2); +} + +#[test] +fn a_web_pick_that_is_not_text_is_reported() { + let (mut app, inbox, _picks) = app_with_picker(); + inbox.lock().unwrap().push(("bad.js".to_string(), Some(vec![0xff, 0xfe]))); + script_runs::poll(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.status, "the script is not UTF-8 text"); +} + +#[test] +fn a_web_pick_too_large_to_read_is_reported() { + let (mut app, inbox, _picks) = app_with_picker(); + inbox.lock().unwrap().push(("big.js".to_string(), None)); + script_runs::poll(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.status, "the script is too large to run"); +} + +/// A run that never ends, with the growth question up. +fn at_the_growth_question(app: &mut VectorcraftApp) { + app.session.prefs.show_external_script_warning = false; + let source = format!("{DRAW} while (true) {{}}"); + menus::run_ui_command(app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(app); + assert!(app.session.script_running()); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::GROWTH_KIND, json!({}))); +} + +#[test] +fn the_growth_questions_stop_button_stops_the_run() { + let mut app = app(); + at_the_growth_question(&mut app); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + finish(&mut app); + assert_eq!(objects(&app), 0); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); +} + +#[test] +fn escape_on_the_growth_question_stops_the_run() { + let mut app = app(); + at_the_growth_question(&mut app); + let key = egui::Key::Escape; + let events = vec![egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]; + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + output.textures_delta.clear(); + assert!(app.ui.dialog.is_none()); + finish(&mut app); + assert_eq!(objects(&app), 0); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); +} + +#[test] +fn a_stopped_run_closes_its_growth_question() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "while (true) {}"})).unwrap().unwrap(); + script_runs::poll(&mut app); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::GROWTH_KIND, json!({}))); + app.run("script.stop", json!({})).unwrap(); + finish(&mut app); + assert!(app.ui.dialog.is_none()); +} + +#[test] +fn finished_background_work_waits_for_the_run_to_end() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.opening.activate.push(("no such document".to_string(), vectorcraft_engine::file_access::ScopeHandle::capture())); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "while (true) {}"})).unwrap().unwrap(); + app.poll_finished_work(); + assert_eq!(app.opening.activate.len(), 1); + app.run("script.stop", json!({})).unwrap(); + finish(&mut app); + app.poll_finished_work(); + assert!(app.opening.activate.is_empty()); +} + +#[test] +fn quitting_asks_to_stop_and_stop_undoes_the_run() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = format!("{DRAW} while (true) {{}}"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_running()); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, json!({}))); + confirm(&mut app).unwrap(); + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 0); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); +} + +#[test] +fn a_stop_names_the_files_the_run_left_written() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let dir = folder("written"); + let path = dir.join("out.svg"); + let p = path.to_string_lossy().into_owned(); + let source = format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(path.exists()); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, json!({}))); + confirm(&mut app).unwrap(); + assert!(app.ui.status.contains(&p), "{}", app.ui.status); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_new_app_shows_the_warning_by_default() { + assert!(Session::new().prefs.show_external_script_warning); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 4f3243c756..be2965ef3c 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -20,6 +20,7 @@ mod numeric; mod panel_chrome; mod text; mod toggles; +mod wheel_stream; pub use blend::{ TransparencyEdit, angle_dial, blend_dropdown, blend_param, blend_param_dropdown, blend_separator_before, opacity_blend, reference_point, @@ -46,7 +47,7 @@ pub use drag::{ use dropdowns::combo_button_id; #[cfg(test)] pub(crate) use dropdowns::menu_floor; -pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field, combo_named, popover_is_open}; +pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field, combo_named, field_focused_in, popover_is_open}; pub use dropdowns::{ dropdown, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, @@ -62,6 +63,7 @@ pub use numeric::{ }; #[cfg(test)] use numeric::{decimal_point, field_number, share_of, spinner_step, step_through, step_to_multiple, within_a_millionth}; +pub(crate) use panel_chrome::{PANEL_FOOTER, panel_footer, panel_footer_bottom, panel_footer_space, panel_list_height}; pub use panel_chrome::{bottom_bar, layout_button, list_box, orientation_button, tab_bar}; pub(crate) use text::{ arm_field_focus, dialog_focus_flag, dialog_reject_commit_flag, disarm_field_focus, enter_modifiers, focus_field, own_field_shift_enter, @@ -72,6 +74,9 @@ pub use text::{ text_presets_named, }; pub use toggles::{check, check_box, check_name, check_tip, check3, check3_tip, radio, radio_button}; +#[cfg(test)] +pub(crate) use wheel_stream::WHEEL_STREAM_GAP; +pub(crate) use wheel_stream::{ArmedWheelField, WheelStream, WheelStreamOwner, taken_from_raw_id}; /// A widget id salt that needs only [`std::hash::Hash`]. egui 0.37's [`egui::AsIdSalt`] also /// requires `Debug` for its debug-only id-source registry; VectorCraft's public field helpers do diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 1046e56a78..d5d914b7b6 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -234,8 +234,13 @@ pub fn popover(resp: &Response, toggle: bool, content: impl FnOnce(&mut Ui) - && click_pos.is_some_and(|pos| ctx.layer_id_at(pos).is_none_or(|l| l.order != egui::Order::Foreground)); was_open && !clicked_elsewhere }; + // Closing with a field in it that has the keyboard: it draws once more, so the field lets go of + // the keyboard to the click and commits what was typed, as in a panel (#6429). + let last = was_open && !open && field_focused_in(ctx, egui::LayerId::new(egui::Order::Foreground, id)); + let mut shown = open || last; let inner = - egui::Popup::menu(resp).id(id).open_bool(&mut open).close_behavior(egui::PopupCloseBehavior::IgnoreClicks).show(content).map(|r| r.inner); + egui::Popup::menu(resp).id(id).open_bool(&mut shown).close_behavior(egui::PopupCloseBehavior::IgnoreClicks).show(content).map(|r| r.inner); + open = shown && !last; ctx.data_mut(|d| { if open { d.insert_temp(id, frame); @@ -246,6 +251,13 @@ pub fn popover(resp: &Response, toggle: bool, content: impl FnOnce(&mut Ui) - inner } +/// Whether a field in the popup on `layer` has the keyboard. A popup closing with one draws once +/// more before it goes: the field lets go of the keyboard to the click away and commits what was +/// typed, as it does in a panel. A popup that closed without drawing again dropped it (#6429). +pub(crate) fn field_focused_in(ctx: &egui::Context, layer: egui::LayerId) -> bool { + ctx.memory(|m| m.focused()).and_then(|id| ctx.read_response(id)).is_some_and(|r| r.layer_id == layer) +} + /// Whether the popover for this anchor was open in the latest completed frame. pub(crate) fn popover_is_open(ctx: &egui::Context, anchor: egui::Id) -> bool { let frame = ctx.cumulative_frame_nr(); diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 582833127c..274861386b 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -429,17 +429,25 @@ fn a_popover_stays_open_for_a_click_on_its_anchor_or_during_a_panel_drag() { } /// #4267: a click on a spinner arrow steps once; an arrow held down steps again and again after a -/// pause, and letting go of it doesn't step once more. +/// pause even past the click timeout (#6307), and letting go doesn't step once more. #[test] fn a_held_spinner_arrow_repeats() { let ctx = themed(Default::default()); let value = std::cell::Cell::new(5.0); + let scroll = std::cell::Cell::new(0.0); + let spinner_rect = std::cell::Cell::new(Rect::NOTHING); let mut add = |ui: &mut Ui| { - ui.horizontal(|ui| { - if let Some(v) = spin_plain(ui, "repeat", value.get(), "", 0, 100.0, 1.0, 0.0, &[]) { - value.set(v); - } + let area = egui::ScrollArea::vertical().max_height(100.0).scroll_source(egui::scroll_area::ScrollSource::DRAG).show(ui, |ui| { + ui.add_space(35.0); + let row = ui.horizontal(|ui| { + if let Some(v) = spin_plain(ui, "repeat", value.get(), "", 0, 100.0, 1.0, 0.0, &[]) { + value.set(v); + } + }); + spinner_rect.set(Rect::from_min_size(row.response.rect.min, vec2(16.0, 26.0))); + ui.add_space(150.0); }); + scroll.set(area.state.clamped_offset().y); }; let shapes = frame(&ctx, 0.0, vec![], &mut add); let spinner = shapes @@ -460,13 +468,31 @@ fn a_held_spinner_arrow_repeats() { frame(&ctx, 1.0, vec![button(true)], &mut add); frame(&ctx, 1.3, vec![], &mut add); assert_eq!(value.get(), 6.0, "no step before the pause"); - for (i, t) in [1.5, 1.6, 1.7].into_iter().enumerate() { + for i in 0..17 { + let t = 1.5 + f64::from(i) * 0.1; frame(&ctx, t, vec![], &mut add); - assert_eq!(value.get(), 7.0 + i as f64, "a step every repeat at {t}"); + assert_eq!(value.get(), 7.0 + f64::from(i), "a step every repeat at {t}"); } - frame(&ctx, 1.75, vec![button(false)], &mut add); - frame(&ctx, 1.8, vec![], &mut add); - assert_eq!(value.get(), 9.0, "letting go doesn't step once more"); + frame(&ctx, 3.2, vec![button(false)], &mut add); + frame(&ctx, 3.3, vec![], &mut add); + assert_eq!(value.get(), 23.0, "letting go doesn't step once more"); + + let down = spinner_rect.get().center_bottom() - vec2(0.0, 6.0); + let modifiers = egui::Modifiers::SHIFT; + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + frame(&ctx, 3.9, vec![egui::Event::PointerMoved(down)], &mut add); + frame(&ctx, 4.0, vec![egui::Event::ModifiersChanged(modifiers), button(down, true)], &mut add); + frame(&ctx, 4.5, vec![], &mut add); + assert_eq!(value.get(), 13.0, "Shift+down steps by ten: press {down:?}, current {:?}", spinner_rect.get()); + frame(&ctx, 4.9, vec![], &mut add); + assert_eq!(value.get(), 3.0, "Shift+down repeats past the click timeout"); + + let outside = down - vec2(0.0, 45.0); + frame(&ctx, 5.0, vec![egui::Event::PointerMoved(outside)], &mut add); + frame(&ctx, 5.1, vec![], &mut add); + frame(&ctx, 5.2, vec![button(outside, false)], &mut add); + assert_eq!(value.get(), 3.0, "dragging away and releasing doesn't step"); + assert!(scroll.get() > 0.0, "a drag starting on the spinner can still scroll the panel"); } /// The Kerning field reads `(10+5)` as 15 whether it shows a manual value (`12`) or an automatic diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 04ac7160f2..bf25ce58bd 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -5,6 +5,7 @@ use super::panel_chrome::{ use super::text::{ after_shift_enter, focus_field, recessed_text, select_all, select_all_on_focus, shift_enter_keeps_focus, take_armed_focus, take_dialog_focus, }; +use super::{ArmedWheelField, WheelStream, WheelStreamOwner}; use super::{CornerRadius, RangeInclusive, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, Unit, id_with, pos2, scrub, vec2}; /// Preferences › Units › Numbers Without Units Are Points (#394; on until set): the app sets it @@ -120,6 +121,27 @@ fn unit_field( stops: &[f64], live: bool, empty: &str, +) -> Option { + unit_field_from(ui, id, label, name, value, unit, width, share_of_value, bounds, stops, live, None, empty) +} + +/// [`unit_field`] whose blank field (`value` is `None`) steps from `blank_from` (points) with +/// ↑/↓ and the wheel instead of doing nothing. +#[allow(clippy::too_many_arguments)] +fn unit_field_from( + ui: &mut Ui, + id: impl std::hash::Hash, + label: Option, + name: Option<&str>, + value: Option, + unit: Unit, + width: f32, + share_of_value: bool, + bounds: RangeInclusive, + stops: &[f64], + live: bool, + blank_from: Option, + empty: &str, ) -> Option { let id = id_with(ui.scope_id(), id); let shown = value.map(|v| unit.format(v)).unwrap_or_else(|| empty.to_string()); @@ -131,8 +153,13 @@ fn unit_field( let read = |b: &str| typed.parse(&decimal_point(b)); let bounds_unit = unit.from_pt(*bounds.start())..=unit.from_pt(*bounds.end()); let stops: Vec = stops.iter().map(|&s| unit.from_pt(s)).collect(); - let stepped = - step_value(ui, &resp, &mut buf, &bounds_unit, (|b: &str| Some(unit.from_pt(read(b)?)), |v| unit.format(unit.to_pt(v))), None, &stops); + let blank_from = blank_from.filter(|_| value.is_none()); + let read_unit = |b: &str| match read(b) { + Some(v) => Some(unit.from_pt(v)), + None if b.trim().is_empty() => blank_from.map(|v| unit.from_pt(v)), + None => None, + }; + let stepped = step_value(ui, &resp, &mut buf, &bounds_unit, (read_unit, |v| unit.format(unit.to_pt(v))), None, &stops); let scrubbed = scrub::field(ui, id, rect, &buf, value.map(|v| unit.from_pt(v)), STEP_DECIMALS, &bounds_unit); let commit = commit && buf != shown; if commit { @@ -247,9 +274,10 @@ pub(super) fn shown_alike(show: impl Fn(f64) -> String) -> impl Fn(f64, f64) -> /// a weight stops at 0, a miter limit at 1), and a plain step also stops at each of `stops` /// ([`step_through`]). The new value is applied at once, as in /// Illustrator's panels and dialogs, and the new text replaces `buf`, all selected so typing -/// replaces it when focused. Returns the new number when a step was taken. While the pointer is -/// over an enabled field the wheel is the field's (the panel under it doesn't scroll), without -/// taking keyboard focus. Arrow keys still require keyboard focus. +/// replaces it when focused. Returns the new number when a step was taken. An enabled field takes +/// the wheel without taking keyboard focus, and the panel under it doesn't scroll, when the wheel +/// stream began over the field and the pointer was moved onto it, or pressed on it, after the +/// field last moved or was covered ([`number_wheel_turns`]). Arrow keys still require keyboard focus. fn step_value( ui: &Ui, resp: &Response, @@ -266,8 +294,10 @@ fn step_value( } let focused = ui.memory(|m| m.has_focus(resp.id)); use egui::{Event, Key, MouseWheelUnit}; - let wheel = resp.contains_pointer(); - if !focused && !wheel { + let (taken, owns) = number_wheel_turns(ui, resp); + let wheel = !taken.is_empty(); + let hold = wheel || owns && resp.contains_pointer(); + if !focused && !hold { return None; } // Wheel turns in notches: a line each, or `line` points of a trackpad or a fine wheel; what is @@ -277,14 +307,18 @@ fn step_value( // Each press and each turn of whole notches in the order they came: its modifiers and size from // [`STEPS`], and how many steps up (down when negative). let mut steps: Vec<(egui::Modifiers, f64, f64)> = Vec::new(); + let mut taken = taken; ui.input_mut(|i| { i.events.retain(|e| { + // Each taken event is matched once by its value, so wheel events that other code adds + // or removes before the field runs do not shift which events the field takes. + let mine = taken.iter().position(|t| t == e).map(|at| taken.swap_remove(at)).is_some(); let (Event::Key { modifiers, .. } | Event::MouseWheel { modifiers, .. }) = e else { return true }; let Some(&(mods, size)) = STEPS.iter().find(|(m, _)| modifiers.matches_logically(*m)) else { return true }; let n = match e { Event::Key { key: Key::ArrowUp, pressed: true, .. } if focused => 1.0, Event::Key { key: Key::ArrowDown, pressed: true, .. } if focused => -1.0, - Event::MouseWheel { unit, delta, .. } if wheel => { + Event::MouseWheel { unit, delta, .. } if mine => { // Shift may turn the wheel sideways (the Mac does). let d = if modifiers.shift { delta.x + delta.y } else { delta.y }; notches += match unit { @@ -302,7 +336,7 @@ fn step_value( } false }); - if wheel { + if hold { // The rest of a turn egui spreads over the next frames scrolls nothing either. i.smooth_scroll_delta = egui::Vec2::ZERO; } @@ -335,6 +369,194 @@ fn step_value( Some(v) } +/// An enabled number field as the wheel finds it. +#[derive(Clone, Copy)] +struct WheelTarget { + id: egui::Id, + rect: Rect, + layer: egui::LayerId, +} + +/// Where the pointer was, the field it was last moved onto, and the running wheel stream. +#[derive(Clone, Copy, Default)] +struct WheelWalk { + pointer: Option, + armed: Option, + stream: WheelStream, +} + +/// The number fields' wheel state in one viewport. +#[derive(Clone, Default)] +struct NumberWheel { + /// The pass whose events `walk` and `taken` cover. + pass: Option, + /// The enabled number fields drawn in the pass before `pass`. + before: Vec, + /// The enabled number fields drawn so far in `pass`. + drawn: Vec, + walk: WheelWalk, + /// Each wheel event of `pass` that a field takes, with the field. + taken: Vec<(egui::Id, egui::Event)>, +} + +/// The wheel events of this pass that number field `resp` takes, and whether the field holds the +/// wheel stream after them. The first field drawn in a pass reads the pass's events for every +/// field, using where the fields were drawn in the pass before. A field takes a wheel stream only +/// when the stream begins with the pointer over it and the pointer was moved onto it, or pressed +/// on it, after the field last moved or was covered by a window or overlay. A stream that began +/// anywhere else stays there until it ends ([`WheelStream`]) or the pointer is pressed on a field, +/// and a stream that leaves its field does not return to it. Trackpad momentum never starts a +/// stream on a field. +fn number_wheel_turns(ui: &Ui, resp: &Response) -> (Vec, bool) { + let ctx = ui.ctx(); + let key = egui::Id::unique("number-field-wheel").with(ctx.viewport_id()); + let pass = ctx.cumulative_pass_nr(); + let font_key = super::taken_from_raw_id(ctx.viewport_id()); + let fresh = ui.data_mut(|d| { + let state = d.get_temp_mut_or_default::(key); + if state.pass == Some(pass) { + return None; + } + let follows = state.pass.is_some_and(|last| last + 1 == pass); + state.before = if follows { std::mem::take(&mut state.drawn) } else { Vec::new() }; + state.drawn.clear(); + state.pass = Some(pass); + if !follows { + state.walk.pointer = None; + state.walk.armed = None; + state.walk.stream.release_any(); + } + // Turns the font family field took from the raw input belong to its stream. + let font_took = d.remove_temp::(font_key); + let state = d.get_temp_mut_or_default::(key); + if let Some(at) = font_took { + state.walk.stream.note_taken_elsewhere(at); + } + // A field that missed a pass may have moved. + if let Some(armed) = state.walk.armed + && !state.before.iter().any(|t| t.id == armed.id) + { + state.walk.armed = None; + state.walk.stream.release(armed.id); + } + Some((state.walk, state.before.clone())) + }); + let walked = fresh.map(|(walk, before)| { + let (events, now) = ui.input(|i| (i.events.clone(), i.time)); + walk_wheel(ctx, walk, &events, &before, now, pass) + }); + let target = WheelTarget { id: resp.id, rect: resp.interact_rect, layer: resp.layer_id }; + let (armed_here, pointer) = ui.data_mut(|d| { + let state = d.get_temp_mut_or_default::(key); + if let Some((walk, taken)) = walked { + state.walk = walk; + state.taken = taken; + } + (state.walk.armed.is_some_and(|armed| armed.id == resp.id), state.walk.pointer) + }); + // A window or overlay over the pointer covers the armed field even when no input arrives. + let covered = armed_here && pointer.is_some_and(|p| target.rect.contains(p) && ctx.layer_id_at(p) != Some(target.layer)); + ui.data_mut(|d| { + let state = d.get_temp_mut_or_default::(key); + if let Some(armed) = &mut state.walk.armed + && armed.id == resp.id + { + if armed.rect == target.rect && !covered { + armed.pass = pass; + } else { + // The field moved or is covered, so the pass's turns stay with the panel. + state.walk.armed = None; + state.walk.stream.release(resp.id); + state.taken.retain(|&(id, _)| id != resp.id); + } + } + state.drawn.push(target); + let mut mine = Vec::new(); + state.taken.retain(|(id, event)| { + if *id == resp.id { + mine.push(event.clone()); + } + *id != resp.id + }); + (mine, state.walk.stream.owner == Some(WheelStreamOwner::Field(resp.id))) + }) +} + +/// `walk` after `events`, with `fields` where the pointer finds them, at input time `now`; and the +/// wheel events a field takes (see [`NumberWheel::taken`]). +fn walk_wheel( + ctx: &egui::Context, + mut walk: WheelWalk, + events: &[egui::Event], + fields: &[WheelTarget], + now: f64, + pass: u64, +) -> (WheelWalk, Vec<(egui::Id, egui::Event)>) { + let under = |p: Option| { + let p = p?; + let layer = ctx.layer_id_at(p); + fields.iter().rev().find(|t| t.rect.contains(p) && layer == Some(t.layer)).copied() + }; + let mut taken = Vec::new(); + let mut left = false; + for event in events { + match event { + egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } => { + let pressed = matches!(event, egui::Event::PointerButton { pressed: true, .. }); + if walk.pointer != Some(*p) || pressed { + let field = under(Some(*p)); + walk.armed = field.map(|t| ArmedWheelField { id: t.id, rect: t.rect, pass }); + if let Some(WheelStreamOwner::Field(id)) = walk.stream.owner + && field.is_none_or(|t| t.id != id) + { + walk.stream.release(id); + } + // A press on a field gives it the rest of a running stream. + if pressed + && let Some(t) = field + && walk.stream.owner != Some(WheelStreamOwner::Field(t.id)) + { + walk.stream.owner = None; + } + } + walk.pointer = Some(*p); + } + egui::Event::PointerGone => { + walk.pointer = None; + walk.armed = None; + walk.stream.release_any(); + } + egui::Event::MouseWheel { delta, source, .. } => { + walk.stream.note_input(now); + let field = under(walk.pointer); + if *delta != egui::Vec2::ZERO { + let starts = field + .filter(|t| walk.armed.is_some_and(|armed| armed.id == t.id) && *source != egui::MouseWheelSource::Momentum) + .map_or(WheelStreamOwner::Elsewhere, |t| WheelStreamOwner::Field(t.id)); + let owner = *walk.stream.owner.get_or_insert(starts); + if field.is_none_or(|t| owner != WheelStreamOwner::Field(t.id)) { + walk.stream.owner = Some(WheelStreamOwner::Elsewhere); + } + } + if let Some(t) = field + && walk.stream.owner == Some(WheelStreamOwner::Field(t.id)) + { + taken.push((t.id, event.clone())); + } else { + left |= *delta != egui::Vec2::ZERO; + } + } + _ => {} + } + } + // egui smooths a pass's wheel input as a whole before any field runs, so a field cannot take + // part of it: a pass whose wheel input also scrolls something else is left whole to the panel. + if left { + taken.clear(); + } + (walk, taken) +} + /// A [`num_field`] for a width or height (Transform panel, Properties panel, Control bar): Ctrl/Cmd+Enter /// also commits it and ends its editing, as Enter does, and [`enter_modifiers`] reports Command. A /// percentage typed alone (`50%`) is that share of the size shown, as in Illustrator (#2401). @@ -625,12 +847,24 @@ pub fn spin_field_stops_named( presets: &[f64], ) -> Option { let label = take_previous_label(ui); - spin_generic(ui, label, value, None, None, None, width, step, min, presets, presets, &|v| unit.format(v), &mut |ui, fw, label| { - unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, presets, false, "") + let blank_from = BLANK_WEIGHT_STEPS_FROM; + // A blank field steps in points from `blank_from`, whatever the unit's preset ladder (#5349). + let stops = if value.is_none() { &BLANK_WEIGHT_STOPS[..] } else { presets }; + let fmt = |v: f64| unit.format(v); + spin_generic(ui, label, value, Some(blank_from), None, None, None, width, step, min, presets, stops, &fmt, &mut |ui, fw, label| { + unit_field_from(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, stops, false, Some(blank_from), "") }) .and_then(SpinPick::value) } +/// Where a blank Stroke Weight (the selected objects differ) steps from, in points: up goes to +/// 0.5 pt and down to 0 pt. This is the behaviour #5349 asks for. +const BLANK_WEIGHT_STEPS_FROM: f64 = 0.25; + +/// The stops a blank Stroke Weight steps through, in points, so that up gives 0.5 pt in every +/// Units > Stroke, not the first preset of the unit's own ladder above 0.25 pt. +const BLANK_WEIGHT_STOPS: [f64; 2] = [BLANK_WEIGHT_STEPS_FROM, 0.5]; + /// A distance field with spinner arrows kept within `bounds` (points), as the Drop Shadow and /// Outer Glow dialogs show their offsets and blur: the spinner steps one `unit` at a time /// (Shift ×10, Ctrl/Cmd ÷10), and it, ↑/↓, the wheel, a scrub and a typed value stop at both @@ -646,7 +880,7 @@ pub fn spin_length_within( let label = take_previous_label(ui); let step = Some(unit.to_pt(1.0)).filter(|s| s.is_finite() && *s > 0.0).unwrap_or(1.0); let field = bounds.clone(); - spin_generic(ui, label, value, None, None, None, width, step, *bounds.start(), &[], &[], &|v| unit.format(v), &mut |ui, fw, label| { + spin_generic(ui, label, value, None, None, None, None, width, step, *bounds.start(), &[], &[], &|v| unit.format(v), &mut |ui, fw, label| { unit_field(ui, id, label, None, value, unit, fw, false, field.clone(), &[], false, "") }) .and_then(SpinPick::value) @@ -671,7 +905,7 @@ pub fn spin_range( let places = decimals.min(6) as i32; let value = value.map(|v| within(v, &range)); let fmt = |v: f64| format!("{v}{suffix}"); - spin_generic(ui, label, value, None, None, None, width, step, *range.start(), &[], &[], &fmt, &mut |ui, fw, label| { + spin_generic(ui, label, value, None, None, None, None, width, step, *range.start(), &[], &[], &fmt, &mut |ui, fw, label| { bounded_field(ui, id, label, None, value, suffix, decimals, fw, &range, None, false, false) }) .and_then(SpinPick::value) @@ -729,7 +963,7 @@ pub fn spin_field_auto_named( presets: &[f64], ) -> Option { let label = take_previous_label(ui); - spin_generic(ui, label, value, auto, None, None, width, step, min, presets, &[], &|v| unit.format(v), &mut |ui, fw, label| { + spin_generic(ui, label, value, None, auto, None, None, width, step, min, presets, &[], &|v| unit.format(v), &mut |ui, fw, label| { unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, &[], false, "") }) } @@ -768,7 +1002,7 @@ pub fn spin_plain_named( let label = take_previous_label(ui); let value = value.into(); let fmt = |v: f64| format!("{v}{suffix}"); - spin_generic(ui, label, value, None, None, None, width, step, min, presets, &[], &fmt, &mut |ui, fw, label| { + spin_generic(ui, label, value, None, None, None, None, width, step, min, presets, &[], &fmt, &mut |ui, fw, label| { bounded_field(ui, id, label, name, value, suffix, decimals, fw, &(min..=f64::INFINITY), None, false, false) }) .and_then(SpinPick::value) @@ -794,6 +1028,7 @@ pub fn spin_kerning( ui, label, value, + None, automatic, optical, Some(optical_label), @@ -814,6 +1049,7 @@ fn spin_generic( ui: &mut Ui, label: Option, value: Option, + blank_from: Option, auto: Option, optical: Option, optical_label: Option<&str>, @@ -853,15 +1089,16 @@ fn spin_generic( ui.painter().line_segment([m + vec2(0.0, d), m + vec2(3.0, -d)], Stroke::new(1.2, c)); } sresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tl!("Step up or down"))); - // A blank field (values that differ) has nothing to step from. A click steps once; an + // A blank field (values that differ) steps from `blank_from`, if any. A click steps once; an // arrow held down steps again and again after a pause, as a spin button does (#4267). - let repeat = held_repeat(ui, &sresp); - if (repeat == Some(true) || (sresp.clicked() && repeat.is_none())) - && let Some(p) = sresp.interact_pointer_pos() - && let Some(v) = value - { + let is_up = match held_repeat(ui, &sresp) { + Some(true) => Some(ui.rect_contains_pointer(up)), + None if sresp.clicked() => sresp.interact_pointer_pos().map(|p| up.contains(p)), + _ => None, + }; + if let (Some(is_up), Some(v)) = (is_up, value.or(blank_from)) { let modifiers = ui.input(|i| i.modifiers); - out = Some(SpinPick::Value(spinner_step(v, step, min, up.contains(p), modifiers, stops, fmt))); + out = Some(SpinPick::Value(spinner_step(v, step, min, is_up, modifiers, stops, fmt))); } let fw = if presets.is_empty() { width - 15.0 } else { width - 34.0 }; let keyed = if presets.is_empty() { None } else { alt_down_in_field(ui, Rect::from_x_y_ranges(sr.right()..=sr.right() + fw, sr.y_range())) }; @@ -914,9 +1151,15 @@ const REPEAT_EVERY: f64 = 0.06; /// must not step once more. fn held_repeat(ui: &Ui, resp: &egui::Response) -> Option { let id = resp.id.with("repeat"); - let now = ui.input(|i| i.time); + let click_dist = ui.ctx().options(|o| o.input_options.max_click_dist); + let (now, primary_held) = ui.input(|i| { + let stayed = i.pointer.total_drag_delta().is_some_and(|d| d.length_sq() <= click_dist * click_dist); + (i.time, i.focused && i.pointer.primary_down() && stayed) + }); let state: Option<(f64, f64, bool)> = ui.data(|d| d.get_temp(id)); - if !resp.is_pointer_button_down_on() { + // Start from an egui press, but keep tracking it past the click timeout without taking drags from a scroll area (#6307). + let down_here = primary_held && resp.contains_pointer() && !resp.long_touched(); + if !resp.enabled() || !down_here || (state.is_none() && !resp.is_pointer_button_down_on()) { ui.data_mut(|d| d.remove::<(f64, f64, bool)>(id)); return state.filter(|(_, _, repeated)| *repeated).map(|_| false); } diff --git a/crates/ui-egui/src/widgets/panel_chrome.rs b/crates/ui-egui/src/widgets/panel_chrome.rs index e07367dab4..2c84716281 100644 --- a/crates/ui-egui/src/widgets/panel_chrome.rs +++ b/crates/ui-egui/src/widgets/panel_chrome.rs @@ -1,5 +1,41 @@ use super::{Color32, CornerRadius, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, Vec2, icons, pos2, theme, vec2}; +pub(crate) const PANEL_FOOTER: &str = "vectorcraft-panel-footer"; +const FOOTER_HEIGHT: f32 = 31.0; + +/// The finite body edge supplied by a sized dock, float or user-resized flyout. +/// Untouched flyouts omit it so their content can still determine their height. +pub(crate) fn panel_footer_bottom(ui: &Ui) -> Option { + ui.stack().iter().find_map(|stack| stack.tags().get_downcast::>(PANEL_FOOTER)).copied().flatten() +} + +/// Space left for a list above the footer and any intervening controls, or its unfitted fallback. +pub(crate) fn panel_list_height(ui: &Ui, fallback: f32, after: f32) -> f32 { + panel_footer_bottom(ui).map_or(fallback, |bottom| (bottom - ui.next_widget_position().y - FOOTER_HEIGHT - after).max(0.0)) +} + +/// Pad short content so a footer of `height` ends at the panel's saved bottom edge. +pub(crate) fn panel_footer_space(ui: &mut Ui, height: f32) { + if let Some(bottom) = panel_footer_bottom(ui) { + ui.add_space((bottom - ui.next_widget_position().y - height).max(0.0)); + } +} + +/// Pin a custom footer (for example the Variables panel's two rows). +pub(crate) fn panel_footer(ui: &mut Ui, height: f32, add: impl FnOnce(&mut Ui)) { + let Some(bottom) = panel_footer_bottom(ui) else { return add(ui) }; + let top = bottom - height; + if ui.next_widget_position().y > top { + ui.add_space(height); + } + let rect = Rect::from_min_size(pos2(ui.max_rect().left(), top), vec2(ui.available_width(), height)); + ui.painter().rect_filled(rect, 0.0, Tokens::get(ui.ctx()).panel); + // Own the blank parts too, so a click cannot select a scrolled row behind the footer. + let _background = ui.interact(rect, ui.scope_id().with("panel-footer-background"), Sense::CLICK); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), add); + ui.advance_cursor_after_rect(rect); +} + /// A bordered list box (Swatches tiles, Appearance rows, Artboards list). pub fn list_box(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { let t = Tokens::get(ui.ctx()); @@ -9,6 +45,25 @@ pub fn list_box(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { /// A bottom button bar separated from the content by a divider (panel footers). pub fn bottom_bar(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { let t = Tokens::get(ui.ctx()); + if let Some(bottom) = panel_footer_bottom(ui) { + // Reserve scrollable room after long content so its final row can move above + // the pinned footer instead of remaining hidden underneath its buttons. + let top = bottom - FOOTER_HEIGHT; + if ui.next_widget_position().y > top { + ui.add_space(FOOTER_HEIGHT); + } + let footer = Rect::from_min_size(pos2(ui.max_rect().left(), top), vec2(ui.available_width(), FOOTER_HEIGHT)); + ui.painter().rect_filled(footer, 0.0, t.panel); + let _background = ui.interact(footer, ui.scope_id().with("panel-footer-background"), Sense::CLICK); + ui.painter().hline(footer.x_range(), top + 4.0, Stroke::new(1.0, t.divider)); + let row = Rect::from_min_max(pos2(footer.left(), top + 7.0), footer.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(row).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + add(ui); + }); + ui.advance_cursor_after_rect(footer); + return; + } ui.add_space(4.0); let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 1.0), Sense::hover()); ui.painter().rect_filled(r, 0.0, t.divider); @@ -202,3 +257,40 @@ pub(super) fn chevron_cell(ui: &mut Ui, h: f32) -> Response { dresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Presets"))); dresp } + +#[cfg(test)] +mod footer_tests { + use super::{PANEL_FOOTER, bottom_bar, panel_footer}; + + /// Blank footer space intercepts clicks instead of selecting list rows underneath it. + #[test] + fn blank_footer_space_does_not_click_a_row_scrolled_behind_it() { + use egui::{Event, PointerButton, Rect, Sense, UiBuilder, UiStackInfo, pos2}; + for custom in [false, true] { + let ctx = egui::Context::default(); + let mut clicked = false; + let at = pos2(150.0, 190.0); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + for events in [vec![], vec![], vec![Event::PointerMoved(at), button(true)], vec![button(false)]] { + let input = + egui::RawInput { screen_rect: Some(Rect::from_min_max(pos2(0.0, 0.0), pos2(200.0, 200.0))), events, ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + let info = UiStackInfo::default().with_tag_value(PANEL_FOOTER, Some(200.0_f32)); + ui.scope_builder(UiBuilder::new().ui_stack_info(info), |ui| { + clicked |= ui.allocate_rect(Rect::from_min_max(pos2(0.0, 100.0), pos2(200.0, 200.0)), Sense::click()).clicked(); + let contents = |ui: &mut egui::Ui| { + let _button = ui.button("Footer button"); + }; + if custom { + panel_footer(ui, 31.0, contents); + } else { + bottom_bar(ui, contents); + } + }); + }); + output.textures_delta.clear(); + } + assert!(!clicked, "custom={custom}: a hidden row received the footer click"); + } + } +} diff --git a/crates/ui-egui/src/widgets/wheel_stream.rs b/crates/ui-egui/src/widgets/wheel_stream.rs new file mode 100644 index 0000000000..826b4dfe8c --- /dev/null +++ b/crates/ui-egui/src/widgets/wheel_stream.rs @@ -0,0 +1,66 @@ +//! Wheel streams for the fields that step on the wheel (number fields and the closed font family +//! field). A field takes a wheel stream only when the stream begins with the pointer over it and +//! the pointer was moved onto it after the field last moved or was covered by a window or overlay. + +/// The seconds without wheel input that end a wheel stream. This is VectorCraft's own value. +pub(crate) const WHEEL_STREAM_GAP: f64 = 0.5; + +/// Where the closed font family field, which takes its wheel events from the raw input, keeps the +/// input time of the last one it took in `viewport`, so number fields see that stream too. +pub(crate) fn taken_from_raw_id(viewport: egui::ViewportId) -> egui::Id { + egui::Id::unique("wheel-taken-from-raw").with(viewport) +} + +/// The field the pointer was last moved onto, while that field stays where it was and uncovered. +#[derive(Clone, Copy)] +pub(crate) struct ArmedWheelField { + pub(crate) id: egui::Id, + pub(crate) rect: egui::Rect, + pub(crate) pass: u64, +} + +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum WheelStreamOwner { + Field(egui::Id), + Elsewhere, +} + +/// One run of wheel input with no gap of [`WHEEL_STREAM_GAP`] in it, trackpad momentum included. +#[derive(Clone, Copy, Default)] +pub(crate) struct WheelStream { + last: Option, + pub(crate) owner: Option, +} + +impl WheelStream { + /// Note wheel input at `now`; a gap since the last input starts a new stream with no owner. + pub(crate) fn note_input(&mut self, now: f64) { + if !self.last.is_some_and(|last| (0.0..WHEEL_STREAM_GAP).contains(&(now - last))) { + self.owner = None; + } + self.last = Some(now); + } + + /// Note wheel input at `at` that another kind of field took: the stream it belongs to is not + /// one of this kind's fields. + pub(crate) fn note_taken_elsewhere(&mut self, at: f64) { + if self.last.is_none_or(|last| last <= at) { + self.note_input(at); + } + self.owner = Some(WheelStreamOwner::Elsewhere); + } + + /// Leave the rest of the stream to the panel when `field` holds it. + pub(crate) fn release(&mut self, field: egui::Id) { + if self.owner == Some(WheelStreamOwner::Field(field)) { + self.owner = Some(WheelStreamOwner::Elsewhere); + } + } + + /// Leave the rest of the stream to the panel when any field holds it. + pub(crate) fn release_any(&mut self) { + if let Some(WheelStreamOwner::Field(field)) = self.owner { + self.release(field); + } + } +} diff --git a/crates/ui-egui/tests/font_wheel.rs b/crates/ui-egui/tests/font_wheel.rs index 9e658a97b9..3cdb017d77 100644 --- a/crates/ui-egui/tests/font_wheel.rs +++ b/crates/ui-egui/tests/font_wheel.rs @@ -60,6 +60,34 @@ fn assert_queued_wheel_discarded_after_target_change(range: bool) { assert_eq!(app.session.active().unwrap().history.undo.len(), before, "the captured turn cannot restyle the new target"); } +#[test] +fn a_font_field_that_appears_under_a_still_pointer_leaves_the_wheel_until_the_pointer_moves() { + let (ctx, mut app) = selected_type_with_control(); + let mut texts = Vec::new(); + for _ in 0..8 { + texts = frame(&mut app, &ctx, vec![]); + } + let point = texts.iter().find(|(t, p)| t == "Inter" && p.y < 150.0).unwrap().1; + let selected = app.session.active().unwrap().selection.objects.first().unwrap().0; + app.run("select.set", json!({"ids": []})).unwrap(); + frame(&mut app, &ctx, vec![Event::PointerMoved(point)]); + frame(&mut app, &ctx, vec![]); + app.run("select.set", json!({"ids": [selected]})).unwrap(); + for _ in 0..8 { + frame(&mut app, &ctx, vec![]); + } + let mut still = wheel_input(point); + still.events.remove(0); + app.raw_input_hook(&ctx, &mut still); + assert!(still.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "the pointer did not move after the field appeared"); + let mut out = ctx.run_ui(still, |ui| app.ui(ui)); + out.textures_delta.clear(); + let mut moved = wheel_input(point + vec2(1.0, 0.0)); + moved.time = Some(ctx.input(|i| i.time) + 5.0); + app.raw_input_hook(&ctx, &mut moved); + assert!(!moved.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "the pointer moved onto the field"); +} + #[test] fn artboard_controls_leave_replaced_font_fields_wheel_available() { let (ctx, mut app) = selected_type_with_control(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2cb542c6b2..4fa8de6dac 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -529,6 +529,11 @@ fields measure visual bounds. Align to Glyph Bounds: the Align panel flyout's Align to Glyph Bounds submenu shows and toggles the `alignGlyphBoundsPoint` (Point Text) and `alignGlyphBoundsArea` (Area Text) preferences (`prefs.set`), checked while on. +Measure Type by Glyph Bounds: the Transform panel menu's Measure Type by Glyph Bounds item shows and toggles the +`typeGlyphBounds` preference (`prefs.set`), checked while on; while it is on, the bounding box and the Transform +panel, Properties and Control bar fields measure each point type object selected as an object (not inside a selected +group) by its glyphs' ink. + Align To: the Align panel's Align To choice is saved with the preferences, and `ui.inspect` reports it as `ui.align_to` (`"selection"` or `"artboard"`; Align to Key Object stores no choice). The align buttons of the Align panel, the Control bar and the Properties panel run `object.align` with `to: "artboard"` when one object is selected, @@ -572,9 +577,15 @@ New Document: File → New… (`file.newDialog`, Cmd+N) opens the `newDocument` `colorMode`, `rasterEffectsPpi`, `previewMode`) plus `category` (the tab: Recent, Saved, Mobile, Web, Print, Film & Video, Art & Illustration, Branding, Social), `advanced` (Advanced Options open), `bleedLinked` and `presetName` (Save Preset's name). Setting `preset` to a name from `file.newPresets` fills the other fields from that preset; -changing a field afterwards makes the settings custom (`preset` becomes ""). More Settings is the `newDocumentMore` -dialog over the same fields (its Profile is `category`). `ui.dialog.confirm` runs `file.new` with the fields (with -`previewMode: "pixel"` the app turns Pixel Preview on); on an error the dialog stays open. +changing a field afterwards makes the settings custom (`preset` becomes ""). The `newDocumentMore` dialog is New +Document with the More Settings pop-up open over it, which edits `artboards` and `artboardLayout` (layout, right-to-left, +spacing and columns). While `__saving` is true, Preset Details shows Save Document Preset with the `presetName` field, +Cancel and Save in place of the document's name and hides Close and Create. `ui.dialog.cancel` closes the More Settings +pop-up first, then leaves saving, and keeps the fields each time. `ui.dialog.confirm` runs `file.new` with the fields +(with `previewMode: "pixel"` the app turns Pixel Preview on); on an error the dialog stays open. While `__saving` is +true, `ui.dialog.confirm` saves the preset and does not create a document; after a save `presetName` is empty, and the +next Save Preset fills it with the first `Preset N` that no saved preset has. `ui.click` on the More Settings button +opens the `newDocumentMore` pop-up. Swatch Conflict: through the app, when the pasted objects' global or spot swatches conflict with the document's (see `clipboard.conflicts`) and the params have no `swatchConflict`, every Paste command opens the `swatchConflict` diff --git a/docs/dimensions.md b/docs/dimensions.md index e55e698f2b..1f1db9a492 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -4,8 +4,11 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers **Angular**, **Radial** and **Tool Options…** (double-clicking the tool opens Tool Options too). - **Linear:** hover a path segment and drag outwards: releasing places the dimension. Or click two - points (anchors snap, Shift constrains to 45°), then click to place. A curved segment is measured - from end to end. With Smart Guides on, both points also snap into line with other objects' + points (anchors snap, Shift constrains to 45°), then click to place. A click within 8 pixels of + an anchor of any path, in groups and compound paths too, takes that anchor, and the dimension + stays linked to it. A press on an anchor picks it when the pointer moves less than 8 pixels + before the release; a longer drag drags out the dimension of the segment under the pointer. A + curved segment is measured from end to end. With Smart Guides on, both points also snap into line with other objects' anchors and centres, and the second onto the construction guides through the first; the guides show while hovering, before each click. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 8f90ce5f4d..b1bc1fa38a 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -1,6 +1,6 @@ # Effects parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (Extrude & Bevel, Inflate and Rotate merge contours that cross, touch or overlap, as type often draws a glyph, before building a solid; previously: Extrude & Bevel, Inflate and Rotate apply to groups and layers, their objects turning about one shared axis (#4506); the Transform effect's copies of a path with a fill and a stroke (or several fills and strokes, an even-odd fill, or a partly transparent one) are drawn each above the one before, as Expand Appearance makes them (#5920); Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612); previously: Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Effect Gallery: a thumbnail for each filter and an in-dialog preview on an original drawing; the 1–2 h for those is done; Extrude & Bevel, Inflate and Rotate merge contours that cross, touch or overlap, as type often draws a glyph, before building a solid; previously: Extrude & Bevel, Inflate and Rotate apply to groups and layers, their objects turning about one shared axis (#4506); the Transform effect's copies of a path with a fill and a stroke (or several fills and strokes, an even-odd fill, or a partly transparent one) are drawn each above the one before, as Expand Appearance makes them (#5920); Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612); previously: Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) Every entry of Illustrator's Effect menu, by its public feature name, against VectorCraft's effects catalogue (`effect_catalog()` in `crates/effects/src/lib.rs`) and the Effect menu built from it @@ -12,7 +12,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( | Group | Illustrator | VectorCraft | % | Remaining (h) | |---|---:|---:|---:|---:| | Illustrator effects (vector and stylize) | 50 | 50 | 100% | — | -| Photoshop effects (raster, Effect Gallery) | 57 | 57 | 100% | 1–2 (Effect Gallery thumbnails and in-dialog preview) | +| Photoshop effects (raster, Effect Gallery) | 57 | 57 | 100% | — | | 3D and Materials | 4 (+3 Classic) | 4 (+1 Classic; initial: Extrude & Bevel, Revolve, Inflate, Rotate, Extrude & Bevel (Classic)) | ~25% | 25–45 | | Beyond Illustrator: Effect › Color Adjustments (6), effect plug-ins (WebAssembly) | — | 6 + plug-ins | — | — | @@ -22,7 +22,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( |---|---|---:|---| | Convert to Shape | Rectangle, Rounded Rectangle, Ellipse | 3/3 | — | | Crop Marks | Crop Marks | 1/1 | — | -| Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646); Expand Appearance of a path whose Transform effect makes copies gives a group of one object per copy, each painted as the path, and a second Transform effect's copies nest in a group per copy of the first (#5612); drawn, each copy of a path with a fill and a stroke (or several, an even-odd fill or a partly transparent one) paints above the one before, its fill covering the strokes of the copies below, instead of one path of every copy (#5920) | +| Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646); Expand Appearance of a path whose Transform effect makes copies gives a group of one object per copy, each painted as the path, and a second Transform effect's copies nest in a group per copy of the first (#5612); drawn, each copy of a path with a fill and a stroke (or several, an even-odd fill or a partly transparent one) paints below the one before, the fills above covering the strokes of the copies below, instead of one path of every copy (#5920), and a group's copies each hold all its members except guides, the original group on top (#6316); a clipping group, a group with a fill or stroke of its own, a group whose type is kept as type, and a group with a member that carries a geometry, Pathfinder or 3D effect copy each member in its place | | Path | Offset Path, Outline Object, Outline Stroke | 3/3 | With Use Preview Bounds on, Align, Distribute and the Transform panel still measure type that carries Outline Object by its layout box (preview bounds leave out effects) | | Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own | | Rasterize | Rasterize… (as a live effect) | 1/1 | — | @@ -48,12 +48,12 @@ its resolution, PDF export warns once per object with the requested and the lowe | Stylize | Glowing Edges | 1/1 | — | | Texture | Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer | 6/6 | — | | Video | De-Interlace, NTSC Colors | 2/2 | — | -| Effect Gallery | the combined browser and stack dialog | 1/1 (Effect › Effect Gallery…, #2883: six categories, per-filter settings, ordered stack with add/reorder/hide/remove, live canvas preview, one undo step; `dialogs::effect_gallery::tests::stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`) | filter thumbnails; a preview area inside the dialog ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)) | +| Effect Gallery | the combined browser and stack dialog | 1/1 (Effect › Effect Gallery…, #2883: six categories, per-filter settings, ordered stack with add/reorder/hide/remove, live canvas preview, one undo step; a thumbnail for each filter and a preview area inside the dialog, both an original landscape drawing passed through the filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html); `dialogs::effect_gallery::tests::stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`, `gallery_shows_thumbnails_and_an_in_dialog_preview`) | — | The pixel-filter pipeline (`vectorcraft_effects::pixel`) is in place: each new filter is one function, a catalogue row, a menu entry and translations. Measured throughput: 0.7–1.2 agent hours per filter (see [calibration](target-app-parity.md#calibration)). Every Photoshop-style filter is in the catalogue, and the Effect -Gallery dialog shipped (#2883); its filter thumbnails and in-dialog preview area are the 1–2 h that remain. +Gallery dialog shipped (#2883), with a thumbnail for each filter and a preview area inside the dialog. Both use an original landscape drawing passed through the filter; the canvas preview and the one-undo OK are unchanged. Film Grain (`artistic.filmGrain`, Effect › Artistic) adds stable monochrome noise to shadows and midtones, with Grain, Highlight Area and Intensity sliders, live preview and appearance editing. @@ -193,6 +193,7 @@ angular cut caps, exact visibility, the rest of 3D Classic (Revolve, Rotate, Map | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Effect Gallery: each filter has a thumbnail, and the dialog has a preview of the visible stack (or the browsed filter when the stack is empty). Both are an original landscape drawing passed through the filter ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)). The canvas preview and one-undo OK are unchanged. Remaining hours for the gallery's thumbnails and in-dialog preview: 1–2 → none. Counts unchanged (57/57). | | 2026-11-08 | minor | Extrude & Bevel, Inflate and Rotate merge contours that cross, touch or overlap (a glyph's arm across its stem) before building a solid, so the solid follows the shape as it is filled; others are built as drawn ([three-d.md](three-d.md)); scores and estimates unchanged | | 2026-11-06 | minor | Extrude & Bevel, Inflate and Rotate apply to a group or layer: a solid for every path, compound path and type in it, all turned about one shared axis as the public documentation describes for groups ([three-d.md](three-d.md#groups), #4506); scores and estimates unchanged | | 2026-11-06 | minor | The Transform effect's copies of a path or compound path whose fills and strokes stack (a fill and a stroke, several of either, an even-odd fill, or a partly transparent or blended one) are drawn each as an object of its own above the one before, as Expand Appearance makes them, instead of one path of every copy whose fill lay under every copy's stroke (#5920). A single opaque stroke or nonzero fill still draws as one path. Counts unchanged. | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9861de2aee..810d1568b9 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (PDF import: Separation images keep their ink, #6314; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (`.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -113,7 +113,10 @@ private editing data. VectorCraft: gutters and first baseline, threaded frames included) and type on a path are written as text: a text object for each, naming its story in the text document, with the characters, fonts, sizes, leading, tracking, baseline shift, scales, solid fills and strokes, capitals and paragraph alignment, indents, spacing and direction; other character - and paragraph attributes are left out with a warning. Each run's baseline direction is written in the form the reader + and paragraph attributes are left out with a warning. A font of the text document's font set that is a variable font + also names where in its design space the type is set (each `fvar` axis in the font's order, as 16.16 fixed: the named + instance's setting, or the run's own Variable Font setting) and its version string, so the type doesn't open at the + font's default instance (#6388); two settings of one font are two fonts of the set, and a static font names neither. Each run's baseline direction is written in the form the reader below reads it: 1 when Standard Vertical Roman Alignment is on, 2 when it is off and 3 for Tate-chu-yoko; the document's defaults and the normal character style carry 1. A run with both Tate-chu-yoko and Standard Vertical Roman Alignment is written as Tate-chu-yoko, with the type attributes warning. Type in opacity masks, pattern tiles, symbols and art cut to a @@ -223,6 +226,9 @@ private editing data. VectorCraft: A 1-bit gray image whose `XI` or `XF` has ImageMask 1 comes in colorized by the fill color set before it, or by black when that fill is not a solid color. VectorCraft's own rule is that the pixels that open black with ImageMask 0 take the color and the others are transparent. + An image whose color space `XC` sets to one ink (`n [… (name) /Separation] XC`) comes in as a grayscale image of + its tints (black at 100 %) colorized by the ink (its spot swatch, or a process plate's CMYK color), its alpha channel + as its opacity mask (#6350). - Estimate: **~65%** for real exchange with Illustrator users (open: ~75%; save: PDF-compatible, or legacy version 7 with layers and groups; not yet tested by users who hand files back). Closing the open-side issues: 10–20 h with users' files. @@ -280,10 +286,10 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | -| PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | +| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined Unicode CMap (`UniJIS-UCS2-H`), set as type in the font of the CIDFont's name; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | -| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`) | +| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`) | | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). CNC preset and VCarve QA remain open | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | @@ -308,8 +314,21 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | Affinity `.af`, `.afdesign`, `.afpub` | no | yes (beyond Illustrator) | no (#665) | 51 pinned files, [affinity-validation.md](affinity-validation.md) | | Clipboard: PDF, SVG, PNG, EMF, text | yes | yes | yes | copied files paste as art; cells copied from a spreadsheet (tab-separated text) paste as a table of point type over gridlines, at most 1000 rows, 256 columns and 20,000 cells (#5296) | +## PDF form gradients + +PDF export's linear and radial gradients stay aligned inside transparency groups, opacity masks, +PDF layers and overprinting art. The original synthetic tests in +`crates/pdf/tests/gradient_forms.rs` check the output with macOS Quartz and an import/render +round trip. The three Quartz checks fail on main `65adb7b21` and pass with the form-space fix; +translated layer bounds also have a regression for the current writer's layer-box repair. +Stop opacity on translated artboards remains outside this regression coverage. + ## PDF editable imports +- [x] Explicit `/ActualText` replaces covered glyph text once, including empty strings and nested spans (outer owner wins), while later glyphs retain pen geometry. Synthetic regressions in `crates/pdf/src/tests/actual_text.rs`; no added fonts/assets. UTF-16BE, BOM UTF-8 and PDFDocEncoding reuse the reader's text-string decoder. +- [x] Authored ordering is protected per stretch; ordinary stretches still reconstruct visual-order text. Outlines mode is unchanged. +- [ ] Exact redistribution of one replacement over several lines/styles, and general mixed-direction paragraph layout. Replacement uses the first placed glyph's line/style. Tags deeper than 128 and replacements over 64 KiB encoded (at most 192 KiB decoded) fall back to glyph mappings with a warning; an outer accepted owner survives deeper tags. + - [x] Place from bytes or unlinked paths, and PDF clipboard paste, keep the selected page's live text. Synthetic two-page regressions in `crates/engine/src/cmd/fileio/tests_pdffidelity.rs` cover both sources, page selection and explicit outlines. The single-page importer honors the same text choice as Open; existing PDF fallback rules are unchanged. ## Corpus download integrity @@ -320,8 +339,15 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | `.ai` and EPS import: an envelope of type (a warp, a mesh or a top object around type) kept its drawn art, its type hidden, because the type is laid out from the text document only after the layers are read. It now waits for that: its text slots get their type, and where VectorCraft's own envelope of that type draws as the drawn art the file saves (the same check and budget as other envelopes, seen on white and on black), it opens live in the drawn art's place, its type editable in Edit Contents, and the hidden copy goes. As with other live envelopes, the layers with one are then compared with the page, which weighs the envelope as the art it draws (not as type laid out again, which the comparison allows more for), and when they don't draw as it the drawn art and the hidden type are put back. Layers used though they don't draw as the page (the editing data trusted, or the objects that differ coming in as the page's art) leave envelopes of type their drawn art and hidden type too. A `.ai` whose layers would open alone, without its PDF part, imports the PDF part to compare them with, and should they still not draw as it, or should no envelope of type open live, they open alone as before, with the envelopes' drawn art. Type in a font that isn't available, slots without type of their own (threaded, bound to a text or a visibility variable, a wrap object, type a look draws), envelopes in a symbol's or a pattern's art, and envelopes that draw differently keep their drawn art, with the note (#3179). Tests `tests_native::an_envelope_of_type_that_draws_as_its_drawn_art_opens_live`, `an_envelope_of_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_white_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone`, `an_envelope_of_type_that_draws_apart_from_the_page_does_not_open_live`, `trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_drawn_art`, `layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_its_drawn_art`, `an_envelope_of_type_bound_to_a_visibility_variable_keeps_its_drawn_art` | +| 2026-11-10 | minor | `.ai` save: a variable font's record in the text document's font set names the type's place in the font's design space (`/4`, each `fvar` axis as 16.16 fixed: the named instance's setting, or the run's own Variable Font setting) and the font's version (`/5`). Without them, type in a named instance such as Bold opened at the font's default instance in the app that opens the file. Two settings of one font are now two fonts of the set; a static font's record is unchanged. The record's form comes from the public report in #6388. Test `ai_editing::tests::variable_font_instances_name_their_design_space` (#6388) | +| 2026-11-10 | minor | `.ai` and EPS import: an envelope of type, which keeps its drawn art with its type hidden, now says so in the import notes ("type in an envelope comes in as the envelope's drawn art, not as editable type"); nothing said it before, while the other envelopes that keep their drawn art have a note. The type is still not editable in the envelope (part of #3179). Test `tests_native::envelope_options_keep_the_source_text_hidden_under_its_outlined_appearance` | +| 2026-11-10 | minor | `.ai` and EPS import: the check that keeps a live envelope or warped type only where it draws as the art saved with it renders each on its own, over nothing, and compared the pixels seen on white, where white art looks like nothing. White contents that drew somewhere else passed it and opened live in the wrong place (white warped type off its banner, in users' files). Pixels now also differ when they look different seen on black, so such art keeps its saved art, as colored art does. Tests `import::ai::tests::a_white_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art`, `white_warped_type_that_draws_elsewhere_comes_in_as_its_look` | +| 2026-11-10 | minor | PDF import: an image in a DeviceN space of one colorant opens as a Separation image does (#6314): a grayscale image of its tints colorized by its ink. One of two or more colorants that are all process plates (Cyan, Magenta, Yellow, Black, and the ink `None`) opens as a CMYK image, each colorant's tint in its plate and its Decode array applied (8 or 16 bits a sample; one that can't be read, such as a JPEG, opens in RGB with the CMYK images' warning). Both used to open as RGB images, losing their inks. A DeviceN image that mixes a spot ink with other colorants, such as a duotone, still opens as RGB: an image holds one ink or the process plates, not both (#6348). Tests `colorize::a_devicen_image_of_one_ink_opens_colorized_by_it`, `colorize::a_devicen_image_of_process_plates_opens_in_cmyk`, `colorize::a_duotone_devicen_image_still_opens_as_rgb` | +| 2026-11-09 | minor | `.ai` import: an image whose color space `XC` sets to one ink (`n [c m y k /DeviceCMYK (name) /Separation] XC`, or an RGB alternate) opened as a gray RGB image: its samples, the ink's tints (255 at 100 %), were read as gray levels, so the tints drew inverted and the ink was lost. It now opens as a grayscale image of the tints, black at 100 %, colorized by the ink at 100 %: a spot swatch, a process plate's CMYK color (no swatch of its name), or Registration; the ink's color counts toward the document's color mode as a fill's does. Its alpha channel becomes its opacity mask, a reduced large image's too: a colorized image reduced to fit the limits (an image mask included) now keeps its alpha as an opacity mask rather than in its pixels, as at its full size. 8-bit and 1-bit samples, binary or in hex comment lines. A device space (`/DeviceGray XC` after a linked image's file name) and the ink `None` change nothing, as before; linked images (`XF`) keep their placeholder. Tests `import::ai::tests::separation_images_are_colorized_with_their_ink`, `separation_images_of_process_plates_and_registration`, `a_separation_image_with_hex_comment_lines_keeps_its_ink`, `a_reduced_separation_image_keeps_its_ink_and_its_alpha_as_a_mask` (#6350) | | 2026-11-09 | minor | PDF import: an image in a Separation color space (one ink, ISO 32000-1 §8.6.6.4) opens as a grayscale image of its tints (white where it lays no ink, black at 100 %, its Decode array applied; 1, 2, 4, 8 and 16 bits a sample, or one gray channel from its JPEG, CCITT, JBIG2 or JPEG 2000 decoder) colorized by its ink at 100 %: a spot ink's swatch, a process plate's CMYK color, or Registration. It used to open as an RGB image, losing the ink, and Fill and Recolor Artwork didn't reach its color. Its soft mask or mask becomes its opacity mask, as a CMYK image's does. The ink is found by the image's color space (kind, colorant name and tint transform), once per image. As with any colorized image, where it lays no ink the art under it shows, where the RGB image was opaque white. The ink `None`, which paints nothing, an ink whose color can't be told, an image inside an alpha soft mask, inline images and DeviceN images open as before; samples that can't be read (data cut short, a decoder's output of another layout) open in RGB with a warning, and the ink gets no swatch. Tests `colorize::a_separation_image_opens_colorized_by_its_ink`, `colorize::a_separation_image_reads_its_samples_and_decode_array`, `colorize::a_separation_image_of_a_process_plate_or_of_no_ink`, `colorize::a_separation_image_keeps_its_soft_mask`, `colorize::a_separation_image_drawn_twice_is_colorized_twice`, `colorize::a_separation_jpeg_opens_colorized_by_its_ink`, `colorize::a_separation_image_that_cant_be_read_stays_rgb` (#6314) | | 2026-11-09 | minor | PDF import: an image mask (`/ImageMask true`, ISO 32000-1 §8.9.6.2) painted in a solid color opens as a grayscale image of what it paints (black, the rest white) colorized by that color, as the `.ai` reader opens a 1-bit image mask (#5790). It used to open as an RGB image with the color in its pixels: Fill and Recolor Artwork didn't reach the color, a spot color lost its ink, and the same mask painted again in another color took the first color, in an uncolored pattern's cell too. Its color now counts toward the document's color mode, as a fill's does. A spot color is found by its color space, as a fill's is when the page's walk names no ink: two spaces of other inks with the same alternate and tint transform can't be told apart, and the color comes in as RGB. Inside an alpha soft mask, or painted with a pattern, a mask opens as before. Tests `colorize::an_image_mask_opens_colorized_by_its_spot_color`, `colorize::an_image_mask_drawn_in_two_colors_keeps_both`, `colorize::an_uncolored_pattern_drawing_an_image_mask_keeps_each_color` (#6313) | +| 2026-11-09 | minor | PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged. Synthetic evidence: `crates/pdf/src/tests/actual_text.rs`. | | 2026-11-09 | minor | PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged. Decoded stream and placement regressions; reader ActualText (#6165), styled clusters and external viewer validation remain separate. | | 2026-11-07 | minor | EPS and `.ai` editing data: when the page's type is matched with the text objects, a glyph the page's font encoding names with a private-use character (a ligature such as `uniE028`, which says nothing of the letters it stands for) splits the page's word there, and the pieces are matched as words. A ligature in "Quality" no longer reads "Qualy" against the text object: four users' Illustrator 30 EPS files (used locally, not committed) lose the false "some of the page's type has no text object" note, their renders unchanged | | 2026-11-07 | minor | EPS import: a CID-keyed font over a predefined Unicode CMap the file doesn't define (Adobe's public CMap resources named `Uni…-UCS2`, `-UTF8`, `-UTF16` or `-UTF32`, `-H` or `-V`: [cmap-resources](https://github.com/adobe-type-tools/cmap-resources)), found by its `CIDFont-CMap` name (`/Ryumin-Light-UniJIS-UCS2-H findfont`, the usual name of a CID-keyed font: its CIDFont's and CMap's names joined by a hyphen) or made with `composefont`, sets its codes' characters as live type in the font of its CIDFont's name, and `stringwidth` measures them. Such type was read as Latin-1 codes, or stopped the program at `composefont`. Vertical CMaps are set horizontally, and the show operators' extra spacing isn't kept; CIDFonts over other CMaps the file doesn't carry still draw nothing, with a warning. | diff --git a/docs/gaps.md b/docs/gaps.md index a62d829f37..ddc02a2d00 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,19 +1,17 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**Feature evidence last updated:** 2026-11-02. -| 2026-11-06 | minor | Opening a file that takes longer than 0.4 s shows a progress window: the file name, a moving bar (reading reports no steps), how many more files wait, Cancel (Esc; the file doesn't open) and Continue in Background (`file.cancelOpen`, `file.openInBackground`); it never opens over another dialog or progress window (part of #5930); scores and estimates unchanged | +**Feature evidence last updated:** 2026-11-03. + Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. -**PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. +Icon-strip flyouts resize from the canvas-side edge and bottom, keeping the icon-column edge anchored (#5713). Independent group heights and flyout widths persist in workspaces; saved heights override content fitting while untouched heights still fit content. Shared panel button bars and the Glyphs font row stay at the bottom after enlargement; the Artboards list grows into the extra space. Regressions: `panel_docking::tests::glyphs_and_artboards_flyouts_keep_user_sizes` and `expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists`. Scores and estimates unchanged. Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. -**PR #3272 revision — 2026-11-04:** Group Selection component drags defer ancestor selection until a completed click, using current Direct Selection release handling; original Outline Stroke fills and newer selection behavior retained. Scores and estimates unchanged. - Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. Window → Help Bar toggles the bottom tool-help strip independently of the status bar. Its visibility is saved with workspaces and UI preferences; Presentation Mode hides both bars. Scores and estimates are unchanged. @@ -24,12 +22,8 @@ adds one undo step; the list follows saved font filters, ignores search text, an stops at its ends. These interaction details are VectorCraft's choices. Scores and estimates are unchanged. -**Feature evidence last updated:** 2026-11-02. -**Feature evidence last updated:** 2026-11-03. - The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. -- Current-main conflict reconciliation retains upstream and feature behavior; scores and estimates unchanged - Superseded 2026-10-20 behavior, retained as history: Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting uses the original target artboard and revision-scoped bounds caches - Artboard Options puts Fit to Artwork Bounds and Fit to Selected Art in the Preset menu. Artwork bounds cover all drawn document art, including other artboards and off-board art; selection bounds may span artboards. Fit changes only the active artboard and keeps artwork stationary, including position-only fitting with Move Artwork enabled. Existing Background Color and presets remain available; scores and estimates unchanged. @@ -43,6 +37,9 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-08 | minor | #3380, deletion only: preserve gradient placement and exact surviving geometry; consume owned subpaths with a shared original-node snapshot; consolidate status/evidence and document command/helper contracts. Compound behavior and the existing M2 status entry are retained. Endpoint highlighting remains open; scores and estimates unchanged. | | 2026-11-07 | minor | #3380 (deletion only): independent surviving path objects; transformed appearance, stacking, selection, cubic handles and Undo/Redo covered by `delete_path_pieces`; compound semantics retained. Endpoint highlighting remains open; scores and estimates unchanged. | | 2026-11-06 | minor | G9: EPS import reads gradients a page paints as abutting strips as one linear gradient each (no seams); an Illustrator EPS whose page drew them that way keeps its layers. Estimate unchanged. | +| 2026-11-06 | minor | Opening a file that takes longer than 0.4 s shows a progress window: the file name, a moving bar (reading reports no steps), how many more files wait, Cancel (Esc; the file doesn't open) and Continue in Background (`file.cancelOpen`, `file.openInBackground`); it never opens over another dialog or progress window (part of #5930); scores and estimates unchanged | +| 2026-11-04 | minor | PR #3273: Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. | +| 2026-11-04 | minor | PR #3272: Group Selection component drags defer ancestor selection until a completed click, using current Direct Selection release handling; original Outline Stroke fills and newer selection behavior retained. Scores and estimates unchanged. | | 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. | | 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. | | 2026-11-07 | minor | Indian-language hyphenation (#4947): eleven MIT-licensed pattern sets, with grapheme and shaping-cluster protection in both composers and existing paragraph limits. Assamese and Sanskrit are selectable; Sanskrit automatic patterns remain pending an allowlisted source. Scores and estimates unchanged. | @@ -51,6 +48,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-05 | minor | G15: Selection skips building corner and pie widgets when the pointer is well outside a large selection; empty-canvas hover with 20,000 selected paths took 28.72 ms before and 16.41 ms after in local median runs. Other cursor targets remain active; estimate unchanged. | | 2026-11-05 | minor | G15: Direct Selection reuses one document hit result when choosing the cursor over a path; after the path hit-test improvement, a 200,000-anchor path's segment cursor took 3.72 ms before and 2.66 ms after in local median runs. Cursor behavior is unchanged; estimate unchanged. | | 2026-11-05 | minor | G15: large-selection transforms reuse object locations found during command validation; a 20,000-object nudge took 58.07 ms before and 51.26 ms after in paired median runs. Estimate unchanged. | +| 2026-11-06 | minor | Icon-strip flyouts resize on their free edges and retain sizes with workspaces (#5713); saved heights beat auto-fit; panel footers stay at the bottom after enlargement. Scores and estimates unchanged. | | 2026-11-05 | minor | G9, G14: `.ai` paths with a Calligraphic brush open brushed (the brush on the stroke, at its weight) where the object's settings are the brush's own, and the brush's Tilt, Bearing and Rotation codes come in as those channels; Windows reads the pen's tilt and barrel rotation from Windows Ink (#372). Checked against a user's file of 6D Art Pen strokes, used locally; not tried with a pen. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | @@ -60,17 +58,11 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-03 | minor | Help Bar has its own Window menu toggle and workspace visibility setting. Scores and estimates unchanged. | | 2026-11-02 | minor | Font-family fields step selected text with the mouse wheel (#5253); no scored gap or estimate reassessed. | | 2026-10-24 | minor | G12: General › Corner Radius is the Rounded Rectangle tool's radius, a change while the tool is active reaches it, and the radius ↑/↓ set while drawing (or a Tool Options value) becomes the preference, within 0–1296 pt (#394, `crates/engine/src/tests/constrain_tools.rs`); no entry closed, estimate unchanged. | -| 2026-10-22 | minor | Reconcile upstream documentation after review F-3; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | -| 2026-10-22 | minor | Reconcile upstream documentation after review F-2; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | -| 2026-10-22 | minor | Reconcile subsequent upstream progress updates without changing the runtime or repeating completed evidence; retain every dated upstream and feature revision. | -| 2026-10-22 | minor | Resynchronize newer upstream progress documentation using the same owned source/build cache; preserve every feature revision and the original scaleArt runtime evidence. | -| 2026-10-22 | minor | Retain the latest upstream shared assessment and complete revision history after newer documentation landed; scaleArt runtime and its original evidence remain unchanged. | -| 2026-10-22 | minor | Correct the scaleArt follow-up evidence description to match current upstream shared status and revision history; runtime, evidence, scores and estimates unchanged. | +| 2026-10-22 | minor | Documentation reconciled with newer upstream progress docs in six passes (after reviews F-2 and F-3), including a corrected description of the scaleArt follow-up evidence; every dated revision and the original scaleArt runtime evidence kept; runtime, scores and estimates unchanged. | | 2026-10-22 | minor | Artboard Options honors Scale Artwork with Artboard for preset, orientation and typed-size changes; both Fits keep artwork stationary; scores and estimates unchanged. | | 2026-10-21 | minor | Correct current global-all-art and document/revision cache descriptions; mark target-scoped fitting as superseded 2026-10-20 history. Runtime, tests, scores and estimates unchanged. | | 2026-10-21 | minor | Artboard Options puts Fit to Artwork Bounds and Fit to Selected Art in the Preset menu. Artwork bounds cover all drawn document art, including other artboards and off-board art; selection bounds may span artboards. Fit changes only the active artboard and keeps artwork stationary, including position-only fitting with Move Artwork enabled. Existing Background Color and presets remain available; scores and estimates unchanged. | -| 2026-10-21 | minor | Reconcile feature status and revision evidence in a dated section; retain shared baseline metadata for independent upstream updates. Scores and estimates are not reassessed. | -| 2026-10-21 | minor | Reconcile this feature with current main, preserving both sets of behavior and progress evidence; scores and estimates unchanged. | +| 2026-10-21 | minor | Feature status and revision evidence reconciled with current main in a dated section, keeping both sets of behaviour and progress evidence and the shared baseline metadata for independent upstream updates; scores and estimates unchanged. | | 2026-10-20 | minor | Review follow-up: artwork fitting uses the original target artboard and revision-scoped bounds caches; focused regression evidence and behavior documentation updated; scores and hours unchanged. | | 2026-10-20 | minor | Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; scores and hours unchanged. | @@ -94,10 +86,10 @@ stage ([ROADMAP.md](../ROADMAP.md)). | 5 | [G11 Correctness bugs in core tools](#g11-correctness-bugs-in-core-tools) | 8–15 | yes | [target-app-parity.md](target-app-parity.md) | | 6 | [G4 Advanced type](#g4-advanced-type) | 34–47 | core part | [type-parity.md](type-parity.md) | | 7 | [G12 Preferences and panels that don't act yet](#g12-preferences-and-panels-that-dont-act-yet) | 13–20 | yes | [ui-parity.md](ui-parity.md) | -| 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 1–2 | no | [effects-parity.md](effects-parity.md) | +| 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 0 | no | [effects-parity.md](effects-parity.md) | | 9 | [G13 Illustrator 2026 (30.x) additions](#g13-illustrator-2026-30x-additions) | 13–23 | no | [target-app-parity.md](target-app-parity.md) | | 10 | [G14 Pen hardware beyond Windows pressure](#g14-pen-hardware-beyond-windows-pressure) | 4–10 | Wayland pressure | [hardware-parity.md](hardware-parity.md) | -| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 11–21 | no | [target-app-parity.md](target-app-parity.md) | +| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 9–19 | no | [target-app-parity.md](target-app-parity.md) | | 12 | [G3 3D and Materials](#g3-3d-and-materials) | 25–45 | no | [effects-parity.md](effects-parity.md) | | 13 | [G7 Views and windows](#g7-views-and-windows) | 15–25 | no | [ui-parity.md](ui-parity.md) | | 14 | [G6 Automation and scripting](#g6-automation-and-scripting) | 4–8 | no | [target-app-parity.md](target-app-parity.md) | @@ -197,6 +189,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G9 Illustrator `.ai` and EPS files from real users +- **Done (#6388, 2026-11-10):** a saved `.ai`'s text document names, for type in a variable font, where in the font's design space it is set (each axis, the named instance's or the run's own setting) and the font's version, so Montserrat Bold no longer opens as the font's default instance (Thin); two settings of one font are two fonts of the set. Test `ai_editing::tests::variable_font_instances_name_their_design_space`. The PDF part's font naming (#4548) remains with craft-libs. Estimate unchanged. + +- **Narrowed (#6165, 2026-11-09):** editable PDF import preserves explicit ActualText once, with empty/nested spans, authored order and glyph advances covered by `crates/pdf/src/tests/actual_text.rs`. One replacement uses the first placed glyph's line/style; exact redistribution across lines/styles and general mixed-direction layout remain. Input is bounded to depth 128 and 64 KiB encoded per accepted replacement. This does not close G9's broader `.ai`/EPS gaps or change its estimate. + - **Done (2026-11-09):** the fonts an EPS carries draw their glyphs instead of being set as type in an installed font: composite (Type 0) fonts with the 8/8 mapping, plain Type 42 fonts (characters from their glyph names or character map, widths from the font), CID-keyed fonts over CMaps (Type 0 and Type 2 CIDFonts, CIDFonts in a FontSet's Compact Font Format data, base-font CMaps, named CIDFonts over predefined Unicode CMaps set as type) and embedded Type 1 fonts; the show operators' spacing along the baseline is kept as tracking, `kshow` included. Each step is charged to the interpreter's budgets. Hand-written test files only (no corpus file uses these fonts); scores and estimates unchanged. This narrows G9. - **Done (2026-11-06):** an EPS page that paints its gradients as rows of abutting one-colour strips imports them as linear gradients, so the seams between strips no longer show and an Illustrator EPS drawn that way keeps its layers instead of opening as its page. This narrows G9; scores and estimates unchanged. - **Done (2026-10-30):** from an audit of a user's `.ai`/EPS files: All Caps and Small Caps; placed files at their box's corner; pages cropped to the art; gradient mesh corners with handle weights of 0 and the transparency written after a mesh, a masked mesh and a blend; a layer's state block with the stroke style; type on a path spaced as the file lays it out (the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box, and the fit under Gravity does not reproduce the file's layout); EPS10 legacy-format type; a PDF of some artboards compared on the artboard its page shows. Comparison limits remain unchanged. This narrows G9; scores and estimates unchanged. @@ -313,7 +309,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G11 Correctness bugs in core tools -- **Export-only improvement (#6309):** PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. Broader G11 scope, scores and estimates unchanged. +- **Export-only improvement (#6309):** PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. Broader G11 scope, scores and estimates unchanged. - **Done, deletion only (#3380):** deleting anchors or segments that disconnect an ordinary contour creates independent selected path objects, preserving appearance, baked transforms, sibling order and one-step Undo/Redo. Existing multi-subpath paths and compound members stay intact. A second Delete removes all selected survivors. Bounds-fitted gradients keep their original placement on the new objects; already placed gradients stay unchanged. Segment endpoint highlighting remains open; broader G11 scope, scores and estimates are unchanged. Evidence: `crates/engine/tests/it/delete_path_pieces.rs` and the Delete/Backspace frame regression in `crates/ui-egui/src/tests/removeanchors.rs`. @@ -447,7 +443,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** CJK vertical composition (mojikumi sets and dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern features beyond bidi, digit types, Character Direction and Kashidas (Middle Eastern composers, a split caret), spell check (its engine is done, #4936: `text.spelling.check` and - `text.spelling.suggest` on craft-proof; the custom dictionary and Ignore All commands; Auto Spell Check, `edit.autoSpellCheck`; the Check Spelling and Edit Custom Dictionary dialogs and the right-click Spelling menu remain), + `text.spelling.suggest` on craft-proof; the custom dictionary and Ignore All commands; Auto Spell Check, `edit.autoSpellCheck`, with a right-click on an underlined word offering its suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type; the Edit Custom Dictionary dialog; the Check Spelling dialog remains), Touch Type, Retype, Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). Itemized in [type-parity.md](type-parity.md). - **Impact:** professional typography and Japanese/Chinese publishing. @@ -510,7 +506,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G2 Photoshop-style raster effects and the Effect Gallery - **Done:** Effect › Texture › Texturizer › Load Texture… (stored grayscale `textureImage`, Loaded Texture in the Texture menu), matching Glass. -- **Missing:** the Effect Gallery's filter thumbnails and a preview area inside the dialog ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)); all 57 Photoshop-style filters are in the catalogue. Measured in +- **Done:** the Effect Gallery's filter thumbnails and in-dialog preview ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)). Each thumbnail is an original landscape drawing passed through that filter at its defaults; the preview area shows the same drawing through the visible stack, or through the filter being browsed when the stack is empty. The canvas preview and the one-undo OK are unchanged (`dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`). All 57 Photoshop-style filters are in the catalogue. Measured in [effects-parity.md](effects-parity.md). - **Done:** the Effect Gallery (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step (`dialogs::effect_gallery::tests::stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`). - **Done:** Effect › Sketch › Conté Crayon (`sketch.conteCrayon`: Foreground Level, Background Level, Texture, Scaling, Relief, Light Direction, Invert; original visual approximation, defaults unverified), the last missing filter. @@ -518,7 +514,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** the pixel-filter pipeline and all 57 Photoshop-style filters (Artistic, Blur, Brush Strokes, Distort, Pixelate, Sharpen, Sketch, Stylize, Texture, Video), with live preview and editable native settings. Smart Blur supports Edge Only and Overlay Edge modes. Per-filter detail: [effects-parity.md](effects-parity.md). -- **Estimate:** 1–2 h (Effect Gallery thumbnails and in-dialog preview). +- **Estimate:** 0 h. ## G13 Illustrator 2026 (30.x) additions @@ -626,8 +622,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi symbol static drops them; stored in the native format. Color eyedropper for scatter, art and pattern brushes (Hue Shift colorization; samples canvas art); symbol libraries ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol - Libraries Menu open each library in a library panel of its own (two original libraries generated in code, - Basic Shapes and UI Frames with default 9-slice guides on Panel, Button and Bar; User Defined; Other + Libraries Menu open each library in a library panel of its own (three original libraries generated in code, + Basic Shapes, UI Frames with default 9-slice guides on Panel, Button and Bar, and Map Markers with Pin, + Flag, Crosshair and Checkpoint; User Defined; Other Library… reads the symbols of any document VectorCraft opens); a click adds a symbol to the document's Symbols with its Symbol Options and the resources it uses, as one undo step, and dragging one onto the canvas also places it; Save Symbols / Save Symbol Library writes the @@ -636,8 +633,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)): Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of - its own (four original libraries generated in code: Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter - Shapes; User Defined; Other Library… reads the brushes of any document VectorCraft opens); a click adds a + its own (five original libraries generated in code: Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter + Shapes and Game Trails; User Defined; Other Library… reads the brushes of any document VectorCraft opens); a + click adds a brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo step (applied to the selected paths in the same step), dragging one onto a path adds and applies it and dragging one onto the Brushes panel adds it; Save Brushes / Save Brush Library writes the document's brushes @@ -649,12 +647,15 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi is on, a Shift-click on a highlighted match leaves it out (`select.globalEditExclude`, #3521 evidence); Direct Selection of a path, compound path or type inside a dynamic instance also takes opacity and blend (`transparency.set`) and a gradient or pattern fill or stroke (`paint.setFill` / `paint.setStroke`, - Eyedropper), for that instance only. -- **Missing:** more built-in brush and graphic-style libraries (and further symbol libraries beyond Basic - Shapes and UI Frames; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; + Eyedropper), for that instance only; + graphic style libraries (Window › Graphic Style Libraries; seven original libraries generated in code, including + Game HUD with Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine and Boss Alert; User Defined; Other + Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). +- **Missing:** more built-in brush libraries beyond the five shipped (and further graphic-style libraries beyond the seven shipped, and further symbol libraries beyond Basic + Shapes, UI Frames and Map Markers; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; Global Edit of groups holding type or images, rotated copies as matches and highlighting matches before the start; 9-slice guides outside the symbol's art (a dragged guide stops at the art's edge). -- **Estimate:** 11–21 h. +- **Estimate:** 8–18 h. ## G3 3D and Materials @@ -688,8 +689,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** a scripting surface over the command registry (Illustrator: JavaScript, File › Scripts; - #1183 is open). Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and +- **Missing:** the document object model for scripts, a script console, the Scripts folder and script + directives (#1183 is open). File › Scripts › Other Script… and `script.run` run JavaScript files over the + command registry. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and export, and full agent control over MCP are done. - **Estimate:** 4–8 h. - **Done (2026-10-16):** the MCP server hears the client during a long call: `notifications/cancelled` stops a queued or running export (PDF pages, flattening, baking, drawing, artboards) without writing anything or changing the document, `ping` and the list methods answer at once, any other request that would wait behind a call running for two seconds or more is refused as busy (`-32003`, naming the call), and `_meta.progressToken` gets page progress (#2165, #2171, #2172). Reading the document during an export is not served (refused as busy); estimate unchanged. @@ -851,10 +853,19 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | G4 type: Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, #4936; the Check Spelling dialog remains; scores and estimates unchanged. | +| 2026-11-10 | minor | Tidy-up, no content change: in Feature submission evidence, a stray table row and two "PR #NNNN revision" notes move into Feature revisions, the three "Feature evidence last updated" lines become one, the duplicate Flyout update note goes (its row stays), and eight reconciliation rows become two. Scores and estimates unchanged. | +| 2026-11-10 | minor | G5: built-in Game HUD graphic style library (Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine, Boss Alert); Missing trimmed; estimate 10–20 → 9–19 h. | +| 2026-11-10 | minor | G5: built-in Map Markers symbol library (Pin, Flag, Crosshair, Checkpoint; no default 9-slice); Missing trimmed; estimate 11–21 → 10–20 h. | +| 2026-11-10 | minor | G4 type: a right-click on type has Spelling › Auto Spell Check, checked while it is on, #4936; the Check Spelling and Edit Custom Dictionary dialogs remain; scores and estimates unchanged. | +| 2026-11-10 | minor | G4 type: a right-click on a word Auto Spell Check underlined lists its suggestions, Ignore All and Add to Dictionary, #4936; the Check Spelling and Edit Custom Dictionary dialogs remain; scores and estimates unchanged. | +| 2026-11-10 | minor | G2: the Effect Gallery shows a thumbnail of each filter and a preview area inside the dialog (an original landscape drawing passed through the filter). Estimate 1–2 h → 0. The canvas preview and one-undo OK are unchanged. | +| 2026-11-09 | minor | G5: built-in Game Trails brush library (Speed Line, Dash Trail, Burst Ray, Zigzag); Missing trimmed; estimate 11–21 → 10–20 h. | | 2026-11-09 | minor | G4 type: Auto Spell Check (`edit.autoSpellCheck`) underlines the unknown words of the visible type, #4936; the Check Spelling and Edit Custom Dictionary dialogs and the right-click Spelling menu remain; scores and estimates unchanged. | | 2026-11-09 | minor | G5: built-in UI Frames symbol library (Panel, Button, Bar with default 9-slice); Missing trimmed; estimate 12–22 → 11–21 h. | | 2026-11-09 | minor | G5: Direct Selection of a dynamic instance part takes opacity, blend, gradient and pattern fill/stroke; Art brush Overlap and Pattern auto corners documented Done; estimate 15–25 → 12–22 h. | | 2026-11-09 | minor | G5: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out documented as Done (already in code); Missing trimmed; estimate unchanged. | +| 2026-11-09 | minor | PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged. Synthetic evidence: `crates/pdf/src/tests/actual_text.rs`. | | 2026-11-09 | minor | PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged. Decoded stream and placement regressions; reader ActualText (#6165), styled clusters and external viewer validation remain separate. | | 2026-11-09 | minor | Interim macOS canvas cursor delivery (#2292): existing artwork in aligned 1×/2× AppKit representations, visible system fallback and host-owned restoration. Headless routing, bitmap and ownership coverage; native timing, menus, focus/handback, mixed displays, Spotlight and full-screen Spaces remain unverified. Scores and estimates unchanged. | | 2026-11-09 | minor | G4 type: the custom dictionary (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, kept in a file beside the preferences) and Ignore All for the active document (`text.spelling.ignoreAll`), #4936; the Check Spelling and Edit Custom Dictionary dialogs and Auto Spell Check remain; scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 8f605eee0f..bc20483938 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -210,8 +210,10 @@ echo '{"jsonrpc":"2.0","id":1,"method":"prompts/get","params":{"name":"poster"," ### Resource templates -`vectorcraft://document` (summary), `vectorcraft://document/json` (the whole model), and -`vectorcraft://commands` (the live command catalog with enabled state) are the fixed resources. The templates read one thing at a time, which matters on a real document: the full model +`vectorcraft://document` (summary), `vectorcraft://document/json` (the whole model), +`vectorcraft://commands` (the live command catalog with enabled state) and `vectorcraft://commands/reference` (the +command API reference in Markdown, `text/markdown; charset=utf-8`; see [Parameter schemas](#parameter-schemas)) are +the fixed resources. The templates read one thing at a time, which matters on a real document: the full model is thousands of lines an agent pays for again on every change. | `uriTemplate` | Reads | @@ -369,10 +371,10 @@ The older names below remain listed because existing workflows use them. | Tool | Arguments and result | |---|---| -| `command_list` | Optional `filter` (or `query`), `menu` (a menu path substring, levels joined with ` > `), `enabled_only`, `brief` (no `params` text); returns the command array. `list_commands` lists the same commands; it takes `enabledOnly` and returns `{count, commands}` | +| `command_list` | Optional `filter` (or `query`), `menu` (a menu path substring, levels joined with ` > `), `enabled_only`, `brief` (no `params` text, `schema` or `inputSchema`); returns the command array. A command with a parameter schema lists `schema` and `inputSchema` (see [Parameter schemas](#parameter-schemas)). `list_commands` lists the same commands; it takes `enabledOnly` and returns `{count, commands}` | | `command_run` | `id`, optional `params`; runs the command through the existing backend. An unknown key in `params` is an error that names it and the nearest key the command takes (`invalid parameters for `file.new`: unknown parameter `widht`; did you mean `width`?`), so a misspelt key no longer runs the command with its default (see [Parameter keys](#parameter-keys)). `run_command` runs a command the same way and takes its id as `command` | | `command_batch` | `steps: [{id, params?}]` (at most 256), optional `stop_on_error` (default true), `atomic` and `label`; returns `completed`, `failed`, `results: [{ok, result\|error}]` and `created` (the ids the `draw_path` / `draw_shape` steps made, in order). A step's `id` is a command id, or `draw_path` / `draw_shape` with that tool's arguments as `params` (checked as `tools/call` checks them; the step's result is the tool's, so `"$N.id"` is the new object). Each edit has its own undo step, or with `atomic: true` the batch's edits are one undo step named `label` (else after its first edit; `edit.undoGroup.begin`/`end` underneath), and the edits made in a document that a step opens or creates (`document.open`, `file.new`) are one undo step there, named the same, also when no document was open before the batch. In a document that was open before the batch and that a step switches to (`document.activate`), each edit stays its own undo step; failures set `isError`. A param string `"$N.path"` or `"$last.path"` takes a value from an earlier step's result (see `run` below). Kept step results total at most 8 MiB; past that the batch stops with the reason. This is the MCP tool, not the engine command `command.batch` (that one takes `commands: [{command, params}]` and is what the Actions panel plays); use `command_run` with `command.batch` when replaying a recorded action | -| `command_list` | Optional `filter` (or `query`), `menu` (a menu path substring, levels joined with ` > `), `enabled_only`, `brief` (no `params` text); returns the command array | +| `command_list` | Optional `filter` (or `query`), `menu` (a menu path substring, levels joined with ` > `), `enabled_only`, `brief` (no `params` text, `schema` or `inputSchema`); returns the command array | | `command_run` | `id`, optional `params`; runs the command through the existing backend. An unknown key in `params` is an error that names it and the nearest key the command takes (`invalid parameters for `file.new`: unknown parameter `widht`; did you mean `width`?`), so a misspelt key no longer runs the command with its default (see [Parameter keys](#parameter-keys)) | | `doc_inspect` | Optional `depth`, `childLimit`, `ids`, `kind`, `limit`, `offset`; same summary as `inspect_document` | | `render_preview` | Optional `max_side` (1–4096, default 1024), `artboard` (0-based, default 0) and `traceViews`; inline PNG of that artboard without editing it, drawn as `export` draws a PNG with `background: "white"` at the scale that fits `max_side` (at most 1). With `traceViews: true`, Image Trace objects draw in the view set with `imageTrace.setView` (outlines, the source image…), as in the app's window; by default they draw their tracing result. Artboards too large to render within the allocation bound return a tool error | @@ -446,7 +448,7 @@ opens the picker through `run_command` with the remote backend. | Tool | Arguments | Notes | |---|---|---| -| `list_commands` | `{filter?, query?, menu?, enabledOnly?, brief?}` | The command catalogue: id, label, menu, shortcut, params doc (left out with `brief`), enablement. | +| `list_commands` | `{filter?, query?, menu?, enabledOnly?, brief?}` | The command catalogue: id, label, menu, shortcut, params doc, enablement, and `schema` and `inputSchema` for a command with a parameter schema (the params doc and both schemas are left out with `brief`). | | `run_command` | `{command, params?}` | Runs any command. Use it for everything without a dedicated tool. | | `inspect_document` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | Artboards (with `color`, `#rrggbb`, for one with a background color), layer tree (ids, kinds, bounds, paint), selection, history, tool. A type node's `fill`, `stroke` and `strokeWidth` are the paint its characters show (its first run's); fills and strokes of the type object itself come as `objectFill`, `objectStroke` and `objectStrokeWidth`. Paint comes as a label (`"#ff0000"`, `"None"`, `"G1 40% (#ff9999)"` for a swatch at a tint); `paint.proxies` gives it as an object. | | `inspect_ui` | `{}` | UI state. Remote mode only. | @@ -748,6 +750,7 @@ Fixed resources and the four templates (same as [Resource templates](#resource-t | `vectorcraft://document` | `document.inspect` summary (JSON) | | `vectorcraft://document/json` | The complete document model (JSON) | | `vectorcraft://commands` | Live command catalog with enabled state | +| `vectorcraft://commands/reference` | The command API reference (`engine.apiReference`), as Markdown (`text/markdown; charset=utf-8`) | | `vectorcraft://object/{id}` | One layer or object (`document.node {id, summary: true}`) | | `vectorcraft://command/{id}` | One command's metadata and enablement | | `vectorcraft://effect/{id}` | One live effect with parameters and defaults | @@ -779,7 +782,7 @@ point (72 times that value in ppi); `options.ppi` wins over either scale option. default 72 ppi still use 72 ppi; use `--ppi 300` for print output from those documents. Raster exports take more options in `options`: `ppi` (72, 150, 300…; stored in the file, except in GIF, WebP and -Targa), `background` (`transparent`, `white`, `black` or `"#rrggbb"`; `#rrggbbaa` and `#rgba` are refused), `antiAlias` (`none`, `art`, `type`: text +Targa), `background` (`transparent`, `white`, `black` or `"#rrggbb"`; `#rrggbbaa` and `#rgba` are refused; drawn under the finished art, so blend modes do not read it), `antiAlias` (`none`, `art`, `type`: text snapped to pixels) and, for PNG, `interlaced`. `width` or `height` sets the size of each file in pixels: each artboard (with `useArtboards`, each file), `rect` or art bounds gets the scale that makes it that wide or high, within 0.01–64 pixels per point, and the file stores the resolution that results, as with `ppi`. `width` wins over `height`, and @@ -837,7 +840,16 @@ transparency and rasterized areas are clipped to their regions. A file that woul export. PDF/X-1a and PDF/X-3 files are PDF 1.3 files too. A page with a side longer than 14,400 pt is written with a `UserUnit` (PDF 1.6): its longer side divided by 14,400, rounded up to the next thousandth, with the page's sizes and coordinates in those units, so that no side is longer than -14,400 units (ISO 32000-1, Annex C.2). In PDF 1.3 to 1.5 files and PDF/X files, such a page is written in points. +14,400 units (ISO 32000-1, Annex C.2). A PDF 1.5 file with such a page is written as PDF 1.6, with a warning, and +keeps PDF 1.5's encryption (128-bit RC4). PDF/X files and PDF 1.3 and 1.4 files write such a page in points, and apps +that keep to the limit cut it to 200 in. In PDF 1.3 and 1.4 files, PDF/X-1a and PDF/X-3 among them, a real number can +be at most 32,767, and whole numbers are written as integers: a page longer than 32,767 pt whose sides aren't whole +numbers of points fails the export with an error naming the page before the thumbnails are drawn and the transparency is +flattened, and one whose art needs a real number past 32,767 fails with the same error when the file is written. A page whose short side is 3 pt or longer but would be under 3 units at that +`UserUnit` (Annex C.2 gives 3 as the smallest page side), such as 30 m × 6 mm, gets a smaller `UserUnit`: its short +side divided by 3, rounded down to the next thousandth, so that the short side is at least 3 units and the long side is +longer than 14,400 units. Each such page adds a warning with its size and how it is written. File › Print writes pages in +points, 14,400 pt at most. An Illustrator EPS (version 9 on) or `.ai` file opens from the editing data it carries (after the EPS page; in the `.ai` file's PDF private data): layers and sublayers (name, order, visibility, lock, printing, preview, dimming, @@ -1111,7 +1123,7 @@ before anything runs, with the step's number and its entry (`entry 3`) or line ( ### What a headless session remembers -`vectorcraft-cli run` and the headless `mcp` server keep two things between runs, in folders next to the +`vectorcraft-cli run` and the headless `mcp` server keep these between runs, in folders and files next to the preferences (the folder the desktop app uses, so both see the same ones; `VECTORCRAFT_CONFIG_DIR` moves it): - **Saved PDF presets** (`pdf.preset.save`, `.delete`, `.import`): one `.vcpdfpresets` file per preset in @@ -1122,8 +1134,12 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR command, so `edit.colorSettings {"cmyk": "…"}` or a preset's output intent can name it in a later run. The copy is what counts: the original may move or be deleted. `color.removeProfile {name}` forgets a profile and its copy (not while it is a working space). +- **Color Settings** (`edit.colorSettings`): the RGB and CMYK working spaces, intent and black point + compensation go into `Color Settings.json` when they change, and are the active settings again at the next + start, after the profiles above are registered (#6335). Saved settings that name a profile that is no longer + there, or a damaged file, leave the defaults (logged), and the next change writes over the file. -Not remembered: Color Settings, the document, anything else. Nothing is read or written when +Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or `--automation-write-root` keeps nothing either (the folders are outside its roots). A file that is damaged, too large (a profile over 32 MB, a presets file over 1 MB) or not a valid preset or profile is skipped and logged. When the @@ -1382,6 +1398,71 @@ reference that names no value fails the step, so a command never runs with one l vectorcraft-cli run --cmd file.new --params '{"width":600,"height":200}' --cmd text.create --params '{"x":10,"y":60,"text":"plain and bold words","size":30}' --cmd text.setRangeStyle --params '{"id":"$1.id","start":10,"end":14,"style":"Bold"}' ``` +### Parameter schemas + +Some commands have a machine-readable parameter schema: at present `view.capsLock`, `view.saved.new`, +`view.saved.edit`, `view.saved.list`, `view.transparencyGrid`, `view.snapToGlyph.options` and `engine.apiReference`. The engine's +`engine.commands` list gives such a command a `schema` field: an object schema in the shape of JSON Schema 2020-12 +(https://json-schema.org/draft/2020-12). Its root has `$schema` (the 2020-12 dialect), `description` when the +command has a summary, and `deprecated: true` when the command is deprecated. The schema uses `type`, `properties`, `required` and +`additionalProperties: false` for objects; `minimum`, `maximum`, `exclusiveMinimum` and `exclusiveMaximum` for ranges; +`enum` for a list of names; `items` for the values of a list; `prefixItems`, `items: false` and `minItems: 2` for a +point; `anyOf` and `minItems: 3` for a color, which is a string, a list of at least three numbers or an object; +`description` for a parameter's doc text; `default` for a default the engine fills in; and `deprecated: true` for a +deprecated parameter. VectorCraft's own fields are `x-since` (the API level that added the command or the parameter), `x-deprecatedSince`, `x-lenient`, +`x-unit`, `x-kind` (`id`, `color` or `point`), `x-default` (a default the command works out, such as `toggle`), +`x-cost`, `x-writes` (`nothing`, `session`, `preferences` or `document`) and `x-returns`. A parameter that reads null +as left out is an `anyOf` with `{"type": "null"}`. Null params read as `{}`, so a schema with no required parameter has +the root `type` `["object", "null"]`. A schema with a required parameter has the root `type` `"object"`, and the engine +refuses null params for it as a missing parameter. A number with no fractional part, such as `2.0`, is an integer, as +JSON Schema defines one, and the command receives `2`. An `x-lenient` parameter's schema states the documented type, +and the engine also passes a value of another type to the command. The command's `params` text equals the text the +schema writes, and a test checks that they are the same. + +The `engine.commands` list and the `command_list` and `list_commands` tools also give such a command an `inputSchema` +field: the same schema in the form of an MCP tool's `inputSchema` +(https://modelcontextprotocol.io/specification/2025-06-18/schema), whose root `type` is always `"object"` +(https://modelcontextprotocol.io/specification/2026-07-28/schema). It differs from `schema` only in the root `type`, +which is `"object"` also when no parameter is required; every other keyword, `$schema` and the `x-` fields included, +is the same. A command without a schema lists neither field. The commands remain commands run with `command_run` +or `run_command`: `tools/list` does not list them as tools. With `brief`, the listings leave out `schema` and +`inputSchema` as well as the `params` text; a listing with the command's id as `filter` gives them. + +The engine checks the params of such a command against its schema before the command runs, for every new call: from +the desktop app, the control channel, MCP or the CLI, and when one command runs another. The steps of `command.batch` +and `action.batch` are checked before the first step runs. A value of the wrong type, out of range or not in its list, +a missing required parameter or an unknown key is refused with a parameter error that names the parameter, with the +path to a value inside a list or an object, and the document and its undo history stay as they were: + +```json +{"id": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}} +→ invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0 +{"id": "view.saved.edit", "params": {"edits": [{"name": "A", "delete": 1}]}} +→ invalid parameters for `view.saved.edit`: `edits[0].delete` must be true or false, not 1 +``` + +An omitted value with a `default` takes it (`rotation` 0 in `view.saved.new`); the journal keeps the params as they +were given. Saved steps played from a journal or an action keep a key the schema does not name, unless its value nests +more than 16 levels deep, and the values of the parameters it names are checked as in a new call. The schemas of built-in commands belong to API level 2 +(`vectorcraft_engine::schemas::API_VERSION`); a change to any of them raises the level. Level 2 added +`engine.apiReference`. Commands that plug-ins add have no schema here. + +`engine.apiReference {}` → `{markdown}` returns the command API reference, written from these schemas each time it +runs; no file of it is kept. It needs no open document and changes nothing. The reference has a `##` section for each +built-in command that has a schema, in registry order (the order `engine.commands` lists them), and leaves out every +command without one, plug-in commands included; `engine.commands` still lists those with their params text. A section +lists the command's label, menu path, API level, deprecation level, what it writes (`x-writes`), cost, summary and +return, then a table of its parameters in the schema's order with the columns Parameter, Type, Range, Unit, Default, +Required, Since, Deprecated and Description. A member of an object parameter is a row of its own after it, named with +dots and `[]` for a list (`edits[].name`). A range says whether each end is included ("more than 0", "at most 64"); a +default is either the JSON value the engine fills in, marked "(JSON)", or the note of a default the command works out; +the Description says when null reads as omitted and when the engine does not refuse a value of another type (a lenient +parameter). Text from a schema is escaped as Markdown text: each of `` \ | [ ] < > ` * _ ! & # ~ : @ `` and the `.` +after `www` get a backslash, and line breaks, tabs and other control characters become spaces, so a description cannot +end a table cell or make a link, an image or HTML. A reference larger than 1 MiB (1,048,576 bytes) is an error naming +`engine.apiReference`, and no part of it is returned. MCP serves the same text as the resource +`vectorcraft://commands/reference`. + ## Checking scripts written for the reference app `script.check {path? | data? | dataBase64?, name?, includes?}` reads a script written for the reference app @@ -1452,6 +1533,77 @@ the included files too. vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}' ``` +`script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. +File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page +https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html +describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any +case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is +not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and +`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the +app through one global object: + +- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can + catch. The documents and the session state the command changed, preferences included, go back, and any file it + wrote stays written and is named in the report. A result too large to cross throws a `RangeError`, and the + command's changes go back the same way. +- `vc.document` is a snapshot of the active document, or `null` when none is open. A snapshot too large to cross + throws a `RangeError`. +- `vc.commands` lists the commands a script may run. +- `vc.log(value)` adds a value to the report. +- `vc.args` is the `args` object. +- `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. + +The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A +run that changes no document adds no undo step. The journal records each command the run finished, as it records +commands run one at a time. A preference the run changed takes the run's value, and a preference changed in the app +while the run went on keeps that change. On an uncaught error, a limit or `script.stop`, every open document and the +session go back to their state before the run. A script can write files through the commands it runs, such as +export commands. A file written before the run failed stays on disk, and the error names it. A run from the menu +shows a warning first, unless you ticked Do not show this warning again or set the preference +`showExternalScriptWarning` to false. + +While a script runs, every other command that changes anything ends with the error `a script is running: stop it or +wait for it to finish`. MCP reports that error as JSON-RPC error `-32003`. `script.stop {}` stops the run and +returns `{stopped}`. `notifications/cancelled` stops a run only while the `tools/call` that started it is waiting +for it, as in a headless server; use `script.stop` for a run the app started. A script cannot run commands that +change anything outside the documents: `script.*` except `script.check`, `plugin.*`, `prefs.*`, `actionSet.*`, +`shortcutSet.*`, `help.*`, `print.*`, `library.*`, `importMatches.*`, `edit.undoGroup.*`, `file.recovery.*`, +`stroke.widthProfile.*`, saving, importing or deleting a preset, `text.addFontFiles`, `text.findFontFiles`, +`text.rescanFonts`, `links.findFiles`, `file.place.queue`, `color.loadProfile`, `color.removeProfile`, `file.print`, +`view.proofSetup`, `view.proofColors`, `view.overprintPreview` and `view.separationsPreview`. It also cannot run +`edit.clearHistory`: a run keeps each document's undo steps from before it and adds one. Calling one of these throws +an error. With Data Recovery off for complex documents, a run in the web build does not start while a complex document +has unsaved changes. + +VectorCraft sets these limits itself: + +| Limit | Value | +|-------|-------| +| Source text | 8 MiB | +| Heap | 256 MiB (128 MiB on the web) | +| Host calls | 2,000,000 | +| `maxFuel`, instructions in all | 1 to 100,000,000,000; 1,000,000,000 by default | +| Instructions without a pause | 200,000,000 | +| Nesting depth | 64 levels | +| A value crossing to or from a command | 16 MiB and 1,048,576 entries | +| `args` as JSON | 1 MiB | +| Log | 10,000 entries and 4 MiB | +| Growth before a person is asked | 100,000 objects and 512 MiB of new document data | + +In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and +`ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends +with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls}`. +In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. +`answers` takes only an empty object, since scripts have no prompts yet. + +```json +{"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} +``` + +```sh +vectorcraft-cli run --cmd script.run --params '{"path": "Tidy Layers.js", "args": {"margin": 12}}' +``` + ## Transparency and opacity masks Transparency and opacity-mask commands take `ids` (or `id`), so they need no selection. Opacity is a percentage @@ -1469,6 +1621,12 @@ the editing layer. With gradient mesh points picked, `opacity` goes to those poi {"name":"run_command","arguments":{"command":"transparency.info","params":{"ids":[12,20]}}} ``` +`transparency.makeOpacityMask` rejects a `clip` or `invert` value that is not a boolean, such as `"clip": "false"`, +and `transparency.setOpacityMask` does the same for `clip`, `invert`, `disabled` and `linked`. The toggles +`transparency.toggleNewMasksClipping`, `transparency.toggleNewMasksInverted`, `transparency.togglePageKnockoutGroup` +and `transparency.togglePageIsolatedBlending` reject a `value` that is not a boolean. A rejected call changes nothing. +Omitting a param or giving null keeps its default. + Knockout Group has three states: `transparency.set {knockout: "on"|"off"|"neutral"}` (`true` = on, `false` = neutral, the default). In a knockout group each child hides what it covers of the children below it; neutral groups pass the enclosing group's setting to their children, off groups never knock out. `knockoutShape: true` makes the @@ -1569,10 +1727,18 @@ overrides selected anchors or guides. Every explicit id is validated before any or unknown id leaves the document unchanged. An empty `ids` array does nothing. Layers themselves are kept, and selecting an ancestor together with its descendants deletes that subtree once. Without `ids`, direct-selected anchors or selected ruler guides retain their usual Clear behavior. -Cut still removes the objects it copied, including a whole compound when a member is selected. With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a boolean. +`edit.copy` takes a compound-path member selected on its own (whole or in part, with Direct or Group Selection) as an +ordinary path with the compound's paint, transparency, opacity mask and fill rule. The path is linked to the compound's +graphic style while it has that style's look, and otherwise to no style. A gradient fitted to the compound keeps the compound's fit. Copy takes the whole compound when the compound itself is selected, or when every member is +selected whole outside isolation mode, which includes the one member of a compound of one. In an isolated compound +path each member is taken as itself. `edit.cut` removes the same objects it copies, so cutting one member leaves the +other members in the compound, a compound of one member included. When Clear deletes every anchor or segment of every +member, it also removes the compound. With a copied member still selected, `edit.pasteInFront` puts the path into the +compound, just above the member. + `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is hidden or locked after the call: the selected objects it hides or locks, selected objects inside them, and selected objects that were already hidden or locked. The key object is cleared when it is one of them, and `edit.undo` selects @@ -1786,6 +1952,11 @@ View › Guides › Lock Guides (`view.guides.lock`) deselects them and the path document, and refuses these commands until unlocked. While it is on, a command that selects art, such as `edit.undo`, `edit.redo`, `object.exitIsolation`, `object.unlockAll`, `object.showAll` or `edit.paste`, leaves the guides out. `view.guides.lock` rejects a `locked` value that is not a boolean. Omitting `locked` toggles the current value. +While guides are locked, `guide.add` and a guide dragged out of a ruler still make new guides, which are locked too. +Preferences › Guides & Grid › Lock Guides by Default (`lockGuidesByDefault`, off by default) locks guides when the +desktop app starts. Changing the preference, with `prefs.set` or `prefs.reset`, sets the lock to the new value at once. +`view.guides.lock` changes the lock for the session and does not change the preference. A headless session starts +with guides unlocked, as the preference is off until `prefs.set` turns it on. `view.guides.release {index?, ids?}` (View › Guides › Release Guides) turns guides into paths → `{count}`. With `index` it releases that ruler guide, and with `ids` it releases those guide paths (and the guide paths inside them). @@ -2347,10 +2518,12 @@ default) white ones knock out instead; `"discard"` writes none. ## Revolve (initial 3D effect) -`effect.apply {effect: "threeD.revolve", params: {...}, ids?, item?}` applies a live Revolve to a path -or compound path. `effect.dialog` opens compact options with artboard rotation and light gizmos, `effect.setParams` edits it, and +`effect.apply {effect: "threeD.revolve", params: {...}, ids?, item?}` applies a live Revolve to a path, +compound path, type, clipping group, blend, symbol instance, or a group or layer of them. `effect.dialog` opens compact options with artboard rotation and light gizmos, `effect.setParams` edits it, and `effect.expandAppearance` bakes it into shaded vector faces. Native saves keep the editable source; SVG/PDF exports bake the same faces the canvas draws. Only one Revolve is supported per profile. +Type sweeps as its glyph outlines and stays type. On a group or layer, every visible member sweeps about one axis on the chosen edge of the members' bounds together, in its own paint, and the members stay editable. A clipping group sweeps its art inside the clipping path, a blend its keys and steps, and a symbol instance its symbol's art where the instance places it, alone or in a group ([three-d.md](three-d.md#clipping-groups-blends-and-symbol-instances)). An image, alone or in a group, is refused with "trace it first with Object › Image Trace › Make"; a group holding another object that can't be swept is refused, and so is type with no outlines or a group with no shape in it. +A surface takes at most 16,384 profile points and 163,840 faces, the members of a group together, counted after any geometry effects before the Revolve. A straight segment takes one point, a curve takes at least four, and each contour takes one. Each curved segment takes 16 samples; on a surface over those limits every curve takes as many as fit, down to 4, and the call is refused below that with "reduce Segments or simplify the profile". The call is also refused with "reduce Segments or simplify the gradient" when the faces' copies of the paint would take more than 256 MiB, counted together for the members of a group and for the fills and strokes of one object that carry a Revolve. To find the holes, mesh export cuts each sampled piece of a closed contour where it crosses another closed contour, adding a profile point at each cut, and tests the middle of each part against the closed contours whose bounds share its cell of a grid over the profile. It refuses the profile as too complex when its contours overlap so much that the search would take more than 16,000,000 steps, where each path element tested, each contour looked at and each contour placed in a grid cell counts one. Parameters: `angle` (degrees, 0..360, default 360), `offset` (points, 0..100000, default 0), `edge` (`"left"` or `"right"`), `rotationX/Y/Z` (degrees, defaults 0/0/0), `perspectiveAngle` @@ -2423,7 +2596,13 @@ checked as that effect's. It is one undo step. Any other `threeDType` value, or `effect.apply {effect: "threeD.extrude" | "threeD.inflate" | "threeD.rotate", params: {...}, ids?, item?}` applies the other 3D types to a path or compound path, live like Revolve (the source stays editable; SVG/PDF exports and -`effect.expandAppearance` use the same shaded faces). An object takes one 3D effect, Revolve included. +`effect.expandAppearance` use the same shaded faces). An object takes one 3D effect, Revolve included. On a group or +layer the 3D effect goes on the group itself: `effect.apply` and `effect.setParams` refuse one on its fill or stroke. +Every 3D type, `threeD.classicExtrude` and `threeD.revolve` included, also applies to a clipping group, a blend or a +symbol instance, alone or in a group, and builds from the art it shows, the same way for the canvas, exports and +`assets.add3D` ([three-d.md](three-d.md#clipping-groups-blends-and-symbol-instances)); like a group, it takes the +effect on the object itself, not on a fill or stroke. An image, alone or in a group, is refused with "trace it first +with Object › Image Trace › Make", and nothing changes. `threeD.extrude`: `depth` (points, 0..2000, default 50), `twist` (degrees, 0..360, 0), `taper` (1..100%, 100), `cap` (true solid, false hollow), `bevel` (`none`, `classic`, `rounded`, `cove`, `step`, `ogee`), `bevelWidth` @@ -2433,6 +2612,12 @@ solid, false open behind), `volume` (0..100%, default 50), `bothSides`. All three take `rotationX/Y/Z` (degrees, -180..180, default the Off-Axis Front position -21.88/-23.4/9.06), `perspectiveAngle` and the lighting parameters as Revolve. See [three-d.md](three-d.md) for the Position presets, the scope and what differs from the public documentation. +`threeD.extrude` and `threeD.inflate` take up to 65,536 outline points and build up to 163,840 faces for each solid +(VectorCraft's own limits); with more faces than that, each curve takes fewer pieces, down to 4. A shape past the +points returns "The shape is too complex for a 3D effect", and one whose faces do not fit at 4 pieces a curve returns +"The 3D surface is too complex; simplify the shape". `threeD.inflate` also returns the surface error when its outline +has so many points across so many of its grid's cells that filling the grid would pass its work limit. `threeD.rotate` +takes up to 65,536 points. ## Extrude & Bevel (Classic) @@ -2471,6 +2656,8 @@ the image; linked images are left alone) and the tiles of pattern fills and stro pattern swatch, e.g. "Dots 2"; the original pattern is untouched). Colorized image fills are recolored when fills are in scope, but their pixels are never recolored. `includeImages: false` leaves other images' pixels unchanged. For `edit.colors.*`, `fill: false` leaves colorized image fills unchanged. `recolor.apply` always includes fills. +`edit.colors.toGrayscale` and `edit.colors.adjustBalance` with `mode: "gray"` and `convert: true` store an embedded image +with one gray channel, so a PDF writes it in gray. `includePatterns: false` leaves patterns out. The Blend commands also grade gradient meshes, which keep their shading. `edit.colors.saturate` needs `intensity`, a number from -100 to 100 (a number outside the range counts as its nearest end). Without one, or with a value that is not a number, it answers `` missing number `intensity` `` and changes nothing. @@ -2644,7 +2831,7 @@ as a value left out. ## Graphic style libraries Graphic style libraries are read-only sets of graphic styles generated in code (Shadows and Glows, Outlines and -Rules, Hand-Drawn, Gradient Finishes, Shape Effects, Blends and Transparency). `graphicStyle.libraries` lists them +Rules, Hand-Drawn, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD). `graphicStyle.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `graphicStyle.library {library}` returns one's styles in the `graphicStyle.list` shape (`library` is an id or a name). `graphicStyle.addFromLibrary {library, name? | names?}` copies styles into the document's Graphic Styles as one undo step (no names: the whole library); styles the @@ -2692,10 +2879,10 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: four generated in code (Art Ribbons, Calligraphic Nibs, Pattern -Borders, Scatter Shapes), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and -the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default -ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and +Brush libraries are read-only sets of brushes: five generated in code (Art Ribbons, Calligraphic Nibs, Pattern +Borders, Scatter Shapes, Game Trails), the `.vectorcraft` files in the user library folder of the desktop app (User +Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has +the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). `brush.addFromLibrary {library, name? | names?}` copies brushes into the document's Brushes as one undo step (no names: the whole library), with the resources their art uses: patterns, symbols, swatches (`swatchConflict` as for @@ -2872,7 +3059,7 @@ where the layout puts it. `object.flattenTransparency {ids?, preset?, …options}` turns transparent art into opaque art that looks the same, in one undo step. The targets split into groups of overlapping objects; groups without transparency stay as they are. Each other group becomes one group of atomic regions: paths filled with the flat colour the art showed there (over -white; over nothing, keeping alpha, with `preserveAlpha: true`), plus one image where gradients, patterns, images, +white, which blend modes do not read; over nothing, keeping alpha, with `preserveAlpha: true`), plus one image where gradients, patterns, images, opacity masks or raster effects reach (clipped to those regions with `clipComplexRegions`, a rectangle without). `preset` is `high`, `medium` (the default) or `low`; option keys (`balance` 0–100, `lineArtPpi`, `gradientPpi`, `textToOutlines`, `strokesToOutlines`, `clipComplexRegions`, `antiAlias`, `preserveAlpha`, `preserveOverprints`) @@ -3177,18 +3364,24 @@ and `stroke.widthProfile.reset` removes every saved one. `stroke.set {profile}` ## Arrowheads -`stroke.set {startArrow, endArrow}` takes any of 40 generated heads by name (the params doc lists them; `null` for -none): arrows (`Arrow`, `Barbed`, `Concave`, `DoubleArrow`, `HalfArrowLeft`/`Right`, `Chevron`, `Feather`, +`stroke.set {startArrow, endArrow}` takes any of 41 generated heads by name (the params doc lists them; `null` for +none): arrows (`Arrow`, `LineArrow`, `Barbed`, `Concave`, `DoubleArrow`, `HalfArrowLeft`/`Right`, `Chevron`, `Feather`, `Swallowtail`…), filled and open shapes (`Triangle`, `Circle`, `Oval`, `Target`, `Tag`, `Diamond`, `Hexagon`, `Star`, the `…Open` rings…) and marks (`Bar`, `DoubleBar`, `DotOnBar`, `Slash`, `DoubleSlash`, `Bracket`, `Fork`, `Cross`, -`Plus`). Each head fits a box about four times its weight (stroke weight × `arrowScale`) long and wide. +`Plus`). Each head fits a box about four times its weight long and wide. A head's weight is the stroke weight scaled by +`arrowScale`, at least 0.25 pt. `LineArrow` has two arms of the head's weight (the line's weight at 100 % for lines of +0.25 pt or more) at right angles and spreads twice as wide. ## Stroke bounds and clicks Visual bounds (Fit to Selected Art, Rasterize, exporting all art) and clicks on the canvas take in the whole stroke as drawn: arrowheads, inside/outside alignment (an outside stroke is hit outside the path, an inside one inside it), the width profile's width where you click, projecting caps and miter spikes up to the miter -limit. A rectangle's right-angle miters stay within half the weight of its edges. +limit. A rectangle's right-angle miters stay within half the weight of its edges. A butt-capped stroke on an open +path does not reach past the path's ends: a straight segment's box comes from the four corners of its stroked +rectangle. Past an end, only a round or projecting cap or an arrowhead adds to the box. A curve that bends more +tightly than half the stroke weight can measure a little larger than it paints, and a butt-dashed path whose first or +last dash is a gap is measured to the path's ends. A symbol instance is measured by its symbol's art, placed by the instance's transform. The bounds in `document.inspect` and `document.node`, the Align commands, `object.setBounds`, the bounding box, clicks, marquees, @@ -3250,6 +3443,8 @@ holds symbol instances that `object` expands, whether only their art holds it, w mesh points as the gradient paints them, with the colors Object › Expand gives them. `object.expand`, `effect.expandAppearance`, `type.createOutlines` and `object.path.outlineStroke` turn a dimension whose art they change into a plain group of that art, in the same undo step (see [dimensions.md](dimensions.md)). +`object.expand` rejects a param of the wrong type, such as `"fill": "yes"`, `"gradient": 3` or `"steps": "16"`, and +changes nothing. Omitting a param or giving null keeps its default. ```json {"name":"run_command","arguments":{"command":"object.expand","params":{"stroke":false,"gradient":"mesh"}}} @@ -3487,6 +3682,11 @@ dialog `simplifySlider` with field `level`) at the Auto-Simplify level for the s opens the Simplify dialog at the slider's tolerance. When OK confirms the dialog with `retain` ticked, the menu item opens the dialog on those settings next time. +`object.path.simplify`, `object.path.offsetPath`, `object.path.splitIntoGrid`, `object.path.cleanUp`, +`object.pathfinder.trap` and `addon.contour.set` reject a param of the wrong type, such as `"offset": true`, +`"joins": 3`, `"rows": "many"` or `"addGuides": "yes"`, and change nothing. A distance still takes a string with a unit +(`"5 mm"`). `joins` must be `miter`, `round` or `bevel`. Omitting a param or giving null keeps its default. + ## Smooth `object.path.smooth` smooths the selected paths (or the objects in `ids`), compound path members included, as one undo @@ -3917,6 +4117,36 @@ an error that lists the choices of a `horizontal`, `vertical`, `to`, `axis` or ` (`object.reflect` also takes an angle and names the value given), and one for a `spacing` that is not a number; nothing moves. +## Glyph bounds for type + +The bounding box normally measures point type by its em box, which leaves room above and below the letters for +ascenders, descenders and capitals. With the preference `typeGlyphBounds` on (`prefs.set {key: "typeGlyphBounds", +value: true}`; also Preferences › Type › Glyph Bounds and the Transform panel menu's Measure Type by Glyph Bounds), the +bounding box and its handles, the Transform panel's, Control bar's and Properties panel's X, Y, W and H, +`object.setBounds`, the Scale, Rotate and Reflect tools' reference point, and Swap Objects, Replace with Top Object, +Set Size of Each and Sort Objects measure point type, horizontal or vertical, by the ink of its glyphs: its glyph +outlines and its underline and strikethrough bars. This applies to each point type object that is selected as an object +(not inside a selected group), in a selection with other objects too. The option is VectorCraft's own and is off by +default. + +A width or height typed with the option on scales the type until its ink has that size. The type stays live type: its +font size changes by the vertical scale, so `object.setBounds {height: 72}` on "H" gives the cap height 72 pt, not a +72 pt font. A width typed alone, out of proportion, changes the horizontal scale and keeps the font size, and a height +typed alone keeps the width, so the horizontal scale changes the other way. With Use Preview Bounds on, the ink takes in the characters' strokes, and type with geometry effects is +measured as drawn. Rotated type keeps its own angle, and skewed type is measured by its glyph outlines. Type that +draws nothing (no text, or only spaces without underline or strikethrough), area type, type on a path and type inside +a selected group are measured as before. Arrange in Grid and Group Overlapping Objects measure visual bounds as +before, and Align and Distribute follow Align to Glyph Bounds. + +When moved type snaps (Snap to Grid, Snap to Pixel, Smart Guides and ruler guides), the edges and center of its ink box +snap, and the Distance Guides measure from that box. The other objects that it snaps to keep their usual boxes, as +they do with Use Preview Bounds. The preference is not saved in documents. + +```json +{"name":"run_command","arguments":{"command":"prefs.set","params":{"values":{"typeGlyphBounds":true}}}} +{"name":"run_command","arguments":{"command":"object.setBounds","params":{"height":72,"proportional":true}}} +``` + ## Selection preferences The Selection & Anchor Display and General preferences apply to `pointer_gesture` as they do to the mouse: @@ -3995,9 +4225,11 @@ desktop app): in View › Pixel Preview, on softens placed and embedded bitmaps; `disableAutoAddDelete` (off by default): on, the Pen no longer adds or deletes an anchor when a click lands on a segment or an anchor of a selected path. -`ctrlWheelScrollsSideways` (on by default): on, Cmd/Ctrl-wheel scrolls the canvas sideways instead of zooming while -`zoomWithMouseWheel` is off; off, Cmd/Ctrl-wheel zooms about the pointer. Alt + Cmd/Ctrl-wheel and a pinch on a Mac -trackpad, on a touch screen or in the web build still zoom about the pointer. With `zoomWithMouseWheel` off, once a +`ctrlWheelScrollsSideways` (on by default): on, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways +instead of zooming while `zoomWithMouseWheel` is off; off, Cmd/Ctrl-wheel zooms about the pointer. Alt + Cmd/Ctrl-wheel +and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer. Under either +wheel preference, Cmd/Ctrl zooms about the pointer for the rest of a wheel turn once the turn has a trackpad event, +point deltas from an unnamed source in the desktop app, or line deltas that are not whole notches. With `zoomWithMouseWheel` off, once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. The control channel's `ui.wheel` with `cmd: true` turns the wheel with Cmd/Ctrl held. @@ -4009,7 +4241,21 @@ every document they read except a native file and the native document that an SV `view.rotate {angle}` (desktop app) turns the view to `angle` degrees about the center of the canvas; a positive angle turns the art clockwise on screen. View › Rotate View and the status bar's angle menu run it. It returns `{angle}`, the -angle it set, normalized to (-180, 180], and `view.rotateReset` turns the view back to 0. +angle it set, normalized to (-180, 180], and `view.rotateReset` turns the view back to 0, returning `null` on success. + +Select the Rotate View Tool with `select_tool` and the tool id `rotateView`. Its `pointer_gesture` +drags turn the canvas about its center; Shift snaps to 15°. Document coordinates for a rotation +gesture use the view at the initial down event, including when the gesture spans several calls. +The control channel rejects malformed rotation packets without changing the angle and cancels +the current press. Start a new down event after an error. +Reset Rotate View is the command `view.rotateReset`: + +```json +{"name":"select_tool","arguments":{"tool":"rotateView"}} +{"name":"pointer_gesture","arguments":{"events":[{"kind":"down","x":300,"y":150},{"kind":"drag","x":200,"y":250},{"kind":"up","x":200,"y":250}]}} +{"name":"command_run","arguments":{"id":"view.rotateReset","params":{}}} +``` + `view.rotateToSelection` (desktop app, View › Rotate View to Selection) turns the view about the center of the canvas to the angle the selected objects share (`selectionRotation` in `document.inspect`, 0 when their angles differ), so their bounding box is square to the window. It returns `{angle}`, and with nothing selected it returns "nothing selected". @@ -5126,7 +5372,12 @@ fallback font…), each note once; the export still writes or returns every file Batch exports (#1935): - **What:** `layers: [id…]` (each layer's art alone) or `selection: "one" | "each"` instead of artboards - (`assets`, `fullDocument` as before). + (`assets`, `fullDocument` as before). A selected object, a layer's object or an asset's object stays in the layers + and groups that hold it, so their clipping paths, opacity masks, effects, opacity and blend modes apply to it as on + the canvas, and the file is cropped to the bounds the renderer measures for that art (a clip group by its clip); an + object of a blend, envelope, repeat or intertwine is drawn on its own. Those layers are drawn even when they are + hidden, template or non-printing layers, and a PSD of the file names its layers after them. + `document.exportSelection` and the pictures of `css.export {rasterize: true}` draw the selected objects the same way. - **Names:** `name` is a pattern for every file: `<filename>` (the document's file name without its extension, or its title before it is saved; the Full Document file and the `.zip` use the same name), `<name>` (the artboard, asset, layer or object), `<index>`, `####` (a counter zero-padded to the run of `#`, from `counterStart`; `counterPer: "item"` @@ -5715,6 +5966,9 @@ undo step. Object › Transform › Scale, the Scale tool and the Transform pane `text.reshapePath {id, anchors: [[subpath, anchor]…], dx, dy}` does the same for the path of type on a path (Direct Selection dragging one of its anchors): the start and end brackets keep their fractions of the path and the text reflows along it. +`text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?}` moves a direction handle of one +of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in one +undo step. ```json {"name":"run_command","arguments":{"command":"text.reshapeArea","params":{"id":42,"anchors":[[0,2]],"dx":40,"dy":60}}} @@ -5928,6 +6182,11 @@ preferences, one word per line; without preferences (`VECTORCRAFT_NO_PREFS`, the closes. `text.spelling.ignoreAll {word}` is Ignore All: the active document's checks skip the word, in any case, while the document is open. It is not saved and not an undo step. +In the app, Edit › Edit Custom Dictionary… (`text.spelling.dictionary` with no params, from the menus) opens a dialog of +the words, with an Entry field and Add, Delete and Change; Done runs `text.spelling.editDictionary {remove, add}` for +the words that differ, which deletes and adds them and saves once, all or none (a save that fails keeps none of them), +and Cancel changes nothing. + ```json {"name":"run_command","arguments":{"command":"text.spelling.addWord","params":{"word":"VectorCraft"}}} {"name":"run_command","arguments":{"command":"text.spelling.ignoreAll","params":{"word":"Zqvwkx"}}} @@ -5936,6 +6195,10 @@ any case, while the document is open. It is not saved and not an undo step. In the app, Edit › Spelling › Auto Spell Check (the UI command `edit.autoSpellCheck`, which returns whether it is now on) underlines on the canvas the words `text.spelling.check` lists, in the visible type without effects, and keeps the lines up to date as the type, the custom dictionary and the Ignore All words change. +A right-click on an underlined word puts at the top of the canvas context menu the words `text.spelling.suggest` gives +for it (each a `text.editRange {id, start, end, insert}` item labelled with its word), or No Suggestions, then Ignore +All (`text.spelling.ignoreAll {word}`) and Add to Dictionary (`text.spelling.addWord {word}`); the context menu's +entries list them with their params. A right-click on type also has Spelling › Auto Spell Check (`edit.autoSpellCheck`). ## Justification options @@ -6724,7 +6987,13 @@ fit makes `plugin.run` return a memory-budget error naming the object and its si memory-budget error `the selection is too large to hand over`, and more than 100,000 of these objects make it return an object-budget error. Its output returns each of them as `{"id": …}` or exactly as given, otherwise `plugin.run` returns an error naming the object and the -field, and the document and undo history are unchanged. A live-effect plug-in is an effect with +field, and the document and undo history are unchanged. A filter at plug-in API level 2 whose manifest lists the +`commands` permission and a `commandAllowlist` (both in its `plugin.list` entry) runs the commands that list names +while it runs, through `vc_call`: the calls and its output are one undo step, and a run that fails or makes a call that +fails leaves the documents, selections and history as they were. Without `doc.read` every call fails. A command that +reads or writes files, uses the clipboard, changes preferences or the view, runs a script, an action or a plug-in, +switches documents or undoes is never called; `plugin.install` refuses a manifest that lists one, and `plugin.inspect` lists such ids as +`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A live-effect plug-in is an effect with id `plugin.<id>`: `effect.apply`, `effect.setParams` and `effect.expandAppearance` work as for built-in effects, and `effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api` and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them @@ -7642,7 +7911,9 @@ Tools: `bezier` or `arc`; E cycles it. Shift steps the length by the keyboard increment. - **Measure & Inspect tool** (`measureInspect`): a drag measures distance, angle and offsets, as the Measure tool does (`tool.options` reports the last one); hovering a path reads it, as `addon.pathtools.inspect` does. Nothing goes into - the document. + the document. With Snap to Glyph, Smart Guides and Alignment Guides on, and Snap to Grid and Snap to Pixel off, both ends + of either tool's drag land within the snapping tolerance on the guides of live type, except Anchor Point, and the guide + shows during the drag. - **Parametric Shape Tool** (`parametricShape`): draws shapes that stay editable as numbers. A drag from the centre runs `addon.pathtools.shape.create`: the drag's length is the shape's size (height 2 × the distance, width in the last shape's proportions), its direction the rotation (Shift: 45° steps). While dragging, ↑/↓ change the kind's count or diff --git a/docs/plugins.md b/docs/plugins.md index 890183c7fb..026dcc0d9a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -27,11 +27,11 @@ This page is the contract for plug-in authors and the reference for the host (`c | Command | Params | What it does | |---|---|---| -| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, size, source, api, paintOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `cacheBytes` is the size of its [cache](#settings-and-cache)) | +| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, size, source, api, paintOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `cacheBytes` is the size of its [cache](#settings-and-cache)) | | `plugin.info` | `{"id"}` | One plug-in: the `plugin.list` entry plus `manifest`, `defaults` and `lastError` (a live effect's last failure). | | `plugin.run` | `{"id", "params"?: {…}, "ids"?: [...]}` (plug-in params may also be top-level keys) | Runs an object filter on the selection (or `ids`; an `ids` that is not a list of object ids is an error). One undo step; the result is selected, except the objects it locked or made guides. | -| `plugin.install` | `{"path": "/x/y.wasm"}` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. | -| `plugin.inspect` | as `plugin.install`: `{"path"}` or `{"dataBase64", "name"?}` | Validates a module without installing it; returns the `plugin.list` entry it would have, plus `needsApproval` (true when installing it needs a person's approval) and `needsReplace` (true when `plugin.install` needs `replace: true`). | +| `plugin.install` | `{"path": "/x/y.wasm"}` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. A module whose `commandAllowlist` lists a command no plug-in may call is refused; ids no command has are listed as `unknownCommands` ([command calls](#command-calls)). | +| `plugin.inspect` | as `plugin.install`: `{"path"}` or `{"dataBase64", "name"?}` | Validates a module without installing it; returns the `plugin.list` entry it would have, plus `needsApproval` (true when installing it needs a person's approval), `needsReplace` (true when `plugin.install` needs `replace: true`), and the `commandAllowlist` ids no command has (`unknownCommands`) and those no plug-in may call (`refusedCommands`). | | `plugin.remove` | `{"id"}` | Uninstalls, and deletes it from the `Plug-ins` folder with its [settings and cache](#settings-and-cache). | | `plugin.clearCache` | `{"id"?}` | Deletes every entry in the [cache](#settings-and-cache) of plug-in `id`, or of every installed plug-in; settings stay. Returns `{"cleared": [id], "bytesFreed"}`. | | `plugin.reload` | `{"path"?: "folder"}` (default: the preference folder) | Installs every `*.wasm` in a folder; a bad module is reported and skipped, and so are a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). | @@ -178,6 +178,7 @@ capability model proposed for PhotoCraft plug-ins | `progress` | all | Show its progress, see Cancel and write log lines through the [host imports](#host-imports-api-level-2). Needs `api` 2. | | `settings` | all | Keep settings of its own between runs and sessions ([settings and cache](#settings-and-cache)). Needs `api` 2. | | `cache` | all | Keep a cache of its own, which the user can clear ([settings and cache](#settings-and-cache)). Needs `api` 2. | +| `commands` | filter | Run the commands its `commandAllowlist` lists on the document ([command calls](#command-calls)). Needs `api` 2. | - A manifest without `permissions` gets the ones its kind implies, as plug-ins did before the key existed: a filter `doc.read`, `doc.write` and `state`; an effect `doc.read` and `effect.render`, and also `doc.write` and `state` @@ -186,9 +187,10 @@ capability model proposed for PhotoCraft plug-ins these, and also installs without a prompt. - An effect, an exporter or an importer that lists permissions lists all of its implied ones (`doc.read` and `effect.render`; `doc.read` and `export.write`; `import.read`). An effect with commands may add `doc.write` and - `state`, which only its commands use. A filter may list any of its three. + `state`, which only its commands use. A filter may list any of its three, and `commands` with a `commandAllowlist`. Any kind may add `progress`, `settings` and `cache`, which no kind implies. An unknown name, a name listed twice, a - name that doesn't apply to the kind, more than 16 names, `progress`, `settings` or `cache` with an `api` below 2, or + name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache` or `commands` with an `api` + below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is installed, and the error names it. - **Installing asks first.** Install Plug-in… and File › Open show the plug-in's name, id, version, the SHA-256 of @@ -308,7 +310,8 @@ module's memory. A plug-in whose manifest gives `"api": 2` and lists the [permission](#permissions) an import needs may import these functions from module `env` (the module a Rust or C toolchain gives `extern` functions by default). `vc_abi_version` still returns `1`. `vc_progress`, `vc_cancelled` and `vc_log` need `progress`; the `vc_settings_*` imports need -`settings` and the `vc_cache_*` imports need `cache` ([settings and cache](#settings-and-cache)). +`settings` and the `vc_cache_*` imports need `cache` ([settings and cache](#settings-and-cache)); `vc_call` and +`vc_call_result` need `commands` ([command calls](#command-calls)). | Import | Signature | Meaning | |---|---|---| @@ -389,6 +392,51 @@ A live effect runs while the art draws, so keep the entries it uses small. `plugin.info` give the cache's size as `cacheBytes`. - Without a `Plug-ins` folder (the web build, and embedders that attach none) the storage calls return `-5`. +### Command calls + +A filter whose manifest lists the `commands` permission and names commands in `commandAllowlist` runs those commands +on the document while it runs (#2186). It names each command by its id, as `command_list` lists it, and passes its +arguments as a JSON object, the params the command takes from any request: + +| Import | Signature | Meaning | +|---|---|---| +| `vc_call` | `(id, id_len, args, args_len) -> i32` | Runs the command whose UTF-8 id is at `id` with the JSON object at `args` (`args_len` 0 means `{}`). Returns `0` when it ran, else a negative code. | +| `vc_call_result` | `(out, out_cap) -> i32` | The JSON result of the last call that ran: its length in bytes. When it fits in the `out_cap` bytes at `out`, its bytes are copied there; otherwise nothing is copied. `-10` when no call has a result, `-1` when the buffer doesn't lie inside the module's memory. | + +`vc_call` returns `-1` when the id or the arguments don't lie inside the module's memory, `-2` when they are not UTF-8, +`-3` when the arguments are not a JSON object, `-4` when `commandAllowlist` doesn't list the id, `-5` when no command +has the id, `-6` when a plug-in may not call the command, `-7` when the command can't run now (nothing is selected), +`-8` when the command ran and failed, `-9` when a limit below is passed, and `-11` when nothing can be called (from +the module's start function, in a run that isn't a filter's run on a document, or after a call in the run failed). + +- Every code also fails the run, whatever the plug-in does next, and the error names the call and why it failed. The run's calls and its output are one undo step, named after the plug-in or its command. A run that fails, + traps, runs out of budget or is canceled leaves every document, its selection and its history as they were. +- Each call runs on the document the run is for, with its params checked as any request's are, and sees what the calls + before it changed: a `select.all` followed by `object.move` moves everything. The filter's own input is the one it + was given when the run started; an edit still in progress (typing, or a shape being drawn) is kept as its own undo + step before that input is made. +- A plug-in never calls a command that reads or writes a file or folder, uses the clipboard, changes preferences or + the view, runs a script, an action or a plug-in (a `plugin.*` command, or arguments naming one, such as an + `effect.apply` of `plugin.<id>`), opens, closes or switches documents, or undoes or redoes, whatever its manifest + lists. The same goes for a command that changes a tool's options, keeps a drag's state or adds font names for the + whole app, and for a command VectorCraft adds later until it has been checked for plug-in calls. Installing a + manifest that lists such a command is refused, and the error names it; `plugin.inspect` lists them as + `refusedCommands`. +- A call whose arguments hold a file or folder key (`path`, `paths`, `file`, `files`, `folder`, `folders`, `dir`, + `directory`, `destinationFolder`, `sourceFolder` or `url`) at any depth, such as an effect's `textureImage.path`, + returns `-6`; only a key that names part of the document in that command, as its own param, is let through. A + command a plug-in calls can't read or write any file or folder. +- An id in `commandAllowlist` that no command has installs, so a plug-in can list a command a later version adds; + `plugin.install` and `plugin.inspect` list such ids as `unknownCommands`, and calling one returns `-5` (`-6` without + `doc.read`). +- Without `doc.read`, every call of a listed id fails with `-6`, since a command's result describes the document. + Without `doc.write`, a call that changes the document fails with `-6`. +- These limits are VectorCraft's own values: at most 1,000 calls a run, 8 MiB of arguments or result a call and 64 MiB + of arguments and results a run. Each call costs 10,000 instructions of the run's budget, plus one for every 64 bytes + of its arguments and its result, and the run checks Cancel and its time budget before and after each call. +- A filter that calls commands runs on the app's main thread, so it can't ask for a heavy budget: a manifest with + `commandAllowlist` and `budget: "heavy"` is refused. + ### Manifest ```json @@ -437,6 +485,10 @@ A live effect runs while the art draws, so keep the entries it uses small. `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; menus show it with control and bidirectional characters escaped. `params` are declared as the plug-in's own `params` are. A malformed entry is refused when the module is installed, and the error names the command by its id (or its place, `[0]`). +- `commandAllowlist` (filters at `api` 2 with the usual budget, and only with the `commands` permission, which needs + it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist": + ["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with + no empty part between dots. A malformed list is refused when the module is installed, and the error names the id. - `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or `preview`. The host validates the user's values before calling: missing values take the default, numbers are clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults diff --git a/docs/revolve.md b/docs/revolve.md index 2ea788f905..18be779d23 100644 --- a/docs/revolve.md +++ b/docs/revolve.md @@ -2,7 +2,15 @@ This initial implementation follows the scope agreed in [issue #605](https://github.com/storytold/vectorcraft/issues/605#issuecomment-6070543567). -Draw an open profile with the Pen tool, select it, then choose **Effect > 3D and Materials > Revolve**. +Select a path, compound path, type, clipping group, blend, symbol instance, or a group or layer of them, then choose **Effect > 3D and Materials > Revolve**. +On a group or layer, every visible member sweeps about one axis, as [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html) +describes for a group. The following rules are VectorCraft's own: type stays editable and sweeps as its glyph outlines, +the shared axis lies on the chosen edge of the members' bounds together, and each member keeps its own paint. +The faces of all members draw in one back-to-front order. The opacity and blending mode of a member, or of a group +inside the group, apply once to all its faces. Where a face of another member lies between its faces in that order +and overlaps them on the page, its faces are split there, and the opacity and blending mode apply once to each part. +Two faces overlap when the convex hulls of their outlines come within the 0.75 pt seam stroke of each other. After +4,194,304 overlap tests on one group, each further face of such a member is drawn as a part of its own. The profile's horizontal distance from a vertical axis is its radius. **Axis side** chooses the left or right edge of the profile's bounds; **Offset** moves the axis outward. For a cylinder made from a vertical line, give it a nonzero offset. A vertical line at zero offset lies on the axis and has no surface. @@ -88,13 +96,13 @@ with the standard command. - Lighting offers Standard, Diffuse, Top Left and Right, using the [shared original rigs](three-d.md#presets). Other effective settings show Custom; changing the view does not change the recognized lighting preset. -- Paths and compound paths only. Type, images and groups must be converted to paths first. +- Paths, compound paths, type, clipping groups, blends, symbol instances, and groups or layers of them. A clipping group, a blend or a symbol instance sweeps the art it shows about one axis, as described in [three-d.md](three-d.md#clipping-groups-blends-and-symbol-instances). Images must be traced first with Object › Image Trace › Make, and other live objects expanded. - Open profiles have circular end caps by default; turning Cap off keeps them open. Partial-sweep angular cut sides remain open. Closed profile boundaries are swept as provided. - One Revolve per source object. Edit its options rather than applying another. - Object-level Revolve uses the top visible fill, falling back to a stroke. Per-item Revolve uses that item's paint. - Smooth diffuse shading, one to ten directional lights, no textures, cast shadows or physical materials. Smooth shading interpolates lighting in projected triangles; it does not smooth the silhouette or add specular highlights. - Faces use back-to-front depth sorting. Caps facing the camera cover their rim seams; caps facing away sit behind the body. Intersecting profiles can have incorrect visibility. -- Curves use sixteen samples per segment; profiles are limited to 1,024 samples and surfaces to 32,768 faces. Smooth shaded side quads become two triangles and share that same limit. A continuous cap retains its original radial mesh cost within this limit. Projected ring curves have a 0.001-point fitting tolerance and a shared 32,768-curve limit. +- Curves use sixteen samples per segment, and as few as four when a surface would otherwise pass its limits. Surfaces are limited to 16,384 profile points and 163,840 faces, the members of a group together. A straight segment takes one point, a curve takes at least four, and each contour takes one. Smooth shaded side quads become two triangles and share the face limit. A continuous cap retains its original radial mesh cost within this limit. Projected ring curves have a 0.001-point fitting tolerance and a shared 32,768-curve limit. - Axis, bounds and ordinary selection handles continue to refer to the editable 2D source profile. - Extrude & Bevel, Inflate and Rotate are described in [three-d.md](three-d.md). Materials remain unimplemented. diff --git a/docs/roadmap.md b/docs/roadmap.md index d231330738..d79efc9f17 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,12 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> +> Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). +> +> **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. +> +> Numeric spinner update (2026-11-10): held mouse arrows repeat past the click timeout; scores and estimates unchanged (#6307). ## Feature submission evidence @@ -8,6 +14,8 @@ Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. +Icon-strip flyouts resize from the canvas-side edge and bottom, keeping the icon-column edge anchored (#5713). Independent group heights and flyout widths persist in workspaces; saved heights override content fitting while untouched heights still fit content. Shared panel button bars and the Glyphs font row stay at the bottom after enlargement; the Artboards list grows into the extra space. Regressions: `panel_docking::tests::glyphs_and_artboards_flyouts_keep_user_sizes` and `expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists`. Scores and estimates unchanged. + **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. @@ -48,6 +56,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. | | 2026-11-07 | minor | Indian-language hyphenation (#4947): eleven MIT-licensed pattern sets, with grapheme and shaping-cluster protection in both composers and existing paragraph limits. Assamese and Sanskrit are selectable; Sanskrit automatic patterns remain pending an allowlisted source. Scores and estimates unchanged. | | 2026-11-05 | minor | Effect dialogs: a colour swatch beside a hex colour field follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills the field (#5365); scores and estimates unchanged. | +| 2026-11-06 | minor | Icon-strip flyouts resize on their free edges and retain sizes with workspaces (#5713); saved heights beat auto-fit; panel footers stay at the bottom after enlargement. Scores and estimates unchanged. | | 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | | 2026-11-05 | minor | Pencil and Paintbrush: a new stroke with Keep selected off leaves nothing selected, the earlier selection included, while Keep selected on selects only the new path (#5752); scores and estimates unchanged. | | 2026-11-05 | minor | Layers panel: a layer whose Layer Options › Print is off shows its name italic, as the reference application shows non-printing layers, and keeps it while the row is dragged (#5739); scores and estimates unchanged. | @@ -113,7 +122,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l 2. **`.ai` files from real users** (G9): layer structure (#951). 10–20 h. 3. **Launch and stability** (G10): the Windows and Linux start-up reports. 20–35 h. 4. **Core-tool bugs** (G11): SVG units reverting to points (#864) and a Transform effect in a fill's or stroke's own effects (#885). Shape Builder regions (#937), Asset Export ghost borders (#983 / #1037) and the stalling bezier drag preview (#834) are fixed. 8–15 h. -5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h. +5. **Then:** advanced type (G4) and the Illustrator 2026 additions (G13), then 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2). ## Next @@ -133,27 +142,27 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts | 3–6 (existing scope; Affinity export unestimated) | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check (#4936; the dialogs and the right-click Spelling menu remain); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check (#4936; the dialogs and the right-click Spelling menu remain); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check (#4936; the dialogs and the right-click Spelling menu remain); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, three generated libraries (Basic Shapes, UI Frames, Map Markers), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, three generated libraries (Basic Shapes, UI Frames, Map Markers), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; broader scripting and batch work remains | 18–27 | +| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369) | 6–10 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files; the script document model and console and batch work remain | 18–27 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 | -| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged | 18–28 | +| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -190,14 +199,23 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M7: the Edit Custom Dictionary dialog (#4936); the Check Spelling dialog remains; scores and estimates unchanged. | +| 2026-11-10 | minor | M10/G5: Game HUD built-in graphic style library; estimates unchanged | +| 2026-11-10 | minor | M10/G5: Map Markers built-in symbol library (Pin, Flag, Crosshair, Checkpoint); estimates unchanged | +| 2026-11-10 | minor | M7: Spelling › Auto Spell Check in the context menu of type (#4936); the dialogs remain; scores and estimates unchanged. | +| 2026-11-10 | minor | M7: right-click suggestions, Ignore All and Add to Dictionary on a word Auto Spell Check underlined (#4936); the dialogs remain; scores and estimates unchanged. | +| 2026-11-10 | minor | Current focus: the Effect Gallery's filter thumbnails and in-dialog preview are in (G2). Scores and estimates of other areas unchanged. | | 2026-11-09 | minor | M7: Auto Spell Check (#4936); the dialogs and the right-click Spelling menu remain; scores and estimates unchanged. | +| 2026-11-09 | minor | PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged. Synthetic evidence: `crates/pdf/src/tests/actual_text.rs`. | | 2026-11-09 | minor | PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged. Decoded stream and placement regressions; reader ActualText (#6165), styled clusters and external viewer validation remain separate. | | 2026-11-09 | minor | Interim macOS canvas cursor delivery (#2292): existing artwork in aligned 1×/2× AppKit representations, visible system fallback and host-owned restoration. Headless routing, bitmap and ownership coverage; native timing, menus, focus/handback, mixed displays, Spotlight and full-screen Spaces remain unverified. Scores and estimates unchanged. | | 2026-11-09 | minor | M7: the custom dictionary commands and Ignore All (#4936); the dialogs and Auto Spell Check remain; scores and estimates unchanged. | | 2026-11-09 | minor | M4/G9: EPS import: the fonts an EPS carries draw their glyphs instead of being set as type in an installed font: composite (Type 0) fonts with the 8/8 mapping, plain Type 42 fonts (characters from their glyph names or character map, widths from the font), CID-keyed fonts over CMaps (Type 0 and Type 2 CIDFonts, CIDFonts in a FontSet's Compact Font Format data, base-font CMaps, named CIDFonts over predefined Unicode CMaps set as type) and embedded Type 1 fonts; the show operators' spacing along the baseline is kept as tracking, `kshow` included. Each step is charged to the interpreter's budgets. Hand-written test files only (no corpus file uses these fonts); scores and estimates unchanged. | | 2026-11-08 | minor | M7: spell check engine, `text.spelling.check` and `text.spelling.suggest` on craft-proof (#4936); the dialog, Auto Spell Check and the custom dictionary remain; scores and estimates unchanged. | | 2026-11-08 | minor | Floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part); tab groups remain intact. Scores and estimates unchanged. | +| 2026-11-10 | minor | Held numeric spinner arrows keep stepping past the click timeout and stop on release (#6307). Scores and estimates unchanged. | | 2026-11-09 | minor | Numeric fields step on wheel hover without taking focus; keyboard focus and existing rounding rules remain (#5949). Scores and estimates unchanged. | +| 2026-11-10 | minor | Vector Halftone Preview leaves the dots unobscured and keeps the selection box (#6369). Scores and estimates unchanged. | | 2026-11-07 | minor | M2: with the Pen or Curvature tool, Edit › Copy and Cut take the anchors and segments a Cmd/Ctrl-lent Direct Selection picked, not the whole path (#6123); estimates unchanged | | 2026-11-07 | minor | Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged. | | 2026-11-06 | minor | M2: a shape just drawn moves by its centre point (Show Center) and turns from the rotate zone just outside a bounding-box corner with its tool still active, as the Selection tool's gestures do (#5477); estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d7e497df8a..68a416efe6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,14 @@ # Parity with Adobe Illustrator +<<<<<<< HEAD > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (Pencil: Edit Selected Paths follows strokes lifted away, carves, loops, closes and redraws compound paths (#3793), scores unchanged; previously: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +======= +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> +> Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). +> +> **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. +>>>>>>> upstream/main ## Feature submission evidence @@ -10,6 +18,8 @@ Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. +Icon-strip flyouts resize from the canvas-side edge and bottom, keeping the icon-column edge anchored (#5713). Independent group heights and flyout widths persist in workspaces; saved heights override content fitting while untouched heights still fit content. Shared panel button bars stay at the bottom after enlargement. Regressions: `panel_docking::tests::glyphs_and_artboards_flyouts_keep_user_sizes` and `expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists`. Scores and estimates unchanged. + **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. @@ -41,6 +51,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-09 | minor | Stroke panel: Line Arrow, a 41st generated arrowhead: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, a sharp tip and square-cut ends, twice as wide as the other heads; bounds and clicks follow each head's own reach (`stroke.set` `LineArrow`, #5421); scores and estimates unchanged | +| 2026-11-09 | minor | Canvas: a 3D effect (Extrude & Bevel, Inflate, Rotate, Revolve) changed on type or a group draws again where its art was and is, measured by that art; the canvas measures through its renderer and draws the part with the art it made to measure it. Exports and Object › Rasterize take the solid of 3D type. Fit to Artwork Bounds and per-artboard SVG export measure every artboard through one renderer, building each solid once. A 3D effect on a fill or stroke that builds nothing (Revolve after Roughen) no longer overflows the stack on the canvas, in Object › Rasterize and in raster and EPS exports: the fill or stroke draws as without it. Tests `tests::changed::a_3d_effect_changed_on_type_or_a_group_changes_where_its_solid_was`, `fx::tests::a_renderer_measures_the_art_on_each_artboard_building_each_solid_once`, `canvas::tests::an_edit_to_a_3d_effect_redraws_with_the_art_measured`, `fx::tests::a_3d_effect_that_builds_nothing_draws_the_item_as_without_it`. Scores and estimates unchanged. | | 2026-11-07 | minor | File formats and Type core (#6147): `.ai`/EPS type keeps its paragraphs' tab stops (positions and alignments; leaders aren't read; at most 1,024 a paragraph and 2^20 a story), and right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops; centred and justified lines are aligned as a whole as before; evidence added. Scores and estimates unchanged. | | 2026-11-07 | minor | File formats and Type core (#6137): `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them, and a line a soft return ends is justified; evidence added. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores and estimates unchanged. | | 2026-11-08 | minor | Style panels: a double-click on a user character style's row opens its Character Style Options (`ui.charStyleOptions`), and on a paragraph style's row its Paragraph Style Options (rename); the Character Style Options dialog keeps a fixed width and scrolls its sections in a shorter window, so OK and Cancel stay on screen. Tests `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options` and `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. Scores and estimates unchanged. | @@ -57,6 +69,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-06 | minor | Stroke gradients: an arrowhead whose tip sits on the end of a long straight leg is painted by the gradient to the corners of its base. The slices that reach across a head now run to the end of its reach instead of narrowing towards the next corner (#5964). Test: `stroke::tests_gradient::slices_cover_an_arrowhead_on_a_long_straight_leg`. Scores and estimates unchanged. | | 2026-11-06 | minor | Width profiles: the width between two width points follows a smooth curve instead of a straight line, so a stroke no longer kinks at each width point (#5714). Each side is a monotone cubic through its points: flat at a widest or narrowest point, never past either point of a span; stacked points still step. Straight runs are sampled between width points to the drawing tolerance. Scores and estimates unchanged. | | 2026-11-05 | minor | A nearby hit on a plain long stroke or outline avoids assembling its whole path. A hit near the middle of a 200,000-anchor path took about 11–13 ms before and 1.0–1.4 ms after in paired runs on a busy Windows machine; a miss inside the path's box fell from 18.7 ms to 1.6 ms, while a distant miss was unchanged. Other stroke styles and fill hits keep their existing checks. Scores and estimates unchanged; idle performance budgets remain unverified. | +| 2026-11-06 | minor | Icon-strip flyouts resize on their free edges and retain sizes with workspaces (#5713); saved heights beat auto-fit; panel footers stay at the bottom after enlargement. Scores and estimates unchanged. | | 2026-11-05 | minor | Translating a type object without changing its text or formatting reuses glyph geometry and expanded character-stroke outlines between frames. The text appears at its new position with unchanged pixels. Scaling the type, editing its content or formatting, or changing installed fonts rebuilds the geometry; scores and estimates unchanged. | | 2026-11-05 | minor | Moving a large selection reuses the object locations found during command validation. A 20,000-object nudge took 58.07 ms before and 51.26 ms after in paired median runs; object positions, selection, and undo behavior stay the same. Scores and estimates unchanged. | | 2026-11-05 | minor | Canvas: an image drawn larger than 1,024 pixels at the size it shows, with its colours made again (separated into ink planes, colorized or shown through Separations Preview), has them made only for the 1,024-pixel tiles in view, each kept for later frames (#4155). Zooming in to 50%, 100% and 200% on the file of #4155 went from 8.6–9.0 s to 0.78 s, 0.05 s and 0.05 s (measured, M3 Pro, one run each), with the same pixels. Scores and estimates unchanged. | @@ -208,34 +221,34 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors | 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (five generated libraries including Game Trails, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Revolve, Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check done, #4936; the dialogs and the right-click Spelling menu remain), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes and UI Frames with default 9-slice are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check done, #4936; the dialogs and the right-click Spelling menu remain), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes and UI Frames with default 9-slice are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility); materials, shadows, ray tracing, the rest of 3D Classic (Revolve, Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check done, #4936; the dialogs and the right-click Spelling menu remain), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check done, #4936; the dialogs and the right-click Spelling menu remain), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Raster effects (Effect Gallery) | 4 | 52% | the Effect Gallery's filter thumbnails and in-dialog preview area ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)) | 1–2 | estimated (raised from 49%: the Effect Gallery shipped, #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `dialogs::effect_gallery::tests::stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; depth estimated | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes and UI Frames with default 9-slice are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); import ActualText (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); import ActualText (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); import ActualText (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -387,7 +400,7 @@ what keeps it from beta, not from alpha. | Dimension | % | One agent (h) | Kind | Doc | |---|---:|---:|---|---| | Features (depth, weighted) | 75% | 220–360 | estimated | this file | -| UI/UX fidelity (look ~80%, interaction ~45%) | 55% | 70–110 | estimated | [ui-parity.md](ui-parity.md); Tools sits inside left-side panels beside the canvas (layout choice; no rescoring) | +| UI/UX fidelity (look ~80%, interaction ~45%) | 55% | 70–110 | estimated | [ui-parity.md](ui-parity.md); Tools sits inside left-side panels beside the canvas (layout choice; no rescoring); held spinner arrows keep stepping (#6307); Vector Halftone Preview keeps the selection box without the dot marks (#6369) | | File formats | 75% | 15–30 | estimated | [file-format-parity.md](file-format-parity.md) | | Hardware (GPU, pen, touch, displays) | 35% | 25–45 | estimated | [hardware-parity.md](hardware-parity.md) | | Localization (the 12 key languages, equally weighted) | 74% | 50–85 | measured from catalogs | [localization-parity.md](localization-parity.md) | @@ -477,16 +490,16 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (four generated in code are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (five generated in code including Game Trails are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art and more complete visibility remain | 25–45 | -| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, spell check (its engine, custom dictionary commands and Auto Spell Check are done, #4936: the Check Spelling and Edit Custom Dictionary dialogs and the right-click Spelling menu remain), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | +| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize) and Texturizer's Load Texture (since done, see the area table above, as is the Effect Gallery, #2883); Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 8–14 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art and more complete visibility remain | 25–45 | -| Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (its engine, custom dictionary commands and Auto Spell Check are done, #4936: the Check Spelling and Edit Custom Dictionary dialogs and the right-click Spelling menu remain), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | +| Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes and UI Frames with default 9-slice are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | @@ -529,7 +542,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~32% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have two (Basic Shapes, UI Frames with default 9-slice) and brush libraries four (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~38% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have three (Basic Shapes, UI Frames with default 9-slice, Map Markers), graphic style libraries seven (including Game HUD) and brush libraries five (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, Game Trails) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -541,11 +554,15 @@ since 2026-10-01. ## Evidence: what ships today, by area +- **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. + + - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. - Window › 3D and Materials panel: `crates/ui-egui/src/panels/three_d.rs` applies a 3D effect by object type (Plane, Extrude, Revolve, Inflate), changes an applied one in place (`effect.setParams` `threeDType`) and edits it with the options dialog's Object, Rotation and Lighting controls, one undo step per change; `crates/engine/src/cmd/effectcmd/three_d_type_tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. No Materials tab. +- 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. - **Status-bar pointer readout (2026-10-18):** uses the same effective ruler origin as the position fields, then formats the relative X/Y in General units. The absolute pointer position, document, selection, Undo/Redo and saved state are preserved. Three `chrome::tests::status_coordinates_*` painted-text regressions cover zero/positive/negative origins, unit conversion, global/artboard mode, active artboard, reset and missing pointer/document. Original headless status-bar captures were reviewed before and after the change. Scores and hours are unchanged. @@ -575,6 +592,7 @@ since 2026-10-01. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. +- **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Global Edit: Shift-click leaves a match out:** while Global Edit is on, a Shift-click with the Selection tool on a highlighted match, or on an object inside a matched group, leaves that match out (`select.globalEditExclude`): it is no longer highlighted and later edits leave it as it is; the object the edit started from stays, and Global Edit ends when fewer than two matches are left ([Update assets quickly with Global Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)). Regression tests: `a_shift_click_*`, `an_object_left_out_*`, `a_group_left_out_*` and `leaving_out_all_but_one_*` in `crates/engine/src/tests/globaledit.rs`. - **Global Edit Options in the Control bar:** while Select › Start Global Edit can run, the Control bar shows a Global Edit Options dropdown that opens the same options as the Properties panel's (Match: Appearance, Size; On Artboards; Include Objects On Canvas; Result(s)); both set the same options. The dropdown is off while Global Edit is on; it sits after Recolor Artwork, ahead of the X/Y/W/H fields ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). Regression test: `the_control_bar_shows_the_global_edit_options` in `crates/ui-egui/src/chrome/tests.rs`. @@ -590,8 +608,12 @@ since 2026-10-01. - **Effects in Export Selection and asset crops:** File › Export Selection, Asset Export, Export for Screens' Assets tab and CSS Properties' rasterized art crop each object to the bounds the renderer measures for what it draws: drop shadows, glows, geometry effects such as Offset Path, a group's own effects and the effects in a symbol's art. A brushed path is cropped to its visual bounds, and a Shaper group is cropped to the art it shows. `assets.list` reports the same crop. Engine tests export a square with each effect, a group with a shadow and an asset with a shadow, and check that the effect is inside the image. Public reference: a [Community Expert answer](https://community.adobe.com/t5/illustrator-discussions/exporting-assets-adds-transparent-borders/m-p/10708713/highlight/true) traces the extra area of exported assets to the raster effects' area (Document Raster Effects Settings › Add Around Object). +- **Clips and masks around exported selections:** File › Export Selection, Export for Screens by selection or by layer, Asset Export and CSS Properties' rasterized art draw each object in the layers and groups that hold it. A clip group's or clipping layer's clip, an opacity mask, and a group's or layer's effects, opacity and blend mode apply as on the canvas. The crop is the bounds the renderer measures for that art, a clip group by its clip. These are VectorCraft's own rules. An object of a blend, envelope, repeat or intertwine is exported on its own, and a text export of the selection holds only the selected type. Engine tests compare the PNG exports with the canvas over the same area, reopen the SVG and PDF exports, and cover nested clip groups, symbol instances, 200 clip groups and assets in hidden or locked groups. + - **Effects in the art's bounds:** Export with Use Artboards off, Fit to Artwork Bounds, and the other exports of the whole art (EPS without artboards, Export for Screens' Full Document, Save for Web (Legacy) with Clip to Artboard off) measure each visible object as the export crops above do. The drop shadows and other effects of groups, layers, type and images are inside the image or the artboard. A Shaper group without effects of its own is measured by the art it shows, and the hidden members of a group with a drop shadow, a glow or another raster effect do not count unless it is a Shaper group or also has a geometry, Pathfinder, Crop Marks or 3D effect or a visible effect on its own fill or stroke. The SVG of an artboard keeps an object whose effects alone reach the artboard. Tests measure a group, type and an image with a drop shadow, export a group and type with Use Artboards off and fit an artboard to them. +- **Raster export backgrounds (#6125):** a raster export draws its background under the finished art, and blend modes read only the art below them, as on the canvas. An Outer Glow in Screen mode on the bare page shows in a PNG on white and in a JPEG. Flatten Transparency puts its white under the finished art the same way. Evidence: `tests::file::a_screen_outer_glow_is_in_raster_exports`, `tests::objectfx::a_screen_outer_glow_on_the_bare_page_shows_on_a_background`, `tests::knockout::page_knockout_and_isolated_blending`, `tests::knockout::no_blend_mode_reads_the_background`, `tests::cmykflatten::every_blend_mode_flattens_to_the_canvas_pixels_in_cmyk`. + - **Selected artboard deletion:** the Artboards panel menu, panel trash button and Properties use the same selected set; selecting all retains artboard 1. Pointer-event tests cover nonadjacent and single selections, the original first-board survivor, ordinary artwork, Undo/Redo and the single-board guard. Public reference: [Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). - **Delete Empty Artboards:** the Artboards panel menu item ([Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html)) runs `artboard.deleteEmpty`: every unlocked artboard with no artwork goes with its guides in one undo step, artboard 1 stays when every artboard is empty and none is locked, and the panel makes an artboard that is left active; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule). Engine tests in `tests/panelcmds.rs` (`delete_empty_artboards_*`) and the panel test `delete_empty_artboards_deletes_the_empty_ones_and_selects_one_left`. The menu item's enabled check measures nothing in a document with one artboard, and Save Gradient Preset's check reads the proxy's paint without measuring the object; both give the same answer as before. An artboard that no path's control points, grown by the farthest its strokes reach, can meet is found empty without measuring the path. With an open path of 200,000 anchors selected, the checks take under 0.01 ms instead of 21.9 ms and 17.2 ms in a release build; with a second, empty artboard, Delete Empty Artboards' check takes 0.85 ms instead of 42.1 ms. Tests `delete_empty_artboards_is_enabled_exactly_when_it_deletes_something`, `delete_empty_artboards_enabled_state_matches_the_command_on_varied_documents`, `empty_artboard_checks_match_the_visual_bounds_on_varied_strokes`, `the_empty_artboard_check_matches_measuring_every_artboard`, `the_save_check_matches_saving_with_and_without_a_gradient`, `the_unmeasured_proxy_paint_is_the_measured_one` and `the_unmeasured_proxy_paint_is_the_measured_one_on_varied_objects`. @@ -643,6 +665,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. +- **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). - **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests/panelcmds.rs`, `tests/brushsym.rs` and `tests/pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies). - **Pattern names and swatch names:** `pattern.options` refuses a new name that another pattern, a swatch or a color group has. It takes a name that only the pattern's own swatches have. The reference page does not say what happens when the new name is taken; the refusal follows VectorCraft's rule that swatches and color groups share one namespace (`Document::swatch_name_taken`), which `swatch.new` and `swatch.edit` also follow. A rename gives the new name only to the pattern's swatches that had the old one; any other swatch with the old name keeps it, and art linked to that swatch stays linked. `object.pattern.make` and `object.pattern.saveCopy` number a color group's name as they number a swatch's. Tests in `tests/pattern.rs` cover each command. Public reference: [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copy). @@ -661,6 +684,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF and JPEG XL, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. - **Architecture:** 19+ crates with enforced layering (`cargo xtask layers`). Every action is a command (~400 engine + ~50 UI). Undo is unlimited via structural sharing. `command.batch` runs several commands as one transaction. +- **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document; saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`. +- **Input schemas in the command listings:** `engine.commands` and the MCP tools `command_list` and `list_commands` give each command with a parameter schema an `inputSchema` next to `schema`: the same schema with the root `type` `"object"`, the form an MCP tool's input schema takes ([MCP schema reference](https://modelcontextprotocol.io/specification/2026-07-28/schema)). A command without a schema lists neither, and `brief` leaves out both schemas with the `params` text. Tests: `schemas::tests::engine_commands_list_an_input_schema_with_an_object_root` and `schemas::tests::an_input_schema_keeps_deprecation` in `vectorcraft-engine`, and `tests::conventions::command_listings_carry_input_schemas` in `vectorcraft-mcp`, which check every listed input schema against the JSON Schema 2020-12 rules. +- **Command API reference:** `engine.apiReference` returns a Markdown reference written from the parameter schemas when it is asked for, and MCP serves the same text as the resource `vectorcraft://commands/reference` (`text/markdown; charset=utf-8`). Each command that has a schema gets a section in registry order with its label, menu path, API levels, what it writes, summary and return, and a table of its parameters (type, range with its ends marked included or not, unit, default, required, levels and description; members of objects as dotted rows). Commands without a schema, plug-in commands included, are left out. Schema text is escaped so it stays plain text in its table cell, the same build always returns the same bytes, and a reference past 1 MiB is an error rather than a cut-short text. The command's own schema raised the API level to 2. This is a VectorCraft documentation feature; no score changes. Tests: `cmd::apiref::tests` and `schemas::tests` in `vectorcraft-engine`, `resources::tests` in `vectorcraft-mcp`. - **Automation:** - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. @@ -699,12 +725,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: a type object holds one text variable. `variable.bind` and Make Text Dynamic refuse a second one and name the text variable the object has; a visibility variable can still share the object, and a document saved with two text variables on one object opens with both. - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. + - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. + - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 16.0, so characters assigned in later Unicode versions are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_16_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. @@ -763,7 +791,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The macOS menu bar is built from the in-window menus (one model, `native_menu`) and laid out as a Mac app's: the VectorCraft menu holds About, Settings ▸ (each Preferences page, General… ⌘K), Language ▸, Appearance ▸ (UI brightness), Services, Hide VectorCraft ⌃⌘H (⌘H stays Hide Edges), Hide Others, Show All and Quit; Window gains Minimize ⌃⌘M, Zoom and Bring All to Front, and Help the system's search field. Its key equivalents go back to egui as key presses, so user shortcuts, focused text fields and the Type tool's input method behave as in the window, and nothing fires twice; enabled, check marks and labels update in place. `--in-window-menus` or `VECTORCRAFT_IN_WINDOW_MENUS=1` keeps the menus in the window; `ui.inspect` reports `nativeMenuBar`. - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes and UI Frames (Panel, Button and Bar with default 9-slice guides), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. + - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes, UI Frames (Panel, Button and Bar with default 9-slice guides) and Map Markers (Pin, Flag, Crosshair and Checkpoint, no default 9-slice), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. - **9-slice scaling** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): a scaled instance of a symbol with Enable Guides for 9-Slice Scaling on stays an instance and keeps the parts of its art outside the guides at their size. New guides sit a quarter of the symbol's width and height in from each edge ([reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section); saved guides keep their values. The rest is VectorCraft's own rule: the corners keep both sizes, the top and bottom edges stretch in width, the left and right edges in height and the center in both; an instance smaller than its two outer cells on an axis shrinks them in proportion and leaves the center empty; the cells are sized along the symbol's axes before the instance's rotation, shear or reflection. A path with solid paint that crosses a guide is cut there and stays one path, its stroke at its weight with Scale Strokes & Effects on or off; type, images, live objects and gradient or pattern paint that cross a guide are drawn in each cell they reach, clipped to it, except those that draw symbol art (a nested instance, type with an inline graphic, a placed document, a brushed stroke, or a pattern whose tile draws one of these), which are placed by the cell their center is in; an object in one cell is placed by that cell and stays as it is. The canvas, bounds, the Eyedropper, Break Link to Symbol and the PDF, EPS, DXF, EMF/WMF and SVG exports place the art the same way; SVG writes such an instance as its placed art instead of a `<use>`, and DXF and WMF, which do not clip, cut every path that crosses a guide and place other such objects by the cell their center is in. Tests: `symbol_nine_slice::tests` in `crates/doc`, `crates/engine/src/tests/symbol_nine_slice.rs`, `a_scaled_nine_slice_instance_keeps_its_corners` (PDF), `a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it` (SVG), `a_scaled_nine_slice_instance_is_sampled_as_it_is_drawn` (Eyedropper). - **Symbol editing mode** ([Edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a double-click on a symbol instance, the Control bar's Edit Symbol button, a double-click on a symbol in the Symbols panel and the panel menu's Edit Symbol (`symbol.edit`) open the symbol's art on a temporary isolated layer, where the instance shows it (from the panel: centered on the active artboard, or in the view in a document without artboards), with the rest of the document dimmed. Each edit there changes every instance at once; the instances keep their own transforms and stay linked (Break Link to Symbol still expands one), and a dynamic symbol's instances keep their appearance changes to the objects the art still has. Escape, the isolation bar's back button, the Control bar's Exit Symbol Editing Mode and a double-click outside the art leave the mode (`symbol.exitEditing`); leaving without an edit adds no undo step. Saving leaves the editing layer out. Tests: `crates/engine/src/tests/symboledit.rs`, `select::tests::a_double_click_on_a_symbol_instance_edits_its_symbol`, `panels::symbols::tests::edit_symbol_from_the_panel_centers_the_art_on_the_active_artboard_or_the_view`. - **Dynamic symbol appearance follows what an object draws** (VectorCraft's own rule): `symbol.instance.setAppearance` refuses a fill or stroke for an object of the art that does not draw it (a guide, blend, envelope, Repeat, Intertwine group, gradient mesh or placed document; a nested symbol instance's stroke, and its fill unless a solid color or none, which stains its art; an image's fill or stroke without a Convert to Shape or Outline Object effect) with an error that names the key and the object, and the call changes nothing. Opacity, blend and `null`, which takes a stored change back, are taken for every object. Tests: `crates/engine/src/tests/dynamic_symbols.rs`. @@ -775,18 +803,19 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol. A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection), or the view commands on empty canvas. + - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, Game Trails) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. + - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. - A right-click over locked objects adds an Unlock submenu to the canvas context menu. The submenu lists up to 20 locked objects under the pointer, topmost first, by the name the Layers panel shows, and choosing one unlocks it (`layer.setProps`). A locked group is listed as one item. Objects on hidden, locked or template layers are not listed. - Native macOS save sheets offer a localised Format menu (#866), built from the request's existing format filters. It selects the suggested filename's format and updates the suffix when changed, including legacy `.drawcraft` names. `apps/vectorcraft/src/mac_save_format.rs` has filename regressions; an actual native SVG save, selection of PDF and cancellation without changing the saved document were verified. - Save / Don't Save / Cancel before closing or quitting with unsaved documents (tabs, Close, Close All, Quit, window close). - Four brightness themes, persistent preferences. - **Snapping quick access (#6164):** Control bar › Snapping includes Snap to Glyph (`view.snapToGlyph`) and Alignment Guides (`prefs.set`, `alignmentGuides`). The headless pointer/accessibility test `the_control_bar_snapping_menu_shares_glyph_and_alignment_settings` covers both commands, independent state, checked states after reopening, and all eight menu rows within a 1200 × 400-point window. Floating-panel parity remains unverified; scores and estimates unchanged. + - **Measure tools and Snap to Glyph:** with Snap to Glyph, Smart Guides and Alignment Guides on, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag land within the snapping tolerance on the guides of live type that the Character panel's options allow, except Anchor Point, and a Shift-drag's end slides along its 45° step to them. The guide shows during the drag. This is VectorCraft's own rule (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`); scores and estimates unchanged. - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default: on, pink behind OpenType substitutions on screen — ligatures, contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set`, #394). About 14 stored options still do nothing yet (the rest of #394: Open Documents As Tabs, Real-time Drawing and Editing, GPU Performance beyond Animated Zoom, hyphenation language, scratch disks, the legacy clipboard, Touch Workspace). - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (on by default: pink behind OpenType substitutions on screen — ligatures, contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set`, #394). About 14 stored options still do nothing yet (the rest of #394: Open Documents As Tabs, Real-time Drawing and Editing, GPU Performance beyond Animated Zoom, hyphenation language, scratch disks, the legacy clipboard, Touch Workspace). - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Three stored options still do nothing yet (the audit below). - - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl-wheel scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. + - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. Under either wheel preference, Cmd/Ctrl with a touchpad zooms about the pointer. - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only (Units › East Asian Type and User Interface › Open Documents As Tabs, stored only on the day of the audit, act now: East Asian Type since 2026-10-31, Open Documents As Tabs as the Window › Arrange bullet says); [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. - Units › East Asian Type (#394, `unitsAsianType`): Points by default; it offers every unit and Q and Ha, a quarter of a millimetre each (0.709 pt: the [Illustrator Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/); `q` and `h` are the field suffixes [InDesign's notation table](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html) lists), and only it lists them: rulers, Document Setup and the other Units preferences keep their ten. The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. The model stays in points; any length field reads `13q`/`13h`. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` (`crates/engine/src/tests/units.rs`). @@ -796,7 +825,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With Real-time Drawing and Editing off, a dragged selection whose outline points and evaluated objects come to more than 100,000 shows its moved bounds instead, as the selection at rest does (#525, #2460; `real_time_drawing_off_draws_the_bounds_of_a_selection_too_big_to_outline`, `real_time_drawing_off_draws_the_bounds_of_a_group_too_big_to_outline`, `real_time_drawing_off_draws_the_bounds_of_a_repeat_with_too_many_objects`). - With Real-time Drawing and Editing off, a move or handle drag of a group, blend, envelope, repeat or intertwine draws the outline of each of its objects instead of one union of them, as VectorCraft's own rule (`real_time_drawing_off_outlines_a_dragged_group_member_by_member`, `real_time_drawing_off_outlines_a_resized_group_member_by_member`, `real_time_drawing_off_outlines_a_dragged_blend_step_by_step`, `real_time_drawing_off_outlines_a_dragged_envelope_object_by_object`). A group with a Pathfinder effect draws the area the effect makes, a gradient mesh draws its mesh lines, and a symbol instance draws its bounds (`real_time_drawing_off_outlines_a_dragged_pathfinder_group_by_its_area`, `real_time_drawing_off_outlines_each_mesh_of_a_dragged_repeat_once`, `real_time_drawing_off_outlines_a_dragged_symbol_instance_by_its_bounds`). - Dialogs move by dragging their heading (the band down from the top edge, as a title bar), stay on screen and keep where they were moved for the session; the form dialogs' choices are dropdowns (Offset Path's Joins, Average's and Shear's and Reflect's axis), and Offset Path lists Offset, Joins, Miter Limit and previews (#423). - - Dialogs open with their first field focused and its value selected: type a value and press Enter (Move, Rotate, Scale…). A dialog opened from a menu takes the keyboard focus every time it opens, not only the first (#1367), and one whose first field starts greyed out (Blend Options on Smooth Color, Layers Panel Options) gives the focus to that field once it is enabled (#1395). Number fields in panels, the Control bar and dialogs (preferences too) step with Up/Down, or with the mouse wheel over the hovered field without requiring focus (#485, #5949: a notch a step; the panel under it then stays put, and a disabled field leaves the wheel to scrolling) (Shift: ten, Ctrl/Cmd: a tenth of their unit), applied at once. + - Dialogs open with their first field focused and its value selected: type a value and press Enter (Move, Rotate, Scale…). A dialog opened from a menu takes the keyboard focus every time it opens, not only the first (#1367), and one whose first field starts greyed out (Blend Options on Smooth Color, Layers Panel Options) gives the focus to that field once it is enabled (#1395). Number fields in panels, the Control bar and dialogs (preferences too) step with Up/Down, or with the mouse wheel over the hovered field without requiring focus (#485, #5949: a notch a step; the panel under it then stays put, and a disabled field leaves the wheel to scrolling) (Shift: ten, Ctrl/Cmd: a tenth of their unit), applied at once. A field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere, such as a panel scrolled under a still pointer, stays there until 0.5 s pass with no wheel input or the pointer is pressed on a field (VectorCraft's own rule and value). - While Alt (Option on macOS) is held, the Flare Tool Options' Cancel button reads Reset, which puts every option back to the Flare tool's default and leaves the dialog open (`ui.dialogReset`). - A plain step of a number field (Up/Down or a wheel notch) goes to the next whole unit in its direction and a Ctrl/Cmd step goes to the next tenth, so 5.1 mm steps up to 6 mm and down to 5 mm (#2881). A Shift step adds or takes ten and keeps the fraction. - In the number, text and color fields of the panels and the Control bar, Shift+Enter (Shift+Return) applies the value and keeps the field active with its value selected; a text box of several lines takes it as a line break. In a dialog, Shift+Enter applies the value and confirms the dialog, as Enter does. @@ -806,6 +835,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Control bar's underlined Transform link opens the Transform panel in a popover under it (reference point, X/Y/W/H, Rotate and Shear with their icons and angle presets, flips, shape properties, Scale Corners and Scale Strokes & Effects), as its Stroke link does the Stroke panel; X/Y/W/H also show inline while the bar has room. The reference point locator is nine squares, the outer eight joined around the box. As VectorCraft's own keyboard rule, the locator is one tab stop in the Control bar popover, the Transform panel, the Properties panel and the dialogs, the Arrange Tools dialogs included. While it has the focus it shows an outline, and ←, →, ↑ and ↓ move the reference point one square, stopping at the edges (`the_reference_point_grid_is_one_tab_stop`, `arrow_keys_move_the_reference_point`, `the_reference_point_locator_is_one_tab_stop_and_arrows_move_it`). - In isolation mode the Control bar has an Exit Isolation Mode button (`object.exitIsolation`), except while a pattern is edited. Outside isolation mode, with one group, compound path, path, image, mesh or placed file selected, it has an Isolate Selected Object button (`object.isolate`), which also isolates a path inside a group that Direct Selection selected. - While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does. + - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). + - Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369). - Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`). - Shift+Tab (`window.panels`) shows and hides the dock and the floating panels and leaves the toolbar and the Control bar as they are; hiding the panels with Tab or Shift+Tab also closes a panel popped out of the icon column. - The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown. @@ -872,6 +903,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance is measured by its symbol's art, as its transform places it, for clicks, the marquee, the bounding box, the Transform panel, Align and Distribute (the art's strokes too with Use Preview Bounds), Fit to Artwork Bounds, exports of the art, thumbnails and canvas culling; one whose symbol is missing is measured as the 20 × 20 square around the origin. A selected clip group shows the outline and anchors of its clipping path, not of the art the path clips, and its hover highlight and key object outline follow the clipping path too. That art shows its whole outline when it is selected on its own: with Edit Contents, Direct or Group Selection, or in isolation mode (#2422). Clear deletes individual selected compound-path members without deleting their siblings, and explicit object ids work without a selection; Cut still removes the same objects it copies (#786). + Copy and Cut of a compound-path member selected on its own, with Direct or Group Selection, take only that member, as an ordinary path with the compound's paint, transparency, opacity mask and fill rule, and a gradient keeps the compound's fit; the other members stay a compound, also when one is left. Selecting the compound, or every member whole outside isolation mode, still takes the whole compound, and Clear of every member's anchors or segments removes the compound too (`engine/tests/it/copy_direct_selection.rs`). A command that leaves out an object selected inside a selected group also leaves it out when `ids` list it together with a group that holds it. Make Repeat and Live Paint no longer fail on such a list, New Symbol no longer stores the object twice, and `object.transform` no longer moves it twice. - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. @@ -965,7 +997,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Blob Brush Tool Options' tip preview is the Angle slider for screen readers, with the Angle in degrees as its value: a click or a drag in it points the Angle at the pointer and gives it the keyboard focus, Tab reaches it after the Roundness field, and the arrow keys step the Angle by 1° (10° with Shift, Home and End to −180° and 180°). The Blob Brush Tool Options also have Fidelity, which the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list as setting how far the pointer moves before the path gets a new anchor point. The range and default are VectorCraft's own values: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). A Blob Brush stroke merges with the topmost path of its fill color and no stroke that it touches, and with the other such paths it touches in the same group or layer that are next to that path in stacking order with no other kind of object between them; matching paths in other groups or layers are left alone, as the Blob Brush tool guidelines in [Paint with fills and strokes](https://web.archive.org/web/20241219085603/https://helpx.adobe.com/illustrator/using/painting-fills-strokes.html) describe (`path.blob`). -- **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. Not done: guides stacked among the art of their layer (they are listed above it), a guide row's own eye and lock. Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. +- **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. Not done: guides stacked among the art of their layer (they are listed above it), a guide row's own eye and lock. Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). Preferences › Guides & Grid › Lock Guides by Default locks guides when the app starts; it is off by default, and new guides can still be dragged out of a ruler while guides are locked. The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. - **Releasing ruler guides:** View › Guides › Release Guides turns the selected ruler guides into paths with no fill or stroke. An artboard guide becomes a line across its artboard, and a canvas guide becomes a line across the artboards (`view.guides.release {index?, ids?}`). A Cmd/Ctrl+Shift double-click with the Selection, Direct Selection or Group Selection tool releases the ruler guide or guide path under the pointer. - **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (layers dropped in the empty space under the last row go below the bottom layer, #2260; dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting. A document opens with only its top-level layers open; the rows left open are saved in the native file (nothing is written for the default) and reopen that way. Only the rows scrolled into view are laid out, from a row list made once per change: a layer of 5,000 groups of 10 paths, all open, draws the panel in 0.4 ms a frame instead of about 29 s (#638). The Filter button at the right of Search All keeps the rows that are of an object kind ticked under By Object (paths, shapes, text, images, effects, groups, linked files, guides) and in a state ticked under By Layer (locked, hidden), with the rows that hold them; a section with nothing ticked takes every row. The filter combines with the search, the button is lit while a filter is on, and Clear All in its popup turns the filter off (`ui.layersFilter`). The filter lasts the session. @@ -991,7 +1023,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Artboard click-to-fit (#1227):** a plain click fits the topmost editable object or group to a new artboard, including its stroke like Fit to Selected Art, and makes the new artboard active. Art and its selection stay unchanged; creation is one undo step. Handles, modified clicks, drags, Escape and tool changes retain their meaning. Tested inside an artboard and on the pasteboard (`crates/engine/tests/it/artboard_click.rs`); the public [CS6 Printing Guide](https://helpx.adobe.com/content/dam/help/en/indesign/pdf/CS6_PrintGuide.pdf) documents the object-click gesture. This legacy gesture adds evidence without regrading the 2026 canvas controls. - **Rotated views:** with the view rotated, Fit Artboard in Window, Fit All in Window and the status bar's artboard navigator fit the artboard or the art as the view turns it, and a Zoom tool marquee (Animated Zoom or GPU Performance off) zooms to the area dragged across. Ruler guides on no artboard turn with the view. The canvas draws the selection marquee where the tools select, Show Hidden Characters draws the marks of type partly inside the canvas, the Contextual Task Bar stays under the selection, and the Navigator's red box outlines what the window shows. - **Navigator panel options:** the Navigator panel menu's Panel Options… sets the color the view box is drawn in, from a preset list (VectorCraft's own: Light Red, the default, then the layer colors) or a custom color, and Draw Dashed Lines as Solid Lines, off by default, which draws dashed strokes without their dashes in the panel's thumbnail only (`ui.navigatorPanelOptions`; kept with the UI state; behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). -- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). +- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). Outline view draws on a white canvas in every interface brightness and Canvas Color, pasteboard included, with the artboards as their edges and no paper (VectorCraft's own rule), so the black outlines of art on the pasteboard show. In Presentation Mode, → and ← go to the next and the previous artboard, and a click anywhere goes to the next one, as the status bar navigator's Next and Previous do (`view.goToArtboard`): on the last artboard → and a click leave the view as it is, and so does ← on the first. The arrow keys do not move the selection there, and the tool does not receive a click, so a click selects and draws nothing (behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). Full Screen Mode and Presentation Mode put the window full screen, covering the taskbar and the window's frame, and Normal Screen Mode or Full Screen Mode with Menu Bar puts it back (#4365); a window the user made full screen stays so. An unmodified Escape in either Full Screen Mode exits to Normal Screen Mode after any open popup, focused field, tool gesture, ruler-origin drag, floating Tools panel move, edit mode, drawer, flyout or view rotation has taken its Escape; a later Escape exits when that action is finished. This is a VectorCraft choice for both full screen variants, based on the public [shortcut list](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html); the list does not specify that priority or the return mode. @@ -1019,7 +1051,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Rotate View turns the view to the status bar's preset angles (`view.rotate {angle}`, which takes any angle). View › Rotate View to Selection turns the view to the angle of the selected objects' bounding box, so the box is square to the window (`view.rotateToSelection`). When the view angle changes (a Rotate View drag, the status bar's angle menu, Reset Rotate View or a saved view) and the desktop app renders the frame at the new angle on the render worker, the canvas draws the last frame turned to the new angle until that frame is ready. It used to draw no art until then. While the desktop app's render worker renders the frame for a new view, the parts of the canvas the last frame does not cover after a pan, a zoom-out or a turn show the art from a frame that a second worker renders at a quarter of the resolution, covering twice the canvas's width and height. That frame draws images only from pixels already decoded (an image not yet decoded shows as a light gray box), and it renders large raster effects at the lower resolution a drag uses. Until it is ready, those parts show the pasteboard and the artboards. They used to show only the pasteboard and the artboards until the frame for the new view was ready. - With the view rotated, a second Escape less than a second after the first resets the rotation, as Reset Rotate View does. The first Escape may end something else, such as isolation mode or a path being drawn. The second resets the view only when it has nothing else to end, and an Escape that closes a menu does not count. After a click, or a press of another key that is not a modifier (Shift, Control, Alt/Option or Command), the next Escape counts as the first. With the Rotate View tool chosen, one Escape resets the view. + With the view rotated, an Escape that has nothing else to end resets the rotation, as Reset Rotate View does, with or without a selection, which stays selected. An Escape that ends something else ends only that, and the next Escape resets the view: to reset the view while another tool or feature is in use, Escape is pressed twice ([Rotate canvas view](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/rotate-canvas-view.html)). Under VectorCraft's own rule, the things an Escape ends first are isolation mode, pattern editing, Global Edit, a tool flyout, a full screen mode, Presentation Mode, a path being drawn with the Pen, Smart Pen or Curvature tool, the Blend tool's first pick, the Artboard tool, a tool's drag, a menu, a dialog, a text field and a drag of the ruler origin, and the second press may come any time later, after clicks or other keys. With the Rotate View tool, the view resets before a full screen mode ends; with another tool, Escape leaves a full screen mode first, and Shift+Escape, which does not leave it, resets the view. An Escape does not reset the view while About, a progress window or an Appearance row's popup is open, while a pointer button is held, or in the frame a button is let go. It used to reset the view only as the second of two Escape presses less than a second apart. A two-finger rotation on a Mac trackpad turns the view about the pointer once it reaches 5° (Preferences › General › Trackpad Gesture to Rotate View, on by default). On a touch screen a second finger cancels the tool press the first finger began, in the frame it lands or later: the Pencil's stroke or a Selection move is rolled back with no undo entry, and a finger that lands while another is down presses nothing, so a pinch or two-finger pan only zooms and pans (#4198; canvas test `a_second_finger_cancels_the_tool_gesture_the_first_began`). A tool press dropped by a second finger, a long touch or a canceled touch cancels the tool's drag as Escape does: the tool gets back the options it had when the press began (the Polygon tool's sides, set with ↑ and ↓) and they are not stored, a press held still opens no size dialog, a Selection or Artboard tool marquee selects nothing, and the Pen goes on drawing its path without the dropped anchor (canvas tests `a_canceled_touch_drops_the_drag_without_keeping_its_options` and `long_touch_drops_a_tool_press_without_committing_art`; engine tests in `tests::toolsettings`). @@ -1034,15 +1066,21 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel and Inflate treat strokes as outlined: each visible stroke builds a solid from its outline in its own paint beside the top fill's ([three-d.md](three-d.md#fills-and-strokes)). - Extrude & Bevel, Inflate and Rotate apply to type: it makes a solid of its glyph outlines, painted with its own fills and strokes or, when it has none, its characters' colour (the first run's), and stays type, so editing the text reshapes the solid (#4715). - Extrude & Bevel, Inflate and Rotate (Effect › 3D and Materials): live effects in the `three-d` crate with depth, twist, taper, solid or hollow caps, five original bevel shapes (width, height, repeat, spacing, inside, both sides), Inflate's volume, both sides, twist, taper and cap, Rotate's turned fills and strokes, Position presets, the rotation and light gizmos, SVG/PDF vector output and Expand Appearance; one 3D effect per object; covered by geometry, effect, canvas-versus-export, command and dialog tests ([three-d.md](three-d.md)). + - Extrude & Bevel and Inflate build detailed shapes: each solid takes up to 65,536 outline points and 163,840 faces (VectorCraft's own limits, was 2,048 points and 32,768 faces), counted before any point is sampled; when the faces do not fit, every curve takes fewer pieces, down to 4. A closed path of 2,000 curves extrudes with a bevel and inflates, and paths of 5,000 and 10,000 curves build at the default settings (`crates/three-d/src/solid/tests_limits.rs`). + - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)). + - Revolve takes type, as its glyph outlines, and groups or layers, whose members sweep about one axis as [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html) describes; a surface can have up to 16,384 profile points, and curves take fewer samples when a surface would pass 163,840 faces (#3617). - Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters). Zig Zag spaces its ridges evenly along each segment, so lines and curves get a regular wave in Corner and Smooth (#1558). Warp › Arc (the effect and Envelope › Make with Warp) bends in the object's real proportions: a circular arc with concentric edges and no fold-over at 100%, so Arc on art that isn't square draws differently from before (#1581, fixes #1578). `effect.apply` and `effect.setParams` give an error for a misspelt or wrongly typed effect parameter instead of running the effect with its default (#1623, #1592). Roughen with Smooth keeps turn-backs smooth instead of making cusps that draw as spikes (#1646, #1643). Scribble draws one zig-zag per region, with no lines across holes and notches; convex shapes are unchanged (#1651, #1648). On the canvas, in Expand Appearance and in exports, Effect → Pathfinder uses the glyph outlines of type in the group, and results painted like the type keep its opacity and blend mode. - Cmd/Ctrl+4 (`pathfinder.repeat`) repeats the last successful Pathfinder panel operation, direct `object.pathfinder.*` command or `command.batch` step (including Actions playback) on the current selection; the panel menu names it. `action.batch`, Trap, compound-shape edits and live effects do not set history. Public references: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html). - Pathfinder Options ([Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the panel menu's Pathfinder Options… sets Precision (0.001–10 pt: results refit to within it, thinner pieces dropped), Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork (`object.pathfinder.options`, kept in the preferences) for every Shape Mode and Pathfinder operation; the defaults keep the earlier output (`pathops` `precision_drops_pieces_thinner_than_it`, engine `tests_pathops` Pathfinder Options tests, `panels::pathfinder` dialog test). - Pathfinder › Trap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html), [Pathfinder panel](https://helpx.adobe.com/illustrator/using/pathfinder-panel-overview.html)): the Pathfinder panel menu's Trap… (`object.pathfinder.trap`) and Effect › Pathfinder › Trap… (`pathfinder.trap`, live on groups) add, where two objects' visible areas of different solid colours meet, a strip of the darker one's area along the edge, filled with the lighter colour at the Tint Reduction percentage and set to overprint (Reverse Traps: the darker colour spreads instead, but not a rich black); Thickness 0.01–5000 pt across vertical edges, Height/Width scales it across horizontal ones, Traps with Process Color paints a swatch colour's trap with its CMYK equivalent; the effect also has Precision and Remove Redundant Points. The panel's Trap is one undo step and groups the traps above the topmost selected object, selected; with no adjoining edges of different colours it says so and changes nothing. Tests: `crates/pathops/src/trap.rs`, `crates/effects/src/trap.rs`, `group::tests::trap_effect_adds_an_overprinting_strip_above_the_members`, `crates/engine/src/tests/trap.rs`, `panels::pathfinder::tests::trap_opens_its_options_and_ok_traps_the_selection`. - Compound shapes ([Create compound shapes with Pathfinder](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the Pathfinder panel menu's Make Compound Shape (every member in Add) and Alt-clicking a Shape Mode (every member in that mode) make the two or more selected paths, compound paths, groups, compound shapes or type a live compound shape (`object.compoundShape.make`): a group whose members each keep a shape mode and stay editable, drawn, printed and exported (SVG, PDF and the rest through the baked document) as the area the modes make from the backmost member up, open paths closed, painted with its own appearance, taken from the topmost member not subtracting. With members selected (Direct Selection, Layers panel, isolation mode) a Shape Mode button sets theirs (`object.compoundShape.setMode`) and is lit for the mode they share; paint given to a member goes to the compound shape. Release Compound Shape gives the members back as they were (`object.compoundShape.release`); Expand Compound Shape and the panel's Expand button turn it into the path or compound path of its area (`object.compoundShape.expand`). Shape Modes and Pathfinders take a compound shape as its area. Saved files keep it (`compound_shape`, `shape_mode`; an unknown mode reads as Add). Blends, envelopes and objects with a warp or another geometry effect are members as they draw (a blend's steps, an envelope's distorted art, the warped outline), and the area follows an edit of the blend, envelope or warp; Release gives them back as they were. Tests: `crates/engine/src/tests/compound_shape.rs`, `group::tests::compound_shapes_draw_the_area_their_shape_modes_make`, `group::tests::nested_compound_shapes_take_part_as_their_area`, `panels::pathfinder::tests::compound_shape_items_follow_the_selection`, the `CompoundShape` op of the property-test strategies. Not yet: the question marks on mixed member modes, hit-testing by the area (a click hits the members). - Effect › Path › Outline Object has no options. Type that carries it is drawn, exported (PDF and SVG as paths, with no font) and expanded as its glyph outlines while it stays editable, and the effects after it reshape those outlines. Paths and images draw as before. With Use Preview Bounds on, type is measured by its glyph outlines. Public reference: [Summary of effects](https://web.archive.org/web/20210901011839/https://helpx.adobe.com/illustrator/using/summary-effects.html) (archived copy). + - A butt cap ends a stroke square at the end of an open path, and a projecting cap extends half the weight past it. VectorCraft's visual box of a butt-capped stroke on an open path does not grow past the path's ends: a straight segment's box comes from the corners of its stroked rectangle, and a curve's box comes from the stroke at its ends and where its tangent is square to an axis. Round and projecting caps and arrowheads still reach past an end. A curve that bends more tightly than half the weight can measure a little larger than it paints, and a butt-dashed path whose first or last dash is a gap is measured to the path's ends. Public reference: [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html). + - A butt-capped curve whose first or last handle sits on its end point also stops at that end: a straight 50 pt curve with a 2 pt stroke and its first handle on its start point measures 50 pt tall, not 51 pt (doc `reach::tests::a_butt_curve_with_a_handle_on_its_end_point_stops_near_that_end`). - With Use Preview Bounds on, the bounding box, the Transform panel, Align, Distribute, Distribute Spacing and `object.setBounds` measure each object after its geometry effects. A path is measured by its effected shape, and a fill or stroke with geometry effects of its own is measured by the shape it paints. Type, images, live objects and symbol instances are measured by their reshaped art, and a symbol instance is also measured by its reshaped art when its symbol's art has geometry effects. A group or layer with geometry or Pathfinder effects, or with a fill or stroke of its own that has geometry effects or paints members with geometry effects, is measured by its evaluated art. A blend, envelope or repeat whose objects have geometry effects is measured by its evaluated art, with those objects measured after their effects. A 100 pt square without a stroke, with Offset Path 10, measures 120 pt, and type with Outline Object aligns and sizes by its glyphs. Raster effects are not measured. Public reference: [Create text](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html) (archived copy). + - VectorCraft's own Measure Type by Glyph Bounds (`typeGlyphBounds`, off by default; Preferences › Type and the Transform panel menu): the bounding box, the Transform panel's, Control bar's and Properties panel's X, Y, W and H, `object.setBounds`, Swap Objects, Replace with Top Object, Set Size of Each and Sort Objects measure each point type object selected as an object by the ink of its glyphs, underline and strikethrough included, instead of its em box. A typed W or H scales the live type until its ink has that size; the font size follows the vertical scale, so a W typed alone, out of proportion, changes the horizontal scale instead. Moved type snaps by its ink box. Type that draws nothing, area type, type on a path and type in a selected group are measured as before, and Align and Distribute follow Align to Glyph Bounds (`tests::typeglyphbounds`, `panels::transform::tests::measure_type_by_glyph_bounds_is_checked_and_resizes_the_box`). - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Cap is on by default with continuous curved vector rims; shading uses vector gradients automatically, with sharp profile corners, uniform caps and round seam joins. One light and approximate visibility remain ([revolve.md](revolve.md)). - Effect › Path › Outline Object has no options. Type that carries it is drawn, exported (PDF and SVG as paths, with no font) and expanded as its glyph outlines while it stays editable, and the effects after it reshape those outlines. Paths and images draw as before. With Use Preview Bounds on, type is still measured by its layout box. Public reference: [Summary of effects](https://web.archive.org/web/20210901011839/https://helpx.adobe.com/illustrator/using/summary-effects.html) (archived copy). - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Cap is on by default with continuous curved vector rims; shading uses vector gradients automatically, with sharp profile corners, uniform caps and round seam joins. The Lights list, Add Light and Delete Light manage one to ten independent colored lights; ambient is shared and visibility remains approximate ([revolve.md](revolve.md)). @@ -1161,11 +1199,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. - **Gradient mesh from an image:** Object › Create Gradient Mesh (`object.mesh.create`) on an embedded image makes a mesh of 1 to 50 rows and columns over the picture's rectangle, placed with the image's transform; each point takes the alpha-weighted average colour and the opacity of the area around it, and Appearance and Highlight apply. A linked image is refused with a message to embed it (#1676). Scores and hours unchanged. +- **Gradient mesh keeps the object's outline (#2752):** Create Gradient Mesh, a Mesh tool click and Expand of a gradient to a mesh lay the mesh's border on the path's outline: each border edge is the piece of the outline between its two points, and where the outline bends through an anchor (a star's points, an L-shape's inner corner, a rounded rectangle's arcs) no single curve follows, the mesh takes a line through that anchor, up to 256 each way. Holes and other subpaths of a compound path are still left out. Public reference: [About mesh objects and Create mesh objects, CS3 user guide, pages 184 to 185](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) (mesh lines carry anchor points as well as mesh points). Tests: `a_mesh_keeps_the_outline_of_every_shape` and `a_mesh_takes_lines_only_where_the_outline_needs_them` in `crates/doc/src/live.rs`, `a_mesh_tool_click_keeps_a_stars_points` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. -- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). +- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)). Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. Smooth Color counts the steps of each pair of keys from their color change, or from the distance between their visible bounding-box edges when their colors match or they hold gradients or patterns ([Blend Options](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)); the step counts, their caps and the colors compared are VectorCraft's own. @@ -1232,7 +1271,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. + - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>) and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -1268,7 +1307,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. - - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; six generated style libraries save and load as `.vcstyles`. + - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; seven generated style libraries (including Game HUD) save and load as `.vcstyles`. In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Load text styles from another document:** the Character Styles and Paragraph Styles panel menus have Load Character Styles… or Load Paragraph Styles… and Load All Styles…, which copy the styles of a document picked in an open dialog, with the swatches and patterns they paint with, in one undo step (`charStyle.load`, `paraStyle.load`, `textStyle.loadAll`); a style the document already has, under its name or a numbered one, is not added again, any other whose name is taken gets a number, and the file's Normal styles are not loaded. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -1307,7 +1346,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The font database looks up a name that is neither a loaded nor an installed family among the other names of the loaded and installed fonts once for each style it is asked in, and keeps the answer until fonts are added or rescanned. Laying out a story of 1,000 paragraphs set in a font that is not installed, with 400 more fonts loaded, takes a median of 56 to 71 ms instead of 409 to 507 ms on Windows 11 (`CRAFT_FONTS_DIR=<craft-fonts checkout> cargo test --release -p vectorcraft-text --lib missing_font_story_layout_timing -- --ignored --nocapture`). A font family removed while the app runs leaves the font menus when the app scans the font folders again (when its window comes to the front after a font folder changed, or Refresh Font List), also when type had used it: that type then draws in the fallback font and Find Font lists the font as missing, until the font is installed again and the folders are scanned. - **Files (M4):** - - PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. + - PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. - PDF export and print composition use the optional shared guarded writer ([pdf-backend.md](pdf-backend.md)); app drawing and output policy and desktop printer submission remain in their existing layers. The shared reader keeps the app-owned import adapter; synthetic tests cover layer and overprint state across windows, long operands, inline images, failed decoding, document limits and incomplete tails. Empty and populated metadata key presence is regression-tested, and CI checks the immutable backend source. PDF export measures each member of a plain group or layer once to leave out what is off the page: the group or layer is measured through its members (`Node::visual_of_members`), and each member uses that box when it is written. The elements of a knockout group are measured twice, once for the group's box and once to choose the elements on the page (`pdf/src/tests/measuring.rs` counts the measures). A local byte comparison with the previous build found identical output on one open path of 200,000 anchors, 20,000 rectangles in 200 groups of 100, 5,000 point type objects and a document of plain, see-through, clipping and knockout groups. The walk that writes link annotations measures only an object with a URL that opens and a clipping group (`links.rs`), and its output on a document of linked objects in plain and clipping groups is the same byte for byte as when it measured every object. Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests/import_fidelity.rs`, `pdf/src/tests/realtext.rs`). @@ -1375,10 +1414,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). - In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type keeps its drawn art, with its type hidden (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). + In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). - PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); in PDF 1.3 to 1.5 files and PDF/X files such a page is written in points. + PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). PDF export warns when a PDF/X file has no bleed on a side where the document's bleed has one, and writes the file as asked. Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). @@ -1467,6 +1506,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur An image whose pixels can't be decoded, such as a PNG cut short or an image over the 2 GB decoding allowance as RGBA that can't be drawn at reduced size, is tried once: the renderer notes it and does not try to decode it again on later frames. An image refused only because the images being drawn leave no room for it is tried again on the next render. On the canvas such an image draws as a light gray box crossed from corner to corner, and the status bar says once for each image that it couldn't be decoded; exports leave it out and report it as before. A PNG, JPEG, GIF or WebP image that takes more than 2 GiB as RGBA (512 MiB in the web app) draws in the canvas and in raster exports at the largest size within that allowance, instead of as that crossed box on the canvas and not at all in exports. Each pixel of the result is the mean of the image's pixels it covers, and the document keeps the whole file. A PNG that isn't interlaced is read a row at a time, and other images are read whole when their decoded samples fit in the allowance. A 16-bit PNG that isn't interlaced, whose decoded samples take more than the allowance and whose RGBA fits in it, draws at its own size, read a row at a time. An image of more pixels than the allowance has bytes (on the desktop, 46,341 × 46,341 is more) still draws as the crossed box, and so does one whose decoded samples take more than the allowance, other than a PNG that isn't interlaced. Open, Place and the Links panel say "an image of W × H pixels is shown at reduced size", and say "too large to draw" of an image that is not drawn at reduced size. The renderers keep the decoded images they share within a quarter of the installed memory on Windows, macOS, Linux and FreeBSD (on Linux, of the process's cgroup memory limit where that is lower, and in a 32-bit build at most a quarter of the address space), within 1 GiB where the installed memory can't be read, and within 256 MiB in the web build; while the decoded images add up to less than that budget, they are not decoded again when the view changes. + The undo histories of all the open documents together keep their steps within a quarter of the installed memory on the same systems (at least 64 MiB, and at most a quarter of the address space in a 32-bit build), within 1 GiB where the installed memory can't be read, and within 256 MiB in the web build; past that budget the oldest steps of any open document are dropped first, but each document keeps its last eight undo steps and its next eight redo steps. Closing a document frees its share for the others. With `--deep`, each memory row of `vectorcraft-cli perf` also gives the peak so far: the peak working set on Windows and the peak resident memory (`VmHWM`) on Linux. A new last row gives the memory after the SVG export and the save → open → save at the end of the run. The renderer composes the two ink planes of a CMYK document that shows transparency into screen colors on up to as many threads as it rasterizes with, instead of on one. At 2880 × 1800 on 8 threads, a page of 300 shapes at 20% to 90% opacity takes 30 ms a frame instead of 55 ms, and 50,000 paths with one at 99% opacity take 258 ms instead of 361 ms (`vectorcraft-cli bench`), with the same pixels. With Overprint Preview or Separations Preview on, the renderer keeps the art it prepared for the preview from one frame to the next. It prepares again the objects that changed, and all of the art when Discard White Overprint changes or, with Separations Preview, when the plates shown, the proof setup, the swatches, the Spot Colors option or the color settings change or a profile is loaded. It draws the other objects from the art, geometry and stroke outlines it kept for them. @@ -1475,6 +1515,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Offset Path looks up the segments near each candidate hole or island in a tree of the source path's segment bounds when it decides whether to drop that contour, instead of testing the bounds of every segment. The output paths are the same. On compound and open paths of 25,000 to 40,000 anchors with 6,400 to 11,976 candidate contours, that check takes 11 to 13 ms instead of 140 to 649 ms (medians of five interleaved runs). The limit on overlapping segment pairs is the same, so a path that stops with "Offset Path: the path is too complex to offset" still stops there. Finding the distinct regions of an arrangement lists the shapes that cover each region instead of keeping a flag for every shape, so that step's time follows how many shapes cover each region rather than how many shapes there are. Divide, Hard Mix, Soft Mix, Shape Builder, Flatten Transparency, trapping, Intertwine and the Pathfinder effects are among the commands that use that step. The regions, their order and the output are the same. Divide on 3,000 overlapping rectangles takes 0.84 to 1.13 billion CPU cycles on its thread instead of 1.25 to 1.46 billion (dev build, six runs of each, alternating, while other builds were running). The contour passes of the two-path boolean operations, Offset Path, compound shapes and Intertwine test the list of shapes that cover each face instead of a flag for every shape, so each test's time follows how many shapes cover the face rather than how many shapes there are. The contours, their order and the output are the same. The many-shape boolean that compound shapes use takes 0.75 to 0.83 billion CPU cycles on its thread instead of 1.28 to 1.33 billion to unite 10,000 squares that do not touch, and 2.27 to 2.30 billion instead of 2.43 to 2.47 billion for 1,500 members of two squares each over 3,000 overlapping squares (dev build, six runs of each, alternating, while other builds were running). + Pathfinder › Unite and the other commands that unite filled paths sweep a single input once instead of twice when its own sweep neither splits nor drops any of its segments and no two of its segments lie within twice the sweep tolerance. The output is the same. Unite on one compound path of 4,000 rings takes 485 to 542 ms instead of 872 to 1,008 ms, and on one zigzag polygon of 20,000 teeth 70 to 76 ms instead of 118 to 130 ms (release build, medians of three alternating rounds of five runs, while other builds were running). With more than 10,000 type on a path objects selected, the Selection and Direct Selection tools neither draw nor hit-test the objects' brackets. The renderer outlines the stroke of a path object with more than 1,024 path elements, without dashes or a width profile, only in and around the view, with a margin of the view's size on each side, and outlines it again when the view moves past that margin. The pixels are the same. At 1600 × 1200, the frame after one anchor of an open path of 200,000 anchors moves takes 28 to 30 ms instead of 103 ms, and with a closed path of 50,000 anchors 10 ms instead of 30 ms (`cargo run --release -p vectorcraft-engine --example anchor_bench`). The renderer outlines a dashed stroke of such a path the same way, without a width profile, and draws its dashes and dots in the same places as when the whole path is dashed, so the pixels are the same. A pattern too fine to draw is drawn solid, as before, and its stroke is outlined near the view too. At 1600 × 1200, the frame after one anchor moves takes 14 ms instead of 102 ms with a filled closed path of 50,000 anchors and a stroke of 6 pt dashes and 4 pt gaps (`cargo run --release -p vectorcraft-engine --example anchor_bench`, which now includes that document). @@ -1483,6 +1524,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 123 ms instead of 403 ms with an open path of 200,000 anchors in view (103 ms with nothing changed), and 13 ms instead of 26 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. When the stroke of a path moved this way has a gradient along or across it, the renderer also draws the gradient from the slices it made before the move, moved by the same offset. It makes the slices again when the path is scaled, rotated or edited, and when the stroke or its gradient changes. The pixels are the same. On Windows at 1600 × 1000, the frame after a 1 pt nudge of an open path of 200,000 anchors takes 75 ms instead of 1,237 ms with the gradient along the stroke and 69 ms instead of 1,420 ms with it across, and with an open path of 50,000 anchors 22 ms instead of 313 ms and 21 ms instead of 352 ms (medians of five interleaved runs). The renderer keeps the path of a path or compound path of 1,024 anchors or more by object, with the bounds of its segments and of its miter spikes in runs of 128 segments. When anchors move and the subpaths and anchor counts stay the same, the next frame changes only the segments that start or end at a moved anchor and measures again only the runs that hold them or the segments with length before them, instead of making the whole path again and measuring it whole for culling. The pixels and the cull bounds are the same. On Windows at 1600 × 1200, the frame after one anchor moves takes 8.2 ms instead of 30.1 ms with an open path of 200,000 anchors, 4.3 ms instead of 10.4 ms with a closed path of 50,000 anchors, and 6.6 ms instead of 11.9 ms with the filled closed path of 50,000 anchors and a dashed stroke (medians of five runs of `anchor_bench`). + When an edit changes a 3D effect (Extrude & Bevel, Inflate, Rotate, Revolve), the canvas draws again where its art was and is, measured by that art: type and groups were measured by their letters or members, so a shallower or turned solid left pieces of the old one on the canvas. When the canvas draws the part on its own thread, it measures through its renderer and draws the part with the art it made to measure it. Exports and Object › Rasterize take the solid of 3D type, where they cropped it to the letters, and Fit to Artwork Bounds and per-artboard SVG export measure every artboard through one renderer, building each solid once unless the object has brushed strokes: 30 extruded type objects measured over 30 artboards take about 2 ms in a release build, where measuring their letters took under 1 ms. A document's first frame builds every 3D object's solid, off the view too, to know whether it reaches into the view. When only anchors of a path or compound path move, the canvas draws again only around the segments that start or end at a moved anchor, grown by the farthest its strokes reach, instead of the whole object before and after. This holds while every fill and stroke is a solid color, and the strokes have no dashes, width profile, arrowheads or brush, and the object has no effects or opacity mask; any other object still counts whole. On a loaded Windows machine at 1600 × 1200, single-threaded in a development build, the frame after one anchor of a filled closed path moves takes 16.6 million CPU cycles instead of 56.4 million with 50,000 anchors and 65.6 million instead of 180.0 million with 200,000 anchors (medians of 15 edits, the two builds run in turn three times). Opening a document keeps the layouts it makes for its type objects, up to 128 MiB, and the first frame uses them instead of laying those objects out again. It does not keep a layout with bitmap or color glyphs or a text object with a gradient. The frame uses a layout only for a text object equal to the one laid out, and only while the fonts and the hyphenation exceptions have not changed. It uses each layout once. The renderer drops the rest when a frame that used one ends, and all of them after eight frames that use none. The frames of a threaded story are laid out while the file is read, and the first frame lays them out again. The pixels are the same. On Windows at 1600 × 1200, in medians of seven interleaved rounds of a local example, counted in the main thread's CPU cycles because other builds were running: with 5,000 point type objects in view the first frame takes 409 million cycles instead of 894 million and the open 816 million instead of 665 million, so the two together take 1,225 million instead of 1,559 million; with one area type object of 500 paragraphs the first frame takes 697 million instead of 1,193 million and the open 535 million instead of 568 million. Type › Show Hidden Characters keeps the marks it places on each text object from one frame to the next. The canvas lays a text object out again when an edit changes it or its threaded story, or when the last frame that showed the marks did not draw it, and it lays out all type in view again when the fonts or the hyphenation exceptions change. With 1,000 two-line labels in view, drawing the marks takes 0.8 ms per frame in a release build instead of 19.7 ms. @@ -1592,6 +1634,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin.<id>.<command>` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) whatever menu the manifest names, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. +- **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in settings and cache (G17, #2191):** at plug-in API level 2 a plug-in with the `settings` permission keeps settings of its own (`env.vc_settings_get`, `_set`, `_delete`) and one with `cache` a cache the user can clear (`env.vc_cache_read`, `_write`, `_clear`), under its id in the `Plug-ins` folder. Keys are plain names, never paths; VectorCraft's own caps refuse a write past 256 settings, 1 MiB of settings or 512 MiB of cache; a damaged settings file is moved aside and the settings start empty. `plugin.clearCache` empties a cache, `plugin.list` and `plugin.info` give `cacheBytes`, replacing a plug-in keeps its storage and `plugin.remove` deletes it. Another module under an id that is installed or has storage installs only with `replace: true`, which the app asks the user for; each storage call counts the whole settings file or cache entry it reads and writes toward the run's 1 GiB. Regressions: `crates/plugins/src/storage.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_clear_cache.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. @@ -1887,7 +1930,13 @@ Edit › Spelling has the commands its Check Spelling dialog will use, as the pu The custom dictionary and Ignore All followed (2026-11-09), as the same page describes them: Add puts a word in the custom dictionary, which Edit Custom Dictionary adds to, deletes from and changes, and Ignore All skips a word in the current document (#4936). `text.spelling.addWord`, `removeWord` and `changeWord` keep the dictionary in craft-proof, which every language's check reads, and the desktop app saves it to `Custom Dictionary.txt` beside its preferences (none in runs without preferences); `text.spelling.dictionary` lists it. `text.spelling.ignoreAll` keeps a word for the active document while it is open, not saved and not undoable (`tests/spelling.rs`). The dialogs remain. -Auto Spell Check followed (2026-11-09): the same page has Edit › Spelling › Auto Spell Check underline potential spelling errors with a red line as you type, and says it isn't available for text with effects applied (#4936). `edit.autoSpellCheck` turns it on and off (off at first, saved with the view settings); the canvas draws a red wavy line under each word `text.spelling.check` would list in the visible type, leaves out type with an effect shown on it or on its fills and strokes, and checks a type object again when it is edited, when the custom dictionary changes and when Ignore All adds a word (`ui-egui/src/canvas/tests.rs`, `auto_spell_check_*`; `tests/spelling.rs`). The right-click Spelling menu on an underlined word (suggestions, Ignore All, Add to Dictionary) and the dialogs remain. +Auto Spell Check followed (2026-11-09): the same page has Edit › Spelling › Auto Spell Check underline potential spelling errors with a red line as you type, and says it isn't available for text with effects applied (#4936). `edit.autoSpellCheck` turns it on and off (off at first, saved with the view settings); the canvas draws a red wavy line under each word `text.spelling.check` would list in the visible type, leaves out type with an effect shown on it or on its fills and strokes, and checks a type object again when it is edited, when the custom dictionary changes and when Ignore All adds a word (`ui-egui/src/canvas/tests.rs`, `auto_spell_check_*`; `tests/spelling.rs`). The dialogs remain. + +The right-click followed (2026-11-10), as the same page's "Correct spelling errors during Auto Spell Check" describes it: right-click a word with a red underline, then choose a suggested word, Ignore All to skip it in the current document, or Add to Dictionary (#4936). The canvas context menu lists the words `text.spelling.suggest` gives for it in its run's language, each replacing the word with `text.editRange` as one undo step, or No Suggestions; then Ignore All (`text.spelling.ignoreAll`) and Add to Dictionary (`text.spelling.addWord`). It lists nothing for a word that is right, with Auto Spell Check off, or once the word under the right-click has changed (`ui-egui/src/tests/contextmenu.rs`). The dialogs remain. + +The page's other way to turn Auto Spell Check on followed (2026-11-10): right-click the text and choose Spelling › Auto Spell Check (#4936). A right-click on type (which selects it) has a Spelling submenu with Auto Spell Check, which runs `edit.autoSpellCheck` as Edit › Spelling does. The context menu draws no check marks, its toggles saying what they do (Show Rulers, Hide Guides), but a submenu that holds only toggles shows them, so Auto Spell Check is checked while it is on; other art has no Spelling submenu (`right_click_on_type_turns_auto_spell_check_on_and_off`). + +Edit Custom Dictionary followed (2026-11-10), as the same page's "Edit the custom dictionary" describes it: Edit › Edit Custom Dictionary…, then enter a word in the Entry field and Add it, select a word and Delete it, or select a word, edit it in the Entry field and Change it, then Done (#4936). The dialog lists the custom dictionary's words (`text.spelling.dictionary`); picking one puts it in the Entry field. Add and Change take one word that isn't listed yet, kept in lower case as the dictionary keeps it, and Delete and Change need a word picked. Nothing changes until Done, which deletes and adds the words that differ (`text.spelling.removeWord`, `text.spelling.addWord`); Cancel leaves the dictionary as it was (`ui-egui/src/dialogs/custom_dictionary.rs`). The Check Spelling dialog remains. ## Control bar: Paragraph section while type is selected (2026-11-06) @@ -1905,10 +1954,20 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Type advanced: the Edit Custom Dictionary dialog, #4936; evidence added; the Check Spelling dialog remains; scores and hours unchanged. | +| 2026-11-10 | minor | File formats: in a `.ai` or EPS opened from its editing data, an envelope of type opens live where it draws as its drawn art and the layers with it draw as the page (the envelope weighed as the art it draws); elsewhere, and where a text or visibility variable binds its type, it keeps its drawn art, with a note (#3179); evidence updated; scores and hours unchanged. | +| 2026-11-10 | minor | Bundled content: built-in Game HUD graphic style library; style libraries evidence updated; ~34% → ~36%; more built-in graphic-style libraries remain. | +| 2026-11-10 | minor | Bundled content: built-in Map Markers symbol library (Pin, Flag, Crosshair, Checkpoint); symbol libraries evidence updated; ~32% → ~34%; more built-in symbol libraries remain. | +| 2026-11-10 | minor | Type advanced: Spelling › Auto Spell Check in the context menu of type, checked while it is on, #4936; evidence added; the dialogs remain; scores and hours unchanged. | +| 2026-11-10 | minor | Type advanced: right-click suggestions, Ignore All and Add to Dictionary on a word Auto Spell Check underlined, #4936; evidence added; the dialogs remain; scores and hours unchanged. | +| 2026-11-10 | minor | Raster effects: the Effect Gallery shows a thumbnail of each filter and a preview of the visible stack (or the filter being browsed) inside the dialog, both an original landscape drawing passed through the filter ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)); 52% → 55%, 1–2 h → none (estimated). The canvas preview and one-undo OK are unchanged. Headline numbers unchanged. | +| 2026-11-09 | minor | Canvas: a 3D effect changed on type or a group redraws where its solid was, measured by the effect's art through the renderer that drew the frame; exports and Object › Rasterize take the solid of 3D type; Fit to Artwork Bounds and per-artboard SVG export measure all artboards through one renderer; a 3D effect on a fill or stroke that builds nothing no longer overflows the stack on the canvas, in Object › Rasterize and in raster and EPS exports (evidence in Feature revisions). Scores and estimates unchanged. | +| 2026-11-09 | minor | Bundled content: built-in Game Trails brush library (Speed Line, Dash Trail, Burst Ray, Zigzag); brush libraries evidence updated; ~32% → ~34%; more built-in brush libraries remain. | | 2026-11-09 | minor | Type advanced: Auto Spell Check (`edit.autoSpellCheck`), #4936; evidence added; the dialogs and the right-click Spelling menu remain; scores and hours unchanged. | | 2026-11-09 | minor | Bundled content: built-in UI Frames symbol library (Panel, Button, Bar with default 9-slice); symbol libraries evidence updated; ~30% → ~32%; more built-in symbol libraries remain. | | 2026-11-09 | minor | Symbols: on-canvas dynamic part appearance takes gradient/pattern fill and stroke and opacity/blend; evidence updated; area ~87% → ~88%; strokes remaining no longer lists Overlap/auto corners. | | 2026-11-09 | minor | Strokes/brushes: Art brush Overlap and Pattern brush auto corners removed from remaining (evidence already covered them); symbols remaining clarified for dynamic on-canvas beyond solid fill/stroke; scores and hours unchanged. | +| 2026-11-09 | minor | PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged. Synthetic evidence: `crates/pdf/src/tests/actual_text.rs`. | | 2026-11-09 | minor | PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged. Decoded stream and placement regressions; reader ActualText (#6165), styled clusters and external viewer validation remain separate. | | 2026-11-09 | minor | Interim macOS canvas cursor delivery (#2292): existing artwork in aligned 1×/2× AppKit representations, visible system fallback and host-owned restoration. Headless routing, bitmap and ownership coverage; native timing, menus, focus/handback, mixed displays, Spotlight and full-screen Spaces remain unverified. Scores and estimates unchanged. | | 2026-11-09 | minor | Type advanced: the custom dictionary commands (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, saved beside the preferences) and Ignore All for the active document (`text.spelling.ignoreAll`), #4936; evidence added; the dialogs and Auto Spell Check remain; scores and hours unchanged. | @@ -1919,6 +1978,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-07 | minor | File formats and Type core: `.ai`/EPS type from the text document lays its lines out closer to the file's page: auto leading per line at the paragraph's share, the paragraph's hyphenation options, possibly more of the last lines the file sets in an area frame of its own, and a line a soft return ends justified (#6137); evidence added; scores unchanged. | | 2026-11-06 | minor | `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; evidence updated; scores unchanged. | | 2026-11-08 | minor | Panel numeric wheel turns do not seed canvas zoom glides; corrected the disabled-field scroll description (#5949). Scores and estimates unchanged. | +| 2026-11-10 | minor | Held numeric spinner arrows keep stepping past the click timeout and stop on release (#6307). Scores and estimates unchanged. | | 2026-11-07 | minor | Numeric fields step on wheel hover without taking focus; keyboard focus and existing rounding rules remain (#5949). Scores and estimates unchanged. | | 2026-11-08 | minor | Consolidated the four current Guides feature-area rows using existing global/artboard ruler mode, video ruler and status-bar evidence; remaining gaps, score and estimates unchanged. The earlier detailed missing-items table remains historical. | | 2026-11-07 | minor | Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged. | @@ -1979,6 +2039,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-10-30 | minor | Color Effects add-on: live Duotone (one to four inks, spot tones kept) and Print Ink Fixes; scores and estimates unchanged | | 2026-10-30 | minor | 3D Extrude & Bevel, Inflate and Rotate apply to type, which stays editable (#4715); scores and estimates unchanged | | 2026-10-30 | minor | Color Effects add-on: live Vector Halftone; scores and estimates unchanged | +| 2026-11-10 | minor | Vector Halftone Preview leaves the dots unobscured and keeps the selection box (#6369). Scores and estimates unchanged. | | 2026-10-30 | minor | Path Precision Tools add-on: the Parametric Shape Tool; evidence added; scores unchanged. | | 2026-10-30 | minor | Presentation Mode fits the active artboard and hides selections, guides, grids and artboard edges; scores and estimates unchanged | | 2026-10-30 | minor | Color Effects add-on: Select by Color Kind; scores and estimates unchanged | @@ -2273,4 +2334,4 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s 2026-10-28 Flare interaction: the center drag turns only the rays by one degree per document point of increasing pointer y and back at the same rate for decreasing y. This is an application rule independent of event frequency. Shift keeps the current turn; Space during either drag moves the flare without changing its size or turn, including the first drag sample. Releasing a modifier resumes from the current pointer position without catching up skipped rotation. Scores and remaining estimates unchanged. ## EPS Save evidence (2026-10-26) -Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. +Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. \ No newline at end of file diff --git a/docs/three-d.md b/docs/three-d.md index f3088cc8d1..bfb626c5ad 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -4,7 +4,8 @@ The other three 3D types of **Effect › 3D and Materials** next to [Revolve](re live effect: the source path stays editable, the effect draws shaded vector faces, and SVG/PDF export, native saves and **Object › Expand Appearance** use the same evaluator. -Select a path or compound path, then choose **Effect › 3D and Materials › Extrude & Bevel…**, **Inflate…** or +Select a path, compound path, type, clipping group, blend, symbol instance, or a group or layer of them, then choose +**Effect › 3D and Materials › Extrude & Bevel…**, **Inflate…** or **Rotate…**. The options dialog opens beside the artboard with tabs: - **Object** (Extrude & Bevel and Inflate): the shape's own options, below. @@ -105,7 +106,8 @@ The rest is our reading: - The solids turn, twist and taper about the center of the bounds of all their shapes, Inflate's grid covers those bounds, and with Perspective one eye sees every solid. A stroke too narrow to hold a point of Inflate's grid stays flat. -- A stroke whose outline takes more than 2,048 points is left out, and the fill's solid still draws. +- A stroke whose outline takes more than 65,536 points, or whose solid takes more than 163,840 faces, is left out, + and the fill's solid still draws. ## Groups @@ -117,13 +119,43 @@ it, at any depth of its groups, each from its own fills and strokes as above ([F and they turn, twist and taper together about the center of their bounds together; with Perspective one eye sees them all. The members stay editable: moving or editing one reshapes the solids. Our reading: -- Each member's own geometry effects shape it first; the group's geometry effects before the 3D effect reshape the +- Each member's own geometry effects shape it first, then those of each group inside the 3D group that holds it, + applied to that group's members together; the 3D group's geometry effects before the 3D effect reshape the members, and those after it bend the result as a whole. The members' other effects, and the group's own fills and strokes, are not drawn. A member's opacity applies to its solids; its blending mode does not. - When every solid is opaque, all members' faces are drawn in one back-to-front order; otherwise each solid is drawn on its own, the backmost member's first. -- Hidden members and guides are left out. A group holding an image, a symbol instance, a clipping group or another - live object is refused with a message saying what to release or expand; so is one with more than 4,096 shapes. +- Hidden members and guides are left out. A group holding a live object other than a blend (an envelope, a mesh, a + repeat) is refused with a message saying what to release or expand; so is one with more than 4,096 shapes. + +## Clipping groups, blends and symbol instances + +Every 3D effect (Extrude & Bevel, Extrude & Bevel (Classic), Inflate, Rotate and Revolve) also applies to a clipping +group, a blend or a symbol instance, alone or inside a group or layer. The help page says that effects apply to +objects, groups or layers ([Apply and modify effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)), +that a clipping mask hides everything outside its shape ([Clipping masks](https://helpx.adobe.com/illustrator/using/clipping-masks.html)), +and that a blend is treated as one object ([Blending objects](https://helpx.adobe.com/illustrator/using/blending-objects.html)). +How the solid is built from each is VectorCraft's own rule: it is built from what the object shows, as a group's +solids are ([Groups](#groups)), turned about one shared axis. + +- A clipping group (or a layer with a clipping mask) builds from its art inside the clipping path: each shape's fill + area cut to the clip, and each stroke's outline cut to the clip and filled in the stroke's paint. The clipping path + draws no solid. A clipping group inside another keeps what both clips show. A clip that shows none of the art + leaves nothing to build, and the effect is refused. +- A blend builds from its key objects and its steps, each in its own paint, in their order. +- A symbol instance builds from its symbol's art where the instance places it. Redefining the symbol reshapes the + solid. An instance of a symbol that is not in the document, a symbol that holds an instance of itself, or art + nested more than 64 levels deep is refused. +- Inside a 3D group, the geometry effects of a clipping group, a blend or a symbol instance reshape the art it shows, + as a group's do. Inside a clipping group, a group's geometry effects reshape its members before the clip cuts them. +- Art whose symbol instances, blends and clipping groups take more than 262,144 objects to go through (counting + hidden objects, and a symbol's art once for each instance that shows it) is refused. +- The objects stay live: editing the clipping path, the blend's keys or the symbol reshapes the solid. +- An image is refused, alone or in a group: trace it first with Object › Image Trace › Make. The help page routes + images to 3D through Image Trace ([Create 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-vector-artwork.html)). + A hidden image in a group is left out like any hidden member, and so is an image in a clipping group whose bounds + lie wholly outside the clipping path's bounds, when the image has no visible fills or strokes of its own and + neither the image nor a group holding it inside the clipping group has effects. ## Rotate @@ -231,14 +263,34 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. drawn in pieces about as long as a wall slice is wide (fewer near the limit of 32,768 facets). The piece drawn on top can still lie a few points behind another nearby piece. - Extrude & Bevel and Rotate retain planar shading. Colored Inflate uses smooth vector lighting; white-light Inflate keeps its original polygon shading; bounded cell triangulation leaves a cell flat when it contains a complete hole or an unusually complex/degenerate contour. Its geometric silhouette is still a polygon approximation. -- Paths, compound paths, type and groups or layers of them (see [Groups](#groups)); images, symbol instances, - clipping groups and other live objects have to be converted first. Revolve on a group is not built yet. One 3D - effect per object. +- Paths, compound paths, type, clipping groups, blends, symbol instances and groups or layers of them (see + [Groups](#groups) and [Clipping groups, blends and symbol instances](#clipping-groups-blends-and-symbol-instances)); + images have to be traced first, and other live objects expanded. Revolve on a group sweeps its members about one + axis ([revolve.md](revolve.md)). One 3D effect per object. - Curves are followed within 1/2000 of the shape's size (at least 0.05 pt), so a small curve takes a few points - and a large one up to 32. Extrude & Bevel and Inflate take up to 2,048 outline points (a stroke's outline is - counted on its own), Rotate (which only turns the outline) 65,536. The limit is counted on the shape as drawn and, - when its contours meet, again on the merged outline, which can have more points (bars crossing in a grid trace - every hole between them); past it, the shape is too complex for the effect. + and a large one up to 32. Extrude & Bevel and Inflate take up to 65,536 outline points and 163,840 faces for each + solid (a stroke's outline is counted on its own), and Rotate (which only turns the outline) takes 65,536 points. + These limits are VectorCraft's own values. Before any point is sampled, Extrude & Bevel counts the faces its walls, + bevels and caps need, and Inflate counts the faces of its sides; when they do not fit, every curve of the shape + takes fewer pieces, down to 4 (a curve that needs fewer takes fewer). A shape that does not fit at 4 pieces a + curve is refused because the 3D surface is too complex. Inflate counts the faces of its front and back as it + builds them, against the same 163,840. The point limit is counted on the shape as drawn and, when its contours + meet, again on the merged outline, which can have more points (bars crossing in a grid trace every hole between + them); past it, the shape is too complex for the effect. +- The faces drawn, exported and made by **Object › Expand Appearance** keep the shape's curves: the caps of + Extrude & Bevel, the flat face of Rotate, and the edges of the walls and bevels where they meet a cap are cubic + curves, with smooth anchors where the art's are smooth, while visibility and depth are worked out on the + sampled points. Without perspective and bevel each curve maps exactly. With perspective, a curve is split into + cubics until each lies within 0.001 pt of the projected outline. A face inset or outset by a bevel follows its + sampled outline within the sampling tolerance above, one curve for each sampled edge through its two sampled + points, so the cap and the walls next to it draw the edge they share as the same curves. The edges between two bevel steps or two wall slices, a + piece of curve that does not fit after 8 halvings, an edge of a twisted wall cut into pieces, and the curves + past 1,048,576 for one solid stay straight. The tolerances and limits are VectorCraft's own values. Inflate's + faces are polygons. +- Inflate also limits the work of filling its grid, which grows with the outline's points times the grid cells its + outline crosses. An outline of tens of thousands of points that crosses nearly every cell (a comb of 4,000 teeth + across the shape) is refused because the 3D surface is too complex; a closed path of 65,536 points round a + circle builds. - **3D (Classic)**: Extrude & Bevel (Classic) is built, with its surface types and blend steps. Revolve (Classic), Rotate (Classic), the track cube, map art, Turntable and 3D export are separate, unbuilt items. diff --git a/docs/type-parity.md b/docs/type-parity.md index daec5c927b..defb384739 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -18,14 +18,14 @@ against Illustrator's public documentation; **estimated** unless noted. | Feature | Status | Notes | |---|---|---| -| Mouse wheel over the closed font-family field | done | #5253: Character, Properties and Control step selected text through the family list using saved font filters (excluding search text), one undo step per notch; the style is matched and the list stops at either end. Escape and leaving the field keep the change. Order, bounds and Undo grouping are VectorCraft's choices; scores unchanged. | +| Mouse wheel over the closed font-family field | done | #5253: Character, Properties and Control step selected text through the family list using saved font filters (excluding search text), one undo step per notch; the style is matched and the list stops at either end. Escape and leaving the field keep the change. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input. Order, bounds, Undo grouping, this rule and its 0.5 s are VectorCraft's choices; scores unchanged. | | Soft return (forced line break, Shift+Enter) | done | Shift+Enter inserts a soft return (U+2028), breaking the line without starting a new paragraph; paragraph spacing (space before/after) and first-line indents apply only at paragraph ends; continuation lines in lists do not repeat the marker; in justified text a line a soft return ends is justified as a wrapped line is, only the paragraph's last line keeping its alignment, as Illustrator's own layout in a user's `.ai` sets it (evidence: `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`; first done the other way in #2754) | | Native font-family labels | partial | With Show Font Names in English off, localized legacy names are used when typographic names contain no native label (#2208); loaded-font and catalog-only regressions. Choosing among multiple native languages is unchanged. | | Point, area and type-on-a-path type; vertical variants | done / partial | vertical point, area and path type have initial support; fullwidth `!` / `?` keep the nominal glyph upright when no vertical alternate exists (Unicode Tu); in a non-rectangular area a word too wide for the top lines moves down to the first line that holds it (#1615); Escape while typing ends the edit, keeps the type selected and switches back to the tool whose double-click on type chose the Type tool (kept until another tool is chosen or another document or window becomes active, so later edits with the Type tool return there too), or to the Selection tool when there is no such tool, as when the Type tool was chosen from the toolbar or after such a switch (#1802), and Cmd+Enter (Ctrl+Enter on Windows and Linux) does the same unless a command is bound to it; `text.create` and `text.createInPath` take `justify` (#1752); MCP `add_text` forwards `vertical` to both commands; Type › Type Orientation sets every frame of a thread, and a thread's frames share one writing direction; the Type and Vertical Type tools make area type when a closed path's outline is clicked and type on a path when an open one is, with pointers that say which, as the public help describes ([Create text](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html), [Create type on a path](https://web.archive.org/web/20220127090635/https://helpx.adobe.com/illustrator/using/creating-type-path.html)) | | Area Type Options (rows, columns, inset, first baseline, Text Flow by rows or by columns, Auto Size, Shrink Text to Fit) | done | Text Flow fills the cells down each column first (By Columns, the default, as files from before it open) or across each row first (By Rows), in the dialog and `text.areaOptions {flow}` (#4978); the commands that make or restyle type say when it does not fit its frame; MCP `add_text` takes Auto Size and Shrink Text to Fit (#1471) | | Threaded text, Fit Headline, Text Wrap | done | Fit Headline sees wrapping in a frame one line tall (#1444); a thread holds area type and type on a path in any mix, as Illustrator links type in an area or along a path ([help](https://helpx.adobe.com/illustrator/using/manage-text-area.html)) | | Threading from the ports: selected area type and type on a path show an in port and an out port, empty, with an arrow on a side where the frame is threaded, or with a red "+" in the out port when the text doesn't fit; a click on either port loads the text; a click on a closed path, area type or type on a path threads into it, a click on empty canvas makes a frame of the same kind, shape and size there, a drag draws a rectangular frame; the frame placed comes after the clicked one from its out port and before it from its in port (the story then starts there); Escape or another tool cancels; a double-click on a threaded port breaks the thread there | partial | #2572: the Selection tool, `text.thread.add {from, to?, rect?, at?, before?}`, as the reference app's help describes ports and threading ([archived help, Threading text between objects](https://web.archive.org/web/20210119051048/https://helpx.adobe.com/illustrator/using/creating-text.html), [create text threads](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html)); area type's in port sits on the left side below the top-left corner, type on a path's just before its start bracket; Show Text Threads draws its lines between the same ports; with more than 1,000 such objects selected no ports are drawn. a double-click on a port where the frame is threaded breaks the thread there, the story flowing into the frames before the break and the frames after it left empty, still threaded with each other when two or more (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)). Remaining: the ports only take clicks with the Selection tool, and the loaded cursor borrows the I-beam until it's drawn | -| Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show) | +| Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); Direct Selection shows the anchors and direction handles of selected type on a path's path and drags both, the brackets keeping their fractions of the path and the text reflowing along it (#3980, #3565; `text.reshapePath`, `text.setPathHandle`), as the [Direct Selection page](https://helpx.adobe.com/illustrator/using/tool-techniques/direct-selection-tool.html) describes for a path | | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing. Double-clicking a user character style's row opens its Character Style Options, and the dialog keeps a fixed width while its sections scroll when the window is shorter, so its buttons stay on screen; a paragraph style's row opens its Paragraph Style Options, the rename dialog the panel menu opens. Evidence: `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`, `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list` | | Copy or Cut selected characters, then paste as separate text art | done | A Type-range copy keeps the selected characters' font family, size and color when pasted on the canvas after leaving text editing, in the same document or another. On desktop the clipboard offers plain text to text consumers and rich art for canvas Paste; Paste Without Formatting while editing uses the destination text's style. `tests::clipboard::type_range_copy_stays_styled_when_pasted_as_art` (#5636) | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | @@ -47,13 +47,13 @@ against Illustrator's public documentation; **estimated** unless noted. | Hyphenation… and Justification… options | done | Eleven Indian languages use attributed patterns and preserve syllables in both composers (#4947). Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled; type on a path doesn't use them. Auto Leading also sets the Leading the Character panel shows for Auto type, the leading Alt+↑/↓ (`type.step`) steps from, per paragraph, and the lines Fill with Placeholder Text counts. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests`, `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading` | | Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877); Ctrl-dragging a stop (Command on macOS) moves all the stops together; in right-aligned area type the text before a line's last tab sits at its stops, from the left edge, and the text after it against the right edge, as Illustrator's own layout in a user's `.ai` sets a price list (evidence: `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`; centred and justified lines are still aligned as a whole) | | Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters` | -| Spell check (Check Spelling, Auto Spell Check, custom dictionary) | partial | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. The Check Spelling and Edit Custom Dictionary dialogs and the right-click Spelling menu (suggestions, Ignore All, Add to Dictionary) remain. Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`). | +| Spell check (Check Spelling, Auto Spell Check, custom dictionary) | partial | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The Check Spelling dialog remains. Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog). | | Smart Punctuation, Change Case, Find & Replace | done | | | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | | Retype (identify fonts in outlines/images) | missing | Illustrator's uses a cloud model | -| Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | +| Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | | Middle Eastern and Indic: digit types (Character panel menu › Digits: Default, Arabic, Hindi, Farsi; Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada, Malayalam) | done | `text.setFormat` / `text.setRangeStyle {digits}` (`"devanagari"`, `"bengali"`, `"gurmukhi"`, `"gujarati"`, `"odia"`, `"tamil"`, `"telugu"`, `"kannada"`, `"malayalam"` added, #4942); the text keeps the typed digits, the glyphs and SVG export follow the style; carried by character styles. Not yet: `.ai` export of the setting; Indic digits typed as such stay as typed under another system. Evidence: `text::tests::indic_digits_map_to_their_scripts_block`, `tests::bidi::indic_digits_draw_the_scripts_own_digits`, `typecmd::area_tests::indic_digits_round_trip_through_the_commands_and_the_file` | @@ -81,6 +81,10 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Edit Custom Dictionary (#4936): Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, applied on Done; the Check Spelling dialog remains. Scores and estimates unchanged. | +| 2026-11-10 | minor | Type on a path (#3565): Direct Selection shows the direction handles of selected type on a path's path, as of a path selected whole, and drags them (`text.setPathHandle`; Alt: one side, Shift: 45° steps); the text reflows along the new curve. Scores and estimates unchanged. | +| 2026-11-10 | minor | Spelling in the canvas context menu (#4936): a right-click on type has Spelling › Auto Spell Check, checked while it is on; the Check Spelling and Edit Custom Dictionary dialogs remain. Scores and estimates unchanged. | +| 2026-11-10 | minor | Spelling in the canvas context menu (#4936): a right-click on a word Auto Spell Check underlined lists its suggestions, Ignore All and Add to Dictionary; the Check Spelling and Edit Custom Dictionary dialogs remain. Scores and estimates unchanged. | | 2026-11-09 | minor | Auto Spell Check (#4936): Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`) underlines the unknown words of the visible type, without type with effects; the Check Spelling and Edit Custom Dictionary dialogs and the right-click Spelling menu remain. Scores and estimates unchanged. | | 2026-11-09 | minor | PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged. Decoded stream and placement regressions; reader ActualText (#6165), styled clusters and external viewer validation remain separate. | | 2026-11-09 | minor | Custom dictionary and Ignore All (#4936): `text.spelling.addWord`, `removeWord`, `changeWord` and `dictionary`, saved beside the preferences, and `text.spelling.ignoreAll` for the active document; the Check Spelling and Edit Custom Dictionary dialogs and Auto Spell Check remain. Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 623f37e7fd..2c33acb609 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,16 @@ # UI and interaction parity +<<<<<<< HEAD > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (Pencil Edit Selected Paths: strokes lifted away, carving, loops, closing over open ends, compound paths, a preview of the stroke as drawn (#3793); scores and estimates unchanged; previously: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +======= +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> +> Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). +> +> Numeric spinner update (2026-11-10): held mouse arrows repeat past the click timeout; scores and estimates unchanged (#6307). + +> **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. +>>>>>>> upstream/main ## Feature submission evidence @@ -9,6 +19,8 @@ Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow | 2026-11-06 | minor | Opening a file that takes longer than 0.4 s shows a progress window: the file name, a moving bar (reading reports no steps), how many more files wait, Cancel (Esc; the file doesn't open) and Continue in Background (`file.cancelOpen`, `file.openInBackground`); it never opens over another dialog or progress window (part of #5930); scores and estimates unchanged | Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. +Icon-strip flyouts resize from the canvas-side edge and bottom, keeping the icon-column edge anchored (#5713). Independent group heights and flyout widths persist in workspaces; saved heights override content fitting while untouched heights still fit content. Shared panel button bars and the Glyphs font row stay at the bottom after enlargement; the Artboards list grows into the extra space. Regressions: `panel_docking::tests::glyphs_and_artboards_flyouts_keep_user_sizes` and `expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists`. Scores and estimates unchanged. + **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. @@ -56,6 +68,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-06 | minor | Shape tools: a press on the selection's centre point (Show Center) moves the selection, also where no art is painted, and a press in the rotate zone just outside a bounding-box corner turns it about the centre, both as the Selection tool's do (#5477); the Selection tool takes its centre point too, so an unfilled shape moves instead of starting a marquee; scores and estimates unchanged | | 2026-11-06 | minor | Transform fields: one Tab moves from one numeric field to the next in the Transform panel, the Properties panel's Transform section and the Control bar — a field's scrub label was a second, invisible tab stop, and the W/H link between W and H is now made after the fields, so it stays a tab stop after them; scores and estimates unchanged | | 2026-11-06 | minor | Scrubby labels: the Control bar's Stroke: and Opacity: and the Properties panel's Stroke, links to their panels, scrub the field after them as other labels do; a click still opens the panel (#4088); scores and estimates unchanged | +| 2026-11-06 | minor | Icon-strip flyouts resize on their free edges and retain sizes with workspaces (#5713); saved heights beat auto-fit; panel footers stay at the bottom after enlargement. Scores and estimates unchanged. | | 2026-11-05 | minor | Direct Selection: Shift-click picks several points of a blend's spine and dragging one moves them all, with the key objects on them, in one undo step (#5285); scores and estimates unchanged | | 2026-11-05 | minor | Direct Selection: Cmd/Ctrl held lends the Selection tool, whose bounding box shows while the key is down over objects selected whole; its handles scale and rotate, and a Cmd drag moves the whole object with its direct-selected anchors kept (#3901); scores and estimates unchanged | | 2026-11-05 | minor | Join tool: scrubbing over the ends of two crossing open paths that run past the crossing trims those ends and joins the paths there with a corner, instead of drawing a segment between the ends (#5844); scores and estimates unchanged | @@ -152,6 +165,7 @@ tools, never checked side by side) isn't captured row by row. | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | +| Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Layers panel lists a blend's spine (#4820) | done | an open blend shows a `<Path>` row below its key objects, where Release leaves the spine; a click selects the blend (Shift/Cmd toggles it) so Direct Selection edits the spine; a locked blend's row selects nothing; no row while searching or filtering (`a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend`) | | Layers panel: a layer whose Layer Options › Print is off shows its name italic (#5739) | done | the panel row and its drag ghost; a printing layer stays upright, and Print on again restores it; `panels::layers` test `a_layer_that_does_not_print_has_its_name_italic` | | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | @@ -222,7 +236,7 @@ tools, never checked side by side) isn't captured row by row. | Distance Guides: Alt/Option over another object, or an empty part of an artboard, shows the selection's distances to it (Smart Guides › Invoke Distance Guides) | done | Selection tool hover with Smart Guides on: the gap between facing edges, else the offsets of matching edges, to another object; the left, right, top and bottom distances to the artboard; labelled in the General unit. The selection is measured as a whole. Nothing while moving or nudging, which the public pages don't describe. [Use Distance Guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html), [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) | | Snapping tolerance preference | done | | | Snap to Point, Snap to Grid, Snap to Pixel; Pixel Preview | done | #1840: with Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked (#1816 waits for the reporter); #3835: a straight segment dragged with Direct Selection lands its anchors on the grid, the box round them putting an edge on a gridline on each axis, as a moved object does | -| Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`); new type and drawing snap to live-text baselines and glyph bounds when Smart Guides are on (#3124). Character panel menu › Show Snap to Glyph Options: a Snap to Glyph checkbox (View › Snap to Glyph), then a checkbox for each guide (Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides, Anchor Point), dimmed while Snap to Glyph is off (#4232); showing them scrolls the panel to them (#5273) | +| Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`); new type and drawing snap to live-text baselines and glyph bounds when Smart Guides are on (#3124). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to them too; that is VectorCraft's choice. Character panel menu › Show Snap to Glyph Options: a Snap to Glyph checkbox (View › Snap to Glyph), then a checkbox for each guide (Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides, Anchor Point), dimmed while Snap to Glyph is off (#4232); showing them scrolls the panel to them (#5273) | | Tangent and perpendicular snapping for line endpoints (new in 30.0) | done | #2530: tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Line Segment, Pen and Curvature tools, and for an existing line whose end anchor is dragged with Direct Selection (the only anchor selected, an open path's end on a straight segment; Shift keeps its angle step instead; Group Selection moves the path whole and does not snap so); mid-line anchors, curved segments' ends and curves as perpendicular targets are excluded, as the pages say. Saved Preferences › Smart Guides › Geometric Guides controls, on by default. [Perpendicular](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-perpendicular.html) and [tangent](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-tangent.html) pages; test `dragged_line_ends_snap_perpendicular_to_segments_and_tangent_to_curves` | | Snapping panel/popover consolidating the snap options (30.0) | partial | Control bar › Snapping provides quick access through existing view commands and prefs.set, including Snap to Glyph and Alignment Guides (#6164); no View › Snapping submenu. Floating-panel parity remains unverified. | | Customisable rotation snap angle (#973) | missing | Illustrator: Constrain Angle and construction angles only | @@ -244,6 +258,7 @@ tools, never checked side by side) isn't captured row by row. | Moving a rounded rectangle with Craquelure at high DPI | partial | Distance searches optimized; moved-viewport pixels unchanged for three texture effects; `texture_drag_perf` probe available. Idle Windows mouse-drag QA remains (#1257) | | Bounding-box handles: Shift proportional, Alt from centre, rotate outside the corners | done | | | Rotated objects keep a rotated bounding box and their angle; Reset Bounding Box | done | | +| Vector Halftone Preview keeps the selection box and hides selection marks on the temporary dots | done | #6369; Preview off and Cancel restore the original marks. | | Free Transform, Scale and Reflect along a rotated box | missing | | | Free Transform widget: constrain, free distort, perspective distort; the key-held variants | done | | | Transform tools: click sets the reference point (snaps to anchors/centres), Alt-click opens the dialog, Alt-release copies | done | with anchors selected with Direct Selection, the tools, the dialogs and Move transform those anchors alone, about the centre of their box by default (#1408; the default point and whole-object copies are our choices) | @@ -264,10 +279,11 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| -| Wheel over a closed font-family field in Character, Properties or Control | done | #5253: applies the next or previous family to selected text, one undo step per notch; uses saved font filters, ignores search text and stops at the list's ends. Escape and pointer departure keep the change. Other font-picking menus and modifier-wheel input keep their existing behavior. | +| Wheel over a closed font-family field in Character, Properties or Control | done | #5253: applies the next or previous family to selected text, one undo step per notch; uses saved font filters, ignores search text and stops at the list's ends. Escape and pointer departure keep the change. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input. This rule and its 0.5 s are VectorCraft's choices. Other font-picking menus and modifier-wheel input keep their existing behavior. | | Arrow keys nudge by Keyboard Increment (0.001–1296 pt); Shift ×10; Alt copies | done | | | Fields commit what was typed on a click away or a move to another field, as Enter does; Escape discards it | done | #1787 | -| Number fields: Up/Down step, Shift ×10, Cmd/Ctrl ÷10, wheel over a hovered field without a click; steps, the wheel and label scrubs stop at the field's bounds (a stroke weight at 0, a miter limit at 1) | done | Shift+arrow in the Stroke weight field doesn't step by 10 (#991); bounds #3370 | +| Number fields: Up/Down step, Shift ×10, Cmd/Ctrl ÷10, wheel over a hovered field without a click; steps, the wheel and label scrubs stop at the field's bounds (a stroke weight at 0, a miter limit at 1) | done | Shift+arrow in the Stroke weight field doesn't step by 10 (#991); bounds #3370. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input or the pointer is pressed on a field, so a panel scrolled under a still pointer keeps scrolling past the field. This rule and its 0.5 s are VectorCraft's choices. | +| Numeric spinner arrows step once on a click and keep repeating while held with the mouse | done | #6307; headless test `a_held_spinner_arrow_repeats` holds past egui's click timeout and checks release. | | Arithmetic in fields (`+ - * /`, and `%` of the value before it: `3cm*50%`, `50pt+25%`) and unit suffixes (`3 mm`, `1in`, `2p6`) | done | `Unit::parse`; mixed units in one expression not verified | | Numeric fields: focus click selects the whole value; dragging selects from the pressed character | partial | #1326; select-all waits for click release; px/pt/plain/optional fields, both directions and replacement text tested; native API input, 17 px partial replacement, Undo/Redo, saved-file round trip and screenshots verified; Tab, double-click, arrows and wheel preserved; short movements still classified as clicks can select all and remain open | | Units: pt, pc, in, mm, cm, px, ft-in, m, yd, ft; General/Stroke/Type units | done | units preference reverting to points on SVG output reported (#864) | @@ -425,6 +441,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>); arcs, spirals, flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | +| Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -494,6 +511,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Held numeric spinner arrows keep stepping past the click timeout and stop on release (#6307). Scores and estimates unchanged. | | 2026-11-09 | minor | Interim macOS canvas cursor delivery (#2292): existing artwork in aligned 1×/2× AppKit representations, visible system fallback and host-owned restoration. Headless routing, bitmap and ownership coverage; native timing, menus, focus/handback, mixed displays, Spotlight and full-screen Spaces remain unverified. Scores and estimates unchanged. | | 2026-11-08 | minor | Floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part); tab groups remain intact. Scores and estimates unchanged. | | 2026-11-09 | minor | Numeric fields step on wheel hover without taking focus; keyboard focus and existing rounding rules remain (#5949). Scores and estimates unchanged. | @@ -557,6 +575,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | 2026-10-31 | minor | Artwork Cleanup add-on (a VectorCraft addition): its text tools in the panel and Object › Plug-ins › Artwork Cleanup; scores and estimates unchanged | | 2026-10-30 | minor | Color Effects add-on: live Duotone (one to four inks, spot tones kept) and Print Ink Fixes; scores and estimates unchanged | | 2026-10-30 | minor | Color Effects add-on: live Vector Halftone; scores and estimates unchanged | +| 2026-11-10 | minor | Vector Halftone Preview leaves the dots unobscured and keeps the selection box (#6369). Scores and estimates unchanged. | | 2026-10-30 | minor | Path Precision Tools add-on: the Parametric Shape Tool (ten re-editable shape kinds), its panel and Convert to Parametric Shape; scores and estimates unchanged | | 2026-10-30 | minor | Smart Pen add-on: an Alt-drag away from paths selects points with a marquee; scores and estimates unchanged | | 2026-10-30 | minor | Color Effects add-on: Select by Color Kind; scores and estimates unchanged | diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 6b8bda8d13..8a6f5f0256 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -64,6 +64,7 @@ pub const TABLE: &[(&str, Class)] = &[ ("affinity", Class::Standalone), ("scriptcheck", Class::Standalone), ("js", Class::Standalone), + ("apischema", Class::Standalone), ]; /// Explicit orderings *within* a layer (earlier may be used by later).